@dsh-gis/dsh-video-studio-skill 0.6.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +951 -0
  2. package/README.md +89 -21
  3. package/THIRD_PARTY_NOTICES.md +1 -0
  4. package/index.js +23 -7
  5. package/package.json +7 -3
  6. package/schemas/film.schema.json +235 -4
  7. package/skills/video-studio/SKILL.md +299 -27
  8. package/skills/video-studio/assets/film.json +7 -14
  9. package/skills/video-studio/assets/golden_frames.json +65 -0
  10. package/skills/video-studio/assets/scenes.py +115 -10
  11. package/skills/video-studio/assets/web/engine.js +81 -3
  12. package/skills/video-studio/assets/web/film.js +249 -101
  13. package/skills/video-studio/assets/web/index.html +9 -2
  14. package/skills/video-studio/assets/web/qa_text.js +36 -8
  15. package/skills/video-studio/references/audio-variation.md +159 -0
  16. package/skills/video-studio/references/audio.md +67 -5
  17. package/skills/video-studio/references/change-impact.md +2 -2
  18. package/skills/video-studio/references/quality-gates.md +25 -3
  19. package/skills/video-studio/references/style-packs.md +7 -3
  20. package/skills/video-studio/references/v08-quality.md +256 -0
  21. package/skills/video-studio/references/web-engine.md +19 -2
  22. package/skills/video-studio/references/word-timeline.md +147 -0
  23. package/skills/video-studio/requirements.txt +16 -1
  24. package/skills/video-studio/scripts/filmcheck.py +202 -12
  25. package/skills/video-studio/scripts/filmkit.py +792 -56
  26. package/skills/video-studio/scripts/gates.py +161 -14
  27. package/skills/video-studio/scripts/preflight.py +774 -0
  28. package/skills/video-studio/scripts/qa_frames.py +154 -23
  29. package/skills/video-studio/scripts/qaasr.py +1563 -0
  30. package/skills/video-studio/scripts/qavmaf.py +1442 -0
  31. package/skills/video-studio/scripts/render.py +1134 -78
  32. package/skills/video-studio/scripts/scorekit.py +305 -76
  33. package/skills/video-studio/scripts/selfcheck.py +576 -2
  34. package/skills/video-studio/scripts/sfxkit.py +262 -44
  35. package/skills/video-studio/scripts/stagewatch.py +159 -36
  36. package/skills/video-studio/scripts/stylekit.py +137 -18
  37. package/skills/video-studio/scripts/voicekit.py +23 -7
  38. package/skills/video-studio/scripts/webengine.py +1186 -85
  39. package/tools/audio_similarity.py +279 -0
  40. package/tools/ci_check.py +310 -59
  41. package/tools/estimate.py +251 -61
  42. package/tools/golden_frames.py +664 -0
  43. package/tools/selftest_noscipy.py +70 -0
@@ -35,6 +35,7 @@ import importlib.util
35
35
  import json
36
36
  import os
37
37
  import shutil
38
+ import subprocess
38
39
  import sys
39
40
  import time
40
41
  from pathlib import Path
@@ -90,14 +91,22 @@ def _file_sha1(path):
90
91
 
91
92
 
92
93
  def _frames_plan_stamp(tl, script, scenes_path, chunk):
93
- """分块计划的指纹:时长 / scenes.py 内容 / 剧本快照任一变化,旧分块就画出错帧。
94
+ """分块计划的指纹:时长 / scenes.py 内容 / 剧本快照 / 时间轴内容任一变化,旧分块就画出错帧。
94
95
 
95
96
  断点续跑只看"分块文件在不在"是危险的:改一句台词 -> 时间轴变了 -> 旧分块
96
97
  仍然被跳过复用,最后拼出一部"画面和旁白对不上"的片子却不报错。
98
+
99
+ 为什么不能只哈希 total/frames/fps:字幕窗口(voice_start/voice_end)与词级断点
100
+ (words_abs)都在 tl["scenes"] 里,而它们可以在 total 分毫不动的情况下变化
101
+ ——逐句被 min_dur 夹住时,重新合成的 TTS 只改句内时长、不改段落总长。只比三个
102
+ 标量会让这种情况静默复用旧分块(字幕按上一版的词断行画)。代价是每家分块计划
103
+ 多一次 timeline.json 的 json.dumps(几十 KB,相对渲一帧可忽略)。
97
104
  """
98
105
  body = json.dumps(dict(script), sort_keys=True, ensure_ascii=False, default=str)
106
+ tl_body = json.dumps(tl, sort_keys=True, ensure_ascii=False, default=str)
99
107
  payload = dict(total=round(float(tl["total"]), 3), frames=int(tl["frames"]),
100
108
  fps=int(tl["fps"]), chunk=int(chunk),
109
+ timeline=hashlib.sha1(tl_body.encode("utf-8")).hexdigest()[:16],
101
110
  scenes=_file_sha1(scenes_path),
102
111
  script=hashlib.sha1(body.encode("utf-8")).hexdigest()[:16])
103
112
  return hashlib.sha1(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()[:16]
@@ -143,6 +152,26 @@ def _web_entry(script):
143
152
  return entry
144
153
 
145
154
 
155
+ def _web_where(entry):
156
+ """报错里告诉用户 DURATION / FPS 到底写在哪:入口 HTML + 同目录脚本 + 一条能照抄的 grep。
157
+
158
+ 只报入口 HTML 不够用:模板的 window.DURATION 写在 web/film.js 开头(engine.js 另有
159
+ 兜底默认值),用户拿到 index.html 还是得全文翻。这里把候选文件一起列出来。
160
+ """
161
+ d = os.path.dirname(entry)
162
+ try:
163
+ scripts = sorted(n for n in os.listdir(d)
164
+ if n.lower().endswith((".js", ".mjs", ".html")))
165
+ except OSError:
166
+ scripts = []
167
+ tail = ("要改的文件:%s(入口 HTML)" % entry)
168
+ if scripts:
169
+ tail += ";页面脚本在 %s%s" % (
170
+ d, "(%s)" % " / ".join(scripts) if len(scripts) <= 6 else "")
171
+ tail += "\n 查 DURATION / FPS 定义在哪:grep -n \"window.DURATION\\|global.DURATION\\|DURATION =\" %s" % d
172
+ return tail
173
+
174
+
146
175
  # ---------------------------------------------------------------- 装载
147
176
  def load_module(path: str, name="film_scenes"):
148
177
  """每次都用独立模块名 + 全新 module 对象,避免跨片污染(历史坑:渲染出上一部片)。"""
@@ -204,6 +233,53 @@ def load_script(p) -> dict:
204
233
  return s
205
234
 
206
235
 
236
+ def _to_gif(mp4, gif, fps=12, width=640):
237
+ """mp4 -> GIF(两遍调色板,避免"一屏噪点"的默认调色板)。
238
+
239
+ GIF 只用来"快速看一眼大概长什么样"(发给别人、贴到文档里),
240
+ 不是交付物:它没有声音、色彩也被量化。真正的交付仍是 mp4。
241
+ """
242
+ pal = gif + ".palette.png"
243
+ _run_ff = K._run if hasattr(K, "_run") else None
244
+ vf1 = "fps=%d,scale=%d:-1:flags=lanczos,palettegen=stats_mode=diff" % (fps, width)
245
+ vf2 = "fps=%d,scale=%d:-1:flags=lanczos,paletteuse=dither=bayer:bayer_scale=3" % (fps, width)
246
+ for args in ([K.FFMPEG, "-y", "-v", "error", "-i", str(mp4), "-vf", vf1, pal],
247
+ [K.FFMPEG, "-y", "-v", "error", "-i", str(mp4), "-i", pal,
248
+ "-lavfi", vf2, "-loop", "0", str(gif)]):
249
+ p = subprocess.run(args, capture_output=True)
250
+ if p.returncode != 0:
251
+ raise RuntimeError("GIF 生成失败: " + p.stderr.decode("utf-8", "replace")[:400])
252
+ try:
253
+ os.remove(pal)
254
+ except OSError:
255
+ pass
256
+ return gif
257
+
258
+
259
+ def _atomic_json_retry(path, obj, tries=3, sleep_s=0.1):
260
+ """原子写 JSON + 有限退避(v0.8)。
261
+
262
+ Windows 上文件被杀毒/预览进程短暂占用时,一次写入失败会让**整片**跑挂。
263
+ 只对"可重试的写状态"退避,不对内容生成盲目重试(那会掩盖真错误)。
264
+ """
265
+ last = None
266
+ for i in range(max(1, int(tries))):
267
+ try:
268
+ d = os.path.dirname(os.path.abspath(str(path)))
269
+ if d:
270
+ os.makedirs(d, exist_ok=True)
271
+ tmp = str(path) + ".tmp"
272
+ with open(tmp, "w", encoding="utf-8") as fh:
273
+ json.dump(obj, fh, ensure_ascii=False, indent=1)
274
+ os.replace(tmp, str(path))
275
+ return True
276
+ except OSError as e: # noqa: BLE001
277
+ last = e
278
+ time.sleep(sleep_s * (i + 1))
279
+ print(" [WARN] 写 %s 失败(重试 %d 次):%s" % (path, tries, last))
280
+ return False
281
+
282
+
207
283
  def _need(cond, msg):
208
284
  if not cond:
209
285
  raise SystemExit("[前置产物缺失] " + msg)
@@ -229,8 +305,13 @@ def resolve_style(script, work=None, verbose=True):
229
305
  return script["_style"]
230
306
  ST = _stylekit()
231
307
  plan = ST.resolve_script_style(script)
232
- # 主题体检:坏主题现在拦,不要等渲完 300 帧
233
- bad = ST.theme_lint(ST.THEMES[plan["theme_id"]])
308
+ # 主题体检:坏主题现在拦,不要等渲完 300 帧。
309
+ # v0.7.2 修:以前只体检**基础主题**(ST.THEMES[theme_id]),而 scenes 实际用的是
310
+ # plan["theme"](= 基础主题 + film.json 的 visual.theme_overrides)。于是用 overrides
311
+ # 把 ink/bg 调成低对比度时,体检照样 PASS,渲完才发现字幕看不清。
312
+ # 实测:overrides ink=[30,30,30] / bg=[10,10,10] -> 基础主题 lint 为空,
313
+ # 最终主题 lint = ['ink 与背景对比度 1.09 < 7.0']。
314
+ bad = ST.theme_lint(plan.get("theme") or ST.THEMES[plan["theme_id"]])
234
315
  if bad:
235
316
  raise SystemExit("[主题体检失败] %s:%s" % (plan["theme_id"], ";".join(bad)))
236
317
  script["_style"] = plan
@@ -252,6 +333,14 @@ def _theme_for(script):
252
333
  plan = resolve_style(script)
253
334
  if plan.get("legacy"):
254
335
  return None
336
+ # plan["theme"] 是 stylekit 合并过 film.json 的 visual.theme_overrides 之后的最终主题,
337
+ # resolve_style 的对比度体检(theme_lint)用的就是它。这里必须用同一份:否则
338
+ # scenes 画背景吃 overrides、字幕底板/字色仍用基础主题——字幕压在同色背景上会看不清,
339
+ # 而体检还照报通过("门禁看着干净、其实没在查")。老 stylekit / 老计划没有 theme
340
+ # 字段时回落到基础主题,行为与本行改动前一致。
341
+ th = plan.get("theme")
342
+ if isinstance(th, dict):
343
+ return th
255
344
  return _stylekit().THEMES[plan["theme_id"]]
256
345
 
257
346
 
@@ -313,6 +402,7 @@ def st_tts(script, work, force=False):
313
402
  ensure_ascii=False, indent=1)
314
403
  if force:
315
404
  shutil.rmtree(os.path.join(work, "tts"), ignore_errors=True)
405
+ want_words = bool(script.get("words", True))
316
406
  done = K.tts_batch(lines, work,
317
407
  voice=script.get("voice", "zh-CN-YunxiNeural"),
318
408
  rate=script.get("rate", "+0%"),
@@ -323,14 +413,50 @@ def st_tts(script, work, force=False):
323
413
  [{"voice": r["voice"], "rate": r["rate"], "pitch": r["pitch"],
324
414
  "volume": r.get("volume", "+0%"),
325
415
  "persona": r.get("persona"), "tone": r.get("tone")} for r in vp],
326
- trim_db=float(script.get("trim_db", -42.0)))
416
+ trim_db=float(script.get("trim_db", -42.0)),
417
+ words=want_words,
418
+ backend=str((script.get("tts") or {}).get("backend") or "edge"))
327
419
  json.dump(done, open(os.path.join(work, "tts.json"), "w", encoding="utf-8"),
328
420
  ensure_ascii=False, indent=1)
329
421
  total = sum(float(x["dur"]) for x in done)
330
422
  print(" 语音总时长 %.2fs / %d 句" % (total, len(done)))
423
+ _write_words(work, done, want_words)
331
424
  return done
332
425
 
333
426
 
427
+ def _write_words(work, done, want_words):
428
+ """把逐句词级时间戳汇总成 work/words.json(v0.8)。
429
+
430
+ 结构:{schema, enabled, lines:{<id>:{dur, n, covered, tail, mono, words:[...]}}, stats}
431
+ 门禁与字幕都从这里读,不再各自去翻 *.mp3.json(单一事实来源)。
432
+ """
433
+ if not want_words:
434
+ print(" 词级时间戳: 未启用(film.json 里 words=false)")
435
+ return None
436
+ lines = {}
437
+ n_words = 0
438
+ n_bad = []
439
+ for row in done or []:
440
+ ws = row.get("words") or []
441
+ summ = K.words_summary(ws, row.get("dur"))
442
+ lines[str(row["id"])] = dict(dur=round(float(row.get("dur") or 0.0), 4),
443
+ words=ws, **{k: v for k, v in summ.items() if k != "n"},
444
+ n=summ["n"])
445
+ n_words += len(ws)
446
+ if not ws:
447
+ n_bad.append(row["id"])
448
+ payload = dict(schema=1, enabled=True, lines=lines,
449
+ stats=dict(lines=len(lines), words=n_words, empty=n_bad))
450
+ p = os.path.join(work, "words.json")
451
+ json.dump(payload, open(p, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
452
+ if n_bad:
453
+ print(" [WARN] %d 句拿不到词级事件(%s);这些句的词级门禁会记 skipped"
454
+ % (len(n_bad), "、".join(n_bad[:6])))
455
+ else:
456
+ print(" 词级时间戳: %d 句 / %d 词 -> %s" % (len(lines), n_words, p))
457
+ return payload
458
+
459
+
334
460
  # ---------------------------------------------------------------- 排版
335
461
  def st_layout(script, work, lines=None):
336
462
  lines = lines or json.load(open(os.path.join(work, "tts.json"), encoding="utf-8"))
@@ -353,6 +479,7 @@ def st_layout(script, work, lines=None):
353
479
  for lid, v in tail_extra.items():
354
480
  if lid in tail_map:
355
481
  tail_map[lid] = float(v)
482
+ vp = K.video_plan(script) # 画幅/帧率:非法配置在这里就报错,不拖到渲帧
356
483
  tl = K.build_timeline(lines,
357
484
  lead=script.get("lead", pace["lead"]),
358
485
  tail=script.get("tail", pace["tail"]),
@@ -360,9 +487,24 @@ def st_layout(script, work, lines=None):
360
487
  tail_map=tail_map or script.get("tail_map"),
361
488
  lead_map=lead_map,
362
489
  hold=script.get("hold", pace["hold"]),
363
- max_dur=script.get("max_dur"))
490
+ max_dur=script.get("max_dur"),
491
+ fps=vp["fps"])
492
+ tl["video"] = vp
493
+ print(" 画幅: %d×%d @ %d fps(内部构图 %d×%d%s)"
494
+ % (vp["out_w"], vp["out_h"], vp["fps"], vp["w"], vp["h"],
495
+ ",编码时 lanczos 缩放" if vp["scale"] else ""))
364
496
  tl["title"] = script["title"]
365
497
  tl["voice"] = script.get("voice", "zh-CN-YunxiNeural")
498
+ # v0.8:词级时间戳(句子时长仍是权威;词只用于字幕断行/锚点/门禁)
499
+ tl["words"] = bool(script.get("words", True))
500
+ wp = os.path.join(work, "words.json")
501
+ if tl["words"] and os.path.exists(wp):
502
+ try:
503
+ wj = json.load(open(wp, encoding="utf-8"))
504
+ tl["word_stats"] = wj.get("stats")
505
+ except Exception as e: # noqa: BLE001
506
+ print(" [WARN] words.json 读不了,词级能力本次不可用:%s" % e)
507
+ tl["words"] = False
366
508
  tl["crf"] = script.get("crf", 18)
367
509
  tl["preset"] = script.get("preset", "medium")
368
510
  tl["style"] = {"style": plan["style"], "theme_id": plan["theme_id"],
@@ -439,6 +581,19 @@ def st_cues(script, work, tl, engine="pil"):
439
581
  except Exception as e: # noqa: BLE001
440
582
  raise SystemExit("scenes.py 的 cues() 钩子报错:%s" % e) from e
441
583
  n_hook = _extend_safe(got, "scenes.py")
584
+ # v0.7.2:web 引擎下要提醒"两套时间基准混用"。
585
+ # scenes.py 的 cues() 是按 **PIL 时间轴**(timeline.json 的段落与 visual_at)算的,
586
+ # 页面动画则按 **页面自己的时间轴**(window.DURATION)。两者合并进同一份 cues.json 后:
587
+ # - 音效会按 PIL 时间响(页面画面此刻可能正在另一幕);
588
+ # - 音画同步门禁能把这种配对识别为"跨基准"并跳过(qa_frames 的 src 过滤),不报假 FAIL,
589
+ # 但**声音与画面对不上的事实仍然存在**。
590
+ # 不静默:说清现象与两条改法,让用户自己选路线。
591
+ if engine == "web" and n_hook:
592
+ print(" [WARN] web 引擎下仍合并了 scenes.py 的 %d 条 cue —— 它们按 PIL 时间轴生成,"
593
+ "页面动画按页面时间轴播放,两者基准不同:音效可能响在错误的幕上。" % n_hook)
594
+ print(" 两种改法:① 走 PIL 路线(--engine pil)用 scenes.py 这套 cue;"
595
+ "② 走 web 路线就把 cue 写进页面(window.getCues())或 film.json 的 sfx.cues,"
596
+ "并删除 scenes.py 的 cues() 钩子。")
442
597
 
443
598
  # web 引擎:从页面导出(需要浏览器)
444
599
  n_web = 0
@@ -476,7 +631,19 @@ def _st_cues_web(script, work):
476
631
  """调用 webengine.export_cues 导出页面提示点(engine=web 时)。"""
477
632
  we = _opt_module("webengine", "浏览器逐帧渲染需要 webengine.py;只用 PIL 路线可以不改 engine")
478
633
  entry = _web_entry(script)
479
- data = we.export_cues(entry)
634
+ tl = {}
635
+ try:
636
+ tp = os.path.join(str(work), "timeline.json")
637
+ if os.path.exists(tp):
638
+ tl = json.load(open(tp, encoding="utf-8"))
639
+ except Exception: # noqa: BLE001
640
+ tl = {}
641
+ style = _web_style_payload(we, script, tl)
642
+ vp = (tl.get("video") or {})
643
+ data = we.export_cues(entry, style=style,
644
+ width=int(vp.get("out_w") or K.W),
645
+ height=int(vp.get("out_h") or K.H),
646
+ fps=int(tl.get("fps") or K.FPS))
480
647
  return data or {}
481
648
 
482
649
 
@@ -521,21 +688,48 @@ def st_score(script, work, tl):
521
688
  style_arg = None if plan_s["legacy"] else str(mp.get("style") or plan_s["style"])
522
689
  kwargs = dict(bpm=float(mp["bpm"]), key=str(mp["key"] or "Dm"), anchors=anchors,
523
690
  sections=sections, seed=int(mp["seed_effective"]))
691
+ # v0.7:内容指纹参与配乐结构变奏(和弦替换 / 动机级数 / 鼓型 ghost,见
692
+ # references/audio-variation.md §3.3)。只在非 legacy 时传——不传 fingerprint 的
693
+ # scorekit 认不出这个 kwarg,会走下面的 TypeError 回退链,照样出片只少变奏。
694
+ # legacy 必须不传:v0.4 的逐样本兼容是硬契约(selfcheck 20/26 条守着)。
695
+ fp_hex = ""
696
+ if not plan_s["legacy"]:
697
+ fp_hex = str((plan_s.get("fingerprint") or {}).get("full") or "")
698
+ kw_fp = dict(kwargs, fingerprint=fp_hex) if fp_hex else kwargs
524
699
  # scorekit 0.5 起:style/mood + music_plan(一次把 bpm/key/mood/seed 全交出去,
525
700
  # 免得两处默认值打架)+ pace(把过碎的段落并进前一段)。
526
701
  # 旧 scorekit 没有这些 kwargs -> TypeError -> 自动退回老接口,不阻断出片。
702
+ # 四级回退:带指纹 -> 不带指纹 -> 只有 style/mood -> 最老的签名。
527
703
  pace = {"min_dur": float(plan_s["pacing"]["min_dur"]),
528
704
  "hold": float(plan_s["pacing"]["hold"])}
529
- try:
530
- samples, report = sk.render(float(tl["total"]), style=style_arg,
531
- mood=str(mp.get("mood") or "steady"),
532
- music_plan=mp, pace=pace, **kwargs)
533
- except TypeError:
705
+ mood_arg = str(mp.get("mood") or "steady")
706
+ samples = report = None
707
+ # v0.7.2:多级签名兼容链以前对**任何** TypeError 都继续换签名试,最后统一报
708
+ # "不接受任何一种已知签名"。scorekit 内部真出 TypeError(例如某个参数是 None 被拿去做
709
+ # 算术)时,用户会照着"签名不兼容"的方向白找半天。这里区分两类:
710
+ # - 报错文本含 "unexpected keyword argument" -> 确实是不认识这个参数,换签名重试;
711
+ # - 其它 TypeError -> 是**内部**错误,带上签名与错误信息立刻报,别吞。
712
+ attempts = (
713
+ dict(style=style_arg, mood=mood_arg, music_plan=mp, pace=pace, **kw_fp),
714
+ dict(style=style_arg, mood=mood_arg, music_plan=mp, pace=pace, **kwargs),
715
+ dict(style=style_arg, mood=mood_arg, **kwargs),
716
+ dict(**kwargs),
717
+ )
718
+ for attempt in attempts:
534
719
  try:
535
- samples, report = sk.render(float(tl["total"]), style=style_arg,
536
- mood=str(mp.get("mood") or "steady"), **kwargs)
537
- except TypeError:
538
- samples, report = sk.render(float(tl["total"]), **kwargs)
720
+ samples, report = sk.render(float(tl["total"]), **attempt)
721
+ break
722
+ except TypeError as err:
723
+ if "unexpected keyword argument" in str(err):
724
+ continue
725
+ raise SystemExit(
726
+ "[score] scorekit.render() 内部报错(不是签名不兼容,别去改调用参数):%s\n"
727
+ " 本次签名:%s\n 要看完整 traceback:set RENDER_DEBUG=1 后重跑"
728
+ % (err, ", ".join(sorted(k for k in attempt if k != "self")))
729
+ ) from err
730
+ if samples is None:
731
+ raise SystemExit("[score] scorekit.render() 不接受任何一种已知签名,无法出配乐"
732
+ "(试过 %d 种:从最全的参数到最简)" % len(attempts))
539
733
  if report and not plan_s["legacy"]:
540
734
  print(" 配乐风格: %s / mood %s / %s BPM / %s"
541
735
  % (report.get("style") or style_arg, mp.get("mood"),
@@ -551,8 +745,82 @@ def st_score(script, work, tl):
551
745
  return out
552
746
 
553
747
 
748
+ def _sfx_seed_context(script):
749
+ """v0.7:算音效的内容派生上下文 (style, content_fp, key, enabled)。
750
+
751
+ legacy(没写 style 字段)时返回全 None -> CueBus 走旧的 seed_base + i 路径,
752
+ v0.4 及以前的片子逐样本不变。参考 references/audio-variation.md §3.2 / §4。
753
+ """
754
+ plan = resolve_style(script)
755
+ sfx_cfg = script.get("sfx") or {}
756
+ want_content = bool(sfx_cfg.get("content_seed", True))
757
+ if plan.get("legacy") or not want_content:
758
+ return None, None, None
759
+ fp = (plan.get("fingerprint") or {}).get("full")
760
+ mus = plan.get("music") or {}
761
+ return str(plan.get("style")), str(fp) if fp else None, str(mus.get("key") or "Dm")
762
+
763
+
764
+ def _duck_transition_sfx(samples, cues, scenes, sr=K.SR, depth_db=-3.0, window=2.2):
765
+ """段落边界前的转场音效自动让位(v0.7,契约 §4)。
766
+
767
+ 配乐在段落交界自己已经有一段过门(scorekit 的 swell / riser / sub_boom),
768
+ sfx 轨再在同一时刻放 whoosh / riser,同一频段叠两层就是"配乐和音效听起来像同一套"。
769
+ 做法:对位于 [边界-window, 边界] 内的转场类 cue,在它的时长内乘一个 dB 增益包络。
770
+ 只压转场类,不碰 impact / 提示音(那是"该响"的语义重音)。
771
+ """
772
+ if not scenes or samples is None or not len(samples):
773
+ return samples
774
+ try:
775
+ import numpy as np
776
+ except Exception: # noqa: BLE001
777
+ return samples
778
+ x = np.array(samples, copy=True, dtype=np.float32)
779
+ n = len(x)
780
+ bounds = [float(s["start"]) for s in scenes if float(s.get("start", 0.0)) > 0.5]
781
+ if not bounds:
782
+ return x
783
+ kinds = 0
784
+ for c in cues or []:
785
+ if str(c.get("type")) not in ("whoosh", "riser", "reverse_swell"):
786
+ continue
787
+ t = float(c.get("t", -1.0))
788
+ if t < 0:
789
+ continue
790
+ near = any(abs(t - b) <= window for b in bounds)
791
+ if not near:
792
+ continue
793
+ dur = float(c.get("dur") or 1.5)
794
+ s = max(0, int(round(t * sr)))
795
+ e = min(n, int(round((t + dur) * sr)))
796
+ if e <= s:
797
+ continue
798
+ g = 10.0 ** (depth_db / 20.0)
799
+ k = min(80, max(8, int(0.01 * sr)))
800
+ ramp = min((e - s) // 2, k)
801
+ seg = x[s:e]
802
+ if ramp > 0:
803
+ env = np.full(e - s, g, dtype=np.float32)
804
+ env[:ramp] = np.linspace(1.0, g, ramp, dtype=np.float32)
805
+ env[-ramp:] = np.linspace(g, 1.0, ramp, dtype=np.float32)
806
+ seg = seg * env[:, None] if seg.ndim == 2 else seg * env
807
+ else:
808
+ seg = seg * g
809
+ x[s:e] = seg
810
+ kinds += 1
811
+ if kinds:
812
+ print(" 过门避让: %d 条转场音效在段落边界前 %.1fs 内 -%.0f dB(避免和配乐过门撞车)"
813
+ % (kinds, window, abs(depth_db)))
814
+ return x
815
+
816
+
554
817
  def st_sfx(script, work, tl):
555
- """按提示点合成音效轨 -> work/sfx.wav。没有 cues.json 就跳过。"""
818
+ """按提示点合成音效轨 -> work/sfx.wav。没有 cues.json 就跳过。
819
+
820
+ v0.7:非 legacy 时走内容派生 seed(跨片同一位置不再逐样本相同),
821
+ 并把配乐调性透传给提示音配方(不再硬编码 Dm);
822
+ 段落边界前的转场音效自动让位(不与配乐过门撞车)。
823
+ """
556
824
  print("== SFX")
557
825
  cues_path = os.path.join(work, "cues.json")
558
826
  if not os.path.exists(cues_path):
@@ -564,10 +832,12 @@ def st_sfx(script, work, tl):
564
832
  print(" cues.json 里没有提示点,跳过")
565
833
  return None
566
834
  sfx_cfg = script.get("sfx") or {}
835
+ style, content_fp, key = _sfx_seed_context(script)
567
836
  try:
568
837
  samples = bus.build_audio(total=tl["total"],
569
838
  base_db=sfx_cfg.get("base_db"),
570
- default_gain_db=float(sfx_cfg.get("gain_db", 0.0)))
839
+ default_gain_db=float(sfx_cfg.get("gain_db", 0.0)),
840
+ style=style, content_fp=content_fp, key=key)
571
841
  except Exception as e: # noqa: BLE001
572
842
  # 音效轨是"增强"不是"必需":sfxkit 缺失/配方不全时不要拖死整片,
573
843
  # 但必须把原因喊出来(静默降级比报错更危险)。
@@ -576,6 +846,10 @@ def st_sfx(script, work, tl):
576
846
  if os.path.exists(stale):
577
847
  os.remove(stale)
578
848
  return None
849
+ if not sfx_cfg.get("duck_transitions", True):
850
+ pass
851
+ else:
852
+ samples = _duck_transition_sfx(samples, bus.resolved(), tl.get("scenes") or [])
579
853
  out = os.path.join(work, "sfx.wav")
580
854
  peak = K.wav_write(out, samples)
581
855
  print(" sfx.wav %.2fs 峰值 %.3f 声道 %d" % (
@@ -672,27 +946,94 @@ def st_audio(tl, work, script):
672
946
  plan_s = resolve_style(script)
673
947
  # 风格化的 duck 深度:轻快/极简风格的配乐更"薄",让位可以浅一点;
674
948
  # 电影/史诗要压得更狠。用户显式写 music.duck_db 时永远以用户为准。
675
- duck_default = 3.0
949
+ # v0.7:整体 +1 dB —— 旧值(2.0/2.5/3.0/4.5)下配乐只比音效低 1.5 dB、duck 仅 3 dB,
950
+ # 段落过门时两者在同一频段几乎等高,是"配乐和音效听起来像同一套"的混音侧成因。
951
+ duck_default = 4.0
676
952
  if not plan_s["legacy"]:
677
- duck_default = {"mono": 2.0, "lo-fi": 2.5, "magazine": 2.5,
678
- "cinema": 4.5, "epic": 4.5}.get(plan_s["style"], 3.0)
953
+ duck_default = {"mono": 3.0, "lo-fi": 3.5, "magazine": 3.5,
954
+ "cinema": 5.5, "epic": 5.5}.get(plan_s["style"], 4.0)
679
955
  samples = K.mix_film(voice, music, sfx, total=total,
680
956
  voice_gain=float(script.get("voice_gain", 1.0)),
681
- music_gain_db=float(mus.get("gain_db", -1.5)),
957
+ # v0.7.1 旁白优先:配乐基线从 -1.5 dB 降到 -12 dB。
958
+ # 视频以旁白为主,-1.5 dB 时背景与台词响度几乎等高,观众要费力分辨字;
959
+ # 12 dB 是"人声明显压住背景"的经验线(audio.md §2 的那条设计标准)。
960
+ music_gain_db=float(mus.get("gain_db", -12.0)),
682
961
  sfx_gain_db=float((script.get("sfx") or {}).get("mix_gain_db", 0.0)),
683
- duck_db=float(mus.get("duck_db", duck_default)))
962
+ duck_db=float(mus.get("duck_db", duck_default)),
963
+ # 旁白说话时再压背景(侧链):配乐 6 dB、音效 3 dB;
964
+ # 间隙自动恢复,避免整片背景被闷住。显式写 0 可关掉。
965
+ voice_duck_db=float(mus.get("voice_duck_db", 6.0)),
966
+ voice_duck_sfx_db=float(mus.get("voice_duck_sfx_db", 3.0)),
967
+ voice_thresh_db=float(mus.get("voice_thresh_db", -42.0)),
968
+ voice_floor_db=float(mus.get("voice_floor_db", -60.0)),
969
+ # SNR 兜底:混音后实测人声活跃区的人声/背景差,不足 12 dB 自动补压背景。
970
+ # 这是"画面/素材电平再离谱也不许盖住旁白"的最后一道闸;0 = 关。
971
+ guard_snr_db=float(mus.get("guard_snr_db", 12.0)),
972
+ guard_cap_db=float(mus.get("guard_cap_db", 30.0)))
684
973
  out = os.path.join(work, "audio.wav")
685
974
  peak = K.wav_write(out, samples)
686
975
  print(" audio.wav %.2fs 峰值 %.3f 声道 %d" % (K.wav_dur(out), peak, 2))
687
976
  return out
688
977
 
689
978
 
979
+ # ---------------------------------------------------------------- 预检闸门
980
+ def _run_preflight(script, work, engine, tl=None, skip=False):
981
+ """渲染前资源闸门(v0.8):缺字形 / 坏音频 / 缺字体,在渲第一帧之前就 fail。
982
+
983
+ 为什么值得单独立一道闸:这类问题以前都是"片渲完、QA 才报"——870 帧白跑,
984
+ 而且 reports 里只有一句"缺字形",说不清是哪个字段哪句台词。
985
+ 三档语义:没装 preflight.py -> skipped(写明原因);有 error -> fail;
986
+ 只有 warning -> pass(warning 仍进账本,不静默)。
987
+ """
988
+ lg = _gate()
989
+ pf = _try_module("preflight")
990
+ if skip:
991
+ if lg is not None:
992
+ lg.bypass("渲染前资源预检(--no-preflight)", "本条不算通过,只记录")
993
+ print(" [preflight] --no-preflight:跳过资源预检(QC 报告里会留痕)")
994
+ return True
995
+ if pf is None:
996
+ if lg is not None:
997
+ lg.skip("G0", "渲染前资源预检", "没有 preflight.py(老版本工作目录,拷一份进来才能查)")
998
+ print(" [preflight] 没有 preflight.py,跳过资源预检(会记 skipped)")
999
+ return True
1000
+ try:
1001
+ res = pf.check(script, work=work, engine=engine, timeline=tl)
1002
+ except Exception as e: # noqa: BLE001
1003
+ if lg is not None:
1004
+ lg.fail("G0", "渲染前资源预检", "预检本身报错:%s" % e)
1005
+ print(" [FAIL][preflight] 预检自身出错:", e)
1006
+ return False
1007
+ for w in (res.get("warnings") or [])[:6]:
1008
+ print(" [WARN][preflight] %s" % (w.get("msg") if isinstance(w, dict) else w))
1009
+ errs = res.get("errors") or []
1010
+ st = (res.get("checks") or {})
1011
+ detail = " ".join("%s=%s" % (k, v.get("status")) for k, v in st.items()) or "-"
1012
+ if errs:
1013
+ if lg is not None:
1014
+ lg.fail("G0", "渲染前资源预检", "%d 处问题:%s" % (
1015
+ len(errs), ";".join((e.get("msg") if isinstance(e, dict) else str(e))
1016
+ for e in errs[:3])))
1017
+ print(" [FAIL][preflight] %d 处问题(下面是前几条):" % len(errs))
1018
+ for e in errs[:8]:
1019
+ msg = e.get("msg") if isinstance(e, dict) else str(e)
1020
+ where = (e.get("where") if isinstance(e, dict) else "") or ""
1021
+ print(" - %s%s" % ((where + ":") if where else "", msg))
1022
+ return False
1023
+ if lg is not None:
1024
+ lg.ok("G0", "渲染前资源预检", detail)
1025
+ print(" [preflight] %s" % detail)
1026
+ return True
1027
+
1028
+
690
1029
  # ---------------------------------------------------------------- 渲染
691
1030
  def _render_range(tl, mod, script, f0, f1, out_path, crf, preset, progress=True):
692
1031
  """渲染 [f0, f1) 帧区间到 out_path。纯函数:同一帧号永远画出同一张图。"""
693
1032
  scenes = tl["scenes"]
694
1033
  total = tl["total"]
695
- sink = K.FrameSink(out_path, crf=crf, preset=preset)
1034
+ _vp = K.video_plan(script)
1035
+ sink = K.FrameSink(out_path, fps=float(tl["fps"]), crf=crf, preset=preset,
1036
+ out_w=_vp["out_w"], out_h=_vp["out_h"])
696
1037
  idx = 0
697
1038
  t_start = time.time()
698
1039
  last_rep = 0
@@ -708,8 +1049,9 @@ def _render_range(tl, mod, script, f0, f1, out_path, crf, preset, progress=True)
708
1049
  th = _theme_for(script) if _THEME_CACHE.get("k") != id(script) else _THEME_CACHE.get("th")
709
1050
  if id(script) != _THEME_CACHE.get("k"):
710
1051
  _THEME_CACHE.update(k=id(script), th=th)
711
- frame = K.draw_subtitle(frame, K.sub_at(scenes, t, script.get("sub_max_hold")),
712
- theme=th)
1052
+ _hold = script.get("sub_max_hold")
1053
+ frame = K.draw_subtitle(frame, K.sub_at(scenes, t, _hold), theme=th,
1054
+ words=K.sub_words_at(scenes, t, _hold))
713
1055
  fade = 1.0
714
1056
  if t < 0.5:
715
1057
  fade *= K.ease_out(t / 0.5)
@@ -732,9 +1074,36 @@ def _render_range(tl, mod, script, f0, f1, out_path, crf, preset, progress=True)
732
1074
  return sink.close()
733
1075
 
734
1076
 
1077
+ def _seg_usable(path, frames):
1078
+ """已有分块能不能复用:体积够 + 头部声明的帧数与计划一致。
1079
+
1080
+ 为什么不能只看 size>1024:Ctrl-C / 杀进程留下的半截 mp4 也 >1024,被当成
1081
+ "已存在"跳过后,拼接只在最后报一句"拼接后时长 0.07s != 预期 29.00s"。
1082
+ v0.7.2 起分块先写 .part 再 os.replace,正常中断不会留下半截正式文件;这里
1083
+ 再补一道头部 nb_frames 比对,挡住"文件在/大小对但帧数不对"的异常(例如被
1084
+ 外部工具截断过)。
1085
+
1086
+ 注意:**不做** -count_frames 逐帧核对。实测 390 帧的块要 3.5 s(只读头部
1087
+ 0.2 s),长片几十个块会让每次 --resume 多花几分钟;被截断的 mp4 头部仍写着
1088
+ 完整 nb_frames,逐帧核对才是唯一能查出来的手段,代价与收益不成比例——真遇到
1089
+ 这种情况由拼接后的时长校验兜底,并在报错里指明怎么重来。
1090
+ """
1091
+ try:
1092
+ if not os.path.exists(path) or os.path.getsize(path) <= 1024:
1093
+ return False
1094
+ info = K.probe(path) or {}
1095
+ for st in info.get("streams") or []:
1096
+ if st.get("codec_type") == "video" and st.get("nb_frames"):
1097
+ return int(st["nb_frames"]) == int(frames)
1098
+ # 读不出 nb_frames(老封装 / ffprobe 版本差异):退回到"体积够就信"
1099
+ return True
1100
+ except Exception: # noqa: BLE001
1101
+ return False
1102
+
1103
+
735
1104
  def _render_chunk_worker(args):
736
1105
  """分块渲染工作单元(供 multiprocessing 调用;函数必须模块级可 pickle)。"""
737
- (tl_path, scenes_path, script_path, f0, f1, out_path, crf, preset) = args
1106
+ (tl_path, scenes_path, script_path, f0, f1, out_path, crf, preset, part_path) = args
738
1107
  tl = json.load(open(tl_path, encoding="utf-8"))
739
1108
  script = json.load(open(script_path, encoding="utf-8"))
740
1109
  script["_total"] = tl["total"]
@@ -749,7 +1118,12 @@ def _render_chunk_worker(args):
749
1118
  print(" [WARN] 子进程重解风格失败,回退到快照里的 _style:%s" % e)
750
1119
  script["_style"] = json.load(open(script_path, encoding="utf-8")).get("_style")
751
1120
  mod = load_module(scenes_path, "film_scenes_chunk_%d" % f0)
752
- return _render_range(tl, mod, script, f0, f1, out_path, crf, preset, progress=False)
1121
+ # 先写 .part 再改名:中途被 Ctrl-C / 被杀时,目标文件名对应的永远是一段**完整**
1122
+ # 编码结果。否则半截 mp4 只要 >1024 字节就会被 --resume 当成"已存在"跳过,
1123
+ # 拼接后时长对不上才报错(实测:截断到 60 KB 的块 -> 拼接后 0.07s vs 预期 29.00s)。
1124
+ _render_range(tl, mod, script, f0, f1, part_path, crf, preset, progress=False)
1125
+ os.replace(part_path, out_path)
1126
+ return out_path
753
1127
 
754
1128
 
755
1129
  def st_frames(tl, work, scenes_mod, script, jobs=1, resume=True, engine="pil"):
@@ -813,13 +1187,31 @@ def st_frames(tl, work, scenes_mod, script, jobs=1, resume=True, engine="pil"):
813
1187
 
814
1188
  todo = []
815
1189
  planned = set()
1190
+ # 上次被中断留下的半成品(编码中途的残片):不算分块,直接清掉,别让它占盘。
1191
+ # 名字带 _part_ 前缀,既不会被 stale 检测当成"不属于当前计划的旧分块",
1192
+ # 也不会被 _seg_usable 当成"已存在的分块"跳过。
1193
+ for n in os.listdir(seg_dir):
1194
+ if n.startswith("_part_"):
1195
+ try:
1196
+ os.remove(os.path.join(seg_dir, n))
1197
+ except OSError:
1198
+ pass
816
1199
  for (f0, f1) in plan:
817
1200
  seg = os.path.join(seg_dir, "seg_%06d_%06d.mp4" % (f0, f1))
818
1201
  planned.add(os.path.basename(seg))
819
- if resume and os.path.exists(seg) and os.path.getsize(seg) > 1024:
1202
+ if resume and _seg_usable(seg, int(f1) - int(f0)):
820
1203
  print(" skip 段 %d-%d(已存在)" % (f0, f1))
821
1204
  continue
822
- todo.append((tl_path, scenes_path, script_path, f0, f1, seg, crf, preset))
1205
+ if os.path.exists(seg):
1206
+ # 存在但不可用(半截 / 时长不符):删掉重渲,别让它混进拼接
1207
+ print(" [WARN] 段 %d-%d 已存在但帧数/时长对不上,重渲(%d 字节)"
1208
+ % (f0, f1, os.path.getsize(seg)))
1209
+ try:
1210
+ os.remove(seg)
1211
+ except OSError:
1212
+ pass
1213
+ part = os.path.join(seg_dir, "_part_" + os.path.basename(seg))
1214
+ todo.append((tl_path, scenes_path, script_path, f0, f1, seg, crf, preset, part))
823
1215
 
824
1216
  # 旧计划留下的分块不会参与拼接,但会一直占盘:说出来,不静默
825
1217
  stale = [n for n in os.listdir(seg_dir)
@@ -861,36 +1253,77 @@ def st_frames(tl, work, scenes_mod, script, jobs=1, resume=True, engine="pil"):
861
1253
  return silent
862
1254
 
863
1255
 
1256
+ def _web_style_payload(we, script, tl=None):
1257
+ """把风格包解析成 webengine 能吃的 __STYLE__ 载荷(v0.8)。
1258
+
1259
+ style=None(legacy 项目 / 解析失败)时返回 None —— webengine 收到 None 连
1260
+ add_init_script 都不调,页面行为与 v0.7 逐字节一致(这是兼容性硬要求)。
1261
+ """
1262
+ try:
1263
+ style_plan = resolve_style(script, verbose=False)
1264
+ except Exception as e: # noqa: BLE001
1265
+ print(" [WARN] web 风格包解析失败,页面用内置配色:%s" % e)
1266
+ return None
1267
+ if not style_plan or style_plan.get("legacy"):
1268
+ return None
1269
+ vp = (tl or {}).get("video") or {}
1270
+ try:
1271
+ return we.normalize_style(style_plan,
1272
+ width=int(vp.get("out_w") or K.W),
1273
+ height=int(vp.get("out_h") or K.H),
1274
+ fps=int((tl or {}).get("fps") or K.FPS))
1275
+ except Exception as e: # noqa: BLE001
1276
+ # 载荷不合法要**说出来**:静默回落会让"换了风格但页面没变"变成一个谜。
1277
+ print(" [WARN] web 风格载荷不可用(%s),页面用内置配色" % e)
1278
+ return None
1279
+
1280
+
864
1281
  def _st_frames_web(tl, work, script, jobs=1, resume=True):
865
1282
  """浏览器逐帧渲染:交给 webengine.render_full(分块并行 + 断点续跑 + 缺口检测)。
866
1283
 
867
1284
  页面的 window.DURATION / window.FPS 是切块与校验的唯一真值来源:
868
1285
  和 timeline.json 对不上就直接报错(十有八九是改了剧本没重新 layout)。
1286
+ v0.8:把风格包与画幅/帧率一起注入页面(window.__STYLE__),页面不再是深蓝橙写死。
869
1287
  """
870
1288
  we = _opt_module("webengine",
871
1289
  "浏览器渲染需要 webengine.py(本技能 scripts/ 里自带;还需要 pip install playwright)")
872
1290
  entry = _web_entry(script)
873
1291
  silent = os.path.join(work, "silent.mp4")
874
1292
  web = script.get("web") or {}
875
-
876
- page_dur, page_fps = we.page_meta(entry)
1293
+ style = _web_style_payload(we, script, tl)
1294
+ vp = tl.get("video") or {}
1295
+ canvas_w = int(vp.get("out_w") or K.W)
1296
+ canvas_h = int(vp.get("out_h") or K.H)
1297
+ if style is not None:
1298
+ print(" 风格注入: %s(%dx%d @ %s fps)"
1299
+ % (style.get("style") or style.get("theme_id") or "custom",
1300
+ canvas_w, canvas_h, tl.get("fps")))
1301
+
1302
+ page_dur, page_fps = we.page_meta(entry, style=style,
1303
+ width=canvas_w, height=canvas_h,
1304
+ fps=int(tl["fps"]))
877
1305
  if abs(float(page_fps) - float(tl["fps"])) > 1e-6:
878
1306
  raise RuntimeError(
879
1307
  "页面 FPS=%s 与 timeline fps=%s 不一致。浏览器逐帧渲染的帧号就是 f/FPS,"
880
- "两边必须同帧率:改页面 window.FPS,或重新 --stage layout。"
881
- % (page_fps, tl["fps"]))
1308
+ "两边必须同帧率:把页面里的 window.FPS 改成 %s(或重新 --stage layout 生成"
1309
+ "与页面一致的 timeline)。\n %s"
1310
+ % (page_fps, tl["fps"], tl["fps"], _web_where(entry)))
882
1311
  if abs(float(page_dur) - float(tl["total"])) > 0.05:
883
1312
  raise RuntimeError(
884
1313
  "页面 DURATION=%.3fs 与 timeline 总时长 %.3fs 不一致(差 %.3fs)。\n"
885
- " 页面里的时长必须等于 timeline.total;跑 --stage layout 后把新的 total 写进页面。"
886
- % (float(page_dur), float(tl["total"]), abs(float(page_dur) - float(tl["total"]))))
1314
+ " 页面里的时长必须等于 timeline.total;把页面里的 window.DURATION 改成 %.3f"
1315
+ "(跑过新的 --stage layout 之后,取 timeline.json 的 total)。\n %s"
1316
+ % (float(page_dur), float(tl["total"]), abs(float(page_dur) - float(tl["total"])),
1317
+ float(tl["total"]), _web_where(entry)))
887
1318
 
888
1319
  out = we.render_full(entry, silent, float(tl["total"]),
889
1320
  workers=max(1, int(jobs)),
890
1321
  chunk_s=float(web.get("chunk_s", 30.0)),
891
1322
  resume=bool(resume),
892
1323
  crf=int(script.get("crf", 17)),
893
- preset=str(script.get("preset", "slow")))
1324
+ preset=str(script.get("preset", "slow")),
1325
+ style=style, width=canvas_w, height=canvas_h,
1326
+ fps=int(tl["fps"]))
894
1327
  got = K.media_dur(str(out) if out else silent)
895
1328
  want = float(tl["frames"]) / float(tl["fps"])
896
1329
  if abs(got - want) > 0.5:
@@ -921,7 +1354,12 @@ def _qa_gates(lg, rep, deep, tl, work):
921
1354
  v = next((s for s in streams if s.get("codec_type") == "video"), {})
922
1355
  a = next((s for s in streams if s.get("codec_type") == "audio"), None)
923
1356
  fmt = pr.get("format") or {}
924
- W, H, FPS = K.W, K.H, K.FPS
1357
+ # v0.8:容器门禁比对的是**交付规格**(timeline 里记的 video 块),不是引擎内部常量。
1358
+ # 老 timeline(升级前生成的)没有 video 字段 -> 回落到 1920x1080,行为不变。
1359
+ _vp = tl.get("video") or {}
1360
+ W = int(_vp.get("out_w") or K.W)
1361
+ H = int(_vp.get("out_h") or K.H)
1362
+ FPS = float(_vp.get("fps") or tl.get("fps") or K.FPS)
925
1363
 
926
1364
  # ---- G4 容器:分辨率 / 帧率 / 音轨 / 时长 ----
927
1365
  try:
@@ -981,6 +1419,9 @@ def _qa_gates(lg, rep, deep, tl, work):
981
1419
  else:
982
1420
  lg.ok("G8", "首尾之外无长黑帧", "0 段")
983
1421
 
1422
+ # ---- G10 词级时间戳(v0.8):覆盖率 / 单调 / 末词偏差 ----
1423
+ _word_gate(lg, tl, work)
1424
+
984
1425
  # ---- G9 帧级深检(闪烁 / 空窗 / 音画同步)----
985
1426
  if deep is None:
986
1427
  lg.skip("G9", "帧级深检(闪烁/空窗/同步)", "没有 qa_frames.py 或深检失败")
@@ -1000,7 +1441,218 @@ def _qa_gates(lg, rep, deep, tl, work):
1000
1441
  (lg.ok if ok9 else lg.fail)("G9", "帧级深检(闪烁/空窗/同步超差)", detail9)
1001
1442
 
1002
1443
 
1003
- def st_qa(film, tl, work, scenes_mod=None, script=None):
1444
+ WORD_TAIL_MAX = 0.40 # 末词终点到句尾静音的上限(实测模板 0.07–0.12 s)
1445
+ WORD_START_MAX = 0.20 # 句首到首词的上限(裁剪把开头静音切掉后通常 ≤ 0.05 s)
1446
+ WORD_COVER_MIN = 0.45 # 词时长之和 / 句实测时长:中文有词间空隙,0.45 是"明显少了"的线
1447
+
1448
+
1449
+ def _word_gate(lg, tl, work):
1450
+ """词级时间戳门禁(v0.8)。
1451
+
1452
+ 为什么值得单独一道闸:词级数据是"字幕按词折行 / cue 词锚点"的依据,
1453
+ 但它来自一个**逆向接口**(edge-tts)。服务端一改,最可能的表现是"仍返回音频、
1454
+ 但词事件为空或整体偏移"——不查就永远发现不了,而画面上只表现为字幕断行变丑。
1455
+ 三档语义:没有启用 / 没有 words.json -> skipped(写明原因),不许冒充 pass。
1456
+ """
1457
+ wp = os.path.join(str(work), "words.json")
1458
+ if not tl.get("words"):
1459
+ lg.skip("G10", "词级时间戳(字幕断行/词锚点依据)",
1460
+ "本片未启用(film.json words=false 或 words.json 缺失)")
1461
+ return
1462
+ if not os.path.exists(wp):
1463
+ lg.skip("G10", "词级时间戳(字幕断行/词锚点依据)", "没有 words.json(跑 --stage tts 生成)")
1464
+ return
1465
+ try:
1466
+ wj = json.load(open(wp, encoding="utf-8"))
1467
+ except Exception as e: # noqa: BLE001
1468
+ lg.fail("G10", "词级时间戳(字幕断行/词锚点依据)", "words.json 读不了:%s" % e)
1469
+ return
1470
+ lines = wj.get("lines") or {}
1471
+ empty = [lid for lid, r in lines.items() if not r.get("n")]
1472
+ n_words = sum(int(r.get("n") or 0) for r in lines.values())
1473
+ if not lines or n_words == 0:
1474
+ lg.skip("G10", "词级时间戳(字幕断行/词锚点依据)",
1475
+ "词事件为空(edge-tts 只回了音频;本次降级为等分/整句字幕)")
1476
+ return
1477
+ bad = []
1478
+ if empty:
1479
+ bad.append("%d 句没有词事件(%s)" % (len(empty), "、".join(empty[:4])))
1480
+ mono_bad = [lid for lid, r in lines.items() if not r.get("mono", True)]
1481
+ if mono_bad:
1482
+ bad.append("词偏移非单调:%s" % "、".join(mono_bad[:4]))
1483
+ tail_bad = [(lid, float(r.get("tail") or 0.0)) for lid, r in lines.items()
1484
+ if r.get("n") and float(r.get("tail") or 0.0) > WORD_TAIL_MAX]
1485
+ if tail_bad:
1486
+ bad.append("末词终点离句尾过远(>%.2fs):%s"
1487
+ % (WORD_TAIL_MAX, "、".join("%s %.2fs" % x for x in tail_bad[:3])))
1488
+ start_bad = [(lid, float(r.get("start") or 0.0)) for lid, r in lines.items()
1489
+ if r.get("n") and float(r.get("start") or 0.0) > WORD_START_MAX]
1490
+ if start_bad:
1491
+ bad.append("首词起点离句首太远(>%.2fs):%s"
1492
+ % (WORD_START_MAX, "、".join("%s %.2fs" % x for x in start_bad[:3])))
1493
+ cover_bad = []
1494
+ for lid, r in lines.items():
1495
+ dur = float(r.get("dur") or 0.0)
1496
+ if not r.get("n") or dur <= 0:
1497
+ continue
1498
+ cov = float(r.get("covered") or 0.0) / dur
1499
+ if cov < WORD_COVER_MIN:
1500
+ cover_bad.append((lid, cov))
1501
+ if cover_bad:
1502
+ bad.append("词覆盖率过低(<%.0f%%):%s"
1503
+ % (WORD_COVER_MIN * 100,
1504
+ "、".join("%s %.0f%%" % (l, c * 100) for l, c in cover_bad[:3])))
1505
+ tail_max = max([float(r.get("tail") or 0.0) for r in lines.values()] or [0.0])
1506
+ detail = "%d 句 / %d 词 · 末词偏差最大 %.2fs" % (len(lines), n_words, tail_max)
1507
+ if bad:
1508
+ lg.fail("G10", "词级时间戳(字幕断行/词锚点依据)", detail + ";" + ";".join(bad))
1509
+ else:
1510
+ lg.ok("G10", "词级时间戳(字幕断行/词锚点依据)", detail)
1511
+
1512
+
1513
+ # ⚠ 阈值**只有一套**:权威定义在 qavmaf.py(VMAF_PASS=92 / VMAF_WARN=96,SSIM 仅诊断)。
1514
+ # 这里刻意不设第二套常量——本仓库的规矩是"同一事实只能有一个权威值"(CHANGELOG v0.4 D 节)。
1515
+ # 真实标定(qavmaf 作者实测,参考帧含字幕与片头片尾淡入淡出):
1516
+ # 模板片 crf17 VMAF 97.24(pass) / crf30 95.74(pass+warning) / 二次编码坏片 29.45(fail)
1517
+ # 想按片收紧或放宽就写 film.json 的 qa.vmaf.pass / qa.vmaf.warn,会透传给 qavmaf。
1518
+ def _qa_vmaf_gate(lg, film, tl, work, scenes_mod, script, mode=""):
1519
+ """全片 VMAF/SSIM 门禁(v0.8):参考帧由场景函数实时渲染,与成片逐帧比较。
1520
+
1521
+ 为什么值得全片跑(用户明确要求"全片 + 阻断"):锐度比只在 4 个时刻采样,
1522
+ 能发现"整体发虚",但发现不了"某 30 秒里字幕糊了 / 某段梯度出现色带"。
1523
+ VMAF 是唯一能覆盖整条时间轴的客观指标。
1524
+
1525
+ 三档语义:
1526
+ * 没有 qavmaf.py / 没有 scenes.py(web 引擎)/ 显式 mode=off -> skipped,写明原因;
1527
+ * 分数低于 pass 阈值 -> fail(阻断交付);
1528
+ * 介于 pass 与 warn 之间 -> pass + warning(能出片,但建议降 CRF)。
1529
+ """
1530
+ qv = _try_module("qavmaf")
1531
+ if mode == "off":
1532
+ lg.skip("G11", "全片 VMAF / SSIM 画质", "本次显式关闭(--vmaf off 或 qa.vmaf.mode=off)")
1533
+ return None
1534
+ if qv is None:
1535
+ lg.skip("G11", "全片 VMAF / SSIM 画质", "没有 qavmaf.py(拷一份进来才能做全片画质门禁)")
1536
+ return None
1537
+ if scenes_mod is None:
1538
+ lg.skip("G11", "全片 VMAF / SSIM 画质",
1539
+ "web 引擎/缺 scenes.py:没有可重渲的参考帧(VMAF 参考帧必须来自场景函数)")
1540
+ return None
1541
+ cfg = ((script or {}).get("qa") or {}).get("vmaf") if isinstance((script or {}).get("qa"), dict) else {}
1542
+ cfg = cfg if isinstance(cfg, dict) else {}
1543
+ m = str(mode or cfg.get("mode") or "full")
1544
+ kw = {}
1545
+ for key, ckey in (("vmaf_pass", "pass"), ("vmaf_warn", "warn"),
1546
+ ("ssim_pass", "ssim_pass"), ("ssim_warn", "ssim_warn")):
1547
+ if cfg.get(ckey) is not None:
1548
+ kw[key] = float(cfg[ckey])
1549
+ # 抽样步长:qavmaf.report 的正式参数名是 sample_step(schema 里也是这个名字)。
1550
+ # 不传的话 mode=sample 永远按 qavmaf 内部默认步长 5 抽样——用户写了 sample_step
1551
+ # 也毫无效果("配置存在但没人读"正是最容易被忽略的那类静默缺陷)。
1552
+ if cfg.get("sample_step") is not None:
1553
+ kw["sample_step"] = max(1, int(cfg["sample_step"]))
1554
+ if cfg.get("ssim") and isinstance(cfg["ssim"], dict):
1555
+ for key, ckey in (("ssim_pass", "pass"), ("ssim_warn", "warn")):
1556
+ if cfg["ssim"].get(ckey) is not None:
1557
+ kw[key] = float(cfg["ssim"][ckey])
1558
+ print(" [vmaf] 模式=%s(参考帧=场景函数实时渲染,不是成片抽帧)" % m)
1559
+ try:
1560
+ res = qv.report(film, tl, scenes_mod, script, mode=m,
1561
+ out_json=os.path.join(str(work), "qa", "vmaf.json"), **kw)
1562
+ except Exception as e: # noqa: BLE001
1563
+ lg.fail("G11", "全片 VMAF / SSIM 画质", "门禁自身失败:%s" % e)
1564
+ print(" [FAIL][vmaf]", e)
1565
+ return None
1566
+ gate = (res or {}).get("gate") or {}
1567
+ v = (res or {}).get("vmaf") or {}
1568
+ s = (res or {}).get("ssim") or {}
1569
+ bits = []
1570
+ if v.get("score") is not None:
1571
+ bits.append("VMAF %.2f" % float(v["score"]))
1572
+ if s.get("score") is not None:
1573
+ bits.append("SSIM %.4f" % float(s["score"]))
1574
+ bits.append("%s 帧" % ((res or {}).get("frames_compared") or 0))
1575
+ detail = " · ".join(bits)
1576
+ if (res or {}).get("elapsed_s") is not None:
1577
+ detail += " · 用时 %.1fs" % float(res["elapsed_s"])
1578
+ st = str(gate.get("status") or "skipped")
1579
+ for w in (res or {}).get("warnings") or []:
1580
+ print(" [WARN][vmaf] %s" % w)
1581
+ for e in (res or {}).get("errors") or []:
1582
+ print(" [FAIL][vmaf] %s" % e)
1583
+ if st == "fail":
1584
+ lg.fail("G11", "全片 VMAF / SSIM 画质", detail + ";" + str(gate.get("detail") or ""))
1585
+ elif st == "skipped":
1586
+ lg.skip("G11", "全片 VMAF / SSIM 画质", str(gate.get("detail") or "本次没跑"))
1587
+ else:
1588
+ lg.ok("G11", "全片 VMAF / SSIM 画质", detail)
1589
+ print(" [vmaf] %s %s" % (st, detail))
1590
+ return res
1591
+
1592
+
1593
+ # v0.8 实测标定(同一部模板片,29 s,faster-whisper small / CPU int8):
1594
+ # 干净成片:字符召回 0.828(专有名词 "DeepSeek 4.1 Flash" 被听成 DIXX/DeepSeek 变体,
1595
+ # 4 段全对上、缺句 0)—— 这不是流水线坏了,是 ASR 对中英混排专名的正常误差。
1596
+ # 所以默认线取 0.85 / 0.72:**低于 0.72 才说明"整句丢了/音轨跟剧本不是一套"**,
1597
+ # 0.72–0.85 之间给 warning(仍然出片,但提示可能串了缓存)。
1598
+ # 想更严就按片覆盖 film.json 的 qa.asr.recall_pass / recall_warn。
1599
+ QA_ASR_RECALL_PASS = 0.85
1600
+ QA_ASR_RECALL_WARN = 0.72
1601
+
1602
+
1603
+ def _qa_asr_gate(lg, film, work, script, tl=None, cfg=None):
1604
+ """ASR 回读门禁(v0.8):把成片音轨转回文字,和剧本逐句对账。
1605
+
1606
+ 为什么值得:容器/响度/帧级质检都默认"音轨里念的就是剧本那几句"。TTS 缓存串了、
1607
+ 换声线漏句、混音压没了、音轨是旧的——这些从波形和容器上都看不出来,只有转回
1608
+ 文字对账才能发现。代价是每片多 4–6 s(small 模型,CPU),可关。
1609
+ """
1610
+ qa = cfg if isinstance(cfg, dict) else {}
1611
+ a = qa.get("asr") if isinstance(qa.get("asr"), dict) else {}
1612
+ if a.get("enabled") is False:
1613
+ lg.skip("G12", "ASR 回读(原稿 vs 成片旁白)",
1614
+ "本次显式关闭(qa.asr.enabled=false)")
1615
+ return None
1616
+ qa_mod = _try_module("qaasr")
1617
+ if qa_mod is None:
1618
+ lg.skip("G12", "ASR 回读(原稿 vs 成片旁白)", "没有 qaasr.py(拷一份进来才能做回读)")
1619
+ return None
1620
+ kw = dict(recall_pass=QA_ASR_RECALL_PASS, recall_warn=QA_ASR_RECALL_WARN)
1621
+ if a.get("recall_pass") is not None:
1622
+ kw["recall_pass"] = float(a["recall_pass"])
1623
+ if a.get("recall_warn") is not None:
1624
+ kw["recall_warn"] = float(a["recall_warn"])
1625
+ if a.get("model"):
1626
+ kw["model_size"] = str(a["model"])
1627
+ print(" [asr] 回读成片音轨(模型 %s,CPU)" % (kw.get("model_size") or "small"))
1628
+ try:
1629
+ res = qa_mod.report(film, tl, script,
1630
+ out_json=os.path.join(str(work), "qa", "asr.json"), **kw)
1631
+ except Exception as e: # noqa: BLE001
1632
+ lg.fail("G12", "ASR 回读(原稿 vs 成片旁白)", "门禁自身失败:%s" % e)
1633
+ print(" [FAIL][asr]", e)
1634
+ return None
1635
+ gate = (res or {}).get("gate") or {}
1636
+ detail = "字符召回 %.3f(%s)" % (float((res or {}).get("recall") or 0.0),
1637
+ (res or {}).get("engine") or "-")
1638
+ if (res or {}).get("elapsed_s") is not None:
1639
+ detail += " · %.1fs" % float(res["elapsed_s"])
1640
+ for w in (res or {}).get("warnings") or []:
1641
+ print(" [WARN][asr] %s" % w)
1642
+ for e in (res or {}).get("errors") or []:
1643
+ print(" [FAIL][asr] %s" % e)
1644
+ st = str(gate.get("status") or "skipped")
1645
+ if st == "fail":
1646
+ lg.fail("G12", "ASR 回读(原稿 vs 成片旁白)", detail + ";" + str(gate.get("detail") or ""))
1647
+ elif st == "skipped":
1648
+ lg.skip("G12", "ASR 回读(原稿 vs 成片旁白)", str(gate.get("detail") or "本次没跑"))
1649
+ else:
1650
+ lg.ok("G12", "ASR 回读(原稿 vs 成片旁白)", detail)
1651
+ print(" [asr] %s %s" % (st, detail))
1652
+ return res
1653
+
1654
+
1655
+ def st_qa(film, tl, work, scenes_mod=None, script=None, vmaf_mode=""):
1004
1656
  print("== QA")
1005
1657
  th = _theme_for(script) if script is not None else None
1006
1658
  shots, refs = [], [] # refs: [(frac 下标, PIL 原图)]
@@ -1025,8 +1677,9 @@ def st_qa(film, tl, work, scenes_mod=None, script=None):
1025
1677
  try:
1026
1678
  fr = scenes_mod.draw_frame(s, sec - s["start"], s["dur"], sec, ref_script,
1027
1679
  int(round(sec * tl["fps"])))
1028
- fr = K.draw_subtitle(fr, K.sub_at(tl["scenes"], sec, ref_script.get("sub_max_hold")),
1029
- theme=th)
1680
+ _hold = ref_script.get("sub_max_hold")
1681
+ fr = K.draw_subtitle(fr, K.sub_at(tl["scenes"], sec, _hold), theme=th,
1682
+ words=K.sub_words_at(tl["scenes"], sec, _hold))
1030
1683
  refs.append((k, fr))
1031
1684
  except Exception as e: # noqa: BLE001
1032
1685
  print(" [WARN] 参考帧渲染失败:", e)
@@ -1040,9 +1693,13 @@ def st_qa(film, tl, work, scenes_mod=None, script=None):
1040
1693
  print(" 锐度参考帧: 场景函数重渲染 t=%.2fs(第 %d 张)" % (ref_sec, k_ref + 1))
1041
1694
  elif scenes_mod is None:
1042
1695
  print(" [WARN] 没有场景函数参考帧(web 引擎或 scenes.py 缺失),锐度比门禁本次跳过")
1696
+ _vq = tl.get("video") or {}
1043
1697
  rep = K.qa_report(film, expect_frames=tl["frames"], ref_img=ref_img,
1044
1698
  ref_sec=ref_sec, expected_subtitles=len(tl["scenes"]),
1045
- notes=os.path.join(work, "sub.srt"), theme=th)
1699
+ notes=os.path.join(work, "sub.srt"), theme=th,
1700
+ expect_w=int(_vq.get("out_w") or K.W),
1701
+ expect_h=int(_vq.get("out_h") or K.H),
1702
+ expect_fps=float(_vq.get("fps") or tl.get("fps") or K.FPS))
1046
1703
  pr = rep["probe"]
1047
1704
  f = pr.get("format", {})
1048
1705
  print(" 时长 %.2fs 大小 %.1f MB 码率 %.2f Mbps" % (
@@ -1090,6 +1747,10 @@ def st_qa(film, tl, work, scenes_mod=None, script=None):
1090
1747
  lg = _gate()
1091
1748
  if lg is not None:
1092
1749
  _qa_gates(lg, rep, deep, tl, work)
1750
+ # 全片 VMAF/SSIM 放在最后跑:它最贵(约 1.2× 实时),前面有 fail 时可省下这十分钟。
1751
+ _qa_vmaf_gate(lg, film, tl, work, scenes_mod, script, mode=vmaf_mode)
1752
+ # ASR 回读最便宜(模板片 6 s),放最后跑:前面已经 fail 的片没必要再花这 6 秒。
1753
+ _qa_asr_gate(lg, film, work, script, tl, cfg=((script or {}).get("qa") or {}))
1093
1754
  return errors
1094
1755
 
1095
1756
 
@@ -1151,8 +1812,10 @@ def st_stills(tl, work, scenes_mod, script, specs=None):
1151
1812
  if tuple(fr.size) != (K.W, K.H):
1152
1813
  raise RuntimeError("场景 %s 在 t=%.2fs 返回 %dx%d,期望 %dx%d(stills 与 FrameSink 一样严格)"
1153
1814
  % (sid, tg, fr.size[0], fr.size[1], K.W, K.H))
1154
- fr = K.draw_subtitle(fr, K.sub_at(tl["scenes"], tg, script.get("sub_max_hold")),
1155
- theme=_theme_for(script))
1815
+ _hold = script.get("sub_max_hold")
1816
+ fr = K.draw_subtitle(fr, K.sub_at(tl["scenes"], tg, _hold),
1817
+ theme=_theme_for(script),
1818
+ words=K.sub_words_at(tl["scenes"], tg, _hold))
1156
1819
  p = os.path.join(outdir, "%s_%05.1f.png" % (sid, float(lt)))
1157
1820
  fr.save(p)
1158
1821
  made.append(p)
@@ -1164,23 +1827,84 @@ def st_stills(tl, work, scenes_mod, script, specs=None):
1164
1827
  return made
1165
1828
 
1166
1829
 
1167
- def _finish_gates(a):
1168
- """一次运行收尾:落 gates.json + 写 out/QC-REPORT.md + 统一退出码。"""
1830
+ def _reload_ledger_from_disk(work, ledger):
1831
+ """把 work/gates.json 里已有的门禁条目搬回内存账本(accept 这类独立进程用)。
1832
+
1833
+ 只搬**内容指纹一致**的条目:指纹不同说明剧本/场景/引擎已经变过,那些结论属于
1834
+ 上一版内容,搬进来等于拿旧结论冒充本版(比丢条目更糟)。搬不回来时明确说一句,
1835
+ 让用户知道报告里的门禁矩阵为什么是空的(该重跑 --stage all)。
1836
+ """
1837
+ p = os.path.join(str(work), "gates.json")
1838
+ if not os.path.exists(p):
1839
+ return 0
1840
+ try:
1841
+ with open(p, encoding="utf-8") as fh:
1842
+ d = json.load(fh)
1843
+ except (OSError, json.JSONDecodeError) as e:
1844
+ print(" [WARN] 旧账本读不了(%s):报告里只会有本次的条目" % e)
1845
+ return 0
1846
+ if not isinstance(d, dict):
1847
+ return 0
1848
+ if str(d.get("contentHash") or "") != str(getattr(ledger, "content_hash", "") or ""):
1849
+ print(" [WARN] 旧账本的内容指纹与当前不一致(剧本/场景/引擎改过),"
1850
+ "不搬旧门禁结论:交付前请重跑 --stage qa")
1851
+ return 0
1852
+ n = 0
1853
+ for it in d.get("items") or []:
1854
+ if not isinstance(it, dict) or not it.get("id"):
1855
+ continue
1856
+ try:
1857
+ ledger.add(str(it["id"]), str(it.get("title") or ""),
1858
+ str(it.get("status") or ""), str(it.get("detail") or ""),
1859
+ at=it.get("at"))
1860
+ n += 1
1861
+ except (ValueError, TypeError) as e:
1862
+ print(" [WARN] 旧账本条目 %r 搬不回来:%s" % (it.get("id"), e))
1863
+ for b in d.get("bypassed") or []:
1864
+ if isinstance(b, dict) and b.get("what"):
1865
+ ledger.bypassed.append(dict(what=str(b["what"]), why=str(b.get("why") or ""),
1866
+ at=float(b.get("at") or time.time())))
1867
+ return n
1868
+
1869
+
1870
+ def _report_path(a):
1871
+ """QC 报告的唯一落点:**站在成片旁边**(--out 的目录),不猜 work 的兄弟目录。
1872
+
1873
+ v0.7.2 修:accept 分支以前用 dirname(abspath(work))/out/QC-REPORT.md,而 all/mux/qa
1874
+ 用 dirname(abspath(out))。--out 指到任何非 out/ 的目录(deliver/、中文工作区/成品/…)
1875
+ 时,签核更新的是另一份没人交付的文件,交付出去的那份仍是"未签核"——正好打穿
1876
+ "报告是交付凭据"这条承诺。两处必须走同一个函数。
1877
+ """
1878
+ return os.path.join(os.path.dirname(os.path.abspath(str(a.out))), "QC-REPORT.md")
1879
+
1880
+
1881
+ # 会写交付账本(work/gates.json + QC-REPORT.md)的阶段。中间产物阶段
1882
+ # (tts/layout/cues/score/sfx/audio)只做自己的事,不去覆盖上一轮完整跑出来的
1883
+ # 交付报告——否则 `--stage layout` 一次就会把「全片通过」的报告改写成「未判定」。
1884
+ _PERSIST_STAGES = ("style", "frames", "mux", "qa", "stills", "all", "accept")
1885
+
1886
+
1887
+ def _finish_gates(a, persist=True):
1888
+ """一次运行收尾:落 gates.json + 写 QC-REPORT.md(在成片旁边)+ 统一退出码。
1889
+
1890
+ persist=False:只打印本次门禁汇总与退出码,不动磁盘上的交付账本(中间阶段用)。
1891
+ """
1169
1892
  lg = _LEDGER
1170
1893
  if lg is None:
1171
1894
  return 0
1172
1895
  errs = lg.exit_errors(strict=bool(getattr(a, "strict_gates", False)))
1173
- try:
1174
- gj = lg.write_json()
1175
- except Exception as e: # noqa: BLE001
1176
- print("[WARN] gates.json 写入失败:", e)
1177
- gj = ""
1178
- try:
1179
- rep = GT.write_report(a.work, os.path.join(
1180
- os.path.dirname(os.path.abspath(a.out)), "QC-REPORT.md"))
1181
- except Exception as e: # noqa: BLE001
1182
- print("[WARN] QC 报告写入失败:", e)
1183
- rep = ""
1896
+ gj = rep = ""
1897
+ if persist:
1898
+ # 交付账本只在交付阶段写;中间阶段(layout 等)写一次就会把上一轮
1899
+ # 「pass 8 / skipped 1」的完整报告换成「只有本阶段一条」的半成品。
1900
+ try:
1901
+ gj = lg.write_json()
1902
+ except Exception as e: # noqa: BLE001
1903
+ print("[WARN] gates.json 写入失败:", e)
1904
+ try:
1905
+ rep = GT.write_report(a.work, _report_path(a))
1906
+ except Exception as e: # noqa: BLE001
1907
+ print("[WARN] QC 报告写入失败:", e)
1184
1908
  c = lg.counts()
1185
1909
  print("")
1186
1910
  print("== 门禁汇总:pass %d · fail %d · skipped %d%s"
@@ -1190,6 +1914,15 @@ def _finish_gates(a):
1190
1914
  print(" 账本:", gj)
1191
1915
  if rep:
1192
1916
  print(" 报告:", rep, " <- 交付时把这个文件一起给出")
1917
+ try:
1918
+ _run_dir, _err = GT.archive_run(a.work, lg, report_path=rep,
1919
+ artifacts=[str(a.out) if getattr(a, "out", "") else ""])
1920
+ if _run_dir:
1921
+ print(" 归档:", _run_dir, "(work/runs/%s/)" % lg.run_id)
1922
+ elif _err:
1923
+ print(" [WARN] 归档失败:", _err)
1924
+ except Exception as e: # noqa: BLE001
1925
+ print(" [WARN] 归档失败:", e)
1193
1926
  if c[GT.SKIP]:
1194
1927
  print(" 注意:有 %d 项本次**没有执行**(skipped != 通过)" % c[GT.SKIP])
1195
1928
  if errs:
@@ -1200,6 +1933,150 @@ def _finish_gates(a):
1200
1933
  return 0
1201
1934
 
1202
1935
 
1936
+ # ---------------------------------------------------------------- 批量
1937
+ BATCH_MAX_FILMS = 100
1938
+ BATCH_MAX_BYTES = 1 << 20 # 1 MiB:清单文件本身不该是个大 JSON
1939
+
1940
+
1941
+ def _load_batch(path):
1942
+ """读批量清单 -> [job]。支持两种写法(都接受):
1943
+
1944
+ ["a/film.json", "b/film.json"] # 简写:只给剧本
1945
+ {"films": [{"script": "a/film.json", "work": "a/work",
1946
+ "scenes": "a/scenes.py", "out": "out/a.mp4"}]}
1947
+
1948
+ 限制来自 MoneyPrinterTurbo 的工程经验(B 线调研):批量最容易死在"第 7 条跑一半
1949
+ 才发现清单写错",所以数量/体积先卡死,并且在**开跑之前**全部预检一遍。
1950
+ """
1951
+ p = str(path)
1952
+ if not os.path.exists(p):
1953
+ raise SystemExit("[batch] 清单不存在:%s" % p)
1954
+ if os.path.getsize(p) > BATCH_MAX_BYTES:
1955
+ raise SystemExit("[batch] 清单 %.1f KB 超过 %d KB 上限:拆成几份跑"
1956
+ % (os.path.getsize(p) / 1024.0, BATCH_MAX_BYTES // 1024))
1957
+ try:
1958
+ data = json.load(open(p, encoding="utf-8"))
1959
+ except json.JSONDecodeError as e:
1960
+ raise SystemExit("[batch] 清单不是合法 JSON:%s" % e) from e
1961
+ rows = data.get("films") if isinstance(data, dict) else data
1962
+ if not isinstance(rows, list) or not rows:
1963
+ raise SystemExit("[batch] 清单必须是数组,或 {\"films\": [...]} 且非空")
1964
+ if len(rows) > BATCH_MAX_FILMS:
1965
+ raise SystemExit("[batch] %d 条超过 %d 条上限:拆成几份跑"
1966
+ % (len(rows), BATCH_MAX_FILMS))
1967
+ base = os.path.dirname(os.path.abspath(p))
1968
+ jobs = []
1969
+ for i, row in enumerate(rows):
1970
+ if isinstance(row, str):
1971
+ row = {"script": row}
1972
+ if not isinstance(row, dict) or not row.get("script"):
1973
+ raise SystemExit("[batch] 第 %d 条缺少 script 字段:%r" % (i + 1, row))
1974
+
1975
+ def _abs(v, default=""):
1976
+ if not v:
1977
+ return default
1978
+ v = str(v)
1979
+ return v if os.path.isabs(v) else os.path.normpath(os.path.join(base, v))
1980
+
1981
+ script = _abs(row["script"])
1982
+ stem = os.path.splitext(os.path.basename(script))[0]
1983
+ jobs.append(dict(
1984
+ script=script,
1985
+ scenes=_abs(row.get("scenes"), os.path.join(os.path.dirname(script), "scenes.py")),
1986
+ work=_abs(row.get("work"), os.path.join(base, "work_" + stem)),
1987
+ out=_abs(row.get("out"), os.path.join(base, "out", stem + ".mp4")),
1988
+ label=str(row.get("label") or stem),
1989
+ ))
1990
+ return jobs
1991
+
1992
+
1993
+ def run_batch(a):
1994
+ """批量渲染:先全量预检 -> 逐条隔离执行 -> JSON 汇总 + 退出码。
1995
+
1996
+ 失败隔离是这套流程的全部价值:一条剧本写错,不该让另外 9 条都不出片。
1997
+ 但也**不静默**:预检阶段就失败的条目会在开跑前一次性报全,跑的过程中失败的
1998
+ 条目会带着退出码与日志尾进汇总。
1999
+ """
2000
+ jobs = _load_batch(a.batch)
2001
+ print("== Batch(%d 条)" % len(jobs))
2002
+ here = os.path.dirname(os.path.abspath(__file__))
2003
+ fc = os.path.join(here, "filmcheck.py")
2004
+ checks = []
2005
+ bad = 0
2006
+ for j in jobs:
2007
+ row = dict(label=j["label"], script=j["script"], ok=False, errors=[], warnings=[])
2008
+ if not os.path.exists(j["script"]):
2009
+ row["errors"].append("剧本不存在:%s" % j["script"])
2010
+ elif os.path.exists(fc):
2011
+ p = subprocess.run([sys.executable, fc, j["script"], "--json"],
2012
+ capture_output=True, text=True, encoding="utf-8",
2013
+ errors="replace")
2014
+ try:
2015
+ d = json.loads((p.stdout or "").strip() or "{}")
2016
+ except json.JSONDecodeError:
2017
+ d = {}
2018
+ row["ok"] = bool(d.get("ok", p.returncode == 0))
2019
+ row["errors"] = [e.get("msg") if isinstance(e, dict) else str(e)
2020
+ for e in (d.get("errors") or [])][:8]
2021
+ row["warnings"] = len(d.get("warnings") or [])
2022
+ else:
2023
+ row["ok"] = True # 没装校验器:不阻断,但汇总里会说
2024
+ row["warnings"] = -1
2025
+ if not row["ok"]:
2026
+ bad += 1
2027
+ checks.append(row)
2028
+ for r in checks:
2029
+ print(" %s %-12s %s" % ("OK " if r["ok"] else "FAIL", r["label"],
2030
+ ";".join(r["errors"][:3]) if r["errors"] else ""))
2031
+ if bad:
2032
+ rep_p = os.path.join(os.path.dirname(os.path.abspath(jobs[0]["work"])), "batch-report.json")
2033
+ # 预检阶段 work/ 目录通常还不存在(子进程要跑起来才会建),这里必须先建父目录:
2034
+ # 否则"清单里有一条写错"这个**本来只想报错退出**的路径,会先抛 FileNotFoundError,
2035
+ # 用户看到的是"[ERROR] 文件/目录操作失败",既丢了"一条都没跑"的说明,也没有台账。
2036
+ os.makedirs(os.path.dirname(rep_p), exist_ok=True)
2037
+ json.dump(dict(phase="preflight", films=checks), open(rep_p, "w", encoding="utf-8"),
2038
+ ensure_ascii=False, indent=1)
2039
+ raise SystemExit("[batch] 预检有 %d 条不通过,**一条都没跑**(清单/剧本先修好):%s\n"
2040
+ " 明细:%s" % (bad, "、".join(r["label"] for r in checks if not r["ok"]),
2041
+ rep_p))
2042
+ print(" 预检全部通过,开始逐条渲染(单条失败不阻断其余)")
2043
+
2044
+ results = []
2045
+ for j in jobs:
2046
+ print("\n---- [batch] %s ----" % j["label"])
2047
+ cmd = [sys.executable, os.path.join(here, "render.py"),
2048
+ "--script", j["script"], "--scenes", j["scenes"],
2049
+ "--work", j["work"], "--out", j["out"], "--stage", "all"]
2050
+ cmd += ["--engine", a.engine] if a.engine else []
2051
+ cmd += ["--cost"] if a.cost else []
2052
+ cmd += ["--strict-gates"] if a.strict_gates else []
2053
+ t0 = time.time()
2054
+ p = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8",
2055
+ errors="replace")
2056
+ wall = time.time() - t0
2057
+ tail = ((p.stdout or "") + (p.stderr or "")).strip().splitlines()[-6:]
2058
+ results.append(dict(label=j["label"], script=j["script"], out=j["out"],
2059
+ work=j["work"], exit=p.returncode, ok=(p.returncode == 0),
2060
+ wall_s=round(wall, 1), tail=tail))
2061
+ print(" %s 用时 %.1fs -> %s" % ("OK" if p.returncode == 0 else "FAIL", wall, j["out"]))
2062
+ if p.returncode != 0:
2063
+ for ln in tail:
2064
+ print(" | " + ln)
2065
+
2066
+ okn = sum(1 for r in results if r["ok"])
2067
+ rep_p = os.path.join(os.path.dirname(os.path.abspath(jobs[0]["work"])), "batch-report.json")
2068
+ os.makedirs(os.path.dirname(rep_p), exist_ok=True)
2069
+ json.dump(dict(phase="render", films=checks, results=results,
2070
+ summary=dict(total=len(results), ok=okn, failed=len(results) - okn)),
2071
+ open(rep_p, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
2072
+ print("\n== Batch 汇总:%d/%d 成功,%d 失败" % (okn, len(results), len(results) - okn))
2073
+ print(" 台账:%s" % rep_p)
2074
+ for r in results:
2075
+ if not r["ok"]:
2076
+ print(" FAIL %-12s exit=%s" % (r["label"], r["exit"]))
2077
+ return 0 if okn == len(results) else 1
2078
+
2079
+
1203
2080
  # ---------------------------------------------------------------- main
1204
2081
  def main():
1205
2082
  _setup_stdio()
@@ -1232,8 +2109,26 @@ def main():
1232
2109
  help="跳过人工签核检查(会在 QC 报告里留痕,不算通过)")
1233
2110
  ap.add_argument("--cost", action="store_true",
1234
2111
  help="每个 stage 往 work/cost.jsonl 记一行实测耗时")
2112
+ # ---- v0.8 ----
2113
+ ap.add_argument("--batch", default="",
2114
+ help="批量清单(JSON 数组或 {\"films\":[...]},≤100 条):"
2115
+ "先全量预检,再逐条渲染,单条失败不阻断其余")
2116
+ ap.add_argument("--vmaf", default="", choices=("", "full", "sample", "off"),
2117
+ help="qa 阶段的全片 VMAF/SSIM 模式(缺省读 film.json 的 qa.vmaf.mode)")
2118
+ ap.add_argument("--no-preflight", action="store_true",
2119
+ help="跳过渲染前资源预检(会在 QC 报告里留痕,不算通过)")
2120
+ ap.add_argument("--preview", default="",
2121
+ help="只渲前 N 秒做预览片(出 out/preview/*.mp4 + .gif),不写交付报告")
2122
+ ap.add_argument("--run-id", default="",
2123
+ help="本次运行的标签(写进 QC 报告,便于对照多版本)")
1235
2124
  a = ap.parse_args()
1236
2125
 
2126
+ if a.batch:
2127
+ _setup_stdio()
2128
+ return run_batch(a)
2129
+
2130
+ # work/ 本来就不存在 = 这一跑自己产出全部中间物,别把"我还没跑到"当成"产物过时"。
2131
+ work_pre_exists = os.path.isdir(a.work)
1237
2132
  try:
1238
2133
  os.makedirs(a.work, exist_ok=True)
1239
2134
  except OSError as e:
@@ -1247,8 +2142,18 @@ def main():
1247
2142
 
1248
2143
  # ---- 门禁账本(v0.6.0)----
1249
2144
  global _LEDGER
2145
+ # engine=web 时把入口页实际引用的同目录页面脚本一起纳入内容指纹:web 的画面逻辑在
2146
+ # web/*.js 里,不在 scenes.py 里——不纳入的话改动画后旧签核仍然"有效",正好违背
2147
+ # v0.6「签核绑内容指纹,改了画面代码旧签核自动失效」的承诺。
2148
+ web_entry = ""
2149
+ if engine == "web":
2150
+ try:
2151
+ web_entry = _web_entry(script) # 入口页不存在时这里会 SystemExit(本来就该早失败)
2152
+ except SystemExit:
2153
+ web_entry = "" # 页面还没建:交给后面的 stage 报错,账本先照建
1250
2154
  _LEDGER = GT.GateLedger(a.work, script, scenes_path=a.scenes,
1251
- script_path=a.script, engine=engine)
2155
+ script_path=a.script, engine=engine,
2156
+ web_entry=web_entry, run_id=a.run_id)
1252
2157
  if a.no_gate:
1253
2158
  _LEDGER.bypass("人工签核检查(--no-gate)", "本条不算通过,只记录")
1254
2159
  print("[gate] --no-gate:跳过人工签核检查(会在 QC 报告里留痕)")
@@ -1257,11 +2162,63 @@ def main():
1257
2162
  """源头输入:剧本与 scenes.py(改它们等于改了所有下游的依据)。"""
1258
2163
  return {"script": a.script, "scenes": a.scenes}
1259
2164
 
2165
+ # 本次命令行**计划要跑**的 stage 集合:--stage all 展开成 10 个,单 stage 就是它自己。
2166
+ # 用途见 stagewatch.check 的 pending:本阶段马上要用新输入重算,那种"输入变了"不是过时。
2167
+ _ALL_ORDER = ("style", "tts", "layout", "cues", "score", "sfx", "audio",
2168
+ "frames", "mux", "qa")
2169
+
2170
+ def _planned(stage_name):
2171
+ if stage_name == "all":
2172
+ return list(_ALL_ORDER)
2173
+ return [stage_name] if stage_name in STAGES else []
2174
+
1260
2175
  def _stage_begin(name):
1261
- """stage 开始时查新鲜度并计时。返回 t0。"""
1262
- if name and not a.allow_stale:
1263
- SW.report(a.work, [name], strict=a.strict_stale, allow_stale=False,
1264
- ledger=_LEDGER, sources=_sources())
2176
+ """stage 开始时查新鲜度并计时。返回 t0。
2177
+
2178
+ report() 自己负责打印 "[stale] <stage>: <原因>" 与"最小重跑"两行
2179
+ (v0.7.2 修:以前只调不接,用户只看到"最小重跑"不知道是哪个阶段、
2180
+ 为什么过时,得上 --stage explain 才知道)。
2181
+ --allow-stale 也要调用:它承诺的是"放行并留痕"(QC 报告里记一条 skipped),
2182
+ 直接跳过检查连痕都没有——那就成了静默。
2183
+ """
2184
+ if name:
2185
+ # 本阶段本轮一定真的会跑,所以必须进 pending:`--stage tts` 会顺带排轴、
2186
+ # `--stage stills` 会自动补 tts/layout,这些"顺手跑的下游"不在 _planned(stage)
2187
+ # 里;不加的话 --strict-stale 下刚写完的 tts.json 会把 layout 判成
2188
+ # "输入变了却还要用旧产物",把自动补前置这条路径整个堵死。
2189
+ pending = list(_planned(stage))
2190
+ if name not in pending:
2191
+ pending.append(name)
2192
+ errs, _warns = SW.report(a.work, [name], strict=a.strict_stale,
2193
+ allow_stale=a.allow_stale,
2194
+ ledger=_LEDGER, sources=_sources(),
2195
+ self_built=not work_pre_exists,
2196
+ pending=pending)
2197
+ if errs:
2198
+ # --strict-stale 的承诺是"上游产物过时算失败"。stagewatch.report 只把
2199
+ # 问题放进返回值(并往账本记一条 fail),它自己不抛异常——所以必须在这里
2200
+ # 真的失败。以前丢弃了返回值,于是 --stage layout --strict-stale 报完过时
2201
+ # 照跑、退出码 0,help 文本与行为对不上。
2202
+ #
2203
+ # 选择"立刻退出"而不是"跑完再在收尾处报":过时的输入会把旧产物掺进
2204
+ # 新结果(比如拿旧 cues.json 渲新时间轴的画面),跑完再报既已浪费渲染
2205
+ # 时间,产出的东西也不能用。--stage all 同理:一发现就停。
2206
+ # 不写 work/gates.json:那是**交付账本**(上一轮 --stage all 的完整
2207
+ # 结论)。中间阶段一次失败就把它覆盖成单条 fail,用户手里那份
2208
+ # QC-REPORT.md 会变成「未判定」,比留证据代价更大。失败证据在
2209
+ # stdout 与退出码里,够定位。
2210
+ # 原因行 report() 已经逐条打过了,这里只补"为什么停下 + 怎么办",
2211
+ # 不再把 errs 原样贴一遍。
2212
+ raise SystemExit(
2213
+ "[stale][strict] 上面 %d 处上游产物过时 -> 本阶段不跑,直接失败。\n"
2214
+ " (--strict-stale 下过时=失败;继续跑会把旧产物掺进新结果,"
2215
+ "白渲一遍还是错的。)\n"
2216
+ " 怎么办:\n"
2217
+ " 1) 照着每条下面的『最小重跑』先补上游,再重跑当前阶段\n"
2218
+ " 2) 确认旧产物可以接受:加 --allow-stale 显式放行"
2219
+ "(退出码 0,QC 报告里记 skipped)\n"
2220
+ " 3) 只想看现状不跑:python render.py --stage explain"
2221
+ % len(errs))
1265
2222
  return time.time()
1266
2223
 
1267
2224
  def _stage_end(name, t0, **extra):
@@ -1341,6 +2298,56 @@ def main():
1341
2298
 
1342
2299
  stage = a.stage
1343
2300
 
2301
+ # ---- preview:前 N 秒试片(v0.8)----
2302
+ if a.preview:
2303
+ try:
2304
+ secs = float(a.preview)
2305
+ except ValueError:
2306
+ raise SystemExit("[preview] 需要秒数,例如 --preview 15")
2307
+ if secs <= 0:
2308
+ raise SystemExit("[preview] 秒数必须 > 0")
2309
+ tl = ensure_tl()
2310
+ mod = load_scenes()
2311
+ pdir = os.path.dirname(os.path.abspath(a.out))
2312
+ os.makedirs(pdir, exist_ok=True)
2313
+ stem = os.path.splitext(os.path.basename(a.out))[0]
2314
+ out_mp4 = os.path.join(pdir, "preview", stem + "_preview.mp4")
2315
+ os.makedirs(os.path.dirname(out_mp4), exist_ok=True)
2316
+ n = min(int(round(secs * float(tl["fps"]))), int(tl["frames"]))
2317
+ print("== Preview(前 %.1fs / %d 帧)" % (n / float(tl["fps"]), n))
2318
+ sc2 = dict(script)
2319
+ sc2["_total"] = tl["total"]
2320
+ sc2.setdefault("_style", resolve_style(script))
2321
+ _render_range(tl, mod, sc2, 0, n, out_mp4, int(script.get("crf", 18)),
2322
+ str(script.get("preset", "medium")), progress=False)
2323
+ # 有 audio.wav 就带上声音(没有也能看画面;不阻断)。
2324
+ # 注意:**必须先把音轨截到预览时长**——K.mux 会校验音视频时长差 < 0.05s,
2325
+ # 直接拿全长 audio.wav 去配 8 秒画面必然被判"音视频时长不一致"(v0.8 开发期实测)。
2326
+ audio = os.path.join(a.work, "audio.wav")
2327
+ if os.path.exists(audio):
2328
+ tmp = out_mp4 + ".mux.mp4"
2329
+ try:
2330
+ pcm, _sr = K.wav_read(audio)
2331
+ need = int(round(n / float(tl["fps"]) * float(_sr)))
2332
+ if need > 0:
2333
+ pcm = pcm[:need]
2334
+ p_audio = os.path.join(a.work, "preview_audio.wav")
2335
+ K.wav_write(p_audio, pcm)
2336
+ audio = p_audio
2337
+ K.mux(out_mp4, audio, tmp, loudnorm=False)
2338
+ os.replace(tmp, out_mp4)
2339
+ except Exception as e: # noqa: BLE001
2340
+ print(" [WARN] 预览片混音失败(保留无声版):%s" % e)
2341
+ gif = os.path.splitext(out_mp4)[0] + ".gif"
2342
+ try:
2343
+ _to_gif(out_mp4, gif, fps=min(10, int(tl["fps"])), width=480)
2344
+ except Exception as e: # noqa: BLE001
2345
+ print(" [WARN] GIF 生成失败(mp4 仍然可用):%s" % e)
2346
+ print(" 预览片:", out_mp4)
2347
+ if os.path.exists(gif):
2348
+ print(" GIF :", gif)
2349
+ return 0
2350
+
1344
2351
  # ---- explain:只报"哪些阶段过时了",不跑任何 stage ----
1345
2352
  if stage == "explain":
1346
2353
  rows = SW.explain(a.work, sources=_sources())
@@ -1391,24 +2398,42 @@ def main():
1391
2398
  % (a.gate, rec["verdict"], _LEDGER.content_hash, rec["atText"]))
1392
2399
  if a.verdict == "rejected":
1393
2400
  print("[accept] 已记「否决」(不算签核通过);改了内容后需重新签。")
1394
- p_rep = GT.write_report(a.work, os.path.join(
1395
- os.path.dirname(os.path.abspath(a.work)), "out", "QC-REPORT.md"))
2401
+ # accept 是**独立进程**:本次账本是空的。直接 write_json 会把上一次 all/mux/qa
2402
+ # 记的 8 条门禁结论整个覆盖掉(报告变成 "pass 0 · skipped 1",交付凭据被打穿)。
2403
+ # 先把磁盘上的旧账本搬回来(内容指纹一致才搬),再追加签核状态。
2404
+ _reload_ledger_from_disk(a.work, _LEDGER)
2405
+ # 签核状态进账本:否则报告里的"人工签核"一行仍是上一次 all/mux 收尾时记的
2406
+ # skipped,用户签完再打开报告却看不到"已签"——签核就不算兑现。
2407
+ try:
2408
+ _check_signoff(stage)
2409
+ except Exception as e: # noqa: BLE001
2410
+ print(" [WARN] 签核状态没记进账本:", e)
2411
+ try:
2412
+ _LEDGER.write_json()
2413
+ except Exception as e: # noqa: BLE001
2414
+ print(" [WARN] gates.json 写入失败:", e)
2415
+ p_rep = GT.write_report(a.work, _report_path(a))
1396
2416
  print("[accept] QC 报告已更新:", p_rep)
1397
2417
  return 0
1398
2418
 
1399
2419
  if stage in ("all", "style"):
1400
- _nm = "style" if stage == "style" else None
1401
- _t0 = _stage_begin(_nm)
2420
+ # --stage all 也要把 style 这一行记进 manifest:以前 _nm 在 all 下是 None,
2421
+ # 而 _stage_begin/_stage_end 对 None 是空操作 -> work/style.json 写出来了、
2422
+ # manifest.json 却从来没有 style 记录。于是之后任何一次 `--stage style` 都会
2423
+ # 命中「产物在但没有记录」的判据,报成 no-manifest(--stage all 的用户 100% 踩到)。
2424
+ _t0 = _stage_begin("style")
1402
2425
  resolve_style(script, a.work)
1403
- _stage_end(_nm, _t0, n_tts=None)
2426
+ _stage_end("style", _t0, n_tts=None)
1404
2427
  if stage == "style":
1405
2428
  print("== Style")
1406
2429
  _print_style(script["_style"])
1407
2430
  _need(os.path.exists(os.path.join(a.work, "style.json")), "style.json 没写出来")
1408
2431
  _LEDGER.ok("style", "风格包解析", str(script["_style"].get("style")))
1409
2432
  _LEDGER.write_json()
1410
- _finish_gates(a)
1411
- return 0
2433
+ # 不能无条件 return 0:--strict-gates 下 skipped 会让 _finish_gates 返回 1,
2434
+ # 账本里也可能已经有 fail —— 门禁结论必须落到退出码,否则 CI 把失败当成功。
2435
+ rc = _finish_gates(a)
2436
+ return 1 if (rc or _LEDGER.fails()) else 0
1412
2437
 
1413
2438
  if stage in ("all", "tts"):
1414
2439
  _t0 = _stage_begin("tts")
@@ -1454,14 +2479,22 @@ def main():
1454
2479
  # 而文档三步上手就把它排在第 4 步(照抄必失败)。这里自动补前置:
1455
2480
  # 缺 tts.json 就真合成一次旁白(要联网),缺 timeline 就排一次轴——
1456
2481
  # 但每一步都**明说**自己在补什么,不偷偷跑。
2482
+ # 自动补的这几步也要 _stage_begin/_stage_end:否则 manifest 里只有 stills 一条记录,
2483
+ # 下次 --stage tts 会看到 tts.json 在、账本里没有 tts 记录 -> 误报「接手旧 work」。
1457
2484
  if not os.path.exists(tts_p):
1458
2485
  print("[stills] 没有 tts.json,自动先跑 --stage tts(需要联网合成旁白)")
2486
+ _t0 = _stage_begin("tts")
1459
2487
  lines = st_tts(script, a.work, force=a.force_tts)
2488
+ _stage_end("tts", _t0, n_tts=len(lines) if isinstance(lines, list) else None)
2489
+ _t0 = _stage_begin("layout")
1460
2490
  tl_tmp = st_layout(script, a.work, lines)
2491
+ _stage_end("layout", _t0)
1461
2492
  tl = tl_tmp
1462
2493
  elif not os.path.exists(tl_p):
1463
2494
  print("[stills] 没有 timeline.json,自动先跑 --stage layout")
2495
+ _t0 = _stage_begin("layout")
1464
2496
  tl = st_layout(script, a.work)
2497
+ _stage_end("layout", _t0)
1465
2498
  else:
1466
2499
  tl = ensure_tl()
1467
2500
  mod = load_scenes()
@@ -1471,8 +2504,10 @@ def main():
1471
2504
  _stage_end("stills", _t0)
1472
2505
  _LEDGER.add("stills", "母版静帧已产出", GT.OK if made else GT.FAIL,
1473
2506
  "%d 张(要人看过才算过:--stage accept --gate stills)" % len(made or []))
1474
- _finish_gates(a)
1475
- return 0
2507
+ # 0 张静帧 = fail 门禁:以前这里无条件 return 0,`--stills 写错 id` 会
2508
+ # "全部跳过 + 退出码 0",CI 看不出根本没出图。
2509
+ rc = _finish_gates(a)
2510
+ return 1 if (rc or _LEDGER.fails()) else 0
1476
2511
 
1477
2512
  if stage == "qa":
1478
2513
  # qa 不重渲、也不重新合成:缺成片就直接报错;缺 scenes.py 只丢参考帧、不阻断质检。
@@ -1480,7 +2515,7 @@ def main():
1480
2515
  _need(os.path.exists(a.out), "没有成片 %s,先跑 --stage mux" % a.out)
1481
2516
  mod = load_scenes(strict=False) if engine == "pil" else None
1482
2517
  _t0 = _stage_begin("qa")
1483
- errs = st_qa(a.out, tl, a.work, scenes_mod=mod, script=script)
2518
+ errs = st_qa(a.out, tl, a.work, scenes_mod=mod, script=script, vmaf_mode=a.vmaf)
1484
2519
  _stage_end("qa", _t0)
1485
2520
  _check_signoff("qa")
1486
2521
  rc = _finish_gates(a)
@@ -1496,6 +2531,10 @@ def main():
1496
2531
  # audio.wav 已经在前面阶段生成——否则 --stage frames 在空 work 目录会白渲全片再挂掉。
1497
2532
  if stage == "all":
1498
2533
  _need(os.path.exists(audio), "混音阶段异常:audio.wav 未生成")
2534
+ if not _run_preflight(script, a.work, engine, tl=tl,
2535
+ skip=bool(a.no_preflight)):
2536
+ print("\n[渲染前预检未过] 按上面逐条修;确认要硬跑加 --no-preflight(会留痕)")
2537
+ return 1
1499
2538
  if engine == "pil":
1500
2539
  mod = load_scenes()
1501
2540
  _t0 = _stage_begin("frames")
@@ -1504,8 +2543,9 @@ def main():
1504
2543
  _stage_end("frames", _t0, frames=int(tl["frames"]))
1505
2544
  if stage == "frames":
1506
2545
  _LEDGER.ok("frames", "逐帧渲染", "%d 帧(%s)" % (int(tl["frames"]), engine))
1507
- _finish_gates(a)
1508
- return 0 if not _LEDGER.fails() else 1
2546
+ # 同上:strict-gates 下 skipped 也要反映到退出码(以前这里只看 fails())。
2547
+ rc = _finish_gates(a)
2548
+ return 1 if (rc or _LEDGER.fails()) else 0
1509
2549
  if stage in ("all", "mux"):
1510
2550
  # mux 只需要 silent.mp4 + audio.wav:不加载 scenes.py(缺场景模块也能合成)
1511
2551
  _need(os.path.exists(silent), "没有 silent.mp4,先跑 --stage frames")
@@ -1516,24 +2556,40 @@ def main():
1516
2556
  _check_signoff("mux")
1517
2557
  if stage == "mux":
1518
2558
  _LEDGER.ok("mux", "合成(视频流 copy + loudnorm)", a.out)
1519
- _finish_gates(a)
1520
- return 0 if not _LEDGER.fails() else 1
2559
+ # 同上:strict-gates 下 skipped 也要反映到退出码(以前这里只看 fails())。
2560
+ rc = _finish_gates(a)
2561
+ return 1 if (rc or _LEDGER.fails()) else 0
1521
2562
  if stage == "all":
1522
2563
  _t0 = _stage_begin("qa")
1523
- errs = st_qa(film, tl, a.work, scenes_mod=mod, script=script)
2564
+ errs = st_qa(film, tl, a.work, scenes_mod=mod, script=script,
2565
+ vmaf_mode=a.vmaf)
1524
2566
  _stage_end("qa", _t0)
1525
2567
  rc = _finish_gates(a)
1526
2568
  if errs or rc:
1527
2569
  print("\n[质检未过] 成片已生成但没有通过门禁,按上面 [FAIL] 逐条修。")
1528
2570
  return 1
1529
2571
  return 0
1530
- rc = _finish_gates(a) if stage == "all" else 0
1531
- return rc
2572
+ # 所有 stage 统一收尾:落 gates.json + QC-REPORT.md,并按门禁结果给退出码。
2573
+ # v0.7.2 修:以前只有 style/frames/mux/qa 这几条分支自己调 _finish_gates,其余
2574
+ # (tts/layout/cues/score/sfx/audio/stills)落在这行 return 0——于是 ledger 里
2575
+ # 记的 fail 传不到退出码,"门禁失败 -> 非 0"这个承诺按 stage 不同行为不一样。
2576
+ # 默认路径不受影响:没有 fail(且没开 --strict-gates)时 _finish_gates 返回 0。
2577
+ rc = _finish_gates(a, persist=(stage in _PERSIST_STAGES))
2578
+ return 1 if (rc or _LEDGER.fails()) else 0
1532
2579
 
1533
2580
 
1534
2581
  if __name__ == "__main__":
1535
2582
  try:
1536
2583
  sys.exit(main())
2584
+ except KeyboardInterrupt:
2585
+ # Ctrl-C:给「能不能续跑」的明确答复,而不是甩 traceback 或静默退出 130。
2586
+ # 分块渲染先写 _part_ 再改名,所以中断不会留下被 --resume 误认的半截分块;
2587
+ # 已完成的段下次加 --resume 直接复用,残留的 _part_ 会被自动清掉。
2588
+ _setup_stdio()
2589
+ print("\n[中断] 收到 Ctrl-C,本次运行已停止。", file=sys.stderr)
2590
+ print(" 已完成的产物都留在 work/ 里:分块渲染请加 --resume 续跑"
2591
+ "(半成品段不会被当成完成段复用)。", file=sys.stderr)
2592
+ sys.exit(130)
1537
2593
  except RuntimeError as e:
1538
2594
  # 领域错误(音视频时长不符 / 分块缺口 / 编码失败 / TTS 重试耗尽 …)给一句话,
1539
2595
  # 不要甩 Python traceback;要完整栈就 set RENDER_DEBUG=1。