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/core.py ADDED
@@ -0,0 +1,340 @@
1
+ """The :func:`inspect` pipeline: load, detect duration, sample, check, compose."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import itertools
6
+ import math
7
+ from pathlib import Path
8
+ import tempfile
9
+ from typing import TYPE_CHECKING
10
+
11
+ from framesheet import analysis, checks, compose, sources, timing
12
+ from framesheet.models import (
13
+ ColorScheme,
14
+ DurationInfo,
15
+ Finding,
16
+ FrameMetrics,
17
+ Images,
18
+ InspectionResult,
19
+ LoopInfo,
20
+ Severity,
21
+ as_rect,
22
+ )
23
+ from framesheet.render import Session, Snapshot
24
+
25
+
26
+ if TYPE_CHECKING:
27
+ from PIL import Image
28
+
29
+ SEAM_MIN_RATIO = 0.002
30
+ """A seam changing fewer than 0.2% of pixels always counts as seamless."""
31
+ SEAM_STEP_FACTOR = 3
32
+ """A seam is a jump if it changes this many times more pixels than one normal step."""
33
+ MIN_AUTO_SIDE = 400
34
+ MAX_CONSOLE_ERRORS = 5
35
+ _SEVERITY_ORDER = {"error": 0, "warning": 1, "info": 2}
36
+
37
+
38
+ def _auto_scale(size: tuple[int, int]) -> float:
39
+ """Tiny SVGs (icons) get a higher device scale factor so frames stay legible."""
40
+ longest = max(size)
41
+ return float(min(8, math.ceil(MIN_AUTO_SIDE / longest))) if longest < MIN_AUTO_SIDE else 1.0
42
+
43
+
44
+ def _resolve(source: str | Path, workdir: Path) -> sources.Source:
45
+ if isinstance(source, str) and source.lstrip().startswith("<"):
46
+ return sources.snippet(source, workdir)
47
+ return sources.resolve(source, workdir)
48
+
49
+
50
+ def inspect(
51
+ source: str | Path,
52
+ *,
53
+ frames: int = 12,
54
+ duration: float | None = None,
55
+ size: tuple[int, int] | None = None,
56
+ scale: float | None = None,
57
+ at: float = 0.0,
58
+ out: str | Path | None = None,
59
+ tile: int | None = None,
60
+ columns: int | None = None,
61
+ keep_frames: bool = False,
62
+ heat_frames: int = 48,
63
+ color_scheme: ColorScheme = "light",
64
+ timeout: float = 30.0,
65
+ ) -> InspectionResult:
66
+ """Render an animated SVG/HTML at evenly spaced times and check it.
67
+
68
+ Args:
69
+ source: Path to an ``.svg``/``.html`` file, an ``http(s)://`` URL, ``-`` for
70
+ stdin, or a markup string starting with ``<``.
71
+ frames: Number of contact-sheet tiles (2-100), spread over one cycle.
72
+ duration: Cycle length in seconds; detected from SMIL/CSS/Web Animations if omitted.
73
+ size: Viewport ``(width, height)`` in CSS px (default: SVG size/viewBox, or 1280x720).
74
+ scale: Device scale factor (default 1; tiny SVGs without ``size`` get more).
75
+ at: Time in seconds of the full-resolution frame ``full.png``.
76
+ out: Output directory (default: a new temporary directory).
77
+ tile: Longest side of a contact-sheet tile in px (default: fit 1568 px width).
78
+ columns: Contact-sheet columns (default: roughly 4:3 sheet).
79
+ keep_frames: Also write every sampled frame to ``frames/``.
80
+ heat_frames: Extra evenly spaced frames (pixels only) for a continuous heatmap
81
+ trail; 0 uses only the contact-sheet frames.
82
+ color_scheme: ``light`` or ``dark`` (``prefers-color-scheme``).
83
+ timeout: Seconds to wait for navigation and page scripts.
84
+
85
+ Returns:
86
+ Paths of the written images plus metrics and findings.
87
+ """
88
+ if not 2 <= frames <= 100: # noqa: PLR2004
89
+ msg = "frames must be between 2 and 100"
90
+ raise ValueError(msg)
91
+ if duration is not None and duration <= 0:
92
+ msg = "duration must be positive"
93
+ raise ValueError(msg)
94
+ out_dir = Path(out) if out else Path(tempfile.mkdtemp(prefix="framesheet-"))
95
+ out_dir.mkdir(parents=True, exist_ok=True)
96
+ src = _resolve(source, out_dir)
97
+ viewport = size or sources.default_size(src)
98
+ dsf = scale or (1.0 if size else _auto_scale(viewport))
99
+
100
+ with Session(src, size=viewport, scale=dsf, color_scheme=color_scheme, timeout=timeout) as s:
101
+ s.load()
102
+ text = src.text if src.text is not None else s.response_text
103
+ findings = _static_findings(src.kind, text)
104
+ animations = timing.parse_timings(s.js("() => window.__framesheet.timings()"))
105
+ info = timing.detect_duration(animations, duration)
106
+ times = timing.sample_times(info.seconds, frames)
107
+ eps = timing.epsilon(info.seconds)
108
+ description = s.js("() => window.__framesheet.describe()")
109
+ targets = s.js("() => window.__framesheet.animatedTargets()")
110
+ canvas = as_rect(s.js("() => window.__framesheet.canvasRect()"))
111
+ viewbox = s.js("() => window.__framesheet.viewBox()")
112
+ is_svg_doc = bool(s.js("() => window.__framesheet.isSvgDoc"))
113
+ snaps: dict[float, Snapshot] = {}
114
+ heat: dict[float, Image.Image] = {}
115
+ measured = {*times, round(eps, 4), at}
116
+ extra = {round(info.seconds * i / heat_frames, 4) for i in range(heat_frames)}
117
+ for t in sorted(measured | extra):
118
+ if t in measured:
119
+ snaps[t] = s.snapshot(t, overflow=src.kind == "html")
120
+ heat[t] = snaps[t].image
121
+ else:
122
+ heat[t] = s.screenshot(t)
123
+ console_errors = list(s.console_errors)
124
+
125
+ sheet_snaps = [snaps[t] for t in times]
126
+ images = [snap.image for snap in sheet_snaps]
127
+ metrics = _frame_metrics(images, times, dsf)
128
+ moving = any(m.changed_ratio > 0 for m in metrics)
129
+ findings += _motion_findings(info, moving)
130
+ loop = _loop_info(
131
+ info, moving, snaps[times[0]].image, snaps[round(eps, 4)].image, images[-1], dsf
132
+ )
133
+ if loop.checked and loop.seamless is False:
134
+ findings.append(
135
+ Finding(
136
+ severity="warning",
137
+ code="non-seamless-loop",
138
+ message=f"The loop jumps at the cycle end: {loop.detail}.",
139
+ check="render",
140
+ times=[times[-1], 0.0],
141
+ )
142
+ )
143
+ geo = analysis.Geometry.build(
144
+ description,
145
+ sheet_snaps,
146
+ canvas=canvas,
147
+ viewbox=as_rect(viewbox) if viewbox else None,
148
+ targets=targets,
149
+ animations=animations,
150
+ is_svg_doc=is_svg_doc,
151
+ )
152
+ findings += analysis.run_checks(geo)
153
+ findings += [
154
+ Finding(severity="warning", code="console-error", message=msg, check="render")
155
+ for msg in console_errors[:MAX_CONSOLE_ERRORS]
156
+ ]
157
+ findings.sort(key=lambda f: _SEVERITY_ORDER[f.severity])
158
+
159
+ heat_images = [heat[t] for t in sorted(heat) if t <= times[-1]]
160
+ paths = _write_images(
161
+ out_dir,
162
+ src.label,
163
+ info,
164
+ times,
165
+ sheet_snaps,
166
+ heat_images,
167
+ snaps[at].image,
168
+ tile,
169
+ columns,
170
+ keep_frames,
171
+ )
172
+ if keep_frames:
173
+ for m in metrics:
174
+ m.path = out_dir / "frames" / f"frame_{m.index:03d}.png"
175
+ result = InspectionResult(
176
+ source=src.label,
177
+ kind=src.kind,
178
+ viewport=viewport,
179
+ device_scale_factor=dsf,
180
+ canvas=canvas,
181
+ duration=info,
182
+ times=times,
183
+ full_at=at,
184
+ images=paths,
185
+ findings=findings,
186
+ frames=metrics,
187
+ elements=analysis.tracks(geo),
188
+ loop=loop,
189
+ console_errors=console_errors,
190
+ )
191
+ paths.report.write_text(result.model_dump_json(indent=2), encoding="utf-8")
192
+ return result
193
+
194
+
195
+ def _static_findings(kind: str, text: str | None) -> list[Finding]:
196
+ if not text:
197
+ return []
198
+ if kind == "svg":
199
+ return checks.check_svg_source(text)
200
+ return checks.check_html_source(text)
201
+
202
+
203
+ def _frame_metrics(
204
+ images: list[Image.Image], times: list[float], scale: float
205
+ ) -> list[FrameMetrics]:
206
+ out = [FrameMetrics(index=0, t=times[0], changed_ratio=0.0)]
207
+ for i in range(1, len(images)):
208
+ ratio, box = compose.diff_stats(images[i - 1], images[i])
209
+ out.append(
210
+ FrameMetrics(
211
+ index=i,
212
+ t=times[i],
213
+ changed_ratio=round(ratio, 5),
214
+ changed_box=compose.to_css(box, scale),
215
+ )
216
+ )
217
+ return out
218
+
219
+
220
+ def _motion_findings(info: DurationInfo, moving: bool) -> list[Finding]:
221
+ def finding(severity: Severity, code: str, message: str) -> Finding:
222
+ return Finding(severity=severity, code=code, message=message, check="render")
223
+
224
+ if info.method == "fallback" and moving:
225
+ info.looping = True
226
+ return [
227
+ finding(
228
+ "warning",
229
+ "js-driven-motion",
230
+ "Pixels change but no SMIL/CSS/Web Animation was found: motion is JS-driven "
231
+ f"(rAF/canvas/timers). Sampled {info.seconds:g}s; pass --duration with the "
232
+ "real cycle length.",
233
+ )
234
+ ]
235
+ if not moving and info.animations:
236
+ return [
237
+ finding(
238
+ "info",
239
+ "no-visible-motion",
240
+ f"{len(info.animations)} animation(s) declared, but no pixel changed between "
241
+ "sampled frames.",
242
+ )
243
+ ]
244
+ if not moving:
245
+ return [finding("info", "no-motion", "No animation found and no pixel changed: static.")]
246
+ return []
247
+
248
+
249
+ def _loop_info(
250
+ info: DurationInfo,
251
+ moving: bool,
252
+ first: Image.Image,
253
+ after_first: Image.Image,
254
+ last: Image.Image,
255
+ scale: float,
256
+ ) -> LoopInfo:
257
+ if not moving:
258
+ return LoopInfo(checked=False, detail="no motion")
259
+ if not info.looping:
260
+ return LoopInfo(checked=False, detail="finite animation (does not repeat)")
261
+ if info.method == "fallback":
262
+ return LoopInfo(checked=False, detail="cycle length unknown (JS-driven); pass --duration")
263
+ seam, box = compose.diff_stats(last, first)
264
+ step, _ = compose.diff_stats(first, after_first)
265
+ seamless = seam <= SEAM_MIN_RATIO or seam <= SEAM_STEP_FACTOR * step + SEAM_MIN_RATIO / 2
266
+ detail = (
267
+ f"last frame -> first frame changes {seam:.2%} of pixels, "
268
+ f"one normal step changes {step:.2%}"
269
+ )
270
+ return LoopInfo(
271
+ checked=True,
272
+ seamless=seamless,
273
+ seam_ratio=round(seam, 5),
274
+ step_ratio=round(step, 5),
275
+ seam_box=compose.to_css(box, scale) if not seamless else None,
276
+ detail=detail,
277
+ )
278
+
279
+
280
+ def _label(t: float, i: int, count: int) -> str:
281
+ label = f"t={t:.2f}s"
282
+ if i == 0:
283
+ return f"{label} start"
284
+ if i == count - 1:
285
+ return f"{label} end"
286
+ return label
287
+
288
+
289
+ def _write_images(
290
+ out_dir: Path,
291
+ name: str,
292
+ info: DurationInfo,
293
+ times: list[float],
294
+ snaps: list[Snapshot],
295
+ heat_images: list[Image.Image],
296
+ full: Image.Image,
297
+ tile: int | None,
298
+ columns: int | None,
299
+ keep_frames: bool,
300
+ ) -> Images:
301
+ images = [s.image for s in snaps]
302
+ title = Path(name).name if name not in {"-", "<snippet>"} else "stdin"
303
+ span = f"{len(times)} frames over 0-{info.seconds:g}s"
304
+ how = {"override": "set by --duration", "detected": "detected", "fallback": "fallback"}
305
+ loop = "looping" if info.looping else "not looping"
306
+ sheet = compose.contact_sheet(
307
+ images,
308
+ [_label(t, i, len(times)) for i, t in enumerate(times)],
309
+ title=title,
310
+ subtitle=f"{span} ({how[info.method]}, {loop}); last tile = 1 frame before the end",
311
+ tile=tile,
312
+ columns=columns,
313
+ highlight=(0, len(images) - 1),
314
+ )
315
+ union = None
316
+ for prev, cur in itertools.pairwise(heat_images):
317
+ _, box = compose.diff_stats(prev, cur)
318
+ if box:
319
+ union = box if union is None else _union(union, box)
320
+ heat = compose.heatmap(
321
+ heat_images,
322
+ title=f"{title}: motion heatmap",
323
+ subtitle=f"pixels that change across {len(heat_images)} frames over 0-{info.seconds:g}s"
324
+ "; background = t=0, dimmed",
325
+ boxes=[union] if union else [],
326
+ )
327
+ paths = Images(
328
+ full=compose.save_png(full, out_dir / "full.png"),
329
+ sheet=compose.save_png(sheet, out_dir / "sheet.png"),
330
+ heatmap=compose.save_png(heat, out_dir / "heatmap.png"),
331
+ report=out_dir / "report.json",
332
+ )
333
+ if keep_frames:
334
+ for i, image in enumerate(images):
335
+ compose.save_png(image, out_dir / "frames" / f"frame_{i:03d}.png")
336
+ return paths
337
+
338
+
339
+ def _union(a: tuple[int, int, int, int], b: tuple[int, int, int, int]) -> tuple[int, int, int, int]:
340
+ return min(a[0], b[0]), min(a[1], b[1]), max(a[2], b[2]), max(a[3], b[3])
framesheet/log.py ADDED
@@ -0,0 +1,25 @@
1
+ """Logging configuration for framesheet."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+
7
+
8
+ LogLevel = int | str
9
+
10
+
11
+ def get_logger(name: str, log_level: LogLevel | None = None) -> logging.Logger:
12
+ """Get a logger for the given name.
13
+
14
+ Args:
15
+ name: The name of the logger.
16
+ Will be prefixed with 'framesheet'
17
+ log_level: The logging level to set for the logger
18
+
19
+ Returns:
20
+ A logger instance
21
+ """
22
+ logger = logging.getLogger(f"framesheet.{name}")
23
+ if log_level is not None:
24
+ logger.setLevel(log_level)
25
+ return logger
framesheet/models.py ADDED
@@ -0,0 +1,195 @@
1
+ """Result models for framesheet inspections."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import TYPE_CHECKING, Literal
7
+
8
+ from pydantic import BaseModel, Field
9
+
10
+
11
+ if TYPE_CHECKING:
12
+ from collections.abc import Sequence
13
+
14
+
15
+ Severity = Literal["error", "warning", "info"]
16
+ SourceKind = Literal["svg", "html"]
17
+ ColorScheme = Literal["light", "dark"]
18
+ Rect = tuple[float, float, float, float]
19
+ """An axis-aligned box as ``(x, y, width, height)``."""
20
+
21
+
22
+ def as_rect(values: Sequence[float]) -> Rect:
23
+ """Coerce a 4-item sequence (e.g. a JSON list from the page) to a :data:`Rect`."""
24
+ x, y, w, h = values
25
+ return float(x), float(y), float(w), float(h)
26
+
27
+
28
+ class Finding(BaseModel):
29
+ """A single problem (or noteworthy fact) found by a static or render check."""
30
+
31
+ severity: Severity
32
+ code: str
33
+ """Stable, kebab-case identifier, e.g. ``parked-at-origin``."""
34
+ message: str
35
+ check: Literal["static", "render"]
36
+ element: str | None = None
37
+ """Human-readable element label such as ``circle#dot`` or ``text[2] "Hello"``."""
38
+ times: list[float] | None = None
39
+ """Sample times (seconds) at which the problem was observed."""
40
+
41
+
42
+ class AnimationTiming(BaseModel):
43
+ """Timing of one declarative animation, as reported by the browser."""
44
+
45
+ kind: Literal["smil", "css-animation", "css-transition", "web-animation"]
46
+ target: str | None = None
47
+ name: str | None = None
48
+ start: float
49
+ """Begin / delay in seconds (may be negative)."""
50
+ duration: float
51
+ """Duration of one iteration in seconds."""
52
+ iterations: float | None
53
+ """Iteration count; ``None`` means infinite."""
54
+ direction: str = "normal"
55
+ period: float
56
+ """Seconds until the animation looks the same again (2x duration for alternate)."""
57
+ end: float | None
58
+ """End of the active interval in seconds; ``None`` if infinite."""
59
+ transform_box: str | None = None
60
+ """Computed ``transform-box`` of an SVG target whose transform is animated by CSS."""
61
+
62
+
63
+ class DurationInfo(BaseModel):
64
+ """The sampled time span and how it was chosen."""
65
+
66
+ seconds: float
67
+ method: Literal["override", "detected", "fallback"]
68
+ looping: bool
69
+ """True if at least one animation repeats forever (or motion is JS-driven)."""
70
+ detail: str
71
+ animations: list[AnimationTiming] = Field(default_factory=list)
72
+
73
+
74
+ class FrameMetrics(BaseModel):
75
+ """Per-frame numbers."""
76
+
77
+ index: int
78
+ t: float
79
+ changed_ratio: float
80
+ """Share of pixels that differ from the previous frame (0 for the first frame)."""
81
+ changed_box: Rect | None = None
82
+ """Bounding box (CSS px) of the pixels that changed vs. the previous frame."""
83
+ path: Path | None = None
84
+ """Path of the individual frame PNG, if frames were kept."""
85
+
86
+
87
+ class ElementTrack(BaseModel):
88
+ """Geometry of one animated element over all frames."""
89
+
90
+ element: str
91
+ animated_by: list[str]
92
+ """``smil``, ``css-animation``, ``web-animation`` and/or ``moved`` (geometry changed)."""
93
+ units: Literal["viewBox", "px"]
94
+ boxes: list[Rect | None]
95
+ """One box per frame (``None`` if not rendered at that frame)."""
96
+
97
+
98
+ class LoopInfo(BaseModel):
99
+ """How cleanly the last frame of a cycle joins the first."""
100
+
101
+ checked: bool
102
+ seamless: bool | None = None
103
+ seam_ratio: float | None = None
104
+ """Changed-pixel share between ``t=end-epsilon`` and ``t=0``."""
105
+ step_ratio: float | None = None
106
+ """Changed-pixel share between ``t=0`` and ``t=epsilon`` (normal motion per step)."""
107
+ seam_box: Rect | None = None
108
+ detail: str
109
+
110
+
111
+ class Images(BaseModel):
112
+ full: Path
113
+ sheet: Path
114
+ heatmap: Path
115
+ report: Path
116
+
117
+
118
+ class InspectionResult(BaseModel):
119
+ """Everything framesheet found out about one input."""
120
+
121
+ source: str
122
+ kind: SourceKind
123
+ viewport: tuple[int, int]
124
+ device_scale_factor: float
125
+ canvas: Rect
126
+ """Drawing area in CSS px (the viewBox for SVG documents, the viewport for HTML)."""
127
+ duration: DurationInfo
128
+ times: list[float]
129
+ """Sample times of the contact-sheet tiles in seconds."""
130
+ full_at: float
131
+ images: Images
132
+ findings: list[Finding]
133
+ frames: list[FrameMetrics]
134
+ elements: list[ElementTrack]
135
+ loop: LoopInfo
136
+ console_errors: list[str] = Field(default_factory=list)
137
+
138
+ @property
139
+ def errors(self) -> list[Finding]:
140
+ return [f for f in self.findings if f.severity == "error"]
141
+
142
+ @property
143
+ def warnings(self) -> list[Finding]:
144
+ return [f for f in self.findings if f.severity == "warning"]
145
+
146
+ def codes(self) -> set[str]:
147
+ """All finding codes, handy for assertions."""
148
+ return {f.code for f in self.findings}
149
+
150
+ def summary(self) -> str:
151
+ """Concise multi-line text for humans and agents (what the CLI prints)."""
152
+ w, h = self.viewport
153
+ d = self.duration
154
+ lines = [
155
+ f"framesheet: {self.source} ({self.kind}, {w}x{h} @{self.device_scale_factor:g}x)",
156
+ f"duration: {d.seconds:g}s {d.method}: {d.detail}"
157
+ + (" [looping]" if d.looping else ""),
158
+ ]
159
+ busiest = max(self.frames, key=lambda f: f.changed_ratio)
160
+ motion = (
161
+ f"max change {busiest.changed_ratio:.1%} at t={busiest.t:.2f}s"
162
+ if busiest.changed_ratio
163
+ else "no pixel changes"
164
+ )
165
+ lines.append(
166
+ f"frames: {len(self.times)} at t={self.times[0]:.2f}..{self.times[-1]:.2f}s; {motion}"
167
+ )
168
+ if self.loop.checked:
169
+ verdict = "seamless" if self.loop.seamless else "NOT seamless"
170
+ lines.append(f"loop: {verdict} ({self.loop.detail})")
171
+ else:
172
+ lines.append(f"loop: not checked ({self.loop.detail})")
173
+ moving = [e.element for e in self.elements][:8]
174
+ if moving:
175
+ more = f" (+{len(self.elements) - 8} more)" if len(self.elements) > 8 else "" # noqa: PLR2004
176
+ lines.append(f"animated elements: {', '.join(moving)}{more}")
177
+ counts = {
178
+ s: sum(f.severity == s for f in self.findings) for s in ("error", "warning", "info")
179
+ }
180
+ lines.append(
181
+ f"findings: {counts['error']} error(s), {counts['warning']} warning(s), "
182
+ f"{counts['info']} info"
183
+ )
184
+ tags = {"error": "ERROR", "warning": "WARN ", "info": "INFO "}
185
+ lines.extend(
186
+ f" {tags[f.severity]} [{f.check}] {f.code}: {f.message}" for f in self.findings
187
+ )
188
+ lines += [
189
+ "images:",
190
+ f" full {self.images.full} (t={self.full_at:g}s: layout, text, margins)",
191
+ f" sheet {self.images.sheet} (motion over one cycle)",
192
+ f" heatmap {self.images.heatmap} (what moves at all)",
193
+ f" report {self.images.report}",
194
+ ]
195
+ return "\n".join(lines)
framesheet/py.typed ADDED
File without changes