#!/usr/bin/env python3 """Build hyperframes projects for all clips from segments.json. Each clip gets: cover (full-frame — use a FRAME FROM THE VIDEO itself, e.g. the clip's first frame, NOT a brand-new AI painting) + body video + outlined HTML/CSS captions + chapter chip + optional illustrations + end-card CTA. Renders to ONE final encode per clip (no decode/encode cascade). This is a TEMPLATE — copy it into your project and edit: - ROOT (project directory containing segments.json + output/) - CHAPTER (per-clip chapter chip text) - SYNC (per-clip sync offset; ZERO when clips were accurate-cut) - illustrations.py (sibling file: per-clip illustration definitions) Sources read from `/output/`: clip_NN_slug.mp4 (HLG/HDR source; tone-mapped to SDR via tonemap_to_sdr) cover_NN_slug.png clip_NN_slug.asr.srt (火山 streaming-ASR word-timed SRT) Targets written under `/hf_clip_NN/1080/`. Run with `python3 build_hf_clips.py [seg_id ...]` — pass segment ids to build a subset (e.g. `python3 build_hf_clips.py 1`); no args builds all. """ import json, os, re, shutil, subprocess, sys from pathlib import Path # illustrations.py sits next to this script (or set sys.path accordingly) sys.path.insert(0, str(Path(__file__).parent)) from illustrations import render_for_clip, ILLUSTRATIONS # ── EDIT THESE PER PROJECT ────────────────────────────────────── ROOT = Path(__file__).resolve().parent SEG_FILE = os.environ.get("SEG_FILE", "segments.json") SEG = json.load(open(ROOT / SEG_FILE)) # Per-clip sync offset (seconds). Use 0.0 when clips were accurate-cut # with `segment.py --reencode` (the recommended default). SYNC = {i: 0.0 for i in range(1, 11)} # Per-clip chapter chip text — short label for the top-left chip CHAPTER = { 1: "第一段 · 效率暴涨", 2: "第二段 · 需求与失业", 3: "第三段 · 编程的终结", 4: "第四段 · 差距变大", 5: "第五段 · 一句 hello", 6: "第六段 · 最好的职业", 7: "第七段 · 学校禁 AI", 8: "第八段 · 代码成艺术", 9: "第九段 · 真有用吗", 10: "第十段 · 驾驭层", } # Opener hook lines shown big over the cover (0→cover end). Each entry is a # list of HTML lines; wrap the punch word in … (gold). HOOK = { 1: ["效率翻了一倍", "需求却涨了十倍"], 2: ["AI 来了", "谁会先失业?"], 3: ["编程", "真的要终结了吗?"], 4: ["AI 时代", "差距只会越来越大"], 5: ["一句 hello", "就能改变什么?"], 6: ["现在", "什么才是最好的职业?"], 7: ["学校为什么", "要禁用 AI?"], 8: ["写代码", "正在变成一门艺术"], 9: ["AI", "真的有用吗?"], 10: ["未来属于", "会驾驭 AI的人"], } # Lower-third nameplate (王建硕 slides in when the speaker first appears). NAMEPLATE_NAME = "王建硕" NAMEPLATE_ROLE = "聊 AI · 聊创业" # Source video suffix. Our cropped vertical clips ARE the canonical # clip_NN_slug.mp4 (horizontal originals archived), so no suffix. CLIP_SUFFIX = "" # ──────────────────────────────────────────────────────────────── COVER_SCENE_DUR = 1.5 CTA_SCENE_DUR = 3.24 # Production pipeline version — bump on every change to the recipe. # Stamped bottom-right on the end card of every clip. SKILL_NAME = "wjs-overlaying-video" VERSION = "v1.5" # v1.5: 面部安全布局 — 所有文字/图形避开人脸(主体侧),图形走对侧/底部 # v1.4: 生动化 — 数据三幕动画+关键词弹跳+开场hook+人物条+Ken Burns+暗角呼吸 # v1.3: 字幕风格03 关键词高亮(金块)+思源宋体 Noto Serif SC # v1.2: 火山流式ASR字幕 + zscale(npl=203 hable) HLG→SDR 调色 # zscale-capable ffmpeg (system Homebrew build lacks zscale/tonemap). TM_FFMPEG = os.environ.get("TM_FFMPEG", str(Path.home() / "Library/Python/3.9/lib/python/site-packages/" "imageio_ffmpeg/binaries/ffmpeg-macos-aarch64-v7.1")) # Locked HLG(BT2020/arib-std-b67)->SDR(BT709) tone map. npl=203 matches the # macOS-native (qlmanage) reference brightness; hable keeps contrast. TONEMAP_VF = ("zscale=tin=arib-std-b67:min=bt2020nc:pin=bt2020:t=linear:npl=203," "format=gbrpf32le,tonemap=tonemap=hable:desat=0," "zscale=t=bt709:m=bt709:p=bt709:r=tv,format=yuv420p,fps=30") def _is_hlg_hdr(src): """True only for genuinely HLG/HDR sources (need tone-mapping). Clips that are ALREADY Rec.709 SDR (e.g. graded multicam renders, polysync output) must NOT be tone-mapped — running the HLG recipe on SDR washes/darkens the color. Detect via the video stream's color_transfer.""" try: out = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=color_transfer", "-of", "csv=p=0", str(src)], capture_output=True, text=True).stdout.strip().lower() except Exception: out = "" return out in ("arib-std-b67", "smpte2084") # HLG / PQ def tonemap_to_sdr(src, dst): """Make a render-ready body clip with DENSE keyframes (-g 30) so HyperFrames can seek every frame. HLG/HDR sources get the locked zscale tone-map; sources that are already SDR just get a straight re-encode (NO tone-map — that would ruin already-correct color). Skips if dst is up-to-date.""" if dst.exists() and dst.stat().st_mtime >= src.stat().st_mtime: print(f" [color] reuse {dst.name} (up-to-date)") return if not _is_hlg_hdr(src): print(f" [color] SDR re-encode (no tone-map) {src.name} -> {dst.name}") subprocess.run(["ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-i", str(src), "-vf", "fps=30,format=yuv420p", "-c:v", "libx264", "-preset", "medium", "-crf", "18", "-g", "30", "-keyint_min", "30", "-movflags", "+faststart", "-color_primaries", "bt709", "-color_trc", "bt709", "-colorspace", "bt709", "-c:a", "aac", "-b:a", "192k", str(dst)], check=True) return print(f" [color] tonemap HLG->SDR {src.name} -> {dst.name} (zscale npl=203 hable)") subprocess.run([TM_FFMPEG, "-y", "-hide_banner", "-loglevel", "error", "-i", str(src), "-vf", TONEMAP_VF, "-c:v", "libx264", "-preset", "medium", "-crf", "18", "-pix_fmt", "yuv420p", # dense keyframes (1/frame-second) so the HyperFrames renderer # can seek every frame without freezing on sparse GOPs. "-g", "30", "-keyint_min", "30", "-movflags", "+faststart", "-color_primaries", "bt709", "-color_trc", "bt709", "-colorspace", "bt709", "-c:a", "aac", "-b:a", "192k", str(dst)], check=True) def parse_ts(t): if isinstance(t, (int, float)): # segments.json may store float seconds return float(t) h, m, s = t.split(":") return int(h)*3600 + int(m)*60 + float(s) # Keyword highlight (字幕风格 03): wrap punchy QUANTITATIVE phrases in a gold # block. Auto-selected, sparse on purpose — most cues stay clean serif white. # Only the genuinely emphatic magnitudes: 倍数(一倍/十倍/翻倍), 大数量级(50万/ # 一亿/1,000万), 百分比(50%). Deliberately EXCLUDES generic 个/年 ("一个","20年") # so the gold block stays meaningful, not noisy. Handles thousands-commas. _NUM = r"[0-90-9,,一二三四五六七八九十百千两零几]+" _HOT_RE = re.compile( rf"(?:翻了?{_NUM}?[倍番]|{_NUM}\s*(?:[倍番]|万亿?|亿|%|%))" ) def mark_keywords(text): """Return HTML with quantitative keywords wrapped in . HTML-escapes the rest so cue text never injects markup.""" import html as _html out, last = [], 0 for m in _HOT_RE.finditer(text): out.append(_html.escape(text[last:m.start()])) out.append(f'{_html.escape(m.group())}') last = m.end() out.append(_html.escape(text[last:])) return "".join(out) def srt_to_cues(srt_path, cover_offset, sync_offset): TS = re.compile(r"(\d{2}):(\d{2}):(\d{2}),(\d{3})") def to_s(g): h,m,s,ms = map(int, g.groups()) return h*3600 + m*60 + s + ms/1000.0 cues = [] for b in re.split(r"\n\s*\n", srt_path.read_text(encoding="utf-8").strip()): lines = b.strip().split("\n") if len(lines) < 3: continue m = list(TS.finditer(lines[1])) if len(m) != 2: continue text = "\n".join(lines[2:]).strip() if not text: continue cues.append({ "text": text, "html": mark_keywords(text), "start": to_s(m[0]) + cover_offset + sync_offset, "end": to_s(m[1]) + cover_offset + sync_offset, }) return cues HTML_TEMPLATE = '''\
@@HOOK_LINES@@
@@CHAPTER_TEXT@@
@@NP_NAME@@ @@NP_ROLE@@
@@ILL_HTML@@
关注王建硕
↓
微信公众号 · 视频号
聊 AI · 聊创业 · 持续更新
@@VER_STAMP@@
''' def build_clip(seg): sid = seg["id"] slug = seg["slug"] body_dur = parse_ts(seg["end"]) - parse_ts(seg["start"]) body_start = COVER_SCENE_DUR cta_start = body_start + body_dur total_dur = cta_start + CTA_SCENE_DUR proj = ROOT / f"hf_clip_{sid:02d}" proj.mkdir(exist_ok=True) work = proj / "1080" if not work.exists(): # init hyperframes scaffold subprocess.run(["npx", "hyperframes", "init"], cwd=proj, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) work.mkdir(exist_ok=True) # Color-convert HLG source -> SDR clip.mp4 (locked zscale recipe), copy cover. tonemap_to_sdr(ROOT / "output" / f"clip_{sid:02d}_{slug}{CLIP_SUFFIX}.mp4", work / "clip.mp4") shutil.copy(ROOT / "output" / f"cover_{sid:02d}_{slug}.png", work / "cover.png") # Build captions json from the 火山 streaming-ASR SRT (word-timed). cues = srt_to_cues( ROOT / "output" / f"clip_{sid:02d}_{slug}.asr.srt", cover_offset=COVER_SCENE_DUR, sync_offset=SYNC[sid], ) captions_json = json.dumps(cues, ensure_ascii=False, indent=2) ill_css, ill_html, ill_gsap = render_for_clip(sid, body_offset=body_start) hook_lines = "\n".join( f'
{ln}
' for ln in HOOK.get(sid, []) ) subs = { "@@TOTAL_DUR@@": f"{total_dur:.2f}", "@@COVER_DUR@@": f"{COVER_SCENE_DUR + 0.1:.2f}", "@@BODY_START@@": f"{body_start:.2f}", "@@BODY_DUR@@": f"{body_dur:.2f}", "@@HOOK_LINES@@": hook_lines, "@@HOOK_OUT@@": f"{COVER_SCENE_DUR - 0.3:.2f}", "@@NAMEPLATE_DUR@@": f"{min(5.0, body_dur):.2f}", "@@NAMEPLATE_IN@@": f"{body_start + 0.3:.2f}", "@@NAMEPLATE_OUT@@": f"{body_start + 4.0:.2f}", "@@NP_NAME@@": NAMEPLATE_NAME, "@@NP_ROLE@@": NAMEPLATE_ROLE, "@@CHAPTER_TEXT@@": CHAPTER[sid], "@@CHAPTER_IN@@": f"{body_start + 0.4:.2f}", "@@CHAPTER_OUT@@": f"{body_start + 4.0:.2f}", "@@CTA_START@@": f"{cta_start:.2f}", "@@CTA_DUR@@": f"{CTA_SCENE_DUR:.2f}", "@@CTA_IN_1@@": f"{cta_start + 0.14:.2f}", "@@CTA_IN_2@@": f"{cta_start + 0.34:.2f}", "@@CTA_IN_3@@": f"{cta_start + 0.54:.2f}", "@@CTA_IN_4@@": f"{cta_start + 0.84:.2f}", "@@VER_STAMP@@": f"{SKILL_NAME} {VERSION}", "@@CAPTIONS_JSON@@": captions_json, "@@ILL_CSS@@": ill_css, "@@ILL_HTML@@": ill_html, "@@ILL_GSAP@@": ill_gsap, } html = HTML_TEMPLATE for k, v in subs.items(): html = html.replace(k, v) (work / "index.html").write_text(html, encoding="utf-8") print(f"[clip {sid}] built {work} ({body_dur:.1f}s body, {len(cues)} cues, sync +{SYNC[sid]:.2f}s)") _only = {int(a) for a in sys.argv[1:] if a.isdigit()} for s in SEG["segments"]: if _only and s["id"] not in _only: continue build_clip(s)