kenryu 0.2.1__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.
- kenryu-0.2.1.dist-info/METADATA +72 -0
- kenryu-0.2.1.dist-info/RECORD +17 -0
- kenryu-0.2.1.dist-info/WHEEL +5 -0
- kenryu-0.2.1.dist-info/entry_points.txt +3 -0
- kenryu-0.2.1.dist-info/top_level.txt +1 -0
- nagare/__init__.py +15 -0
- nagare/__main__.py +70 -0
- nagare/engine.py +221 -0
- nagare/preview.py +54 -0
- nagare/registry.py +239 -0
- nagare/server.py +168 -0
- nagare/static/app.css +59 -0
- nagare/static/app.js +473 -0
- nagare/static/index.html +39 -0
- nagare/static/vendor/LITEGRAPH-LICENSE +19 -0
- nagare/static/vendor/litegraph.core.min.js +342 -0
- nagare/static/vendor/litegraph.css +680 -0
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: kenryu
|
|
3
|
+
Version: 0.2.1
|
|
4
|
+
Summary: A node editor for Python functions (prototype)
|
|
5
|
+
Requires-Python: >=3.10
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
Provides-Extra: demo
|
|
8
|
+
Requires-Dist: pandas; extra == "demo"
|
|
9
|
+
Requires-Dist: numpy; extra == "demo"
|
|
10
|
+
Requires-Dist: scipy; extra == "demo"
|
|
11
|
+
Requires-Dist: matplotlib; extra == "demo"
|
|
12
|
+
|
|
13
|
+
# nagare 流
|
|
14
|
+
|
|
15
|
+
A prototype node editor for Python functions, in the spirit of Blender's node editor. Write ordinary type-hinted functions; each one becomes a node you wire up in the browser, run with caching, preview and export as a plain script.
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
pip install git+https://github.com/ShashankRaoCoding/kenryu
|
|
19
|
+
nagare path/to/your/nodes # opens http://127.0.0.1:8650/
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
To try the demo, clone the repo and install with the demo extras (pandas, numpy, scipy, matplotlib):
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
git clone https://github.com/ShashankRaoCoding/kenryu && cd kenryu
|
|
26
|
+
pip install ".[demo]"
|
|
27
|
+
nagare examples
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
The RNA-seq demo loads on first start: simulate counts → filter → CPM → PCA and differential expression → plots.
|
|
31
|
+
|
|
32
|
+
## Your own nodes
|
|
33
|
+
|
|
34
|
+
Point nagare at any folder of `.py` files. Every public function becomes a node, and its type hints decide the shape:
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
def normalise_cpm(counts: pd.DataFrame, log: bool = True) -> pd.DataFrame:
|
|
38
|
+
"""Counts per million, optionally log2(CPM + 1)."""
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
| In the signature | On the node |
|
|
42
|
+
| --- | --- |
|
|
43
|
+
| `int`, `float`, `bool`, `str` parameter | a setting (number box, toggle, text) |
|
|
44
|
+
| `Literal["a", "b"]` | a drop-down |
|
|
45
|
+
| any other type (`DataFrame`, `Figure`, `AnnData`…) | an input socket of that type; only matching outputs connect |
|
|
46
|
+
| no annotation | a socket that accepts anything |
|
|
47
|
+
| return type | the output; `tuple[A, B]` gives two |
|
|
48
|
+
| first paragraph of the docstring | the description |
|
|
49
|
+
|
|
50
|
+
No nagare import is needed. `from nagare import node` gives an optional decorator for a title, output names, or turning a `str`/`int` parameter into a socket: `@node(title="PCA", outputs=["pcs"], sockets=["path"])`.
|
|
51
|
+
|
|
52
|
+
## How it behaves
|
|
53
|
+
|
|
54
|
+
- **Live**: change a setting or a connection and the graph re-runs. Each node is cached by its code, its settings and its inputs, so only what changed (and what's downstream) runs again. Its code means its whole file plus any other file of the folder that file imports, so editing a helper function re-runs the nodes that use it. Edit a function in your editor and switch back: it re-runs the nodes from that file.
|
|
55
|
+
- **Previews**: tables, figures and text show in the side panel; figures also show inside the node. Errors show the traceback from your function, and downstream nodes wait.
|
|
56
|
+
- **Save / Open** keep graphs in `FOLDER/graphs/`; the canvas also survives a page reload.
|
|
57
|
+
- **Export .py** writes the graph as a plain Python script that runs without nagare.
|
|
58
|
+
|
|
59
|
+
## Inside kenkyu
|
|
60
|
+
|
|
61
|
+
[kenkyu](https://github.com/ShashankRaoCoding/kenkyu) uses an installed nagare for its **Flows**: install this package (`pip install git+https://github.com/ShashankRaoCoding/kenryu`) where kenkyu runs. kenkyu starts it as `nagare FOLDER --port 8650 --kenkyu` (no browser, the address printed once ready, and an exit when kenkyu closes its stdin), or uses a nagare already running on 8650, and serves the canvas at `/nagare/?flow=ID`. `GET /api/info` tells kenkyu it is talking to a nagare that speaks its protocol. In that mode the canvas loads and saves the flow in kenkyu's library instead of local storage and `graphs/`, and tells kenkyu which node is selected so its figure can go into a document. Runs return each node's cache `key`, which kenkyu stores with a figure to notice when the code behind it changes, and take a `dpi` for figures. The page uses relative addresses, so it works the same at `/` and under `/nagare/`.
|
|
62
|
+
|
|
63
|
+
## Prototype limits
|
|
64
|
+
|
|
65
|
+
- One process and an in-memory cache: restarting loses cached results.
|
|
66
|
+
- Nodes get their inputs by reference: a function that changes its input in place also changes the cached copy. Return new objects.
|
|
67
|
+
- New settings or sockets on a function need a page reload (a banner offers it); changed function bodies don't.
|
|
68
|
+
- The cache knows about the files in your nodes folder, not installed packages: after upgrading a library your nodes use, restart nagare to clear it.
|
|
69
|
+
- The server only answers to `localhost` or an IP address, and refuses requests that change things when the browser says they came from another site, so other web pages can't run your nodes.
|
|
70
|
+
- No per-sample "for each" yet, no environments per node, no concurrency.
|
|
71
|
+
|
|
72
|
+
`static/vendor/` holds [LiteGraph.js](https://github.com/jagenjo/litegraph.js) 0.7.18 (MIT).
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
nagare/__init__.py,sha256=CU-hLcjdJj2nDCE3eRjKOaX0lZzNvwwsGAXf8ussqOg,492
|
|
2
|
+
nagare/__main__.py,sha256=JDESJxZep9_jb7znhYBL4UV50WnXu_5eK-H4nnhFn98,2317
|
|
3
|
+
nagare/engine.py,sha256=k1_Z6yevTwnFDZGXNU7D89CxKlJ6_t8fAitW3a9VS7Y,8895
|
|
4
|
+
nagare/preview.py,sha256=EZ4BM7WZNRbd4tyZJ99zolnpY-LEFKYLqs9NXWtcgxg,1977
|
|
5
|
+
nagare/registry.py,sha256=jkSDBl4G-vZanC7IgodSr-BWaNsBV-aNKYZDpU5DKso,9271
|
|
6
|
+
nagare/server.py,sha256=hHrxtaZ32r6usRJnk2NIt0sT6_ysvIUdbW7unXC0VW8,7063
|
|
7
|
+
nagare/static/app.css,sha256=hqGk0B4rcHjOOEU8WyN7aiG_PThN5fdu7PPU08pcbqg,3877
|
|
8
|
+
nagare/static/app.js,sha256=JGQqx2-lc34kViNtCpP36Kus6UEU2ssUBo2JCoNpjL8,19682
|
|
9
|
+
nagare/static/index.html,sha256=Zm_QHbEHc3DzINN7ggA8XfATaC-MB0xxYXHPWXVqGbM,1707
|
|
10
|
+
nagare/static/vendor/LITEGRAPH-LICENSE,sha256=GzjMMP53S8x3U4q5nrRg9OHIpHxP3cbpke47XMKpa7k,1077
|
|
11
|
+
nagare/static/vendor/litegraph.core.min.js,sha256=5pe6Wpj6t3oa1-fzol9Z1jY1lwrOCOIpIoiUWQmBHVs,176325
|
|
12
|
+
nagare/static/vendor/litegraph.css,sha256=VlzujVTn39FilfDsexn5EKc5wPQtUmMZjjQWo4pgBrM,12820
|
|
13
|
+
kenryu-0.2.1.dist-info/METADATA,sha256=voa6uC8fVnVcdHtv6SmpW6vt6A7JNeyf2-9DHyJyPpc,4612
|
|
14
|
+
kenryu-0.2.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
15
|
+
kenryu-0.2.1.dist-info/entry_points.txt,sha256=xwIHqbxLnoZmTM3Hppiu33o-SzRbmlPG4CJ5hYAXTf8,78
|
|
16
|
+
kenryu-0.2.1.dist-info/top_level.txt,sha256=RJqafq1vn4xdEpfjvZYGapiDM32ZBOj7e5TDeZW5p_E,7
|
|
17
|
+
kenryu-0.2.1.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
nagare
|
nagare/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""nagare: a node editor for Python functions.
|
|
2
|
+
|
|
3
|
+
Write plain, type-hinted functions; nagare turns each into a node you can
|
|
4
|
+
wire up in the browser, run with caching, preview, and export as a script.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from .registry import node
|
|
8
|
+
|
|
9
|
+
__all__ = ["node"]
|
|
10
|
+
__version__ = "0.2.1"
|
|
11
|
+
|
|
12
|
+
# The version of what kenkyu relies on: --kenkyu, cache keys and dpi in
|
|
13
|
+
# runs, relative page addresses and the ?flow= canvas. kenkyu reads it from
|
|
14
|
+
# /api/info before using a nagare it finds running.
|
|
15
|
+
KENKYU_PROTOCOL = 1
|
nagare/__main__.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""python -m nagare [nodes-folder] [--port 8650]"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
import threading
|
|
9
|
+
import webbrowser
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _exit_when_stdin_closes() -> None:
|
|
14
|
+
"""kenkyu starts nagare with a pipe on stdin and never writes to it.
|
|
15
|
+
|
|
16
|
+
When kenkyu stops, for any reason, the pipe closes and this read returns,
|
|
17
|
+
so nagare never outlives the app that started it.
|
|
18
|
+
"""
|
|
19
|
+
try:
|
|
20
|
+
while sys.stdin.buffer.read(4096):
|
|
21
|
+
pass
|
|
22
|
+
except (OSError, ValueError):
|
|
23
|
+
pass
|
|
24
|
+
os._exit(0)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def main(argv=None) -> int:
|
|
28
|
+
ap = argparse.ArgumentParser(prog="nagare", description="A node editor for your Python functions.")
|
|
29
|
+
ap.add_argument("folder", nargs="?", default=".", help="folder of .py files whose functions become nodes")
|
|
30
|
+
ap.add_argument("--port", type=int, default=8650, help="0 picks any free port")
|
|
31
|
+
ap.add_argument("--graphs", help="where graphs are saved (default: FOLDER/graphs)")
|
|
32
|
+
ap.add_argument("--no-browser", action="store_true")
|
|
33
|
+
ap.add_argument("--kenkyu", action="store_true",
|
|
34
|
+
help="run inside kenkyu: no browser, print the address once ready, stop when stdin closes")
|
|
35
|
+
args = ap.parse_args(argv)
|
|
36
|
+
|
|
37
|
+
try: # figures are drawn off-screen and sent to the browser
|
|
38
|
+
import matplotlib
|
|
39
|
+
|
|
40
|
+
matplotlib.use("Agg")
|
|
41
|
+
except ImportError:
|
|
42
|
+
pass
|
|
43
|
+
|
|
44
|
+
from .server import serve
|
|
45
|
+
|
|
46
|
+
folder = Path(args.folder)
|
|
47
|
+
if not folder.is_dir():
|
|
48
|
+
print(f"nagare: {folder} is not a folder", file=sys.stderr)
|
|
49
|
+
return 2
|
|
50
|
+
app, httpd = serve(folder, args.port, args.graphs)
|
|
51
|
+
url = f"http://127.0.0.1:{httpd.server_address[1]}/"
|
|
52
|
+
for f, err in app.registry.errors.items():
|
|
53
|
+
print(f" could not load {f}: {err}", file=sys.stderr)
|
|
54
|
+
if args.kenkyu:
|
|
55
|
+
threading.Thread(target=_exit_when_stdin_closes, daemon=True).start()
|
|
56
|
+
print(f"nagare: ready {url}", flush=True)
|
|
57
|
+
else:
|
|
58
|
+
print(f"nagare: {len(app.registry.types)} nodes from {app.registry.folder}")
|
|
59
|
+
print(f"nagare: open {url} (Ctrl-C to stop)")
|
|
60
|
+
if not args.no_browser:
|
|
61
|
+
webbrowser.open(url)
|
|
62
|
+
try:
|
|
63
|
+
httpd.serve_forever()
|
|
64
|
+
except KeyboardInterrupt:
|
|
65
|
+
pass
|
|
66
|
+
return 0
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
if __name__ == "__main__":
|
|
70
|
+
raise SystemExit(main())
|
nagare/engine.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
"""Running a graph of nodes, with a cache so only what changed runs again.
|
|
2
|
+
|
|
3
|
+
A graph is plain JSON:
|
|
4
|
+
|
|
5
|
+
{"nodes": [{"id": "1", "type": "rnaseq.simulate_counts", "params": {"n_genes": 2000}}, ...],
|
|
6
|
+
"links": [{"from": "1", "out": 0, "to": "2", "input": "counts"}, ...]}
|
|
7
|
+
|
|
8
|
+
Each node's cache key comes from its function's source, its settings and
|
|
9
|
+
the keys of everything upstream. Change a setting (or edit the function)
|
|
10
|
+
and that node and everything downstream run again; the rest is reused.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import hashlib
|
|
16
|
+
import json
|
|
17
|
+
import time
|
|
18
|
+
import traceback
|
|
19
|
+
from collections import OrderedDict
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from .preview import preview, summary
|
|
23
|
+
from .registry import Registry
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class GraphError(ValueError):
|
|
27
|
+
pass
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def topo_order(graph: dict) -> list[str]:
|
|
31
|
+
ids = [str(n["id"]) for n in graph.get("nodes", [])]
|
|
32
|
+
deps: dict[str, set[str]] = {i: set() for i in ids}
|
|
33
|
+
for link in graph.get("links", []):
|
|
34
|
+
src, dst = str(link["from"]), str(link["to"])
|
|
35
|
+
if src in deps and dst in deps:
|
|
36
|
+
deps[dst].add(src)
|
|
37
|
+
order, done, visiting = [], set(), set()
|
|
38
|
+
|
|
39
|
+
def visit(i: str) -> None:
|
|
40
|
+
if i in done:
|
|
41
|
+
return
|
|
42
|
+
if i in visiting:
|
|
43
|
+
raise GraphError("the graph has a cycle")
|
|
44
|
+
visiting.add(i)
|
|
45
|
+
for d in sorted(deps[i]):
|
|
46
|
+
visit(d)
|
|
47
|
+
visiting.discard(i)
|
|
48
|
+
done.add(i)
|
|
49
|
+
order.append(i)
|
|
50
|
+
|
|
51
|
+
for i in ids:
|
|
52
|
+
visit(i)
|
|
53
|
+
return order
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def upstream(graph: dict, target: str) -> set[str]:
|
|
57
|
+
back: dict[str, set[str]] = {}
|
|
58
|
+
for link in graph.get("links", []):
|
|
59
|
+
back.setdefault(str(link["to"]), set()).add(str(link["from"]))
|
|
60
|
+
seen, stack = set(), [target]
|
|
61
|
+
while stack:
|
|
62
|
+
i = stack.pop()
|
|
63
|
+
if i not in seen:
|
|
64
|
+
seen.add(i)
|
|
65
|
+
stack.extend(back.get(i, ()))
|
|
66
|
+
return seen
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class Engine:
|
|
70
|
+
def __init__(self, registry: Registry, cache_size: int = 256):
|
|
71
|
+
self.registry = registry
|
|
72
|
+
self.cache: OrderedDict[str, tuple] = OrderedDict() # key -> outputs
|
|
73
|
+
self.cache_size = cache_size
|
|
74
|
+
|
|
75
|
+
def _remember(self, key: str, outputs: tuple) -> None:
|
|
76
|
+
self.cache[key] = outputs
|
|
77
|
+
self.cache.move_to_end(key)
|
|
78
|
+
while len(self.cache) > self.cache_size:
|
|
79
|
+
self.cache.popitem(last=False)
|
|
80
|
+
|
|
81
|
+
def run(self, graph: dict, target: str | None = None, dpi: int = 110) -> dict[str, dict]:
|
|
82
|
+
"""Run the graph (or just what target needs). Returns a result per node.
|
|
83
|
+
|
|
84
|
+
Each finished node's result carries its cache key: the same key means
|
|
85
|
+
the same function source, settings and inputs, so the same output.
|
|
86
|
+
kenkyu uses it to tell whether a figure in a document is out of date.
|
|
87
|
+
"""
|
|
88
|
+
self.registry.refresh()
|
|
89
|
+
nodes = {str(n["id"]): n for n in graph.get("nodes", [])}
|
|
90
|
+
order = topo_order(graph)
|
|
91
|
+
if target is not None:
|
|
92
|
+
needed = upstream(graph, str(target))
|
|
93
|
+
order = [i for i in order if i in needed]
|
|
94
|
+
incoming: dict[str, dict[str, tuple[str, int]]] = {}
|
|
95
|
+
for link in graph.get("links", []):
|
|
96
|
+
incoming.setdefault(str(link["to"]), {})[link["input"]] = (str(link["from"]), int(link.get("out", 0)))
|
|
97
|
+
|
|
98
|
+
keys: dict[str, str] = {}
|
|
99
|
+
values: dict[str, tuple] = {}
|
|
100
|
+
results: dict[str, dict] = {}
|
|
101
|
+
for nid in order:
|
|
102
|
+
n = nodes[nid]
|
|
103
|
+
nt = self.registry.types.get(n["type"])
|
|
104
|
+
if nt is None:
|
|
105
|
+
results[nid] = {"status": "error", "error": f"no node type {n['type']!r} (was the function renamed or removed?)"}
|
|
106
|
+
continue
|
|
107
|
+
params = {p.name: n.get("params", {}).get(p.name, p.default) for p in nt.params}
|
|
108
|
+
# Settings arrive from the browser as JSON; give them their declared types.
|
|
109
|
+
for p in nt.params:
|
|
110
|
+
try:
|
|
111
|
+
if p.type == "int":
|
|
112
|
+
params[p.name] = int(params[p.name])
|
|
113
|
+
elif p.type == "float":
|
|
114
|
+
params[p.name] = float(params[p.name])
|
|
115
|
+
elif p.type == "bool":
|
|
116
|
+
params[p.name] = params[p.name] in (True, "true", "True", 1, "1")
|
|
117
|
+
except (TypeError, ValueError):
|
|
118
|
+
pass
|
|
119
|
+
|
|
120
|
+
args: dict[str, Any] = {}
|
|
121
|
+
arg_keys: dict[str, str] = {}
|
|
122
|
+
blocked = None
|
|
123
|
+
for s in nt.inputs:
|
|
124
|
+
src = incoming.get(nid, {}).get(s.name)
|
|
125
|
+
if src is None:
|
|
126
|
+
if s.name in nt.required:
|
|
127
|
+
blocked = f"connect its {s.name!r} input"
|
|
128
|
+
continue
|
|
129
|
+
src_id, out = src
|
|
130
|
+
if src_id not in values:
|
|
131
|
+
blocked = "an upstream node did not finish"
|
|
132
|
+
continue
|
|
133
|
+
if out >= len(values[src_id]):
|
|
134
|
+
blocked = f"input {s.name!r} is linked to an output that no longer exists"
|
|
135
|
+
continue
|
|
136
|
+
args[s.name] = values[src_id][out]
|
|
137
|
+
arg_keys[s.name] = f"{keys[src_id]}:{out}"
|
|
138
|
+
if blocked:
|
|
139
|
+
results[nid] = {"status": "waiting", "error": blocked.capitalize() + "."}
|
|
140
|
+
continue
|
|
141
|
+
|
|
142
|
+
key = hashlib.sha1(json.dumps(
|
|
143
|
+
[nt.id, nt.source_hash, params, arg_keys], sort_keys=True, default=str).encode()).hexdigest()
|
|
144
|
+
keys[nid] = key
|
|
145
|
+
cached = key in self.cache
|
|
146
|
+
started = time.perf_counter()
|
|
147
|
+
if cached:
|
|
148
|
+
outputs = self.cache[key]
|
|
149
|
+
self.cache.move_to_end(key)
|
|
150
|
+
else:
|
|
151
|
+
try:
|
|
152
|
+
ret = nt.fn(**args, **params)
|
|
153
|
+
except Exception as e:
|
|
154
|
+
# Start the traceback at the user's function, not at this loop.
|
|
155
|
+
tb = "".join(traceback.format_exception(type(e), e, e.__traceback__.tb_next))
|
|
156
|
+
results[nid] = {"status": "error", "error": f"{type(e).__name__}: {e}", "traceback": tb}
|
|
157
|
+
continue
|
|
158
|
+
if len(nt.outputs) > 1:
|
|
159
|
+
outputs = tuple(ret)
|
|
160
|
+
elif len(nt.outputs) == 1:
|
|
161
|
+
outputs = (ret,)
|
|
162
|
+
else:
|
|
163
|
+
outputs = ()
|
|
164
|
+
self._remember(key, outputs)
|
|
165
|
+
values[nid] = outputs
|
|
166
|
+
res: dict[str, Any] = {"status": "ok", "cached": cached, "key": key,
|
|
167
|
+
"seconds": round(time.perf_counter() - started, 3)}
|
|
168
|
+
if outputs:
|
|
169
|
+
res["summary"] = " · ".join(summary(o) for o in outputs)
|
|
170
|
+
try:
|
|
171
|
+
res["preview"] = preview(outputs[0], dpi)
|
|
172
|
+
except Exception as e: # a preview failing should not fail the node
|
|
173
|
+
res["preview"] = {"kind": "text", "text": f"(no preview: {e})"}
|
|
174
|
+
results[nid] = res
|
|
175
|
+
return results
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def export_script(graph: dict, registry: Registry) -> str:
|
|
179
|
+
"""The graph as a plain Python script that runs without nagare."""
|
|
180
|
+
registry.refresh()
|
|
181
|
+
nodes = {str(n["id"]): n for n in graph.get("nodes", [])}
|
|
182
|
+
order = topo_order(graph)
|
|
183
|
+
incoming: dict[str, dict[str, tuple[str, int]]] = {}
|
|
184
|
+
for link in graph.get("links", []):
|
|
185
|
+
incoming.setdefault(str(link["to"]), {})[link["input"]] = (str(link["from"]), int(link.get("out", 0)))
|
|
186
|
+
|
|
187
|
+
imports: dict[str, list[str]] = {}
|
|
188
|
+
lines: list[str] = []
|
|
189
|
+
outnames: dict[str, list[str]] = {}
|
|
190
|
+
for nid in order:
|
|
191
|
+
n = nodes[nid]
|
|
192
|
+
nt = registry.types.get(n["type"])
|
|
193
|
+
if nt is None:
|
|
194
|
+
lines.append(f"# node {nid}: unknown type {n['type']}")
|
|
195
|
+
continue
|
|
196
|
+
module, fname = nt.id.rsplit(".", 1)
|
|
197
|
+
imports.setdefault(module, [])
|
|
198
|
+
if fname not in imports[module]:
|
|
199
|
+
imports[module].append(fname)
|
|
200
|
+
var = f"{fname}_{nid}"
|
|
201
|
+
names = [var] if len(nt.outputs) <= 1 else [f"{var}_{o.name}" for o in nt.outputs]
|
|
202
|
+
outnames[nid] = names
|
|
203
|
+
args = []
|
|
204
|
+
for s in nt.inputs:
|
|
205
|
+
src = incoming.get(nid, {}).get(s.name)
|
|
206
|
+
if src and src[0] in outnames and src[1] < len(outnames[src[0]]):
|
|
207
|
+
args.append(f"{s.name}={outnames[src[0]][src[1]]}")
|
|
208
|
+
for p in nt.params:
|
|
209
|
+
v = n.get("params", {}).get(p.name, p.default)
|
|
210
|
+
if v != p.default:
|
|
211
|
+
args.append(f"{p.name}={v!r}")
|
|
212
|
+
call = f"{fname}({', '.join(args)})"
|
|
213
|
+
lhs = ", ".join(names) + " = " if nt.outputs else ""
|
|
214
|
+
lines.append(f"{lhs}{call}")
|
|
215
|
+
|
|
216
|
+
head = ["# Generated by nagare. Runs on its own: python this_file.py",
|
|
217
|
+
"import sys",
|
|
218
|
+
f"sys.path.insert(0, {str(registry.folder)!r}) # the folder holding your node functions",
|
|
219
|
+
""]
|
|
220
|
+
head += [f"from {m} import {', '.join(fs)}" for m, fs in imports.items()]
|
|
221
|
+
return "\n".join(head + [""] + lines) + "\n"
|
nagare/preview.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Small previews of node outputs for the browser: a table, a picture or text."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import html
|
|
7
|
+
import io
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def summary(value: Any) -> str:
|
|
12
|
+
"""A few words shown on the node itself."""
|
|
13
|
+
shape = getattr(value, "shape", None)
|
|
14
|
+
kind = type(value).__name__
|
|
15
|
+
if kind == "Figure":
|
|
16
|
+
return "figure"
|
|
17
|
+
if kind == "AnnData":
|
|
18
|
+
return f"{value.n_obs} × {value.n_vars} AnnData"
|
|
19
|
+
if shape is not None and isinstance(shape, tuple):
|
|
20
|
+
return " × ".join(str(s) for s in shape) + f" {kind}"
|
|
21
|
+
if isinstance(value, (list, tuple, set, dict)):
|
|
22
|
+
return f"{len(value)} items"
|
|
23
|
+
if value is None:
|
|
24
|
+
return "None"
|
|
25
|
+
text = repr(value)
|
|
26
|
+
return text if len(text) <= 28 else text[:27] + "…"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def preview(value: Any, dpi: int = 110) -> dict:
|
|
30
|
+
kind = type(value).__name__
|
|
31
|
+
if kind == "Figure" and hasattr(value, "savefig"):
|
|
32
|
+
buf = io.BytesIO()
|
|
33
|
+
value.savefig(buf, format="png", dpi=dpi, bbox_inches="tight")
|
|
34
|
+
return {"kind": "image", "png": base64.b64encode(buf.getvalue()).decode()}
|
|
35
|
+
if kind in ("DataFrame", "Series") and hasattr(value, "head"):
|
|
36
|
+
df = value.to_frame() if kind == "Series" else value
|
|
37
|
+
shown = df.iloc[:15, :12]
|
|
38
|
+
return {"kind": "table", "shape": list(df.shape),
|
|
39
|
+
"html": shown.to_html(classes="pv-table", border=0, float_format=lambda x: f"{x:.4g}")}
|
|
40
|
+
if kind == "AnnData":
|
|
41
|
+
return {"kind": "text", "text": repr(value)}
|
|
42
|
+
if kind == "ndarray":
|
|
43
|
+
import numpy as np
|
|
44
|
+
|
|
45
|
+
with np.printoptions(threshold=200, edgeitems=4, precision=4):
|
|
46
|
+
return {"kind": "text", "text": f"array shape {value.shape} dtype {value.dtype}\n{value!r}"}
|
|
47
|
+
text = repr(value)
|
|
48
|
+
if len(text) > 4000:
|
|
49
|
+
text = text[:4000] + "\n…"
|
|
50
|
+
return {"kind": "text", "text": text}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def error_html(tb: str) -> str:
|
|
54
|
+
return "<pre class='pv-error'>" + html.escape(tb) + "</pre>"
|