|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# /// script |
| 3 | +# requires-python = ">=3.9" |
| 4 | +# dependencies = [ |
| 5 | +# "pillow>=10.0.0", |
| 6 | +# ] |
| 7 | +# /// |
| 8 | + |
| 9 | +from __future__ import annotations |
| 10 | + |
| 11 | +import argparse |
| 12 | +from dataclasses import dataclass |
| 13 | +from pathlib import Path |
| 14 | + |
| 15 | +from PIL import Image, ImageDraw, ImageFont, ImageSequence |
| 16 | + |
| 17 | + |
| 18 | +@dataclass(frozen=True) |
| 19 | +class FrameInfo: |
| 20 | + image: Image.Image # RGBA |
| 21 | + duration_ms: int |
| 22 | + |
| 23 | + |
| 24 | +def _load_font(size: int, font_path: str | None = None) -> ImageFont.ImageFont: |
| 25 | + if size <= 0: |
| 26 | + raise ValueError("--text-size must be > 0") |
| 27 | + if font_path: |
| 28 | + return ImageFont.truetype(font_path, size=size) |
| 29 | + # Try common fonts; fall back to Pillow's tiny default if unavailable. |
| 30 | + for name in ("DejaVuSans-Bold.ttf", "DejaVuSans.ttf", "Arial.ttf"): |
| 31 | + try: |
| 32 | + return ImageFont.truetype(name, size=size) |
| 33 | + except Exception: |
| 34 | + continue |
| 35 | + return ImageFont.load_default() |
| 36 | + |
| 37 | + |
| 38 | +def _extract_frames(gif_path: Path) -> list[FrameInfo]: |
| 39 | + with Image.open(gif_path) as im: |
| 40 | + frames: list[FrameInfo] = [] |
| 41 | + for frame in ImageSequence.Iterator(im): |
| 42 | + # In most GIFs this produces a fully composited frame when converted. |
| 43 | + rgba = frame.copy().convert("RGBA") |
| 44 | + duration = int(frame.info.get("duration", im.info.get("duration", 0)) or 0) |
| 45 | + frames.append(FrameInfo(image=rgba, duration_ms=duration)) |
| 46 | + |
| 47 | + if not frames: |
| 48 | + raise ValueError(f"No frames found in GIF: {gif_path}") |
| 49 | + return frames |
| 50 | + |
| 51 | + |
| 52 | +def _measure_max_label_width( |
| 53 | + labels: list[str], font: ImageFont.ImageFont, padding: int = 0 |
| 54 | +) -> int: |
| 55 | + if not labels: |
| 56 | + return 0 |
| 57 | + tmp = Image.new("RGBA", (1, 1)) |
| 58 | + draw = ImageDraw.Draw(tmp) |
| 59 | + max_w = 0 |
| 60 | + for s in labels: |
| 61 | + bbox = draw.textbbox((0, 0), s, font=font) |
| 62 | + w = bbox[2] - bbox[0] |
| 63 | + max_w = max(max_w, w) |
| 64 | + return max_w + padding |
| 65 | + |
| 66 | + |
| 67 | +def _resize_if_needed(img: Image.Image, scale: float) -> Image.Image: |
| 68 | + if scale == 1.0: |
| 69 | + return img |
| 70 | + if scale <= 0: |
| 71 | + raise ValueError("--scale must be > 0") |
| 72 | + w, h = img.size |
| 73 | + nw = max(1, int(round(w * scale))) |
| 74 | + nh = max(1, int(round(h * scale))) |
| 75 | + return img.resize((nw, nh), resample=Image.Resampling.LANCZOS) |
| 76 | + |
| 77 | + |
| 78 | +def render_vertical_sheet( |
| 79 | + frames: list[FrameInfo], |
| 80 | + *, |
| 81 | + frame_width: int | None = None, |
| 82 | + scale: float = 1.0, |
| 83 | + margin: int = 16, |
| 84 | + gap: int = 10, |
| 85 | + bg: str = "#ffffff", |
| 86 | + text_color: str = "#ffffff", |
| 87 | + burn_color: str = "#000000", |
| 88 | + text_size: int = 32, |
| 89 | + text_inset: int = 10, |
| 90 | + burn_px: int = 3, |
| 91 | + font_path: str | None = None, |
| 92 | +) -> Image.Image: |
| 93 | + font = _load_font(text_size, font_path=font_path) |
| 94 | + |
| 95 | + if frame_width is not None and frame_width <= 0: |
| 96 | + raise ValueError("--frame-width must be a positive integer") |
| 97 | + if text_inset < 0: |
| 98 | + raise ValueError("--text-inset must be >= 0") |
| 99 | + if burn_px < 0: |
| 100 | + raise ValueError("--burn-px must be >= 0") |
| 101 | + |
| 102 | + # Compute a uniform scale so the widest frame becomes `frame_width` (if provided), |
| 103 | + # then apply the user-provided `scale` multiplier. |
| 104 | + base_w = max(f.image.size[0] for f in frames) |
| 105 | + width_scale = (frame_width / base_w) if frame_width else 1.0 |
| 106 | + final_scale = width_scale * scale |
| 107 | + |
| 108 | + scaled_frames: list[FrameInfo] = [] |
| 109 | + for f in frames: |
| 110 | + scaled_frames.append(FrameInfo(_resize_if_needed(f.image, final_scale), f.duration_ms)) |
| 111 | + |
| 112 | + max_frame_w = max(f.image.size[0] for f in scaled_frames) |
| 113 | + total_h = sum(f.image.size[1] for f in scaled_frames) + gap * (len(scaled_frames) - 1) |
| 114 | + |
| 115 | + canvas_w = margin + max_frame_w + margin |
| 116 | + canvas_h = margin + total_h + margin |
| 117 | + |
| 118 | + out = Image.new("RGBA", (canvas_w, canvas_h), bg) |
| 119 | + draw = ImageDraw.Draw(out) |
| 120 | + |
| 121 | + x_img = margin |
| 122 | + y = margin |
| 123 | + for f in scaled_frames: |
| 124 | + # Left align frames; keep their native width. |
| 125 | + out.paste(f.image, (x_img, y), f.image) |
| 126 | + |
| 127 | + label = f"{f.duration_ms} ms" |
| 128 | + bbox = draw.textbbox((0, 0), label, font=font) |
| 129 | + text_w = bbox[2] - bbox[0] |
| 130 | + |
| 131 | + x_text = x_img + f.image.size[0] - text_inset - text_w |
| 132 | + y_text = y + text_inset |
| 133 | + |
| 134 | + # "Burn" outline for readability on any background. |
| 135 | + if burn_px > 0: |
| 136 | + for dy in range(-burn_px, burn_px + 1): |
| 137 | + for dx in range(-burn_px, burn_px + 1): |
| 138 | + if dx == 0 and dy == 0: |
| 139 | + continue |
| 140 | + draw.text((x_text + dx, y_text + dy), label, fill=burn_color, font=font) |
| 141 | + |
| 142 | + draw.text((x_text, y_text), label, fill=text_color, font=font) |
| 143 | + |
| 144 | + y += f.image.size[1] + gap |
| 145 | + |
| 146 | + return out |
| 147 | + |
| 148 | + |
| 149 | +def main() -> int: |
| 150 | + p = argparse.ArgumentParser( |
| 151 | + description="Extract GIF frames and render a vertical sheet with per-frame delays." |
| 152 | + ) |
| 153 | + p.add_argument("input_gif", type=Path, help="Path to input GIF") |
| 154 | + p.add_argument( |
| 155 | + "-o", |
| 156 | + "--output", |
| 157 | + type=Path, |
| 158 | + default=None, |
| 159 | + help="Output PNG path (default: <input>.frames.png)", |
| 160 | + ) |
| 161 | + p.add_argument( |
| 162 | + "--frame-width", |
| 163 | + type=int, |
| 164 | + default=1000, |
| 165 | + help="Scale frames so the widest frame is this many pixels wide (default: 1000). " |
| 166 | + "Set to 0 to disable.", |
| 167 | + ) |
| 168 | + p.add_argument("--scale", type=float, default=1.0, help="Scale frames (e.g. 0.5)") |
| 169 | + p.add_argument("--margin", type=int, default=16, help="Outer margin (px)") |
| 170 | + p.add_argument("--gap", type=int, default=10, help="Gap between frames (px)") |
| 171 | + p.add_argument("--bg", type=str, default="#ffffff", help="Background color") |
| 172 | + p.add_argument("--text-color", type=str, default="#ffffff", help="Label text color") |
| 173 | + p.add_argument("--burn-color", type=str, default="#000000", help="Burn/outline color") |
| 174 | + p.add_argument("--text-size", type=int, default=32, help="Label font size (px)") |
| 175 | + p.add_argument("--text-inset", type=int, default=10, help="Inset from top-right of frame (px)") |
| 176 | + p.add_argument("--burn-px", type=int, default=3, help="Burn/outline thickness (px)") |
| 177 | + p.add_argument( |
| 178 | + "--font", |
| 179 | + type=str, |
| 180 | + default=None, |
| 181 | + help="Optional path to a .ttf/.otf font file to use for labels", |
| 182 | + ) |
| 183 | + args = p.parse_args() |
| 184 | + |
| 185 | + in_path: Path = args.input_gif |
| 186 | + if not in_path.exists(): |
| 187 | + raise SystemExit(f"Input GIF not found: {in_path}") |
| 188 | + |
| 189 | + out_path: Path = args.output or in_path.with_suffix("").with_suffix(".frames.png") |
| 190 | + frames = _extract_frames(in_path) |
| 191 | + sheet = render_vertical_sheet( |
| 192 | + frames, |
| 193 | + frame_width=(None if args.frame_width == 0 else args.frame_width), |
| 194 | + scale=args.scale, |
| 195 | + margin=args.margin, |
| 196 | + gap=args.gap, |
| 197 | + bg=args.bg, |
| 198 | + text_color=args.text_color, |
| 199 | + burn_color=args.burn_color, |
| 200 | + text_size=args.text_size, |
| 201 | + text_inset=args.text_inset, |
| 202 | + burn_px=args.burn_px, |
| 203 | + font_path=args.font, |
| 204 | + ) |
| 205 | + |
| 206 | + out_path.parent.mkdir(parents=True, exist_ok=True) |
| 207 | + sheet.save(out_path, format="PNG") |
| 208 | + print(f"Wrote: {out_path}") |
| 209 | + return 0 |
| 210 | + |
| 211 | + |
| 212 | +if __name__ == "__main__": |
| 213 | + raise SystemExit(main()) |
| 214 | + |
0 commit comments