motion-graphics-bench / scripts /extract_input_static_svgs.py
Jiaju Ma
Copilot
Add input static SVG converter and LottieFiles source links
dcfca3a
Raw History Blame Contribute Delete
11.2 kB
"""Rebuild benchmark input static SVGs from trusted local Lottie JSON files."""
from __future__ import annotations
import argparse
import hashlib
import json
import re
from pathlib import Path
from typing import Any
from playwright.sync_api import Error as PlaywrightError
from playwright.sync_api import Page, sync_playwright
LOTTIE_WEB_SHA256 = "2eb762973aec914d981f426123040bfac9d26217239605e225ddc7cee17618ac"
GENERATED_ID = re.compile(r"__lottie_element_[0-9]+")
PATH_TAG = re.compile(r"<path\b[^>]*>", re.S)
PATH_DATA = re.compile(r'(?<![\w-])d\s*=\s*"([^"]*)"', re.S)
GROUP_TAG = re.compile(r"<g\b[^>]*>", re.S)
STYLE = re.compile(r'style\s*=\s*"([^"]*)"', re.S)
HIDDEN = re.compile(r"display\s*:\s*none", re.I)
DISPLAY = re.compile(r'display\s*:\s*[^;"]*;?', re.I)
def layer_lists(animation):
yield animation["layers"]
for asset in animation.get("assets") or []:
if isinstance(asset, dict) and asset.get("layers"):
yield asset["layers"]
def inject_svg_ids(animation: dict[str, Any]) -> None:
seen = set()
def assign(node, parent):
existing = node.get("ln")
if isinstance(existing, str) and existing:
seen.add(existing)
return existing
slug = re.sub(r"[^a-zA-Z0-9_-]+", "-", node["nm"].strip().lower())
slug = re.sub(r"-+", "-", slug).strip("-") or "layer"
if re.match(r"^[0-9]", slug):
slug = f"layer-{slug}"
base = f"{parent}-{slug}" if parent else slug
value, suffix = base, 2
while value in seen:
value = f"{base}-{suffix}"
suffix += 1
seen.add(value)
node["ln"] = value
return value
def visit_shapes(shapes, parent):
for shape in shapes or []:
if not isinstance(shape, dict):
continue
name = shape.get("nm")
group = assign(shape, parent) if shape.get("ty") == "gr" and isinstance(name, str) and name else parent
visit_shapes(shape.get("it"), group)
for layers in layer_lists(animation):
for layer in layers:
if not isinstance(layer, dict):
continue
name = layer.get("nm")
parent = assign(layer, "") if layer.get("ty") != 3 and isinstance(name, str) and name else ""
visit_shapes(layer.get("shapes"), parent)
def render_frame(page: Page, animation: dict[str, Any], index: int, *, recover: bool = False) -> str:
width, height = (int(animation.get(key) or 512) for key in ("w", "h"))
page.set_viewport_size({"width": width, "height": height})
page.evaluate(
"""([data, width, height, hide]) => {
const container = document.getElementById('c');
container.style.width = width + 'px';
container.style.height = height + 'px';
if (window.__a) window.__a.destroy();
window.__a = lottie.loadAnimation({
container, renderer: 'svg', loop: false, autoplay: false,
rendererSettings: {hideOnTransparent: hide}, animationData: JSON.parse(data)
});
return new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error('Lottie DOMLoaded timeout')), 8000);
window.__a.addEventListener('DOMLoaded', () => { clearTimeout(timer); resolve(); });
});
}""",
[json.dumps(animation, separators=(",", ":"), allow_nan=False), width, height, not recover],
)
if index >= page.evaluate("Math.floor(window.__a.totalFrames)"):
raise ValueError("recorded frame index is outside playback")
# Capture frame zero separately to preserve the renderer's original attribute order.
page.evaluate("frame => window.__a.goToAndStop(frame, true)", index if recover else 0)
svg = page.evaluate("document.getElementById('c').innerHTML")
if recover or not index:
return svg
return page.evaluate(
"""last => {
for (let frame = 1; frame <= last; frame++) window.__a.goToAndStop(frame, true);
return document.getElementById('c').innerHTML;
}""",
index,
)
def count_empty_paths(svg: str) -> int:
return sum(
not (match and match[1].strip())
for match in (PATH_DATA.search(tag) for tag in PATH_TAG.findall(svg))
)
def restore_visibility(normal: str, complete: str) -> str:
groups = GROUP_TAG.findall(normal)
if (
len(groups) != len(GROUP_TAG.findall(complete))
or len(PATH_TAG.findall(normal)) != len(PATH_TAG.findall(complete))
or count_empty_paths(complete)
):
raise ValueError("hidden geometry does not match the original frame structure")
hidden = iter(bool(style and HIDDEN.search(style[1])) for style in map(STYLE.search, groups))
def restore(match):
tag = match[0]
if not next(hidden):
return tag
style = STYLE.search(tag)
if not style:
return tag[:2] + ' style="display: none;"' + tag[2:]
if HIDDEN.search(style[1]):
return tag
value, replacements = DISPLAY.subn("display: none;", style[1], count=1)
if not replacements:
value = style[1].rstrip()
if value and not value.endswith(";"):
value += ";"
value = (value + " display: none;").strip()
return tag[:style.start(1)] + value + tag[style.end(1):]
return GROUP_TAG.sub(restore, complete)
def restore_input_static_svg_ids(svg: str, original_generated_ids: list[str], expected_sha256: str) -> bytes:
# Replace the numbered prefix, including in mask IDs with suffixes and their references.
current = dict.fromkeys(GENERATED_ID.findall(svg))
if len(current) != len(original_generated_ids):
raise ValueError(
"Generated ID count does not match the original benchmark input static SVG. No SVGs were written."
)
mapping = dict(zip(current, original_generated_ids, strict=True))
result = GENERATED_ID.sub(lambda match: mapping[match[0]], svg).encode("utf-8")
if hashlib.sha256(result).hexdigest() != expected_sha256:
raise ValueError(
"Rebuilt SVG does not match the original benchmark input static SVG (checksum mismatch). "
"No SVGs were written."
)
return result
def read_input_static_svg_metadata(path: Path) -> list[dict[str, Any]]:
entries = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(entries, list) or not entries or not all(isinstance(row, dict) for row in entries):
raise ValueError("Input static SVG metadata must be a nonempty JSON list of task records.")
seen = set()
for row in entries:
key, index = row.get("animation_id"), row.get("input_static_svg_frame_index")
ids, digest = row.get("original_generated_ids"), row.get("input_static_svg_sha256")
if not isinstance(key, str) or not re.fullmatch(r"[0-9]+", key) or key in seen:
raise ValueError("Metadata animation IDs must be unique numeric strings.")
seen.add(key)
if type(index) is not int or index < 0:
raise ValueError(f"{key}: expected a nonnegative frame index")
if (
not isinstance(ids, list)
or not all(isinstance(value, str) and GENERATED_ID.fullmatch(value) for value in ids)
or len(set(ids)) != len(ids)
):
raise ValueError(f"{key}: invalid original generated ID list")
if not isinstance(digest, str) or not re.fullmatch(r"[a-f0-9]{64}", digest):
raise ValueError(f"{key}: invalid input static SVG SHA-256")
return entries
def extract_input_static_svgs(lottie_dir: Path, metadata: Path, player: Path, output: Path) -> None:
if output.exists(follow_symlinks=False):
raise FileExistsError(f"output directory already exists: {output}")
entries = read_input_static_svg_metadata(metadata)
library = player.read_bytes()
if hashlib.sha256(library).hexdigest() != LOTTIE_WEB_SHA256:
raise ValueError("expected the pinned lottie-web 5.13.0 lottie.min.js")
html = (
"<!doctype html><html><head><script>" + library.decode("utf-8") + "</script>"
"<style>html,body{margin:0}#c{background:#fff}</style>"
"</head><body><div id='c'></div></body></html>"
)
files = {}
recovered = 0
with sync_playwright() as pw:
browser = pw.chromium.launch()
context = browser.new_context(offline=True, service_workers="block")
context.route("**/*", lambda route: route.abort())
page, harvest = context.new_page(), context.new_page()
for tab in (page, harvest):
tab.set_default_timeout(12000)
tab.set_content(html)
for row in entries:
key, index = row["animation_id"], row["input_static_svg_frame_index"]
try:
data = json.loads((lottie_dir / f"{key}.json").read_text(encoding="utf-8-sig"))
if not isinstance(data, dict) or not isinstance(data.get("layers"), list):
raise ValueError("expected a Lottie JSON object with layers")
inject_svg_ids(data)
svg = render_frame(page, data, index)
empty = count_empty_paths(svg)
if empty:
for layers in layer_lists(data):
for layer in layers:
if isinstance(layer, dict):
layer.update(ip=-100000, op=100000)
svg = restore_visibility(svg, render_frame(harvest, data, index, recover=True))
recovered += empty
files[key] = restore_input_static_svg_ids(
svg, row["original_generated_ids"], row["input_static_svg_sha256"]
)
except (OSError, ValueError, PlaywrightError) as error:
raise ValueError(f"{key}: {error}") from None
browser.close()
output.mkdir(parents=True, mode=0o700)
for key, svg in files.items():
(output / f"{key}.svg").write_bytes(svg)
print(f"Rebuilt {len(files)} input static SVGs. All checksums match; recovered {recovered} hidden paths.")
print(f"Wrote {output}")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--lottie-dir", type=Path, required=True, help="Local <animation_id>.json files")
parser.add_argument(
"--metadata", type=Path, default=Path(__file__).with_name("input_static_svg_metadata.json"),
help="Input static SVG metadata (default: bundled input_static_svg_metadata.json)",
)
parser.add_argument("--lottie-web", type=Path, required=True, help="Pinned lottie-web 5.13.0 lottie.min.js")
parser.add_argument("--output-dir", type=Path, required=True, help="New directory for the rebuilt input static SVGs")
args = parser.parse_args()
try:
extract_input_static_svgs(args.lottie_dir, args.metadata, args.lottie_web, args.output_dir)
except (OSError, ValueError, PlaywrightError) as error:
parser.exit(1, f"{error}\n")
if __name__ == "__main__":
main()