Datasets:
Download scripts/render_frames.py from figma-ai/motion-graphics-bench: direct link, hf CLI and curl.
- Browser
- Download file 6.15 kB
-
https://huggingface.co/datasets/figma-ai/motion-graphics-bench/resolve/main/scripts/render_frames.py
- Command line
-
hf download hf://datasets/figma-ai/motion-graphics-bench/scripts/render_frames.py
-
curl -L -o render_frames.py https://huggingface.co/datasets/figma-ai/motion-graphics-bench/resolve/main/scripts/render_frames.py
6.15 kB
| """Render a supplied GSAP program with MoVer and the benchmark's GSAP runtime.""" | |
| from __future__ import annotations | |
| import asyncio | |
| import json | |
| from importlib.metadata import version | |
| from pathlib import Path | |
| from typing import Any | |
| from mover.converter.mover_converter import capture_frames_server_driven | |
| from mover.converter.render_session import RenderSession | |
| GSAP_VERSION = "3.14.1" | |
| GSAP_ROOT = Path(__file__).resolve().parents[1] / "node_modules" / "gsap" | |
| RUNTIME_FILES = ( | |
| "gsap.min.js", | |
| "MotionPathPlugin.min.js", | |
| "EasePack.min.js", | |
| "MotionPathHelper.min.js", | |
| "DrawSVGPlugin.min.js", | |
| "MorphSVGPlugin.min.js", | |
| "CustomEase.min.js", | |
| "CustomBounce.min.js", | |
| ) | |
| PLUGIN_GLOBALS = ( | |
| "MotionPathPlugin", "SlowMo", "RoughEase", "ExpoScaleEase", | |
| "MotionPathHelper", "DrawSVGPlugin", "MorphSVGPlugin", "CustomEase", "CustomBounce", | |
| ) | |
| def assemble_html(svg: str, program: str) -> str: | |
| if not program.strip() or "</script" in program.lower(): | |
| raise ValueError("the GSAP program must be nonempty and contain no closing </script> tag") | |
| manifest = GSAP_ROOT / "package.json" | |
| installed = json.loads(manifest.read_text(encoding="utf-8"))["version"] | |
| if installed != GSAP_VERSION: | |
| raise RuntimeError(f"GSAP {GSAP_VERSION} is required, found {installed}; run npm ci") | |
| scripts = [] | |
| for name in RUNTIME_FILES: | |
| source = (GSAP_ROOT / "dist" / name).read_text(encoding="utf-8") | |
| if "</script" in source.lower(): | |
| raise ValueError(f"GSAP runtime file cannot be safely inlined: {name}") | |
| scripts.append(f'<script data-gsap-runtime="{name}">\n{source}\n</script>') | |
| return f"""<!doctype html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="utf-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1"> | |
| <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self' 'unsafe-inline'; style-src 'unsafe-inline'; img-src data: blob:; connect-src 'self' http://localhost:* http://127.0.0.1:*; media-src 'none'; object-src 'none'; frame-src 'none'; worker-src 'none'; base-uri 'none'; form-action 'none'"> | |
| <meta name="gsap-runtime-version" content="{GSAP_VERSION}"> | |
| <title>MotionGraphicsBench animation</title> | |
| <style>html,body{{margin:0;padding:0;background:transparent}}</style> | |
| </head> | |
| <body> | |
| {svg} | |
| {"".join(scripts)} | |
| <script> | |
| (() => {{ | |
| const names = {json.dumps(PLUGIN_GLOBALS)}; | |
| const missing = names.filter(name => typeof window[name] === "undefined"); | |
| if (missing.length) throw new Error(`Missing GSAP plugins: ${{missing.join(", ")}}`); | |
| gsap.registerPlugin(...names.map(name => window[name])); | |
| const errors = []; | |
| Object.defineProperty(window, "__benchmark_errors", {{get: () => errors.slice()}}); | |
| window.addEventListener("error", event => errors.push(event.error?.stack || event.message)); | |
| window.addEventListener("unhandledrejection", event => errors.push(String(event.reason))); | |
| const blocked = name => () => {{ throw new Error(`${{name}} is disabled by the benchmark harness`); }}; | |
| const nativeFetch = window.fetch.bind(window); | |
| Object.defineProperty(window, "fetch", {{configurable: false, writable: false, value: (input, init) => {{ | |
| const raw = input && typeof input === "object" && "url" in input ? input.url : String(input); | |
| const url = new URL(raw, window.location.href); | |
| if (!["localhost", "127.0.0.1", "::1"].includes(url.hostname) || | |
| url.protocol !== "http:" || url.port !== window.location.port) {{ | |
| return Promise.reject(new Error("fetch is restricted to the active MoVer loopback port")); | |
| }} | |
| return nativeFetch(input, init); | |
| }}}}); | |
| for (const name of ["XMLHttpRequest", "WebSocket", "EventSource", "Worker", "SharedWorker"]) {{ | |
| Object.defineProperty(window, name, {{configurable: false, writable: false, value: blocked(name)}}); | |
| }} | |
| Object.defineProperty(window, "open", {{configurable: false, writable: false, value: blocked("window.open")}}); | |
| Object.defineProperty(navigator, "sendBeacon", {{configurable: false, writable: false, value: blocked("sendBeacon")}}); | |
| }})(); | |
| </script> | |
| <script id="svg-script"> | |
| {program} | |
| </script> | |
| <script src="./convert.js"></script> | |
| </body> | |
| </html> | |
| """ | |
| async def _capture( | |
| html: Path, output: Path, fps: float, capture_duration: float | None, | |
| ) -> tuple[list[str], dict[str, Any]]: | |
| async with RenderSession(html, output_dir=output, capture_duration=capture_duration) as session: | |
| errors: list[str] = [] | |
| session.page.on("pageerror", lambda error: errors.append(str(error))) | |
| initial_errors = await session.page.evaluate("window.__benchmark_errors") | |
| if initial_errors: | |
| raise RuntimeError("GSAP execution failed:\n" + "\n".join(initial_errors)) | |
| info = await session.get_animation_info(fps) | |
| frames_dir = output / "svg_frames" | |
| await capture_frames_server_driven( | |
| session.page, str(frames_dir), fps=fps, output_format="svg", | |
| capture_duration=capture_duration, | |
| ) | |
| errors.extend(await session.page.evaluate("window.__benchmark_errors")) | |
| if errors: | |
| raise RuntimeError("GSAP execution failed:\n" + "\n".join(errors)) | |
| paths = sorted(frames_dir.glob("frame_*.svg")) | |
| frames = [path.read_text(encoding="utf-8").strip() for path in paths] | |
| browser = session.page.context.browser | |
| assert browser is not None | |
| return frames, { | |
| "mover_version": version("mover"), | |
| "gsap_version": GSAP_VERSION, | |
| "chromium": browser.version, | |
| "fps": fps, | |
| "duration": float(info["animDuration"]), | |
| "frame_count": len(frames), | |
| } | |
| def render_frames( | |
| svg: str, program: str, output: Path, *, fps: float, | |
| capture_duration: float | None = None, timeout: float = 900, | |
| ) -> tuple[list[str], dict[str, Any]]: | |
| html_source = assemble_html(svg, program) | |
| output.mkdir(parents=True, exist_ok=False) | |
| html = output / "animation.html" | |
| html.write_text(html_source, encoding="utf-8") | |
| return asyncio.run(asyncio.wait_for(_capture(html, output, fps, capture_duration), timeout=timeout)) | |