skilltree-lab 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,311 @@
1
+ """skilltree edit tree.toml: drag, add, link and take away nodes in a browser page; Save writes the hand fixes back.
2
+ A file of [[tree]] blocks opens every tree at once, and lines between trees go to links."""
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import math
8
+ import re
9
+ import threading
10
+ import tomllib
11
+ import webbrowser
12
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
13
+ from importlib import resources
14
+ from pathlib import Path
15
+
16
+ from .shapes import BY_LABEL, LOOKS, SHAPES, build_file, stamp
17
+ from .svg import UNIT, colour, mark
18
+
19
+ KEYS = ("move", "place", "joins", "add", "remove", "cut", "shift", "node_shapes") # what the page edits; the rest stays
20
+ DICTS = ("move", "place", "add", "shift", "node_shapes")
21
+ _BARE = re.compile(r"^[A-Za-z0-9_-]+$")
22
+ _NEW = re.compile(r"^n(\d+)$") # the names the page gives new nodes
23
+
24
+
25
+ def _split(cfg: dict, name=None) -> dict:
26
+ """One tree's settings as the page holds them: its hand fixes apart from the rest."""
27
+ return {**{k: cfg.get(k, {} if k in DICTS else []) for k in KEYS}, "name": name if name is not None else cfg.get("name"),
28
+ "at": cfg.get("at", [0, 0]), "settings": None}
29
+
30
+
31
+ def hand_of(cfg: dict) -> dict:
32
+ """The page's part of a file: per tree its hand fixes (and at), where it comes from, plus links between trees.
33
+ src is the tree's block in the file (0 for a file of one tree); a tree added on the page has src None and
34
+ carries its own settings."""
35
+ if "tree" in cfg:
36
+ return {"multi": True, "links": cfg.get("links", []),
37
+ "trees": [{**_split(tc), "src": i} for i, tc in enumerate(cfg["tree"])]}
38
+ return {"multi": False, "links": [], "trees": [{**_split(cfg), "name": None, "src": 0}]}
39
+
40
+
41
+ def parse(text: str, stem: str) -> dict:
42
+ """Another file's trees, ready to join the page's: each with settings of its own, src None."""
43
+ cfg = tomllib.loads(text)
44
+ if "tree" in cfg:
45
+ trees = [dict(tc) for tc in cfg["tree"]]
46
+ links = cfg.get("links", [])
47
+ else:
48
+ trees = [{**{k: v for k, v in cfg.items() if k != "links"}, "name": re.sub(r"[^A-Za-z0-9_-]", "_", stem) or "tree"}]
49
+ links = []
50
+ out = []
51
+ for tc in trees:
52
+ t = _split(tc)
53
+ t["settings"] = {k: v for k, v in tc.items() if k not in KEYS + ("name", "at")}
54
+ t["src"] = None
55
+ out.append(t)
56
+ return {"trees": out, "links": links}
57
+
58
+
59
+ def _fill(hand: dict) -> None:
60
+ """Every key in place, so a page or a test that leaves an empty one out reads the same."""
61
+ hand.setdefault("links", [])
62
+ for h in hand["trees"]:
63
+ for k in KEYS:
64
+ h.setdefault(k, {} if k in DICTS else [])
65
+ h.setdefault("at", [0, 0])
66
+
67
+
68
+ def merged(cfg: dict, hand: dict) -> dict:
69
+ """The settings the page stands for: the file's trees it kept, the trees it added, with its hand fixes."""
70
+ _fill(hand)
71
+ def put(dst: dict, h: dict, keys) -> None:
72
+ for k in keys:
73
+ if h.get(k):
74
+ dst[k] = h[k]
75
+ else:
76
+ dst.pop(k, None)
77
+ blocks = cfg.get("tree")
78
+
79
+ def base(h: dict) -> dict:
80
+ if h.get("settings") is not None:
81
+ return dict(h["settings"])
82
+ if blocks is None:
83
+ return {k: v for k, v in cfg.items() if k != "links"}
84
+ if not 0 <= h["src"] < len(blocks):
85
+ raise ValueError("the file's trees changed; press Reset")
86
+ return dict(blocks[h["src"]])
87
+ if not hand["multi"]:
88
+ out = base(hand["trees"][0])
89
+ put(out, hand["trees"][0], KEYS)
90
+ return out
91
+ if not hand["trees"]:
92
+ raise ValueError("at least one tree stays")
93
+ trees = []
94
+ for h in hand["trees"]:
95
+ tc = base(h)
96
+ tc["name"] = h["name"]
97
+ put(tc, h, KEYS + ("at",))
98
+ trees.append(tc)
99
+ return {"tree": trees, **({"links": hand["links"]} if hand["links"] else {})}
100
+
101
+
102
+ def _named(settings: dict) -> set[str]:
103
+ """Labels a tree's other settings name, which renumbering cannot follow."""
104
+ out = set(settings.get("node_costs", {})) | set(settings.get("need_all", []))
105
+ out |= {g.get("at") for g in settings.get("grow", []) if isinstance(g, dict)}
106
+ out |= {lb for pair in settings.get("meet", []) for lb in pair}
107
+ return out
108
+
109
+
110
+ def renumber(hand: dict, t, settings: list[dict]) -> bool:
111
+ """New nodes (n1, n2...) numbered outward along their lines, nearest the start first, so a line drawn
112
+ n3-n1-n2 out from the start reads n1-n2-n3. Renames them everywhere in hand; True if any changed."""
113
+ tier = {n.label: n.tier for n in t.nodes}
114
+ changed = False
115
+ for h in hand["trees"]:
116
+ pre = f"{h['name']}." if hand["multi"] else ""
117
+ new = sorted((lb for lb in h["add"] if _NEW.match(lb)),
118
+ key=lambda lb: (tier.get(pre + lb, -1) if tier.get(pre + lb, -1) >= 0 else math.inf,
119
+ int(_NEW.match(lb).group(1))))
120
+ names = {old: f"n{i}" for i, old in enumerate(new, 1)}
121
+ taken = {lb[len(pre):] for lb in tier if lb.startswith(pre)} - set(h["add"]) # arm n of a 14-arm shape
122
+ if all(a == b for a, b in names.items()) or taken & set(names.values()) or \
123
+ _named(settings[hand["trees"].index(h)]) & set(names): # node_costs = {n3 = ...} would go astray
124
+ continue
125
+ changed = True
126
+ r = lambda lb: names.get(lb, lb)
127
+ h["add"] = {r(k): v for k, v in h["add"].items()}
128
+ h["move"] = {r(k): v for k, v in h["move"].items()}
129
+ h["place"] = {r(k): v for k, v in h["place"].items()}
130
+ h["shift"] = {r(k): v for k, v in h["shift"].items()}
131
+ h["node_shapes"] = {r(k): v for k, v in h["node_shapes"].items()}
132
+ h["joins"] = [[r(a), r(b)] for a, b in h["joins"]]
133
+ h["cut"] = [[r(a), r(b)] for a, b in h["cut"]]
134
+ if pre:
135
+ rf = lambda lb: pre + r(lb[len(pre):]) if lb.startswith(pre) else lb
136
+ hand["links"] = [[rf(a), rf(b)] for a, b in hand["links"]]
137
+ return changed
138
+
139
+
140
+ def tree_data(cfg: dict, hand: dict) -> dict:
141
+ """Build every tree with the page's hand fixes, renumbering new nodes first if their order is off."""
142
+ m = merged(cfg, hand)
143
+ t = build_file(m)
144
+ if renumber(hand, t, m.get("tree", [m])):
145
+ t = build_file(merged(cfg, hand))
146
+ top = max(n.tier for n in t.nodes) or 1
147
+ seen: set[int] = set()
148
+ edges = []
149
+ for a, b in t.edges:
150
+ edges.append([a, b, b in seen]) # a second line into a node is a join
151
+ seen.add(b)
152
+ names = [h["name"] for h in hand["trees"]]
153
+ nodes = []
154
+ for n in t.nodes:
155
+ name, _, local = n.label.rpartition(".") if hand["multi"] else (None, "", n.label)
156
+ nodes.append({"id": n.id, "x": n.x, "y": n.y, "label": n.label, "local": local, "look": n.look, "ratio": list(n.ratio),
157
+ "tree": names.index(name) if hand["multi"] else 0,
158
+ "mark": mark(n.look, n.ratio, 0, 0, colour(n, t, top), f"{n.label} tier {n.tier}")})
159
+ ratios = [list(tc.get("node_ratio", [1, 1])) for tc in m.get("tree", [m])] # each tree's default, for the node panel
160
+ return {"unit": UNIT, "warnings": t.warnings, "edges": edges, "nodes": nodes, "ratios": ratios}
161
+
162
+
163
+ def _value(v) -> str:
164
+ if isinstance(v, dict):
165
+ return "{" + ", ".join(f"{k if _BARE.match(k) else json.dumps(k)} = {_value(x)}" for k, x in v.items()) + "}"
166
+ if isinstance(v, list):
167
+ return "[" + ", ".join(_value(x) for x in v) + "]"
168
+ if isinstance(v, float):
169
+ return repr(round(v, 3))
170
+ return json.dumps(v)
171
+
172
+
173
+ def _rewrite(seg: list[str], values: dict) -> list[str]:
174
+ """seg with the lines of values' keys taken out and the new ones put at its end (before blank lines)."""
175
+ out = []
176
+ for line in seg:
177
+ m = re.match(r"\s*(\w+)\s*=", line)
178
+ if m and m.group(1) in values:
179
+ body = line.split("=", 1)[1]
180
+ if body.count("[") + body.count("{") != body.count("]") + body.count("}"):
181
+ # shortcut: only one-line values are rewritten; a value spread over lines would need a TOML writer
182
+ raise ValueError(f"{m.group(1)} runs over several lines; put it on one line to save from the editor")
183
+ continue
184
+ out.append(line)
185
+ at = len(out)
186
+ while at > 0 and not out[at - 1].strip():
187
+ at -= 1
188
+ out[at:at] = [f"{k} = {_value(v)}" for k, v in values.items() if v]
189
+ return out
190
+
191
+
192
+ def write_back(text: str, hand: dict) -> str:
193
+ """The file with the page's lines in place of its own; every other line stays as it was. Trees the page took
194
+ away lose their block, trees it added get one, and a file of one tree that got a second becomes blocks."""
195
+ _fill(hand)
196
+ lines = text.splitlines()
197
+ heads = [i for i, ln in enumerate(lines) if re.match(r"\s*\[", ln)]
198
+ blocks = [i for i in heads if re.match(r"\s*\[\[tree\]\]\s*(#.*)?$", lines[i])]
199
+ if not hand["multi"]: # one tree: its keys must come before any [table]
200
+ end = heads[0] if heads else len(lines)
201
+ h = hand["trees"][0]
202
+ return "\n".join(_rewrite(lines[:end], {**{k: h[k] for k in KEYS}, "made_with": h.get("made_with")})
203
+ + lines[end:]) + "\n"
204
+ if blocks != heads:
205
+ raise ValueError("a file of [[tree]] blocks may hold no other [table]; write it inline to save from the editor")
206
+ if blocks:
207
+ top = lines[:blocks[0]]
208
+ src = {i: (lines[s], lines[s + 1:e]) for i, (s, e) in enumerate(zip(blocks, blocks[1:] + [len(lines)]))}
209
+ else: # the one tree's settings move into a block of their own; comments above them stay on top
210
+ first = next((i for i, ln in enumerate(lines) if re.match(r"\s*[\w\"-]+\s*=", ln)), len(lines))
211
+ top, src = lines[:first], {0: ("[[tree]]", lines[first:])}
212
+ out = _rewrite(top, {"links": hand["links"]})
213
+ for h in hand["trees"]:
214
+ if h.get("settings") is None:
215
+ head, body = src[h["src"]]
216
+ if not blocks:
217
+ body = [f"name = {json.dumps(h['name'])}"] + body
218
+ else: # a renamed tree: its name line changes where it stands
219
+ body = [f"name = {json.dumps(h['name'])}" if re.match(r"\s*name\s*=", ln) else ln for ln in body]
220
+ else:
221
+ head = "[[tree]]"
222
+ body = [f"name = {json.dumps(h['name'])}"] + [f"{k if _BARE.match(k) else json.dumps(k)} = {_value(v)}"
223
+ for k, v in h["settings"].items()]
224
+ at = h["at"] if any(h["at"]) else None # at = [0, 0] is the default: no line for it
225
+ if out and out[-1].strip():
226
+ out.append("")
227
+ out += [head] + _rewrite(body, {**{k: h[k] for k in KEYS}, "at": at, "made_with": h.get("made_with")})
228
+ return "\n".join(out).rstrip("\n") + "\n"
229
+
230
+
231
+ def stamp_trees(cfg: dict, hand: dict) -> None:
232
+ """made_with for every tree that has hand fixes, from the settings that decide its labels; none for the rest."""
233
+ m = merged(cfg, hand)
234
+ for h, tc in zip(hand["trees"], m.get("tree", [m])):
235
+ fixed = any(h.get(k) for k in KEYS) or any(tc.get(k) for k in BY_LABEL - {"made_with"})
236
+ h["made_with"] = stamp(tc) if fixed else None
237
+
238
+
239
+ def version(text: str) -> str:
240
+ return hashlib.sha1(text.encode("utf-8")).hexdigest()[:12]
241
+
242
+
243
+ def serve(path: str | Path, port: int = 0, open_page: bool = True) -> ThreadingHTTPServer:
244
+ path = Path(path)
245
+ page = resources.files(__package__).joinpath("editor.html").read_text(encoding="utf-8")
246
+
247
+ class Handler(BaseHTTPRequestHandler):
248
+ def log_message(self, *a): # quiet: the terminal shows only the address
249
+ pass
250
+
251
+ def send(self, code: int, body: dict | str, kind: str = "application/json") -> None:
252
+ data = (body if isinstance(body, str) else json.dumps(body)).encode("utf-8")
253
+ self.send_response(code)
254
+ self.send_header("Content-Type", f"{kind}; charset=utf-8")
255
+ self.send_header("Content-Length", str(len(data)))
256
+ self.end_headers()
257
+ self.wfile.write(data)
258
+
259
+ def foreign(self) -> bool:
260
+ """A request from another site (or a rebound name) instead of this page: refused, so no web page
261
+ the user has open can read or rewrite the file."""
262
+ me = f"127.0.0.1:{self.server.server_port}"
263
+ origin = self.headers.get("Origin")
264
+ if self.headers.get("Host") != me or (origin is not None and origin != f"http://{me}"):
265
+ self.send(403, {"error": "refused: not the editor page"})
266
+ return True
267
+ return False
268
+
269
+ def do_GET(self):
270
+ if self.foreign():
271
+ return
272
+ if self.path == "/":
273
+ return self.send(200, page, "text/html")
274
+ if self.path == "/state":
275
+ try:
276
+ text = path.read_text(encoding="utf-8")
277
+ cfg = tomllib.loads(text)
278
+ hand = hand_of(cfg)
279
+ return self.send(200, {"file": path.name, "stem": path.stem, "shapes": list(SHAPES), "looks": list(LOOKS),
280
+ "version": version(text),
281
+ "tree": tree_data(cfg, hand), "hand": hand})
282
+ except (ValueError, tomllib.TOMLDecodeError) as e:
283
+ return self.send(200, {"error": str(e)})
284
+ self.send(404, "{}")
285
+
286
+ def do_POST(self):
287
+ if self.foreign():
288
+ return
289
+ if self.path not in ("/build", "/parse"):
290
+ return self.send(404, "{}")
291
+ try:
292
+ req = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))))
293
+ if self.path == "/parse": # a file the page read from disk, to bring in as more trees
294
+ return self.send(200, parse(req["text"], req.get("stem", "tree")))
295
+ text = path.read_text(encoding="utf-8")
296
+ if req.get("version") != version(text): # the page's trees map to blocks of the text it loaded
297
+ raise ValueError(f"{path.name} changed on disk since it was opened; press Reset (unsaved work is lost)")
298
+ cfg, hand = tomllib.loads(text), req["hand"]
299
+ tree = tree_data(cfg, hand) # may renumber new nodes in hand
300
+ if req.get("save"):
301
+ stamp_trees(cfg, hand)
302
+ text = write_back(text, hand)
303
+ path.write_text(text, encoding="utf-8")
304
+ self.send(200, {"tree": tree, "hand": hand, "saved": bool(req.get("save")), "version": version(text)})
305
+ except (ValueError, KeyError, TypeError, tomllib.TOMLDecodeError) as e:
306
+ self.send(200, {"error": str(e)})
307
+
308
+ srv = ThreadingHTTPServer(("127.0.0.1", port), Handler) # this machine only
309
+ if open_page:
310
+ threading.Timer(0.3, webbrowser.open, [f"http://127.0.0.1:{srv.server_port}/"]).start()
311
+ return srv
@@ -0,0 +1,201 @@
1
+ """Star figures for the constellation shape: the 88 real ones, or ones you draw.
2
+
3
+ The real lines are Sky & Telescope's, the ones on the IAU's constellation
4
+ charts (data/snt.lines.json), and the asterisms are Stellarium's western ones
5
+ (data/asterisms.lines.json); both CC BY-SA, see data/NOTICE. Star positions
6
+ come from d3-celestial (BSD-3-Clause, data/LICENSE.d3-celestial).
7
+ tools/build_figures.py rebuilds both files. A figure here is plain
8
+ geometry: star positions on the page (y grows downward), the lines between
9
+ them, and the star the figure starts from.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import math
15
+ import random
16
+ from importlib import resources
17
+
18
+ Figure = tuple[list[tuple[float, float]], list[list[int]], int] # stars, strokes (stars in drawing order), start
19
+
20
+
21
+ def real_names() -> list[str]:
22
+ return sorted(_real())
23
+
24
+
25
+ def asterism_names() -> list[str]:
26
+ return sorted(_real("asterisms"))
27
+
28
+
29
+ def strokes_of(name: str) -> list[int]:
30
+ """Stars in each stroke of a real figure, for choosing parts with {name, strokes}."""
31
+ return [len(st) for st in _project(_real()[name.lower()])[1]]
32
+
33
+
34
+ def _keep(stars, strokes, chosen: list[int], name: str):
35
+ """Only the chosen strokes, numbered from 1, and only the stars they use."""
36
+ if any(not 1 <= c <= len(strokes) for c in chosen):
37
+ raise ValueError(f"figure {name}: strokes run from 1 to {len(strokes)}")
38
+ picked = [strokes[c - 1] for c in chosen]
39
+ used = sorted({i for st in picked for i in st})
40
+ new = {old: k for k, old in enumerate(used)}
41
+ return [stars[i] for i in used], [[new[i] for i in st] for st in picked]
42
+
43
+
44
+ _cache: dict[str, dict[str, list]] = {}
45
+
46
+
47
+ def _real(kind: str = "snt") -> dict[str, list]:
48
+ if kind not in _cache:
49
+ text = resources.files("skilltree_lab").joinpath(f"data/{kind}.lines.json").read_text("utf-8")
50
+ _cache[kind] = {}
51
+ for f in json.loads(text)["features"]:
52
+ _cache[kind].setdefault(f["id"].lower(), []).extend(f["geometry"]["coordinates"])
53
+ return _cache[kind]
54
+
55
+
56
+ def _project(lines: list) -> tuple[list[tuple[float, float]], list[list[int]]]:
57
+ """Sky lines (RA, Dec in degrees) to page stars and strokes, as seen looking up: east on the left."""
58
+ keys: dict[tuple[float, float], int] = {}
59
+ sky: list[tuple[float, float]] = []
60
+ strokes: list[list[int]] = []
61
+ for line in lines:
62
+ ids: list[int] = []
63
+ for ra, dec in line:
64
+ k = (round(ra, 3), round(dec, 3))
65
+ if k not in keys:
66
+ keys[k] = len(sky)
67
+ sky.append((math.radians(ra), math.radians(dec)))
68
+ if not ids or ids[-1] != keys[k]:
69
+ ids.append(keys[k])
70
+ if len(ids) > 1:
71
+ strokes.append(ids)
72
+ vx = sum(math.cos(d) * math.cos(r) for r, d in sky)
73
+ vy = sum(math.cos(d) * math.sin(r) for r, d in sky)
74
+ vz = sum(math.sin(d) for _, d in sky)
75
+ r0, d0 = math.atan2(vy, vx), math.atan2(vz, math.hypot(vx, vy))
76
+ page = []
77
+ for r, d in sky: # gnomonic projection about the figure's middle
78
+ c = math.sin(d0) * math.sin(d) + math.cos(d0) * math.cos(d) * math.cos(r - r0)
79
+ xi = math.cos(d) * math.sin(r - r0) / c
80
+ eta = (math.cos(d0) * math.sin(d) - math.sin(d0) * math.cos(d) * math.cos(r - r0)) / c
81
+ page.append((-xi, -eta))
82
+ return page, strokes
83
+
84
+
85
+ def _start(strokes: list[list[int]]) -> int:
86
+ """The first line end drawn, so the figure starts at a tip with one arm; failing that (all loops),
87
+ the first star drawn where no more than two lines meet (a start holds at most two arms)."""
88
+ deg: dict[int, int] = {}
89
+ for st in strokes:
90
+ for a, b in zip(st, st[1:]):
91
+ deg[a] = deg.get(a, 0) + 1
92
+ deg[b] = deg.get(b, 0) + 1
93
+ drawn = [i for st in strokes for i in st]
94
+ return next((i for i in drawn if deg[i] == 1), next((i for i in drawn if deg[i] <= 2), drawn[0]))
95
+
96
+
97
+ def pick(v, rng: random.Random) -> list[Figure]:
98
+ """figure = "ori", "random", a drawn figure {stars = [[x, y], ...], lines = [[0, 1], ...], start = 0},
99
+ or a list of those."""
100
+ out = []
101
+ for f in v if isinstance(v, list) else [v]:
102
+ if isinstance(f, dict) and "name" in f: # part of a real figure: {name = "ori", strokes = [1, 2]}
103
+ if set(f) - {"name", "strokes"}:
104
+ raise ValueError(f"figure {f}: name and strokes only")
105
+ name = str(f["name"]).lower()
106
+ if name not in _real():
107
+ raise ValueError(f"figure {f['name']!r}: not a constellation")
108
+ stars, strokes = _keep(*_project(_real()[name]), list(f.get("strokes") or range(1, len(strokes_of(name)) + 1)), name)
109
+ out.append((stars, strokes, _start(strokes)))
110
+ continue
111
+ if isinstance(f, dict):
112
+ extra = set(f) - {"stars", "lines", "start"}
113
+ if extra or "stars" not in f or "lines" not in f:
114
+ raise ValueError(f"figure {f}: needs stars and lines, may have start")
115
+ stars = [(float(x), float(y)) for x, y in f["stars"]]
116
+ lines = [(int(a), int(b)) for a, b in f["lines"]]
117
+ if any(not 0 <= i < len(stars) for ab in lines for i in ab):
118
+ raise ValueError(f"figure: a line names a star that is not there ({len(stars)} stars)")
119
+ strokes = [[a, b] for a, b in lines] # the order lines are written is the drawing order
120
+ out.append((stars, strokes, int(f.get("start", _start(strokes)))))
121
+ continue
122
+ name = str(f).lower()
123
+ if name in _real("asterisms"):
124
+ stars, strokes = _project(_real("asterisms")[name])
125
+ out.append((stars, strokes, _start(strokes)))
126
+ continue
127
+ if name == "random":
128
+ name = rng.choice(real_names())
129
+ if name not in _real():
130
+ raise ValueError(f"figure {f!r}: not a constellation or asterism (skilltree figures lists them)")
131
+ stars, strokes = _project(_real()[name])
132
+ out.append((stars, strokes, _start(strokes)))
133
+ return out
134
+
135
+
136
+ def trace(path: str, erode: int = 5, threshold: int = 128) -> dict:
137
+ """Trial: read a drawing (round stars, thinner lines, light on dark or dark on light) into a figure.
138
+
139
+ Stars are blobs that survive shaving `erode` pixels off every edge; a line is drawn between two
140
+ stars when nearly every pixel on the straight path between them is marked and no third star sits
141
+ on it. Needs Pillow (pip install skilltree-lab[trace]).
142
+ """
143
+ try:
144
+ from PIL import Image, ImageFilter, ImageStat
145
+ except ImportError as e:
146
+ raise SystemExit("trace needs Pillow: pip install skilltree-lab[trace]") from e
147
+ img = Image.open(path).convert("L")
148
+ if ImageStat.Stat(img).mean[0] > 128: # dark marks on a light page
149
+ img = img.point(lambda v: 255 - v)
150
+ mask = img.point(lambda v: 255 if v >= threshold else 0)
151
+ core = mask.filter(ImageFilter.MinFilter(erode)) if erode > 1 else mask
152
+ w, h = mask.size
153
+ on, cpx = mask.load(), core.load()
154
+ seen: set[tuple[int, int]] = set()
155
+ blobs: list[tuple[float, float, float]] = [] # x, y, radius
156
+ for y in range(h):
157
+ for x in range(w):
158
+ if cpx[x, y] and (x, y) not in seen:
159
+ todo, pix = [(x, y)], []
160
+ seen.add((x, y))
161
+ while todo:
162
+ a, b = todo.pop()
163
+ pix.append((a, b))
164
+ for q in ((a + 1, b), (a - 1, b), (a, b + 1), (a, b - 1)):
165
+ if 0 <= q[0] < w and 0 <= q[1] < h and cpx[q] and q not in seen:
166
+ seen.add(q)
167
+ todo.append(q)
168
+ cx, cy = sum(a for a, _ in pix) / len(pix), sum(b for _, b in pix) / len(pix)
169
+ blobs.append((cx, cy, math.sqrt(len(pix) / math.pi) + erode / 2))
170
+ if len(blobs) < 2:
171
+ raise SystemExit(f"{path}: found {len(blobs)} star(s); try a smaller --erode")
172
+ lines = []
173
+ for i, (ax, ay, ar) in enumerate(blobs):
174
+ for j in range(i + 1, len(blobs)):
175
+ bx, by, br = blobs[j]
176
+ d = math.hypot(bx - ax, by - ay)
177
+ if any(k not in (i, j) and _near_segment(blobs[k], (ax, ay), (bx, by)) for k in range(len(blobs))):
178
+ continue
179
+ steps = max(2, int(d))
180
+ path_px = [(ax + (bx - ax) * s / steps, ay + (by - ay) * s / steps) for s in range(steps + 1)]
181
+ path_px = [q for q in path_px if math.dist(q, (ax, ay)) > ar and math.dist(q, (bx, by)) > br]
182
+ if path_px and sum(1 for q in path_px if on[int(q[0]), int(q[1])]) >= 0.9 * len(path_px):
183
+ lines.append([i, j])
184
+ lengths = sorted(math.dist(blobs[a][:2], blobs[b][:2]) for a, b in lines) or [1.0]
185
+ unit = lengths[len(lengths) // 2]
186
+ stars = [[round(x / unit, 2), round(y / unit, 2)] for x, y, _ in blobs]
187
+ return {"stars": stars, "lines": lines}
188
+
189
+
190
+ def _near_segment(star, a, b) -> bool:
191
+ x, y, r = star
192
+ ax, ay, bx, by = *a, *b
193
+ vx, vy = bx - ax, by - ay
194
+ k = ((x - ax) * vx + (y - ay) * vy) / (vx * vx + vy * vy)
195
+ return 0 < k < 1 and math.hypot(ax + k * vx - x, ay + k * vy - y) < r
196
+
197
+
198
+ def as_toml(fig: dict) -> str:
199
+ stars = ", ".join(f"[{x}, {y}]" for x, y in fig["stars"])
200
+ lines = ", ".join(f"[{a}, {b}]" for a, b in fig["lines"])
201
+ return f"[figure]\nstars = [{stars}]\nlines = [{lines}]\n"