framesheet 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.
framesheet/render.py ADDED
@@ -0,0 +1,192 @@
1
+ """Playwright/Chromium session with frame-accurate time control.
2
+
3
+ Time is virtual. Three mechanisms are driven to the same target time ``t``:
4
+
5
+ * JavaScript clocks (``Date``, ``performance.now``, ``setTimeout``, ``requestAnimationFrame``)
6
+ run on Playwright's fake clock, installed before navigation and paused. Moving to ``t``
7
+ calls ``page.clock.run_for(delta)``, which fires every due timer and rAF callback in
8
+ order, so canvas/rAF animations advance deterministically.
9
+ * SMIL: every outermost ``<svg>`` gets ``pauseAnimations()`` + ``setCurrentTime(t)``.
10
+ * CSS animations/transitions and Web Animations: ``document.getAnimations()`` are paused
11
+ and ``currentTime`` is set to ``t`` (relative to when the animation first appeared).
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from dataclasses import dataclass, field
17
+ import datetime as dt
18
+ from importlib.resources import files
19
+ import io
20
+ import subprocess
21
+ import sys
22
+ from typing import TYPE_CHECKING, Any, Self
23
+
24
+ from PIL import Image
25
+
26
+
27
+ if TYPE_CHECKING:
28
+ from types import TracebackType
29
+
30
+ from playwright.sync_api import Browser, Page, Playwright
31
+
32
+ from framesheet.models import ColorScheme
33
+ from framesheet.sources import Source
34
+
35
+
36
+ INSTALL_HINT = (
37
+ "Chromium for Playwright is not installed. Run `framesheet install-browser` "
38
+ "(or `uv run playwright install chromium`)."
39
+ )
40
+ _EPOCH = dt.datetime(2025, 1, 1, tzinfo=dt.UTC)
41
+ _RUNTIME_JS = files("framesheet").joinpath("runtime.js").read_text(encoding="utf-8")
42
+ _FIRST_FRAME_MS = 17
43
+ _LAUNCH_ARGS = [
44
+ # Compositor-thread animations race with pause(): keep them on the main thread.
45
+ "--disable-threaded-animation",
46
+ "--hide-scrollbars",
47
+ "--force-color-profile=srgb",
48
+ "--disable-lcd-text",
49
+ ]
50
+
51
+
52
+ class BrowserNotInstalledError(RuntimeError):
53
+ """Raised when Playwright's Chromium is missing."""
54
+
55
+ def __init__(self) -> None:
56
+ super().__init__(INSTALL_HINT)
57
+
58
+
59
+ def install_browser() -> int:
60
+ """Install Playwright's Chromium for the running Python environment."""
61
+ cmd = [sys.executable, "-m", "playwright", "install", "chromium"]
62
+ return subprocess.run(cmd, check=False).returncode
63
+
64
+
65
+ @dataclass
66
+ class Snapshot:
67
+ """Everything captured at one sample time."""
68
+
69
+ t: float
70
+ image: Image.Image
71
+ geometry: list[Any]
72
+ """``[index, clientRect, userRect | None, visible]`` per rendered element."""
73
+ overflow: list[Any] = field(default_factory=list)
74
+ """HTML text overflow: ``[index, dx, dy]``."""
75
+
76
+
77
+ class Session:
78
+ """One browser page showing one input, with a virtual clock starting at ``t=0``."""
79
+
80
+ def __init__(
81
+ self,
82
+ source: Source,
83
+ *,
84
+ size: tuple[int, int],
85
+ scale: float = 1.0,
86
+ color_scheme: ColorScheme = "light",
87
+ timeout: float = 30.0,
88
+ ) -> None:
89
+ self.source = source
90
+ self.size = size
91
+ self.scale = scale
92
+ self.color_scheme = color_scheme
93
+ self.timeout_ms = timeout * 1000
94
+ self.console_errors: list[str] = []
95
+ self.response_text: str | None = None
96
+ self._now_ms = 0
97
+ self._pw: Playwright | None = None
98
+ self._browser: Browser | None = None
99
+ self._page: Page | None = None
100
+
101
+ def __enter__(self) -> Self:
102
+ from playwright.sync_api import Error, sync_playwright
103
+
104
+ self._pw = sync_playwright().start()
105
+ try:
106
+ self._browser = self._pw.chromium.launch(args=_LAUNCH_ARGS)
107
+ except Error as exc:
108
+ self._pw.stop()
109
+ if "Executable doesn't exist" in str(exc) or "playwright install" in str(exc):
110
+ raise BrowserNotInstalledError from None
111
+ raise
112
+ context = self._browser.new_context(
113
+ viewport={"width": self.size[0], "height": self.size[1]},
114
+ device_scale_factor=self.scale,
115
+ color_scheme=self.color_scheme,
116
+ reduced_motion="no-preference",
117
+ locale="en-US",
118
+ timezone_id="UTC",
119
+ )
120
+ page = context.new_page()
121
+ page.set_default_timeout(self.timeout_ms)
122
+ page.on("pageerror", lambda exc: self.console_errors.append(f"pageerror: {exc}"))
123
+ page.on(
124
+ "console",
125
+ lambda msg: (
126
+ self.console_errors.append(f"console.{msg.type}: {msg.text}")
127
+ if msg.type == "error"
128
+ else None
129
+ ),
130
+ )
131
+ page.clock.install(time=_EPOCH)
132
+ page.clock.pause_at(_EPOCH + dt.timedelta(seconds=1))
133
+ self._page = page
134
+ return self
135
+
136
+ def __exit__(
137
+ self,
138
+ exc_type: type[BaseException] | None,
139
+ exc: BaseException | None,
140
+ tb: TracebackType | None,
141
+ ) -> None:
142
+ if self._browser:
143
+ self._browser.close()
144
+ if self._pw:
145
+ self._pw.stop()
146
+
147
+ @property
148
+ def page(self) -> Page:
149
+ assert self._page is not None, "Session not entered"
150
+ return self._page
151
+
152
+ def js(self, expression: str, arg: Any = None) -> Any:
153
+ return self.page.evaluate(expression, arg)
154
+
155
+ def load(self) -> None:
156
+ response = self.page.goto(self.source.url, wait_until="load")
157
+ if response is not None and self.source.text is None:
158
+ try:
159
+ self.response_text = response.text()
160
+ except Exception: # noqa: BLE001
161
+ self.response_text = None
162
+ self.js(_RUNTIME_JS)
163
+ self.js("() => window.__framesheet.ready()")
164
+ # Let one fake animation frame run so rAF-driven content has painted at t=0.
165
+ # (JS clocks are therefore ~17 ms ahead of SMIL/CSS time.)
166
+ self.page.clock.run_for(_FIRST_FRAME_MS)
167
+ self.seek(0.0)
168
+
169
+ def seek(self, t: float) -> None:
170
+ """Move all clocks to virtual time ``t`` (seconds). Time only moves forward."""
171
+ target = round(t * 1000)
172
+ if target < self._now_ms:
173
+ msg = f"Cannot seek backwards ({t}s < {self._now_ms / 1000}s)"
174
+ raise ValueError(msg)
175
+ if target > self._now_ms:
176
+ self.page.clock.run_for(target - self._now_ms)
177
+ self._now_ms = target
178
+ self.js("t => window.__framesheet.seek(t)", t)
179
+ self.js("() => window.__framesheet.settle()")
180
+
181
+ def screenshot(self, t: float) -> Image.Image:
182
+ """Pixels only, at virtual time ``t``."""
183
+ self.seek(t)
184
+ png = self.page.screenshot(type="png", caret="hide", animations="allow", scale="device")
185
+ return Image.open(io.BytesIO(png)).convert("RGB")
186
+
187
+ def snapshot(self, t: float, *, overflow: bool = False) -> Snapshot:
188
+ """Pixels plus element geometry at virtual time ``t``."""
189
+ image = self.screenshot(t)
190
+ geometry = self.js("() => window.__framesheet.measure()")
191
+ over = self.js("() => window.__framesheet.htmlOverflow()") if overflow else []
192
+ return Snapshot(t=t, image=image, geometry=geometry, overflow=over)
framesheet/runtime.js ADDED
@@ -0,0 +1,323 @@
1
+ // framesheet in-page runtime. Evaluated once after load; exposes window.__framesheet.
2
+ // Everything returns plain JSON so the Python side stays simple.
3
+ (() => {
4
+ if (window.__framesheet) return;
5
+
6
+ const SMIL_SELECTOR = "animate, animateTransform, animateMotion, set, animateColor";
7
+ const NON_RENDERED = new Set([
8
+ "defs", "clippath", "mask", "symbol", "marker", "pattern", "lineargradient",
9
+ "radialgradient", "filter", "style", "script", "title", "desc", "metadata",
10
+ "head", "meta", "link", "template", "noscript", "animate", "animatetransform",
11
+ "animatemotion", "set", "animatecolor", "mpath", "stop",
12
+ "fegaussianblur", "feoffset", "feblend", "fecolormatrix", "femerge", "femergenode",
13
+ "feflood", "fecomposite", "fedropshadow",
14
+ ]);
15
+ const MAX_ELEMENTS = 4000;
16
+ const births = new WeakMap();
17
+ const labels = new WeakMap();
18
+
19
+ let nth = null;
20
+ function countTags() {
21
+ nth = new WeakMap();
22
+ const counts = new Map();
23
+ for (const el of document.querySelectorAll("*")) {
24
+ const tag = el.tagName.toLowerCase();
25
+ const n = (counts.get(tag) || 0) + 1;
26
+ counts.set(tag, n);
27
+ nth.set(el, n);
28
+ }
29
+ }
30
+
31
+ const isSvgDoc = document.documentElement instanceof SVGSVGElement;
32
+
33
+ function outerSvgRoots() {
34
+ return [...document.querySelectorAll("svg")].filter((s) => !s.ownerSVGElement);
35
+ }
36
+
37
+ function label(el) {
38
+ if (!el || !el.tagName) return null;
39
+ if (labels.has(el)) return labels.get(el);
40
+ const tag = el.tagName.toLowerCase();
41
+ let text;
42
+ if (el.id) {
43
+ text = `${tag}#${el.id}`;
44
+ } else {
45
+ if (!nth) countTags();
46
+ const idx = nth.get(el) || 1;
47
+ const cls = el.classList && el.classList.length ? `.${el.classList[0]}` : "";
48
+ text = `${tag}${cls}[${idx}]`;
49
+ }
50
+ if (tag === "text" || (!(el instanceof SVGElement) && el.children.length === 0)) {
51
+ const content = (el.textContent || "").trim().replace(/\s+/g, " ");
52
+ if (content) text += ` "${content.length > 24 ? content.slice(0, 23) + "…" : content}"`;
53
+ }
54
+ labels.set(el, text);
55
+ return text;
56
+ }
57
+
58
+ function clockSeconds(value) {
59
+ // SMIL clock values: "2s", "500ms", "1.5", "0:01.5", "1min", "1h".
60
+ if (value == null) return null;
61
+ const v = String(value).trim();
62
+ let m;
63
+ if ((m = v.match(/^(-?[\d.]+)(ms|s|min|h)?$/))) {
64
+ const n = parseFloat(m[1]);
65
+ return { ms: n / 1000, s: n, min: n * 60, h: n * 3600, undefined: n }[m[2]];
66
+ }
67
+ if ((m = v.match(/^(?:(\d+):)?(\d+):([\d.]+)$/))) {
68
+ return (parseInt(m[1] || "0", 10) * 3600) + parseInt(m[2], 10) * 60 + parseFloat(m[3]);
69
+ }
70
+ return null;
71
+ }
72
+
73
+ function smilTiming(el) {
74
+ let start = 0;
75
+ try { start = el.getStartTime(); } catch (e) {
76
+ const first = (el.getAttribute("begin") || "0").split(";")[0];
77
+ const parsed = clockSeconds(first);
78
+ if (parsed == null) return null; // event-based begin: not time-driven
79
+ start = parsed;
80
+ }
81
+ let duration;
82
+ try { duration = el.getSimpleDuration(); } catch (e) { duration = clockSeconds(el.getAttribute("dur")); }
83
+ if (duration == null || !isFinite(duration) || duration <= 0) return null;
84
+ const rc = el.getAttribute("repeatCount");
85
+ const rd = el.getAttribute("repeatDur");
86
+ let iterations = 1;
87
+ if (rc === "indefinite" || rd === "indefinite") iterations = null;
88
+ else if (rc != null && !isNaN(parseFloat(rc))) iterations = parseFloat(rc);
89
+ else if (rd != null && clockSeconds(rd) != null) iterations = clockSeconds(rd) / duration;
90
+ const target = el.targetElement || el.parentElement;
91
+ return {
92
+ kind: "smil",
93
+ target: label(target),
94
+ name: el.tagName + (el.getAttribute("attributeName") ? `:${el.getAttribute("attributeName")}` : ""),
95
+ start, duration, iterations, direction: "normal", period: duration,
96
+ end: iterations == null ? null : start + duration * iterations,
97
+ };
98
+ }
99
+
100
+ function animationKind(a) {
101
+ if (typeof CSSAnimation !== "undefined" && a instanceof CSSAnimation) return "css-animation";
102
+ if (typeof CSSTransition !== "undefined" && a instanceof CSSTransition) return "css-transition";
103
+ return "web-animation";
104
+ }
105
+
106
+ const TRANSFORM_PROPS = ["transform", "rotate", "scale", "translate"];
107
+
108
+ function waapiTiming(a) {
109
+ const effect = a.effect;
110
+ if (!effect || !effect.getComputedTiming) return null;
111
+ const t = effect.getComputedTiming();
112
+ const duration = (typeof t.duration === "number" ? t.duration : 0) / 1000;
113
+ if (!(duration > 0)) return null;
114
+ const iterations = t.iterations === Infinity ? null : t.iterations;
115
+ const alternate = String(t.direction || "normal").startsWith("alternate");
116
+ const start = (t.delay || 0) / 1000;
117
+ const target = effect.target || null;
118
+ let transformBox = null;
119
+ if (target instanceof SVGElement && !(target instanceof SVGSVGElement)) {
120
+ let frames = [];
121
+ try { frames = effect.getKeyframes(); } catch (e) { frames = []; }
122
+ const animatesTransform = frames.some((f) => TRANSFORM_PROPS.some((p) => p in f));
123
+ if (animatesTransform) transformBox = getComputedStyle(target).transformBox || "view-box";
124
+ }
125
+ return {
126
+ kind: animationKind(a),
127
+ target: label(target),
128
+ name: a.animationName || a.transitionProperty || a.id || null,
129
+ start, duration, iterations,
130
+ direction: t.direction || "normal",
131
+ period: alternate ? duration * 2 : duration,
132
+ end: iterations == null ? null : start + duration * iterations + (t.endDelay || 0) / 1000,
133
+ transform_box: transformBox,
134
+ };
135
+ }
136
+
137
+ function timings() {
138
+ const out = [];
139
+ for (const el of document.querySelectorAll(SMIL_SELECTOR)) {
140
+ if (!(el instanceof SVGElement)) continue;
141
+ const t = smilTiming(el);
142
+ if (t) out.push(t);
143
+ }
144
+ for (const a of document.getAnimations()) {
145
+ const t = waapiTiming(a);
146
+ if (t) out.push(t);
147
+ }
148
+ return out;
149
+ }
150
+
151
+ function seek(t) {
152
+ for (const svg of outerSvgRoots()) {
153
+ if (svg.pauseAnimations) {
154
+ svg.pauseAnimations();
155
+ svg.setCurrentTime(t);
156
+ }
157
+ }
158
+ for (const a of document.getAnimations()) {
159
+ // Animations created later by script (class toggles, el.animate()) start at the
160
+ // virtual time they were first seen, so their local time stays consistent.
161
+ if (!births.has(a)) births.set(a, t);
162
+ a.pause();
163
+ a.currentTime = Math.max(0, t - births.get(a)) * 1000;
164
+ }
165
+ // Force style + layout so geometry queries and the next paint see the new state.
166
+ void document.documentElement.getBoundingClientRect();
167
+ return true;
168
+ }
169
+
170
+ function canvasRect() {
171
+ if (isSvgDoc) {
172
+ const root = document.documentElement;
173
+ const vb = root.viewBox && root.viewBox.baseVal;
174
+ const ctm = root.getScreenCTM();
175
+ if (vb && vb.width > 0 && vb.height > 0 && ctm) {
176
+ const p0 = new DOMPoint(vb.x, vb.y).matrixTransform(ctm);
177
+ const p1 = new DOMPoint(vb.x + vb.width, vb.y + vb.height).matrixTransform(ctm);
178
+ return [p0.x, p0.y, p1.x - p0.x, p1.y - p0.y];
179
+ }
180
+ const r = root.getBoundingClientRect();
181
+ return [r.x, r.y, r.width, r.height];
182
+ }
183
+ return [0, 0, window.innerWidth, window.innerHeight];
184
+ }
185
+
186
+ function viewBox() {
187
+ if (!isSvgDoc) return null;
188
+ const vb = document.documentElement.viewBox && document.documentElement.viewBox.baseVal;
189
+ if (vb && vb.width > 0 && vb.height > 0) return [vb.x, vb.y, vb.width, vb.height];
190
+ const r = document.documentElement.getBoundingClientRect();
191
+ return [0, 0, r.width, r.height];
192
+ }
193
+
194
+ function nonRendered(el) {
195
+ for (let n = el; n && n !== document.documentElement; n = n.parentElement) {
196
+ if (NON_RENDERED.has(n.tagName.toLowerCase())) return true;
197
+ }
198
+ return false;
199
+ }
200
+
201
+ function effectiveOpacity(el, cache) {
202
+ if (!el || el === document) return 1;
203
+ if (cache.has(el)) return cache.get(el);
204
+ const cs = getComputedStyle(el);
205
+ let op = parseFloat(cs.opacity);
206
+ if (isNaN(op)) op = 1;
207
+ const val = op * (el.parentElement ? effectiveOpacity(el.parentElement, cache) : 1);
208
+ cache.set(el, val);
209
+ return val;
210
+ }
211
+
212
+ function toUser(el, r) {
213
+ let root = el.ownerSVGElement;
214
+ if (!root) return null;
215
+ while (root.ownerSVGElement) root = root.ownerSVGElement;
216
+ const ctm = root.getScreenCTM();
217
+ if (!ctm) return null;
218
+ const inv = ctm.inverse();
219
+ const a = new DOMPoint(r.x, r.y).matrixTransform(inv);
220
+ const b = new DOMPoint(r.x + r.width, r.y + r.height).matrixTransform(inv);
221
+ return [Math.min(a.x, b.x), Math.min(a.y, b.y), Math.abs(b.x - a.x), Math.abs(b.y - a.y)];
222
+ }
223
+
224
+ function round(v) { return Math.round(v * 100) / 100; }
225
+
226
+ let elementList = null;
227
+ let indexOf = null;
228
+
229
+ function elements() {
230
+ if (!elementList) {
231
+ elementList = [];
232
+ for (const el of document.querySelectorAll("*")) {
233
+ if (elementList.length >= MAX_ELEMENTS) break;
234
+ const tag = el.tagName.toLowerCase();
235
+ if (tag === "html" || tag === "body" || el === document.documentElement) continue;
236
+ if (nonRendered(el)) continue;
237
+ elementList.push(el);
238
+ }
239
+ indexOf = new Map(elementList.map((el, i) => [el, i]));
240
+ }
241
+ return elementList;
242
+ }
243
+
244
+ function animatedTargets() {
245
+ const out = {};
246
+ const add = (el, kind) => {
247
+ const i = el && indexOf.get(el);
248
+ if (i == null) return;
249
+ (out[i] = out[i] || []).includes(kind) || out[i].push(kind);
250
+ };
251
+ elements();
252
+ for (const el of document.querySelectorAll(SMIL_SELECTOR)) add(el.targetElement || el.parentElement, "smil");
253
+ for (const a of document.getAnimations()) if (a.effect && a.effect.target) add(a.effect.target, animationKind(a));
254
+ return out;
255
+ }
256
+
257
+ // One geometry snapshot: [index, clientRect, userRect, visible] for every rendered element.
258
+ function measure() {
259
+ const cache = new WeakMap();
260
+ const out = [];
261
+ for (const [i, el] of elements().entries()) {
262
+ if (!el.isConnected) continue;
263
+ const r = el.getBoundingClientRect();
264
+ if (!(r.width > 0 || r.height > 0)) continue;
265
+ const cs = getComputedStyle(el);
266
+ const visible = cs.visibility !== "hidden" && cs.display !== "none" && effectiveOpacity(el, cache) > 0.01;
267
+ const user = el instanceof SVGElement ? toUser(el, r) : null;
268
+ out.push([i, [r.x, r.y, r.width, r.height].map(round), user && user.map(round), visible]);
269
+ }
270
+ return out;
271
+ }
272
+
273
+ function describe() {
274
+ const els = elements();
275
+ return els.map((el, i) => {
276
+ const tag = el.tagName.toLowerCase();
277
+ let parent = -1;
278
+ for (let p = el.parentElement; p; p = p.parentElement) {
279
+ const j = indexOf.get(p);
280
+ if (j != null) { parent = j; break; }
281
+ }
282
+ return { i, tag, label: label(el), svg: el instanceof SVGElement, parent };
283
+ });
284
+ }
285
+
286
+ // HTML text overflow: elements with their own text whose content is larger than the box.
287
+ function htmlOverflow() {
288
+ const out = [];
289
+ for (const [i, el] of elements().entries()) {
290
+ if (el instanceof SVGElement) continue;
291
+ const ownText = [...el.childNodes].some((n) => n.nodeType === 3 && n.textContent.trim());
292
+ if (!ownText || el.clientWidth === 0) continue;
293
+ const dx = el.scrollWidth - el.clientWidth;
294
+ const dy = el.scrollHeight - el.clientHeight;
295
+ if (dx > 1 || dy > 1) out.push([i, dx, dy]);
296
+ }
297
+ return out;
298
+ }
299
+
300
+ // Wait for real (compositor) frames. requestAnimationFrame and timers are faked by the
301
+ // Playwright clock, but Web Animations still tick on the real document timeline.
302
+ async function settle(count = 2) {
303
+ for (let i = 0; i < count; i++) {
304
+ const a = document.documentElement.animate([{}, {}], { duration: 1 });
305
+ try { await a.finished; } catch (e) { /* cancelled */ }
306
+ a.cancel();
307
+ }
308
+ return true;
309
+ }
310
+
311
+ async function ready() {
312
+ if (document.fonts && document.fonts.ready) await document.fonts.ready;
313
+ const imgs = [...document.images].filter((img) => !img.complete);
314
+ await Promise.all(imgs.map((img) => new Promise((res) => { img.onload = img.onerror = res; })));
315
+ return true;
316
+ }
317
+
318
+ window.__framesheet = {
319
+ isSvgDoc, timings, seek, settle, measure, describe, animatedTargets, canvasRect, viewBox, htmlOverflow, ready,
320
+ hasScript: () => document.querySelectorAll("script").length > 0,
321
+ canvasCount: () => document.querySelectorAll("canvas").length,
322
+ };
323
+ })();
framesheet/sources.py ADDED
@@ -0,0 +1,135 @@
1
+ """Input handling: files, stdin snippets and URLs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+ import re
8
+ import sys
9
+ from typing import TYPE_CHECKING
10
+ import urllib.request
11
+ import xml.etree.ElementTree as ET
12
+
13
+
14
+ if TYPE_CHECKING:
15
+ from framesheet.models import SourceKind
16
+
17
+
18
+ DEFAULT_HTML_SIZE = (1280, 720)
19
+ DEFAULT_SVG_SIZE = (960, 540)
20
+ _LENGTH = re.compile(r"^\s*([0-9]*\.?[0-9]+)\s*(px)?\s*$")
21
+
22
+
23
+ @dataclass
24
+ class Source:
25
+ """A resolved input."""
26
+
27
+ label: str
28
+ """What the user passed (path, ``-`` or URL)."""
29
+ kind: SourceKind
30
+ url: str
31
+ """What the browser navigates to."""
32
+ text: str | None
33
+ """Source text if available locally (used for static checks and size detection)."""
34
+
35
+
36
+ def looks_like_svg(text: str) -> bool:
37
+ head = re.sub(r"<!--.*?-->", "", text[:4096], flags=re.S).lstrip().lower()
38
+ if head.startswith("<?xml"):
39
+ head = head.split("?>", 1)[-1].lstrip()
40
+ if head.startswith("<!doctype svg"):
41
+ return True
42
+ return head.startswith("<svg")
43
+
44
+
45
+ def resolve(source: str | Path, workdir: Path) -> Source:
46
+ """Turn a path, ``-`` (stdin) or URL into a :class:`Source`.
47
+
48
+ Stdin snippets are written to ``workdir`` so they load as real documents.
49
+ """
50
+ if isinstance(source, str) and source == "-":
51
+ text = sys.stdin.read()
52
+ return snippet(text, workdir, label="-")
53
+ if isinstance(source, str) and re.match(r"^https?://", source):
54
+ text = fetch_text(source)
55
+ by_name = source.split("?")[0].lower().endswith(".svg")
56
+ is_svg = by_name or bool(text and looks_like_svg(text))
57
+ kind: SourceKind = "svg" if is_svg else "html"
58
+ return Source(label=source, kind=kind, url=source, text=text)
59
+ path = Path(source).expanduser().resolve()
60
+ if not path.is_file():
61
+ msg = f"Input not found: {source}"
62
+ raise FileNotFoundError(msg)
63
+ text = path.read_text(encoding="utf-8", errors="replace")
64
+ if path.suffix.lower() == ".svg":
65
+ kind = "svg"
66
+ elif path.suffix.lower() in {".html", ".htm", ".xhtml"}:
67
+ kind = "html"
68
+ else:
69
+ kind = "svg" if looks_like_svg(text) else "html"
70
+ return Source(label=str(source), kind=kind, url=path.as_uri(), text=text)
71
+
72
+
73
+ def fetch_text(url: str, timeout: float = 15.0) -> str | None:
74
+ """Best-effort download of a URL's body (for static checks and SVG size detection)."""
75
+ request = urllib.request.Request(url, headers={"User-Agent": "framesheet"})
76
+ try:
77
+ with urllib.request.urlopen(request, timeout=timeout) as response:
78
+ return response.read().decode("utf-8", errors="replace")
79
+ except (OSError, ValueError):
80
+ return None
81
+
82
+
83
+ def snippet(text: str, workdir: Path, *, label: str = "<snippet>") -> Source:
84
+ """Wrap an in-memory SVG/HTML snippet as a source (written to ``workdir``)."""
85
+ kind: SourceKind = "svg" if looks_like_svg(text) else "html"
86
+ if kind == "html" and "<html" not in text.lower():
87
+ text = (
88
+ f"<!DOCTYPE html>\n<html><head><meta charset='utf-8'></head><body>{text}</body></html>"
89
+ )
90
+ workdir.mkdir(parents=True, exist_ok=True)
91
+ path = workdir / f"input.{kind}"
92
+ path.write_text(text, encoding="utf-8")
93
+ return Source(label=label, kind=kind, url=path.as_uri(), text=text)
94
+
95
+
96
+ def _length(value: str | None) -> float | None:
97
+ if value is None:
98
+ return None
99
+ match = _LENGTH.match(value)
100
+ return float(match.group(1)) if match else None
101
+
102
+
103
+ def svg_size(text: str) -> tuple[int, int] | None:
104
+ """Intrinsic size of an SVG: absolute width/height attributes, else the viewBox."""
105
+ try:
106
+ root = ET.fromstring(text)
107
+ except ET.ParseError:
108
+ return None
109
+ width, height = _length(root.get("width")), _length(root.get("height"))
110
+ box = [float(v) for v in re.split(r"[\s,]+", root.get("viewBox", "").strip()) if v]
111
+ if len(box) == 4 and box[2] > 0 and box[3] > 0: # noqa: PLR2004
112
+ vb_w, vb_h = box[2], box[3]
113
+ if width and not height:
114
+ height = width * vb_h / vb_w
115
+ elif height and not width:
116
+ width = height * vb_w / vb_h
117
+ width, height = width or vb_w, height or vb_h
118
+ if width and height:
119
+ return max(1, round(width)), max(1, round(height))
120
+ return None
121
+
122
+
123
+ def default_size(src: Source) -> tuple[int, int]:
124
+ if src.kind == "svg" and src.text and (size := svg_size(src.text)):
125
+ return size
126
+ return DEFAULT_SVG_SIZE if src.kind == "svg" else DEFAULT_HTML_SIZE
127
+
128
+
129
+ def parse_size(value: str) -> tuple[int, int]:
130
+ """Parse ``WxH`` (e.g. ``1280x720``)."""
131
+ match = re.fullmatch(r"\s*(\d+)\s*[xX*]\s*(\d+)\s*", value)
132
+ if not match:
133
+ msg = f"Invalid size {value!r}; expected WIDTHxHEIGHT, e.g. 1280x720"
134
+ raise ValueError(msg)
135
+ return int(match.group(1)), int(match.group(2))