File size: 5,159 Bytes
15689bb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 | """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): # chunked: 600 frames of 720p as one batch = ~1.7 GB
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: # clamp missing tail indices to last decoded frame
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): # ffmpeg may drop trailing frames; clamp
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)) # dedupe, keep order
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()
|