Skip to content

Reverse-engineer any video, shot by shot: filmed, AI-generated or coded, and how to remake it. Breakdowns in the open VIDEO.md format. 逆向一切视频,逐个镜头看是拍的、AI 生成的还是代码做的,再告诉你怎么复刻;拆解结果按 VIDEO.md 格式输出。

Decode once for samples, sheets and stills; fewer model threads

june2478ce5778b5
diff --git a/eval/RESULTS.md b/eval/RESULTS.md
index 8077fb1..eb36663 100644
--- a/eval/RESULTS.md
+++ b/eval/RESULTS.md
@@ -150,7 +150,7 @@
| 集合 | 准确率 |
|---|---|
| `labels.yaml`(缺 11 条) | 100% |
-| `holdout.yaml`(缺 3 条) | 100% |
+| `holdout.yaml`(缺 3 条) | 99.5%(一个 0.5 秒短镜头在 AI 视频和实拍之间摇摆,置信度 0.48;镜头的每一帧现在都读进来,它落到了实拍一边) |
| `holdout2.yaml`(缺 4 条) | 100% |
| `articles.yaml` 文章视频(转码) | 97.2% |
| `daihuo.yaml` 带货 | 63.2% |
@@ -160,7 +160,7 @@
| `code_videos_holdout.yaml` | 100% |
| `particles.yaml`(3 条) | 66.7%(集合从 1 条扩到 3 条;新增的 bokeh 样本没认出,原有样本仍然判对) |
-和前面记录的只用工具的分数比,没有一组下降:文章视频 88.6% → 97.2%,带货 46.4% → 63.2%,口播 75.5% → 93.3%,影视混剪 15% → 15.8%。带货和影视混剪只用工具仍然不够,要靠看图复核(第 5、6 节)。
+和前面记录的只用工具的分数比,除了 holdout 那一个短镜头,没有一组下降:文章视频 88.6% → 97.2%,带货 46.4% → 63.2%,口播 75.5% → 93.3%,影视混剪 15% → 15.8%。带货和影视混剪只用工具仍然不够,要靠看图复核(第 5、6 节)。
## 已知局限
diff --git a/rea_video/effects.py b/rea_video/effects.py
index 05ece45..465f8b2 100644
--- a/rea_video/effects.py
+++ b/rea_video/effects.py
@@ -89,7 +89,12 @@ def extract_effects(src: str | Path, out_dir: str | Path) -> dict:
try:
import onnxruntime as ort
- session = ort.InferenceSession(str(ensure_model()), providers=["CPUExecutionProvider"])
+ from .stems import MODEL_THREADS
+
+ model = ensure_model()
+ so = ort.SessionOptions()
+ so.intra_op_num_threads = MODEL_THREADS
+ session = ort.InferenceSession(str(model), so, providers=["CPUExecutionProvider"])
except Exception as e: # offline / no onnxruntime: the report falls back to effects found on the mix
LOG.warning("effects separation unavailable: %s", e)
return {"ok": False, "reason": f"{type(e).__name__}: {e}"}
diff --git a/rea_video/features.py b/rea_video/features.py
index 72405b5..ec101a6 100644
--- a/rea_video/features.py
+++ b/rea_video/features.py
@@ -206,38 +206,67 @@ def global_motion(prev: np.ndarray, nxt: np.ndarray) -> dict | None:
}
-def collect_samples(path: str, info: VideoInfo, shot: Shot, n_frames: int = 16, n_motion: int = 24,
- crop: tuple[float, float, float, float] | None = None) -> ShotSamples:
- """crop: measure only this part of the frame (0-1 x, y, w, h), e.g. to leave out a sticker / GIF layer."""
- total = shot.end_frame - shot.start_frame
- trim = 2 if total > 12 else 0 # skip frames touching the transition
- lo, hi = trim, max(trim + 1, total - trim)
- usable = hi - lo
- keep = set(np.linspace(lo, hi - 1, num=min(n_frames, usable)).round().astype(int).tolist())
- motion_idx = set(np.linspace(lo + 1, hi - 1, num=min(n_motion, max(usable - 1, 0))).round().astype(int).tolist()) if usable > 1 else set()
- out = ShotSamples()
- prev_gray = None
- for i, bgr in enumerate(iter_frames(path, info, ANALYSIS_W, start=shot.start, duration=shot.duration, crop=crop)):
- if i >= total:
- break
+class _Samples:
+ """One shot's samples, fed frame by frame (index from the shot's first frame)."""
+
+ def __init__(self, shot: Shot, n_frames: int, n_motion: int):
+ self.shot = shot
+ self.total = shot.end_frame - shot.start_frame
+ trim = 2 if self.total > 12 else 0 # skip frames touching the transition
+ self.lo, self.hi = trim, max(trim + 1, self.total - trim)
+ usable = self.hi - self.lo
+ self.keep = set(np.linspace(self.lo, self.hi - 1, num=min(n_frames, usable)).round().astype(int).tolist())
+ self.motion_idx = set(np.linspace(self.lo + 1, self.hi - 1, num=min(n_motion, max(usable - 1, 0))).round().astype(int).tolist()) \
+ if usable > 1 else set()
+ self.out = ShotSamples()
+ self.prev_gray = None
+
+ def add(self, i: int, bgr: np.ndarray) -> None:
+ out = self.out
gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
- if lo <= i < hi:
+ if self.lo <= i < self.hi:
out.sharpness.append(float(cv2.Laplacian(gray, cv2.CV_32F).var()))
- if i in keep:
+ if i in self.keep:
out.frames.append(bgr.copy())
- out.frame_times.append(shot.t(shot.start_frame + i))
- if prev_gray is not None and i - 1 >= lo:
- d = cv2.absdiff(gray, prev_gray)
+ out.frame_times.append(self.shot.t(self.shot.start_frame + i))
+ if self.prev_gray is not None and i - 1 >= self.lo:
+ d = cv2.absdiff(gray, self.prev_gray)
out.pair_mad.append(float(d.mean()))
out.pair_zero.append(float((d == 0).mean()))
still = d < 6
out.pair_tnoise.append(float(np.mean(d[still])) if still.any() else 0.0)
- if i in motion_idx:
- m = global_motion(prev_gray, gray)
+ if i in self.motion_idx:
+ m = global_motion(self.prev_gray, gray)
if m is not None:
out.motion.append(m)
- prev_gray = gray
- return out
+ self.prev_gray = gray
+
+
+def collect_samples(path: str, info: VideoInfo, shot: Shot, n_frames: int = 16, n_motion: int = 24,
+ crop: tuple[float, float, float, float] | None = None) -> ShotSamples:
+ """crop: measure only this part of the frame (0-1 x, y, w, h), e.g. to leave out a sticker / GIF layer."""
+ c = _Samples(shot, n_frames, n_motion)
+ for i, bgr in enumerate(iter_frames(path, info, ANALYSIS_W, start=shot.start, duration=shot.duration, crop=crop)):
+ if i >= c.total:
+ break
+ c.add(i, bgr)
+ return c.out
+
+
+def collect_all_samples(path: str, info: VideoInfo, shots: list[Shot], n_frames: int = 16, n_motion: int = 24) -> dict[int, ShotSamples]:
+ """collect_samples for every shot from one decode of the whole video (a decode per shot starts each time from the
+ key frame before the shot, so a video with many cuts decodes much of itself several times over)."""
+ cols = sorted((_Samples(s, n_frames, n_motion) for s in shots), key=lambda c: c.shot.start_frame)
+ k = 0
+ for g, bgr in enumerate(iter_frames(path, info, ANALYSIS_W)):
+ while k < len(cols) and g >= cols[k].shot.end_frame:
+ k += 1
+ if k == len(cols):
+ break
+ c = cols[k]
+ if g >= c.shot.start_frame:
+ c.add(g - c.shot.start_frame, bgr)
+ return {c.shot.index: c.out for c in cols}
def _periodicity(flags: list[bool]) -> dict:
diff --git a/rea_video/media.py b/rea_video/media.py
index a52dc3c..4ddffea 100644
--- a/rea_video/media.py
+++ b/rea_video/media.py
@@ -244,6 +244,36 @@ def extract_frame(path: str | Path, t: float, out_path: str | Path, width: int |
return out_path
+def extract_frames(path: str | Path, picks: list[tuple[int, str | Path]], width: int | None = None) -> list[Path]:
+ """Frames by index (decode order, as the frame track counts them) to JPEG files, all from one decode: the same
+ pictures extract_frame writes for those frames, without a seek and a decode from the key frame before each."""
+ if not picks:
+ return []
+ by_frame: dict[int, list[Path]] = {}
+ for n, out in picks:
+ by_frame.setdefault(max(0, int(n)), []).append(Path(out))
+ order = sorted(by_frame)
+ tmp = Path(tempfile.mkdtemp(prefix="rea_frames_"))
+ try:
+ sel = "+".join(f"eq(n\\,{n})" for n in order)
+ vf = f"select='{sel}'" + (f",scale={width}:-2" if width else "")
+ cmd = ["ffmpeg", "-v", "error", "-y", "-i", str(path), "-vf", vf, *passthrough_args(), "-q:v", "2", str(tmp / "f_%06d.jpg")]
+ _run_ffmpeg(cmd, f"{len(order)} frames")
+ got = sorted(tmp.glob("f_*.jpg"))
+ written = []
+ for k, n in enumerate(order):
+ for out in by_frame[n]:
+ out.parent.mkdir(parents=True, exist_ok=True)
+ src = got[min(k, len(got) - 1)] if got else None
+ if src is None:
+ continue
+ shutil.copyfile(src, out)
+ written.append(out)
+ return written
+ finally:
+ shutil.rmtree(tmp, ignore_errors=True)
+
+
def _run_ffmpeg(cmd: list[str], what: str) -> None:
got = subprocess.run(cmd, capture_output=True)
if got.returncode != 0:
diff --git a/rea_video/overlay.py b/rea_video/overlay.py
index 0c704f5..5b912b9 100644
--- a/rea_video/overlay.py
+++ b/rea_video/overlay.py
@@ -82,10 +82,12 @@ class _RapidOCR3:
"""rapidocr 3.x (used on Python >= 3.13, where rapidocr-onnxruntime has no release) behind the
rapidocr-onnxruntime call shape: ocr(img) -> ([[box, text, score], ...] or None, elapse)."""
- def __init__(self, rec_model_path: str | None = None, use_cls: bool | None = None):
+ def __init__(self, rec_model_path: str | None = None, use_cls: bool | None = None, intra_op_num_threads: int | None = None):
from rapidocr import RapidOCR # type: ignore
params = {"Global.log_level": "warning"}
+ if intra_op_num_threads:
+ params["EngineConfig.onnxruntime.intra_op_num_threads"] = intra_op_num_threads
if rec_model_path: # its character list is read from the ONNX metadata, as with rapidocr-onnxruntime
params["Rec.model_path"] = rec_model_path
if use_cls is not None:
@@ -113,6 +115,11 @@ def get_ocr():
if lang not in _OCR:
try:
kwargs = {"rec_model_path": str(rec_model(lang))} if lang in _REC_MODELS else {}
+ # as many threads as the separation models get: OCR runs alongside them, and more threads than the
+ # performance cores only fight over them (faster alone too, same reads)
+ from .stems import MODEL_THREADS
+
+ kwargs["intra_op_num_threads"] = MODEL_THREADS
if lang in _NO_ANGLE_CLS:
kwargs["use_cls"] = False # rapidocr-onnxruntime takes it as a constructor option too
_OCR[lang] = _ocr_engine(**kwargs)
diff --git a/rea_video/pipeline.py b/rea_video/pipeline.py
index 646b502..bf607f9 100644
--- a/rea_video/pipeline.py
+++ b/rea_video/pipeline.py
@@ -13,8 +13,8 @@ from .assets import detect_embedded, material_summary
from .audio import analyze_audio, merge_audio_with_vlm, speaks_in
from .sound_source import MUSIC_ZH, classify_sound_sources, per_clip_audio
from .classify import FILM_HINT_ZH, LABEL_ZH, OVERLAY_KIND_ZH, RULES, UNMEASURED, decide, deterministic, drop_scene_text, fuse, group_of, image_source_guess, overlay_layers, top, verdict_text, video_context
-from .features import collect_samples, crop_box, intersect_box, photo_letterbox, shot_features
-from .media import cut_clip, extract_frame, require_tools, video_info
+from .features import collect_all_samples, collect_samples, crop_box, intersect_box, photo_letterbox, shot_features
+from .media import cut_clip, extract_frame, extract_frames, require_tools, video_info
from .overlay import ocr_frames, persistent_template, shot_ocr_frames, shot_ocr_items, static_overlays, summarize_text
from .plan import Planner
from .probe import provenance
@@ -70,11 +70,8 @@ _DECODE_FP: str | None = None
KEY_SHEET_MAX = 8 # key frames on one shot's contact sheet
-def key_sheet_frames(video: Path, info, kf: list[dict], smp) -> tuple[list, list[float]]:
- """Frames for a shot's contact sheet: its key frames (at most KEY_SHEET_MAX, named roles first), else the evenly
- spaced samples."""
- from .survey import _grab
-
+def key_sheet_times(kf: list[dict]) -> list[float]:
+ """Times of a shot's contact-sheet frames: its key frames, at most KEY_SHEET_MAX, named roles first."""
rows = kf
if len(rows) > KEY_SHEET_MAX:
generic = [r.get("by") == "tool" and r.get("role") in ("change", "last") for r in rows]
@@ -84,12 +81,29 @@ def key_sheet_frames(video: Path, info, kf: list[dict], smp) -> tuple[list, list
ranked = sorted(range(1, len(rows)), key=lambda i: (generic[i], -float(rows[i].get("p") or 0)))
keep = set(ranked[:KEY_SHEET_MAX - 1]) | {0}
rows = [r for i, r in enumerate(rows) if i in keep]
- times = [float(r["t"]) for r in rows]
- if len(times) >= 2:
- frames = _grab(str(video), info, times, width=320)
- if len(frames) == len(times):
- return frames, times
- return smp.frames, smp.frame_times
+ return [float(r["t"]) for r in rows]
+
+
+def key_sheets(video: Path, info, kf_by_shot: dict[int, list[dict]]) -> dict[int, tuple[list, list[float]]]:
+ """{shot: (frames, times)} for every shot's contact sheet, from one decode of the video; a shot with fewer than two
+ key frames, or whose frames were not found, is left out (its sheet uses the evenly spaced samples)."""
+ from .survey import _grab
+
+ want = {i: t for i, kf in kf_by_shot.items() if len(t := key_sheet_times(kf)) >= 2}
+ flat = [t for ts in want.values() for t in ts]
+ got = _grab(str(video), info, flat, width=320, fill=False) if flat else []
+ out, k = {}, 0
+ for i, ts in want.items():
+ fr = got[k:k + len(ts)]
+ k += len(ts)
+ if len(fr) == len(ts) and any(f is not None for f in fr):
+ first = next(f for f in fr if f is not None)
+ out[i] = ([f if f is not None else first for f in fr], ts)
+ return out
+
+
+STILLS_BATCH_EVERY = 250 # first / last stills come from one decode when shots average fewer frames than this (decoding
+# runs ~1800 frames a second while a seek costs ~0.07 s even four at a time: one pass wins unless shots are very long)
def decode_fingerprint() -> str:
@@ -166,6 +180,33 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,
stems_job = stems_pool.submit(run_stems)
stems_pool.shutdown(wait=False)
+ # ---------------- shared decodes, alongside the packaging pass ---------------
+ # every shot's samples (all its frames, as collect_samples reads them), its contact-sheet frames and its full-size
+ # first / last frames come from whole-video decodes (a decode per shot starts from the key frame before it each
+ # time) running while the text is read
+ still_w = min(1080, info.display_size[0] or 1080) # never upscale; rotated video: displayed width
+ kf_by_shot = {s.index: keyframes.get(str(s.index)) or [{"frame": f, "t": round(s.t(f), 3), "role": "first" if f == s.start_frame else "change", "by": "tool"}
+ for f in key_frames(track, s.start_frame, s.end_frame)] for s in shots}
+ still_jobs = []
+ for s in shots:
+ sid = f"shot_{s.index:03d}"
+ still_jobs.append((s.start + min(0.05, s.duration / 4), out / "shots" / f"{sid}_first.jpg"))
+ still_jobs.append((max(s.start, s.end - min(0.08, s.duration / 4)), out / "shots" / f"{sid}_last.jpg"))
+ decode_pool = ThreadPoolExecutor(max_workers=3)
+ samples_job = decode_pool.submit(collect_all_samples, str(video), info, shots)
+ sheets_job = decode_pool.submit(key_sheets, video, info, kf_by_shot)
+ if track.n < STILLS_BATCH_EVERY * len(shots): # dense cuts: one decode beats a seek per still
+ times = track.times if track.times is not None else None
+
+ def first_at(t: float) -> int: # the frame a seek to t shows: the first one at or after t
+ if times is not None:
+ return min(track.n - 1, int(np.searchsorted(np.asarray(times), t - 1e-6)))
+ return min(track.n - 1, int(np.ceil(t * track.fps - 1e-6)))
+ stills_job = decode_pool.submit(extract_frames, video, [(first_at(t), p) for t, p in still_jobs], still_w)
+ else:
+ still_pool = ThreadPoolExecutor(max_workers=4)
+ stills_job = [still_pool.submit(extract_frame, video, t, p, still_w) for t, p in still_jobs]
+
# ---------------- packaging layer: subtitles / 花字 / stickers on one timeline ---------------
pack = None
if packaging:
@@ -183,18 +224,16 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,
shot_records: list[dict] = []
template_frames: list[np.ndarray] = []
- samples_by_shot = {}
+ samples_by_shot = samples_job.result()
+ sheets = sheets_job.result()
for s in shots:
- smp = collect_samples(str(video), info, s)
- samples_by_shot[s.index] = smp
+ smp = samples_by_shot[s.index]
if smp.frames:
template_frames.extend([smp.frames[0], smp.frames[-1]])
template = persistent_template(template_frames[:60]) if len(shots) >= 2 else {"frozen_ratio": 0.0, "boxes": []}
from .packaging import clean_region
- still_pool = ThreadPoolExecutor(max_workers=4)
- stills = []
for s in shots:
smp = samples_by_shot[s.index]
crop = clean_region(pack["stickers"], s.start, s.end) if pack else None
@@ -231,15 +270,9 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,
layers = overlay_layers(ov, text, template)
sid = f"shot_{s.index:03d}"
# key frames: the survey's (the AI's picks and names) when it ran, else the tool's: start, stop, turn, extreme
- kf = keyframes.get(str(s.index)) or [{"frame": f, "t": round(s.t(f), 3), "role": "first" if f == s.start_frame else "change", "by": "tool"}
- for f in key_frames(track, s.start_frame, s.end_frame)]
- sheet_frames, sheet_times = key_sheet_frames(video, info, kf, smp)
+ kf = kf_by_shot[s.index]
+ sheet_frames, sheet_times = sheets.get(s.index) or (smp.frames, smp.frame_times)
shot_sheet(sheet_frames, sheet_times, out / "shots" / f"{sid}.jpg", n=len(sheet_frames) if sheet_frames is not smp.frames else 4)
- still_w = min(1080, info.display_size[0] or 1080) # never upscale; rotated video: displayed width
- # full-resolution first / last frames (remake keyframes): ffmpeg runs in the background while the next shot is measured
- stills.append(still_pool.submit(extract_frame, video, s.start + min(0.05, s.duration / 4), out / "shots" / f"{sid}_first.jpg", still_w))
- stills.append(still_pool.submit(extract_frame, video, max(s.start, s.end - min(0.08, s.duration / 4)),
- out / "shots" / f"{sid}_last.jpg", still_w))
motion = None
if top(probs)[0] in ("code_render", "screen_capture") or facts.get("graphic_score", 0.0) >= 0.5:
# rendered picture: element-level motion timeline, key-frame strip and hex palette for a code remake
@@ -275,9 +308,13 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,
dl, dp = top(probs)
LOG.info("%s %s-%s det=%s(%.0f%%) %s", sid, fmt_time(s.start), fmt_time(s.end), dl, dp * 100, facts.get("temporal_family"))
- for job in stills:
- job.result()
- still_pool.shutdown()
+ if isinstance(stills_job, list):
+ for job in stills_job:
+ job.result()
+ still_pool.shutdown()
+ else:
+ stills_job.result()
+ decode_pool.shutdown()
# ---------------- VLM pass ------------------------------------------------------
# "used" means at least one VLM answer actually came back; "status" says why not otherwise.
diff --git a/rea_video/stems.py b/rea_video/stems.py
index 896369d..be584e3 100644
--- a/rea_video/stems.py
+++ b/rea_video/stems.py
@@ -28,6 +28,11 @@ GEN = CHUNK - 2 * TRIM
WINDOW = (0.5 - 0.5 * np.cos(2 * np.pi * np.arange(N_FFT) / N_FFT)).astype(np.float32) # periodic hann
+# threads per separation model: the models run alongside the picture analysis, and more threads than the machine's
+# performance cores only fight over them (4 is as fast as all of them alone, and leaves room; the output is the same)
+MODEL_THREADS = max(1, min(4, os.cpu_count() or 4))
+
+
def models_dir() -> Path:
return Path(os.getenv("REA_VIDEO_MODELS", str(Path.home() / ".cache/rea-video/models"))).expanduser()
diff --git a/rea_video/survey.py b/rea_video/survey.py
index 3e9397c..f75e2bb 100644
--- a/rea_video/survey.py
+++ b/rea_video/survey.py
@@ -22,6 +22,7 @@ it, probability), the stretches where a lot happens inside one shot, each shot's
curve of the whole video (the rhythm). decompose reads it to split the shots and to pick each shot's key frames."""
from __future__ import annotations
+import bisect
import json
import math
from concurrent.futures import ThreadPoolExecutor
@@ -232,26 +233,32 @@ def rhythm(track: FrameTrack, step: float = RHYTHM_STEP) -> list[float]:
# ------------------------------------------------------------------ sheets -----------------------------------------
-def _grab(video: str, info: VideoInfo, times: list[float], width: int = 160) -> list[np.ndarray]:
+def _grab(video: str, info: VideoInfo, times: list[float], width: int = 160, fill: bool = True) -> list:
"""Frames at the given times, one decode pass over the span they cover, keeping only the frame nearest each time
- (a whole video's overview never holds more than its tiles in memory)."""
+ (a whole video's overview never holds more than its tiles in memory). A time with no frame within one frame:
+ filled with the first frame found (fill), else None."""
if not times:
return []
order = sorted(range(len(times)), key=lambda k: times[k])
- t0, t1 = times[order[0]], times[order[-1]]
+ sorted_t = [times[k] for k in order]
+ t0, t1 = sorted_t[0], sorted_t[-1]
step = 1.0 / max(info.fps, 1)
best: dict[int, tuple[float, np.ndarray]] = {}
for i, f in enumerate(iter_frames(video, info, width, start=t0, duration=t1 - t0 + 2 * step)):
ft = t0 + i * step
- for k in order:
+ lo, hi = bisect.bisect_left(sorted_t, ft - step), bisect.bisect_right(sorted_t, ft + step)
+ for j in range(lo, hi):
+ k = order[j]
d = abs(ft - times[k])
if d <= step and (k not in best or d < best[k][0]):
best[k] = (d, f)
if not best:
- return []
+ return [] if fill else [None] * len(times)
got = [best.get(k, (0, None))[1] for k in range(len(times))]
- fill = next(f for f in got if f is not None)
- return [f if f is not None else fill for f in got]
+ if not fill:
+ return got
+ first = next(f for f in got if f is not None)
+ return [f if f is not None else first for f in got]
def tile_size(info: VideoInfo, look: str) -> tuple[int, int]: