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/cli.py ADDED
@@ -0,0 +1,113 @@
1
+ """Command line interface: ``framesheet inspect FILE...``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+ import re
8
+ import sys
9
+ from typing import Annotated
10
+
11
+ import typer
12
+
13
+ from framesheet.render import BrowserNotInstalledError, install_browser
14
+
15
+
16
+ app = typer.Typer(
17
+ name="framesheet",
18
+ help="Frame-accurate contact sheets and motion maps for animated SVG and HTML.",
19
+ no_args_is_help=True,
20
+ add_completion=False,
21
+ )
22
+
23
+
24
+ def _out_for(base: Path | None, source: str, multiple: bool) -> Path | None:
25
+ if base is None or not multiple:
26
+ return base
27
+ stem = "stdin" if source == "-" else re.sub(r"[^\w.-]+", "_", Path(source).stem)[:60]
28
+ return base / stem
29
+
30
+
31
+ @app.command("inspect")
32
+ def inspect_cmd(
33
+ sources: Annotated[
34
+ list[str], typer.Argument(help="SVG/HTML files, http(s):// URLs, or - for stdin.")
35
+ ],
36
+ frames: Annotated[int, typer.Option("--frames", "-n", help="Contact-sheet tiles.")] = 12,
37
+ duration: Annotated[
38
+ float | None, typer.Option(help="Cycle length in seconds (default: detected).")
39
+ ] = None,
40
+ at: Annotated[float, typer.Option(help="Time (s) of the full-resolution frame.")] = 0.0,
41
+ size: Annotated[
42
+ str | None, typer.Option(help="Viewport WxH (default: SVG size or 1280x720).")
43
+ ] = None,
44
+ scale: Annotated[float | None, typer.Option(help="Device scale factor.")] = None,
45
+ out: Annotated[
46
+ Path | None, typer.Option("--out", "-o", help="Output dir (default: new temp dir).")
47
+ ] = None,
48
+ tile: Annotated[
49
+ int | None, typer.Option(help="Longest side of a sheet tile in px (default: auto).")
50
+ ] = None,
51
+ columns: Annotated[int | None, typer.Option(help="Sheet columns.")] = None,
52
+ keep_frames: Annotated[bool, typer.Option(help="Also write every frame to frames/.")] = False,
53
+ dark: Annotated[bool, typer.Option(help="Emulate prefers-color-scheme: dark.")] = False,
54
+ as_json: Annotated[bool, typer.Option("--json", help="Print only the JSON report.")] = False,
55
+ ) -> None:
56
+ """Render inputs at evenly spaced times and check them.
57
+
58
+ Writes full.png, sheet.png, heatmap.png and report.json per input and prints a
59
+ summary. Exits 1 if any error-level finding was reported.
60
+ """
61
+ from framesheet.core import inspect
62
+ from framesheet.sources import parse_size
63
+
64
+ try:
65
+ viewport = parse_size(size) if size else None
66
+ except ValueError as exc:
67
+ raise typer.BadParameter(str(exc), param_hint="--size") from None
68
+ results = []
69
+ for source in sources:
70
+ try:
71
+ result = inspect(
72
+ source,
73
+ frames=frames,
74
+ duration=duration,
75
+ size=viewport,
76
+ scale=scale,
77
+ at=at,
78
+ out=_out_for(out, source, len(sources) > 1),
79
+ tile=tile,
80
+ columns=columns,
81
+ keep_frames=keep_frames,
82
+ color_scheme="dark" if dark else "light",
83
+ )
84
+ except BrowserNotInstalledError as exc:
85
+ typer.echo(f"error: {exc}", err=True)
86
+ raise typer.Exit(2) from None
87
+ except (FileNotFoundError, ValueError) as exc:
88
+ typer.echo(f"error: {exc}", err=True)
89
+ raise typer.Exit(2) from None
90
+ results.append(result)
91
+ if not as_json:
92
+ typer.echo(result.summary())
93
+ if len(sources) > 1:
94
+ typer.echo("")
95
+ if as_json:
96
+ payload = [r.model_dump(mode="json") for r in results]
97
+ sys.stdout.write(json.dumps(payload[0] if len(payload) == 1 else payload, indent=2) + "\n")
98
+ if any(r.errors for r in results):
99
+ raise typer.Exit(1)
100
+
101
+
102
+ @app.command("install-browser")
103
+ def install_browser_cmd() -> None:
104
+ """Install Playwright's Chromium for this Python environment."""
105
+ raise typer.Exit(install_browser())
106
+
107
+
108
+ def main() -> None:
109
+ app()
110
+
111
+
112
+ if __name__ == "__main__":
113
+ main()
framesheet/compose.py ADDED
@@ -0,0 +1,259 @@
1
+ """Image composition with Pillow: contact sheet, motion heatmap, pixel diffs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from functools import cache
6
+ import itertools
7
+ import math
8
+ from typing import TYPE_CHECKING
9
+
10
+ from PIL import Image, ImageChops, ImageDraw, ImageFont
11
+
12
+
13
+ if TYPE_CHECKING:
14
+ from collections.abc import Sequence
15
+ from pathlib import Path
16
+
17
+ from framesheet.models import Rect
18
+
19
+ DIFF_THRESHOLD = 8
20
+ """Per-channel difference (0-255) below which a pixel counts as unchanged."""
21
+ SHEET_BG = (226, 228, 233)
22
+ INK = (17, 24, 39)
23
+ MUTED = (75, 85, 99)
24
+ LABEL_BG = (17, 24, 39)
25
+ LABEL_FG = (255, 255, 255)
26
+ ACCENT_BG = (190, 18, 60)
27
+ TILE_BORDER = (100, 116, 139)
28
+ BOX_COLOR = (34, 211, 238)
29
+ HEADER_H = 66
30
+ LABEL_H = 34
31
+ GAP = 12
32
+ PAD = 12
33
+ LABEL_FONT = 22
34
+
35
+
36
+ @cache
37
+ def font(size: int) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
38
+ """Pillow's bundled font: identical on every platform, so output is deterministic."""
39
+ return ImageFont.load_default(size=size)
40
+
41
+
42
+ def save_png(image: Image.Image, path: Path) -> Path:
43
+ path.parent.mkdir(parents=True, exist_ok=True)
44
+ image.save(path, format="PNG", optimize=False, compress_level=6)
45
+ return path
46
+
47
+
48
+ def change_mask(a: Image.Image, b: Image.Image) -> Image.Image:
49
+ """``L`` image: per-pixel max channel difference between two RGB frames."""
50
+ r, g, b_ = ImageChops.difference(a, b).split()
51
+ return ImageChops.lighter(ImageChops.lighter(r, g), b_)
52
+
53
+
54
+ def diff_stats(a: Image.Image, b: Image.Image) -> tuple[float, tuple[int, int, int, int] | None]:
55
+ """Share of changed pixels and the bounding box (device px) of the change."""
56
+ mask = change_mask(a, b).point(lambda v: 255 if v > DIFF_THRESHOLD else 0)
57
+ hist = mask.histogram()
58
+ total = a.width * a.height
59
+ return hist[255] / total, mask.getbbox()
60
+
61
+
62
+ def to_css(box: tuple[int, int, int, int] | None, scale: float) -> Rect | None:
63
+ if box is None:
64
+ return None
65
+ x0, y0, x1, y1 = box
66
+ return (
67
+ round(x0 / scale, 1),
68
+ round(y0 / scale, 1),
69
+ round((x1 - x0) / scale, 1),
70
+ round((y1 - y0) / scale, 1),
71
+ )
72
+
73
+
74
+ def _fit(image: Image.Image, max_w: int, max_h: int) -> Image.Image:
75
+ factor = min(max_w / image.width, max_h / image.height)
76
+ size = (max(1, round(image.width * factor)), max(1, round(image.height * factor)))
77
+ return image.resize(size, Image.Resampling.LANCZOS)
78
+
79
+
80
+ def _text_width(draw: ImageDraw.ImageDraw, text: str, size: int) -> float:
81
+ return draw.textlength(text, font=font(size))
82
+
83
+
84
+ def _header(width: int, title: str, subtitle: str) -> Image.Image:
85
+ band = Image.new("RGB", (width, HEADER_H), SHEET_BG)
86
+ draw = ImageDraw.Draw(band)
87
+ draw.text((PAD, 8), title, fill=INK, font=font(24))
88
+ draw.text((PAD, 39), subtitle, fill=MUTED, font=font(18))
89
+ return band
90
+
91
+
92
+ MAX_SHEET_WIDTH = 1568
93
+ """Vision models downscale larger images; keep the sheet at or below this width."""
94
+ MAX_TILE = 480
95
+
96
+
97
+ def default_columns(count: int, tile_aspect: float) -> int:
98
+ """Columns that give a landscape (at least ~4:3) sheet for tiles of ``tile_aspect`` (w/h)."""
99
+ cols = math.ceil(math.sqrt(count * 4 / 3 / tile_aspect) - 0.25)
100
+ return max(1, min(count, cols))
101
+
102
+
103
+ def auto_tile(columns: int) -> int:
104
+ """Largest tile that keeps ``columns`` tiles within :data:`MAX_SHEET_WIDTH`."""
105
+ return max(120, min(MAX_TILE, (MAX_SHEET_WIDTH - 24 - (columns - 1) * 12) // columns - 2))
106
+
107
+
108
+ def contact_sheet(
109
+ frames: Sequence[Image.Image],
110
+ labels: Sequence[str],
111
+ *,
112
+ title: str,
113
+ subtitle: str,
114
+ tile: int | None = None,
115
+ columns: int | None = None,
116
+ highlight: Sequence[int] = (),
117
+ ) -> Image.Image:
118
+ """Grid of frames, each with a timestamp label band above it.
119
+
120
+ Args:
121
+ frames: Full-resolution frames (all the same size).
122
+ labels: One label per frame (e.g. ``t=0.50s``).
123
+ title: Header line (input name).
124
+ subtitle: Second header line (frames, span, how the duration was found).
125
+ tile: Longest side of a tile in pixels (default: as large as fits 1568 px).
126
+ columns: Grid columns (default: roughly 4:3 sheet).
127
+ highlight: Frame indices whose label gets the accent colour (first/last).
128
+ """
129
+ first = frames[0]
130
+ aspect = first.width / first.height
131
+ cols = columns or default_columns(len(frames), aspect)
132
+ tile = tile or auto_tile(cols)
133
+ tw, th = (tile, round(tile / aspect)) if aspect >= 1 else (round(tile * aspect), tile)
134
+ rows = math.ceil(len(frames) / cols)
135
+ gap, label_h, pad = GAP, LABEL_H, PAD
136
+ cell_w, cell_h = tw + 2, th + 2 + label_h
137
+ width = max(pad * 2 + cols * cell_w + (cols - 1) * gap, 560)
138
+ header = _header(width, title, subtitle)
139
+ height = header.height + pad + rows * cell_h + (rows - 1) * gap + pad
140
+ sheet = Image.new("RGB", (width, height), SHEET_BG)
141
+ sheet.paste(header, (0, 0))
142
+ draw = ImageDraw.Draw(sheet)
143
+ for i, (frame, label) in enumerate(zip(frames, labels)):
144
+ row, col = divmod(i, cols)
145
+ x = pad + col * (cell_w + gap)
146
+ y = header.height + pad + row * (cell_h + gap)
147
+ bg = ACCENT_BG if i in highlight else LABEL_BG
148
+ draw.rectangle((x, y, x + cell_w - 1, y + label_h - 1), fill=bg)
149
+ draw.text((x + 8, y + 5), label, fill=LABEL_FG, font=font(LABEL_FONT))
150
+ index = f"#{i + 1}"
151
+ draw.text(
152
+ (x + cell_w - 8 - _text_width(draw, index, 16), y + 10),
153
+ index,
154
+ fill=(203, 213, 225),
155
+ font=font(16),
156
+ )
157
+ draw.rectangle((x, y + label_h, x + cell_w - 1, y + cell_h - 1), outline=TILE_BORDER)
158
+ thumb = _fit(frame, tw, th)
159
+ sheet.paste(thumb, (x + 1 + (tw - thumb.width) // 2, y + label_h + 1))
160
+ return sheet
161
+
162
+
163
+ def motion_map(frames: Sequence[Image.Image]) -> Image.Image:
164
+ """``L`` image: per-pixel max change between consecutive frames and vs. the first."""
165
+ acc = Image.new("L", frames[0].size, 0)
166
+ for prev, cur in itertools.pairwise(frames):
167
+ acc = ImageChops.lighter(acc, change_mask(prev, cur))
168
+ for cur in frames[1:]:
169
+ acc = ImageChops.lighter(acc, change_mask(frames[0], cur))
170
+ return acc
171
+
172
+
173
+ def _heat_lut() -> tuple[list[int], list[int], list[int], list[int]]:
174
+ """Colour ramp for change strength: violet (subtle) -> red -> orange -> yellow (strong)."""
175
+ stops = [
176
+ (0.0, (168, 85, 247)),
177
+ (0.4, (239, 68, 68)),
178
+ (0.7, (249, 115, 22)),
179
+ (1.0, (253, 230, 80)),
180
+ ]
181
+ red, green, blue, alpha = [], [], [], []
182
+ for v in range(256):
183
+ if v <= DIFF_THRESHOLD:
184
+ red.append(0)
185
+ green.append(0)
186
+ blue.append(0)
187
+ alpha.append(0)
188
+ continue
189
+ s = min(1.0, (v - DIFF_THRESHOLD) / 120) ** 0.5
190
+ for (p0, c0), (p1, c1) in itertools.pairwise(stops):
191
+ if s <= p1:
192
+ f = (s - p0) / (p1 - p0)
193
+ rgb = [round(a + (b - a) * f) for a, b in zip(c0, c1)]
194
+ break
195
+ red.append(rgb[0])
196
+ green.append(rgb[1])
197
+ blue.append(rgb[2])
198
+ alpha.append(round(170 + 85 * s))
199
+ return red, green, blue, alpha
200
+
201
+
202
+ _LUT = _heat_lut()
203
+
204
+
205
+ def heatmap(
206
+ frames: Sequence[Image.Image],
207
+ *,
208
+ title: str,
209
+ subtitle: str,
210
+ max_side: int = 1280,
211
+ min_side: int = 800,
212
+ boxes: Sequence[tuple[int, int, int, int]] = (),
213
+ ) -> Image.Image:
214
+ """Coloured motion overlay on a dimmed, desaturated first frame.
215
+
216
+ Args:
217
+ frames: Full-resolution frames.
218
+ title: Header line.
219
+ subtitle: Second header line.
220
+ max_side: Longest side of the image area (frames are downscaled to fit).
221
+ min_side: Small inputs are upscaled until their longest side reaches this.
222
+ boxes: Device-px boxes to outline (e.g. the overall changed region).
223
+ """
224
+ motion = motion_map(frames)
225
+ # Grey, low-contrast base in a fixed dark range so every overlay colour stands out.
226
+ base = frames[0].convert("L").point(lambda v: round(28 + v * 0.32)).convert("RGB")
227
+ red, green, blue, alpha = _LUT
228
+ overlay = Image.merge(
229
+ "RGBA",
230
+ (motion.point(red), motion.point(green), motion.point(blue), motion.point(alpha)),
231
+ )
232
+ composed = base.convert("RGBA")
233
+ composed.alpha_composite(overlay)
234
+ image = composed.convert("RGB")
235
+ draw = ImageDraw.Draw(image)
236
+ stroke = max(2, round(max(image.size) / 300))
237
+ for box in boxes:
238
+ draw.rectangle(box, outline=BOX_COLOR, width=stroke)
239
+ if max(image.size) > max_side:
240
+ image = _fit(image, max_side, max_side)
241
+ elif max(image.size) < min_side:
242
+ image = _fit(image, min_side, min_side)
243
+ pad = 12
244
+ width = max(image.width + 2 * pad, 560)
245
+ header = _header(width, title, subtitle)
246
+ legend_h = 34
247
+ out = Image.new("RGB", (width, header.height + image.height + legend_h + pad), SHEET_BG)
248
+ out.paste(header, (0, 0))
249
+ out.paste(image, (pad, header.height))
250
+ draw = ImageDraw.Draw(out)
251
+ y = header.height + image.height + 8
252
+ x = pad
253
+ for v, text in ((20, "subtle"), (70, "medium"), (255, "strong")):
254
+ draw.rectangle((x, y + 2, x + 18, y + 20), fill=(red[v], green[v], blue[v]))
255
+ draw.text((x + 24, y + 1), text, fill=INK, font=font(16))
256
+ x += 34 + round(_text_width(draw, text, 16)) + 12
257
+ draw.rectangle((x, y + 2, x + 18, y + 20), outline=BOX_COLOR, width=3)
258
+ draw.text((x + 24, y + 1), "changed region", fill=INK, font=font(16))
259
+ return out