| """Shared frame extraction for Stage D (caption + AuroraCap runners). |
| |
| Contract (unified across all stages): |
| - indices = round(linspace(0, n_frames-1, 32)) over meta.json n_frames |
| - decode via decord -> cv2 -> ffmpeg-select fallback |
| - JPEG q=85, long side capped at 768px |
| - single_frame condition = THE MIDDLE FRAME = round((n_frames-1)/2) |
| (= sample_indices(n_frames, 1); the data contract and stage_e1_api's |
| remote extractor use this rule — an earlier version of this module took |
| position 16 of the 32-index list, round(16*(n-1)/31), which drifts off |
| the true middle) |
| |
| frames_for_hash() deduplicates repeated indices (videos with n_frames < 32 |
| produce duplicate indices); callers can report len(result) as n_frames_used. |
| Dependency-light on purpose: json/PIL only; decord/cv2 optional. |
| """ |
| import io |
| import json |
| import os |
| import subprocess |
| import tempfile |
|
|
| from PIL import Image |
|
|
| N_FRAMES_DEFAULT = 32 |
| LONG_SIDE = 768 |
| JPEG_QUALITY = 85 |
|
|
|
|
| def sample_indices(n_frames, n=N_FRAMES_DEFAULT): |
| """round(linspace(0, n_frames-1, n)) without numpy. May contain duplicates.""" |
| if n_frames <= 0: |
| raise ValueError("n_frames must be positive") |
| if n == 1: |
| return [round((n_frames - 1) / 2)] |
| return [round(i * (n_frames - 1) / (n - 1)) for i in range(n)] |
|
|
|
|
| def _resize(img): |
| w, h = img.size |
| m = max(w, h) |
| if m > LONG_SIDE: |
| img = img.resize((max(1, round(w * LONG_SIDE / m)), |
| max(1, round(h * LONG_SIDE / m))), Image.LANCZOS) |
| return img.convert("RGB") |
|
|
|
|
| def _decode_decord(path, idxs): |
| import decord |
| vr = decord.VideoReader(path, num_threads=2) |
| avail = len(vr) |
| uniq = sorted({min(i, avail - 1) for i in idxs}) |
| out = {} |
| for c0 in range(0, len(uniq), 64): |
| chunk = uniq[c0:c0 + 64] |
| batch = vr.get_batch(chunk).asnumpy() |
| for j, u in enumerate(chunk): |
| out[u] = Image.fromarray(batch[j]) |
| return out |
|
|
|
|
| def _decode_cv2(path, idxs): |
| import cv2 |
| cap = cv2.VideoCapture(path) |
| if not cap.isOpened(): |
| raise RuntimeError(f"cv2 cannot open {path}") |
| want = sorted(set(idxs)) |
| out, pos = {}, 0 |
| hi = want[-1] |
| wi = 0 |
| while wi < len(want): |
| ok = cap.grab() |
| if not ok: |
| break |
| if pos == want[wi]: |
| ok, fr = cap.retrieve() |
| if not ok: |
| break |
| out[pos] = Image.fromarray(cv2.cvtColor(fr, cv2.COLOR_BGR2RGB)) |
| wi += 1 |
| pos += 1 |
| if pos > hi: |
| break |
| cap.release() |
| if not out: |
| raise RuntimeError(f"cv2 decoded 0/{len(want)} frames from {path}") |
| last = max(out) |
| for w in want: |
| if w not in out: |
| out[w] = out[last] |
| return out |
|
|
|
|
| def _decode_ffmpeg(path, idxs): |
| uniq = sorted(set(idxs)) |
| sel = "+".join(f"eq(n\\,{i})" for i in uniq) |
| with tempfile.TemporaryDirectory() as td: |
| cmd = [os.environ.get("FFMPEG_BIN", "ffmpeg"), "-y", "-v", "error", |
| "-i", path, "-vf", f"select='{sel}'", "-vsync", "0", |
| f"{td}/f_%05d.jpg"] |
| subprocess.run(cmd, check=True, capture_output=True, timeout=1800) |
| files = sorted(os.listdir(td)) |
| if not files: |
| raise RuntimeError(f"ffmpeg extracted 0 frames from {path}") |
| imgs = [Image.open(os.path.join(td, f)) for f in files] |
| for im in imgs: |
| im.load() |
| out = {} |
| for j, u in enumerate(uniq): |
| out[u] = imgs[min(j, len(imgs) - 1)] |
| return out |
|
|
|
|
| def _decode(path, idxs): |
| errs = [] |
| for fn in (_decode_decord, _decode_cv2, _decode_ffmpeg): |
| try: |
| return fn(path, idxs) |
| except ImportError: |
| continue |
| except Exception as e: |
| errs.append(f"{fn.__name__}: {e}") |
| raise RuntimeError("all decoders failed: " + " | ".join(errs)) |
|
|
|
|
| def frames_for_hash(store, content_hash, n=N_FRAMES_DEFAULT, single=False): |
| """Return list[PIL.Image] (RGB, long side <=768) for a normalized video. |
| |
| single=True -> [middle frame] = round((n_frames-1)/2), the contract rule |
| shared with stage_e1_api's remote extractor. |
| Otherwise the n sampled frames with duplicate indices removed |
| (order preserved); len(result) == n unless n_frames < n. |
| """ |
| d = os.path.join(store, "normalized", content_hash) |
| meta = json.load(open(os.path.join(d, "meta.json"))) |
| if single: |
| idxs = sample_indices(meta["n_frames"], 1) |
| else: |
| idxs = sample_indices(meta["n_frames"], n) |
| keep = list(dict.fromkeys(idxs)) |
| decoded = _decode(os.path.join(d, "video.mp4"), keep) |
| avail_max = max(decoded) |
| return [_resize(decoded[min(i, avail_max)]) for i in keep] |
|
|
|
|
| def to_jpeg_bytes(img): |
| buf = io.BytesIO() |
| img.save(buf, format="JPEG", quality=JPEG_QUALITY) |
| return buf.getvalue() |
|
|
|
|
| def to_data_url(img): |
| import base64 |
| return "data:image/jpeg;base64," + base64.b64encode(to_jpeg_bytes(img)).decode() |
|
|