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.
nagare/registry.py ADDED
@@ -0,0 +1,239 @@
1
+ """Turn plain Python functions into node types.
2
+
3
+ Every public function defined in a .py file of the nodes folder becomes a
4
+ node. Its type hints decide the node's shape:
5
+
6
+ * parameters typed str, int, float, bool or Literal[...] become settings
7
+ (widgets on the node);
8
+ * every other parameter becomes an input socket, typed by its annotation
9
+ (DataFrame, Figure, AnnData, ...); unannotated ones accept anything;
10
+ * the return annotation gives the output socket(s); tuple[A, B] gives two.
11
+
12
+ @node is optional. Use it to rename outputs, give a title, or force a
13
+ str/int parameter to be a socket instead of a setting.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import hashlib
19
+ import importlib.util
20
+ import inspect
21
+ import sys
22
+ import typing
23
+ from dataclasses import dataclass, field
24
+ from pathlib import Path
25
+ from typing import Any, Callable, Literal, get_args, get_origin
26
+
27
+ WIDGET_TYPES = {str: "str", int: "int", float: "float", bool: "bool", Path: "str"}
28
+
29
+
30
+ def node(fn: Callable | None = None, *, title: str | None = None, outputs: list[str] | None = None,
31
+ sockets: list[str] | None = None, category: str | None = None):
32
+ """Optional decorator: extra details for a node."""
33
+
34
+ def wrap(f: Callable) -> Callable:
35
+ f.__nagare__ = {"title": title, "outputs": outputs, "sockets": set(sockets or []), "category": category}
36
+ return f
37
+
38
+ return wrap(fn) if fn is not None else wrap
39
+
40
+
41
+ @dataclass
42
+ class Socket:
43
+ name: str
44
+ type: str # a type name such as "DataFrame"; "*" accepts anything
45
+
46
+
47
+ @dataclass
48
+ class Param:
49
+ name: str
50
+ type: str # str, int, float, bool or choice
51
+ default: Any = None
52
+ choices: list[Any] | None = None
53
+
54
+
55
+ @dataclass
56
+ class NodeType:
57
+ id: str # "module.function"
58
+ title: str
59
+ category: str
60
+ doc: str
61
+ fn: Callable = field(repr=False)
62
+ source_hash: str
63
+ inputs: list[Socket]
64
+ params: list[Param]
65
+ outputs: list[Socket]
66
+ required: set[str] = field(default_factory=set) # inputs without a default
67
+
68
+ def spec(self) -> dict:
69
+ return {
70
+ "id": self.id, "title": self.title, "category": self.category, "doc": self.doc,
71
+ "inputs": [s.__dict__ for s in self.inputs],
72
+ "params": [p.__dict__ for p in self.params],
73
+ "outputs": [s.__dict__ for s in self.outputs],
74
+ "required": sorted(self.required),
75
+ }
76
+
77
+
78
+ def type_name(t: Any) -> str:
79
+ if t is inspect.Parameter.empty or t is Any or t is None:
80
+ return "*"
81
+ if isinstance(t, str): # unresolved forward reference
82
+ return t.split(".")[-1]
83
+ origin = get_origin(t)
84
+ if origin is not None: # list[str], Optional[X] ...
85
+ return getattr(origin, "__name__", str(origin))
86
+ return getattr(t, "__name__", str(t))
87
+
88
+
89
+ def _hints(fn: Callable) -> dict[str, Any]:
90
+ try:
91
+ return typing.get_type_hints(fn)
92
+ except Exception: # a type that cannot be resolved: fall back to raw annotations
93
+ return dict(getattr(fn, "__annotations__", {}))
94
+
95
+
96
+ def describe(fn: Callable, module: str) -> NodeType:
97
+ extra = getattr(fn, "__nagare__", {})
98
+ hints = _hints(fn)
99
+ sig = inspect.signature(fn)
100
+ inputs, params, required = [], [], set()
101
+ for p in sig.parameters.values():
102
+ if p.kind in (p.VAR_POSITIONAL, p.VAR_KEYWORD):
103
+ continue
104
+ ann = hints.get(p.name, p.annotation)
105
+ default = None if p.default is inspect.Parameter.empty else p.default
106
+ if get_origin(ann) is Literal and p.name not in extra.get("sockets", ()):
107
+ choices = list(get_args(ann))
108
+ params.append(Param(p.name, "choice", default if default is not None else choices[0], choices))
109
+ elif ann in WIDGET_TYPES and p.name not in extra.get("sockets", ()):
110
+ wt = WIDGET_TYPES[ann]
111
+ if default is None:
112
+ default = {"str": "", "int": 0, "float": 0.0, "bool": False}[wt]
113
+ params.append(Param(p.name, wt, str(default) if ann is Path else default))
114
+ else:
115
+ inputs.append(Socket(p.name, type_name(ann)))
116
+ if p.default is inspect.Parameter.empty:
117
+ required.add(p.name)
118
+
119
+ ret = hints.get("return", sig.return_annotation)
120
+ names = extra.get("outputs")
121
+ if get_origin(ret) is tuple and get_args(ret) and Ellipsis not in get_args(ret):
122
+ types = [type_name(a) for a in get_args(ret)]
123
+ elif ret is None or ret is type(None):
124
+ types = []
125
+ else:
126
+ types = [type_name(ret)]
127
+ if names and len(names) != len(types):
128
+ raise ValueError(f"{fn.__name__}: @node outputs names {len(names)} outputs, the return type has {len(types)}")
129
+ outputs = [Socket((names or [])[i] if names else (t.lower() if t != "*" else "out"), t) for i, t in enumerate(types)]
130
+
131
+ try:
132
+ src = inspect.getsource(fn)
133
+ except OSError:
134
+ src = fn.__qualname__
135
+ doc = (inspect.getdoc(fn) or "").strip().split("\n\n")[0].replace("\n", " ")
136
+ return NodeType(
137
+ id=f"{module}.{fn.__name__}",
138
+ title=extra.get("title") or fn.__name__.replace("_", " ").capitalize(),
139
+ category=extra.get("category") or module,
140
+ doc=doc, fn=fn, source_hash=hashlib.sha1(src.encode()).hexdigest()[:12],
141
+ inputs=inputs, params=params, outputs=outputs, required=required,
142
+ )
143
+
144
+
145
+ def _folder_imports(mod: Any, names: set[str]) -> set[str]:
146
+ """The other files of the nodes folder that a module uses, by name.
147
+
148
+ Catches `import other` and `from other import helper` (functions and
149
+ classes remember the module they were defined in).
150
+ """
151
+ used = set()
152
+ for value in vars(mod).values():
153
+ if inspect.ismodule(value):
154
+ m = value.__name__
155
+ else:
156
+ m = getattr(value, "__module__", None) if (inspect.isfunction(value) or inspect.isclass(value)) else None
157
+ if m in names and m != mod.__name__:
158
+ used.add(m)
159
+ return used
160
+
161
+
162
+ def _closure(name: str, deps: dict[str, set[str]]) -> set[str]:
163
+ """A module and every folder module it depends on, directly or not."""
164
+ seen, stack = set(), [name]
165
+ while stack:
166
+ m = stack.pop()
167
+ if m not in seen:
168
+ seen.add(m)
169
+ stack.extend(deps.get(m, ()))
170
+ return seen
171
+
172
+
173
+ class Registry:
174
+ """The node types found in a folder of .py files, reloaded when a file changes."""
175
+
176
+ def __init__(self, folder: str | Path):
177
+ self.folder = Path(folder).resolve()
178
+ self.types: dict[str, NodeType] = {}
179
+ self.errors: dict[str, str] = {} # file -> import error
180
+ self._mtimes: dict[Path, float] = {}
181
+
182
+ def files(self) -> list[Path]:
183
+ return sorted(p for p in self.folder.glob("*.py") if not p.name.startswith("_"))
184
+
185
+ def refresh(self) -> bool:
186
+ """Reload if any file changed. Returns True when something was reloaded."""
187
+ mtimes = {p: p.stat().st_mtime for p in self.files()}
188
+ if mtimes == self._mtimes:
189
+ return False
190
+ self._mtimes = mtimes
191
+ self.types, self.errors = {}, {}
192
+ if str(self.folder) not in sys.path:
193
+ sys.path.insert(0, str(self.folder))
194
+ names = {p.stem for p in mtimes}
195
+ # Forget the old copies first, so a file that imports another file of
196
+ # the folder gets the new one, not what was loaded before the edit.
197
+ for name in names:
198
+ sys.modules.pop(name, None)
199
+
200
+ file_hash: dict[str, str] = {}
201
+ deps: dict[str, set[str]] = {}
202
+ loaded: list[tuple[Path, Any]] = []
203
+ for path in mtimes:
204
+ name = path.stem
205
+ file_hash[name] = hashlib.sha1(path.read_bytes()).hexdigest()
206
+ try:
207
+ spec = importlib.util.spec_from_file_location(name, path)
208
+ mod = importlib.util.module_from_spec(spec)
209
+ sys.modules[name] = mod
210
+ spec.loader.exec_module(mod)
211
+ except Exception as e: # show the error instead of failing the whole palette
212
+ self.errors[path.name] = f"{type(e).__name__}: {e}"
213
+ continue
214
+ deps[name] = _folder_imports(mod, names)
215
+ loaded.append((path, mod))
216
+
217
+ for path, mod in loaded:
218
+ name = path.stem
219
+ # A node's result depends on more than its own source: helpers in
220
+ # the same file, and other files of the folder it imports. So the
221
+ # cache key covers the whole file and those files. Editing one
222
+ # function re-runs every node from that file, which costs a little
223
+ # time but never shows a result from old code.
224
+ code = "".join(file_hash[m] for m in sorted(_closure(name, deps)))
225
+ for fname, fn in vars(mod).items():
226
+ if fname.startswith("_") or not inspect.isfunction(fn) or fn.__module__ != name:
227
+ continue
228
+ try:
229
+ nt = describe(fn, name)
230
+ except Exception as e:
231
+ self.errors[f"{path.name}:{fname}"] = str(e)
232
+ continue
233
+ nt.source_hash = hashlib.sha1((nt.source_hash + code).encode()).hexdigest()[:12]
234
+ self.types[nt.id] = nt
235
+ return True
236
+
237
+ def specs(self) -> dict:
238
+ self.refresh()
239
+ return {"types": [t.spec() for t in self.types.values()], "errors": self.errors}
nagare/server.py ADDED
@@ -0,0 +1,168 @@
1
+ """The local web server: the canvas, the node palette, runs and saved graphs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ipaddress
6
+ import json
7
+ import re
8
+ import threading
9
+ from http import HTTPStatus
10
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
11
+ from pathlib import Path
12
+ from urllib.parse import urlsplit
13
+
14
+ from .engine import Engine, GraphError, export_script
15
+ from .registry import Registry
16
+
17
+ STATIC = Path(__file__).parent / "static"
18
+ TYPES = {".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8",
19
+ ".css": "text/css; charset=utf-8", ".svg": "image/svg+xml"}
20
+ NAME = re.compile(r"^[\w.-]{1,80}$")
21
+
22
+
23
+ def local_host(hostport: str) -> bool:
24
+ """Whether a Host header names this machine by "localhost" or an IP address.
25
+
26
+ DNS rebinding (a page on evil.example pointing its own name at 127.0.0.1
27
+ to read nagare as if same-origin) always needs a domain name, so those
28
+ requests are refused while IP addresses, LAN ones included, still work.
29
+ """
30
+ host = hostport.strip()
31
+ if host.startswith("["): # [::1]:8650
32
+ host = host[1:].split("]", 1)[0]
33
+ elif host.count(":") == 1:
34
+ host = host.split(":", 1)[0]
35
+ host = host.rstrip(".")
36
+ if host.lower() == "localhost":
37
+ return True
38
+ try:
39
+ ipaddress.ip_address(host)
40
+ return True
41
+ except ValueError:
42
+ return False
43
+
44
+
45
+ def cross_site(headers, host: str) -> bool:
46
+ """Whether a browser marked the request as coming from another site's page.
47
+
48
+ Any page open in the browser can POST to 127.0.0.1:8650 without a CORS
49
+ preflight (a form, or fetch with text/plain), which would run your node
50
+ functions or overwrite a saved graph. Requests without either header
51
+ (curl, scripts, kenkyu's own server calls) are let through: only browsers
52
+ carry other sites' pages. The same rules as kenkyu's server.Guard.
53
+ """
54
+ site = headers.get("Sec-Fetch-Site")
55
+ if site in ("same-origin", "none"):
56
+ return False
57
+ if site in ("same-site", "cross-site"):
58
+ return True
59
+ origin = headers.get("Origin") # older browsers send no Sec-Fetch-Site
60
+ if not origin:
61
+ return False
62
+ netloc = urlsplit(origin).netloc # "null" (sandboxed frames, file://) has none
63
+ return not netloc or netloc.lower() != host.lower()
64
+
65
+
66
+ class App:
67
+ def __init__(self, folder: str | Path, graphs: str | Path | None = None):
68
+ self.registry = Registry(folder)
69
+ self.engine = Engine(self.registry)
70
+ self.graphs = Path(graphs) if graphs else self.registry.folder / "graphs"
71
+ self.lock = threading.Lock() # one run at a time keeps the cache simple
72
+
73
+
74
+ def handler(app: App):
75
+ class Handler(BaseHTTPRequestHandler):
76
+ def log_message(self, fmt, *args): # quiet
77
+ pass
78
+
79
+ def send(self, status: int, body: bytes | str, ctype: str = "application/json") -> None:
80
+ data = body.encode() if isinstance(body, str) else body
81
+ self.send_response(status)
82
+ self.send_header("Content-Type", ctype)
83
+ self.send_header("Content-Length", str(len(data)))
84
+ self.send_header("Cache-Control", "no-store")
85
+ self.end_headers()
86
+ self.wfile.write(data)
87
+
88
+ def json(self, value, status: int = 200) -> None:
89
+ self.send(status, json.dumps(value, default=str))
90
+
91
+ def body(self):
92
+ n = int(self.headers.get("Content-Length") or 0)
93
+ return json.loads(self.rfile.read(n) or b"{}")
94
+
95
+ def allowed(self, changes: bool) -> bool:
96
+ host = self.headers.get("Host", "")
97
+ if not local_host(host):
98
+ self.send(421, "nagare only answers to localhost or an IP address", "text/plain")
99
+ return False
100
+ if changes and cross_site(self.headers, host):
101
+ self.json({"error": "cross-site request refused"}, 403)
102
+ return False
103
+ return True
104
+
105
+ def do_GET(self):
106
+ if not self.allowed(changes=False):
107
+ return
108
+ path = self.path.split("?")[0]
109
+ if path == "/":
110
+ path = "/index.html"
111
+ if path == "/api/info":
112
+ from . import KENKYU_PROTOCOL, __version__
113
+
114
+ return self.json({"name": "nagare", "version": __version__, "kenkyu": KENKYU_PROTOCOL,
115
+ "folder": str(app.registry.folder)})
116
+ if path == "/api/nodes":
117
+ return self.json(app.registry.specs())
118
+ if path == "/api/graphs":
119
+ names = sorted(p.stem for p in app.graphs.glob("*.json")) if app.graphs.exists() else []
120
+ return self.json(names)
121
+ if path.startswith("/api/graphs/"):
122
+ name = path.rsplit("/", 1)[1]
123
+ f = app.graphs / f"{name}.json"
124
+ if not NAME.match(name) or not f.exists():
125
+ return self.json({"error": "no such graph"}, 404)
126
+ return self.send(200, f.read_bytes())
127
+ f = (STATIC / path.lstrip("/")).resolve()
128
+ if not str(f).startswith(str(STATIC.resolve())) or not f.is_file():
129
+ return self.send(404, "not found", "text/plain")
130
+ self.send(200, f.read_bytes(), TYPES.get(f.suffix, "application/octet-stream"))
131
+
132
+ def do_POST(self):
133
+ if not self.allowed(changes=True):
134
+ return
135
+ path = self.path.split("?")[0]
136
+ try:
137
+ data = self.body()
138
+ except json.JSONDecodeError:
139
+ return self.json({"error": "bad JSON"}, 400)
140
+ if path == "/api/run":
141
+ with app.lock:
142
+ try:
143
+ dpi = min(max(int(data.get("dpi") or 110), 50), 600)
144
+ return self.json({"results": app.engine.run(data["graph"], data.get("target"), dpi)})
145
+ except (GraphError, KeyError, TypeError, ValueError) as e:
146
+ return self.json({"error": str(e)}, 400)
147
+ if path == "/api/export":
148
+ try:
149
+ return self.send(200, export_script(data["graph"], app.registry), "text/x-python; charset=utf-8")
150
+ except GraphError as e:
151
+ return self.json({"error": str(e)}, 400)
152
+ if path.startswith("/api/graphs/"):
153
+ name = path.rsplit("/", 1)[1]
154
+ if not NAME.match(name):
155
+ return self.json({"error": "use letters, digits, - _ and ."}, 400)
156
+ app.graphs.mkdir(parents=True, exist_ok=True)
157
+ (app.graphs / f"{name}.json").write_text(json.dumps(data, indent=1))
158
+ return self.json({"saved": name})
159
+ self.json({"error": "not found"}, HTTPStatus.NOT_FOUND)
160
+
161
+ return Handler
162
+
163
+
164
+ def serve(folder: str | Path, port: int = 8650, graphs: str | Path | None = None, host: str = "127.0.0.1"):
165
+ app = App(folder, graphs)
166
+ app.registry.refresh()
167
+ httpd = ThreadingHTTPServer((host, port), handler(app))
168
+ return app, httpd
nagare/static/app.css ADDED
@@ -0,0 +1,59 @@
1
+ :root {
2
+ --bg: #1d1d1f; --panel: #252527; --line: #38383b; --text: #e6e6e6; --muted: #9a9aa0;
3
+ --accent: #e0883a; --ok: #5fb36b; --err: #e05a4f; --wait: #c9a640;
4
+ font: 13px/1.45 system-ui, -apple-system, "Segoe UI", sans-serif;
5
+ }
6
+ * { box-sizing: border-box; }
7
+ html, body { margin: 0; height: 100%; background: var(--bg); color: var(--text); }
8
+ body { display: flex; flex-direction: column; }
9
+
10
+ .bar { display: flex; align-items: center; gap: .5rem; padding: .45rem .75rem; background: var(--panel); border-bottom: 1px solid var(--line); }
11
+ .brand { font-size: 14px; margin-right: .75rem; letter-spacing: .02em; }
12
+ .bar button, .bar select {
13
+ background: #333336; color: var(--text); border: 1px solid #47474b; border-radius: 4px;
14
+ padding: .25rem .7rem; font: inherit; cursor: pointer;
15
+ }
16
+ .bar button:hover, .bar select:hover { border-color: var(--accent); }
17
+ #run { background: var(--accent); border-color: var(--accent); color: #1a1a1a; font-weight: 600; }
18
+ .live { display: flex; align-items: center; gap: .3rem; color: var(--muted); cursor: pointer; }
19
+ .sep { width: 1px; height: 1.2rem; background: var(--line); margin: 0 .25rem; }
20
+ .status { margin-left: auto; color: var(--muted); }
21
+ .notice { background: #3b3220; color: #f1d9a6; padding: .35rem .75rem; border-bottom: 1px solid #5a4a26; }
22
+ .notice button { margin-left: .5rem; }
23
+
24
+ main { flex: 1; display: grid; grid-template-columns: 210px 1fr 360px; min-height: 0; }
25
+ .palette, .panel { background: var(--panel); overflow: auto; }
26
+ .palette { border-right: 1px solid var(--line); padding: .6rem; }
27
+ .panel { border-left: 1px solid var(--line); padding: .8rem; }
28
+ .canvas-wrap { position: relative; min-width: 0; }
29
+ #canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
30
+
31
+ #filter { width: 100%; padding: .35rem .5rem; background: #1f1f21; color: var(--text); border: 1px solid var(--line); border-radius: 4px; font: inherit; }
32
+ .cat { margin: .8rem 0 .25rem; color: var(--muted); font-size: 11px; text-transform: uppercase; letter-spacing: .06em; }
33
+ .pal-item { display: block; width: 100%; text-align: left; background: none; border: 0; color: var(--text); padding: .25rem .4rem; border-radius: 3px; cursor: pointer; font: inherit; }
34
+ .pal-item:hover { background: #333336; }
35
+ .pal-item small { display: block; color: var(--muted); font-size: 11px; line-height: 1.3; }
36
+ .hint, .muted { color: var(--muted); font-size: 12px; }
37
+ .load-error { color: var(--err); font-size: 12px; }
38
+
39
+ .panel h2 { font-size: 15px; margin: 0 0 .2rem; }
40
+ .panel .doc { color: var(--muted); margin: 0 0 .6rem; }
41
+ .badges { display: flex; gap: .35rem; flex-wrap: wrap; margin-bottom: .7rem; }
42
+ .badge { font-size: 11px; padding: .05rem .45rem; border-radius: 3px; background: #333336; color: var(--muted); }
43
+ .badge.ok { color: var(--ok); } .badge.error { color: var(--err); } .badge.waiting { color: var(--wait); }
44
+ .panel img { max-width: 100%; background: #fff; border-radius: 4px; }
45
+ .pv-table { border-collapse: collapse; font-size: 11.5px; font-variant-numeric: tabular-nums; }
46
+ .pv-table th, .pv-table td { padding: .15rem .45rem; border-bottom: 1px solid var(--line); text-align: right; white-space: nowrap; }
47
+ .pv-table thead th { color: var(--muted); }
48
+ .table-wrap { overflow: auto; max-height: 60vh; }
49
+ pre { white-space: pre-wrap; word-break: break-word; font-size: 11.5px; background: #1f1f21; padding: .5rem; border-radius: 4px; }
50
+ pre.pv-error { color: #f2b8b2; }
51
+
52
+ /* Inside kenkyu: a narrower frame, so slimmer side columns. */
53
+ .flow-name { font-weight: 600; margin-right: .5rem; max-width: 16rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
54
+ .in-kenkyu .brand { margin-right: .25rem; }
55
+ .in-kenkyu main { grid-template-columns: 170px 1fr 270px; }
56
+ @media (max-width: 820px) {
57
+ .in-kenkyu main { grid-template-columns: 0 1fr 240px; }
58
+ .in-kenkyu .palette { padding: 0; border: 0; overflow: hidden; }
59
+ }