analysis-workflow-viewer 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,9 @@
1
+ """An interactive viewer for the lineage that analysis-workflow records."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ from analysis_workflow_viewer.repo import Repo
6
+ from analysis_workflow_viewer.server import serve
7
+
8
+ __all__ = ["Repo", "serve"]
9
+ __version__ = version("analysis-workflow-viewer")
@@ -0,0 +1,101 @@
1
+ """What a data artifact is, from its metadata alone: a file's size and date, the kind and shape of a store's keys.
2
+
3
+ AnnData elements are opened with anndata's lazy reader, which knows every encoding and reads no data. SpatialData
4
+ images and labels give the shape of their full-resolution level; shapes and points are only named.
5
+ """
6
+
7
+ import datetime
8
+ from pathlib import Path
9
+
10
+ import zarr
11
+ from anndata.experimental import read_elem_lazy
12
+
13
+ #: AnnData encodings, in words.
14
+ KINDS = {
15
+ "csr_matrix": "sparse matrix (CSR)",
16
+ "csc_matrix": "sparse matrix (CSC)",
17
+ "array": "dense array",
18
+ "categorical": "categorical",
19
+ "dataframe": "table",
20
+ "string-array": "text",
21
+ "nullable-integer": "integers, some missing",
22
+ "nullable-boolean": "true/false, some missing",
23
+ "nullable-string-array": "text, some missing",
24
+ "numeric-scalar": "number",
25
+ "string": "text",
26
+ "dict": "nested values",
27
+ "awkward-array": "ragged array",
28
+ "anndata": "AnnData object",
29
+ "raw": "raw AnnData",
30
+ }
31
+
32
+
33
+ def describe_path(path: Path) -> dict:
34
+ """A file's size and when it was last changed; a folder's number of entries; an object's shape."""
35
+ stat = path.stat()
36
+ found = {"modified": datetime.datetime.fromtimestamp(stat.st_mtime).strftime("%Y-%m-%d %H:%M")}
37
+ if path.is_file():
38
+ return {"kind": "file", "bytes": stat.st_size, **found}
39
+ root = _group(path)
40
+ if root is None:
41
+ return {"kind": "folder", "entries": sum(1 for _ in path.iterdir()), **found}
42
+ if root.attrs.get("encoding-type") == "anndata":
43
+ return {"kind": "AnnData object", "shape": [_rows(root["obs"]), _rows(root["var"])], **found}
44
+ if "spatialdata_attrs" in root.attrs:
45
+ elements = {
46
+ kind: len(list(root[kind])) for kind in ("images", "labels", "points", "shapes", "tables") if kind in root
47
+ }
48
+ return {"kind": "SpatialData object", "elements": elements, **found}
49
+ return {"kind": "zarr store", **found}
50
+
51
+
52
+ def describe_keys(path: Path, keys: list[str]) -> list[dict]:
53
+ """Each key's kind, shape and type, read from the store at ``path``."""
54
+ root = _group(path)
55
+ return [describe_key(root, key) if root is not None else {"key": key} for key in keys]
56
+
57
+
58
+ def describe_key(root, key: str) -> dict:
59
+ """One key of an open store: what kind of element it is, its shape and its type of values."""
60
+ try:
61
+ node = root[key]
62
+ except KeyError:
63
+ return {"key": key, "kind": "not in the store"}
64
+ attrs = dict(node.attrs)
65
+ encoding = attrs.get("encoding-type")
66
+ if encoding in KINDS:
67
+ found = {"key": key, "kind": KINDS[encoding]}
68
+ try:
69
+ lazy = read_elem_lazy(node)
70
+ found["shape"] = [int(n) for n in lazy.shape]
71
+ if encoding not in ("dataframe", "categorical") and getattr(lazy, "dtype", None) is not None:
72
+ found["dtype"] = str(lazy.dtype)
73
+ except Exception: # noqa: BLE001 - an encoding the lazy reader does not open is still named
74
+ if "shape" in attrs:
75
+ found["shape"] = list(attrs["shape"])
76
+ if encoding == "categorical":
77
+ found["categories"] = int(node["categories"].shape[0])
78
+ if encoding == "dataframe":
79
+ found["columns"] = len(attrs.get("column-order", []))
80
+ return found
81
+ multiscales = attrs.get("multiscales") or attrs.get("ome", {}).get("multiscales")
82
+ if multiscales: # a SpatialData image or labels (OME-NGFF, which newer versions keep under "ome")
83
+ level = multiscales[0]["datasets"][0]["path"]
84
+ kind = "labels" if key.startswith("labels/") else "image"
85
+ return {"key": key, "kind": kind, "shape": list(node[level].shape), "dtype": str(node[level].dtype)}
86
+ if str(encoding).startswith("ngff:"):
87
+ return {"key": key, "kind": encoding.removeprefix("ngff:")}
88
+ if isinstance(node, zarr.Array):
89
+ return {"key": key, "kind": "array", "shape": list(node.shape), "dtype": str(node.dtype)}
90
+ return {"key": key, "kind": "group"}
91
+
92
+
93
+ def _group(path: Path):
94
+ """The zarr group at ``path``, or None when it is no zarr store."""
95
+ if not any((path / name).is_file() for name in ("zarr.json", ".zgroup")):
96
+ return None
97
+ return zarr.open_group(str(path), mode="r", use_consolidated=False)
98
+
99
+
100
+ def _rows(dataframe_group) -> int:
101
+ return int(read_elem_lazy(dataframe_group).shape[0])
@@ -0,0 +1,39 @@
1
+ """``analysis-workflow-viewer``: serve the viewer for the analysis repo it is started in, and open it."""
2
+
3
+ import argparse
4
+ import webbrowser
5
+ from pathlib import Path
6
+
7
+ from analysis_workflow_viewer.repo import Repo
8
+ from analysis_workflow_viewer.server import serve
9
+
10
+
11
+ def main(argv: list[str] | None = None) -> None:
12
+ """Start the viewer, open it in a browser and serve until interrupted.
13
+
14
+ In a VS Code remote terminal, ``$BROWSER`` is VS Code's helper, which forwards the port and opens the page on
15
+ the machine VS Code runs on; Python's `webbrowser` uses it.
16
+ """
17
+ parser = argparse.ArgumentParser(prog="analysis-workflow-viewer", description=__doc__)
18
+ parser.add_argument("repo", nargs="?", default=".", type=Path, help="any path in the analysis repo")
19
+ parser.add_argument("--host", default="127.0.0.1", help="where to listen; the default is this machine only")
20
+ parser.add_argument("--port", type=int, default=8765, help="the port; 0 picks a free one")
21
+ parser.add_argument("--no-open", action="store_true", help="do not open the page in a browser")
22
+ args = parser.parse_args(argv)
23
+
24
+ repo = Repo(args.repo)
25
+ try:
26
+ server = serve(repo, args.host, args.port)
27
+ except OSError as err:
28
+ parser.exit(1, f"Cannot listen on {args.host}:{args.port} ({err.strerror}): pass another --port.\n")
29
+ host, port = server.server_address[:2]
30
+ url = f"http://{host}:{port}/"
31
+ print(f"Serving the lineage of {repo.roots[0].name} at {url} (Ctrl-C stops it)")
32
+ if not args.no_open and not webbrowser.open(url):
33
+ print("No browser to open it in: forward the port and open the address yourself.")
34
+ try:
35
+ server.serve_forever()
36
+ except KeyboardInterrupt:
37
+ pass
38
+ finally:
39
+ server.server_close()
@@ -0,0 +1,262 @@
1
+ """What the viewer shows of an analysis repo: its files, the keys of its stores, traces and task READMEs.
2
+
3
+ Everything is read from disk when asked for, so the view follows the analysis as it moves on; nothing is written.
4
+ Files are listed from the main checkout, where shared data and the untracked outputs of tasks are, together with
5
+ the checkout the viewer was started in, whose tasks may be on a branch that is not merged yet.
6
+
7
+ What can be traced is what a task produced: a file in one of its output directories, or a key of a store that a
8
+ record credits to a task. A task's README, ``inputs.yaml``, code and logs are not.
9
+ """
10
+
11
+ import re
12
+ import subprocess
13
+ from dataclasses import dataclass, field
14
+ from pathlib import Path
15
+
16
+ from analysis_workflow.paths import (
17
+ NON_TASK_DIRS,
18
+ TRACKED_TASK_DIRS,
19
+ UNTRACKED_TASK_DIRS,
20
+ checkout,
21
+ main_checkout,
22
+ task_field,
23
+ task_id,
24
+ )
25
+ from analysis_workflow.provenance import keys, records
26
+ from analysis_workflow.trace import ROOT_SOURCE_DIR, SOURCE_DIRS, owner, trace
27
+
28
+ from analysis_workflow_viewer.about import describe_keys, describe_path
29
+
30
+ #: Suffixes of files and directories that may hold the keys of an AnnData or SpatialData object.
31
+ STORE_SUFFIXES = (".zarr", ".h5ad")
32
+ #: The directories of a task that hold what it produced; its logs record a run, not data.
33
+ PRODUCT_DIRS = frozenset({*TRACKED_TASK_DIRS, *UNTRACKED_TASK_DIRS}) - {"logs"}
34
+ #: How many entries of one directory are listed; the rest are counted.
35
+ MAX_ENTRIES = 2000
36
+ #: How many entries a directory's search for something traceable looks at before it gives up and says yes.
37
+ MAX_SEARCH = 5000
38
+ #: README lines that are not its opening sentence: the header fields and the guidance comments.
39
+ HEADER = re.compile(r"^(\*\*[^*]+:\*\*|<!--|#)")
40
+ #: A GitHub remote, over https or ssh.
41
+ GITHUB = re.compile(r"github\.com[:/](?P<repo>[^/]+/[^/]+?)(?:\.git)?/?$")
42
+
43
+
44
+ def _hidden(name: str) -> bool:
45
+ return name.startswith(".") or name in NON_TASK_DIRS
46
+
47
+
48
+ @dataclass
49
+ class Repo:
50
+ """An analysis repo, seen from ``start``: any path in one of its checkouts."""
51
+
52
+ start: Path
53
+ roots: list[Path] = field(init=False)
54
+
55
+ def __post_init__(self):
56
+ self.start = Path(self.start).resolve()
57
+ self.roots = list(dict.fromkeys([main_checkout(self.start), checkout(self.start)]))
58
+
59
+ def _git(self, *args: str, where: Path) -> str:
60
+ return subprocess.run(["git", "-C", str(where), *args], capture_output=True, text=True).stdout.strip()
61
+
62
+ def info(self) -> dict:
63
+ """The repo's name, from its main checkout; the branch it is viewed on; its GitHub page, if it has one."""
64
+ here = self.roots[-1]
65
+ found = GITHUB.search(self._git("remote", "get-url", "origin", where=self.roots[0]))
66
+ return {
67
+ "name": self.roots[0].name,
68
+ "branch": self._git("branch", "--show-current", where=here) or None,
69
+ "worktree": here != self.roots[0],
70
+ "github": found and f"https://github.com/{found['repo']}",
71
+ }
72
+
73
+ def _rel(self, rel: str) -> Path:
74
+ """``rel`` as a path inside the repo; ValueError if it would leave it."""
75
+ path = Path(rel or ".")
76
+ if path.is_absolute() or ".." in path.parts:
77
+ raise ValueError(f"{rel!r} is not a path inside the repo.")
78
+ return path
79
+
80
+ def on_disk(self, rel: Path) -> Path:
81
+ """Where ``rel`` is: in the first checkout that has it, else where the main checkout would have it."""
82
+ return next((root / rel for root in self.roots if (root / rel).exists()), self.roots[0] / rel)
83
+
84
+ def _children(self, rel: Path) -> dict[str, Path]:
85
+ """The visible entries of the directory ``rel``, from every checkout, by name."""
86
+ found: dict[str, Path] = {}
87
+ for root in self.roots:
88
+ directory = root / rel
89
+ if directory.is_dir() and not directory.name.endswith(STORE_SUFFIXES):
90
+ for child in directory.iterdir():
91
+ if not _hidden(child.name):
92
+ found.setdefault(child.name, child)
93
+ return found
94
+
95
+ def traceable(self, rel: Path) -> bool:
96
+ """Whether ``rel`` is something a task produced: an entry in one of its output directories."""
97
+ task = owner(rel)
98
+ if task is None or not any((root / task / "README.md").exists() for root in self.roots):
99
+ return False
100
+ inside = rel.relative_to(task).parts
101
+ return len(inside) > 1 and inside[0] in PRODUCT_DIRS
102
+
103
+ def _recorded(self, rel: Path) -> bool:
104
+ """Whether a record credits any key of the store ``rel`` to a task."""
105
+ return bool(records(self.on_disk(rel)))
106
+
107
+ @staticmethod
108
+ def _source(rel: Path) -> bool:
109
+ """Whether ``rel`` holds data from outside the repo, which no task made."""
110
+ return rel.parts[:1] == (ROOT_SOURCE_DIR,) or (
111
+ rel.parts[:1] == ("data",) and bool(SOURCE_DIRS & {*rel.parts[2:3]})
112
+ )
113
+
114
+ def holds_traceable(self, rel: Path) -> bool:
115
+ """Whether the directory ``rel`` holds anything traceable, at any depth.
116
+
117
+ Data from outside the repo is not searched. Past MAX_SEARCH entries the answer is yes: too large to tell.
118
+ """
119
+ stack, seen = [rel], 0
120
+ while stack:
121
+ current = stack.pop()
122
+ for name, child in self._children(current).items():
123
+ seen += 1
124
+ child_rel = current / name
125
+ if self.traceable(child_rel):
126
+ return True
127
+ if name.endswith(STORE_SUFFIXES):
128
+ if self._recorded(child_rel):
129
+ return True
130
+ elif child.is_dir() and not self._source(child_rel):
131
+ stack.append(child_rel)
132
+ if seen > MAX_SEARCH:
133
+ return True
134
+ return False
135
+
136
+ def entries(self, rel: str = "") -> list[dict]:
137
+ """The files and directories in the directory ``rel``, from every checkout; directories first.
138
+
139
+ Each entry has its ``name``, its ``path`` in the repo, whether it is a ``dir``, whether it may hold the
140
+ keys of a ``store``, whether it is ``traceable`` itself, and whether it is or ``holds`` anything
141
+ traceable. Past MAX_ENTRIES, one last entry counts the rest.
142
+ """
143
+ rel_path = self._rel(rel)
144
+ listed = []
145
+ for name, child in sorted(self._children(rel_path).items(), key=lambda i: (not i[1].is_dir(), i[0].lower())):
146
+ child_rel = rel_path / name
147
+ store = name.endswith(STORE_SUFFIXES)
148
+ directory = child.is_dir() and not store
149
+ traceable = self.traceable(child_rel)
150
+ if store:
151
+ holds = traceable or self._recorded(child_rel)
152
+ elif directory:
153
+ holds = traceable or (not self._source(child_rel) and self.holds_traceable(child_rel))
154
+ else:
155
+ holds = traceable
156
+ listed.append(
157
+ {
158
+ "name": name,
159
+ "path": child_rel.as_posix(),
160
+ "dir": directory,
161
+ "store": store,
162
+ "traceable": traceable,
163
+ "holds": holds,
164
+ }
165
+ )
166
+ if len(listed) > MAX_ENTRIES:
167
+ listed = [*listed[:MAX_ENTRIES], {"name": f"… {len(listed) - MAX_ENTRIES} more", "more": True}]
168
+ return listed
169
+
170
+ def store_keys(self, rel: str) -> list[dict]:
171
+ """The keys of the store ``rel``, each with whether a record names the task that wrote it."""
172
+ path = self.on_disk(self._rel(rel))
173
+ covered = {k for record in records(path) for k in record["keys"]}
174
+ return [{"key": key, "traceable": key in covered} for key in sorted(keys(path))]
175
+
176
+ def about(self, rel: str, keys: list[str] | None = None) -> dict | list[dict]:
177
+ """What ``rel`` is, from its metadata; or, given ``keys`` of the store ``rel``, what each of them is."""
178
+ path = self.on_disk(self._rel(rel))
179
+ if not path.exists():
180
+ raise ValueError(f"{rel} is not there.")
181
+ return describe_keys(path, keys) if keys else describe_path(path)
182
+
183
+ def place(self, path: str) -> str:
184
+ """Where an input from outside lives, in a few words: a dataset's raw data, another repo, the home directory."""
185
+ p = Path(path).expanduser()
186
+ if not p.is_absolute():
187
+ parts = p.parts
188
+ if parts[:1] == ("data",) and len(parts) > 2:
189
+ return f"this repo · {parts[1]} · {parts[2]}"
190
+ return f"this repo · {parts[0]}"
191
+ for parent in p.parents:
192
+ if (parent / ".git").exists() and not Path.home().is_relative_to(parent):
193
+ return f"repo {parent.name}"
194
+ return "home directory" if p.is_relative_to(Path.home()) else "elsewhere"
195
+
196
+ def trace(self, rel: str, key: str | None = None) -> dict:
197
+ """The trace of the file ``rel``, or of the key ``key`` of the store ``rel``, as `analysis_workflow` gives it.
198
+
199
+ Each input a task read that no task made also says where it lives (``place``).
200
+ """
201
+ found = trace(self.on_disk(self._rel(rel)), key or None, start=self.start)
202
+ for node in found.tasks.values():
203
+ for entry in node["consumed"]:
204
+ entry["place"] = self.place(entry["path"])
205
+ return {"target": found.target, "tasks": found.tasks, "edges": found.edges, "undeclared": found.undeclared}
206
+
207
+ def stores(self) -> list[Path]:
208
+ """The zarr stores under ``data/`` that tasks can write to: not the data from outside the repo."""
209
+ found, stack = [], [Path("data")]
210
+ while stack:
211
+ current = stack.pop()
212
+ for name, child in self._children(current).items():
213
+ child_rel = current / name
214
+ if name.endswith(".zarr"):
215
+ found.append(child_rel)
216
+ elif child.is_dir() and not self._source(child_rel):
217
+ stack.append(child_rel)
218
+ return sorted(found)
219
+
220
+ def outputs(self, rel: str) -> list[dict]:
221
+ """Everything the task ``rel`` produced: the files in its output folders, and the store keys credited to it.
222
+
223
+ Each entry is an artifact, ``{"path": ...}`` with the ``"keys"`` of a store, and its ``group``: the output
224
+ folder, or "shared stores".
225
+ """
226
+ task = self._rel(rel)
227
+ if not any((root / task / "README.md").is_file() for root in self.roots):
228
+ raise ValueError(f"{rel} is no task directory: it has no README.md.")
229
+ identity = task_id(self.on_disk(task))
230
+ found = []
231
+ for folder in sorted(PRODUCT_DIRS):
232
+ stack = [task / folder]
233
+ while stack and len(found) < MAX_ENTRIES:
234
+ current = stack.pop()
235
+ for name, child in sorted(self._children(current).items()):
236
+ if child.is_dir() and not name.endswith(STORE_SUFFIXES):
237
+ stack.append(current / name)
238
+ else:
239
+ found.append({"path": (current / name).as_posix(), "group": f"{folder}/"})
240
+ for store in self.stores():
241
+ keys = sorted(
242
+ k for record in records(self.on_disk(store)) if record["task"] == identity for k in record["keys"]
243
+ )
244
+ if keys:
245
+ found.append({"path": store.as_posix(), "keys": keys, "group": "shared stores"})
246
+ return found
247
+
248
+ def task(self, rel: str) -> dict:
249
+ """A task's id, author, date and opening sentence, from its README."""
250
+ directory = self.on_disk(self._rel(rel))
251
+ readme = directory / "README.md"
252
+ if not readme.is_file():
253
+ raise ValueError(f"{rel} is no task directory: it has no README.md.")
254
+ paragraphs = [p.strip() for p in re.split(r"\n\s*\n", readme.read_text())]
255
+ summary = next((p for p in paragraphs if p and not HEADER.match(p)), "")
256
+ return {
257
+ "path": rel,
258
+ "id": task_id(directory),
259
+ "author": task_field(directory, "Author"),
260
+ "date": task_field(directory, "Date"),
261
+ "summary": " ".join(summary.split()),
262
+ }
@@ -0,0 +1,83 @@
1
+ """A small local web server: the page and its libraries, and a JSON API over `Repo`.
2
+
3
+ GET / the page
4
+ GET /static/<file> its script, style and vendored libraries
5
+ GET /api/repo the repo's name and branch
6
+ GET /api/entries?path= the files in a directory
7
+ GET /api/keys?path= the keys of a store
8
+ GET /api/trace?path=&key= the trace of a file, or of a store's key
9
+ GET /api/task?path= a task's README header and opening sentence
10
+ GET /api/outputs?path= everything a task produced: files in its output folders, store keys credited to it
11
+ GET /api/about?path=&key= what a file or store is, or what each of the given keys is: kind, shape, size
12
+ """
13
+
14
+ import json
15
+ import mimetypes
16
+ from functools import partial
17
+ from http import HTTPStatus
18
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
19
+ from importlib.resources import files
20
+ from urllib.parse import parse_qs, urlparse
21
+
22
+ from analysis_workflow_viewer.repo import Repo
23
+
24
+ STATIC = files("analysis_workflow_viewer") / "static"
25
+
26
+
27
+ class Handler(BaseHTTPRequestHandler):
28
+ """Answers the page's requests; anything that would change the repo has no route."""
29
+
30
+ def __init__(self, *args, repo: Repo, **kwargs):
31
+ self.repo = repo
32
+ super().__init__(*args, **kwargs)
33
+
34
+ def log_message(self, format, *args):
35
+ """Stay quiet: the terminal shows where to open the page, not every request."""
36
+
37
+ def send(self, status: HTTPStatus, body: bytes, content_type: str) -> None:
38
+ """Send a response with no caching: every request reads the repo afresh."""
39
+ self.send_response(status)
40
+ self.send_header("Content-Type", content_type)
41
+ self.send_header("Content-Length", str(len(body)))
42
+ self.send_header("Cache-Control", "no-store")
43
+ self.end_headers()
44
+ self.wfile.write(body)
45
+
46
+ def send_json(self, value, status: HTTPStatus = HTTPStatus.OK) -> None:
47
+ """Send ``value`` as JSON."""
48
+ self.send(status, json.dumps(value).encode(), "application/json")
49
+
50
+ def do_GET(self):
51
+ """Route a request."""
52
+ url = urlparse(self.path)
53
+ given = parse_qs(url.query)
54
+ query = {name: values[0] for name, values in given.items()}
55
+ api = {
56
+ "/api/repo": self.repo.info,
57
+ "/api/entries": lambda: self.repo.entries(query.get("path", "")),
58
+ "/api/keys": lambda: self.repo.store_keys(query["path"]),
59
+ "/api/trace": lambda: self.repo.trace(query["path"], query.get("key")),
60
+ "/api/task": lambda: self.repo.task(query["path"]),
61
+ "/api/about": lambda: self.repo.about(query["path"], given.get("key")),
62
+ "/api/outputs": lambda: self.repo.outputs(query["path"]),
63
+ }
64
+ if url.path in api:
65
+ try:
66
+ self.send_json(api[url.path]())
67
+ except (KeyError, ValueError, FileNotFoundError, NotADirectoryError) as err:
68
+ self.send_json({"error": str(err)}, HTTPStatus.BAD_REQUEST)
69
+ return
70
+ name = "index.html" if url.path == "/" else url.path.removeprefix("/static/")
71
+ resource = STATIC.joinpath(*name.split("/"))
72
+ if url.path != "/" and (not url.path.startswith("/static/") or ".." in name.split("/")):
73
+ resource = None
74
+ if resource is None or not resource.is_file():
75
+ self.send(HTTPStatus.NOT_FOUND, b"Not found", "text/plain")
76
+ return
77
+ content_type = mimetypes.guess_type(name)[0] or "application/octet-stream"
78
+ self.send(HTTPStatus.OK, resource.read_bytes(), content_type)
79
+
80
+
81
+ def serve(repo: Repo, host: str = "127.0.0.1", port: int = 0) -> ThreadingHTTPServer:
82
+ """A server for ``repo``, bound but not yet serving; port 0 picks a free one."""
83
+ return ThreadingHTTPServer((host, port), partial(Handler, repo=repo))