scope 0.3.2__tar.gz → 0.4.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
scope-0.4.1/PKG-INFO ADDED
@@ -0,0 +1,66 @@
1
+ Metadata-Version: 2.1
2
+ Name: scope
3
+ Version: 0.4.1
4
+ Summary: Metrics logging and analysis
5
+ Home-page: http://github.com/danijar/scope
6
+ Classifier: Intended Audience :: Science/Research
7
+ Classifier: License :: OSI Approved :: MIT License
8
+ Classifier: Programming Language :: Python :: 3
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+
12
+ # 🔬 Scope
13
+
14
+ Scalable metrics logging and analysis.
15
+
16
+ ## Features
17
+
18
+ - 🚀 **Scalable:** Quickly log and view petabytes of metrics, thousands of keys, and large videos.
19
+ - 🎞️ **Formats:** Log and view scalars, text, images, and videos. Easy to extend with custom formats.
20
+ - 🧑🏻‍🔬 **Productivity:** Metrics viewer with focus on power users and full keyboard support.
21
+ - ☁️ **Cloud support:** Directly write to and read from Cloud storage via pathlib interface.
22
+ - 🍃 **Lightweight:** The writer and reader measure only ~400 lines of Python code.
23
+ - 🧱 **Reliability:** Unit tested and used across diverse research projects.
24
+
25
+ ## Usage
26
+
27
+ ### Installation
28
+
29
+ ```sh
30
+ pip install scope
31
+ ```
32
+
33
+ ### Writing
34
+
35
+ ```python
36
+ import scope
37
+
38
+ writer = scope.Writer(logdir)
39
+ for step in range(3)
40
+ video = np.zeros((100, 640, 360, 3), np.uint8)
41
+ writer.add(step, {'foo': 42, 'bar': video, 'baz': 'Hello World'})
42
+ writer.flush()
43
+ ```
44
+
45
+ ### Viewing
46
+
47
+ ```sh
48
+ python -m scope.viewer --basedir ... --port 8000
49
+ ```
50
+
51
+ ### Reading
52
+
53
+ ```python
54
+ import scope
55
+
56
+ reader = scope.Reader(logdir)
57
+ print(reader.keys()) # ('foo', 'bar', 'baz')
58
+
59
+ print(reader.length('foo')) # 3
60
+ steps, values = reader['foo']
61
+ print(steps) # np.array([0, 1, 2], np.int64)
62
+ print(values) # np.array([42, 42, 42], np.float64)
63
+
64
+ steps, filenames = reader['bar']
65
+ reader.load('bar', filenames[-1]) # np.zeros((100, 640, 360, 3), np.uint8)
66
+ ```
@@ -0,0 +1,6 @@
1
+ av
2
+ elements>=3.16.6
3
+ fastapi
4
+ numpy
5
+ pillow
6
+ uvicorn[standard]
@@ -1,4 +1,4 @@
1
- __version__ = '0.3.2'
1
+ __version__ = '0.4.1'
2
2
 
3
3
  from .reader import Reader
4
4
  from .writer import Writer
@@ -18,7 +18,7 @@ class Reader:
18
18
  formats = formats or FORMATS
19
19
  if isinstance(logdir, str):
20
20
  logdir = pathlib.Path(logdir)
21
- self.logdir = logdir
21
+ self.logdir = logdir / 'scope'
22
22
  self.fmts = {x.extension: x for x in formats}
23
23
  self.cols = {}
24
24
  for child in sorted(logdir.glob('*')):
@@ -33,7 +33,7 @@ class Writer:
33
33
  formats = formats or FORMATS
34
34
  if isinstance(logdir, str):
35
35
  logdir = pathlib.Path(logdir)
36
- self.logdir = logdir
36
+ self.logdir = logdir / 'scope'
37
37
  self.logdir.mkdir(parents=True, exist_ok=True)
38
38
  self.workers = workers
39
39
  self.rng = np.random.default_rng(seed=None)
@@ -1,6 +1,11 @@
1
+ import os
1
2
  import pathlib
2
3
  import re
4
+ import subprocess
5
+
3
6
  import setuptools
7
+ from distutils.command.sdist import sdist as _sdist
8
+ from setuptools.command.develop import develop as _develop
4
9
 
5
10
 
6
11
  def parse_requirements(filename):
@@ -16,6 +21,24 @@ def parse_version(filename):
16
21
  return version
17
22
 
18
23
 
24
+ def build_viewer():
25
+ orig = os.getcwd()
26
+ try:
27
+ os.chdir(pathlib.Path(__file__).parent / 'viewer')
28
+ subprocess.check_call(['npm', 'install'])
29
+ subprocess.check_call(['npm', 'run', 'build'])
30
+ finally:
31
+ os.chdir(orig)
32
+
33
+
34
+ def patch(cmd):
35
+ class Patched(cmd):
36
+ def run(self):
37
+ build_viewer()
38
+ cmd.run(self)
39
+ return Patched
40
+
41
+
19
42
  setuptools.setup(
20
43
  name='scope',
21
44
  version=parse_version('scope/__init__.py'),
@@ -23,9 +46,20 @@ setuptools.setup(
23
46
  url='http://github.com/danijar/scope',
24
47
  long_description=pathlib.Path('README.md').read_text(),
25
48
  long_description_content_type='text/markdown',
26
- packages=['scope'],
27
- include_package_data=True,
28
49
  install_requires=parse_requirements('requirements.txt'),
50
+ packages=['scope', 'scope.viewer'],
51
+ package_dir={
52
+ 'scope': 'scope',
53
+ 'scope.viewer': 'viewer',
54
+ },
55
+ package_data={
56
+ 'scope.viewer': ['dist/*'],
57
+ },
58
+ include_package_data=True,
59
+ cmdclass={
60
+ 'sdist': patch(_sdist),
61
+ 'develop': patch(_develop),
62
+ },
29
63
  classifiers=[
30
64
  'Intended Audience :: Science/Research',
31
65
  'License :: OSI Approved :: MIT License',
@@ -0,0 +1,20 @@
1
+ import pathlib
2
+ import sys
3
+
4
+ import uvicorn
5
+ from . import config
6
+
7
+
8
+ config = config.config
9
+
10
+ print(config)
11
+
12
+ sys.path.insert(0, str(pathlib.Path(__file__).parent))
13
+
14
+ uvicorn.run(
15
+ 'server:app',
16
+ host='0.0.0.0',
17
+ port=config.port,
18
+ reload=config.debug,
19
+ workers=None if config.debug else config.workers,
20
+ )
@@ -0,0 +1,15 @@
1
+ import os
2
+
3
+ import elements
4
+
5
+
6
+ config = elements.Flags(
7
+ port=int(os.environ.get('SCOPE_PORT', 8000)),
8
+ basedir=os.environ.get('SCOPE_BASEDIR', ''),
9
+ filesystem=os.environ.get('SCOPE_FILESYSTEM', 'elements'),
10
+ maxdepth=2,
11
+ workers=32,
12
+ debug=False,
13
+ ).parse()
14
+
15
+ assert config.basedir, config.basedir
Binary file
@@ -0,0 +1,14 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <link rel="icon" href="/favicon.png">
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
7
+ <title>Scope</title>
8
+ <script type="module" crossorigin src="/assets/index-BZlTxr6y.js"></script>
9
+ <link rel="stylesheet" crossorigin href="/assets/index-DlFPK5at.css">
10
+ </head>
11
+ <body>
12
+ <div id="app"></div>
13
+ </body>
14
+ </html>
Binary file
@@ -0,0 +1,89 @@
1
+ import elements
2
+ import io
3
+ import os
4
+ import subprocess
5
+
6
+
7
+ class Local:
8
+
9
+ def list(self, path):
10
+ return os.listdir(path)
11
+
12
+ def size(self, path):
13
+ return os.path.getsize(path)
14
+
15
+ def read(self, path):
16
+ with open(path, 'rb') as f:
17
+ return f.read()
18
+
19
+ def open(self, path, seek=0, limit=None):
20
+ f = open(path, 'rb')
21
+ f.seek(seek)
22
+ return f
23
+
24
+
25
+ class Elements:
26
+
27
+ def list(self, path):
28
+ paths = elements.Path(path).glob('*')
29
+ return [str(x) for x in paths]
30
+
31
+ def size(self, path):
32
+ return elements.Path(path).size
33
+
34
+ def read(self, path):
35
+ return elements.Path(path).read_bytes()
36
+
37
+ def open(self, path, seek=0, limit=None):
38
+ f = elements.Path(path).open('rb')
39
+ f.seek(seek)
40
+ return f
41
+
42
+
43
+ class Fileutil:
44
+
45
+ def __init__(
46
+ self,
47
+ ls='fileutil ls {}',
48
+ cat='fileutil cat {}',
49
+ size="fileutil ls -l {} | tr -s ' ' | cut -d' ' -f5",
50
+ catrange='fileutil cat -input_startpos={} -input_endpos={} {}',
51
+ ):
52
+ self._ls = ls
53
+ self._cat = cat
54
+ self._size = size
55
+ self._catrange = catrange
56
+
57
+ def list(self, path):
58
+ try:
59
+ output = self._sh(self._ls.format(path))
60
+ return [x.rstrip('/') for x in output.decode('utf-8').splitlines()]
61
+ except RuntimeError as e:
62
+ print(e)
63
+ return []
64
+
65
+ def size(self, path):
66
+ output = self._sh(self._size.format(path))
67
+ return int(output.decode('utf-8').strip('\n'))
68
+
69
+ def read(self, path):
70
+ return self._sh(self._cat.format(path))
71
+
72
+ def open(self, path, seek=0, limit=None):
73
+ limit = limit or self._size(path)
74
+ buffer = self._sh(self._catrange.format(seek, limit, path))
75
+ return io.BytesIO(buffer)
76
+
77
+ def _sh(self, cmd):
78
+ if '|' in cmd:
79
+ process = subprocess.Popen(
80
+ cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
81
+ out, err = process.communicate()
82
+ if process.returncode:
83
+ raise RuntimeError((process.returncode, out, err))
84
+ return out
85
+ else:
86
+ try:
87
+ return subprocess.check_output(cmd.split(), shell=False)
88
+ except subprocess.CalledProcessError as e:
89
+ raise RuntimeError(f'Error in subprocess: {e}')
@@ -0,0 +1,166 @@
1
+ import concurrent.futures
2
+ import functools
3
+ import pathlib
4
+ import struct
5
+
6
+ import fastapi
7
+ import fastapi.responses
8
+ import fastapi.staticfiles
9
+
10
+ import filesystems
11
+ import config
12
+
13
+
14
+ config = config.config
15
+ app = fastapi.FastAPI(debug=config.debug)
16
+ basedir = config.basedir.rstrip('/')
17
+ fs = dict(
18
+ elements=filesystems.Elements,
19
+ fileutil=filesystems.Fileutil,
20
+ local=filesystems.Local,
21
+ )[config.filesystem]()
22
+
23
+
24
+ @app.get('/api/exps')
25
+ def get_exps():
26
+ print('GET /exps', flush=True)
27
+ folders = fs.list(basedir)
28
+ expids = [x.rsplit('/', 1)[-1] for x in folders]
29
+ return {'exps': expids}
30
+
31
+
32
+ @app.get('/api/exp/{expid}')
33
+ def get_exp(expid: str):
34
+ print(f'GET /exp/{expid}', flush=True)
35
+ folders = find_runs(basedir + '/' + expid)
36
+ folders = [x.removeprefix(str(basedir))[1:] for x in folders]
37
+ runids = [x.replace('/', ':') for x in folders]
38
+ return {'id': expid, 'runs': runids}
39
+
40
+
41
+ @app.get('/api/run/{runid}')
42
+ def get_run(runid: str):
43
+ print(f'GET /run/{runid}', flush=True)
44
+ folder = basedir + '/' + runid.replace(':', '/') + '/scope'
45
+ children = fs.list(folder)
46
+ children = [x.removeprefix(str(basedir))[1:] for x in children]
47
+ colids = [x.replace('/', ':') for x in children]
48
+ return {'id': runid, 'cols': colids}
49
+
50
+
51
+ @app.get('/api/col/{colid}')
52
+ def get_col(colid: str):
53
+ print(f'GET /col/{colid}', flush=True)
54
+ ext = colid.rsplit('.', 1)[-1]
55
+ path = basedir + '/' + colid.replace(':', '/')
56
+ runid = colid.rsplit(':', 2)[0] # Remove metric name and scope folder.
57
+ if ext == 'float':
58
+ buffer = fs.read(path)
59
+ steps, values = tuple(zip(*struct.iter_unpack('>qd', buffer)))
60
+ return {'id': colid, 'run': runid, 'steps': steps, 'values': values}
61
+ elif ext in ('txt', 'mp4', 'webm'):
62
+ buffer = fs.read(path + '/index')
63
+ steps, idents = tuple(zip(*struct.iter_unpack('q8s', buffer)))
64
+ filenames = [f'{s:020}-{x.hex()}.{ext}' for s, x in zip(steps, idents)]
65
+ values = [f'{colid}:{x}' for x in filenames]
66
+ return {'id': colid, 'run': runid, 'steps': steps, 'values': values}
67
+ else:
68
+ raise NotImplementedError((colid, ext))
69
+
70
+
71
+ @app.get('/api/file/{fileid}')
72
+ def get_file(request: fastapi.Request, fileid: str):
73
+ print(f'GET /file/{fileid}', flush=True)
74
+ ext = fileid.rsplit('.', 1)[-1]
75
+ path = basedir + '/' + fileid.replace(':', '/')
76
+ if ext == 'txt':
77
+ text = fs.read(path).decode('utf-8')
78
+ return {'id': fileid, 'text': text}
79
+ elif ext in ('mp4', 'webm'):
80
+ filesize = fs.size(path)
81
+ openfn = functools.partial(fs.open, path)
82
+ content_type = f'video/{ext}'
83
+ return RangeResponse(request, openfn, filesize, content_type)
84
+ else:
85
+ raise NotImplementedError((fileid, ext))
86
+
87
+
88
+ dist = pathlib.Path(__file__).parent / 'dist'
89
+ app.mount('/', fastapi.staticfiles.StaticFiles(directory=dist, html=True))
90
+
91
+
92
+ def find_runs(folder, maxdepth=config.maxdepth, workers=64):
93
+ if not workers:
94
+ runs = []
95
+ queue = [(folder, 0)]
96
+ while queue:
97
+ node, depth = queue.pop(0)
98
+ children = fs.list(node)
99
+ if any(x.endswith('/scope') for x in children):
100
+ runs.append(node)
101
+ elif depth < maxdepth:
102
+ queue += [(x, depth + 1) for x in children]
103
+ return runs
104
+ runs = []
105
+ with concurrent.futures.ThreadPoolExecutor(workers) as pool:
106
+ future = pool.submit(fs.list, folder)
107
+ future.parent = folder
108
+ future.depth = 0
109
+ queue = [future]
110
+ while queue:
111
+ current = queue.pop(0)
112
+ children = current.result()
113
+ if any(x.endswith('/scope') for x in children):
114
+ runs.append(current.parent)
115
+ elif current.depth < maxdepth:
116
+ for child in children:
117
+ future = pool.submit(fs.list, child)
118
+ future.parent = child
119
+ future.depth = current.depth + 1
120
+ queue.append(future)
121
+ return runs
122
+
123
+
124
+ def RangeResponse(request, openfn, filesize, content_type):
125
+ headers = {
126
+ 'content-type': content_type,
127
+ 'accept-ranges': 'bytes',
128
+ 'content-length': str(filesize),
129
+ 'access-control-expose-headers': (
130
+ 'content-type, accept-ranges, content-length, '
131
+ 'content-range, content-encoding'
132
+ ),
133
+ }
134
+ range_header = request.headers.get('range')
135
+ if range_header:
136
+ try:
137
+ h = range_header.replace('bytes=', '').split('-')
138
+ start = int(h[0]) if h[0] != '' else 0
139
+ end = int(h[1]) if h[1] != '' else filesize - 1
140
+ except ValueError:
141
+ raise fastapi.HTTPException(
142
+ fastapi.status.HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE,
143
+ detail=f'Invalid request range (Range:{range_header!r})')
144
+ if start > end or start < 0 or end > filesize - 1:
145
+ raise fastapi.HTTPException(
146
+ fastapi.status.HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE,
147
+ detail=f'Invalid request range (Range:{range_header!r})')
148
+ size = end - start + 1
149
+ headers['content-length'] = str(size)
150
+ headers['content-range'] = f'bytes {start}-{end}/{filesize}'
151
+ status_code = fastapi.status.HTTP_206_PARTIAL_CONTENT
152
+ else:
153
+ start = 0
154
+ end = filesize - 1
155
+ status_code = fastapi.status.HTTP_200_OK
156
+ stop = end + 1
157
+ def iterfile(chunksize=int(2e5)):
158
+ with openfn(start, stop) as f:
159
+ total = stop - start
160
+ nbytes = 0
161
+ while nbytes < total:
162
+ chunk = f.read(min(chunksize, total - nbytes))
163
+ nbytes += len(chunk)
164
+ yield chunk
165
+ return fastapi.responses.StreamingResponse(
166
+ iterfile(), headers=headers, status_code=status_code)
scope-0.3.2/LICENSE DELETED
@@ -1,19 +0,0 @@
1
- Copyright (c) 2024 Danijar Hafner
2
-
3
- Permission is hereby granted, free of charge, to any person obtaining a copy
4
- of this software and associated documentation files (the "Software"), to deal
5
- in the Software without restriction, including without limitation the rights
6
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
- copies of the Software, and to permit persons to whom the Software is
8
- furnished to do so, subject to the following conditions:
9
-
10
- The above copyright notice and this permission notice shall be included in all
11
- copies or substantial portions of the Software.
12
-
13
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
- SOFTWARE.
scope-0.3.2/MANIFEST.in DELETED
@@ -1 +0,0 @@
1
- include requirements.txt
scope-0.3.2/PKG-INFO DELETED
@@ -1,10 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: scope
3
- Version: 0.3.2
4
- Summary: Metrics logging and analysis
5
- Home-page: http://github.com/danijar/scope
6
- Classifier: Intended Audience :: Science/Research
7
- Classifier: License :: OSI Approved :: MIT License
8
- Classifier: Programming Language :: Python :: 3
9
- Description-Content-Type: text/markdown
10
- License-File: LICENSE
@@ -1,5 +0,0 @@
1
- [tool.pytest.ini_options]
2
- markers = ['slow']
3
- addopts = ['--strict-config', '-ra']
4
- pythonpath = ['.']
5
- testpaths = ['tests']
@@ -1,3 +0,0 @@
1
- av
2
- numpy
3
- pillow
@@ -1,10 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: scope
3
- Version: 0.3.2
4
- Summary: Metrics logging and analysis
5
- Home-page: http://github.com/danijar/scope
6
- Classifier: Intended Audience :: Science/Research
7
- Classifier: License :: OSI Approved :: MIT License
8
- Classifier: Programming Language :: Python :: 3
9
- Description-Content-Type: text/markdown
10
- License-File: LICENSE
@@ -1,18 +0,0 @@
1
- LICENSE
2
- MANIFEST.in
3
- README.md
4
- pyproject.toml
5
- requirements.txt
6
- setup.py
7
- scope/__init__.py
8
- scope/formats.py
9
- scope/reader.py
10
- scope/writer.py
11
- scope.egg-info/PKG-INFO
12
- scope.egg-info/SOURCES.txt
13
- scope.egg-info/dependency_links.txt
14
- scope.egg-info/requires.txt
15
- scope.egg-info/top_level.txt
16
- tests/test_float.py
17
- tests/test_image.py
18
- tests/test_video.py
@@ -1,3 +0,0 @@
1
- av
2
- numpy
3
- pillow
@@ -1 +0,0 @@
1
- scope
scope-0.3.2/setup.cfg DELETED
@@ -1,4 +0,0 @@
1
- [egg_info]
2
- tag_build =
3
- tag_date = 0
4
-
File without changes
File without changes
File without changes
File without changes