#!/usr/bin/env python3 """xv 分镜清单校验器 —— 零第三方依赖,Python 3.9+。 ERROR 阻断进入生成阶段;WARN 不阻断但必须逐条确认。 规则来源:Toonflow workflow PART A(references/toonflow-workflow-director.md) """ import json import re import sys from pathlib import Path def _find_root(): """工作空间根:MANJU_ROOT > cwd 向上找 config/pipeline.json > 脚本上级。""" import os as _os env = _os.environ.get("MANJU_ROOT") if env: return Path(env).expanduser().absolute() d = Path.cwd().absolute() for p in (d, *d.parents): if (p / "config" / "pipeline.json").is_file(): return p return Path(__file__).absolute().parent.parent ROOT = _find_root() SHOT_ID_RE = re.compile(r"^S\d{2}$") EVENT_ID_RE = re.compile(r"^E\d{2}$") EVENT_SCAN_RE = re.compile(r"\bE\d{2}\b") SHOT_TYPES = ["大特写", "特写", "近景", "中景", "全景", "远景"] STATUSES = {"planned", "prompted", "generated", "adopted", "rejected"} RELATIONS = {"continuous", "partial", "reset"} FORBIDDEN_STATE = ("同上", "延续上一段", "沿用上一段", "同上一段") def nominal_seconds(): try: with (ROOT / "config/pipeline.json").open(encoding="utf-8") as f: return float(json.load(f)["videoModel"]["nominalSeconds"]) except Exception: return 5.06 def load_events(ep_dir): path = ep_dir / "10_events.md" if not path.exists(): return None return set(EVENT_SCAN_RE.findall(path.read_text(encoding="utf-8"))) def shot_hash(text): import hashlib return hashlib.sha256(text.encode("utf-8")).hexdigest()[:8] def validate(path): errors, warns = [], [] path = Path(path).resolve() ep_dir = path.parent nominal = nominal_seconds() try: data = json.loads(path.read_text(encoding="utf-8")) except Exception as exc: return [f"无法读取清单:{exc}"], [], {} for key in ("episode", "targetDuration", "shots"): if key not in data: errors.append(f"顶层缺少必填字段 {key}") shots = data.get("shots") or [] if not shots: errors.append("shots 为空") return errors, warns, {"shots": 0, "total": 0.0, "errors": len(errors), "warns": len(warns)} if not re.match(r"^EP\d{2}$", str(data.get("episode", ""))): errors.append("episode 需为 EPxx 格式") events = load_events(ep_dir) if events is None: warns.append("未找到 10_events.md,跳过 E## 溯源校验") else: for eid in sorted(events): used = any(eid in (s.get("eventIds") or []) for s in shots) if not used: warns.append(f"源节拍 {eid} 未映射到任何镜头(可能漏拍)") seen, total = set(), 0.0 prev = None for i, s in enumerate(shots): sid = str(s.get("shotId", f"<第{i + 1}项>")) if not SHOT_ID_RE.match(sid): errors.append(f"{sid}: shotId 需为 Sxx 格式") if sid in seen: errors.append(f"{sid}: 镜号重复") seen.add(sid) if SHOT_ID_RE.match(sid) and int(sid[1:]) != i + 1: errors.append(f"{sid}: 镜号未按 S01 起顺序编号") eids = s.get("eventIds") or [] if not eids: errors.append(f"{sid}: 缺 eventIds,禁止无源新增动作") else: for eid in eids: if not EVENT_ID_RE.match(str(eid)): errors.append(f"{sid}: 非法事件号 {eid}") elif events is not None and eid not in events: errors.append(f"{sid}: 事件 {eid} 未登记在 10_events.md") if not str(s.get("visual", "")).strip(): errors.append(f"{sid}: visual 为空") dur = s.get("duration") if not isinstance(dur, (int, float)) or dur <= 0: errors.append(f"{sid}: duration 非法") else: total += dur if dur > nominal and not s.get("pad"): errors.append( f"{sid}: 时长 {dur}s 超过模型标称 {nominal}s,需置 pad=true(tpad clone 补足)" ) if dur > 8: warns.append(f"{sid}: 单镜 {dur}s 偏长,注意长空档") if str(s.get("line", "")).strip() and not str(s.get("voice", "")).strip(): errors.append(f"{sid}: 有台词必须固定音色 voice") if s.get("status") not in STATUSES: errors.append(f"{sid}: status 非法") st = s.get("shotType") if st and st not in SHOT_TYPES: errors.append(f"{sid}: shotType 非法:{st}") cont = s.get("continuity") or {} if cont.get("relation") not in RELATIONS: errors.append(f"{sid}: continuity.relation 应为 continuous/partial/reset") initial = str(cont.get("initialState", "")) if cont.get("relation") in ("continuous", "partial") and not initial.strip(): errors.append(f"{sid}: 连续关联段必须写绝对 initialState") for bad in FORBIDDEN_STATE: if bad in initial: errors.append(f"{sid}: initialState 含「{bad}」,须重写为绝对初始状态") for ref in s.get("refs") or []: if not (ROOT / ref).exists(): warns.append(f"{sid}: 参考资产尚未就位 {ref}") pf = s.get("promptFile") if pf: fp = ep_dir / pf if not str(pf).startswith("/") else Path(pf) if not fp.exists(): warns.append(f"{sid}: 提示词文件缺失 {pf}") elif s.get("promptHash"): actual = shot_hash(fp.read_text(encoding="utf-8")) if actual != s["promptHash"]: errors.append( f"{sid}: promptHash 与 {pf} 不符(应为 {actual}),改词须换哈希另存" ) if prev: same_subject = prev.get("subject") and prev.get("subject") == s.get("subject") if same_subject: types = SHOT_TYPES try: gap = abs(types.index(prev.get("shotType")) - types.index(s.get("shotType"))) except (ValueError, AttributeError): gap = 0 if gap < 2 and prev.get("angle") == s.get("angle"): warns.append( f"{sid}: 与前镜主体/景别/角度近似,跨独立生成段易像错误续帧" ) prev = s target = float(data.get("targetDuration") or 0) tol = float(data.get("tolerance") or 3.0) if target and total > target + tol: errors.append(f"总时长 {total:.2f}s 超出目标 {target + tol:.2f}s") if target and total < target - tol: warns.append(f"总时长 {total:.2f}s 低于目标下限 {target - tol:.2f}s") summary = { "episode": data.get("episode"), "shots": len(shots), "total": round(total, 2), "target": target, "errors": len(errors), "warns": len(warns), } return errors, warns, summary def main(argv): if len(argv) != 2: print("用法: validate_shots.py <30_shots.json>", file=sys.stderr) return 2 errors, warns, summary = validate(argv[1]) print(f"[{summary.get('episode', '?')}] {summary['shots']} 镜 / {summary['total']}s " f"(目标 {summary['target']}s) ERROR={summary['errors']} WARN={summary['warns']}") for item in errors: print(f" ERROR {item}") for item in warns: print(f" WARN {item}") if not errors: print(" 校验通过(WARN 需在生成前逐条确认)") return 1 if errors else 0 if __name__ == "__main__": sys.exit(main(sys.argv))