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 格式输出。
Python agent-skillsai-videoaigc-detectionclaude-codecodexffmpegprompt-engineeringremotionreverse-engineeringshort-videoshot-detectionsubtitlesvideo-analysisvideo-breakdownvideo-editingvideo-generationvideomdvlm
优化视频复刻切点问题:镜头切细后拆解不变慢,跳剪镜头合并 VLM 调用
junecc88feefe962
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex daa7f72..0b0fc7b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -28,9 +28,19 @@制作方式准确率:labels / holdout / holdout2 为 100% → 99.2% / 99.5% → 99.7% / 100% → 100%。**速度和消耗**-- 切点判断本身几乎不变:13 分钟视频多 0.1 秒。-- 拆解时间随镜头数增加,每多一个镜头约多 1.5–2 秒(逐镜 OCR、采样、特征)。评测集整体镜头数多了 14%。以前漏切少的片子基本不变(166 秒口播:224 → 229 秒);跳剪密集、以前大量漏切的片子变化最大(72 秒开箱:镜头 29 → 68,100 → 173 秒)。-- 开 VLM 时每个镜头调用一次,调用次数随镜头数增加,每条视频最多 60 个镜头。++切得更细以后镜头变多(评测集整体 +14%),这一版同时把逐镜的开销压下来,拆解时间和 VLM 调用次数都没有因此上涨:+- 镜头上的文字直接取剪辑包装层整片 OCR 那一遍的结果,不再每个镜头另读 4 帧;整片 OCR 太稀(长视频)或关掉包装层时,按镜头时长读 1–4 帧。+- 全分辨率首尾帧(复刻的首帧参考)在后台抽取,和下一个镜头的计算并行。+- 跳剪连起来的几段是同一条素材剪开的,报告里标为「跳剪」。开 VLM 时合成一个片段问一次(最长 12 秒、最多 8 段):制作方式和拍法整段给一次,每段的内容描述和复刻提示词分开给。复刻计划里这几段照常合成同一个生成单元。+- VLM 调用次数到上限(60 次)时,优先给工具最拿不准、时长最长的镜头,不再只取前 60 个。++| 片子(不开 VLM) | 切点优化前 | 切点优化后 | 提速后 |+|---|---|---|---|+| 72 秒开箱 | 29 镜 100 秒 | 68 镜 173 秒 | 68 镜 104 秒 |+| 166 秒口播 | 62 镜 224 秒 | 69 镜 229 秒 | 69 镜 206 秒 |++镜头的制作方式判断、真实素材判断和字幕时间轴与提速前一致(全部评测集逐条对比)。开 VLM 时:开箱片 68 个镜头只需 24 次调用(按镜头调要到 60 次上限,最后 8 个镜头拿不到 VLM);夜景口播 69 个镜头 57 次,全部镜头都有 VLM 结果。**已知局限**- 手机录屏里的界面滑动、翻页动画仍会被当成切点。diff --git a/docs/decompose.md b/docs/decompose.mdindex 187fd99..48ccc04 100644--- a/docs/decompose.md+++ b/docs/decompose.md@@ -23,7 +23,7 @@| 问题 | 方法 | 可靠度 ||---|---|---|-| 哪里切镜 | HSV 直方图距离与像素差分,加局部自适应阈值;变化面积要足够大,元素弹出不算切镜。交叉溶解:中间帧是否为两端帧的线性混合,并用光流排除推拉运动 | 高(两条真值片 F1=1.0,其中一条含 14 处 0.25s 溶解) |+| 哪里切镜 | HSV 直方图距离与像素差分,加局部自适应阈值;变化面积要足够大,元素弹出不算切镜。跳剪 / 推近切:同机位一帧内的跳变,比前后几帧的变化高出很多且前后平稳;一两帧内亮了又恢复的闪光、火光不算切镜。交叉溶解:中间帧是否为两端帧的线性混合,并用光流排除推拉运动 | 高(两条真值片 F1=1.0,其中一条含 14 处 0.25s 溶解) || 画面动没动 | 逐像素完全重复帧的比例、首尾帧差 | 高 || 是不是一张图在推拉 | LK 光流拟合相似变换(RANSAC):内点率高、残差小、无局部运动,且运动补偿后几乎没有残余 | 高 || 渲染还是拍摄的纹理 | 平坦 8×8 块比例、覆盖 95% 像素所需颜色数、横竖直边比例、Immerkær 噪声 | 高(区分渲染与照片) |@@ -34,6 +34,8 @@| 叠加层 | 背景在动但像素冻结的边缘簇,加 OCR 文字轨(位置、是否随时间变化、是否水平) | 中高 || 音频 | 起音/节拍、切点落在起音上的比例(卡点)、语音调制特征 | 中 |+跳剪连起来的几段是同一条素材剪开的(同机位、同背景),开 VLM 时合成一个片段问一次(最长 12 秒、最多 8 段):制作方式和拍法整段给一次,每段的内容描述和复刻提示词分开给。VLM 调用次数有上限时,优先给工具最拿不准、时长最长的镜头。镜头上的文字直接取整片 OCR 那一遍在这段时间里读到的结果,整片 OCR 太稀(长视频)或关掉剪辑包装层时,才按镜头时长自己读 1–4 帧。+## 2.1 用户真实素材素材来源分为四种:AI 生成、制作方渲染、用户真实素材、混合。diff --git a/rea_video/overlay.py b/rea_video/overlay.pyindex 5652035..3741381 100644--- a/rea_video/overlay.py+++ b/rea_video/overlay.py@@ -160,6 +160,22 @@ def ocr_frames(frames: list[np.ndarray], times: list[float], max_frames: int = 4return results+def shot_ocr_items(whole: list[dict] | None, step: float, start: float, end: float) -> list[dict] | None:+ """The whole-video OCR pass already read this shot: its hits in [start, end), or None when that pass is+ missing or too sparse here (fewer than one read per 0.6 s, or no read inside the shot)."""+ if whole is None or not step or step > 0.6:+ return None+ first_read = np.ceil(start / step - 1e-6) * step # reads happen at 0, step, 2*step, ...+ if first_read >= end:+ return None+ return [dict(it, band=_band(it["bbox"][1] + it["bbox"][3] / 2, 1)) for it in whole if start <= it["t"] < end]+++def shot_ocr_frames(duration: float) -> int:+ """Frames to OCR for a shot of this length when the whole-video pass is not there: one per ~0.75 s, 1 to 4."""+ return int(min(4, max(1, np.ceil(duration / 0.75))))++def summarize_text(items: list[dict]) -> dict:"""Group OCR hits into tracks: same band + similar x-position."""if not items:diff --git a/rea_video/packaging.py b/rea_video/packaging.pyindex bd5a570..48d4945 100644--- a/rea_video/packaging.py+++ b/rea_video/packaging.py@@ -1243,7 +1243,8 @@ def analyze(path: str | Path, info: VideoInfo, cuts: list[float], out_dir: Pathkinds: dict[str, int] = {}for c in cues:kinds[c["kind"]] = kinds.get(c["kind"], 0) + 1- return {"text_cues": cues, "stickers": stickers, "ocr": {"step_s": round(step, 3), "frames": int(round(info.duration / step)) if step else 0,+ # the raw OCR hits go back to the caller for the per-shot text (popped before the breakdown is written)+ return {"_ocr_items": items, "text_cues": cues, "stickers": stickers, "ocr": {"step_s": round(step, 3), "frames": int(round(info.duration / step)) if step else 0,"dense_step_s": round(dstep, 3)},"counts": {"text": kinds, "stickers": len(stickers)}}diff --git a/rea_video/pipeline.py b/rea_video/pipeline.pyindex 0039376..0310944 100644--- a/rea_video/pipeline.py+++ b/rea_video/pipeline.py@@ -15,7 +15,7 @@ from .sound_source import MUSIC_ZH, classify_sound_sources, per_clip_audiofrom .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_contextfrom .features import collect_samples, crop_box, intersect_box, photo_letterbox, shot_featuresfrom .media import cut_clip, extract_frame, require_tools, video_info-from .overlay import ocr_frames, persistent_template, static_overlays, summarize_text+from .overlay import ocr_frames, persistent_template, shot_ocr_frames, shot_ocr_items, static_overlays, summarize_textfrom .plan import Plannerfrom .probe import provenancefrom .motion import element_crops, motion_events, palette, strip_frames@@ -25,7 +25,7 @@ from . import aspectsfrom .faces import shot_facesfrom .visual import LABEL_SHORT, shot_sheet, storyboardfrom .i18n import T, join, semi, set_lang-from .vlm import SHOT_PROMPT, WHOLE_PROMPT, VLMClient, VLMConfig, normalize_shot_result, normalize_whole, prompt_lang_note, shot_hints, vlm_note+from .vlm import SHOT_PROMPT, TAKE_NOTE, WHOLE_PROMPT, VLMClient, VLMConfig, normalize_shot_result, normalize_whole, prompt_lang_note, shot_hints, take_results, vlm_notedef _sha256_head(path: Path, limit: int = 64 << 20) -> str:@@ -35,6 +35,32 @@ def _sha256_head(path: Path, limit: int = 64 << 20) -> str:return h.hexdigest()+TAKE_MAX_S, TAKE_MAX_PIECES = 12.0, 8 # one VLM look at most this long / this many jump-cut pieces+++def vlm_units(records: list[dict], max_calls: int) -> list[list[dict]]:+ """Group shots for the VLM: jump-cut pieces of one take (same camera setup, cut apart in the edit) are one+ clip and one call; every other shot is its own call. Past `max_calls`, the calls go to the units the+ pixel statistics are least sure about, weighted by length, rather than to the first ones in the video."""+ units: list[list[dict]] = []+ for r in records:+ u = units[-1] if units else None+ if (u and r.get("transition_in") == "jump" and len(u) < TAKE_MAX_PIECES+ and r["end"] - u[0]["start"] <= TAKE_MAX_S):+ u.append(r)+ else:+ units.append([r])+ if len(units) <= max_calls:+ return units++ def need(u: list[dict]) -> float:+ sure = min(top(r["deterministic"]["probs"])[1] for r in u)+ return (u[-1]["end"] - u[0]["start"]) * (1.05 - sure)++ keep = sorted(sorted(range(len(units)), key=lambda k: -need(units[k]))[:max_calls])+ return [units[k] for k in keep]++def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False, whole_vlm: bool = True,ocr: bool = True, workers: int = 3, engine: str = "seedance2.0", max_shots_vlm: int = 60,platform_meta: dict | None = None, stems: bool = True, memory: bool = True, packaging: bool = True,@@ -75,6 +101,8 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,ev = [e for e in visual_events(pack["text_cues"], pack["stickers"], []) if e["type"] != "subtitle_in"]pack["sfx_anchored"] = anchored_sfx(video, ev, (audio.get("sfx") or {}).get("events", []))pack["version"] = PACKAGING_VERSION+ ocr_items = pack.pop("_ocr_items", None) if pack else None # whole-video OCR hits, reused per shot below+ ocr_step = float((pack or {}).get("ocr", {}).get("step_s") or 0.0)shot_records: list[dict] = []template_frames: list[np.ndarray] = []@@ -88,6 +116,8 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,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@@ -104,7 +134,13 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,if crop and not lbox:feats["measured_region"] = list(crop)ov = static_overlays(smp.frames)- text = summarize_text(ocr_frames(smp.frames, smp.frame_times)) if ocr else {"tracks": [], "text_coverage": 0.0, "items": []}+ if ocr:+ hits = shot_ocr_items(ocr_items, ocr_step, s.start, s.end)+ if hits is None: # no whole-video pass, or too sparse here: read a few of this shot's own frames+ hits = ocr_frames(smp.frames, smp.frame_times, max_frames=shot_ocr_frames(s.duration))+ text = summarize_text(hits)+ else:+ text = {"tracks": [], "text_coverage": 0.0, "items": []}embedded = detect_embedded(smp.frames, text.get("items"))# faces, framing and light are read on the picture itself (inside the letterbox), not on the barspic = [crop_box(f, lbox["box"]) for f in smp.frames] if lbox else smp.frames@@ -119,8 +155,10 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,sid = f"shot_{s.index:03d}"shot_sheet(smp.frames, smp.frame_times, out / "shots" / f"{sid}.jpg")still_w = min(1080, info.display_size[0] or 1080) # never upscale; rotated video: displayed width- extract_frame(video, s.start + min(0.05, s.duration / 4), out / "shots" / f"{sid}_first.jpg", width=still_w)- extract_frame(video, max(s.start, s.end - min(0.08, s.duration / 4)), out / "shots" / f"{sid}_last.jpg", width=still_w)+ # 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 = Noneif 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@@ -148,6 +186,10 @@ 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()+# ---------------- VLM pass ------------------------------------------------------# "used" means at least one VLM answer actually came back; "status" says why not otherwise.vlm_info = {"used": False, "requested": use_vlm, "status": "off"}@@ -161,31 +203,49 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,client = VLMClient(cfg, out / "vlm_cache")vlm_info = {"used": False, "requested": True, "status": "failed", "model": cfg.describe(), "media": cfg.media, "errors": []}- def run_shot(rec: dict) -> None:+ def run_unit(unit: list[dict]) -> None:+ """One VLM call per unit: a single shot, or the jump-cut pieces of one take seen as one clip."""+ first, last = unit[0], unit[-1]+ span = last["end"] - first["start"]media = []if cfg.media in ("both", "video"):- clip = cut_clip(video, rec["start"], min(rec["duration"], 12.0), out / "clips" / f"{rec['id']}.mp4", width=480)+ clip = cut_clip(video, first["start"], min(span, 12.0), out / "clips" / f"{first['id']}.mp4", width=480)media.append((clip, "video/mp4"))if cfg.media in ("both", "frames"):- media += [(out / rec["assets"]["first_frame"], "image/jpeg"), (out / rec["assets"]["sheet"], "image/jpeg"),- (out / rec["assets"]["last_frame"], "image/jpeg")]- dl, dp = top(rec["deterministic"]["probs"])- prompt = SHOT_PROMPT.format(hints=shot_hints(rec["features"], rec["deterministic"]["facts"], dl, dp)) + prompt_lang_note()+ mid = unit[len(unit) // 2]+ media += [(out / first["assets"]["first_frame"], "image/jpeg"), (out / mid["assets"]["sheet"], "image/jpeg"),+ (out / last["assets"]["last_frame"], "image/jpeg")]+ lead = max(unit, key=lambda r: r["duration"])+ dl, dp = top(lead["deterministic"]["probs"])+ prompt = SHOT_PROMPT.format(hints=shot_hints(lead["features"], lead["deterministic"]["facts"], dl, dp))+ if len(unit) > 1:+ prompt += TAKE_NOTE.format(n=len(unit), cuts=", ".join(f"{r['start'] - first['start']:.2f}" for r in unit[1:]))+ prompt += prompt_lang_note()+ fallback = Nonetry:- rec["vlm"] = normalize_shot_result(client.ask_json(prompt, media))+ raw = client.ask_json(prompt, media)except Exception as exc: # keep going; deterministic result stands+ raw = Noneif cfg.media == "both":try:- frames_only = [m for m in media if m[1] != "video/mp4"]- rec["vlm"] = normalize_shot_result(client.ask_json(prompt, frames_only))- rec["vlm"]["_fallback"] = "frames_only"- return+ raw = client.ask_json(prompt, [m for m in media if m[1] != "video/mp4"])+ fallback = "frames_only"except Exception as exc2: # pragma: no coverexc = exc2- vlm_info["errors"].append(f"{rec['id']}: {str(exc)[:160]}")-+ if raw is None:+ vlm_info["errors"].append(f"{first['id']}: {str(exc)[:160]}")+ return+ answers = take_results(raw, len(unit)) if len(unit) > 1 else [raw]+ for i, (rec, ans) in enumerate(zip(unit, answers)):+ rec["vlm"] = normalize_shot_result(ans)+ if fallback:+ rec["vlm"]["_fallback"] = fallback+ if len(unit) > 1:+ rec["vlm"]["take"] = {"shots": [r["index"] for r in unit], "piece": i + 1}++ units = vlm_units(shot_records, max_shots_vlm)with ThreadPoolExecutor(max_workers=max(1, workers)) as pool:- list(pool.map(run_shot, shot_records[:max_shots_vlm]))+ list(pool.map(run_unit, units))if whole_vlm:try:low = cut_clip(video, 0, info.duration, out / "clips" / "whole_480p.mp4", width=480, audio=True, crf=30)@@ -193,9 +253,9 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,whole = normalize_whole(client.ask_json(WHOLE_PROMPT.format(shots=cuts) + prompt_lang_note(), [(low, "video/mp4")], max_tokens=6000))except Exception as exc:vlm_info["errors"].append(f"whole: {str(exc)[:160]}")- asked = shot_records[:max_shots_vlm]+ asked = [r for u in units for r in u]ok_shots = sum(1 for r in asked if r.get("vlm"))- vlm_info.update(ok_shots=ok_shots, asked_shots=len(asked), whole_ok=whole is not None)+ vlm_info.update(ok_shots=ok_shots, asked_shots=len(asked), calls=len(units), whole_ok=whole is not None)if ok_shots == len(asked) and (whole is not None or not whole_vlm):vlm_info.update(used=True, status="ok")elif ok_shots or whole is not None:diff --git a/rea_video/production.py b/rea_video/production.pyindex 772682e..0d20019 100644--- a/rea_video/production.py+++ b/rea_video/production.py@@ -176,7 +176,7 @@ def _runs(shots: list[dict], same_scene, labels: tuple) -> list[list[dict]]:runs.append(cur)cur, gap = [], Falsecontinue- joinable = cur and same_scene(cur[-1], r) and (gap or r.get("transition_in") in ("cut", "flash"))+ joinable = cur and same_scene(cur[-1], r) and (gap or r.get("transition_in") in ("cut", "jump", "flash"))if cur and not joinable:runs.append(cur)cur = []@@ -265,7 +265,7 @@ def _unit(seg: list[dict], k: int, lim: dict, model: dict | None, style: str, ca+ T(":参考动作、运镜和剪辑节奏(只作参考,不复制画面)",": reference for action, camera movement and cutting rhythm (reference only, do not copy the picture)"), "user": False})cont = None- if prev_unit and same_scene_prev and seg[0].get("transition_in") in ("cut", "flash") and abs(prev_unit["ranges"][-1][1] - t0) < 1e-3:+ if prev_unit and same_scene_prev and seg[0].get("transition_in") in ("cut", "jump", "flash") and abs(prev_unit["ranges"][-1][1] - t0) < 1e-3:cont = T("首帧用 {p} 的尾帧,接上动作", "first frame = last frame of {p}, continue the action", p=prev_unit["id"])elif lim["first_frame"]:cont = T("首帧:参照原片第 {i} 镜首帧({f})的构图出图", "first frame: generate an image matching the composition of source shot {i}'s first frame ({f})",diff --git a/rea_video/report.py b/rea_video/report.pyindex 18f8f19..4e87563 100644--- a/rea_video/report.py+++ b/rea_video/report.py@@ -147,8 +147,8 @@ def _span(a, z) -> str:# ------------------------------------------------------------------ sections ---------------------------------------TRANS_ZH = LangDict({"cut": "硬切", "flash": "闪亮切", "fade": "淡入淡出", "dissolve": "叠化", "mg_transition": "版式切换"},- en={"cut": "cut", "flash": "flash cut", "fade": "fade", "dissolve": "dissolve", "mg_transition": "layout change"})+TRANS_ZH = LangDict({"cut": "硬切", "jump": "跳剪", "flash": "闪亮切", "fade": "淡入淡出", "dissolve": "叠化", "mg_transition": "版式切换"},+ en={"cut": "cut", "jump": "jump cut", "flash": "flash cut", "fade": "fade", "dissolve": "dissolve", "mg_transition": "layout change"})def _head_md(b: dict) -> list[str]:diff --git a/rea_video/shots.py b/rea_video/shots.pyindex 7f6a905..d83fa99 100644--- a/rea_video/shots.py+++ b/rea_video/shots.py@@ -143,12 +143,16 @@ def detect_shots(track: FrameTrack, min_shot_s: float = 0.35, cut_threshold: flo# frames; a filmed screen whose content changes keeps sensor noise, 0.002-0.03, and is not a cut)still_swap = (s > cut_threshold and track.hist_dist[i] > 0.25 and chg[i] > 0.18 and chg_base[i] < 0.01and s > base[i] * 5 + 0.1 and i >= 3 and float(track.pix_diff[i - 3:i].max()) < 1e-3)- if strong or relative or still_swap or _jump_cut(track, i):+ jump = _jump_cut(track, i)+ if strong or relative or still_swap or jump:# a muzzle flash / strobe, or the frame where a one- or two-frame flash or glitch ends: the picture# is back to what it was, so nothing was cutif _brief_flash(track, i) or _back_to_before(track.thumbs, i):continue- boundaries[i] = ("cut", float(max(s, chg[i])))+ # a jump cut keeps the camera setup: same colours, less than half the frame changes. Shots joined by+ # jump cuts are pieces of one take (one VLM look, one generation in the remake plan)+ same_take = jump and track.hist_dist[i] < 0.4 and chg[i] < 0.5+ boundaries[i] = ("jump" if same_take else "cut", float(max(s, chg[i])))# 2) fades through black / white: luma dips to an extreme and comes backlo_l = min(10.0, float(np.percentile(track.luma, 50)) * 0.35)@@ -237,7 +241,7 @@ def detect_shots(track: FrameTrack, min_shot_s: float = 0.35, cut_threshold: flodef _clean_cut(boundaries: dict[int, tuple[str, float]], b: int) -> bool:kind, strength = boundaries[b]- return kind == "cut" and strength >= 0.35+ return kind in ("cut", "jump") and strength >= 0.35def _brief_flash(track: FrameTrack, i: int) -> bool:diff --git a/rea_video/vlm.py b/rea_video/vlm.pyindex 4d20fb9..3933ec5 100644--- a/rea_video/vlm.py+++ b/rea_video/vlm.py@@ -10,6 +10,7 @@ REA_VLM_MEDIA = both | video | frames (default both: a short clip as data:videofrom __future__ import annotationsimport base64+import copyimport hashlibimport jsonimport os@@ -250,6 +251,33 @@ AI 仿定格风格(材质在帧间漂移)与真正的定格动画(同一}}"""+# appended to SHOT_PROMPT when one clip covers several jump-cut pieces of the same take+TAKE_NOTE = """+这段片子是同一机位、同一条素材剪成的 {n} 段(跳剪),后面几段从片段开头后 {cuts} 秒开始。+制作方式、拍法和素材(label_probs、aspects、embedded_assets 等)对整段给一次即可;+另外加一个 segments 数组,按顺序给每一段的内容,共 {n} 项:+"segments": [{{"description": "这一段的主体、动作和结束状态", "replication": {{"video_prompt": "复刻这一段的中文视频提示词", "video_prompt_en": "same in English"}}}}]+"""+++def take_results(raw: dict, n: int) -> list[dict]:+ """Split one answer about a jump-cut take into per-piece answers: the shared verdict, with each piece's own+ description and video prompt when the model gave one per piece."""+ segs = raw.pop("segments", None)+ segs = segs if isinstance(segs, list) and len(segs) == n else [None] * n+ out = []+ for seg in segs:+ r = copy.deepcopy(raw)+ if isinstance(seg, dict):+ if isinstance(seg.get("description"), str) and seg["description"].strip():+ r["description"] = seg["description"]+ rep = seg.get("replication")+ if isinstance(rep, dict):+ r["replication"] = {**(r.get("replication") or {}), **{k: v for k, v in rep.items() if isinstance(v, str) and v.strip()}}+ out.append(r)+ return out++WHOLE_PROMPT = """你是短视频拆解专家。完整观看并**仔细收听**这条视频,拆解它的结构、文案、声音与整体制作方式。声音要拆到可以复刻:旁白是真人还是 TTS、音色;背景音乐的风格/情绪/节奏/是否 AI 生成或知名歌曲;判断音乐来源时结合视频形式:AI 音乐 MV(整片一首歌、歌词唱的就是画面内容)大概率是 AI 生成的歌;普通视频的垫底配乐大概率是现成曲库;diff --git a/tests/test_vlm_take.py b/tests/test_vlm_take.pynew file mode 100644index 0000000..6768d39--- /dev/null+++ b/tests/test_vlm_take.py@@ -0,0 +1,108 @@+"""Jump-cut pieces of one take share one VLM call; the call budget goes where the pixels are least sure."""+import json+import threading+from http.server import BaseHTTPRequestHandler, HTTPServer++import numpy as np+import pytest++from rea_video.overlay import shot_ocr_frames, shot_ocr_items+from rea_video.pipeline import decompose, vlm_units+from rea_video.vlm import take_results+from tests.conftest import _photo_like, _write+from tests.test_shots import H, W, _speaker+++def _rec(i, start, end, trans="cut", sure=0.9):+ return {"index": i, "id": f"shot_{i:03d}", "start": start, "end": end, "duration": end - start, "transition_in": trans,+ "deterministic": {"probs": {"live_action": sure, "ai_video": 1 - sure}}}+++def test_jump_pieces_form_one_unit_up_to_the_clip_limit():+ recs = [_rec(1, 0, 2, "start"), _rec(2, 2, 4, "jump"), _rec(3, 4, 6, "jump"), _rec(4, 6, 8, "cut"),+ _rec(5, 8, 15, "jump"), _rec(6, 15, 21, "jump")]+ units = vlm_units(recs, 60)+ assert [[r["index"] for r in u] for u in units] == [[1, 2, 3], [4, 5], [6]] # 4+5 is 9 s; adding 6 would be 15 s+++def test_call_budget_goes_to_uncertain_long_units_in_time_order():+ recs = [_rec(1, 0, 1, "start", 0.95), _rec(2, 1, 5, "cut", 0.5), _rec(3, 5, 6, "cut", 0.55), _rec(4, 6, 9, "cut", 0.9)]+ assert [u[0]["index"] for u in vlm_units(recs, 2)] == [2, 3]+++def test_take_answer_is_split_per_piece():+ raw = {"label_probs": {"live_action": 1}, "description": "整段", "replication": {"image_prompt": "首帧", "video_prompt": "整段动作"},+ "segments": [{"description": "拆开盒子", "replication": {"video_prompt": "双手拆开纸盒"}},+ {"description": "拿出杯子", "replication": {"video_prompt": "从盒里拿出水杯"}}]}+ a, b = take_results(raw, 2)+ assert a["description"] == "拆开盒子" and b["replication"]["video_prompt"] == "从盒里拿出水杯"+ assert a["replication"]["image_prompt"] == "首帧" and "segments" not in a # shared fields stay, pieces do not leak+ c, d = take_results({"description": "整段", "segments": [{"description": "只有一段"}]}, 2) # wrong count: shared answer+ assert c["description"] == d["description"] == "整段"+++def test_shot_text_comes_from_the_whole_video_ocr_pass():+ whole = [{"t": 1.0, "text": "字幕", "conf": 0.9, "bbox": [0.2, 0.8, 0.6, 0.05], "angle": 0.0},+ {"t": 2.0, "text": "下一句", "conf": 0.9, "bbox": [0.2, 0.8, 0.6, 0.05], "angle": 0.0}]+ hits = shot_ocr_items(whole, 0.5, 0.8, 1.6)+ assert [h["text"] for h in hits] == ["字幕"] and hits[0]["band"] == "bottom"+ assert shot_ocr_items(whole, 0.5, 1.6, 1.9) is None # no read inside this shot: read its own frames+ assert shot_ocr_items(whole, 2.5, 0, 3) is None # too sparse (long video): read its own frames+ assert [shot_ocr_frames(d) for d in (0.3, 1.2, 6.0)] == [1, 2, 4]+++TAKE = {"label_probs": {"live_action": 0.9, "ai_video": 0.1}, "image_source": "photo", "evidence": ["手持轻微抖动"],+ "description": "整条口播", "shot_size": "近景", "camera_move": "固定", "style": "实拍",+ "replication": {"image_prompt": "人物近景", "video_prompt": "人物对镜头说话"}}+++class Handler(BaseHTTPRequestHandler):+ seen = []++ def do_POST(self): # noqa: N802+ body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))+ text = body["messages"][0]["content"][-1]["text"]+ Handler.seen.append(text)+ if "label_probs" in text:+ n = text.count("segments 数组") and int(text.split("剪成的 ")[1].split(" 段")[0])+ payload = dict(TAKE, segments=[{"description": f"第{k + 1}段", "replication": {"video_prompt": f"第{k + 1}段动作"}}+ for k in range(n)]) if n else TAKE+ else:+ payload = {"summary": "测试", "segments": []}+ data = json.dumps({"choices": [{"message": {"content": json.dumps(payload, ensure_ascii=False)}}]}).encode()+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(data)))+ self.end_headers()+ self.wfile.write(data)++ def log_message(self, *a):+ pass+++def fake_server(monkeypatch):+ Handler.seen = []+ srv = HTTPServer(("127.0.0.1", 0), Handler)+ threading.Thread(target=srv.serve_forever, daemon=True).start()+ monkeypatch.setenv("REA_VLM_BASE_URL", f"http://127.0.0.1:{srv.server_port}/v1")+ monkeypatch.setenv("REA_VLM_API_KEY", "test")+ monkeypatch.setenv("REA_VLM_MODEL", "fake-model")+ yield Handler+ srv.shutdown()+++def test_jump_cut_take_is_one_vlm_call(tmp_path, fake_server):+ rng = np.random.default_rng(2)+ bg = _photo_like(W, H, 5)+ frames = [_speaker(bg, 180, 160, t, rng) for t in range(45)]+ frames += [_speaker(bg, 120, 210, t, rng) for t in range(45, 90)]+ frames += [_speaker(bg, 200, 150, t, rng) for t in range(90, 135)]+ p = _write(frames, tmp_path / "take.mp4")+ b = decompose(p, tmp_path / "o", use_vlm=True, whole_vlm=False, ocr=False, workers=1, stems=False, packaging=False, memory=False)+ shots = b["shots"]+ assert [s["transition_in"] for s in shots] == ["start", "jump", "jump"]+ assert sum("label_probs" in t for t in fake_server.seen) == 1 # one look at the whole take+ assert [s["vlm"]["description"] for s in shots] == ["第1段", "第2段", "第3段"]+ assert all(s["vlm"]["take"]["shots"] == [1, 2, 3] for s in shots)+ assert b["analysis"]["vlm"]["calls"] == 1 and b["analysis"]["vlm"]["ok_shots"] == 3