|
| 1 | +#!/usr/bin/env -S uv run |
| 2 | + |
| 3 | +import argparse |
| 4 | +import json |
| 5 | +import math |
| 6 | +import subprocess |
| 7 | +from pathlib import Path |
| 8 | +from typing import BinaryIO, TypedDict, cast |
| 9 | + |
| 10 | +from make_ass import CaptionCue, default_font_size |
| 11 | + |
| 12 | +SAMPLE_FPS = 2 |
| 13 | +SAMPLE_WIDTH = 64 |
| 14 | +SAMPLE_HEIGHT = 32 |
| 15 | +WHITE_CONTRAST_MAX_LUMINANCE = 0.183 |
| 16 | +BLACK_TEXT_MIN_LUMINANCE = 0.35 |
| 17 | + |
| 18 | + |
| 19 | +class VideoDimensions(TypedDict): |
| 20 | + width: int |
| 21 | + height: int |
| 22 | + |
| 23 | + |
| 24 | +def probe_dimensions(video: Path) -> VideoDimensions: |
| 25 | + result = subprocess.run( |
| 26 | + [ |
| 27 | + "ffprobe", |
| 28 | + "-v", |
| 29 | + "error", |
| 30 | + "-select_streams", |
| 31 | + "v:0", |
| 32 | + "-show_entries", |
| 33 | + "stream=width,height", |
| 34 | + "-of", |
| 35 | + "json", |
| 36 | + str(video), |
| 37 | + ], |
| 38 | + check=True, |
| 39 | + capture_output=True, |
| 40 | + text=True, |
| 41 | + ) |
| 42 | + payload = json.loads(result.stdout) |
| 43 | + streams = payload.get("streams", []) |
| 44 | + if not streams: |
| 45 | + raise ValueError("Video has no video stream") |
| 46 | + width, height = streams[0].get("width"), streams[0].get("height") |
| 47 | + if not isinstance(width, int) or not isinstance(height, int): |
| 48 | + raise ValueError("Video dimensions are unavailable") |
| 49 | + if width <= 0 or height <= 0: |
| 50 | + raise ValueError("Video dimensions must be positive") |
| 51 | + return {"width": width, "height": height} |
| 52 | + |
| 53 | + |
| 54 | +def sample_frame_indices(start: float, end: float) -> tuple[int, ...]: |
| 55 | + if not math.isfinite(start) or not math.isfinite(end) or end <= start: |
| 56 | + raise ValueError("Caption interval must be finite and increasing") |
| 57 | + inset = min(0.5, (end - start) * 0.2) |
| 58 | + times = (start + inset, (start + end) / 2, end - inset) |
| 59 | + return tuple( |
| 60 | + dict.fromkeys(max(0, round(value * SAMPLE_FPS)) for value in times) |
| 61 | + ) |
| 62 | + |
| 63 | + |
| 64 | +def relative_luminances(frame: bytes) -> list[float]: |
| 65 | + expected = SAMPLE_WIDTH * SAMPLE_HEIGHT * 3 |
| 66 | + if len(frame) != expected: |
| 67 | + raise ValueError("Unexpected RGB frame size") |
| 68 | + linear = [ |
| 69 | + value / 12.92 if value <= 0.04045 else ((value + 0.055) / 1.055) ** 2.4 |
| 70 | + for value in (channel / 255 for channel in range(256)) |
| 71 | + ] |
| 72 | + return [ |
| 73 | + 0.2126 * linear[frame[index]] |
| 74 | + + 0.7152 * linear[frame[index + 1]] |
| 75 | + + 0.0722 * linear[frame[index + 2]] |
| 76 | + for index in range(0, len(frame), 3) |
| 77 | + ] |
| 78 | + |
| 79 | + |
| 80 | +def percentile(values: list[float], fraction: float) -> float: |
| 81 | + if not values: |
| 82 | + raise ValueError("At least one luminance sample is required") |
| 83 | + ordered = sorted(values) |
| 84 | + return ordered[round((len(ordered) - 1) * fraction)] |
| 85 | + |
| 86 | + |
| 87 | +def choose_style(luminances: list[float]) -> str: |
| 88 | + if percentile(luminances, 0.9) <= WHITE_CONTRAST_MAX_LUMINANCE: |
| 89 | + return "Default" |
| 90 | + if percentile(luminances, 0.1) >= BLACK_TEXT_MIN_LUMINANCE: |
| 91 | + return "DarkOnLight" |
| 92 | + return "Boxed" |
| 93 | + |
| 94 | + |
| 95 | +def read_exact(stream: BinaryIO, size: int) -> bytes: |
| 96 | + chunks = [] |
| 97 | + remaining = size |
| 98 | + while remaining: |
| 99 | + chunk = stream.read(remaining) |
| 100 | + if not chunk: |
| 101 | + break |
| 102 | + chunks.append(chunk) |
| 103 | + remaining -= len(chunk) |
| 104 | + return b"".join(chunks) |
| 105 | + |
| 106 | + |
| 107 | +def sampled_luminances( |
| 108 | + video: Path, |
| 109 | + required_indices: set[int], |
| 110 | + *, |
| 111 | + width: int, |
| 112 | + height: int, |
| 113 | + font_size: int, |
| 114 | + margin_bottom: int, |
| 115 | +) -> dict[int, list[float]]: |
| 116 | + band_top = max(0, height - margin_bottom - round(font_size * 2.8)) |
| 117 | + band_bottom = min(height, height - margin_bottom + round(font_size * 0.35)) |
| 118 | + band_height = max(1, band_bottom - band_top) |
| 119 | + video_filter = ( |
| 120 | + f"crop={width}:{band_height}:0:{band_top}," |
| 121 | + f"scale={SAMPLE_WIDTH}:{SAMPLE_HEIGHT}:flags=area," |
| 122 | + f"fps={SAMPLE_FPS}:start_time=0:round=near,format=rgb24" |
| 123 | + ) |
| 124 | + process = subprocess.Popen( |
| 125 | + [ |
| 126 | + "ffmpeg", |
| 127 | + "-v", |
| 128 | + "error", |
| 129 | + "-i", |
| 130 | + str(video), |
| 131 | + "-vf", |
| 132 | + video_filter, |
| 133 | + "-an", |
| 134 | + "-sn", |
| 135 | + "-f", |
| 136 | + "rawvideo", |
| 137 | + "pipe:1", |
| 138 | + ], |
| 139 | + stdout=subprocess.PIPE, |
| 140 | + stderr=subprocess.PIPE, |
| 141 | + ) |
| 142 | + if process.stdout is None or process.stderr is None: |
| 143 | + process.kill() |
| 144 | + raise RuntimeError("Could not open ffmpeg output pipes") |
| 145 | + |
| 146 | + frame_size = SAMPLE_WIDTH * SAMPLE_HEIGHT * 3 |
| 147 | + samples: dict[int, list[float]] = {} |
| 148 | + frame_index = 0 |
| 149 | + stdout = cast(BinaryIO, process.stdout) |
| 150 | + while frame := read_exact(stdout, frame_size): |
| 151 | + if len(frame) != frame_size: |
| 152 | + process.kill() |
| 153 | + raise RuntimeError("ffmpeg returned an incomplete RGB frame") |
| 154 | + if frame_index in required_indices: |
| 155 | + samples[frame_index] = relative_luminances(frame) |
| 156 | + frame_index += 1 |
| 157 | + |
| 158 | + error = process.stderr.read().decode(errors="replace").strip() |
| 159 | + if process.wait() != 0: |
| 160 | + raise RuntimeError(error or "ffmpeg caption-background analysis failed") |
| 161 | + missing = required_indices - samples.keys() |
| 162 | + if missing: |
| 163 | + raise RuntimeError( |
| 164 | + "Video ended before all caption backgrounds were sampled" |
| 165 | + ) |
| 166 | + return samples |
| 167 | + |
| 168 | + |
| 169 | +def style_cues( |
| 170 | + cues: list[CaptionCue], |
| 171 | + samples: dict[int, list[float]], |
| 172 | +) -> list[CaptionCue]: |
| 173 | + styled = [] |
| 174 | + for cue in cues: |
| 175 | + indices = sample_frame_indices(cue["start"], cue["end"]) |
| 176 | + luminances = [value for index in indices for value in samples[index]] |
| 177 | + styled_cue: CaptionCue = { |
| 178 | + "start": cue["start"], |
| 179 | + "end": cue["end"], |
| 180 | + "text": cue["text"], |
| 181 | + "style": choose_style(luminances), |
| 182 | + } |
| 183 | + styled.append(styled_cue) |
| 184 | + return styled |
| 185 | + |
| 186 | + |
| 187 | +def main() -> None: |
| 188 | + parser = argparse.ArgumentParser( |
| 189 | + description="Choose readable ASS caption styles from the video background." |
| 190 | + ) |
| 191 | + parser.add_argument("video", type=Path) |
| 192 | + parser.add_argument("input", type=Path) |
| 193 | + parser.add_argument("output", type=Path) |
| 194 | + parser.add_argument("--font-size", type=int) |
| 195 | + parser.add_argument("--margin-bottom", type=int, default=105) |
| 196 | + args = parser.parse_args() |
| 197 | + |
| 198 | + video = args.video.resolve(strict=True) |
| 199 | + parsed = json.loads(args.input.read_text(encoding="utf-8")) |
| 200 | + cues = parsed if isinstance(parsed, list) else parsed["cues"] |
| 201 | + if not cues: |
| 202 | + raise ValueError("At least one caption cue is required") |
| 203 | + dimensions = probe_dimensions(video) |
| 204 | + font_size = args.font_size or default_font_size( |
| 205 | + dimensions["width"], dimensions["height"] |
| 206 | + ) |
| 207 | + indices = { |
| 208 | + index |
| 209 | + for cue in cues |
| 210 | + for index in sample_frame_indices(cue["start"], cue["end"]) |
| 211 | + } |
| 212 | + samples = sampled_luminances( |
| 213 | + video, |
| 214 | + indices, |
| 215 | + width=dimensions["width"], |
| 216 | + height=dimensions["height"], |
| 217 | + font_size=font_size, |
| 218 | + margin_bottom=args.margin_bottom, |
| 219 | + ) |
| 220 | + styled = style_cues(cues, samples) |
| 221 | + output = styled if isinstance(parsed, list) else {**parsed, "cues": styled} |
| 222 | + args.output.write_text( |
| 223 | + json.dumps(output, ensure_ascii=False, indent=2) + "\n", |
| 224 | + encoding="utf-8", |
| 225 | + ) |
| 226 | + |
| 227 | + |
| 228 | +if __name__ == "__main__": |
| 229 | + main() |
0 commit comments