Datasets:
Download code/burn_corpus.py from teawhite/EYBX-processed: direct link, hf CLI and curl.
- Browser
- Download file 13.3 kB
-
https://huggingface.co/datasets/teawhite/EYBX-processed/resolve/main/code/burn_corpus.py
- Command line
-
hf download hf://datasets/teawhite/EYBX-processed/code/burn_corpus.py
-
curl -L -o burn_corpus.py https://huggingface.co/datasets/teawhite/EYBX-processed/resolve/main/code/burn_corpus.py
13.3 kB
| #!/usr/bin/env python3 | |
| # -*- coding: utf-8 -*- | |
| """ | |
| burn_corpus.py —— 转场语料:把两个不同场景的 clip 烧成一个新的 81 帧 clip | |
| 目的不是做特效,是训一个**可触发的换场景开关**:推理时把场景从句换成 trigger | |
| 从句、握持几个 cell,模型就烧向指定的新场景。 | |
| 四条硬约束(缺一条这个开关就训不出来): | |
| 1. trigger 从句里**必须含目的地** —— 否则没法指定转到哪个场景 | |
| 2. 燃烧的起止必须踩 latent cell 边界 —— (N_pre-1)%4==0、N_burn ∈ {8,12,16} | |
| cell k 覆盖帧 4k-3..4k,燃烧不踩边界的话某个 cell 会同时含 A 和火, | |
| 那个 cell 的文本条件就无法定义 | |
| 3. N_pre 在样本间随机 —— 固定的话模型会把「烧」绑到时间位置而不是绑到 prompt | |
| 4. 烧完切回纯 B | |
| 动作从句全程不变:所以只挑「21 个 cell 动作恒定」的 clip,且 A、B 的动作相同。 | |
| 这正是要用动作真值对齐接缝的原因 —— 接缝两侧玩家的运动方向必须一致, | |
| 否则烧完的瞬间画面会出现一个物理上不可能的转向。 | |
| hardcut 是负对照("cutting to",瞬切无火),教模型 trigger 词本身 ≠ 火。 | |
| 火焰合成直接用 burn_transition.py 的实现(极坐标湍流火口 + 焦化 + 热浪 + 四层火焰), | |
| 只是把它从「读两个视频文件」改成「吃内存里的两段帧」。 | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| import random | |
| import subprocess | |
| import sys | |
| import numpy as np | |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |
| sys.path.insert(0, "/data/zhiyangdeng") # burn_transition.py | |
| from scenes import SCENE_NL, ACTIONS # noqa: E402 | |
| import burn_transition as BT # noqa: E402 | |
| W, H, FRAMES, CELLS, FPS = 832, 480, 81, 21, 16.0 | |
| BURN_BASE, HARDCUT_BASE = 300_000_000, 400_000_000 | |
| N_PRE_CHOICES = [9, 13, 17, 21, 25, 29, 33] # 均满足 (N_pre-1)%4==0 | |
| N_BURN_CHOICES = [8, 12, 16] # 2 / 3 / 4 个 cell | |
| # 场景从句统一是 "in a ..." 开头,直接套进 "burning away into {b}" 会拼出 | |
| # "...burning away into in a dark cave..."。目的地要去掉前导的 "in ", | |
| # 只留名词短语,才读得通。 | |
| TRIG_BURN = "In a 2.5D top down view, {a} burning away into {b}, the player is {action}." | |
| TRIG_CUT = "In a 2.5D top down view, {a} cutting to {b}, the player is {action}." | |
| def np_of(clause: str) -> str: | |
| """场景从句 -> 名词短语:只去掉前导的 "in ",冠词要留着。 | |
| "in a dark cave lit by blue crystal glow" -> "a dark cave lit by blue crystal glow" | |
| """ | |
| return clause[3:] if clause.startswith("in ") else clause | |
| PLAIN = "In a 2.5D top down view, {s}, the player is {action}." | |
| def cell_of(frame_idx: int) -> int: | |
| """帧 -> latent cell(cell 0 = 帧 0;cell k = 帧 4k-3..4k)。""" | |
| return 0 if frame_idx == 0 else (frame_idx + 3) // 4 | |
| def read_clip(path): | |
| raw = subprocess.run(["ffmpeg", "-v", "error", "-i", path, "-f", "rawvideo", | |
| "-pix_fmt", "rgb24", "-"], capture_output=True).stdout | |
| n = len(raw) // (W * H * 3) | |
| if n < FRAMES: | |
| return None | |
| return np.frombuffer(raw[:FRAMES * W * H * 3], np.uint8).reshape(FRAMES, H, W, 3) | |
| def encode(frames, path, crf=18): | |
| p = subprocess.Popen(["ffmpeg", "-y", "-v", "error", "-f", "rawvideo", "-pix_fmt", "rgb24", | |
| "-s", f"{W}x{H}", "-r", f"{FPS:g}", "-i", "-", "-an", | |
| "-c:v", "libx264", "-crf", str(crf), "-preset", "veryfast", | |
| "-pix_fmt", "yuv420p", "-movflags", "+faststart", path], | |
| stdin=subprocess.PIPE) | |
| p.stdin.write(np.ascontiguousarray(frames).tobytes()) | |
| p.stdin.close() | |
| return p.wait() == 0 | |
| def compose_burn(fa, fb, n_pre, n_burn, seed, amp=110.0, embers=1.0, color="fire"): | |
| """fa/fb: [81,H,W,3] RGB uint8。返回烧接后的 [81,H,W,3]。""" | |
| rng = np.random.default_rng(seed) | |
| cx, cy = 0.5 * W, 0.5 * H | |
| yy, xx = np.mgrid[0:H, 0:W].astype(np.float32) | |
| dxg, dyg = xx - cx, yy - cy | |
| dist = np.hypot(dxg, dyg) | |
| rmax = float(dist.max()) | |
| noise = BT.PolarNoise(dist, np.arctan2(dyg, dxg), rmax, rng) | |
| emb = BT.Embers(W, H, cx, cy, rng) | |
| C_HOT, C_MID, C_OUT, C_GLOW = (np.array(c, np.float32) for c in BT.PALETTES[color]) | |
| cfg = BT.Config(a="", b="", out="", amp=amp, embers=embers, style="burn", color=color) | |
| out = np.empty((FRAMES, H, W, 3), np.uint8) | |
| out[:n_pre] = fa[:n_pre] | |
| prev_r = 0.0 | |
| for k in range(n_burn): | |
| i = n_pre + k | |
| # BGR:burn_transition 的配色是 BGR 序,这里整段在 BGR 域里算完再转回来 | |
| A = fa[i][:, :, ::-1].astype(np.float32) | |
| B = fb[i][:, :, ::-1].astype(np.float32) | |
| u = (k + 1) / n_burn | |
| img, r = BT._composite_burn(A, B, dist, dxg, dyg, xx, yy, rmax, u, k, | |
| cfg, noise, rng, C_HOT, C_MID, C_OUT, C_GLOW) | |
| fade = 1.0 - BT.smoothstep((r - rmax * 0.90) / (rmax * 0.22)) | |
| emb.spawn(int(160 * embers * fade * (0.4 + 0.6 * min(r / 200.0, 1.0))), | |
| max(r, 6.0), max(r - prev_r, 0.0)) | |
| emb.step() | |
| import cv2 | |
| sp = cv2.GaussianBlur(emb.draw(), (0, 0), 0.7) | |
| big = cv2.GaussianBlur(sp, (0, 0), 5.0) * 0.60 | |
| img = img + (C_HOT * (np.clip(sp, 0, 2.6) * 0.75)[..., None] | |
| + C_MID * (np.clip(sp, 0, 2.6) * 1.05)[..., None] | |
| + C_OUT * big[..., None]) | |
| prev_r = r | |
| out[i] = np.clip(img, 0, 255).astype(np.uint8)[:, :, ::-1] | |
| # 烧完切回纯 B(余烬只留很短一截,避免污染 B 的场景条件) | |
| import cv2 | |
| for i in range(n_pre + n_burn, FRAMES): | |
| img = fb[i][:, :, ::-1].astype(np.float32) | |
| if len(emb) and i - (n_pre + n_burn) < 8: | |
| emb.step() | |
| sp = cv2.GaussianBlur(emb.draw(), (0, 0), 1.2) | |
| img = img + C_MID * (np.clip(sp, 0, 2.2) * 0.95)[..., None] | |
| out[i] = np.clip(img, 0, 255).astype(np.uint8)[:, :, ::-1] | |
| return out | |
| def prompt_schedule(sa, sb, action, n_pre, n_burn, trig_tmpl): | |
| """21 条逐 cell prompt:A 场景 -> trigger(含目的地) -> B 场景。""" | |
| c0 = cell_of(n_pre) # 燃烧起始 cell | |
| c1 = cell_of(n_pre + n_burn - 1) # 燃烧结束 cell(含) | |
| act = ACTIONS[action] | |
| ps = [] | |
| for k in range(CELLS): | |
| if k < c0: | |
| ps.append(PLAIN.format(s=SCENE_NL[sa], action=act)) | |
| elif k <= c1: | |
| ps.append(trig_tmpl.format(a=SCENE_NL[sa], b=np_of(SCENE_NL[sb]), action=act)) | |
| else: | |
| ps.append(PLAIN.format(s=SCENE_NL[sb], action=act)) | |
| return ps, c0, c1 | |
| def hamiltonian_pairs(scenes, rng): | |
| """18 个场景的哈密顿圈:每个场景各当一次源、一次目的地。""" | |
| s = list(scenes); rng.shuffle(s) | |
| return [(s[i], s[(i + 1) % len(s)]) for i in range(len(s))] | |
| def main(): | |
| ap = argparse.ArgumentParser(description="燃烧转场语料") | |
| ap.add_argument("--root", default="/data/zhiyangdeng/data_eybx") | |
| ap.add_argument("--n_burn", type=int, default=1500) | |
| ap.add_argument("--n_hardcut", type=int, default=400) | |
| ap.add_argument("--n_dir_pairs", type=int, default=6, help="额外留出的方向对") | |
| ap.add_argument("--seed", type=int, default=7) | |
| ap.add_argument("--workers", type=int, default=16) | |
| args = ap.parse_args() | |
| rng = random.Random(args.seed) | |
| rows = [] | |
| for f in sorted(os.listdir(os.path.join(args.root, "meta"))): | |
| if not f.endswith(".jsonl"): | |
| continue | |
| with open(os.path.join(args.root, "meta", f), encoding="utf-8") as fh: | |
| rows += [json.loads(l) for l in fh] | |
| # 只用「场景纯 + 动作恒定 + 在动」的 clip:接缝两侧的动作从句必须完全一样 | |
| pool = {} | |
| for r in rows: | |
| # 纯度 >=0.75 就收(旧交付成品里本来就有 min_purity 0.75 的 clip); | |
| # 场景取该 clip 的主场景。要求全程只出现一个场景,接缝才不会把第三个场景带进来。 | |
| if r["min_purity"] < 0.75: | |
| continue | |
| acts = set(r["actions"]); scs = set(r["scenes"]) | |
| if len(acts) != 1 or len(scs) != 1: | |
| continue | |
| a = acts.pop() | |
| if a == 0: # 站着不动的接缝没有对齐意义 | |
| continue | |
| pool.setdefault((scs.pop(), a), []).append(r) | |
| scenes = sorted({k[0] for k in pool}) | |
| print(f"可用底料 {sum(len(v) for v in pool.values()):,} 个 clip · " | |
| f"{len(scenes)} 个场景 · {len(pool)} 个 (场景,动作) 组合") | |
| # 留出:18 对哈密顿圈(每场景各当一次源、一次目的地)+ 6 对方向对 | |
| held = set(hamiltonian_pairs(scenes, rng)) | |
| cand = [(a, b) for a in scenes for b in scenes if a != b and (a, b) not in held | |
| and (b, a) not in held] | |
| rng.shuffle(cand) | |
| dir_pairs = cand[:args.n_dir_pairs] | |
| held |= set(dir_pairs) | |
| print(f"留出 {len(held)} 对({len(held)-len(dir_pairs)} 对哈密顿圈 + " | |
| f"{len(dir_pairs)} 对方向对,方向对的反向留在训练集里)") | |
| out_clips = os.path.join(args.root, "clips", "transition"); os.makedirs(out_clips, exist_ok=True) | |
| out_meta = os.path.join(args.root, "meta"); os.makedirs(out_meta, exist_ok=True) | |
| def sample_pair(allow_held): | |
| for _ in range(400): | |
| a, b = rng.sample(scenes, 2) | |
| if ((a, b) in held) != allow_held: | |
| continue | |
| acts = [k[1] for k in pool if k[0] == a] | |
| rng.shuffle(acts) | |
| for act in acts: | |
| if (b, act) in pool and pool[(a, act)] and pool[(b, act)]: | |
| return a, b, act | |
| return None | |
| jobs = [] | |
| for i in range(args.n_burn + args.n_hardcut): | |
| is_burn = i < args.n_burn | |
| # 留出对也要生成 clip,但只进 pool_heldout,不进训练池 | |
| allow_held = (i % 12 == 0) | |
| got = sample_pair(allow_held) | |
| if got is None: | |
| got = sample_pair(False) | |
| allow_held = False | |
| if got is None: | |
| continue | |
| a, b, act = got | |
| ra = rng.choice(pool[(a, act)]); rb = rng.choice(pool[(b, act)]) | |
| n_pre = rng.choice(N_PRE_CHOICES) | |
| n_bn = rng.choice(N_BURN_CHOICES) | |
| base = BURN_BASE if is_burn else HARDCUT_BASE | |
| jobs.append(dict(idx=i, kind="burn" if is_burn else "hardcut", | |
| a=a, b=b, action=act, ra=ra["clip_id"], rb=rb["clip_id"], | |
| sa=ra["session"], sb=rb["session"], | |
| n_pre=n_pre, n_burn=n_bn, held=allow_held, | |
| fight=base + i, seed=args.seed * 100003 + i)) | |
| print(f"计划生成 {len(jobs):,} 条(burn {sum(1 for j in jobs if j['kind']=='burn'):,} / " | |
| f"hardcut {sum(1 for j in jobs if j['kind']=='hardcut'):,}," | |
| f"其中留出 {sum(1 for j in jobs if j['held']):,})") | |
| json.dump(dict(pairs=[list(p) for p in sorted(held)], | |
| hamiltonian=len(held) - len(dir_pairs), direction=len(dir_pairs)), | |
| open(os.path.join(args.root, "latent", "heldout_pairs.json"), "w"), | |
| ensure_ascii=False, indent=1) | |
| from concurrent.futures import ProcessPoolExecutor, as_completed | |
| with open(os.path.join(out_meta, "transition.jsonl"), "w", encoding="utf-8") as fh, \ | |
| ProcessPoolExecutor(args.workers) as ex: | |
| futs = {ex.submit(_render, j, args.root, out_clips): j for j in jobs} | |
| done = 0 | |
| for f in as_completed(futs): | |
| r = f.result() | |
| if r: | |
| fh.write(json.dumps(r, ensure_ascii=False) + "\n"); done += 1 | |
| if done % 100 == 0 and done: | |
| print(f" {done:,}/{len(jobs):,}", flush=True) | |
| print(f"DONE {done:,} 条转场 -> {out_clips}") | |
| def _render(j, root, out_clips): | |
| fa = read_clip(os.path.join(root, "clips", j["sa"], j["ra"] + ".mp4")) | |
| fb = read_clip(os.path.join(root, "clips", j["sb"], j["rb"] + ".mp4")) | |
| if fa is None or fb is None: | |
| return None | |
| if j["kind"] == "burn": | |
| pix = compose_burn(fa, fb, j["n_pre"], j["n_burn"], j["seed"]) | |
| tmpl = TRIG_BURN | |
| else: | |
| pix = np.concatenate([fa[:j["n_pre"]], fb[j["n_pre"]:]], 0) # 瞬切,无火 | |
| tmpl = TRIG_CUT | |
| ps, c0, c1 = prompt_schedule(j["a"], j["b"], j["action"], j["n_pre"], j["n_burn"], tmpl) | |
| stem = f"clip_Eybx_{j['fight']}_{0:06d}" | |
| if not encode(pix, os.path.join(out_clips, stem + ".mp4")): | |
| return None | |
| return dict(clip_id=stem, session="transition", kind=j["kind"], fight=j["fight"], | |
| start_cell=0, pair=[j["a"], j["b"]], action=j["action"], | |
| src_a=j["ra"], src_b=j["rb"], n_pre=j["n_pre"], n_burn=j["n_burn"], | |
| burn_cells=[c0, c1], heldout=j["held"], prompts=ps, | |
| actions=[j["action"]] * CELLS, | |
| scenes=[j["a"]] * c0 + [f"{j['a']}->{j['b']}"] * (c1 - c0 + 1) | |
| + [j["b"]] * (CELLS - c1 - 1), | |
| min_purity=1.0) | |
| if __name__ == "__main__": | |
| main() | |