Skip to content

framesheet

Class info

Re-exported classes

Class Module Description
AnimationTiming framesheet.models Timing of one declarative animation, as reported by the browser.
BrowserNotInstalledError framesheet.render Raised when Playwright's Chromium is missing.
DurationInfo framesheet.models The sampled time span and how it was chosen.
ElementTrack framesheet.models Geometry of one animated element over all frames.
Finding framesheet.models A single problem (or noteworthy fact) found by a static or render check.
FrameMetrics framesheet.models Per-frame numbers.
Images framesheet.models
InspectionResult framesheet.models Everything framesheet found out about one input.
LoopInfo framesheet.models How cleanly the last frame of a cycle joins the first.

🛈 DocStrings

framesheet: main package.

Frame-accurate contact sheets and motion maps for animated SVG and HTML, for humans and AI agents.

AnimationTiming

Bases: BaseModel

Timing of one declarative animation, as reported by the browser.

Source code in src/framesheet/models.py
class AnimationTiming(BaseModel):
    """Timing of one declarative animation, as reported by the browser."""

    kind: Literal["smil", "css-animation", "css-transition", "web-animation"]
    target: str | None = None
    name: str | None = None
    start: float
    """Begin / delay in seconds (may be negative)."""
    duration: float
    """Duration of one iteration in seconds."""
    iterations: float | None
    """Iteration count; ``None`` means infinite."""
    direction: str = "normal"
    period: float
    """Seconds until the animation looks the same again (2x duration for alternate)."""
    end: float | None
    """End of the active interval in seconds; ``None`` if infinite."""
    transform_box: str | None = None
    """Computed ``transform-box`` of an SVG target whose transform is animated by CSS."""

duration instance-attribute

duration: float

Duration of one iteration in seconds.

end instance-attribute

end: float | None

End of the active interval in seconds; None if infinite.

iterations instance-attribute

iterations: float | None

Iteration count; None means infinite.

period instance-attribute

period: float

Seconds until the animation looks the same again (2x duration for alternate).

start instance-attribute

start: float

Begin / delay in seconds (may be negative).

transform_box class-attribute instance-attribute

transform_box: str | None = None

Computed transform-box of an SVG target whose transform is animated by CSS.

BrowserNotInstalledError

Bases: RuntimeError

Raised when Playwright's Chromium is missing.

Source code in src/framesheet/render.py
class BrowserNotInstalledError(RuntimeError):
    """Raised when Playwright's Chromium is missing."""

    def __init__(self) -> None:
        super().__init__(INSTALL_HINT)

DurationInfo

Bases: BaseModel

The sampled time span and how it was chosen.

Source code in src/framesheet/models.py
class DurationInfo(BaseModel):
    """The sampled time span and how it was chosen."""

    seconds: float
    method: Literal["override", "detected", "fallback", "media"]
    looping: bool
    """True if at least one animation repeats forever (or motion is JS-driven)."""
    detail: str
    animations: list[AnimationTiming] = Field(default_factory=list)

looping instance-attribute

looping: bool

True if at least one animation repeats forever (or motion is JS-driven).

ElementTrack

Bases: BaseModel

Geometry of one animated element over all frames.

Source code in src/framesheet/models.py
class ElementTrack(BaseModel):
    """Geometry of one animated element over all frames."""

    element: str
    animated_by: list[str]
    """``smil``, ``css-animation``, ``web-animation`` and/or ``moved`` (geometry changed)."""
    units: Literal["viewBox", "px"]
    boxes: list[Rect | None]
    """One box per frame (``None`` if not rendered at that frame)."""

animated_by instance-attribute

animated_by: list[str]

smil, css-animation, web-animation and/or moved (geometry changed).

boxes instance-attribute

boxes: list[Rect | None]

One box per frame (None if not rendered at that frame).

Finding

Bases: BaseModel

A single problem (or noteworthy fact) found by a static or render check.

Source code in src/framesheet/models.py
class Finding(BaseModel):
    """A single problem (or noteworthy fact) found by a static or render check."""

    severity: Severity
    code: str
    """Stable, kebab-case identifier, e.g. ``parked-at-origin``."""
    message: str
    check: Literal["static", "render"]
    element: str | None = None
    """Human-readable element label such as ``circle#dot`` or ``text[2] "Hello"``."""
    times: list[float] | None = None
    """Sample times (seconds) at which the problem was observed."""

code instance-attribute

code: str

Stable, kebab-case identifier, e.g. parked-at-origin.

element class-attribute instance-attribute

element: str | None = None

Human-readable element label such as circle#dot or text[2] "Hello".

times class-attribute instance-attribute

times: list[float] | None = None

Sample times (seconds) at which the problem was observed.

FrameMetrics

Bases: BaseModel

Per-frame numbers.

Source code in src/framesheet/models.py
class FrameMetrics(BaseModel):
    """Per-frame numbers."""

    index: int
    t: float
    changed_ratio: float
    """Share of pixels that differ from the previous frame (0 for the first frame)."""
    changed_box: Rect | None = None
    """Bounding box (CSS px) of the pixels that changed vs. the previous frame."""
    path: Path | None = None
    """Path of the individual frame PNG, if frames were kept."""

changed_box class-attribute instance-attribute

changed_box: Rect | None = None

Bounding box (CSS px) of the pixels that changed vs. the previous frame.

changed_ratio instance-attribute

changed_ratio: float

Share of pixels that differ from the previous frame (0 for the first frame).

path class-attribute instance-attribute

path: Path | None = None

Path of the individual frame PNG, if frames were kept.

InspectionResult

Bases: BaseModel

Everything framesheet found out about one input.

Source code in src/framesheet/models.py
class InspectionResult(BaseModel):
    """Everything framesheet found out about one input."""

    source: str
    kind: SourceKind
    viewport: tuple[int, int]
    device_scale_factor: float
    canvas: Rect
    """Drawing area in CSS px (the viewBox for SVG documents, the viewport for HTML)."""
    duration: DurationInfo
    times: list[float]
    """Sample times of the contact-sheet tiles in seconds."""
    full_at: float
    images: Images
    findings: list[Finding]
    frames: list[FrameMetrics]
    elements: list[ElementTrack]
    loop: LoopInfo
    console_errors: list[str] = Field(default_factory=list)
    video: VideoInfo | None = None
    """Media facts and per-tile metrics (video inputs only)."""
    marks: Marks | None = None
    """The marks drawn onto the sheet (``--marks``), as given."""

    @property
    def errors(self) -> list[Finding]:
        return [f for f in self.findings if f.severity == "error"]

    @property
    def warnings(self) -> list[Finding]:
        return [f for f in self.findings if f.severity == "warning"]

    def codes(self) -> set[str]:
        """All finding codes, handy for assertions."""
        return {f.code for f in self.findings}

    def summary(self) -> str:
        """Concise multi-line text for humans and agents (what the CLI prints)."""
        w, h = self.viewport
        d = self.duration
        lines = [
            f"framesheet: {self.source} ({self.kind}, {w}x{h} @{self.device_scale_factor:g}x)",
            f"duration: {d.seconds:g}s {d.method}: {d.detail}"
            + (" [looping]" if d.looping else ""),
        ]
        if v := self.video:
            facts = f"{v.container} {v.codec or '?'} {v.width}x{v.height}"
            if v.fps:
                facts += f" {v.fps:g}fps"
            if v.frame_count:
                facts += f", {v.frame_count} frames"
            lines.append(f"video: {facts}; range {v.start:g}-{v.end:g}s, {len(v.samples)} samples")
        busiest = max(self.frames, key=lambda f: f.changed_ratio)
        motion = (
            f"max change {busiest.changed_ratio:.1%} at t={busiest.t:.2f}s"
            if busiest.changed_ratio
            else "no pixel changes"
        )
        lines.append(
            f"frames: {len(self.times)} at t={self.times[0]:.2f}..{self.times[-1]:.2f}s; {motion}"
        )
        if self.loop.checked:
            verdict = "seamless" if self.loop.seamless else "NOT seamless"
            lines.append(f"loop: {verdict} ({self.loop.detail})")
        else:
            lines.append(f"loop: not checked ({self.loop.detail})")
        moving = [e.element for e in self.elements][:8]
        if moving:
            more = f" (+{len(self.elements) - 8} more)" if len(self.elements) > 8 else ""  # noqa: PLR2004
            lines.append(f"animated elements: {', '.join(moving)}{more}")
        counts = {
            s: sum(f.severity == s for f in self.findings) for s in ("error", "warning", "info")
        }
        lines.append(
            f"findings: {counts['error']} error(s), {counts['warning']} warning(s), "
            f"{counts['info']} info"
        )
        tags = {"error": "ERROR", "warning": "WARN ", "info": "INFO "}
        lines.extend(
            f"  {tags[f.severity]} [{f.check}] {f.code}: {f.message}" for f in self.findings
        )
        lines += [
            "images:",
            f"  full     {self.images.full}  (t={self.full_at:g}s: layout, text, margins)",
            f"  sheet    {self.images.sheet}  "
            + ("(tiles over the range + timeline)" if self.video else "(motion over one cycle)"),
            f"  heatmap  {self.images.heatmap}  (what moves at all)",
            f"  report   {self.images.report}",
        ]
        return "\n".join(lines)

canvas instance-attribute

canvas: Rect

Drawing area in CSS px (the viewBox for SVG documents, the viewport for HTML).

marks class-attribute instance-attribute

marks: Marks | None = None

The marks drawn onto the sheet (--marks), as given.

times instance-attribute

times: list[float]

Sample times of the contact-sheet tiles in seconds.

video class-attribute instance-attribute

video: VideoInfo | None = None

Media facts and per-tile metrics (video inputs only).

codes

codes() -> set[str]

All finding codes, handy for assertions.

Source code in src/framesheet/models.py
def codes(self) -> set[str]:
    """All finding codes, handy for assertions."""
    return {f.code for f in self.findings}

summary

summary() -> str

Concise multi-line text for humans and agents (what the CLI prints).

Source code in src/framesheet/models.py
def summary(self) -> str:
    """Concise multi-line text for humans and agents (what the CLI prints)."""
    w, h = self.viewport
    d = self.duration
    lines = [
        f"framesheet: {self.source} ({self.kind}, {w}x{h} @{self.device_scale_factor:g}x)",
        f"duration: {d.seconds:g}s {d.method}: {d.detail}"
        + (" [looping]" if d.looping else ""),
    ]
    if v := self.video:
        facts = f"{v.container} {v.codec or '?'} {v.width}x{v.height}"
        if v.fps:
            facts += f" {v.fps:g}fps"
        if v.frame_count:
            facts += f", {v.frame_count} frames"
        lines.append(f"video: {facts}; range {v.start:g}-{v.end:g}s, {len(v.samples)} samples")
    busiest = max(self.frames, key=lambda f: f.changed_ratio)
    motion = (
        f"max change {busiest.changed_ratio:.1%} at t={busiest.t:.2f}s"
        if busiest.changed_ratio
        else "no pixel changes"
    )
    lines.append(
        f"frames: {len(self.times)} at t={self.times[0]:.2f}..{self.times[-1]:.2f}s; {motion}"
    )
    if self.loop.checked:
        verdict = "seamless" if self.loop.seamless else "NOT seamless"
        lines.append(f"loop: {verdict} ({self.loop.detail})")
    else:
        lines.append(f"loop: not checked ({self.loop.detail})")
    moving = [e.element for e in self.elements][:8]
    if moving:
        more = f" (+{len(self.elements) - 8} more)" if len(self.elements) > 8 else ""  # noqa: PLR2004
        lines.append(f"animated elements: {', '.join(moving)}{more}")
    counts = {
        s: sum(f.severity == s for f in self.findings) for s in ("error", "warning", "info")
    }
    lines.append(
        f"findings: {counts['error']} error(s), {counts['warning']} warning(s), "
        f"{counts['info']} info"
    )
    tags = {"error": "ERROR", "warning": "WARN ", "info": "INFO "}
    lines.extend(
        f"  {tags[f.severity]} [{f.check}] {f.code}: {f.message}" for f in self.findings
    )
    lines += [
        "images:",
        f"  full     {self.images.full}  (t={self.full_at:g}s: layout, text, margins)",
        f"  sheet    {self.images.sheet}  "
        + ("(tiles over the range + timeline)" if self.video else "(motion over one cycle)"),
        f"  heatmap  {self.images.heatmap}  (what moves at all)",
        f"  report   {self.images.report}",
    ]
    return "\n".join(lines)

LoopInfo

Bases: BaseModel

How cleanly the last frame of a cycle joins the first.

Source code in src/framesheet/models.py
class LoopInfo(BaseModel):
    """How cleanly the last frame of a cycle joins the first."""

    checked: bool
    seamless: bool | None = None
    seam_ratio: float | None = None
    """Changed-pixel share between ``t=end-epsilon`` and ``t=0``."""
    step_ratio: float | None = None
    """Changed-pixel share between ``t=0`` and ``t=epsilon`` (normal motion per step)."""
    seam_box: Rect | None = None
    detail: str

seam_ratio class-attribute instance-attribute

seam_ratio: float | None = None

Changed-pixel share between t=end-epsilon and t=0.

step_ratio class-attribute instance-attribute

step_ratio: float | None = None

Changed-pixel share between t=0 and t=epsilon (normal motion per step).

inspect

inspect(
    source: str | Path,
    *,
    frames: int = 12,
    duration: float | None = None,
    size: tuple[int, int] | None = None,
    scale: float | None = None,
    at: float | None = None,
    out: str | Path | None = None,
    tile: int | None = None,
    columns: int | None = None,
    keep_frames: bool = False,
    heat_frames: int = 48,
    color_scheme: ColorScheme = "light",
    timeout: float = 30.0,
    every: float | None = None,
    times: Sequence[float] | Literal["marks"] | None = None,
    start: float | None = None,
    end: float | None = None,
    marks: str | Path | dict[str, Any] | Marks | None = None,
    static_stretch: float = 2.0,
    channel: str | None = None,
) -> InspectionResult

Render an animated SVG/HTML (or a video) at evenly spaced times and check it.

Parameters:

Name Type Description Default
source str | Path

Path to an .svg/.html file or a video (.mp4, .webm, .mov, .mkv, animated .gif/.webp), an http(s):// URL, - for stdin, or a markup string starting with <.

required
frames int

Number of contact-sheet tiles (2-100), spread over one cycle.

12
duration float | None

Cycle length in seconds; detected from SMIL/CSS/Web Animations if omitted.

None
size tuple[int, int] | None

Viewport (width, height) in CSS px (default: SVG size/viewBox, or 1280x720).

None
scale float | None

Device scale factor (default 1; tiny SVGs without size get more).

None
at float | None

Time in seconds of the full-resolution frame full.png.

None
out str | Path | None

Output directory (default: a new temporary directory).

None
tile int | None

Longest side of a contact-sheet tile in px (default: fit 1568 px width).

None
columns int | None

Contact-sheet columns (default: roughly 4:3 sheet).

None
keep_frames bool

Also write every sampled frame to frames/.

False
heat_frames int

Extra evenly spaced frames (pixels only) for a continuous heatmap trail; 0 uses only the contact-sheet frames.

48
color_scheme ColorScheme

light or dark (prefers-color-scheme).

'light'
timeout float

Seconds to wait for navigation and page scripts.

30.0
every float | None

Videos: one tile every this many seconds (instead of frames).

None
times Sequence[float] | Literal['marks'] | None

Videos: explicit tile times (seconds), or "marks" for each point's t and each region's/span's midpoint.

None
start float | None

Videos: start of the inspected range (default 0).

None
end float | None

Videos: end of the inspected range (default: the media duration).

None
marks str | Path | dict[str, Any] | Marks | None

Videos: marks to draw (path, JSON string, dict or :class:Marks).

None
static_stretch float

Videos: seconds without visible change reported as video-static-stretch.

2.0
channel str | None

Browser channel for Playwright (e.g. chrome for H.264 if the bundled Chromium lacks it).

None

Returns:

Type Description
InspectionResult

Paths of the written images plus metrics and findings.

Source code in src/framesheet/core.py
def inspect(
    source: str | Path,
    *,
    frames: int = 12,
    duration: float | None = None,
    size: tuple[int, int] | None = None,
    scale: float | None = None,
    at: float | None = None,
    out: str | Path | None = None,
    tile: int | None = None,
    columns: int | None = None,
    keep_frames: bool = False,
    heat_frames: int = 48,
    color_scheme: ColorScheme = "light",
    timeout: float = 30.0,
    every: float | None = None,
    times: Sequence[float] | Literal["marks"] | None = None,
    start: float | None = None,
    end: float | None = None,
    marks: str | Path | dict[str, Any] | Marks | None = None,
    static_stretch: float = 2.0,
    channel: str | None = None,
) -> InspectionResult:
    """Render an animated SVG/HTML (or a video) at evenly spaced times and check it.

    Args:
        source: Path to an ``.svg``/``.html`` file or a video (``.mp4``, ``.webm``,
            ``.mov``, ``.mkv``, animated ``.gif``/``.webp``), an ``http(s)://`` URL, ``-``
            for stdin, or a markup string starting with ``<``.
        frames: Number of contact-sheet tiles (2-100), spread over one cycle.
        duration: Cycle length in seconds; detected from SMIL/CSS/Web Animations if omitted.
        size: Viewport ``(width, height)`` in CSS px (default: SVG size/viewBox, or 1280x720).
        scale: Device scale factor (default 1; tiny SVGs without ``size`` get more).
        at: Time in seconds of the full-resolution frame ``full.png``.
        out: Output directory (default: a new temporary directory).
        tile: Longest side of a contact-sheet tile in px (default: fit 1568 px width).
        columns: Contact-sheet columns (default: roughly 4:3 sheet).
        keep_frames: Also write every sampled frame to ``frames/``.
        heat_frames: Extra evenly spaced frames (pixels only) for a continuous heatmap
            trail; 0 uses only the contact-sheet frames.
        color_scheme: ``light`` or ``dark`` (``prefers-color-scheme``).
        timeout: Seconds to wait for navigation and page scripts.
        every: Videos: one tile every this many seconds (instead of ``frames``).
        times: Videos: explicit tile times (seconds), or ``"marks"`` for each point's
            ``t`` and each region's/span's midpoint.
        start: Videos: start of the inspected range (default 0).
        end: Videos: end of the inspected range (default: the media duration).
        marks: Videos: marks to draw (path, JSON string, dict or :class:`Marks`).
        static_stretch: Videos: seconds without visible change reported as
            ``video-static-stretch``.
        channel: Browser channel for Playwright (e.g. ``chrome`` for H.264 if the bundled
            Chromium lacks it).

    Returns:
        Paths of the written images plus metrics and findings.
    """
    if not 2 <= frames <= 100:  # noqa: PLR2004
        msg = "frames must be between 2 and 100"
        raise ValueError(msg)
    if duration is not None and duration <= 0:
        msg = "duration must be positive"
        raise ValueError(msg)
    out_dir = Path(out) if out else Path(tempfile.mkdtemp(prefix="framesheet-"))
    out_dir.mkdir(parents=True, exist_ok=True)
    src = _resolve(source, out_dir)
    if src.kind == "video":
        from framesheet.marks import load_marks
        from framesheet.video import inspect_video

        if static_stretch <= 0:
            msg = "static_stretch must be positive"
            raise ValueError(msg)
        return inspect_video(
            src,
            out_dir=out_dir,
            frames=frames,
            duration=duration,
            size=size,
            scale=scale,
            at=at,
            tile=tile,
            columns=columns,
            keep_frames=keep_frames,
            heat_frames=heat_frames,
            timeout=timeout,
            every=every,
            times=times,
            start=start,
            end=end,
            marks=load_marks(marks) if marks is not None else None,
            static_stretch=static_stretch,
            channel=channel,
        )
    video_only = {"every": every, "times": times, "start": start, "end": end, "marks": marks}
    if given := [name for name, value in video_only.items() if value is not None]:
        msg = f"{', '.join(given)}: only for video inputs"
        raise ValueError(msg)
    at = 0.0 if at is None else at
    viewport = size or sources.default_size(src)
    dsf = scale or (1.0 if size else _auto_scale(viewport))

    with Session(
        src, size=viewport, scale=dsf, color_scheme=color_scheme, timeout=timeout, channel=channel
    ) as s:
        s.load()
        text = src.text if src.text is not None else s.response_text
        findings = _static_findings(src.kind, text)
        animations = timing.parse_timings(s.js("() => window.__framesheet.timings()"))
        info = timing.detect_duration(animations, duration)
        times = timing.sample_times(info.seconds, frames)
        eps = timing.epsilon(info.seconds)
        description = s.js("() => window.__framesheet.describe()")
        targets = s.js("() => window.__framesheet.animatedTargets()")
        canvas = as_rect(s.js("() => window.__framesheet.canvasRect()"))
        viewbox = s.js("() => window.__framesheet.viewBox()")
        is_svg_doc = bool(s.js("() => window.__framesheet.isSvgDoc"))
        snaps: dict[float, Snapshot] = {}
        heat: dict[float, Image.Image] = {}
        measured = {*times, round(eps, 4), at}
        extra = {round(info.seconds * i / heat_frames, 4) for i in range(heat_frames)}
        for t in sorted(measured | extra):
            if t in measured:
                snaps[t] = s.snapshot(t, overflow=src.kind == "html")
                heat[t] = snaps[t].image
            else:
                heat[t] = s.screenshot(t)
        console_errors = list(s.console_errors)

    sheet_snaps = [snaps[t] for t in times]
    images = [snap.image for snap in sheet_snaps]
    metrics = _frame_metrics(images, times, dsf)
    moving = any(m.changed_ratio > 0 for m in metrics)
    findings += _motion_findings(info, moving)
    loop = _loop_info(
        info, moving, snaps[times[0]].image, snaps[round(eps, 4)].image, images[-1], dsf
    )
    if loop.checked and loop.seamless is False:
        findings.append(
            Finding(
                severity="warning",
                code="non-seamless-loop",
                message=f"The loop jumps at the cycle end: {loop.detail}.",
                check="render",
                times=[times[-1], 0.0],
            )
        )
    geo = analysis.Geometry.build(
        description,
        sheet_snaps,
        canvas=canvas,
        viewbox=as_rect(viewbox) if viewbox else None,
        targets=targets,
        animations=animations,
        is_svg_doc=is_svg_doc,
    )
    findings += analysis.run_checks(geo)
    findings += [
        Finding(severity="warning", code="console-error", message=msg, check="render")
        for msg in console_errors[:MAX_CONSOLE_ERRORS]
    ]
    findings.sort(key=lambda f: _SEVERITY_ORDER[f.severity])

    heat_images = [heat[t] for t in sorted(heat) if t <= times[-1]]
    paths = _write_images(
        out_dir,
        src.label,
        info,
        times,
        sheet_snaps,
        heat_images,
        snaps[at].image,
        tile,
        columns,
        keep_frames,
    )
    if keep_frames:
        for m in metrics:
            m.path = out_dir / "frames" / f"frame_{m.index:03d}.png"
    result = InspectionResult(
        source=src.label,
        kind=src.kind,
        viewport=viewport,
        device_scale_factor=dsf,
        canvas=canvas,
        duration=info,
        times=times,
        full_at=at,
        images=paths,
        findings=findings,
        frames=metrics,
        elements=analysis.tracks(geo),
        loop=loop,
        console_errors=console_errors,
    )
    paths.report.write_text(result.model_dump_json(indent=2), encoding="utf-8")
    return result

install_browser

install_browser() -> int

Install Playwright's Chromium for the running Python environment.

Source code in src/framesheet/render.py
def install_browser() -> int:
    """Install Playwright's Chromium for the running Python environment."""
    cmd = [sys.executable, "-m", "playwright", "install", "chromium"]
    return subprocess.run(cmd, check=False).returncode