"""Measure SVG frames in Chromium and return per-element animation data.""" from __future__ import annotations import json import os import subprocess import sys import tempfile from typing import Any, Dict, List, Optional, Sequence _SELF = os.path.abspath(__file__) _OBSERVER = os.path.join(os.path.dirname(_SELF), "observer.js") # Paint and clipping styles are retained even when constant. STYLE_FLOOR = ( "opacity", "display", "visibility", "fill", "fill-opacity", "stroke", "stroke-width", "stroke-opacity", "stroke-linecap", "stroke-dasharray", "stroke-dashoffset", "clip-path", "mask-image", "mask-mode", "mask-composite", "filter", "marker-start", "marker-mid", "marker-end", ) # Definition geometry and paint remain available even when constant. RESOURCE_STYLE_FLOOR = STYLE_FLOOR + ( "color", "fill-rule", "stroke-linejoin", "stroke-miterlimit", "vector-effect", "clip-rule", "mask-type", "stop-color", "stop-opacity", "flood-color", "flood-opacity", "lighting-color", "color-interpolation", "color-interpolation-filters", "transform", "transform-origin", "transform-box", "d", "x", "y", "cx", "cy", "r", "rx", "ry", "width", "height", ) ALL_STYLES = ("*",) # Style changes between sampled frames may be missed; 0 reads all properties per frame. STYLE_SAMPLE_FRAMES = 10 FACT_COLUMNS = ( "ctm", "own", "bbox", "length", "ends", "contour", "stroke_width", "visible_fraction", "clip_box", "mask_box", "resource_inputs", "tag", "parent", "order", ) COLUMN_DOC = { "ctm": "where the element sits, as six numbers, in the root SVG's own user space", "own": "its own transform alone, without its ancestors' -- `ctm` composes the whole chain", "bbox": "its own extent (x, y, w, h) in its own coordinates", "length": "the outline length of a shape that has one, and `None` for a shape that has none", "ends": "where its outline begins and ends, for telling a draw-on from a move", "contour": "32 samples along its outline, already placed in root space", "stroke_width": "its painted stroke width in root space; exact under uniform scale", "visible_fraction": "the sampled painted fraction kept by supported clips and binary alpha masks", "clip_box": "the box a clip leaves visible, already placed in root space", "mask_box": "the box a mask's content covers, already placed in root space. Its shape, not its paint", "resource_inputs": ( "referenced SVG definition inputs, keyed by URL/href; each has tag, attrs, effective style and children, " "with linked definitions in the same map. Missing/external references are None; no references is {}. " "Read with get_column(matrix, path, 'resource_inputs'); group-owned effects stay on the parent row. " "These are source inputs, not resolved instance geometry or final visible paint; a difference need not change pixels" ), "tag": "what it is: `path`, `g`, `rect`", "parent": "the path of the element that contains it", "order": "where it falls among its siblings in the document", } def _observer_source() -> str: with open(_OBSERVER, encoding="utf-8") as f: return f.read() def _render(page, svg: str) -> None: page.set_content(f"{svg}", wait_until="load") def _observe(page, js: str, styles, baseline, reuse_outline: bool = True, resource_styles=None): """Observe one frame, restoring the style baseline after a cleared browser context.""" opts = { "wantDiff": baseline is not None, "styles": styles, "resourceStyles": resource_styles, "reuseOutline": reuse_outline, } got = page.evaluate(js, opts) if got.get("needsBaseline"): page.evaluate("(b) => { window.__baseline = b; }", baseline) got = page.evaluate(js, {**opts, "wantDiff": True}) assert "error" not in got, got["error"] return got def _spread(total: int, n: int) -> List[int]: """Select evenly spaced frame indices, including endpoints when n permits.""" if n <= 0 or n >= total: return list(range(total)) if n == 1: return [0] return sorted({round(i * (total - 1) / (n - 1)) for i in range(n)}) def _resource_nodes(resources): """Referenced nodes keyed by reference and child position, independently of their drawable owners.""" for reference, node in resources.items(): if node is not None: yield (reference,), node for path, child in _resource_nodes(dict(enumerate(node["children"]))): yield (reference, *path), child def _moving_styles(page, js: str, frames: List[str], sampled: Sequence[int]) -> tuple[set, set]: """Find styles that vary across sampled frames; unsampled changes may be missed.""" moved: set = set() resource_moved: set = set() resource_baseline: dict = {} baseline: Dict[str, Dict[str, str]] | None = None born: Dict[str, Dict[str, str]] = {} for i in sampled: _render(page, frames[i]) got = _observe(page, js, None, baseline) rows = {r["path"]: r for r in got["rows"]} resources = {ref: node for row in rows.values() for ref, node in row["resource_inputs"].items()} for path, node in _resource_nodes(resources): style = node["style"] base = resource_baseline.setdefault(path, style) resource_moved.update(k for k in base.keys() | style.keys() if base.get(k) != style.get(k)) if baseline is None: baseline = {path: r["style"] for path, r in rows.items()} page.evaluate("(b) => { window.__baseline = b; }", baseline) continue for path, row in rows.items(): style = row["style"] if path in baseline: moved.update(style) elif path in born: moved.update(k for k, v in style.items() if born[path].get(k) != v) else: born[path] = style return moved, resource_moved def _measure_in_process( frames: List[str], viewport: int = 1000, fps: float | None = None, style_floor: Sequence[str] = STYLE_FLOOR, frame_indices: Sequence[int] | None = None, style_sample_frames: int = STYLE_SAMPLE_FRAMES, reuse_outline: bool = True, ) -> Dict[str, Any]: """Browser measurement worker; use measure to avoid conflicts with an existing event loop.""" from playwright.sync_api import sync_playwright js = _observer_source() per_frame: List[Dict[str, Any]] = [] canvases: List[Any] = [] with sync_playwright() as p: browser = p.chromium.launch(args=["--disable-dev-shm-usage"]) version = browser.version page = browser.new_page(viewport={"width": viewport, "height": viewport}) styles: Optional[List[str]] = None resource_styles: Optional[List[str]] = None if tuple(style_floor) != ALL_STYLES and style_sample_frames > 0 and len(frames) > 1: sampled = _spread(len(frames), style_sample_frames) moved, resource_moved = _moving_styles(page, js, frames, sampled) styles = sorted(set(style_floor) | moved) resource_styles = sorted(set(RESOURCE_STYLE_FLOOR) | set(style_floor) | resource_moved) page.evaluate("() => { window.__baseline = undefined; }") baseline: Dict[str, Dict[str, str]] | None = None for svg in frames: _render(page, svg) got = _observe(page, js, styles, baseline, reuse_outline, resource_styles) rows = {r["path"]: r for r in got["rows"]} if baseline is None: baseline = {path: r["style"] for path, r in rows.items()} page.evaluate("(b) => { window.__baseline = b; }", baseline) per_frame.append(rows) canvases.append(got["canvas"]) browser.close() return _assemble(per_frame, canvases, version, baseline or {}, fps, style_floor, frame_indices, styles) def measure( frames: List[str], viewport: int = 1000, fps: float | None = None, style_floor: Sequence[str] = STYLE_FLOOR, frame_indices: Optional[Sequence[int]] = None, timeout: float = 900.0, style_sample_frames: int = STYLE_SAMPLE_FRAMES, reuse_outline: bool = True, ) -> Dict[str, Any]: """Measure frames in a child process. Coordinates use root SVG units; fps and frame_indices record caller-supplied timing.""" if not frames: raise ValueError("no frames to measure: an animation matrix needs at least one frame") with tempfile.TemporaryDirectory() as tmp: given, produced = os.path.join(tmp, "given.json"), os.path.join(tmp, "matrix.json") with open(given, "w") as f: json.dump( { "frames": list(frames), "viewport": viewport, "fps": fps, "style_floor": list(style_floor), "frame_indices": list(frame_indices) if frame_indices is not None else None, "style_sample_frames": style_sample_frames, "reuse_outline": reuse_outline, }, f, ) try: proc = subprocess.run( [sys.executable, _SELF, given, produced], capture_output=True, text=True, timeout=timeout, ) except subprocess.TimeoutExpired: raise RuntimeError(f"measuring {len(frames)} frames timed out after {timeout:.0f}s") from None if not os.path.exists(produced): raise RuntimeError(f"measuring failed (exit {proc.returncode}): {(proc.stderr or '')[-1500:]}") with open(produced) as f: return json.load(f) def _assemble( per_frame, canvases, version: str, baseline, fps: float | None = None, style_floor: Sequence[str] = STYLE_FLOOR, frame_indices: Sequence[int] | None = None, styles_measured: Sequence[str] | None = None, ) -> Dict[str, Any]: """Split observations into constant and per-frame columns; absent nodes contribute None.""" n = len(per_frame) if frame_indices is None: frame_indices = list(range(n)) elif len(frame_indices) != n: raise ValueError(f"{len(frame_indices)} frame indices for {n} frames: they name the frames measured") paths: List[str] = [] for rows in per_frame: for path in rows: if path not in paths: paths.append(path) if tuple(style_floor) != ALL_STYLES: resource_seen: dict = {} for rows in per_frame: for row in rows.values(): for resource_path, node in _resource_nodes(row.get("resource_inputs", {})): resource_seen.setdefault(resource_path, []).append(node) kept: dict = {} for nodes in resource_seen.values(): base = nodes[0]["style"] keep = set(RESOURCE_STYLE_FLOOR) | set(style_floor) keep.update( k for node in nodes for k in base.keys() | node["style"].keys() if base.get(k) != node["style"].get(k) ) for node in nodes: kept.setdefault(id(node), (node, set()))[1].update(keep) # Shared definitions must be discovered before their styles are pruned. for node, keep in kept.values(): node["style"] = {k: v for k, v in node["style"].items() if k in keep} objects: Dict[str, Any] = {} for path in paths: seen = [rows.get(path) for rows in per_frame] cells: Dict[str, List[Any]] = {} for key in FACT_COLUMNS: cells[key] = [None if r is None else r.get(key) for r in seen] attr_names = sorted({k for r in seen if r for k in r["attrs"]}) for name in attr_names: cells[f"attr.{name}"] = [None if r is None else r["attrs"].get(name) for r in seen] # Missing style entries reuse the frame-zero baseline. base = baseline.get(path, {}) style_names = set(base) | {k for r in seen if r for k in r["style"]} for name in sorted(style_names): cells[f"style.{name}"] = [None if r is None else r["style"].get(name, base.get(name)) for r in seen] const, series = {}, {} for key, values in cells.items(): present = [v for v in values if v is not None] if present and all(v == present[0] for v in present) and len(present) == n: const[key] = present[0] elif present: series[key] = values else: const[key] = None if tuple(style_floor) != ALL_STYLES: const = {k: v for k, v in const.items() if not k.startswith("style.") or k[len("style.") :] in style_floor} objects[path] = {"const": const, "series": series} canvas_const = all(c == canvases[0] for c in canvases) return { "info": { "frames": n, "fps": fps, # Duration spans the intervals between frames, not the number of samples. "duration": round((n - 1) / fps, 6) if fps else None, "chromium": version, "source_frames": list(frame_indices), "canvas": canvases[0] if canvas_const else None, "canvas_series": None if canvas_const else canvases, "aliased_rows": _aliased_rows(objects), # None means every style property was measured. "styles_measured": list(styles_measured) if styles_measured is not None else None, }, "objects": objects, } def _aliased_rows(objects: Dict[str, Any]) -> List[str]: """Paths with uncertain identity after sibling changes, including affected descendants.""" aliases = set() siblings: Dict[str, List[str]] = {} identifiers = {} anonymous = set() for path, obj in objects.items(): for column in ("tag", "attr.id"): if len({v for v in obj["series"].get(column, []) if v}) > 1: aliases.add(path) tags = obj["series"].get("tag", []) ids = obj["series"].get("attr.id", [obj["const"].get("attr.id")] * max(1, len(tags))) identifiers[path] = {v for v in ids if v} tags = tags or [obj["const"].get("tag")] * len(ids) if any(not identity and tag is not None for identity, tag in zip(ids, tags)): anonymous.add(path) siblings.setdefault(path.rsplit("[", 1)[0], []).append(path) for paths in siblings.values(): if len(paths) < 2 or not any(None in objects[p]["series"].get("tag", []) for p in paths): continue for path in paths: tags = objects[path]["series"].get("tag", []) if tags and sum(t is not None for t in tags) < 2: continue if path in anonymous or any(identifiers[path] & identifiers[p] for p in paths if p != path): aliases.add(path) # ponytail: Equal-count anonymous replacements cannot be identified from these observations; stable IDs are needed for that. return [p for p in objects if p in aliases or any(p.startswith(a + "/") for a in aliases)] if __name__ == "__main__": with open(sys.argv[1]) as f: asked = json.load(f) matrix = _measure_in_process( asked["frames"], viewport=asked["viewport"], fps=asked["fps"], style_floor=asked["style_floor"], frame_indices=asked["frame_indices"], style_sample_frames=asked.get("style_sample_frames", STYLE_SAMPLE_FRAMES), reuse_outline=asked.get("reuse_outline", True), ) with open(sys.argv[2], "w") as f: json.dump(matrix, f)