uppercut-contact-sheet 0.1.0__tar.gz

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.
@@ -0,0 +1,8 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.egg-info/
4
+ dist/
5
+ build/
6
+ .pytest_cache/
7
+ .DS_Store
8
+ uv.lock
@@ -0,0 +1,91 @@
1
+ Metadata-Version: 2.5
2
+ Name: uppercut-contact-sheet
3
+ Version: 0.1.0
4
+ Summary: Build labelled contact-sheet grids from images and video frames with Pillow.
5
+ Project-URL: Source, https://github.com/uppercut-labs/py-kit/tree/main/packages/uppercut-contact-sheet
6
+ Author-email: Uppercut Labs <packages@uppercut-labs.com>
7
+ License-Expression: MIT
8
+ Keywords: contact sheet,pillow,thumbnails,video frames
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Topic :: Multimedia :: Graphics
11
+ Classifier: Typing :: Typed
12
+ Requires-Python: >=3.10
13
+ Requires-Dist: pillow>=10
14
+ Description-Content-Type: text/markdown
15
+
16
+ # uppercut-contact-sheet
17
+
18
+ Builds contact sheets with Pillow: a grid of thumbnails, each with a caption, saved as one image or split across numbered sheets. Tiles can come from image files or, when ffmpeg is installed, from frames of a video. It works as a Python module and as a command line tool.
19
+
20
+ ## Install
21
+
22
+ ```sh
23
+ pip install uppercut-contact-sheet
24
+ ```
25
+
26
+ Requires Python 3.10 or newer and Pillow 10 or newer. Video input needs `ffmpeg` and `ffprobe` on your PATH; everything else works without them.
27
+
28
+ ## Example
29
+
30
+ ```python
31
+ from uppercut_contact_sheet import contact_sheet, tiles_from_paths
32
+
33
+ tiles = tiles_from_paths(["a.png", "b.png", "c.png"])
34
+ sheet = contact_sheet(tiles, cols=3, cell=(320, 200), title="My set")
35
+ sheet.save("sheet.png")
36
+ ```
37
+
38
+ From the command line:
39
+
40
+ ```sh
41
+ uppercut-contact-sheet frames/ -o sheet.jpg --cols 4 --cell 320x200
42
+ uppercut-contact-sheet --video clip.mp4 --every 5 -o overview.jpg --per-sheet 16
43
+ ```
44
+
45
+ With `--per-sheet`, the output name is used as a prefix and the sheets are written as `overview_01.jpg`, `overview_02.jpg`, and so on.
46
+
47
+ ## Module
48
+
49
+ | Name | What it does |
50
+ | --- | --- |
51
+ | `Tile(image, label="", error=None)` | One cell. `image=None` draws a MISSING marker, `error` draws that message instead of the picture, and a `label` with newlines gives several caption lines. |
52
+ | `contact_sheet(tiles, ...)` | Returns an RGB `PIL.Image` with the tiles in a grid. |
53
+ | `save_paged(tiles, out_prefix, per_sheet, *, ext="jpg", quality=88, title=None, **options)` | Writes `<prefix>_01.<ext>`, `<prefix>_02.<ext>` and so on, and returns the paths. `options` go to `contact_sheet`. |
54
+ | `save_image(img, path, *, quality=88)` | Saves JPEG with a quality, or any format Pillow infers from the suffix. |
55
+ | `tiles_from_paths(paths, labels=None)` | Opens files as tiles, labelled with the file name by default. A file that cannot be read becomes an error tile. |
56
+ | `crop_to_bbox(tiles, margin=6)` | Crops all tiles to one shared box around the non-transparent pixels of every tile. |
57
+ | `load_font(size, candidates=None)` | Tries your font paths, then common monospace fonts for macOS, Windows and Linux, then Pillow's built-in font. |
58
+ | `ffmpeg_available()` | True when `ffmpeg` and `ffprobe` are on PATH. |
59
+ | `frame_times(duration, *, every=None, count=None, start=0, end=None)` | Timestamps, one every N seconds or N evenly spaced. |
60
+ | `grab_frame(video, t, width=None)` | Decodes one frame as an RGB image. Steps back a few frames if the seek lands past the end. |
61
+ | `video_tiles(video, times, *, width=480)` | One tile per timestamp, labelled `m:ss`. |
62
+ | `probe_duration(video)`, `parse_time(text)`, `format_time(seconds)` | Helpers for timestamps. |
63
+
64
+ ### contact_sheet options
65
+
66
+ | Option | Default | Meaning |
67
+ | --- | --- | --- |
68
+ | `cols` | `4` | Tiles per row. |
69
+ | `cell` | `(320, 200)` | Picture area of each tile in pixels. |
70
+ | `fit` | `"thumbnail"` | `thumbnail` only shrinks, `contain` scales up or down, `nearest` scales up or down without smoothing, for pixel art. The aspect ratio is always kept and the picture is centred. |
71
+ | `bg` | `"#111419"` | Background color. Transparent images are composited onto it. |
72
+ | `fg` | `"white"` | Caption and title color. |
73
+ | `caption` | `"below"` | `below`, `above` or `none`. The caption sits in its own strip, so it never covers the picture. Long lines are shortened with an ellipsis. |
74
+ | `pad` | `8` | Space around and between cells. |
75
+ | `font` | auto | A Pillow font. Defaults to `load_font` at a size that suits the cell width. |
76
+ | `title` | `None` | Text at the top of the sheet. |
77
+ | `border` | `None` | Outline color drawn around each picture area. |
78
+ | `error_color` | `"#d24b50"` | Color of MISSING and error messages. |
79
+
80
+ ### Command line options
81
+
82
+ `inputs` (files or folders), `-o/--out`, `--video`, `--every`, `--count`, `--at`, `--start`, `--end`, `--cols`, `--cell WxH`, `--fit`, `--bg`, `--fg`, `--caption`, `--pad`, `--title`, `--border`, `--font`, `--per-sheet`, `--quality`. The command exits with status 1 and a message on stderr when it cannot build the sheet.
83
+
84
+ ## Errors
85
+
86
+ - `ValueError` for no tiles, `cols` or `cell` below 1, an unknown `fit` or `caption`, or bad `frame_times` arguments.
87
+ - `RuntimeError` when a video function is called without ffmpeg, or a frame cannot be decoded.
88
+
89
+ ## License
90
+
91
+ MIT
@@ -0,0 +1,76 @@
1
+ # uppercut-contact-sheet
2
+
3
+ Builds contact sheets with Pillow: a grid of thumbnails, each with a caption, saved as one image or split across numbered sheets. Tiles can come from image files or, when ffmpeg is installed, from frames of a video. It works as a Python module and as a command line tool.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ pip install uppercut-contact-sheet
9
+ ```
10
+
11
+ Requires Python 3.10 or newer and Pillow 10 or newer. Video input needs `ffmpeg` and `ffprobe` on your PATH; everything else works without them.
12
+
13
+ ## Example
14
+
15
+ ```python
16
+ from uppercut_contact_sheet import contact_sheet, tiles_from_paths
17
+
18
+ tiles = tiles_from_paths(["a.png", "b.png", "c.png"])
19
+ sheet = contact_sheet(tiles, cols=3, cell=(320, 200), title="My set")
20
+ sheet.save("sheet.png")
21
+ ```
22
+
23
+ From the command line:
24
+
25
+ ```sh
26
+ uppercut-contact-sheet frames/ -o sheet.jpg --cols 4 --cell 320x200
27
+ uppercut-contact-sheet --video clip.mp4 --every 5 -o overview.jpg --per-sheet 16
28
+ ```
29
+
30
+ With `--per-sheet`, the output name is used as a prefix and the sheets are written as `overview_01.jpg`, `overview_02.jpg`, and so on.
31
+
32
+ ## Module
33
+
34
+ | Name | What it does |
35
+ | --- | --- |
36
+ | `Tile(image, label="", error=None)` | One cell. `image=None` draws a MISSING marker, `error` draws that message instead of the picture, and a `label` with newlines gives several caption lines. |
37
+ | `contact_sheet(tiles, ...)` | Returns an RGB `PIL.Image` with the tiles in a grid. |
38
+ | `save_paged(tiles, out_prefix, per_sheet, *, ext="jpg", quality=88, title=None, **options)` | Writes `<prefix>_01.<ext>`, `<prefix>_02.<ext>` and so on, and returns the paths. `options` go to `contact_sheet`. |
39
+ | `save_image(img, path, *, quality=88)` | Saves JPEG with a quality, or any format Pillow infers from the suffix. |
40
+ | `tiles_from_paths(paths, labels=None)` | Opens files as tiles, labelled with the file name by default. A file that cannot be read becomes an error tile. |
41
+ | `crop_to_bbox(tiles, margin=6)` | Crops all tiles to one shared box around the non-transparent pixels of every tile. |
42
+ | `load_font(size, candidates=None)` | Tries your font paths, then common monospace fonts for macOS, Windows and Linux, then Pillow's built-in font. |
43
+ | `ffmpeg_available()` | True when `ffmpeg` and `ffprobe` are on PATH. |
44
+ | `frame_times(duration, *, every=None, count=None, start=0, end=None)` | Timestamps, one every N seconds or N evenly spaced. |
45
+ | `grab_frame(video, t, width=None)` | Decodes one frame as an RGB image. Steps back a few frames if the seek lands past the end. |
46
+ | `video_tiles(video, times, *, width=480)` | One tile per timestamp, labelled `m:ss`. |
47
+ | `probe_duration(video)`, `parse_time(text)`, `format_time(seconds)` | Helpers for timestamps. |
48
+
49
+ ### contact_sheet options
50
+
51
+ | Option | Default | Meaning |
52
+ | --- | --- | --- |
53
+ | `cols` | `4` | Tiles per row. |
54
+ | `cell` | `(320, 200)` | Picture area of each tile in pixels. |
55
+ | `fit` | `"thumbnail"` | `thumbnail` only shrinks, `contain` scales up or down, `nearest` scales up or down without smoothing, for pixel art. The aspect ratio is always kept and the picture is centred. |
56
+ | `bg` | `"#111419"` | Background color. Transparent images are composited onto it. |
57
+ | `fg` | `"white"` | Caption and title color. |
58
+ | `caption` | `"below"` | `below`, `above` or `none`. The caption sits in its own strip, so it never covers the picture. Long lines are shortened with an ellipsis. |
59
+ | `pad` | `8` | Space around and between cells. |
60
+ | `font` | auto | A Pillow font. Defaults to `load_font` at a size that suits the cell width. |
61
+ | `title` | `None` | Text at the top of the sheet. |
62
+ | `border` | `None` | Outline color drawn around each picture area. |
63
+ | `error_color` | `"#d24b50"` | Color of MISSING and error messages. |
64
+
65
+ ### Command line options
66
+
67
+ `inputs` (files or folders), `-o/--out`, `--video`, `--every`, `--count`, `--at`, `--start`, `--end`, `--cols`, `--cell WxH`, `--fit`, `--bg`, `--fg`, `--caption`, `--pad`, `--title`, `--border`, `--font`, `--per-sheet`, `--quality`. The command exits with status 1 and a message on stderr when it cannot build the sheet.
68
+
69
+ ## Errors
70
+
71
+ - `ValueError` for no tiles, `cols` or `cell` below 1, an unknown `fit` or `caption`, or bad `frame_times` arguments.
72
+ - `RuntimeError` when a video function is called without ffmpeg, or a frame cannot be decoded.
73
+
74
+ ## License
75
+
76
+ MIT
@@ -0,0 +1,31 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.25"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "uppercut-contact-sheet"
7
+ version = "0.1.0"
8
+ description = "Build labelled contact-sheet grids from images and video frames with Pillow."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ authors = [{ name = "Uppercut Labs", email = "packages@uppercut-labs.com" }]
13
+ dependencies = ["Pillow>=10"]
14
+ keywords = ["contact sheet", "thumbnails", "pillow", "video frames"]
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "Topic :: Multimedia :: Graphics",
18
+ "Typing :: Typed",
19
+ ]
20
+
21
+ [project.urls]
22
+ Source = "https://github.com/uppercut-labs/py-kit/tree/main/packages/uppercut-contact-sheet"
23
+
24
+ [project.scripts]
25
+ uppercut-contact-sheet = "uppercut_contact_sheet.cli:main"
26
+
27
+ [tool.hatch.build.targets.wheel]
28
+ packages = ["src/uppercut_contact_sheet"]
29
+
30
+ [tool.hatch.build.targets.sdist]
31
+ include = ["src", "tests", "README.md"]
@@ -0,0 +1,43 @@
1
+ """Labelled contact-sheet grids from images and video frames."""
2
+
3
+ from .sheet import (
4
+ DEFAULT_FONTS,
5
+ IMAGE_SUFFIXES,
6
+ Tile,
7
+ contact_sheet,
8
+ crop_to_bbox,
9
+ load_font,
10
+ save_image,
11
+ save_paged,
12
+ tiles_from_paths,
13
+ )
14
+ from .video import (
15
+ ffmpeg_available,
16
+ format_time,
17
+ frame_times,
18
+ grab_frame,
19
+ parse_time,
20
+ probe_duration,
21
+ video_tiles,
22
+ )
23
+
24
+ __all__ = [
25
+ "DEFAULT_FONTS",
26
+ "IMAGE_SUFFIXES",
27
+ "Tile",
28
+ "contact_sheet",
29
+ "crop_to_bbox",
30
+ "ffmpeg_available",
31
+ "format_time",
32
+ "frame_times",
33
+ "grab_frame",
34
+ "load_font",
35
+ "parse_time",
36
+ "probe_duration",
37
+ "save_image",
38
+ "save_paged",
39
+ "tiles_from_paths",
40
+ "video_tiles",
41
+ ]
42
+
43
+ __version__ = "0.1.0"
@@ -0,0 +1,101 @@
1
+ """Command line entry point: ``uppercut-contact-sheet``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from .sheet import IMAGE_SUFFIXES, contact_sheet, save_image, save_paged, tiles_from_paths
10
+ from .video import frame_times, parse_time, probe_duration, video_tiles
11
+
12
+
13
+ def _parse_cell(text: str) -> tuple[int, int]:
14
+ try:
15
+ w, h = text.lower().split("x")
16
+ return int(w), int(h)
17
+ except ValueError:
18
+ raise argparse.ArgumentTypeError("cell must look like 320x200") from None
19
+
20
+
21
+ def _expand(inputs: list[str]) -> list[Path]:
22
+ paths: list[Path] = []
23
+ for item in inputs:
24
+ p = Path(item)
25
+ if p.is_dir():
26
+ paths.extend(sorted(c for c in p.iterdir() if c.suffix.lower() in IMAGE_SUFFIXES))
27
+ else:
28
+ paths.append(p)
29
+ return paths
30
+
31
+
32
+ def build_parser() -> argparse.ArgumentParser:
33
+ ap = argparse.ArgumentParser(
34
+ prog="uppercut-contact-sheet",
35
+ description="Build a labelled contact sheet from images, folders of images, or video frames.",
36
+ )
37
+ ap.add_argument("inputs", nargs="*", help="image files or folders of images")
38
+ ap.add_argument("-o", "--out", required=True, help="output file, or the prefix when --per-sheet is set")
39
+ ap.add_argument("--video", help="grab frames from this video instead of reading images (needs ffmpeg)")
40
+ g = ap.add_mutually_exclusive_group()
41
+ g.add_argument("--every", type=float, help="video: one frame every N seconds")
42
+ g.add_argument("--count", type=int, help="video: N evenly spaced frames")
43
+ g.add_argument("--at", help="video: comma-separated timestamps (seconds or mm:ss)")
44
+ ap.add_argument("--start", type=float, default=0.0, help="video: first second to sample")
45
+ ap.add_argument("--end", type=float, help="video: last second to sample")
46
+ ap.add_argument("--cols", type=int, default=4)
47
+ ap.add_argument("--cell", type=_parse_cell, default=(320, 200), help="picture area, WxH (default 320x200)")
48
+ ap.add_argument("--fit", choices=["thumbnail", "contain", "nearest"], default="thumbnail")
49
+ ap.add_argument("--bg", default="#111419")
50
+ ap.add_argument("--fg", default="white")
51
+ ap.add_argument("--caption", choices=["below", "above", "none"], default="below")
52
+ ap.add_argument("--pad", type=int, default=8)
53
+ ap.add_argument("--title")
54
+ ap.add_argument("--border", help="outline color for each cell")
55
+ ap.add_argument("--font", action="append", default=[], help="font file to try first (repeatable)")
56
+ ap.add_argument("--per-sheet", type=int, help="split into numbered sheets of this many tiles")
57
+ ap.add_argument("--quality", type=int, default=88, help="JPEG quality")
58
+ return ap
59
+
60
+
61
+ def main(argv: list[str] | None = None) -> int:
62
+ args = build_parser().parse_args(argv)
63
+ from .sheet import load_font
64
+
65
+ try:
66
+ if args.video:
67
+ dur = probe_duration(args.video)
68
+ if args.at:
69
+ times = [parse_time(x) for x in args.at.split(",") if x.strip()]
70
+ elif args.every or args.count:
71
+ times = frame_times(dur, every=args.every, count=args.count, start=args.start, end=args.end)
72
+ else:
73
+ raise ValueError("with --video give --every, --count or --at")
74
+ tiles = video_tiles(args.video, times, width=args.cell[0])
75
+ else:
76
+ if not args.inputs:
77
+ raise ValueError("give image files or folders, or use --video")
78
+ tiles = tiles_from_paths(_expand(args.inputs))
79
+ if not tiles:
80
+ raise ValueError("no images found")
81
+
82
+ font = load_font(max(12, args.cell[0] // 24), args.font) if args.font else None
83
+ opts = dict(cols=args.cols, cell=args.cell, fit=args.fit, bg=args.bg, fg=args.fg,
84
+ caption=args.caption, pad=args.pad, border=args.border, font=font)
85
+ if args.per_sheet:
86
+ out = Path(args.out)
87
+ paths = save_paged(tiles, out.with_suffix(""), args.per_sheet, ext=out.suffix.lstrip(".") or "jpg",
88
+ quality=args.quality, title=args.title, **opts)
89
+ else:
90
+ out = Path(args.out)
91
+ out.parent.mkdir(parents=True, exist_ok=True)
92
+ paths = [save_image(contact_sheet(tiles, title=args.title, **opts), out, quality=args.quality)]
93
+ except (ValueError, RuntimeError, OSError) as exc:
94
+ print(f"uppercut-contact-sheet: {exc}", file=sys.stderr)
95
+ return 1
96
+ print("\n".join(str(p) for p in paths))
97
+ return 0
98
+
99
+
100
+ if __name__ == "__main__":
101
+ raise SystemExit(main())
@@ -0,0 +1,257 @@
1
+ """Labelled contact-sheet grids built with Pillow."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+ from typing import Literal, Sequence
9
+
10
+ from PIL import Image, ImageDraw, ImageFont
11
+
12
+ Color = str | tuple[int, ...]
13
+ Fit = Literal["thumbnail", "contain", "nearest"]
14
+ CaptionPlacement = Literal["below", "above", "none"]
15
+
16
+ IMAGE_SUFFIXES = (".png", ".jpg", ".jpeg", ".webp", ".bmp", ".gif", ".tif", ".tiff")
17
+
18
+ DEFAULT_FONTS: tuple[str, ...] = (
19
+ "/System/Library/Fonts/Menlo.ttc",
20
+ "C:/Windows/Fonts/consola.ttf",
21
+ "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf",
22
+ "DejaVuSansMono.ttf",
23
+ )
24
+
25
+
26
+ @dataclass
27
+ class Tile:
28
+ """One cell of a sheet.
29
+
30
+ ``image`` of None draws a MISSING marker. ``error`` draws that message
31
+ instead of the image. ``label`` may contain newlines for several lines.
32
+ """
33
+
34
+ image: Image.Image | None
35
+ label: str = ""
36
+ error: str | None = None
37
+
38
+
39
+ def load_font(size: int, candidates: Sequence[str] | None = None) -> ImageFont.ImageFont:
40
+ """Return a font of ``size`` px, trying each candidate path or name in order.
41
+
42
+ Falls back to Pillow's built-in font, which is scalable on Pillow 10.1+.
43
+ """
44
+ for name in (*(candidates or ()), *DEFAULT_FONTS):
45
+ try:
46
+ return ImageFont.truetype(name, size)
47
+ except OSError:
48
+ continue
49
+ try:
50
+ return ImageFont.load_default(size=size)
51
+ except TypeError: # Pillow older than 10.1
52
+ return ImageFont.load_default()
53
+
54
+
55
+ def tiles_from_paths(
56
+ paths: Sequence[str | os.PathLike[str]],
57
+ labels: Sequence[str] | None = None,
58
+ ) -> list[Tile]:
59
+ """Open each path as a tile. Unreadable files become error tiles.
60
+
61
+ Labels default to the file name.
62
+ """
63
+ if labels is not None and len(labels) != len(paths):
64
+ raise ValueError("labels must have the same length as paths")
65
+ tiles: list[Tile] = []
66
+ for i, p in enumerate(paths):
67
+ label = labels[i] if labels is not None else Path(p).name
68
+ try:
69
+ with Image.open(p) as im:
70
+ im.load()
71
+ tiles.append(Tile(im.copy(), label))
72
+ except Exception as exc: # noqa: BLE001 - any decode failure becomes a marker tile
73
+ tiles.append(Tile(None, label, error=f"{type(exc).__name__}"))
74
+ return tiles
75
+
76
+
77
+ def crop_to_bbox(tiles: Sequence[Tile], margin: int = 6) -> list[Tile]:
78
+ """Crop every tile to the union of the non-transparent areas of all tiles.
79
+
80
+ All tiles are cut to the same box so they stay aligned. Tiles without an
81
+ image, and tiles that are fully transparent, are passed through. The
82
+ margin is added on each side and clamped to each image.
83
+ """
84
+ boxes = []
85
+ for t in tiles:
86
+ if t.image is None:
87
+ continue
88
+ box = t.image.convert("RGBA").getchannel("A").getbbox()
89
+ if box:
90
+ boxes.append(box)
91
+ if not boxes:
92
+ return list(tiles)
93
+ x0 = min(b[0] for b in boxes) - margin
94
+ y0 = min(b[1] for b in boxes) - margin
95
+ x1 = max(b[2] for b in boxes) + margin
96
+ y1 = max(b[3] for b in boxes) + margin
97
+ out: list[Tile] = []
98
+ for t in tiles:
99
+ if t.image is None:
100
+ out.append(t)
101
+ continue
102
+ w, h = t.image.size
103
+ crop = t.image.crop((max(x0, 0), max(y0, 0), min(x1, w), min(y1, h)))
104
+ out.append(Tile(crop, t.label, t.error))
105
+ return out
106
+
107
+
108
+ def _text_width(font: ImageFont.ImageFont, text: str) -> float:
109
+ return font.getlength(text) if hasattr(font, "getlength") else float(font.getbbox(text)[2])
110
+
111
+
112
+ def _line_height(font: ImageFont.ImageFont) -> int:
113
+ box = font.getbbox("Ag")
114
+ return int(box[3] - box[1])
115
+
116
+
117
+ def _clip_line(font: ImageFont.ImageFont, text: str, width: int) -> str:
118
+ if _text_width(font, text) <= width:
119
+ return text
120
+ ellipsis = "..."
121
+ while text and _text_width(font, text + ellipsis) > width:
122
+ text = text[:-1]
123
+ return text + ellipsis if text else ""
124
+
125
+
126
+ def _fit_image(im: Image.Image, cell: tuple[int, int], fit: Fit) -> Image.Image:
127
+ cw, ch = cell
128
+ im = im.convert("RGBA")
129
+ w, h = im.size
130
+ if w <= 0 or h <= 0:
131
+ raise ValueError("image has no pixels")
132
+ scale = min(cw / w, ch / h)
133
+ if fit == "thumbnail":
134
+ scale = min(scale, 1.0)
135
+ nw, nh = max(1, round(w * scale)), max(1, round(h * scale))
136
+ if (nw, nh) == (w, h):
137
+ return im
138
+ resample = Image.Resampling.NEAREST if fit == "nearest" else Image.Resampling.LANCZOS
139
+ return im.resize((nw, nh), resample)
140
+
141
+
142
+ def contact_sheet(
143
+ tiles: Sequence[Tile],
144
+ *,
145
+ cols: int = 4,
146
+ cell: tuple[int, int] = (320, 200),
147
+ fit: Fit = "thumbnail",
148
+ bg: Color = "#111419",
149
+ fg: Color = "white",
150
+ caption: CaptionPlacement = "below",
151
+ pad: int = 8,
152
+ font: ImageFont.ImageFont | None = None,
153
+ title: str | None = None,
154
+ border: Color | None = None,
155
+ error_color: Color = "#d24b50",
156
+ ) -> Image.Image:
157
+ """Lay ``tiles`` out in a grid and return an RGB image.
158
+
159
+ ``cell`` is the picture area of each tile in pixels. ``fit`` picks the
160
+ scaling: ``thumbnail`` shrinks only, ``contain`` scales up or down,
161
+ ``nearest`` scales up or down without smoothing (pixel art). Pictures keep
162
+ their aspect ratio and sit centred in the cell. Captions are drawn in a
163
+ strip below or above the cell so they never cover the picture, and long
164
+ lines are shortened with an ellipsis.
165
+ """
166
+ if cols < 1:
167
+ raise ValueError("cols must be at least 1")
168
+ if cell[0] < 1 or cell[1] < 1:
169
+ raise ValueError("cell must be positive")
170
+ if caption not in ("below", "above", "none"):
171
+ raise ValueError(f"unknown caption placement: {caption!r}")
172
+ if fit not in ("thumbnail", "contain", "nearest"):
173
+ raise ValueError(f"unknown fit mode: {fit!r}")
174
+ if not tiles:
175
+ raise ValueError("no tiles to lay out")
176
+
177
+ cw, ch = cell
178
+ font = font or load_font(max(12, cw // 24))
179
+ title_font = load_font(max(14, font.size + 4)) if hasattr(font, "size") else font
180
+ line_h = _line_height(font)
181
+ gap = 4
182
+ lines = max((len(t.label.split("\n")) if t.label else 0) for t in tiles)
183
+ cap_h = 0 if caption == "none" or lines == 0 else lines * (line_h + 2) + gap * 2
184
+ title_h = _line_height(title_font) + 2 * pad if title else 0
185
+ rows = (len(tiles) + cols - 1) // cols
186
+ row_h = ch + cap_h
187
+ width = cols * cw + (cols + 1) * pad
188
+ height = title_h + rows * row_h + (rows + 1) * pad
189
+
190
+ sheet = Image.new("RGB", (width, height), bg)
191
+ draw = ImageDraw.Draw(sheet)
192
+ if title:
193
+ draw.text((pad, pad), title, font=title_font, fill=fg)
194
+
195
+ for i, tile in enumerate(tiles):
196
+ x = pad + (i % cols) * (cw + pad)
197
+ y = title_h + pad + (i // cols) * (row_h + pad)
198
+ pic_y = y + (cap_h if caption == "above" else 0)
199
+ if border is not None:
200
+ draw.rectangle((x, pic_y, x + cw - 1, pic_y + ch - 1), outline=border)
201
+ if tile.error is not None or tile.image is None:
202
+ msg = tile.error if tile.error is not None else "MISSING"
203
+ msg = _clip_line(font, msg, cw - 8)
204
+ draw.text((x + 4, pic_y + ch // 2 - line_h // 2), msg, font=font, fill=error_color)
205
+ else:
206
+ pic = _fit_image(tile.image, cell, fit)
207
+ px = x + (cw - pic.width) // 2
208
+ py = pic_y + (ch - pic.height) // 2
209
+ sheet.paste(pic, (px, py), pic)
210
+ if cap_h and tile.label:
211
+ cap_y = (y if caption == "above" else y + ch) + gap
212
+ for n, line in enumerate(tile.label.split("\n")):
213
+ draw.text((x + 2, cap_y + n * (line_h + 2)), _clip_line(font, line, cw - 4), font=font, fill=fg)
214
+ return sheet
215
+
216
+
217
+ def save_paged(
218
+ tiles: Sequence[Tile],
219
+ out_prefix: str | os.PathLike[str],
220
+ per_sheet: int,
221
+ *,
222
+ ext: str = "jpg",
223
+ quality: int = 88,
224
+ title: str | None = None,
225
+ **options,
226
+ ) -> list[Path]:
227
+ """Split ``tiles`` into sheets of ``per_sheet`` and save ``<prefix>_01.<ext>`` and on.
228
+
229
+ ``options`` go to :func:`contact_sheet`. When ``title`` is given, each
230
+ sheet's title is followed by its page number. Returns the written paths.
231
+ """
232
+ if per_sheet < 1:
233
+ raise ValueError("per_sheet must be at least 1")
234
+ if not tiles:
235
+ raise ValueError("no tiles to lay out")
236
+ prefix = Path(out_prefix)
237
+ prefix.parent.mkdir(parents=True, exist_ok=True)
238
+ pages = (len(tiles) + per_sheet - 1) // per_sheet
239
+ paths: list[Path] = []
240
+ for n in range(pages):
241
+ chunk = tiles[n * per_sheet:(n + 1) * per_sheet]
242
+ page_title = f"{title} ({n + 1}/{pages})" if title and pages > 1 else title
243
+ img = contact_sheet(chunk, title=page_title, **options)
244
+ path = prefix.with_name(f"{prefix.name}_{n + 1:02d}.{ext.lstrip('.')}")
245
+ save_image(img, path, quality=quality)
246
+ paths.append(path)
247
+ return paths
248
+
249
+
250
+ def save_image(img: Image.Image, path: str | os.PathLike[str], *, quality: int = 88) -> Path:
251
+ """Save as JPEG (with ``quality``) or any other format Pillow infers from the suffix."""
252
+ p = Path(path)
253
+ if p.suffix.lower() in (".jpg", ".jpeg"):
254
+ img.convert("RGB").save(p, quality=quality)
255
+ else:
256
+ img.save(p)
257
+ return p
@@ -0,0 +1,110 @@
1
+ """Frame grabbing for video contact sheets. Needs ffmpeg and ffprobe on PATH."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import json
7
+ import shutil
8
+ import subprocess
9
+ from pathlib import Path
10
+
11
+ from PIL import Image
12
+
13
+ from .sheet import Tile
14
+
15
+
16
+ def ffmpeg_available() -> bool:
17
+ """True when both ffmpeg and ffprobe can be found on PATH."""
18
+ return shutil.which("ffmpeg") is not None and shutil.which("ffprobe") is not None
19
+
20
+
21
+ def parse_time(text: str | float | int) -> float:
22
+ """Parse seconds (``12.5``) or ``mm:ss`` / ``hh:mm:ss`` into seconds."""
23
+ total = 0.0
24
+ for part in str(text).strip().split(":"):
25
+ total = total * 60 + float(part)
26
+ return total
27
+
28
+
29
+ def format_time(t: float) -> str:
30
+ """Format seconds as ``m:ss`` or ``m:ss.ss`` when there is a fractional part."""
31
+ m, s = divmod(t, 60)
32
+ return f"{int(m)}:{s:05.2f}" if round(s, 2) % 1 else f"{int(m)}:{int(round(s)):02d}"
33
+
34
+
35
+ def frame_times(
36
+ duration: float,
37
+ *,
38
+ every: float | None = None,
39
+ count: int | None = None,
40
+ start: float = 0.0,
41
+ end: float | None = None,
42
+ ) -> list[float]:
43
+ """Pick timestamps: one every ``every`` seconds, or ``count`` evenly spaced.
44
+
45
+ Exactly one of ``every`` and ``count`` is required. Times stay inside
46
+ ``[start, end]`` (``end`` defaults to the duration).
47
+ """
48
+ if (every is None) == (count is None):
49
+ raise ValueError("give exactly one of every and count")
50
+ end = duration if end is None else min(end, duration)
51
+ if end <= start:
52
+ raise ValueError("end must be after start")
53
+ if every is not None:
54
+ if every <= 0:
55
+ raise ValueError("every must be positive")
56
+ n = int((end - start) / every) + 1
57
+ return [start + i * every for i in range(n)]
58
+ if count < 1:
59
+ raise ValueError("count must be at least 1")
60
+ return [start + (end - start) * (i + 0.5) / count for i in range(count)]
61
+
62
+
63
+ def probe_duration(video: str | Path) -> float:
64
+ """Duration in seconds of the first video stream, falling back to the container."""
65
+ if not ffmpeg_available():
66
+ raise RuntimeError("ffprobe was not found on PATH")
67
+ out = subprocess.run(
68
+ ["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries",
69
+ "stream=duration:format=duration", "-of", "json", str(video)],
70
+ capture_output=True, text=True, check=True,
71
+ )
72
+ data = json.loads(out.stdout)
73
+ streams = data.get("streams") or [{}]
74
+ value = streams[0].get("duration") or data.get("format", {}).get("duration")
75
+ if value is None:
76
+ raise RuntimeError(f"could not read the duration of {video}")
77
+ return float(value)
78
+
79
+
80
+ def grab_frame(video: str | Path, t: float, width: int | None = None, *, retries: int = 3, step: float = 1 / 30) -> Image.Image:
81
+ """Decode one frame at ``t`` seconds, optionally scaled to ``width`` px.
82
+
83
+ A seek near the end can land past the last frame, so the time is stepped
84
+ back by ``step`` seconds up to ``retries`` times before giving up.
85
+ """
86
+ if not ffmpeg_available():
87
+ raise RuntimeError("ffmpeg was not found on PATH")
88
+ scale = ["-vf", f"scale={width}:-2"] if width else []
89
+ last = ""
90
+ for k in range(retries + 1):
91
+ tt = max(t - k * step, 0.0)
92
+ r = subprocess.run(
93
+ ["ffmpeg", "-nostdin", "-v", "error", "-ss", f"{tt:.4f}", "-i", str(video),
94
+ "-frames:v", "1", *scale, "-f", "image2pipe", "-c:v", "png", "-"],
95
+ capture_output=True,
96
+ )
97
+ if r.returncode == 0 and r.stdout:
98
+ return Image.open(io.BytesIO(r.stdout)).convert("RGB")
99
+ last = r.stderr.decode(errors="replace").strip()[-300:]
100
+ raise RuntimeError(f"could not grab a frame near {t:.3f}s: {last}")
101
+
102
+
103
+ def video_tiles(
104
+ video: str | Path,
105
+ times: list[float],
106
+ *,
107
+ width: int = 480,
108
+ ) -> list[Tile]:
109
+ """Grab a frame at each time and label it with the timestamp."""
110
+ return [Tile(grab_frame(video, t, width), format_time(t)) for t in times]
@@ -0,0 +1,150 @@
1
+ import pytest
2
+ from PIL import Image
3
+
4
+ from uppercut_contact_sheet import (
5
+ Tile,
6
+ contact_sheet,
7
+ crop_to_bbox,
8
+ load_font,
9
+ save_paged,
10
+ tiles_from_paths,
11
+ )
12
+
13
+
14
+ def solid(w, h, color=(200, 30, 30)):
15
+ return Image.new("RGB", (w, h), color)
16
+
17
+
18
+ def test_grid_size_without_captions():
19
+ tiles = [Tile(solid(50, 40)) for _ in range(5)]
20
+ sheet = contact_sheet(tiles, cols=2, cell=(60, 50), pad=4, caption="below")
21
+ # no labels -> no caption strip
22
+ assert sheet.size == (2 * 60 + 3 * 4, 3 * 50 + 4 * 4)
23
+
24
+
25
+ def test_caption_strip_adds_height_and_placement_changes_pixels():
26
+ tiles = [Tile(solid(40, 40), "one"), Tile(solid(40, 40), "two\nlines")]
27
+ below = contact_sheet(tiles, cols=2, cell=(80, 60), pad=4)
28
+ above = contact_sheet(tiles, cols=2, cell=(80, 60), pad=4, caption="above")
29
+ none = contact_sheet(tiles, cols=2, cell=(80, 60), pad=4, caption="none")
30
+ assert below.size == above.size
31
+ assert below.height > none.height
32
+ assert below.tobytes() != above.tobytes()
33
+
34
+
35
+ def test_title_adds_height():
36
+ tiles = [Tile(solid(10, 10))]
37
+ assert contact_sheet(tiles, title="t").height > contact_sheet(tiles).height
38
+
39
+
40
+ def test_thumbnail_does_not_upscale_but_contain_and_nearest_do():
41
+ tiles = [Tile(Image.new("RGB", (2, 2), "white"))]
42
+ kw = dict(cell=(40, 40), pad=0, bg="black", caption="none", cols=1)
43
+ thumb = contact_sheet(tiles, fit="thumbnail", **kw)
44
+ contain = contact_sheet(tiles, fit="contain", **kw)
45
+ nearest = contact_sheet(tiles, fit="nearest", **kw)
46
+ assert thumb.getpixel((0, 0)) == (0, 0, 0) # small image centred, corner stays background
47
+ assert thumb.getpixel((20, 20)) == (255, 255, 255)
48
+ assert contain.getpixel((1, 1)) == (255, 255, 255)
49
+ assert nearest.getpixel((39, 39)) == (255, 255, 255)
50
+
51
+
52
+ def test_nearest_keeps_hard_edges():
53
+ im = Image.new("RGB", (2, 1))
54
+ im.putpixel((0, 0), (255, 0, 0))
55
+ im.putpixel((1, 0), (0, 0, 255))
56
+ sheet = contact_sheet([Tile(im)], fit="nearest", cell=(20, 10), pad=0, caption="none", cols=1)
57
+ assert {sheet.getpixel((x, 5)) for x in range(20)} == {(255, 0, 0), (0, 0, 255)}
58
+
59
+
60
+ def test_transparent_image_shows_background():
61
+ im = Image.new("RGBA", (10, 10), (0, 0, 0, 0))
62
+ sheet = contact_sheet([Tile(im)], cell=(10, 10), pad=0, bg="#102030", caption="none", cols=1)
63
+ assert sheet.getpixel((5, 5)) == (16, 32, 48)
64
+
65
+
66
+ def test_missing_and_error_tiles_draw_markers():
67
+ plain = contact_sheet([Tile(solid(10, 10))], cell=(100, 40), pad=2, caption="none", cols=1)
68
+ missing = contact_sheet([Tile(None)], cell=(100, 40), pad=2, caption="none", cols=1)
69
+ error = contact_sheet([Tile(solid(10, 10), error="boom")], cell=(100, 40), pad=2, caption="none", cols=1)
70
+ assert missing.tobytes() != Image.new("RGB", missing.size, "#111419").tobytes()
71
+ assert error.tobytes() != plain.tobytes()
72
+
73
+
74
+ def test_border_draws_outline():
75
+ sheet = contact_sheet([Tile(None)], cell=(20, 20), pad=3, border="#ff00ff", caption="none", cols=1)
76
+ assert sheet.getpixel((3, 3)) == (255, 0, 255)
77
+
78
+
79
+ def test_long_label_is_clipped_to_cell():
80
+ tiles = [Tile(solid(10, 10), "x" * 500)]
81
+ sheet = contact_sheet(tiles, cell=(60, 40), pad=2, cols=1)
82
+ assert sheet.width == 64
83
+
84
+
85
+ def test_validation_errors():
86
+ t = [Tile(solid(5, 5))]
87
+ with pytest.raises(ValueError):
88
+ contact_sheet([])
89
+ with pytest.raises(ValueError):
90
+ contact_sheet(t, cols=0)
91
+ with pytest.raises(ValueError):
92
+ contact_sheet(t, cell=(0, 10))
93
+ with pytest.raises(ValueError):
94
+ contact_sheet(t, caption="side")
95
+ with pytest.raises(ValueError):
96
+ contact_sheet(t, fit="stretch")
97
+
98
+
99
+ def test_load_font_falls_back():
100
+ f = load_font(14, ["/no/such/font.ttf"])
101
+ assert f.getbbox("Ag")[3] > 0
102
+
103
+
104
+ def test_tiles_from_paths(tmp_path):
105
+ good = tmp_path / "a.png"
106
+ solid(8, 8).save(good)
107
+ bad = tmp_path / "b.png"
108
+ bad.write_bytes(b"not an image")
109
+ tiles = tiles_from_paths([good, bad, tmp_path / "missing.png"])
110
+ assert [t.label for t in tiles] == ["a.png", "b.png", "missing.png"]
111
+ assert tiles[0].image is not None and tiles[0].error is None
112
+ assert tiles[1].image is None and tiles[1].error
113
+ assert tiles[2].image is None and tiles[2].error
114
+ named = tiles_from_paths([good], labels=["custom"])
115
+ assert named[0].label == "custom"
116
+ with pytest.raises(ValueError):
117
+ tiles_from_paths([good], labels=["a", "b"])
118
+
119
+
120
+ def test_crop_to_bbox_shares_one_box():
121
+ a = Image.new("RGBA", (40, 40), (0, 0, 0, 0))
122
+ a.paste((255, 0, 0, 255), (10, 10, 15, 15))
123
+ b = Image.new("RGBA", (40, 40), (0, 0, 0, 0))
124
+ b.paste((0, 255, 0, 255), (20, 12, 30, 20))
125
+ out = crop_to_bbox([Tile(a, "a"), Tile(None, "gone"), Tile(b, "b")], margin=2)
126
+ assert out[0].image.size == out[2].image.size == (24, 14)
127
+ assert out[1].image is None
128
+ assert out[0].label == "a"
129
+
130
+
131
+ def test_crop_to_bbox_margin_clamped_and_all_transparent_passthrough():
132
+ a = Image.new("RGBA", (10, 10), (0, 0, 0, 0))
133
+ a.putpixel((0, 0), (1, 2, 3, 255))
134
+ assert crop_to_bbox([Tile(a)], margin=50)[0].image.size == (10, 10)
135
+ empty = Tile(Image.new("RGBA", (5, 5), (0, 0, 0, 0)))
136
+ assert crop_to_bbox([empty])[0].image.size == (5, 5)
137
+
138
+
139
+ def test_save_paged(tmp_path):
140
+ tiles = [Tile(solid(10, 10), str(i)) for i in range(5)]
141
+ paths = save_paged(tiles, tmp_path / "out" / "sheet", 2, cols=1, cell=(20, 20), title="Set")
142
+ assert [p.name for p in paths] == ["sheet_01.jpg", "sheet_02.jpg", "sheet_03.jpg"]
143
+ assert all(p.exists() for p in paths)
144
+ assert Image.open(paths[2]).height < Image.open(paths[0]).height # last page has one row
145
+ png = save_paged(tiles[:1], tmp_path / "p", 5, ext="png", cols=1, cell=(20, 20))
146
+ assert png[0].suffix == ".png"
147
+ with pytest.raises(ValueError):
148
+ save_paged(tiles, tmp_path / "x", 0)
149
+ with pytest.raises(ValueError):
150
+ save_paged([], tmp_path / "x", 3)
@@ -0,0 +1,103 @@
1
+ import shutil
2
+ import subprocess
3
+
4
+ import pytest
5
+ from PIL import Image
6
+
7
+ from uppercut_contact_sheet import (
8
+ ffmpeg_available,
9
+ format_time,
10
+ frame_times,
11
+ grab_frame,
12
+ parse_time,
13
+ probe_duration,
14
+ video_tiles,
15
+ )
16
+ from uppercut_contact_sheet.cli import main
17
+
18
+ needs_ffmpeg = pytest.mark.skipif(not ffmpeg_available(), reason="ffmpeg/ffprobe not installed")
19
+
20
+
21
+ def test_parse_and_format_time():
22
+ assert parse_time("12.5") == 12.5
23
+ assert parse_time("1:05") == 65
24
+ assert parse_time("1:02:03") == 3723
25
+ assert format_time(65) == "1:05"
26
+ assert format_time(5.5) == "0:05.50"
27
+
28
+
29
+ def test_frame_times_every_and_count():
30
+ assert frame_times(10, every=5) == [0, 5, 10]
31
+ assert frame_times(10, every=4, start=1, end=9) == [1, 5, 9]
32
+ assert frame_times(10, count=4) == [1.25, 3.75, 6.25, 8.75]
33
+ assert frame_times(10, count=2, end=100) == [2.5, 7.5] # end clamps to duration
34
+
35
+
36
+ def test_frame_times_errors():
37
+ with pytest.raises(ValueError):
38
+ frame_times(10)
39
+ with pytest.raises(ValueError):
40
+ frame_times(10, every=1, count=2)
41
+ with pytest.raises(ValueError):
42
+ frame_times(10, every=0)
43
+ with pytest.raises(ValueError):
44
+ frame_times(10, count=0)
45
+ with pytest.raises(ValueError):
46
+ frame_times(10, every=1, start=10)
47
+
48
+
49
+ def test_cli_images(tmp_path, capsys):
50
+ d = tmp_path / "imgs"
51
+ d.mkdir()
52
+ for i in range(3):
53
+ Image.new("RGB", (30, 20), (i * 80, 0, 0)).save(d / f"{i}.png")
54
+ out = tmp_path / "sheet.png"
55
+ assert main([str(d), "-o", str(out), "--cols", "2", "--cell", "40x30", "--title", "T"]) == 0
56
+ assert out.exists()
57
+ assert str(out) in capsys.readouterr().out
58
+
59
+
60
+ def test_cli_paged(tmp_path):
61
+ files = []
62
+ for i in range(3):
63
+ p = tmp_path / f"{i}.png"
64
+ Image.new("RGB", (10, 10)).save(p)
65
+ files.append(str(p))
66
+ assert main([*files, "-o", str(tmp_path / "out" / "s.jpg"), "--per-sheet", "2", "--cell", "20x20"]) == 0
67
+ assert (tmp_path / "out" / "s_01.jpg").exists() and (tmp_path / "out" / "s_02.jpg").exists()
68
+
69
+
70
+ def test_cli_errors(tmp_path, capsys):
71
+ assert main(["-o", str(tmp_path / "x.png")]) == 1
72
+ assert main([str(tmp_path), "-o", str(tmp_path / "x.png")]) == 1 # empty folder
73
+ assert "no images" in capsys.readouterr().err
74
+ with pytest.raises(SystemExit):
75
+ main(["a.png", "-o", "x.png", "--cell", "nope"])
76
+
77
+
78
+ @needs_ffmpeg
79
+ def test_video_frames_and_cli(tmp_path):
80
+ video = tmp_path / "v.mp4"
81
+ subprocess.run(
82
+ ["ffmpeg", "-v", "error", "-f", "lavfi", "-i", "testsrc=size=160x90:rate=10:duration=2",
83
+ "-pix_fmt", "yuv420p", str(video)],
84
+ check=True,
85
+ )
86
+ assert 1.5 < probe_duration(video) < 2.5
87
+ assert grab_frame(video, 1.0, 80).width == 80
88
+ assert grab_frame(video, probe_duration(video)).size == (160, 90) # seek at the very end steps back
89
+ tiles = video_tiles(video, [0, 1], width=64)
90
+ assert [t.label for t in tiles] == ["0:00", "0:01"]
91
+ out = tmp_path / "v.jpg"
92
+ assert main(["--video", str(video), "--count", "4", "-o", str(out), "--cell", "64x40"]) == 0
93
+ assert out.exists()
94
+ assert main(["--video", str(video), "-o", str(out)]) == 1 # no sampling mode
95
+
96
+
97
+ def test_missing_binary_message(monkeypatch, tmp_path):
98
+ monkeypatch.setattr(shutil, "which", lambda name: None)
99
+ assert not ffmpeg_available()
100
+ with pytest.raises(RuntimeError, match="ffmpeg"):
101
+ grab_frame(tmp_path / "x.mp4", 0)
102
+ with pytest.raises(RuntimeError, match="ffprobe"):
103
+ probe_duration(tmp_path / "x.mp4")