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
Look at the whole video first, then closer where it needs it
june2a77f914d2e9
diff --git a/docs/cli.md b/docs/cli.mdindex 536516b..e886b4e 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -44,6 +44,8 @@ rea-video decompose ref.mp4 -o out/ref --vlmopen out/ref/report.html# 3. 没有 VLM,但 agent 自己能看图(zcode、Claude Code 等多模态 agent):让 agent 当 VLM+rea-video survey ref.mp4 -o out/ref # 先看全片总览再局部细看:定切点、转场和每镜关键帧(答完再跑同一条命令,直到 done)+rea-video decompose ref.mp4 -o out/ref # 镜头按 survey 的切点切分rea-video review out/ref # 生成逐镜看图任务和答案模板rea-video apply-review out/ref --by zcode # agent 填完答案后并入结论和报告@@ -94,6 +96,7 @@ rea-video capsule-draft out/ref/breakdown.json --capsule-root $CC --capsule-name| 命令 | 作用 ||---|---|| `decompose VIDEO [--vlm] [--no-ocr] [--ocr-lang zh\|ja\|ko] [--lang zh\|en] [--no-packaging] [--max-vlm-shots N] [--no-asr] [--asr-lang auto\|bn] [--no-speakers]` | 拆解,输出 breakdown.json、report.html/md、拆片包(`VIDEO.md` + `video/`)、storyboard.jpg、每镜首尾帧,`packaging/`(字幕 SRT、带样式的 ASS、包装时间轴、贴纸截图),以及 `sfx/`(每处音效从原片剪出的一小段,报告音效表里可直接试听);`--lang en` 让结论、报告、`summary` 输出和 VLM 描述都用英文(默认中文;agent 按用户提问的语言选,`rea-video prefs lang en` 可设成默认;breakdown.json 里的 `*_zh` 字段名保留,内容跟报告语言走);`--no-packaging` 跳过包装层(省约每分钟 30–50 秒);`--ocr-lang ja` 用日文识别模型读字幕和花字(首次使用自动下载约 10 MB 到 `$REA_VIDEO_MODELS`,离线时可用 `$REA_OCR_REC_MODEL` 指向本地模型),`rea-video prefs ocr_lang ja` 可设成默认;`--ocr-lang ko` 同理用韩文识别模型(PP-OCRv5,约 14 MB),并关掉文字方向分类(它会把韩文行误判成倒置、读成乱码);`--max-vlm-shots N` 是最多发给 VLM 的调用数(默认 60),镜头更多时先看最拿不准的,其余只靠确定性取证,`VLM:` 一行会写明送了多少个;装了可选的 `rea-video[asr]` 时会在人声干声上做本地语音识别,带时间的台词写进 `speech.lines` 和报告的脚本表(机器听写,未校对),`--no-asr` 跳过;台词是孟加拉语时加 `--asr-lang bn`,换用孟加拉语识别模型(SenseVoice 不认孟加拉语,会听成英/日/韩文;首次使用自动下载约 90 MB 到 `$REA_VIDEO_MODELS`),`rea-video prefs asr_lang bn` 可设成默认 |+| `survey VIDEO [-o OUT_DIR] [--vlm] [--no-detail] [--workers N]` | 先看后拆:第一轮把全片等距排成总览图,问每两格之间是同一画面、画面变化多、硬切、转场还是看不清;转场和看不清的地方下一轮加密抽帧再看(转场按变化最大的帧抽,同一轮的任务可以并发,最多三轮);切点定下来后逐镜出候选关键帧(动作起止、转折、元素出入),让 AI 挑出关键帧并标明是哪一种。问答是 JEV 格式:`state` 放材料,问题带 `criteria`,答案只写选项和概率。结果写进 `survey/timeline.json`(切点、转场时长、每镜关键帧、镜头长度、画面变化曲线、每段底层画面判断),decompose 按它切镜,报告和拆片包的「节奏与关键帧」也来自它。没有 VLM 时由 agent 回答:命令输出要看的图和要写的答案文件,答完再跑同一条命令;`--vlm` 用配置的模型自动答;decompose 开了 VLM 时会自动先跑(`--no-survey` 跳过) || `review OUT_DIR` | 给能看图的 agent 生成逐镜看图任务(review_tasks.json)和答案模板(review_answers.json) || `apply-review OUT_DIR [ANSWERS] [--by NAME] [--lang zh\|en]` | 把 agent 看图的答案和确定性结果融合,重写 breakdown.json 和报告;`--lang` 可以在这一步换报告语言(结论、证据和报告文字重新生成,VLM 已写好的描述和提示词保持原语言) || `correct OUT_DIR --shots N --label L [--real yes/no] [--note]` | 用户指出判错:改正结论和报告,并记入记忆(以后同一文件自动套用,同类镜头复核时提示) |diff --git a/docs/videomd.md b/docs/videomd.mdindex d2dc429..6a75ec6 100644--- a/docs/videomd.md+++ b/docs/videomd.md@@ -25,10 +25,11 @@| `video/content.md` | 内容与结构、叙事线、台词 || `video/cast.md` | 角色、场景、道具 || `video/sound.md` | 人声、BGM、音效、节拍和来源 |+| `video/rhythm.md` | 节奏与关键帧:每分钟几刀、镜头长度、画面变化曲线(每 0.5 秒一位数字)、切点和转场的时间与时长、每镜关键帧(时间 + 是哪一种:首帧、动作开始 / 到位、转折、元素出入、构图变化、表情峰值、转场中段……) || `video/look.md` | 实拍镜头的景别、机位、打光、剪辑和器材(有实拍镜头时) || `video/packaging.md` | 字幕、花字、贴纸、画中画的时间和样式 || `video/remake.md` | 复刻方案:生成单元、拍摄场次、代码合成、要准备的真实素材、表演与情绪 |-| `video/shots/<编号>.md` | 每镜的 `inferred`(制作方式、概率、次选、由谁判定、有没有真实素材)、`flags`、`frames`;正文是看得到的、推断和依据、提示词 |+| `video/shots/<编号>.md` | 每镜的 `inferred`(制作方式、概率、次选、由谁判定、有没有真实素材)、`flags`、`keyframes`(时间和种类)、`frames`;正文是看得到的、推断和依据、提示词 || `breakdown.json`、`shots/`、`stems/`、`sfx/`、`packaging/`、`frames/`(有代码渲染镜头时才有)、`storyboard.jpg`、`audio.png` | 完整数据和媒体文件,地图里都列着 |没有内容的主题文件不生成。diff --git a/rea_video/cli.py b/rea_video/cli.pyindex ee1368b..8f8e1d0 100644--- a/rea_video/cli.py+++ b/rea_video/cli.py@@ -87,13 +87,43 @@ def cmd_decompose(args) -> int:b = decompose(args.video, out, use_vlm=use_vlm, whole_vlm=not args.no_whole, ocr=not args.no_ocr,workers=args.workers, engine=args.engine or pref("engine"), platform_meta=meta, stems=stems,packaging=not args.no_packaging, lang=lang, asr=not args.no_asr, max_shots_vlm=max(1, args.max_vlm_shots),- speakers=not args.no_speakers)+ speakers=not args.no_speakers, survey=not args.no_survey)print(json.dumps({"out": str(out), "verdict": b["summary"]["verdict"], "shots": b["summary"]["shots"],"confidence": b["summary"]["confidence"], "vlm": b["summary"]["vlm"],"report": str(out / "report.html")}, ensure_ascii=False, indent=2))return 0+def cmd_survey(args) -> int:+ from .media import video_info+ from .memory import pref+ from .shots import build_track, detect_shots+ from .survey import run, vlm_asker++ out = Path(args.out) if args.out else Path("out") / Path(args.video).stem+ info = video_info(args.video)+ track = build_track(str(args.video), info)+ asker = None+ if args.vlm or (pref("vlm") == "on" and not args.no_vlm):+ _check_vlm_config()+ from .vlm import VLMClient, VLMConfig, prompt_lang_note++ cfg = VLMConfig.from_env()+ if cfg is None:+ raise SystemExit("rea-video: --vlm 需要 VLM 配置(REA_VLM_BASE_URL / REA_VLM_API_KEY / REA_VLM_MODEL)")+ asker = vlm_asker(VLMClient(cfg, out / "vlm_cache"), prompt_lang_note())+ res = run(Path(args.video).expanduser().resolve(), out.expanduser().resolve(), track, detect_shots(track), info,+ asker=asker, workers=args.workers, detail=not args.no_detail)+ if res["status"] == "waiting":+ res["next"] = T("看 images 里的图,按 tasks 里的问题把答案写进 waiting 里的文件(各文件互不相关,可以并发),再运行同一条命令",+ "look at the images, answer the questions in tasks into the waiting files (independent: can run in parallel), then run the same command again")+ else:+ res["next"] = T("运行 rea-video decompose(同一个 -o),镜头按这次的切点切分,关键帧和节奏写进报告",+ "run rea-video decompose (same -o): shots follow these cuts, key frames and rhythm go into the report")+ print(json.dumps(res, ensure_ascii=False, indent=1))+ return 0++def cmd_review(args) -> int:"""Write review_tasks.json + review_answers.json so a multimodal agent can act as the VLM."""from .review import build_tasks@@ -695,6 +725,7 @@ def main(argv: list[str] | None = None) -> int:d.add_argument("--no-asr", action="store_true", help="不做本地语音识别(装了 rea-video[asr] 才会做:在人声干声上识别台词和时间,首次使用下载约 160 MB 模型)")d.add_argument("--asr-lang", choices=ASR_LANGS, help="台词的语言:auto(默认,SenseVoice 自动识别中/英/日/韩/粤)、bn 孟加拉语(换用孟加拉语识别模型,首次使用自动下载约 90 MB);也可用 prefs asr_lang 设成默认")d.add_argument("--no-speakers", action="store_true", help="不区分说话人(装了 rea-video[asr] 才会做:在人声干声上分出谁在什么时候说话,多人时每人输出一条 stems/voice_S1.wav;首次使用下载约 35 MB 模型)")+ d.add_argument("--no-survey", action="store_true", help="开 VLM 时也不做总览 + 局部细看(只用切镜检测器的切点)")d.add_argument("--no-stems", action="store_true", help="不做人声/配乐分离(默认会输出 stems/original.wav、vocals.wav、music.wav)")d.set_defaults(func=cmd_decompose)@@ -818,6 +849,15 @@ def main(argv: list[str] | None = None) -> int:pd.add_argument("out_dir")pd.set_defaults(func=cmd_pdf)+ sv = sub.add_parser("survey", help="先看全片总览再局部细看:定切点、转场和每镜关键帧(JEV 格式问答);decompose 会按结果切镜")+ sv.add_argument("video")+ sv.add_argument("-o", "--out")+ sv.add_argument("--vlm", action="store_true", help="用配置的 VLM 自动回答每一轮(同一轮的任务并发)")+ sv.add_argument("--no-vlm", action="store_true", help="本次不用 VLM(覆盖 prefs 里的 vlm=on):输出任务,由能看图的 agent 回答")+ sv.add_argument("--no-detail", action="store_true", help="只定切点,不逐镜挑关键帧")+ sv.add_argument("--workers", type=int, default=4, help="VLM 并发数")+ sv.set_defaults(func=cmd_survey)+rv = sub.add_parser("review", help="能看图的 agent 当 VLM:生成逐镜看图任务和答案模板")rv.add_argument("out_dir", help="decompose 的输出目录")rv.add_argument("--force", action="store_true", help="覆盖已有的 review_answers.json")diff --git a/rea_video/code_remake.py b/rea_video/code_remake.pyindex d8ed755..f3aa59d 100644--- a/rea_video/code_remake.py+++ b/rea_video/code_remake.py@@ -38,7 +38,9 @@ def build_spec(out: Path) -> dict:b = read_json(out / "breakdown.json")src = b.get("source") or {}fdir = out / "frames"- if not (fdir / "scenes.json").exists():+ want = sorted(s.get("index") for s in b.get("shots", []) if shot_label(s) == "code_render")+ have = sorted({sc.get("shot") for sc in read_json(fdir / "scenes.json").get("scenes", [])}) if (fdir / "scenes.json").exists() else None+ if have is None or have != want: # the labels changed since (a review, the survey): measure the shots they name nowscene_frames(out, breakdown=b)scenes = read_json(fdir / "scenes.json").get("scenes", [])shots = {s.get("index"): s for s in b.get("shots", [])}@@ -101,7 +103,7 @@ def match(out: Path, spec_path: Path, rounds: int = 5) -> list[dict]:if e["draw"] == "points" and got["cover"] > 0 and want["cover"] > 0:e["count"] = int(np.clip(e["count"] * (want["cover"] / got["cover"]) ** 0.9, 150, 40000))# amount first: brightness also moves how much stands out, so it is matched only once the count settles- if k >= rounds // 2 and got["lit"] > 0 and want["lit"] > 0:+ if e["draw"] == "points" and k >= rounds // 2 and got["lit"] > 0 and want["lit"] > 0: # a cut-out keeps its own colourse["gain"] = round(float(np.clip(e["gain"] * want["lit"] / got["lit"], 0.5, 4.0)), 3)if e.get("glow") and got["rest"] > 1 and want["rest"] > 1:e["glow"]["strength"] = round(float(np.clip(e["glow"]["strength"] * want["rest"] / got["rest"], 0.2, 3.0)), 3)diff --git a/rea_video/layers.py b/rea_video/layers.pyindex 63022cc..1e60195 100644--- a/rea_video/layers.py+++ b/rea_video/layers.py@@ -142,22 +142,42 @@ def sample_points(bgr: np.ndarray, n: int = 4000, text_boxes: list | None = Noneround(float(wts[i]) / top, 2)] for i in pick]+CUTOUT_FROM, CUTOUT_FULL = 6.0, 30.0 # Lab distance from the ground where a pixel starts to belong to the picture / fully does++def cutout(bgr: np.ndarray, text_boxes: list | None = None) -> np.ndarray:- """The drawn layer as an RGBA image (BGRA for OpenCV): the frame's colours, alpha by how strongly each pixel- stands out from the smooth background; text left out."""- c = np.clip(contrast(bgr) / 100.0, 0, 1)- c[~cv2.dilate(layer_mask(bgr, text_boxes).astype(np.uint8), np.ones((3, 3), np.uint8)).astype(bool)] = 0+ """Everything drawn over the ground as an RGBA image (BGRA for OpenCV): the frame's colours, alpha by how far each+ pixel is from the ground colour (a big flat fill counts as much as its outline) or how much it stands out from+ the smooth background, whichever is more; text left out. The renderer lays it over the ground."""+ lab = cv2.cvtColor(bgr, cv2.COLOR_BGR2LAB).astype(np.float32)+ g = cv2.cvtColor(ground(bgr).astype(np.uint8)[None, None], cv2.COLOR_BGR2LAB).astype(np.float32)[0, 0]+ far = (np.linalg.norm(lab - g, axis=2) - CUTOUT_FROM) / (CUTOUT_FULL - CUTOUT_FROM)+ c = np.clip(np.maximum(far, contrast(bgr) / 100.0), 0, 1)+ h, w = c.shape+ for x, y, bw, bh in text_boxes or []:+ pad = 0.01+ c[int(max(0, y - pad) * h):int(min(1, y + bh + pad) * h + 1), int(max(0, x - pad) * w):int(min(1, x + bw + pad) * w + 1)] = 0return np.dstack([bgr, (c * 255).astype(np.uint8)])def _text_boxes(out: Path, b: dict) -> list[tuple[float, float, list]]:"""Where text sits and when: every OCR read stored on the shots, plus the packaging timeline once it is written(decompose measures the layer before that file exists)."""- boxes = [(float(it["t"]) - 0.6, float(it["t"]) + 0.6, it["bbox"]) for s in b.get("shots", [])- for it in (s.get("text") or {}).get("items", []) if it.get("bbox") and it.get("t") is not None]+ # reads the packaging layer judged to be the picture itself (a shape read as a letter, writing drawn into the+ # scene) are drawing, not text to leave out; so are lone characters, which shapes and faces often read as+ cues = list((b.get("packaging") or {}).get("text_cues", []))tl = out / "packaging" / "timeline.json"if tl.exists():- boxes += [(float(x["t0"]), float(x["t1"]), x["bbox"]) for x in read_json(tl).get("text", []) if x.get("bbox")]+ cues += read_json(tl).get("text", [])+ drawn = [(float(c["t0"]) - 0.6, float(c["t1"]) + 0.6, str(c.get("text", "")).strip()) for c in cues if c.get("part_of_picture")]++ def is_text(it: dict) -> bool:+ txt, t = str(it.get("text", "")).strip(), float(it["t"])+ return len(txt) > 1 and not any(a <= t <= z and txt == w for a, z, w in drawn)++ boxes = [(float(it["t"]) - 0.6, float(it["t"]) + 0.6, it["bbox"]) for s in b.get("shots", [])+ for it in (s.get("text") or {}).get("items", []) if it.get("bbox") and it.get("t") is not None and is_text(it)]+ boxes += [(float(x["t0"]), float(x["t1"]), x["bbox"]) for x in cues if x.get("bbox") and not x.get("part_of_picture")]return boxesdiff --git a/rea_video/pipeline.py b/rea_video/pipeline.pyindex da12cd0..51384c5 100644--- a/rea_video/pipeline.py+++ b/rea_video/pipeline.py@@ -67,6 +67,31 @@ _FINALIZE_ONLY = {"classify.py", "report.py", "plan.py", "production.py", "entit_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++ rows = kf+ if len(rows) > KEY_SHEET_MAX:+ generic = [r.get("by") == "tool" and r.get("role") in ("change", "last") for r in rows]+ if all(generic[1:]): # the tool's picks only: spread them evenly+ keep = set(np.linspace(0, len(rows) - 1, num=KEY_SHEET_MAX).round().astype(int).tolist())+ else: # named key frames first, the most certain first+ 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++def decode_fingerprint() -> str:"""Hash of the code that measures a video (decode, shots, features, audio, packaging). `rea-video eval`reuses a stored breakdown only while this is unchanged, so a change to the measuring code cannot hide behind@@ -87,7 +112,7 @@ def decode_fingerprint() -> str: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 | None = None, max_shots_vlm: int = 60,platform_meta: dict | None = None, stems: bool = True, memory: bool = True, packaging: bool = True, asr: bool = True,- lang: str = "zh", speakers: bool = True) -> dict:+ lang: str = "zh", speakers: bool = True, survey: bool = True) -> dict:lang = set_lang(lang)require_tools()t0 = time.time()@@ -101,6 +126,27 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,track = build_track(str(video), info)shots = detect_shots(track)LOG.info("detected %d shots", len(shots))+ # the survey (overview first, closer looks where needed): an agent's answers from `rea-video survey`, or the VLM's+ from .survey import key_frames, load_timeline, run as run_survey, source_at, vlm_asker++ timeline = load_timeline(out, video, info)+ vlm_client = None # one client for the survey and the shot pass: a model found down stays skipped+ if timeline is None and use_vlm and survey:+ cfg = VLMConfig.from_env()+ if cfg is not None:+ vlm_client = VLMClient(cfg, out / "vlm_cache")+ try:+ got = run_survey(video, out, track, shots, info, asker=vlm_asker(vlm_client, prompt_lang_note()), workers=workers)+ LOG.info("survey: %s", {k: got.get(k) for k in ("status", "rounds", "shots", "keyframes")})+ timeline = load_timeline(out, video, info)+ except Exception as exc: # noqa: BLE001 the cut detector's shots still stand+ LOG.warning("survey with the VLM failed: %s", str(exc)[:160])+ if timeline is not None:+ from .shots import shots_from_cuts++ shots = shots_from_cuts(track, shots, timeline["cuts"])+ LOG.info("survey: %d shots after the overview and closer looks", len(shots))+ keyframes = (timeline or {}).get("keyframes") or {}marks = [s.t(b) for s in shots for b in s.beats]audio = analyze_audio(str(video), [s.start for s in shots[1:]], marks) if info.has_audio else {"has_audio": False}stems_job = None@@ -184,7 +230,11 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,probs, evidence, facts = deterministic(feats, ov, text, faces, audio, prov, fps=info.fps)layers = overlay_layers(ov, text, template)sid = f"shot_{s.index:03d}"- shot_sheet(smp.frames, smp.frame_times, out / "shots" / f"{sid}.jpg")+ # 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)+ 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 measuredstills.append(still_pool.submit(extract_frame, video, s.start + min(0.05, s.duration / 4), out / "shots" / f"{sid}_first.jpg", still_w))@@ -206,8 +256,12 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,sheet = element_crops(video, info, s.start, s.end, motion, out / "shots", sid, min(1080, info.display_size[0] or 1080))if sheet:motion["elements_sheet"] = sheet+ look = source_at(timeline, s.start, s.end) if timeline else Nonerec = {- "id": sid, **s.to_dict(), "features": round_floats(feats), "faces": round(faces, 3),+ **({"survey_look": {"label_probs": {k: float(look["p"].get(k, 0.0)) for k in LABEL_ZH}, "answer": look["answer"],+ "_by": look.get("by") or "agent", "evidence": []}} if look else {}),+ "id": sid, **s.to_dict(), "keyframes": [{k: r[k] for k in ("t", "role", "by", "p") if k in r} for r in kf],+ "features": round_floats(feats), "faces": round(faces, 3),"aspects": round_floats(asp), "overlay": round_floats(ov), "text": text, "layers": layers, "embedded_assets": round_floats(embedded),"deterministic": {"probs": round_floats(probs), "evidence": evidence, "facts": facts},"assets": {"sheet": f"shots/{sid}.jpg", "first_frame": f"shots/{sid}_first.jpg", "last_frame": f"shots/{sid}_last.jpg"},@@ -235,7 +289,7 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,LOG.warning("--vlm requested but no VLM config found (REA_VLM_* / VIDEO_ANALYSIS_* / GEMINI3_*); continuing without it")vlm_info = {"used": False, "requested": True, "status": "not_configured", "error": "no_config"}else:- client = VLMClient(cfg, out / "vlm_cache")+ client = vlm_client or VLMClient(cfg, out / "vlm_cache")vlm_info = {"used": False, "requested": True, "status": "failed", "model": cfg.describe(), "media": cfg.media, "errors": []}def run_unit(unit: list[dict]) -> None:@@ -367,6 +421,8 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,"stems": {k: (Path(v).name if k in ("original", "vocals", "music") else v) for k, v in stem_info.items()},"speech": heard,"speakers": who,+ **({"rhythm": timeline["rhythm"], "survey": {"rounds": timeline.get("rounds"), "shots_estimate": timeline.get("shots_estimate"),+ "cuts": timeline["cuts"], "busy": timeline.get("busy", [])}} if timeline else {}),"per_clip_audio": per_clip_audio(str(video), [s.start for s in shots[1:]], info.duration) if info.has_audio else {},}if pack is not None:@@ -472,8 +528,11 @@ def _user_real(material: dict, real: bool) -> None:def visual_opinion(rec: dict) -> dict | None:- """What a model saw in the shot: the VLM answer, an agent's review (rea-video apply-review), or both averaged."""+ """What a model saw in the shot: the VLM answer, an agent's review (rea-video apply-review), or both averaged;+ with neither, the survey's look at the whole video (how this stretch was made, from the overview)."""v, a = rec.get("vlm"), rec.get("review")+ if not (v or a):+ return rec.get("survey_look")if not (v and a):return v or amerged = dict(v)@@ -552,7 +611,7 @@ def _vlm_gate(rec: dict, vprobs: dict | None, vctx: dict) -> dict | None:# The exception holds only when fusing actually lands on the agent's pick; a compromise label nobody voted for# is worse than the tools' call (eval holdout2 dual_role_realcat: agent "still image move" + tools "code render"# fused to "AI video").- agent_only = bool(rec.get("review")) and not rec.get("vlm") \+ agent_only = bool(rec.get("review") or rec.get("survey_look")) and not rec.get("vlm") \and decide(fuse(rec["deterministic"]["probs"], vprobs, facts.get("temporal_family", "dynamic")))[0] == vif v not in (d, ranked[1][0]) and not person and not undecided and not same_group and not agent_only: # it must back one of the tools' two best guessesreturn None@@ -692,7 +751,12 @@ def finalize(breakdown: dict, out: Path, engine: str | None = None) -> dict:by=by, at=join(fmt_time(c) for c in split["cuts"][:6]))+ (T("({seq})", " ({seq})", seq=seq) if seq else "") + (T(":", ": ") + split['note'] if split.get("note") else ""))evidence = measured + seen_ev- decided = "fused" if rec.get("vlm") else ("fused_agent" if rec.get("review") else "deterministic")+ if not rec.get("vlm") and not rec.get("review") and rec.get("survey_look"):+ sl = rec["survey_look"]+ seen_ev.append(T("[{by} 总览] 全片总览判断这段是{l}", "[{by} overview] The whole-video overview reads this stretch as {l}",+ by=reviewer_name(sl.get("_by") or "agent"), l=LABEL_ZH.get(sl.get("answer"), sl.get("answer"))))+ evidence = measured + seen_ev+ decided = "fused" if rec.get("vlm") else ("fused_agent" if rec.get("review") or rec.get("survey_look") else "deterministic")user = rec.get("user") or {}if user.get("label") in LABEL_ZH: # the user said what this shot is: that is the answerlabel, conf, decided = user["label"], 1.0, "user"diff --git a/rea_video/redraw.py b/rea_video/redraw.pyindex 0343ec4..39ff3e9 100644--- a/rea_video/redraw.py+++ b/rea_video/redraw.py@@ -82,7 +82,8 @@ class Scene:img = cv2.imread(str(base / sc["cutout"]), cv2.IMREAD_UNCHANGED)img = cv2.resize(img, (W, H), interpolation=cv2.INTER_AREA)a = img[..., 3:4].astype(np.float32) / 255.0- self.layer = img[..., :3].astype(np.float32) / 255.0 * a+ self.layer = img[..., :3].astype(np.float32) / 255.0 * a # premultiplied+ self.alpha = np.repeat(a, 3, axis=2)returnrows = np.array(json.loads((base / sc["points"]).read_text(encoding="utf-8"))["points"], np.float32).reshape(-1, 6)n = int(sc.get("count", len(rows)))@@ -162,10 +163,17 @@ class Redraw:bg = s.bg if mix >= 1 else prev.bg * (1 - mix) + s.bg * mixdrawn = np.zeros((self.H, self.W, 3), np.float32)if s.draw == "cutout":- drawn += cv2.warpAffine(s.layer, s.matrix(t), (self.W, self.H)) * s.gain * mix+ # a cut-out picture lies over the ground (dark ink on paper must darken it, not add light); while it+ # morphs in, the previous scene's picture fades out under it+ out = bg.copy()if mix < 1 and prev.draw == "cutout":- drawn += cv2.warpAffine(prev.layer, prev.matrix(prev.end), (self.W, self.H)) * prev.gain * (1 - mix)- dot = 0.0+ M = prev.matrix(prev.end)+ pa = cv2.warpAffine(prev.alpha, M, (self.W, self.H)) * (1 - mix)+ out = out * (1 - pa) + cv2.warpAffine(prev.layer, M, (self.W, self.H)) * prev.gain * (1 - mix)+ M = s.matrix(t)+ a = cv2.warpAffine(s.alpha, M, (self.W, self.H)) * mix+ out = out * (1 - a) + cv2.warpAffine(s.layer, M, (self.W, self.H)) * s.gain * mix+ return (np.clip(out, 0, 1) * 255 + 0.5).astype(np.uint8)else:xy, col = s.particles(t)dot = s.dotdiff --git a/rea_video/report.py b/rea_video/report.pyindex 7e4d1bc..5e09011 100644--- a/rea_video/report.py+++ b/rea_video/report.py@@ -159,11 +159,11 @@ def _span(a, z) -> str:TRANS_ZH = LangDict({"cut": "硬切", "jump": "跳剪", "flash": "闪亮切", "fade": "淡入淡出", "dissolve": "叠化", "wipe": "划像","slide": "推移", "whip": "甩镜", "zoom": "缩放转场", "spin": "旋转转场", "blur": "模糊转场", "glitch": "故障转场",- "shake": "抖动转场", "effect": "转场特效", "mg_transition": "版式切换"},+ "shake": "抖动转场", "effect": "转场特效", "mg_transition": "版式切换", "morph": "形变转场", "match": "匹配剪辑"},en={"cut": "cut", "jump": "jump cut", "flash": "flash cut", "fade": "fade", "dissolve": "dissolve", "wipe": "wipe","slide": "slide", "whip": "whip pan", "zoom": "zoom transition", "spin": "spin transition","blur": "blur transition", "glitch": "glitch transition", "shake": "shake transition",- "effect": "transition effect", "mg_transition": "layout change"})+ "effect": "transition effect", "mg_transition": "layout change", "morph": "morph", "match": "match cut"})# which way a transition moves: the direction the edge or the picture travelsTRANS_DIR_ZH = LangDict({"left": "向左", "right": "向右", "up": "向上", "down": "向下", "diagonal": "斜向", "center_out": "从中心展开","edges_in": "向中心收拢"},diff --git a/rea_video/review.py b/rea_video/review.pyindex a0bdccc..1e2f56a 100644--- a/rea_video/review.py+++ b/rea_video/review.py@@ -31,7 +31,7 @@ INSTRUCTIONS = f"""你是这次的 VLM:逐个镜头看图,判断「底层画把你的判断并入结论(会重写 breakdown.json、report.md、report.html)。怎么看:-1. 先看 storyboard.jpg 建立整体印象;每个镜头看 images 里的 sheet(首/中/尾联系表,一张就够,不用另开首尾帧)。+1. 先看 storyboard.jpg 建立整体印象;每个镜头看 images 里的 sheet(这个镜头的关键帧:动作起止、转折、元素出入,一张就够,不用另开首尾帧)。要细看时运行顶层的 zoom_cmd,把 {{start}} {{end}} {{id}} 换成该镜头的值。2. priority=high 的镜头(低置信、次选接近、转码后实拍/AI 待确认)一定要看;其余镜头也尽量都答。3. common_evidence 是整片共有的工具证据(帧率、转码),每镜 tool.evidence 里不再重复。只依据画面证据,独立判断(这里不给 VLM 的答案,它会在融合时单独计入)。tool 一栏是确定性取证的结果,可能有误,但帧率类证据(24→30 重复帧)和 AIGC 标识可靠,@@ -63,7 +63,7 @@ video_prompt(复刻该镜头的<PROMPT_LANG>视频提示词:先写景别、最后在答案顶层的 aspects 里写整片:机位/场景、推测设备、整体布光、剪辑手法、视频形式。有人在表演的镜头填 performance(表演和情绪;报告「表演与情绪」一节和生成单元的提示词都用它,复刻时表情、动作、语气靠它还原)。-看 sheet 的首 / 中 / 尾三帧,表情变化快的镜头用 zoom_cmd 抽帧细看;有 said 的镜头结合台词写 voice:+看 sheet 里的关键帧(表情峰值、动作转折都在里面),表情变化快的镜头用 zoom_cmd 抽帧细看;有 said 的镜头结合台词写 voice:{PERF_GUIDE}每个镜头再填 narrative(这个镜头在讲什么):role 选它在叙事上的作用,point 用一句话写它讲的那一点(去掉具体的人和产品也成立的写法,@@ -159,7 +159,8 @@ def build_tasks(breakdown: dict, out_dir: str) -> tuple[dict, dict]:# the tool's top label is already in "tool"; drop it from the raw hints"hints": shot_hints(rec["features"], rec["deterministic"]["facts"], dl, dp).split("; 确定性初判=")[0],**({"aspects": {k: v["result"] for k, v in (rec.get("aspects") or {}).items() if v.get("result")}} if shoot_like else {}),- # the sheet already holds first / middle / last; separate first / last frames would triple the image tokens+ # the sheet already holds the key frames; separate first / last frames would triple the image tokens+ **({"keyframes": [[k["t"], k.get("role", "")] for k in rec["keyframes"]]} if rec.get("keyframes") else {}),**({"said": said[rec["index"]]} if said.get(rec["index"]) else {}),"images": {"sheet": rec["assets"]["sheet"], **({"strip": rec["assets"]["strip"]} if rec["assets"].get("strip") else {})},"_shoot_like": shoot_like,diff --git a/rea_video/shots.py b/rea_video/shots.pyindex 564fa3f..3a55194 100644--- a/rea_video/shots.py+++ b/rea_video/shots.py@@ -479,3 +479,43 @@ def _steady_morph(thumbs: list[np.ndarray], i: int, k: int) -> bool:mid = rate(i - k, i + k)around = [r for r in (rate(i - 3 * k, i - k), rate(i + k, i + 3 * k)) if r is not None]return bool(mid and around and mid < 1.3 * max(around))+++def shots_from_cuts(track: FrameTrack, detected: list[Shot], cuts: list[dict], min_frames: int = 2) -> list[Shot]:+ """Shots bounded by the survey's scene changes (survey/timeline.json `cuts`: frame, kind, span). A boundary the+ detector also found keeps its measured transition; beats move to the shot they fall in."""+ n = track.n+ by_frame = {s.start_frame: s for s in detected[1:]}+ edges: list[tuple[int, dict]] = []+ for c in sorted(cuts, key=lambda c: int(c["frame"])):+ f = int(c["frame"])+ if min_frames <= f <= n - min_frames and (not edges or f - edges[-1][0] >= min_frames):+ edges.append((f, c))+ beats = sorted(b for s in detected for b in s.beats)+ shots: list[Shot] = []+ start, trans, score, tdict = 0, "start", 0.0, {}+ for f, c in edges + [(n, {})]:+ sh = Shot(index=len(shots) + 1, start_frame=start, end_frame=f, fps=track.fps, transition_in=trans, boundary_score=score,+ times=track.times)+ sh.transition = tdict+ shots.append(sh)+ if c:+ old = by_frame.get(f)+ kind = c.get("kind") or "cut"+ if old is not None and kind in ("cut", "effect"):+ trans, score, tdict = old.transition_in, old.boundary_score, dict(old.transition)+ else:+ trans, score = kind, float(c.get("p") or 0.5)+ span = c.get("span") or []+ def at(t: float) -> int:+ if track.times is not None and len(track.times):+ return int(np.clip(np.searchsorted(track.times, t - 1e-6), 0, n - 1))+ return int(np.clip(round(t * track.fps), 0, n - 1))+ a, z = (at(span[0]), at(span[1])) if len(span) == 2 and span[1] > span[0] else (f, f)+ tdict = {"type": kind, "by": c.get("by", "survey"), "start_frame": max(0, min(a, f) - 1), "end_frame": max(z, f)}+ start = f+ for sh in shots:+ sh.beats = [b for b in beats if sh.start_frame < b < sh.end_frame]+ if sh.index > 1 and sh.start_frame in by_frame:+ sh.flash_s = by_frame[sh.start_frame].flash_s+ return shotsdiff --git a/rea_video/survey.py b/rea_video/survey.pynew file mode 100644index 0000000..50c4bfd--- /dev/null+++ b/rea_video/survey.py@@ -0,0 +1,791 @@+"""Survey: look at the whole video once, then look closer only where it needs it.++Round 1 lays evenly spaced frames of the whole video on one or a few overview sheets (index, time, how much the+picture changes in each gap, the cut detector's cuts marked) and asks typed questions about every gap between two+tiles. Gaps answered "transition" or "unsure" get a zoom sheet in the next round: frames picked where the picture+changes most, every frame or two through a transition. Zoom tasks are independent, so they can be answered in+parallel. At most three rounds.++Questions and answers follow the JEV shape: `state` holds the material, each question has `type`, `instructions`+and `criteria`; an answer is the chosen option and its probabilities (`{"answer": "cut", "p": {"cut": 0.9, ...}}`),+no prose. Gaps that are plain continuations are left out of the answer, so an answer stays a few dozen tokens.++The result, survey/timeline.json, holds the scene changes (time, frame, kind, span of the transition, who found+it, probability), the stretches where a lot happens inside one shot, and the change 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 json+import math+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path+from typing import Callable++import cv2+import numpy as np+from PIL import Image, ImageDraw++from .media import VideoInfo, iter_frames, video_info+from .shots import FrameTrack, Shot+from .util import fmt_time, read_json, write_json+from .visual import _font, _to_pil++VERSION = 1+TILE_W = 240+COLS = 8+MAX_TILES = 48 # tiles on one overview sheet+MAX_SHEETS = 4 # overview sheets; past MAX_TILES * MAX_SHEETS tiles the spacing grows+OVERVIEW_EVERY = 1.0 # seconds between overview tiles when the video is short enough+ZOOM_MAX = 16 # tiles on one zoom sheet+ZOOM_SPAN = 4.0 # longest stretch one zoom sheet covers+MAX_ROUNDS = 3+RHYTHM_STEP = 0.25 # seconds per value of the change curve+SPEED_GRID = (12, 8) # blocks the frame change is measured in (see speed())+KEY_MOVING = 0.025 # speed (see speed()) above which the picture counts as moving+KEY_MOVING_BUSY = 0.015 # ... inside stretches answered "busy"+KEY_LONG_MOVE = 0.5 # inside a long move, a key frame this often (s)+KEY_MAX = 12 # key frames per shot at most+DROP_TOOL_CUT_P = 0.85 # a detector cut is dropped only when its gap is explicitly answered "same" this sure++GAP_CRITERIA = {+ "same": "同一个镜头在继续:画面延续,只有小幅运动",+ "busy": "同一个镜头,但这段里画面变化很多(动作、元素进出、形变),要多抽关键帧",+ "cut": "这段里换了镜头 / 场景,是一刀硬切",+ "transition": "这段里换了场景,但不是硬切:形变、叠化、推拉进出、划像、甩镜等,过程要细看",+ "unsure": "看不出来,要在这段加密抽帧再看",+}+KEY_ROLES = {+ "first": "镜头 / 场景的第一帧",+ "last": "镜头的最后一帧(和下一镜衔接的样子)",+ "move_start": "动作或运镜开始",+ "move_end": "动作或运镜停下、到位",+ "extreme": "动作的转折 / 极值:反向、最远、最高、落地、最歪的那一下",+ "enter": "新元素(图形、人、物、文字、贴纸)出现,或刚完全展开",+ "exit": "元素离开 / 消失",+ "framing": "构图或景别变了(推近 / 拉远到位、主体换位置)",+ "expression": "表情或姿态的峰值",+ "transition_mid": "转场 / 形变进行到一半的样子",+ "light": "颜色、光线、底色突变(闪白、换底色、亮起)",+ "beat": "卡在节拍 / 音效上的画面变化",+}+DETAIL_INSTRUCTIONS = """你是动画原画师,在挑关键帧。图里是一个镜头的候选帧,每格左上角是编号和时间。+关键帧 = 用最少的帧把这段画面定下来,其余帧都能从它们插值出来:状态的起点、终点和转折点,不是"变了多少就取一张"。++按 JEV 格式回答,只回 JSON,不写解释:+- frames:是关键帧的格子写 {"格子编号": {"answer": 角色, "p": {角色: 概率}}},角色从 roles 里选;不是关键帧的不写。+- missing:哪两格之间还漏了关键帧(例如动作在两格之间转折了、有元素一闪而过),写成 ["03-04", ...];没有就写 []。+- 第一格一般是 first;动作的转折和极值最重要,宁多勿漏。+- 这个镜头很简单、候选帧已经够用时,只回 {"accept": true}。"""+SOURCE_CRITERIA = {+ "live_action": "真实摄像机 / 手机实拍", "ai_video": "AI 生成视频(形变、纹理闪烁、物理不合理)", "avatar": "数字人口播",+ "cg_3d": "3D 渲染(Blender / C4D / UE,几何干净、光影一致)",+ "code_render": "代码 / 模板渲染:MG 动效、矢量图形、粒子、图表、按参数生成的动画(含手绘质感的矢量动画)",+ "screen_capture": "录屏 / 截图", "still_motion": "一张静图推拉", "static_hold": "静帧", "anim_2d": "2D 逐帧手绘 / 骨骼动画",+ "stop_motion": "定格动画(实物逐帧拍)", "film_footage": "剪进来的影视片段",+}+KINDS = {"cut": "硬切", "dissolve": "叠化", "morph": "形变:上一画面的图形直接变成下一画面", "zoom": "推进 / 拉出进入新画面",+ "wipe": "划像", "slide": "推移", "whip": "甩镜", "fade": "经黑场 / 白场", "match": "匹配剪辑(形状或动作接上)",+ "effect": "其他转场特效"}++INSTRUCTIONS = """你是视频节奏审阅员。图里是按时间等距排开的帧,每格左上角是编号和时间;格子之间叫 gap,+编号 gNN 表示第 NN 格和下一格之间。格子底部的橙色条是这段里画面变化有多大(越长越大),右边红色竖线 + CUT 表示切镜检测器在这段里找到了切点。++按 JEV 格式回答:只回 JSON,不写解释。+- gaps:每个 gap 从 criteria 里选一项,写成 {"answer": 选项, "p": {选项: 概率, ...}};是 "same" 的 gap 不用写,但画了红线的 gap 必须写。+- 选 cut / transition 的,再加 "kind"(从 kinds 里选)。一个转场跨几个 gap 时,这几个 gap 的 kind 写成一样;+ 紧接着又是另一个转场(A 变成 B,B 马上又变成 C),换一个 kind,或者在 B 停留的那格写 busy。+- source:按底层画面的制作方式分段(格子编号范围 + 选项 + 概率)。+- 拿不准就选 unsure,会在那里加密抽帧再看一轮;不要猜。+- 宁可多报 transition / unsure,也不要漏掉换场景的地方:每个场景的第一帧都是关键帧。"""+++# ------------------------------------------------------------------ measurements -----------------------------------++def change_score(track: FrameTrack) -> np.ndarray:+ """Per-frame change from the previous frame, 0-1 (the cut detector's score)."""+ s = 0.6 * track.hist_dist + 0.4 * np.clip(track.pix_diff * 4.0, 0, 1)+ if len(s):+ s[0] = 0.0+ return s+++def _t(track: FrameTrack, i: int) -> float:+ if track.times is not None and 0 <= i < len(track.times):+ return float(track.times[i])+ return i / track.fps+++def frame_at(track: FrameTrack, t: float) -> int:+ if track.times is not None and len(track.times):+ return int(min(len(track.times) - 1, max(0, np.searchsorted(track.times, t - 1e-6))))+ return int(min(track.n - 1, max(0, round(t * track.fps))))+++def speed(track: FrameTrack, a: int, z: int) -> np.ndarray:+ """How fast the picture moves at each frame of [a, z), 0-1: the change in the most-changed block of a 12 x 8 grid+ (a small subject moving counts as much as the whole frame), held over the animation's steps (drawings on twos or+ threes repeat frames) and smoothed."""+ T = track.thumbs++ def block_max(i: int) -> float:+ d = np.abs(T[i].astype(np.float32) - T[i - 1].astype(np.float32))+ return float(cv2.resize(d, SPEED_GRID, interpolation=cv2.INTER_AREA).max()) / 255.0+ raw = np.array([0.0] + [block_max(i) for i in range(a + 1, z)])+ hold = max(1, int(round(track.fps * 0.12)))+ held = np.array([raw[max(0, i - hold + 1):i + 1].max() for i in range(len(raw))])+ return np.convolve(held, np.ones(3) / 3, mode="same") if len(held) >= 3 else held+++def key_frames(track: FrameTrack, a: int, z: int, busy: list[tuple[float, float]] | None = None, max_n: int = KEY_MAX,+ moving: float = KEY_MOVING, moving_busy: float = KEY_MOVING_BUSY) -> list[int]:+ """Key frames of [a, z): the frames that fix the motion, from which the rest can be in-betweened. The first and+ last frame; where each move starts and ends (the rest pose before, the pose it settles in); inside a move, the+ dips in speed (a turn, an extreme, a reversal); inside a long move, a frame every KEY_LONG_MOVE seconds. A still+ shot gets its first frame, a steady pan its two ends. Past max_n the least important go: small moves before+ big ones, the frames inside a move before its ends."""+ z = max(a + 1, min(z, track.n))+ if z - a <= 2:+ return list(range(a, z))+ sp = speed(track, a, z)+ hold = max(1, int(round(track.fps * 0.12)))+ busy = busy or []+ thr = np.array([moving_busy if any(b0 <= _t(track, a + i) < b1 for b0, b1 in busy) else moving for i in range(len(sp))])+ on = sp > thr+ cand: dict[int, float] = {a: 1e9} # frame -> importance+ i = 0+ while i < len(on):+ if not on[i]:+ i += 1+ continue+ j = i+ while j < len(on) and on[j]:+ j += 1+ peak = float(sp[i:j].max())+ cand[a + max(0, i - 1)] = max(cand.get(a + max(0, i - 1), 0), peak) # rest pose before the move+ end = min(len(on) - 1, max(i, j - hold + 1)) # where it settles (speed() holds each change for `hold` frames)+ cand[a + end] = max(cand.get(a + end, 0), peak)+ seg = sp[i:j]+ for k in range(1, len(seg) - 1): # dips: the move turns or reaches an extreme+ lo, hi = max(0, k - 4), min(len(seg), k + 5)+ if seg[k] == seg[lo:hi].min() and seg[k] < 0.6 * min(seg[lo:k].max(initial=0), seg[k + 1:hi].max(initial=0)):+ cand[a + i + k] = max(cand.get(a + i + k, 0), 0.5 * peak)+ step = max(2, int(round(KEY_LONG_MOVE * track.fps)))+ for k in range(i + step, j - step // 2, step): # a long move: its in-between poses every KEY_LONG_MOVE+ cand.setdefault(a + k, 0.3 * peak)+ i = j+ last = z - 1+ cand[last] = max(cand.get(last, 0), 1e8 if len(cand) > 1 else 0)+ out = sorted(f for f in cand if a <= f < z)+ if len(out) > max_n:+ # drop, one at a time, the frame that loses least: low importance and crowded by its neighbours, so the key+ # frames stay spread over the shot instead of piling up in its busiest second+ order = sorted(out, key=lambda f: cand[f])+ rank = {f: 0.3 + 0.7 * k / max(1, len(order) - 1) for k, f in enumerate(order)}+ while len(out) > max_n:+ w = [(rank[f] * min(out[k] - out[k - 1], out[k + 1] - out[k]), f) for k, f in enumerate(out) if 0 < k < len(out) - 1]+ out.remove(min(w)[1])+ if len(out) == 2 and float(sp.max()) <= float(thr.min()): # nothing moves: the first frame says it all+ out = out[:1]+ return out+++def rhythm(track: FrameTrack, step: float = RHYTHM_STEP) -> list[float]:+ """The change curve: the largest per-frame change in each `step` seconds (0-1)."""+ s = change_score(track)+ dur = _t(track, track.n - 1) + 1 / track.fps if track.n else 0.0+ out = []+ for k in range(int(math.ceil(dur / step))):+ a, z = frame_at(track, k * step), frame_at(track, (k + 1) * step)+ seg = s[a:max(a + 1, z)]+ out.append(round(float(seg.max()), 2) if len(seg) else 0.0)+ return out+++# ------------------------------------------------------------------ sheets -----------------------------------------++def _grab(video: str, info: VideoInfo, times: list[float], width: int = TILE_W) -> list[np.ndarray]:+ """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)."""+ if not times:+ return []+ order = sorted(range(len(times)), key=lambda k: times[k])+ t0, t1 = times[order[0]], times[order[-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:+ 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 []+ 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]+++def _sheet(frames: list[np.ndarray], labels: list[str], bars: list[float], cuts: list[bool], out: Path, cols: int = COLS) -> Path:+ """Tiles in rows; under each tile a bar for the change in the gap after it; a red edge + ✂ for detector cuts."""+ font = _font(15)+ cells = []+ for f, lab, bar, cut in zip(frames, labels, bars, cuts):+ im = _to_pil(f)+ im = im.resize((TILE_W, max(1, int(im.height * TILE_W / im.width))))+ cell = Image.new("RGB", (TILE_W, im.height + 10), (24, 24, 24))+ cell.paste(im, (0, 0))+ d = ImageDraw.Draw(cell)+ w = int(d.textlength(lab, font=font)) + 8+ d.rectangle([0, 0, w, 19], fill=(0, 0, 0))+ d.text((4, 1), lab, fill=(255, 255, 255), font=font)+ d.rectangle([0, im.height + 2, int((TILE_W - 2) * min(1.0, bar)), im.height + 8], fill=(245, 158, 11))+ if cut:+ d.rectangle([TILE_W - 5, 0, TILE_W - 1, im.height + 9], fill=(230, 30, 30))+ d.rectangle([TILE_W - 40, im.height - 22, TILE_W - 6, im.height - 2], fill=(230, 30, 30))+ d.text((TILE_W - 37, im.height - 21), "CUT", fill=(255, 255, 255), font=_font(13))+ cells.append(cell)+ ch = max(c.height for c in cells)+ rows = int(math.ceil(len(cells) / cols))+ sheet = Image.new("RGB", (TILE_W * min(cols, len(cells)) + 2 * (min(cols, len(cells)) - 1), rows * (ch + 2)), (255, 255, 255))+ for k, c in enumerate(cells):+ sheet.paste(c, ((k % cols) * (TILE_W + 2), (k // cols) * (ch + 2)))+ out.parent.mkdir(parents=True, exist_ok=True)+ sheet.save(out, quality=85)+ return out+++def _gap_bars(track: FrameTrack, times: list[float], score: np.ndarray, cut_frames: list[int]) -> tuple[list[float], list[bool]]:+ bars, cuts = [], []+ for k, t in enumerate(times):+ nxt = times[k + 1] if k + 1 < len(times) else _t(track, track.n - 1)+ a, z = frame_at(track, t) + 1, frame_at(track, nxt) + 1+ bars.append(float(score[a:z].max()) if z > a else 0.0)+ cuts.append(any(a <= c < z for c in cut_frames) and k + 1 < len(times))+ return bars, cuts+++# ------------------------------------------------------------------ rounds -----------------------------------------++def _source(video: str, info: VideoInfo) -> dict:+ return {"path": str(video), "duration": round(info.duration, 3), "size": [info.width, info.height], "fps": round(info.fps, 3)}+++def overview_task(video: str, info: VideoInfo, track: FrameTrack, shots: list[Shot], sdir: Path) -> dict:+ dur = info.duration or _t(track, track.n - 1)+ n = int(min(MAX_TILES * MAX_SHEETS, max(8, round(dur / OVERVIEW_EVERY))))+ every = dur / n+ times = [round((k + 0.5) * every, 3) for k in range(n)]+ score = change_score(track)+ cut_frames = [s.start_frame for s in shots[1:]]+ frames = _grab(video, info, times)+ bars, cuts = _gap_bars(track, times, score, cut_frames)+ images = []+ for p in range(int(math.ceil(n / MAX_TILES))):+ sl = slice(p * MAX_TILES, (p + 1) * MAX_TILES)+ labels = [f"{k:02d} {fmt_time(t)}" for k, t in enumerate(times)][sl]+ name = f"overview_{p + 1}.jpg" if n > MAX_TILES else "overview.jpg"+ _sheet(frames[sl], labels, bars[sl], cuts[sl], sdir / name)+ images.append(f"survey/{name}")+ gaps = {f"g{k:02d}": [times[k], times[k + 1]] for k in range(n - 1)}+ return {+ "id": "overview", "round": 1, "images": images, "instructions": INSTRUCTIONS,+ "state": {"duration": round(dur, 3), "tiles": n, "every": round(every, 3), "times": times,+ "tool_cuts": [round(s.start, 3) for s in shots[1:]],+ "tool_cut_gaps": [g for g, c in zip(gaps, cuts) if c]},+ "questions": {+ "shots_estimate": {"type": "integer", "instructions": "整条视频大约有多少个镜头 / 场景(数换场景的次数 + 1);同时给 range"},+ "gaps": {"type": "choice", "per": "gap", "ids": list(gaps), "criteria": GAP_CRITERIA, "kinds": KINDS},+ "source": {"type": "choice", "per": "segment", "criteria": SOURCE_CRITERIA,+ "instructions": "按底层画面的制作方式把整条视频分段,tiles 写格子编号范围(如 \"00-12\");整条是同一种就写一段。"+ "看整片的一致性:同一套底纹、描边、配色贯穿全片,通常是同一种做法"},+ },+ "answer_template": {"shots_estimate": {"answer": None, "range": [None, None]}, "gaps": {},+ "source": [{"tiles": "00-NN", "answer": None, "p": {}}]},+ "_gaps": gaps,+ }+++def _zoom_frames(track: FrameTrack, a: int, z: int, score: np.ndarray, cap: int = ZOOM_MAX) -> list[int]:+ """Frames to show for [a, z]: every frame when few; otherwise the ends, the peaks of change (a transition's key+ moments) and frames where the picture has become something new, topped up evenly."""+ z = min(z, track.n - 1)+ if z - a + 1 <= cap:+ return list(range(a, z + 1))+ keep = {a, z}+ seg = score[a:z + 1]+ for i in np.argsort(-seg)[:cap // 3]: # biggest changes: the frame before and the frame of each+ if seg[i] > 0.05:+ keep.update({a + int(i) - 1, a + int(i)})+ keep.update(key_frames(track, a, z + 1, busy=[(-1e9, 1e9)], max_n=cap))+ keep = sorted(k for k in keep if a <= k <= z)+ if len(keep) < cap:+ keep = sorted(set(keep) | set(np.linspace(a, z, num=cap - len(keep) + 2).round().astype(int).tolist()))+ if len(keep) > cap:+ must = {a, z}+ rest = [k for k in keep if k not in must]+ idx = np.unique(np.linspace(0, len(rest) - 1, num=cap - 2).round().astype(int))+ keep = sorted(must | {rest[i] for i in idx})+ return keep+++def zoom_task(video: str, info: VideoInfo, track: FrameTrack, shots: list[Shot], sdir: Path, tid: str, t0: float, t1: float,+ rnd: int, why: str) -> dict:+ score = change_score(track)+ a, z = frame_at(track, t0), frame_at(track, t1)+ idx = _zoom_frames(track, a, z, score)+ times = [round(_t(track, i), 3) for i in idx]+ frames = _grab(video, info, times)+ bars, cuts = _gap_bars(track, times, score, [s.start_frame for s in shots[1:]])+ labels = [f"{k:02d} {fmt_time(t)}" for k, t in enumerate(times)]+ name = f"zoom/{tid}.jpg"+ _sheet(frames, labels, bars, cuts, sdir / name, cols=min(COLS, 4 if len(frames) <= 16 else COLS))+ gaps = {f"{tid}.{k:02d}": [times[k], times[k + 1]] for k in range(len(times) - 1)}+ return {+ "id": tid, "round": rnd, "why": why, "images": [f"survey/{name}"], "instructions": INSTRUCTIONS,+ "state": {"span": [round(t0, 3), round(t1, 3)], "tiles": len(times), "times": times,+ "tool_cut_gaps": [g for g, c in zip(gaps, cuts) if c]},+ "questions": {"gaps": {"type": "choice", "per": "gap", "ids": list(gaps), "criteria": GAP_CRITERIA, "kinds": KINDS}},+ "answer_template": {"gaps": {}},+ "_gaps": gaps,+ }+++DETAIL_CANDIDATES = 12 # candidate frames on one shot's detail sheet+DETAIL_MIN_S = 1.5 # shorter shots keep the tool's key frames without asking+DETAIL_MIN_KEYS = 4 # ... and so do shots where the tool finds fewer key frames (little happens)+++def detail_task(video: str, info: VideoInfo, track: FrameTrack, sdir: Path, k: int, a: int, z: int,+ busy: list[list[float]]) -> dict | None:+ """One shot's candidate key frames, more than the tool would keep (a lower threshold), for the AI to choose+ and name."""+ if _t(track, z - 1) - _t(track, a) < DETAIL_MIN_S:+ return None+ if len(key_frames(track, a, z, [tuple(b) for b in busy])) < DETAIL_MIN_KEYS:+ return None # little happens: the tool's key frames stand, no question asked+ idx = key_frames(track, a, z, [tuple(b) for b in busy], max_n=DETAIL_CANDIDATES,+ moving=KEY_MOVING * 0.8, moving_busy=KEY_MOVING_BUSY * 0.8)+ if len(idx) < DETAIL_CANDIDATES // 2: # few changes: top up evenly so a quick blink between two picks is still seen+ idx = sorted(set(idx) | set(np.linspace(a, z - 1, num=DETAIL_CANDIDATES // 2).round().astype(int).tolist()))+ times = [round(_t(track, i), 3) for i in idx]+ frames = _grab(video, info, times)+ score = change_score(track)+ bars, _ = _gap_bars(track, times, score, [])+ tid = f"shot_{k:03d}"+ name = f"detail/{tid}.jpg"+ _sheet(frames, [f"{j:02d} {fmt_time(t)}" for j, t in enumerate(times)], bars, [False] * len(times), sdir / name,+ cols=min(COLS, 6))+ return {"id": tid, "stage": "detail", "images": [f"survey/{name}"], "instructions": DETAIL_INSTRUCTIONS,+ "state": {"shot": k, "span": [times[0], round(_t(track, z - 1), 3)], "tiles": len(times), "times": times},+ "questions": {"frames": {"type": "choice", "per": "tile", "criteria": KEY_ROLES},+ "missing": {"type": "multi_choice", "instructions": "漏了关键帧的相邻两格,写成 \"03-04\""}},+ "answer_template": {"frames": {}, "missing": []},+ "_frames": idx}+++def read_detail(path: Path) -> dict | None:+ if not path.is_file():+ return None+ try:+ got = read_json(path)+ except (OSError, ValueError):+ return None+ if not isinstance(got, dict) or not (got.get("filled") or got.get("frames") or got.get("accept") or got.get("missing")):+ return None+ if got.get("accept"): # the tool's key frames are fine for this shot+ return {"accept": True, "frames": {}, "missing": []}+ frames = {}+ for k, v in (got.get("frames") or {}).items():+ v = {"answer": v} if isinstance(v, str) else v+ if isinstance(v, dict) and v.get("answer") in KEY_ROLES and str(k).isdigit():+ p = {r: float(x) for r, x in (v.get("p") or {}).items() if r in KEY_ROLES and isinstance(x, (int, float))}+ frames[int(k)] = {"answer": v["answer"], "p": p or {v["answer"]: 1.0}}+ missing = []+ for m in got.get("missing") or []:+ try:+ i, j = (int(x) for x in str(m).split("-"))+ missing.append((min(i, j), max(i, j)))+ except ValueError:+ continue+ return {"frames": frames, "missing": missing}+++def _clean_gap(v) -> dict | None:+ """One gap answer -> {"answer", "p", "kind"?}; None when unusable."""+ if isinstance(v, str):+ v = {"answer": v}+ if not isinstance(v, dict):+ return None+ ans = v.get("answer")+ if ans not in GAP_CRITERIA:+ return None+ p = v.get("p") if isinstance(v.get("p"), dict) else {}+ p = {k: float(x) for k, x in p.items() if k in GAP_CRITERIA and isinstance(x, (int, float))}+ tot = sum(p.values())+ p = {k: round(x / tot, 3) for k, x in p.items()} if tot > 0 else {ans: 1.0}+ out = {"answer": ans, "p": p}+ if v.get("kind") in KINDS:+ out["kind"] = v["kind"]+ return out+++def read_answer(path: Path) -> dict | None:+ """A filled answer file, or None when it is missing or still the empty template."""+ if not path.is_file():+ return None+ try:+ got = read_json(path)+ except (OSError, ValueError):+ return None+ if not isinstance(got, dict):+ return None+ gaps = {k: g for k, v in (got.get("gaps") or {}).items() if (g := _clean_gap(v))}+ est = got.get("shots_estimate")+ src = []+ for seg in got.get("source") or []:+ if not isinstance(seg, dict) or seg.get("answer") not in SOURCE_CRITERIA:+ continue+ try:+ i, j = (int(x) for x in str(seg.get("tiles", "")).split("-"))+ except ValueError:+ continue+ p = {k: float(x) for k, x in (seg.get("p") or {}).items() if k in SOURCE_CRITERIA and isinstance(x, (int, float))}+ tot = sum(p.values())+ src.append({"tiles": [min(i, j), max(i, j)], "answer": seg["answer"],+ "p": {k: round(x / tot, 3) for k, x in p.items()} if tot > 0 else {seg["answer"]: 1.0}})+ if not (got.get("filled") or gaps or src or (isinstance(est, dict) and est.get("answer"))):+ return None # the empty template: "filled": true marks an answer where every gap is a plain continuation+ return {"gaps": gaps, "by": got.get("by") or "", **({"source": src} if src else {}),+ **({"shots_estimate": est} if isinstance(est, dict) and est.get("answer") else {})}+++def spikes(track: FrameTrack, t0: float, t1: float, level: float = 0.25) -> int:+ """How many separate sudden changes (frames changing by `level` or more, two frames apart) lie in [t0, t1]."""+ s = change_score(track)+ a, z = frame_at(track, t0) + 1, frame_at(track, t1) + 1+ hits = [i for i in range(a, min(z, len(s))) if s[i] >= level]+ return sum(1 for k, i in enumerate(hits) if k == 0 or i - hits[k - 1] > 2)+++def _windows(task: dict, gaps: dict, rnd: int = 1, track: FrameTrack | None = None) -> list[tuple[float, float, str]]:+ """Stretches to zoom into next: runs of neighbouring gaps answered transition / unsure on the overview (and cut,+ when the gap holds more than one sudden change: one answer can only place one cut), unsure on a zoom sheet (a+ transition there has been looked at closely already), split to ZOOM_SPAN."""+ ids = list(task["_gaps"])+ want = ("transition", "unsure") if rnd == 1 else ("unsure",)++ def zoom(g: str) -> bool:+ ans = (gaps.get(g) or {}).get("answer")+ return ans in want or (rnd == 1 and ans == "cut" and track is not None and spikes(track, *task["_gaps"][g]) > 1)+ pick = [g for g in ids if zoom(g)]+ runs: list[list[str]] = []+ for g in pick:+ if runs and ids.index(g) == ids.index(runs[-1][-1]) + 1:+ runs[-1].append(g)+ else:+ runs.append([g])+ out = []+ for r in runs:+ t0, t1 = task["_gaps"][r[0]][0], task["_gaps"][r[-1]][1]+ why = "unsure" if all(gaps[g]["answer"] == "unsure" for g in r) else ("cuts" if all(gaps[g]["answer"] == "cut" for g in r) else "transition")+ n = max(1, int(math.ceil((t1 - t0) / ZOOM_SPAN)))+ for k in range(n):+ out.append((t0 + (t1 - t0) * k / n, t0 + (t1 - t0) * (k + 1) / n, why))+ return out+++# ------------------------------------------------------------------ run ------------------------------------------++Asker = Callable[[dict, list[Path]], dict]+++def _public(task: dict) -> dict:+ return {k: v for k, v in task.items() if not k.startswith("_")}+++def _task_paths(sdir: Path, tid: str) -> tuple[Path, Path]:+ base = sdir if tid == "overview" else sdir / ("detail" if tid.startswith("shot_") else "zoom")+ return base / f"{tid}.task.json", base / f"{tid}.answer.json"+++def _write_task(sdir: Path, task: dict) -> None:+ tp, ap = _task_paths(sdir, task["id"])+ write_json(tp, {**_public(task), "gap_times": task.get("_gaps"), "frame_index": task.get("_frames")})+ if not ap.exists():+ write_json(ap, {"filled": False, **task["answer_template"]})+++def _load_task(sdir: Path, tid: str) -> dict | None:+ tp, _ = _task_paths(sdir, tid)+ if not tp.is_file():+ return None+ t = read_json(tp)+ t["_gaps"] = t.pop("gap_times", None) or {}+ t["_frames"] = t.pop("frame_index", None) or []+ return t+++def _reset(sdir: Path) -> None:+ for d in (sdir, sdir / "zoom", sdir / "detail"):+ for p in [*d.glob("*.json"), *d.glob("*.jpg")]:+ p.unlink()+++def run(video: str | Path, out: Path, track: FrameTrack, shots: list[Shot], info: VideoInfo | None = None,+ asker: Asker | None = None, workers: int = 4, detail: bool = True) -> dict:+ """Advance the survey as far as the answers allow. Stage 1 finds the scene changes (overview, then zoom rounds);+ stage 2 picks each shot's key frames (one detail sheet per shot). With `asker` (a VLM) every task is answered+ right away, the tasks of a round in parallel; without it the tasks waiting for an answer are returned, an agent+ fills their answer files (they are independent: several agents can work at once) and runs this again.+ Returns {"status": "done" | "waiting", "stage", "round", "waiting": [answer files], ...}."""+ video = str(video)+ info = info or video_info(video)+ sdir = Path(out) / "survey"+ sdir.mkdir(parents=True, exist_ok=True)+ src = _source(video, info)+ meta_p = sdir / "survey.json"+ meta = read_json(meta_p) if meta_p.is_file() else {}+ if meta.get("source") != src or meta.get("version") != VERSION:+ _reset(sdir)+ meta = {"version": VERSION, "source": src, "rounds": [["overview"]]}+ _write_task(sdir, overview_task(video, info, track, shots, sdir))+ write_json(meta_p, meta)++ def answer(tasks: list[dict], reader) -> None:+ if asker is None:+ return++ def one(t: dict) -> None:+ _, ap = _task_paths(sdir, t["id"])+ if reader(ap) is None:+ got = asker(_public(t), [Path(out) / im for im in t["images"]])+ write_json(ap, {"filled": True, "by": "vlm", **(got or {})})+ with ThreadPoolExecutor(max_workers=max(1, workers)) as pool:+ list(pool.map(one, tasks))++ def waiting(tasks: list[dict], reader, stage: str, rnd: int) -> dict | None:+ left = [t for t in tasks if reader(_task_paths(sdir, t["id"])[1]) is None]+ if not left:+ return None+ return {"status": "waiting", "stage": stage, "round": rnd, "waiting": [str(_task_paths(sdir, t["id"])[1]) for t in left],+ "tasks": [str(_task_paths(sdir, t["id"])[0]) for t in left],+ "images": [str(Path(out) / im) for t in left for im in t["images"]]}++ # ---- stage 1: scene changes+ found: dict[str, dict] = {}+ for rnd, ids in enumerate(meta["rounds"], start=1):+ tasks = [t for tid in ids if (t := _load_task(sdir, tid))]+ answer(tasks, read_answer)+ if (w := waiting(tasks, read_answer, "cuts", rnd)):+ return w+ nxt: list[tuple[float, float, str]] = []+ for t in tasks:+ ans = read_answer(_task_paths(sdir, t["id"])[1]) or {"gaps": {}}+ for g, span in t["_gaps"].items():+ if g in ans["gaps"]:+ found[g] = {"t": span, "round": rnd, **ans["gaps"][g]}+ elif rnd > 1: # a zoomed stretch: gaps left out are continuations, and replace the coarser answer+ found[g] = {"t": span, "round": rnd, "answer": "same", "p": {"same": 1.0}, "implicit": True}+ if rnd == 1 and ans.get("shots_estimate"):+ meta["shots_estimate"] = ans["shots_estimate"]+ if rnd == 1 and ans.get("source"):+ times = t["state"]["times"]+ half = float(t["state"].get("every", 1.0)) / 2+ meta["source_segments"] = [{"span": [round(max(0.0, times[min(sg["tiles"][0], len(times) - 1)] - half), 3),+ round(times[min(sg["tiles"][1], len(times) - 1)] + half, 3)],+ "answer": sg["answer"], "p": sg["p"], "by": ans.get("by") or ""} for sg in ans["source"]]+ if rnd < MAX_ROUNDS:+ nxt += _windows(t, ans["gaps"], rnd, track)+ if rnd == len(meta["rounds"]) and nxt:+ new = []+ for k, (t0, t1, why) in enumerate(nxt):+ tid = f"r{rnd + 1}_{k + 1:02d}"+ _write_task(sdir, zoom_task(video, info, track, shots, sdir, tid, t0, t1, rnd + 1, why))+ new.append(tid)+ meta["rounds"].append(new)+ write_json(meta_p, meta)+ return run(video, out, track, shots, info, asker, workers, detail)+ timeline = build_timeline(track, shots, found, meta)++ # ---- stage 2: key frames of every shot+ bounds = [0, *[c["frame"] for c in timeline["cuts"]], track.n]+ spans = list(zip(bounds[:-1], bounds[1:]))+ if detail:+ if meta.get("detail_for") != [c["frame"] for c in timeline["cuts"]]:+ for p in [*(sdir / "detail").glob("*")]:+ p.unlink()+ ids = []+ for k, (a, z) in enumerate(spans, start=1):+ t = detail_task(video, info, track, sdir, k, a, z, timeline["busy"])+ if t:+ _write_task(sdir, t)+ ids.append(t["id"])+ meta.update(detail=ids, detail_for=[c["frame"] for c in timeline["cuts"]])+ write_json(meta_p, meta)+ tasks = [t for tid in meta.get("detail", []) if (t := _load_task(sdir, tid))]+ answer(tasks, read_detail)+ if (w := waiting(tasks, read_detail, "keyframes", 1)):+ write_json(sdir / "timeline.json", timeline) # the cuts are settled already+ return w+ timeline["keyframes"] = keyframe_list(track, spans, timeline["busy"], sdir if detail else None)+ write_json(sdir / "timeline.json", timeline)+ return {"status": "done", "rounds": len(meta["rounds"]), "timeline": str(sdir / "timeline.json"),+ "shots": timeline["shots"], "cuts": len(timeline["cuts"]),+ "keyframes": sum(len(v) for v in timeline["keyframes"].values())}+++def keyframe_list(track: FrameTrack, spans: list[tuple[int, int]], busy: list[list[float]], sdir: Path | None) -> dict:+ """{shot number: [{t, frame, role, p?, by}]}: the AI's picks and names where a detail answer exists (plus the+ frame farthest from the in-between in every gap it said misses one), the tool's key frames elsewhere."""+ out: dict[str, list[dict]] = {}+ for k, (a, z) in enumerate(spans, start=1):+ rows: list[dict] = []+ t = _load_task(sdir, f"shot_{k:03d}") if sdir else None+ ans = read_detail(_task_paths(sdir, f"shot_{k:03d}")[1]) if t else None+ if t and ans and not ans.get("accept"):+ idx = t["_frames"]+ for j, v in ans["frames"].items():+ if 0 <= j < len(idx):+ rows.append({"frame": idx[j], "role": v["answer"], "p": round(max(v["p"].values()), 3), "by": "ai"})+ for i, j in ans["missing"]:+ if 0 <= i < j < len(idx) and idx[j] - idx[i] >= 2:+ got = key_frames(track, idx[i], idx[j] + 1, max_n=3, moving=KEY_MOVING * 0.4, moving_busy=KEY_MOVING_BUSY * 0.4)+ rows += [{"frame": f, "role": "missed", "by": "ai+tool"} for f in got if idx[i] < f < idx[j]][:1]+ if not any(r["frame"] == a for r in rows):+ rows.append({"frame": a, "role": "first", "by": "tool"})+ else:+ got = key_frames(track, a, z, [tuple(b) for b in busy])+ rows = [{"frame": f, "role": "first" if f == a else ("last" if f == z - 1 else "change"), "by": "tool"} for f in got]+ seen = set()+ rows = [r for r in sorted(rows, key=lambda r: r["frame"]) if not (r["frame"] in seen or seen.add(r["frame"]))]+ for r in rows:+ r["t"] = round(_t(track, r["frame"]), 3)+ out[str(k)] = rows+ return out+++def _finest(found: dict) -> dict:+ """Keep, for every stretch, the answers of the round that looked closest: a gap whose span holds gaps answered+ in a later round is replaced by them."""+ out = {}+ for g, v in found.items():+ t0, t1 = v["t"]+ if any(w["round"] > v["round"] and t0 - 1e-3 <= w["t"][0] and w["t"][1] <= t1 + 1e-3 for w in found.values()):+ continue+ out[g] = v+ return out+++def build_timeline(track: FrameTrack, shots: list[Shot], found: dict, meta: dict) -> dict:+ score = change_score(track)+ fin = _finest(found)+ cuts: list[dict] = []+ busy: list[list[float]] = []+ # runs of neighbouring transition gaps are one transition: the boundary in its middle, the run as its span+ items = sorted(fin.items(), key=lambda kv: kv[1]["t"][0])+ k = 0+ while k < len(items):+ g, v = items[k]+ ans = v["answer"]+ if ans == "busy":+ busy.append([round(v["t"][0], 3), round(v["t"][1], 3)])+ elif ans == "cut" or (ans == "unsure"):+ a, z = frame_at(track, v["t"][0]) + 1, frame_at(track, v["t"][1]) + 1+ b = a + int(np.argmax(score[a:max(a + 1, z)]))+ tb = round(_t(track, b), 3)+ cuts.append({"t": tb, "frame": int(b), "kind": v.get("kind", "cut") if ans == "cut" else "cut",+ "span": [tb, tb], "p": v["p"].get(ans, 0.5) if ans == "cut" else 0.5,+ "by": "survey", "round": v["round"], **({"unsure": True} if ans == "unsure" else {})})+ elif ans == "transition":+ run_ = [v]+ # one transition = neighbouring gaps of the same kind; a new kind right after is the next transition+ while (k + 1 < len(items) and items[k + 1][1]["answer"] == "transition" and abs(items[k + 1][1]["t"][0] - run_[-1]["t"][1]) < 1e-3+ and items[k + 1][1].get("kind") == run_[0].get("kind")):+ k += 1+ run_.append(items[k][1])+ t0, t1 = run_[0]["t"][0], run_[-1]["t"][1]+ a, z = frame_at(track, t0) + 1, frame_at(track, t1) + 1+ seg = score[a:max(a + 1, z)]+ # the boundary: the biggest single change inside the transition, else its middle+ b = a + int(np.argmax(seg)) if len(seg) and seg.max() > 0.15 else (a + z) // 2+ kinds = [r.get("kind") for r in run_ if r.get("kind")]+ cuts.append({"t": round(_t(track, b), 3), "frame": int(b), "kind": max(set(kinds), key=kinds.count) if kinds else "effect",+ "span": [round(t0, 3), round(t1, 3)], "p": round(float(np.mean([r["p"].get("transition", 0.5) for r in run_])), 3),+ "by": "survey", "round": max(r["round"] for r in run_)})+ k += 1+ # the detector's cuts: kept unless their gap was answered "same" with high probability+ same = [v for v in fin.values() if v["answer"] == "same" and not v.get("implicit") and v["p"].get("same", 0) >= DROP_TOOL_CUT_P]+ dropped = []+ near = 0.25 # a detector cut this close to a transition the survey found is that transition+ for s in shots[1:]:+ t = s.start+ if any(c["span"][0] - near <= t <= c["span"][1] + near for c in cuts):+ for c in cuts: # the survey found the same change: take the detector's exact frame when it lies inside+ if c["span"][0] - 1e-3 <= t <= c["span"][1] + 1e-3:+ c.update(frame=s.start_frame, t=round(t, 3), by="survey+tool")+ if c["kind"] in ("cut", "effect") and s.transition_in not in ("cut", "start"):+ c["kind"] = s.transition_in+ continue+ if any(v["t"][0] <= t <= v["t"][1] for v in same):+ dropped.append(round(t, 3))+ continue+ cuts.append({"t": round(t, 3), "frame": s.start_frame, "kind": s.transition_in or "cut", "span": [round(t, 3), round(t, 3)],+ "p": round(float(min(1.0, s.boundary_score)) or 0.6, 3), "by": "tool"})+ cuts.sort(key=lambda c: c["frame"])+ dedup: list[dict] = []+ tool_gap = max(2, int(round(0.12 * track.fps)))+ for c in cuts:+ # two changes the AI saw may be two frames apart (a flash frame); the detector's are kept 0.12 s apart+ gap = 2 if c["by"] != "tool" and dedup and dedup[-1]["by"] != "tool" else tool_gap+ if dedup and c["frame"] - dedup[-1]["frame"] < gap:+ if c["by"] != "tool" and dedup[-1]["by"] == "tool":+ dedup[-1] = c+ continue+ dedup.append(c)+ cuts = [c for c in dedup if 0 < c["frame"] < track.n - 1]+ edges = [0.0, *[c["t"] for c in cuts], _t(track, track.n - 1) + 1 / track.fps]+ lengths = [round(b - a, 3) for a, b in zip(edges[:-1], edges[1:])]+ dur = edges[-1]+ return {+ "version": VERSION, "source": meta.get("source"), "rounds": len(meta.get("rounds", [])),+ "shots_estimate": meta.get("shots_estimate"), "shots": len(cuts) + 1, "cuts": cuts,+ **({"looks": meta["source_segments"]} if meta.get("source_segments") else {}),+ **({"dropped_tool_cuts": dropped} if dropped else {}), "busy": busy,+ "rhythm": {"shot_lengths": lengths, "mean_shot_s": round(float(np.mean(lengths)), 3) if lengths else 0.0,+ "cuts_per_min": round(len(cuts) / dur * 60, 1) if dur else 0.0,+ "change_step_s": RHYTHM_STEP, "change": rhythm(track)},+ }+++def source_at(timeline: dict, t0: float, t1: float) -> dict | None:+ """The overview's opinion on how [t0, t1] was made: the segment holding most of it."""+ best, cover = None, 0.0+ for sg in timeline.get("looks") or []:+ c = min(t1, sg["span"][1]) - max(t0, sg["span"][0])+ if c > cover:+ best, cover = sg, c+ return best+++def load_timeline(out: Path, video: str | Path, info: VideoInfo) -> dict | None:+ """survey/timeline.json when it was made for this video."""+ p = Path(out) / "survey" / "timeline.json"+ if not p.is_file():+ return None+ try:+ tl = read_json(p)+ except (OSError, ValueError):+ return None+ return tl if tl.get("source") == _source(str(video), info) and tl.get("version") == VERSION else None+++# ------------------------------------------------------------------ VLM ------------------------------------------++def vlm_asker(client, lang_note: str = "") -> Asker:+ def ask(task: dict, images: list[Path]) -> dict:+ q = {k: task[k] for k in ("state", "questions")}+ prompt = (f"{task['instructions']}\n\n{lang_note}\n请求:\n{json.dumps(q, ensure_ascii=False)}\n\n"+ f"只输出 JSON,形如 {json.dumps(task['answer_template'], ensure_ascii=False)},gaps 里按 gap 编号填。")+ got = client.ask_json(prompt, [(p, "image/jpeg") for p in images], max_tokens=2048)+ return got if isinstance(got, dict) else {}+ return askdiff --git a/rea_video/videomd.py b/rea_video/videomd.pyindex c02caeb..79cd2d1 100644--- a/rea_video/videomd.py+++ b/rea_video/videomd.py@@ -36,7 +36,8 @@ OVERLAY_ID = {"huazi": "styled_text"}# shot-boundary kinds from the cut detector -> transition ids in the spec (`x-` = not in the taxonomy); plain cuts are not writtenTRANSITION_ID = {"jump": "jump_cut", "fade": "fade_through", "dissolve": "dissolve", "wipe": "wipe", "flash": "flash","slide": "slide", "whip": "whip", "zoom": "zoom", "spin": "spin", "blur": "x-blur", "glitch": "glitch",- "shake": "x-shake", "effect": "x-effect", "mg_transition": "x-mg_transition"}+ "shake": "x-shake", "effect": "x-effect", "mg_transition": "x-mg_transition",+ "morph": "x-morph", "match": "x-match"}# timeline keys, in line order; `~` = inferred by the toolsKEYS = ("story", "seen", "act", "layers", "camera", "transition", "overlay", "made~", "material~", "remake", "flag")@@ -90,7 +91,8 @@ _TRANSITION_WORDS = {"jump_cut": ("跳切", "jump cut"), "fade_through": ("黑"wipe": ("划像", "wipe"), "flash": ("闪白", "flash"), "slide": ("推移", "slide"), "whip": ("甩镜", "whip pan"),"zoom": ("缩放转场", "zoom"), "spin": ("旋转转场", "spin"), "x-blur": ("模糊转场", "blur"), "glitch": ("故障转场", "glitch"),"x-shake": ("抖动转场", "shake"), "x-effect": ("转场特效", "transition effect"),- "x-mg_transition": ("版式切换", "layout change")}+ "x-mg_transition": ("版式切换", "layout change"), "x-morph": ("形变转场", "morph"),+ "x-match": ("匹配剪辑", "match cut")}def _transition_in(r: dict) -> dict:@@ -175,6 +177,7 @@ def _shot_file(r: dict) -> str:"decided_by": DECIDED_BY.get(base["decided_by"], base["decided_by"]), "real_material": bool((r.get("material") or {}).get("has_real_material"))},"flags": [k for k in ("uncertain", "disputed") if base.get(k)] + (["low_confidence"] if base["confidence"] < 0.6 and base["decided_by"] != "user" else []),**({"transition_in": _transition_in(r)} if _transition_in(r) else {}),+ **({"keyframes": [[k["t"], k.get("role", "")] for k in r["keyframes"]]} if r.get("keyframes") else {}),"frames": {k: v for k, v in (("sheet", assets.get("sheet")), ("first", assets.get("first_frame")), ("last", assets.get("last_frame"))) if v},}title = T("# 镜头 {i} · {a}–{z}s · {v}", "# Shot {i} · {a}–{z}s · {v}", i=r["index"], a=f"{r['start']:.1f}", z=f"{r['end']:.1f}", v=r.get("verdict", ""))@@ -191,12 +194,53 @@ def _topics(b: dict) -> list[tuple[str, str, str, list[str]]]:("content", T("内容与结构", "Content and structure"), T("要讲什么、叙事线、结构时间轴、台词", "what it says, the narrative line, structure, the script"), _content_md(b)),("cast", T("角色、场景与道具", "Cast, scenes and props"), T("做角色参考图、写首帧提示词", "reference images for characters, first-frame prompts"), _cast_md(b)),("sound", T("声音", "Sound"), T("人声、BGM、音效、节拍和来源", "voice, music, sound effects, beats and sources"), _audio_md(b)),+ ("rhythm", T("节奏与关键帧", "Rhythm and key frames"), T("切点和转场的时间、镜头长度、画面变化曲线、每镜关键帧", "when cuts and transitions happen, shot lengths, the change curve, key frames of each shot"), rhythm_md(b)),("look", T("拍法、打光与剪辑", "Camera, lighting and editing"), T("有实拍镜头时:景别、机位、布光、器材", "for filmed shots: framing, camera, lighting, kit"), _visual_md(b)),("packaging", T("剪辑包装", "Packaging"), T("字幕、花字、贴纸、画中画的时间和样式", "subtitles, styled text, stickers, picture-in-picture: timing and style"), packaging_md(b)),("remake", T("复刻方案", "Remake plan"), T("生成单元、拍摄场次、代码合成、要准备的真实素材、表演与情绪", "generation units, shoots, code builds, real material to collect, acting and emotion"), _remake_md(b)),]+KEY_ROLE_WORDS = {"first": ("首帧", "first"), "last": ("尾帧", "last"), "move_start": ("动作开始", "move starts"),+ "move_end": ("动作到位", "move ends"), "extreme": ("转折 / 极值", "turn / extreme"), "enter": ("元素出现", "element in"),+ "exit": ("元素离开", "element out"), "framing": ("构图变化", "framing change"), "expression": ("表情峰值", "expression peak"),+ "transition_mid": ("转场中段", "mid-transition"), "light": ("颜色光线突变", "colour / light change"),+ "beat": ("卡点", "on the beat"), "missed": ("补的关键帧", "added key frame"), "change": ("画面变化", "change")}+++def _curve(vals: list[float], every: float, per: float = 0.5) -> str:+ """The change curve as one digit (0-9) per `per` seconds: the rhythm at a glance, a few tokens per second."""+ k = max(1, int(round(per / every)))+ return "".join(str(min(9, int(max(vals[i:i + k]) * 10))) for i in range(0, len(vals), k))+++def rhythm_md(b: dict) -> list[str]:+ """Cuts, transitions, shot lengths, the change curve and every shot's key frames, with times."""+ rh, sv = b.get("rhythm") or {}, b.get("survey") or {}+ if not rh and not any(r.get("keyframes") for r in b.get("shots", [])):+ return []+ out = [T("# 节奏与关键帧", "# Rhythm and key frames"), ""]+ if rh:+ out += [T("每分钟 {n} 刀,平均镜头 {m}s;镜头长度:{l}", "{n} cuts a minute, mean shot {m}s; shot lengths: {l}",+ n=rh.get("cuts_per_min"), m=rh.get("mean_shot_s"), l=" ".join(f"{x:.1f}" for x in rh.get("shot_lengths", []))), ""]+ if rh.get("change"):+ out += [T("画面变化曲线(每 0.5 秒一位,0 静止 – 9 全变):", "Change curve (one digit per 0.5 s, 0 still – 9 all new):"),+ "", f"`{_curve(rh['change'], float(rh.get('change_step_s') or 0.25))}`", ""]+ if sv.get("cuts"):+ out += [T("## 切点和转场", "## Cuts and transitions"), ""]+ for c in sv["cuts"]:+ span = c.get("span") or [c["t"], c["t"]]+ dur = f" {span[1] - span[0]:.2f}s" if span[1] > span[0] and c.get("kind", "cut") not in ("cut", "jump") else ""+ out.append(f"- {c['t']:.2f}s {c.get('kind', 'cut')}{dur}" + (T("(待确认)", " (to confirm)") if c.get("unsure") else ""))+ out.append("")+ rows = [(r["index"], r["keyframes"]) for r in b.get("shots", []) if r.get("keyframes")]+ if rows:+ out += [T("## 每镜关键帧", "## Key frames per shot"), ""]+ for i, kf in rows:+ out.append(f"- #{i}: " + ", ".join(f"{k['t']:.2f}s {T(*KEY_ROLE_WORDS.get(k.get('role', ''), (k.get('role', ''), k.get('role', ''))))}" for k in kf))+ return out++def _has_body(text: str) -> bool:return sum(1 for ln in text.splitlines() if ln.strip() and not ln.startswith("#")) >= 1diff --git a/skills/rea-video/SKILL.md b/skills/rea-video/SKILL.mdindex 7b28b22..ab6ad47 100644--- a/skills/rea-video/SKILL.md+++ b/skills/rea-video/SKILL.md@@ -31,13 +31,17 @@ VLM(能看图的多模态模型)建议配,不强制,配置方法也在 ````bash# ⓪ 先看记住了什么:用户偏好(默认引擎、是否开 VLM、给你的偏好说明)和常见纠正类型rea-video memory-# ① 拆解(产出 out/<名>/VIDEO.md + video/(给你读的拆片包)、report.html / report.md(给用户看)、breakdown.json、storyboard.jpg、audio.png、shots/、stems/)+# ① 先看后拆(能看图、没开 VLM 时):总览图定切点和转场,看不清的地方加密抽帧再看,再逐镜挑关键帧。+# 按输出的 images 看图,把答案写进 waiting 里的文件,再跑同一条命令,直到 status 是 done;同一轮的任务互不相关,可以分给几个子 agent 并发。+# 答案按 JEV 格式只写选项和概率,是 same 的 gap 不写;简单镜头的关键帧回 {"accept": true}。开了 VLM 时 decompose 会自动做这一步+rea-video survey ref.mp4 -o out/ref+# ② 拆解(产出 out/<名>/VIDEO.md + video/(给你读的拆片包)、report.html / report.md(给用户看)、breakdown.json、storyboard.jpg、audio.png、shots/、stems/)rea-video --env-file <你的 .env> decompose ref.mp4 -o out/ref --vlm --lang <zh|en> # --lang 按用户提问的语言选(见「交付给用户」);没有 VLM 配置就去掉 --env-file 和 --vlm;字幕/花字是日文就加 --ocr-lang ja,是韩文就加 --ocr-lang ko;台词是孟加拉语就加 --asr-lang bn-# ② 看紧凑摘要:低置信镜头会被标出;先看 VLM: 那一行确认 VLM 是否生效+# ③ 看紧凑摘要:低置信镜头会被标出;先看 VLM: 那一行确认 VLM 是否生效rea-video summary out/ref/breakdown.json```-**省 token,按拆片包逐层读**(格式见仓库 `docs/videomd.md`;地图一行一个文件:`路径 | 约 token | 内容`):先读 `out/ref/VIDEO.md`(卡片 + 概览 + 地图,约 2k token),多数问题到这里就能答;要按镜头回答时读 `video/timeline.md`(一行一镜,键名带 `~` 的是推断,不带的是画面里看得到的);要核实某一镜再打开 `video/shots/<编号>.md` 和它 `frames` 里的截图;某一方面(声音、包装、复刻方案)按地图打开对应的 `video/*.md`。不要读 `breakdown.json`(几十万字)或 `report.md`(那是给人看的)。复核时每镜看 `shots/shot_XXX.jpg` 联系表就够(已含首 / 中 / 尾帧),`_first` / `_last` 是复刻时给生成模型参照用的,不用另开。+**省 token,按拆片包逐层读**(格式见仓库 `docs/videomd.md`;地图一行一个文件:`路径 | 约 token | 内容`):先读 `out/ref/VIDEO.md`(卡片 + 概览 + 地图,约 2k token),多数问题到这里就能答;要按镜头回答时读 `video/timeline.md`(一行一镜,键名带 `~` 的是推断,不带的是画面里看得到的);要核实某一镜再打开 `video/shots/<编号>.md` 和它 `frames` 里的截图;某一方面(声音、包装、复刻方案)按地图打开对应的 `video/*.md`。不要读 `breakdown.json`(几十万字)或 `report.md`(那是给人看的)。节奏、转场和每镜关键帧在 `video/rhythm.md`。复核时每镜看 `shots/shot_XXX.jpg` 联系表就够(是这一镜的关键帧),`_first` / `_last` 是复刻时给生成模型参照用的,不用另开。### 看图复核并入(能看图的 agent 必做,开了 VLM 也建议做低置信镜头)