dsh-qqbot-muu 0.1.20 → 0.1.21

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 (92) hide show
  1. package/CHANGELOG.md +168 -154
  2. package/client/qqbot-settings.js +13401 -13380
  3. package/dist/config.js +573 -581
  4. package/dist/features/contextless-store.js +247 -247
  5. package/dist/features/four-source.js +338 -336
  6. package/dist/features/group-join-request.js +289 -287
  7. package/dist/features/local-models.js +1494 -1467
  8. package/dist/features/style-layer.js +501 -498
  9. package/dist/features/thinking-log.js +71 -69
  10. package/dist/gateway/bootstrap.js +1704 -1652
  11. package/dist/model/settings-reader.js +193 -102
  12. package/dist/shared/paths.js +128 -0
  13. package/dist/shared/settings-io.js +79 -83
  14. package/dshqqbot/.qqbot-extensions/inbound/00-vision.mjs +111 -0
  15. package/dshqqbot/.qqbot-extensions/inbound/aa-memory-recall.mjs +802 -794
  16. package/dshqqbot/.qqbot-extensions/inbound/az-feedback.mjs +113 -115
  17. package/dshqqbot/.qqbot-extensions/inbound/local-answer.mjs +689 -568
  18. package/dshqqbot/.qqbot-extensions/lib/local-llm.mjs +455 -444
  19. package/dshqqbot/.qqbot-extensions/lib/memory-agent.mjs +930 -928
  20. package/dshqqbot/.qqbot-extensions/lib/memory-core.mjs +537 -537
  21. package/dshqqbot/.qqbot-extensions/lib/memory-db.mjs +2476 -2245
  22. package/dshqqbot/.qqbot-extensions/lib/memory-hippo.mjs +18 -0
  23. package/dshqqbot/.qqbot-extensions/lib/memory.mjs +191 -186
  24. package/dshqqbot/.qqbot-extensions/lib/scope-util.mjs +84 -0
  25. package/dshqqbot/.qqbot-extensions/outbound/aa-sanitize.mjs +158 -154
  26. package/dshqqbot/.qqbot-extensions/outbound/memory-agent.mjs +121 -130
  27. package/dshqqbot/.qqbot-extensions/outbound/turn-memory.mjs +92 -101
  28. package/dshqqbot/.qqbot-extensions/tools/memory.mjs +178 -120
  29. package/dshqqbot/.qqbot-extensions/vendor/abogus/test-abogus.mjs +128 -126
  30. package/package.json +119 -118
  31. package/scripts/__pycache__/fan-mode.cpython-311.pyc +0 -0
  32. package/scripts/__pycache__/memory-audit.cpython-311.pyc +0 -0
  33. package/scripts/__pycache__/qq-ip-sync.cpython-311.pyc +0 -0
  34. package/scripts/__pycache__/qq-whitelist.cpython-311.pyc +0 -0
  35. package/scripts/ai-toolkit.py +607 -478
  36. package/scripts/chat-archive/__pycache__/build-sft-v4.cpython-311.pyc +0 -0
  37. package/scripts/chat-archive/__pycache__/build-sft.cpython-311.pyc +0 -0
  38. package/scripts/chat-archive/build-sft-v4.py +566 -0
  39. package/scripts/chat-archive/build-sft.py +390 -0
  40. package/scripts/chat-archive/eval-sft.py +155 -0
  41. package/scripts/chat-archive/extract-memory.py +143 -0
  42. package/scripts/chat-archive/inventory.py +182 -0
  43. package/scripts/chat-archive/merge-sft.py +114 -0
  44. package/scripts/chat-archive/qce-pull.py +217 -0
  45. package/scripts/chat-archive/qqheader.py +110 -0
  46. package/scripts/chat-archive/qqkey2.py +113 -0
  47. package/scripts/chat-archive/qqprobe.py +153 -0
  48. package/scripts/chat-archive/screen-collect.py +163 -0
  49. package/scripts/chat-archive/sqlcipher_probe.py +444 -0
  50. package/scripts/episode.py +529 -0
  51. package/scripts/fan-curve.py +218 -0
  52. package/scripts/fan-guard.cmd +8 -0
  53. package/scripts/fan-mode.py +380 -263
  54. package/scripts/gen-image.py +420 -413
  55. package/scripts/gen-video.py +186 -178
  56. package/scripts/hw-profile.py +175 -0
  57. package/scripts/media-enhance.py +402 -0
  58. package/scripts/memory-audit.py +581 -0
  59. package/scripts/migrate-scope.mjs +140 -139
  60. package/scripts/qq-connect-login.py +133 -0
  61. package/scripts/qq-ip-sync-hidden.vbs +5 -0
  62. package/scripts/qq-ip-sync.py +300 -0
  63. package/scripts/qq-whitelist.py +71 -0
  64. package/scripts/release-all.mjs +636 -509
  65. package/scripts/release-check.mjs +244 -226
  66. package/scripts/secure-room/index.html +334 -0
  67. package/scripts/secure-room/server.py +582 -0
  68. package/scripts/stickers/auto-tag.mjs +161 -0
  69. package/scripts/train/__pycache__/train-lora.cpython-311.pyc +0 -0
  70. package/scripts/train/gguf-quantize.py +92 -0
  71. package/scripts/train/gguf-to-hf.py +112 -0
  72. package/scripts/train/merge-lora.py +51 -0
  73. package/scripts/train/probe-mirrors.sh +12 -0
  74. package/scripts/train/probe-mirrors2.sh +20 -0
  75. package/scripts/train/setup-wsl.sh +23 -0
  76. package/scripts/train/setup-wsl2.sh +25 -0
  77. package/scripts/train/setup-wsl3.sh +22 -0
  78. package/scripts/train/setup-wsl4.sh +22 -0
  79. package/scripts/train/train-lora.py +319 -0
  80. package/dist/_backup_ctx_20261125_183653/dist/config.d.ts +0 -473
  81. package/dist/_backup_ctx_20261125_183653/dist/config.js +0 -450
  82. package/dist/_backup_ctx_20261125_183653/dist/features/contextless-trim.js +0 -304
  83. package/dist/_backup_ctx_20261125_183653/dist/session/session-manager.js +0 -1588
  84. package/dist/_backup_ctx_20261125_183653/dist/transport/inbound.js +0 -1567
  85. package/dist/_backup_ctx_20261125_183653/dist/transport/outbound.js +0 -647
  86. package/scripts/__pycache__/ai-mode.cpython-311.pyc +0 -0
  87. package/scripts/__pycache__/ai-toolkit.cpython-311.pyc +0 -0
  88. package/scripts/__pycache__/comfy_gen.cpython-311.pyc +0 -0
  89. package/scripts/__pycache__/gen-image.cpython-311.pyc +0 -0
  90. package/scripts/__pycache__/gen-video.cpython-311.pyc +0 -0
  91. package/scripts/__pycache__/model-registry.cpython-311.pyc +0 -0
  92. package/scripts/__pycache__/purge-standby.cpython-311.pyc +0 -0
@@ -0,0 +1,529 @@
1
+ # -*- coding: utf-8 -*-
2
+ """episode.py —— 一条「短片」的确定性流水线(分镜 → 出图 → 修复 → 配音 → 拼片)。
3
+
4
+ 为什么要脚本化:
5
+ 以前做短片是「想到哪调哪」:提示词随手改、种子随机、TTS 参数忘了、拼片全靠手工。
6
+ 这里把整条链路写死成**一份分镜表 + 五个固定步骤**,任何机器跑到同一份分镜,
7
+ 产物逐帧一致(图片/配音的随机性都被显式种子钉住)。调用方只需要拿到最后那行 JSON。
8
+
9
+ 步骤(可以只跑其中几步,产物有缓存,重复跑不会重做):
10
+ images 每镜出 1 张底图(ComfyUI / FLUX.1-schnell,固定 seed)
11
+ enhance 每张图过 media-enhance(去噪 + 局部对比 + 锐化 + 2x)
12
+ tts 每句旁白过 LocalAI /tts(VoxCPM2,默认音色)
13
+ clips 每镜做「缓慢推拉」动态片段(ffmpeg zoompan),并把配音压进该镜时长
14
+ final 拼接 + 烧字幕 + 响度归一 + 首尾淡入淡出
15
+
16
+ 用法:
17
+ python scripts/episode.py --story builtin --only all
18
+ python scripts/episode.py --story f:\\qqbot\\config\\episodes\\xx.json --only images,enhance
19
+ python scripts/episode.py --story builtin --only final --force final
20
+ python scripts/episode.py --story builtin --with-video # 其中一镜改用 Wan2.2 生成的真实视频
21
+ python scripts/episode.py --story builtin --list # 只打印分镜表
22
+
23
+ 产物: out/episodes/<slug>/{frames,voices,clips}/* + final.mp4 + report.json
24
+ """
25
+ import argparse
26
+ import json
27
+ import os
28
+ import re
29
+ import subprocess
30
+ import sys
31
+ import time
32
+ import urllib.request
33
+
34
+ CREATE_NO_WINDOW = 0x08000000
35
+
36
+
37
+ def _resolve_root():
38
+ here = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
39
+ cands = []
40
+ for k in ("QQBOT_ROOT", "QQBOT_REPO_ROOT"):
41
+ v = (os.environ.get(k) or "").strip()
42
+ if v:
43
+ cands.append(os.path.abspath(v))
44
+ d = here
45
+ for _ in range(8):
46
+ cands.append(d)
47
+ nd = os.path.dirname(d)
48
+ if nd == d:
49
+ break
50
+ d = nd
51
+ for c in cands:
52
+ try:
53
+ if os.path.isdir(os.path.join(c, ".models")):
54
+ return c
55
+ except Exception:
56
+ continue
57
+ return here
58
+
59
+
60
+ ROOT = _resolve_root()
61
+ SCRIPTS = os.path.join(ROOT, "scripts")
62
+ PY = sys.executable
63
+ FFMPEG = os.environ.get("FFMPEG") or os.path.join(ROOT, "bin", "ffmpeg", "ffmpeg.exe")
64
+ FFPROBE = FFMPEG.replace("ffmpeg.exe", "ffprobe.exe")
65
+ LOCALAI = os.environ.get("LOCALAI_URL", "http://127.0.0.1:8188")
66
+
67
+ # ── 内置分镜(主题:换新家 + 主机升级;6 镜 × 5 秒 ≈ 30 秒) ────────────────
68
+ # 种子固定 → 同一台机器重复跑得到同一组画面;换主题请复制成 config/episodes/*.json。
69
+ BUILTIN = {
70
+ "slug": "host-upgrade-30s",
71
+ "title": "换新家 · 主机升级",
72
+ "width": 1280,
73
+ "height": 720,
74
+ "fps": 30,
75
+ "voice": "zh_female",
76
+ "voice_ref_text": "今天风不大,我把桌子挪到了窗边,先把显示器接好。",
77
+ "speed": 1.0,
78
+ # 2026-12-02 主人反馈「画里文字错乱」:扩散模型一看到 box / packaging / label / screen
79
+ # 就会硬造字,所以提示词里只描述材质与光,负向统一压掉文字类概念。
80
+ "model": "krea",
81
+ "steps": 28,
82
+ "guidance": 4.5,
83
+ "negative": ("text, letters, words, typing, caption, subtitle, watermark, logo, signature, "
84
+ "label, packaging print, brand name, lowres, blurry, jpeg artifacts, "
85
+ "deformed hands, extra fingers, oversaturated"),
86
+ "shots": [
87
+ {"id": "01", "seed": 2026120201, "dur": 5.0, "motion": "in",
88
+ "image": "a cramped old bedroom at night, a dusty beige PC tower on a worn wooden desk, "
89
+ "single warm desk lamp, tangled cables, cinematic still, 50mm, shallow depth of field",
90
+ "line": "上个月搬了家,也把用了六年的老主机拆了。"},
91
+ {"id": "02", "seed": 2026120202, "dur": 5.0, "motion": "left",
92
+ "image": "close up of two hands lifting a graphics card out of an open cardboard box, "
93
+ "backlit by soft window light, blurred empty apartment behind, cinematic still, shallow depth of field",
94
+ "line": "新显卡到手,我在地上拆了半小时。"},
95
+ {"id": "03", "seed": 2026120203, "dur": 5.0, "motion": "in",
96
+ "image": "a bright apartment corner, wooden desk by the window, green plants, morning sunlight "
97
+ "falling across a keyboard, minimal cozy workspace, cinematic still",
98
+ "line": "新桌子靠窗,晨光正好落在键盘上。"},
99
+ {"id": "04", "seed": 2026120204, "dur": 5.0, "motion": "right",
100
+ "image": "macro close up inside a black PC case, blue and warm white light strips glowing, "
101
+ "graphics card fans, dust free, dark room, cinematic still, macro photography",
102
+ "line": "开机那一刻,机箱里的灯一圈圈亮起来。"},
103
+ {"id": "05", "seed": 2026120205, "dur": 5.0, "motion": "out",
104
+ "image": "over the shoulder view of a dim room at night, a monitor glowing softly out of focus, "
105
+ "warm desk lamp, a mug of tea, a cat sleeping on the chair, cinematic still",
106
+ "line": "夜里跑模型,它不再像旧机器那样喘。"},
107
+ {"id": "06", "seed": 2026120206, "dur": 5.0, "motion": "in",
108
+ "image": "a cozy new room seen from behind a desk, big window with city lights at night, "
109
+ "warm ambient light, film look, cinematic still",
110
+ "line": "还在调,但屋子亮着,我就想再改一版。"},
111
+ ],
112
+ }
113
+
114
+
115
+ def log(msg):
116
+ print("[episode] %s" % msg, flush=True)
117
+
118
+
119
+ def run(args, timeout=1800, cwd=None):
120
+ t0 = time.time()
121
+ p = subprocess.run(args, capture_output=True, text=True, timeout=timeout,
122
+ creationflags=CREATE_NO_WINDOW, cwd=cwd)
123
+ return {"argv": [str(x) for x in args], "rc": p.returncode,
124
+ "seconds": round(time.time() - t0, 1),
125
+ "stdout_tail": (p.stdout or "").strip().splitlines()[-3:],
126
+ "stderr_tail": (p.stderr or "").strip().splitlines()[-3:]}
127
+
128
+
129
+ def run_json(args, timeout=1800, cwd=None):
130
+ r = run(args, timeout, cwd)
131
+ line = ""
132
+ for s in reversed(r["stdout_tail"]):
133
+ if s.strip().startswith("{"):
134
+ line = s.strip()
135
+ break
136
+ try:
137
+ r["json"] = json.loads(line) if line else None
138
+ except json.JSONDecodeError:
139
+ r["json"] = None
140
+ return r
141
+
142
+
143
+ def probe_dur(path):
144
+ try:
145
+ p = subprocess.run([FFPROBE, "-v", "error", "-show_entries", "format=duration",
146
+ "-of", "csv=p=0", path], capture_output=True, text=True,
147
+ timeout=60, creationflags=CREATE_NO_WINDOW)
148
+ return float((p.stdout or "0").strip() or 0)
149
+ except Exception:
150
+ return 0.0
151
+
152
+
153
+ def http_post(path, body, timeout=900, raw=False):
154
+ req = urllib.request.Request(LOCALAI + path, data=json.dumps(body).encode("utf-8"),
155
+ headers={"Content-Type": "application/json"}, method="POST")
156
+ with urllib.request.urlopen(req, timeout=timeout) as r:
157
+ data = r.read()
158
+ return data if raw else json.loads(data.decode("utf-8", "replace"))
159
+
160
+
161
+ def load_story(spec):
162
+ if spec in ("", "builtin"):
163
+ return json.loads(json.dumps(BUILTIN))
164
+ with open(spec, "r", encoding="utf-8") as f:
165
+ return json.load(f)
166
+
167
+
168
+ # ── 步骤 ────────────────────────────────────────────────────────────────────
169
+ def step_images(story, work, force=False, timeout=1800):
170
+ out = []
171
+ fdir = os.path.join(work, "frames")
172
+ os.makedirs(fdir, exist_ok=True)
173
+ model = story.get("model") or "krea"
174
+ for s in story["shots"]:
175
+ dst = os.path.join(fdir, "shot-%s.png" % s["id"])
176
+ if os.path.exists(dst) and not force:
177
+ out.append({"id": s["id"], "path": dst, "cached": True})
178
+ log("image %s 已存在,跳过" % s["id"])
179
+ continue
180
+ args = [PY, "-u", os.path.join(SCRIPTS, "gen-image.py"),
181
+ "-p", s["image"], "--model", model, "--w", "1216", "--h", "832",
182
+ "--seed", str(s["seed"]), "-o", dst, "--no-cool", "--json"]
183
+ if story.get("negative"):
184
+ args += ["-n", story["negative"]]
185
+ if story.get("steps"):
186
+ args += ["--steps", str(story["steps"])]
187
+ if story.get("guidance"):
188
+ args += ["--guidance", str(story["guidance"])]
189
+ r = run_json(args, timeout)
190
+ ok = bool(r.get("json") and r["json"].get("ok"))
191
+ out.append({"id": s["id"], "path": dst, "cached": False, "call": r, "ok": ok})
192
+ log("image %s -> %s (%ss)%s" % (s["id"], "ok" if ok else "FAIL", r["seconds"],
193
+ "" if ok else " " + str(r.get("stderr_tail"))))
194
+ if not ok:
195
+ raise RuntimeError("出图失败 shot=%s" % s["id"])
196
+ return out
197
+
198
+
199
+ def step_enhance(story, work, force=False):
200
+ out = []
201
+ edir = os.path.join(work, "frames")
202
+ for s in story["shots"]:
203
+ src = os.path.join(edir, "shot-%s.png" % s["id"])
204
+ dst = os.path.join(edir, "shot-%s.enhanced.png" % s["id"])
205
+ if os.path.exists(dst) and not force:
206
+ entry = {"id": s["id"], "path": dst, "cached": True}
207
+ try:
208
+ with open(os.path.splitext(dst)[0] + "-report.json", "r", encoding="utf-8") as f:
209
+ prev = json.load(f)
210
+ entry.update({"gain": prev.get("gain"), "before": prev.get("before"),
211
+ "after": prev.get("after")})
212
+ except Exception:
213
+ pass
214
+ out.append(entry)
215
+ log("enhance %s 已存在,跳过" % s["id"])
216
+ continue
217
+ r = run_json([PY, "-u", os.path.join(SCRIPTS, "media-enhance.py"), "image",
218
+ "-i", src, "-o", dst, "--preset", "photo", "--scale", "2", "--json"], 600)
219
+ j = r.get("json") or {}
220
+ out.append({"id": s["id"], "path": dst, "ok": bool(j.get("ok")), "call": r,
221
+ "gain": j.get("gain"), "before": j.get("before"), "after": j.get("after")})
222
+ log("enhance %s -> %s %s" % (s["id"], "ok" if j.get("ok") else "FAIL", j.get("gain")))
223
+ if not j.get("ok"):
224
+ raise RuntimeError("增强失败 shot=%s" % s["id"])
225
+ return out
226
+
227
+
228
+ def ensure_voice_ref(story, work):
229
+ """固定一条参考音,用 clone 模式配音。
230
+
231
+ 为什么必须这样:VoxCPM2 没有 speaker id,/tts 是「按文字描述现场生成音色」,
232
+ 每调一次音色都会漂(主人听出来的「前后不一致」)。clone 模式把参考音的音色锁住。
233
+ """
234
+ vdir = os.path.join(work, "voices")
235
+ os.makedirs(vdir, exist_ok=True)
236
+ voice = story.get("voice") or "zh_female"
237
+ ref = os.path.join(vdir, "_ref-%s.wav" % re.sub(r"[^A-Za-z0-9_-]", "", voice))
238
+ text = story.get("voice_ref_text") or "今天风不大,我把桌子挪到了窗边。"
239
+ if os.path.exists(ref) and os.path.getsize(ref) > 1024:
240
+ return ref, text
241
+ body = {"text": text, "format": "wav", "speed": 1.0,
242
+ "voice": voice}
243
+ raw = http_post("/tts", body, timeout=1800, raw=True)
244
+ with open(ref, "wb") as f:
245
+ f.write(raw)
246
+ log("voice ref 已生成 %.2fs(%d KB)" % (probe_dur(ref), len(raw) // 1024))
247
+ return ref, text
248
+
249
+
250
+ def step_tts(story, work, force=False):
251
+ out = []
252
+ vdir = os.path.join(work, "voices")
253
+ os.makedirs(vdir, exist_ok=True)
254
+ ref, ref_text = ensure_voice_ref(story, work)
255
+ for s in story["shots"]:
256
+ dst = os.path.join(vdir, "line-%s.wav" % s["id"])
257
+ raw_path = os.path.join(vdir, "line-%s.raw.wav" % s["id"])
258
+ if os.path.exists(dst) and not force:
259
+ out.append({"id": s["id"], "path": dst, "cached": True, "dur": round(probe_dur(dst), 2)})
260
+ log("tts %s 已存在,跳过" % s["id"])
261
+ continue
262
+ t0 = time.time()
263
+ body = {"text": s["line"], "format": "wav", "speed": story.get("speed") or 1.0,
264
+ "ref_audio_path": ref, "prompt_text": ref_text}
265
+ raw = http_post("/tts/clone", body, timeout=1800, raw=True)
266
+ with open(raw_path, "wb") as f:
267
+ f.write(raw)
268
+ # 每句单独做响度归一:否则「同一段旁白里有的句子响、有的句子轻」
269
+ r = run_json([PY, "-u", os.path.join(SCRIPTS, "media-enhance.py"), "audio",
270
+ "-i", raw_path, "-o", dst, "--json"], 300)
271
+ j = r.get("json") or {}
272
+ if not j.get("ok"):
273
+ raise RuntimeError("配音归一失败 shot=%s: %s" % (s["id"], j.get("error")))
274
+ d = probe_dur(dst)
275
+ out.append({"id": s["id"], "path": dst, "bytes": len(raw), "dur": round(d, 2),
276
+ "seconds": round(time.time() - t0, 1), "text": s["line"],
277
+ "loudness": [j.get("loudness_before"), j.get("loudness_after")],
278
+ "ref": ref})
279
+ log("tts %s -> %.2fs 音频,响度 %s -> %s LUFS"
280
+ % (s["id"], d, j.get("loudness_before"), j.get("loudness_after")))
281
+ return out
282
+
283
+
284
+ def kb_filter(motion, frames, w, h):
285
+ """Ken Burns:先把图放大到 2x 目标再推拉,避免 zoompan 在 720p 上放大的糊。"""
286
+ pre_w, pre_h = w * 2, h * 2
287
+ if motion == "out":
288
+ z = "max(1.12-0.12*on/%d,1.0)" % frames
289
+ x, y = "iw/2-(iw/zoom/2)", "ih/2-(ih/zoom/2)"
290
+ elif motion == "left":
291
+ z = "1.10"
292
+ x, y = "(iw-iw/zoom)*on/%d" % frames, "ih/2-(ih/zoom/2)"
293
+ elif motion == "right":
294
+ z = "1.10"
295
+ x, y = "(iw-iw/zoom)*(1-on/%d)" % frames, "ih/2-(ih/zoom/2)"
296
+ else:
297
+ z = "min(1.0+0.12*on/%d,1.12)" % frames
298
+ x, y = "iw/2-(iw/zoom/2)", "ih/2-(ih/zoom/2)"
299
+ return ("scale=%d:%d:force_original_aspect_ratio=increase,crop=%d:%d,"
300
+ "zoompan=z='%s':x='%s':y='%s':d=%d:s=%dx%d:fps=%d"
301
+ % (pre_w, pre_h, pre_w, pre_h, z, x, y, frames, w, h, 30))
302
+
303
+
304
+ def step_clips(story, work, force=False, with_video=False, video_shot="04"):
305
+ out = []
306
+ cdir = os.path.join(work, "clips")
307
+ os.makedirs(cdir, exist_ok=True)
308
+ w, h, fps = story["width"], story["height"], story["fps"]
309
+ gen_video = ""
310
+ video_meta = {}
311
+ if with_video:
312
+ vs = next((s for s in story["shots"] if s["id"] == video_shot), story["shots"][0])
313
+ gen_video = os.path.join(os.path.dirname(cdir), "gen", "wan-%s.mp4" % vs["id"])
314
+ if not os.path.exists(gen_video):
315
+ os.makedirs(os.path.dirname(gen_video), exist_ok=True)
316
+ log("gen-video: 用 Wan2.2 生成一镜(这一步最慢,约数分钟)")
317
+ r = run_json([PY, "-u", os.path.join(SCRIPTS, "gen-video.py"),
318
+ "-p", vs["image"], "-o", gen_video, "--frames", "49",
319
+ "--w", "704", "--h", "480", "--steps", "20", "--json"], 3600)
320
+ if not (r.get("json") or {}).get("ok") and not os.path.exists(gen_video):
321
+ log("gen-video 失败,该镜退回静态推拉: %s" % r.get("stderr_tail"))
322
+ gen_video = ""
323
+ else:
324
+ video_meta = {"kind": "gen-video", "id": vs["id"], "call": r,
325
+ "json": r.get("json")}
326
+ else:
327
+ video_meta = {"kind": "gen-video", "id": vs["id"], "cached": True, "path": gen_video}
328
+ for s in story["shots"]:
329
+ img = os.path.join(work, "frames", "shot-%s.enhanced.png" % s["id"])
330
+ voice = os.path.join(work, "voices", "line-%s.wav" % s["id"])
331
+ dst = os.path.join(cdir, "clip-%s.mp4" % s["id"])
332
+ adur = probe_dur(voice) if os.path.exists(voice) else 0.0
333
+ dur = max(float(s.get("dur") or 5.0), round(adur + 0.7, 2))
334
+ frames = int(round(dur * fps))
335
+ if os.path.exists(dst) and not force:
336
+ out.append({"id": s["id"], "path": dst, "cached": True, "dur": round(probe_dur(dst), 2),
337
+ "uses_gen_video": bool(gen_video and s["id"] == video_shot)})
338
+ if gen_video and s["id"] == video_shot and video_meta:
339
+ out[-1]["gen_video"] = video_meta
340
+ log("clip %s 已存在,跳过" % s["id"])
341
+ continue
342
+ use_video = gen_video and s["id"] == video_shot
343
+ if use_video:
344
+ # 生成的视频片段 → 拉长/裁剪到该镜时长,统一规格(不改内容,只补时长)
345
+ src = gen_video
346
+ vf = ("scale=%d:%d:force_original_aspect_ratio=increase,crop=%d:%d,fps=%d,"
347
+ "tpad=stop_mode=clone:stop_duration=%s,format=yuv420p"
348
+ % (w, h, w, h, fps, dur))
349
+ args = [FFMPEG, "-y", "-i", src, "-vf", vf, "-t", "%.2f" % dur,
350
+ "-c:v", "libx264", "-crf", "18", "-preset", "medium", "-an", dst]
351
+ else:
352
+ args = [FFMPEG, "-y", "-loop", "1", "-framerate", str(fps), "-i", img,
353
+ "-t", "%.2f" % dur, "-vf", kb_filter(s.get("motion", "in"), frames, w, h),
354
+ "-c:v", "libx264", "-crf", "18", "-preset", "medium", "-pix_fmt", "yuv420p",
355
+ "-an", dst]
356
+ r = run(args, 900)
357
+ if r["rc"] != 0:
358
+ raise RuntimeError("片段生成失败 shot=%s: %s" % (s["id"], r["stderr_tail"]))
359
+ # 配音压进该镜:先补静音到整镜时长,再与视频合流
360
+ mix = os.path.join(cdir, "clip-%s-av.mp4" % s["id"])
361
+ if os.path.exists(voice) and adur > 0:
362
+ padded = os.path.join(cdir, "voice-%s-pad.wav" % s["id"])
363
+ run([FFMPEG, "-y", "-i", voice, "-af",
364
+ "adelay=300|300,apad=whole_dur=%.2f" % dur,
365
+ "-t", "%.2f" % dur, "-ar", "48000", "-ac", "2", padded], 300)
366
+ r2 = run([FFMPEG, "-y", "-i", dst, "-i", padded, "-c:v", "copy",
367
+ "-c:a", "aac", "-b:a", "192k", "-shortest", mix], 600)
368
+ else:
369
+ r2 = run([FFMPEG, "-y", "-i", dst, "-f", "lavfi", "-i",
370
+ "anullsrc=r=48000:cl=stereo", "-t", "%.2f" % dur,
371
+ "-c:v", "copy", "-c:a", "aac", "-b:a", "192k", mix], 600)
372
+ if r2["rc"] != 0:
373
+ raise RuntimeError("音轨合成失败 shot=%s: %s" % (s["id"], r2["stderr_tail"]))
374
+ os.replace(mix, dst)
375
+ out.append({"id": s["id"], "path": dst, "dur": round(probe_dur(dst), 2),
376
+ "audio_dur": round(adur, 2), "uses_gen_video": bool(use_video), "call": r})
377
+ if use_video and video_meta:
378
+ out[-1]["gen_video"] = video_meta
379
+ log("clip %s -> %.2fs" % (s["id"], probe_dur(dst)))
380
+ return out
381
+
382
+
383
+ def ass_time(t):
384
+ h = int(t // 3600)
385
+ m = int((t % 3600) // 60)
386
+ s = t % 60
387
+ return "%d:%02d:%05.2f" % (h, m, s)
388
+
389
+
390
+ def write_ass(story, work, clips):
391
+ lines, t = [], 0.0
392
+ for s, c in zip(story["shots"], clips):
393
+ d = float(c.get("dur") or s.get("dur") or 5.0)
394
+ lines.append("Dialogue: 0,%s,%s,CN,,0,0,0,,%s"
395
+ % (ass_time(t + 0.25), ass_time(t + max(0.8, d - 0.20)), s["line"]))
396
+ t += d
397
+ head = """[Script Info]
398
+ ScriptType: v4.00+
399
+ PlayResX: %d
400
+ PlayResY: %d
401
+ WrapStyle: 2
402
+ ScaledBorderAndShadow: yes
403
+
404
+ [V4+ Styles]
405
+ Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
406
+ Style: CN,Microsoft YaHei,40,&H00FFFFFF,&H000000FF,&H00202020,&HA0000000,0,0,0,0,100,100,1,0,1,2.4,1,2,70,70,52,1
407
+
408
+ [Events]
409
+ Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
410
+ """ % (story["width"], story["height"])
411
+ path = os.path.join(work, "subs.ass")
412
+ with open(path, "w", encoding="utf-8") as f:
413
+ f.write(head + "\n".join(lines) + "\n")
414
+ return path, round(t, 2)
415
+
416
+
417
+ def step_final(story, work, clips, force=False, bgm=""):
418
+ final = os.path.join(work, "final.mp4")
419
+ if os.path.exists(final) and not force:
420
+ log("final 已存在,跳过(要重做加 --force final)")
421
+ return {"path": final, "cached": True, "dur": round(probe_dur(final), 2)}
422
+ lst = os.path.join(work, "concat.txt")
423
+ with open(lst, "w", encoding="utf-8") as f:
424
+ for c in clips:
425
+ f.write("file '%s'\n" % c["path"].replace("\\", "/"))
426
+ merged = os.path.join(work, "merged.mp4")
427
+ r = run([FFMPEG, "-y", "-f", "concat", "-safe", "0", "-i", lst, "-c", "copy", merged], 900)
428
+ if r["rc"] != 0:
429
+ raise RuntimeError("拼接失败: %s" % r["stderr_tail"])
430
+ ass, total = write_ass(story, work, clips)
431
+ fade_out = max(0.0, total - 0.8)
432
+ vf = "ass=subs.ass,fade=t=in:st=0:d=0.6,fade=t=out:st=%.2f:d=0.8" % fade_out
433
+ args = [FFMPEG, "-y", "-i", merged, "-vf", vf,
434
+ "-af", "loudnorm=I=-16:TP=-1.5:LRA=11",
435
+ "-c:v", "libx264", "-crf", "19", "-preset", "medium", "-pix_fmt", "yuv420p",
436
+ "-c:a", "aac", "-b:a", "192k", "-ar", "48000", "-movflags", "+faststart", final]
437
+ r2 = run(args, 1800, cwd=work)
438
+ if r2["rc"] != 0:
439
+ raise RuntimeError("终混失败: %s" % r2["stderr_tail"])
440
+ return {"path": final, "cached": False, "dur": round(probe_dur(final), 2),
441
+ "subs_seconds": total, "call": r2}
442
+
443
+
444
+ def main(argv=None):
445
+ argv = list(sys.argv[1:] if argv is None else argv)
446
+ force_json = "--json" in argv
447
+ argv = [x for x in argv if x != "--json"]
448
+ ap = argparse.ArgumentParser(description="确定性短片流水线")
449
+ ap.add_argument("--story", default="builtin")
450
+ ap.add_argument("--only", default="all",
451
+ help="images,enhance,tts,clips,final 用逗号组合;all=全部")
452
+ ap.add_argument("--force", default="", help="强制重做的步骤(逗号分隔),空=用缓存")
453
+ ap.add_argument("--with-video", action="store_true", help="其中一镜改用 Wan2.2 生成的视频")
454
+ ap.add_argument("--video-shot", default="04")
455
+ ap.add_argument("--bgm", default="")
456
+ ap.add_argument("--list", action="store_true")
457
+ a = ap.parse_args(argv)
458
+
459
+ story = load_story(a.story)
460
+ if a.list:
461
+ print(json.dumps(story, ensure_ascii=False, indent=2))
462
+ return 0
463
+ work = os.path.join(ROOT, "out", "episodes", story["slug"])
464
+ os.makedirs(work, exist_ok=True)
465
+ todo = [x.strip() for x in a.only.split(",") if x.strip()]
466
+ if "all" in todo:
467
+ todo = ["images", "enhance", "tts", "clips", "final"]
468
+ frc = [x.strip() for x in (a.force or "").split(",") if x.strip()]
469
+
470
+ report = {"ok": True, "slug": story["slug"], "title": story["title"],
471
+ "work": work, "started": time.strftime("%Y-%m-%d %H:%M:%S"),
472
+ "steps": {}, "shots": story["shots"]}
473
+ # 只跑某几步时不要把之前跑过的步骤记录冲掉(report.json 是「这条片子的完整工具调用轨迹」)
474
+ try:
475
+ with open(os.path.join(work, "report.json"), "r", encoding="utf-8") as f:
476
+ prev = json.load(f)
477
+ if isinstance(prev.get("steps"), dict):
478
+ report["steps"] = prev["steps"]
479
+ except Exception:
480
+ pass
481
+ t_all = time.time()
482
+ # 风扇:不动。2026-12-02 主人明确要求——没人叫他提转速,空转的风扇很吵;
483
+ # 需要降温请自己在外面跑 fan-mode.py(且 FanControl 的进出风曲线本身就不合理)。
484
+
485
+ try:
486
+ images = step_images(story, work, force=("images" in frc)) if "images" in todo else []
487
+ if images:
488
+ report["steps"]["images"] = images
489
+ enhance = step_enhance(story, work, force=("enhance" in frc)) if "enhance" in todo else []
490
+ if enhance:
491
+ report["steps"]["enhance"] = enhance
492
+ tts = step_tts(story, work, force=("tts" in frc)) if "tts" in todo else []
493
+ if tts:
494
+ report["steps"]["tts"] = tts
495
+ clips = step_clips(story, work, force=("clips" in frc),
496
+ with_video=a.with_video, video_shot=a.video_shot) if "clips" in todo else []
497
+ if clips:
498
+ report["steps"]["clips"] = clips
499
+ if "final" in todo:
500
+ if not clips:
501
+ # 单独跑 final 时从磁盘恢复片段顺序
502
+ clips = [{"id": s["id"], "path": os.path.join(work, "clips", "clip-%s.mp4" % s["id"]),
503
+ "dur": round(probe_dur(os.path.join(work, "clips", "clip-%s.mp4" % s["id"])), 2)}
504
+ for s in story["shots"]]
505
+ report["steps"]["final"] = step_final(story, work, clips, force=("final" in frc), bgm=a.bgm)
506
+ except Exception as e:
507
+ report["ok"] = False
508
+ report["error"] = "%s: %s" % (type(e).__name__, e)
509
+ report["seconds_total"] = round(time.time() - t_all, 1)
510
+ with open(os.path.join(work, "report.json"), "w", encoding="utf-8") as f:
511
+ json.dump(report, f, ensure_ascii=False, indent=2)
512
+ print(json.dumps({"ok": False, "error": report["error"], "work": work}, ensure_ascii=False))
513
+ return 4
514
+
515
+ report["seconds_total"] = round(time.time() - t_all, 1)
516
+ fin = report["steps"].get("final") or {}
517
+ report["final"] = fin.get("path", "")
518
+ with open(os.path.join(work, "report.json"), "w", encoding="utf-8") as f:
519
+ json.dump(report, f, ensure_ascii=False, indent=2)
520
+ summary = {"ok": True, "slug": story["slug"], "final": fin.get("path", ""),
521
+ "duration": fin.get("dur"), "work": work,
522
+ "report": os.path.join(work, "report.json"),
523
+ "seconds_total": report["seconds_total"]}
524
+ print(json.dumps(summary, ensure_ascii=False) if force_json else json.dumps(summary, ensure_ascii=False, indent=2))
525
+ return 0
526
+
527
+
528
+ if __name__ == "__main__":
529
+ sys.exit(main())