build_plan.py --clips [DIR] (default clips/) now exports one validated single-shot plan JSON per scene (clip_01.json, ...) alongside the merged plan. Each clip renders through plan_json_input as its own video at FULL duration (no chain overlap trim), then the clips are stitched in order; the mid-motion open/close craft rules make the cuts read as one take. plan.json stays as the optional single continuous-take render. SKILL.md Step 3/4 rewritten (merge exports clips + plan; deliver = render-per-clip then stitch), README intro/example/wiring/validating updated to multi-clip-first with real clip output shown. Verified from a simulated project root: export green, every clip re-checks PLAN OK.
166 lines
6.9 KiB
Python
Executable File
166 lines
6.9 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Merge MiniMax H3 scene-agent fragments into the final plan JSON for plan_json_input.
|
|
|
|
Stage 3 of the agent workflow (outline -> one scene per turn -> assembly).
|
|
Deterministic and byte-exact: fragment prompt strings are copied, never rewritten.
|
|
Every fragment and the merged plan are validated with the same rules the node uses
|
|
(replicated in verify_plan_rules.py) before anything is written.
|
|
|
|
Usage:
|
|
python build_plan.py outline.json scene_01.json scene_02.json scene_03.json -o plan.json --clips
|
|
python build_plan.py scene_01.json scene_02.json -o plan.json [--duration 10] [--steps 20]
|
|
python build_plan.py --check plan.json # validate an existing plan file
|
|
|
|
--clips [DIR] (default dir: clips) additionally writes one single-shot plan JSON per
|
|
scene (clip_01.json, clip_02.json, ...) for MULTI-CLIP rendering: render each clip
|
|
through plan_json_input as its own video, then stitch the clips in an editor. Each
|
|
clip plays at its full duration (no chain overlap trimming). The merged plan (-o /
|
|
stdout) remains the single continuous-take render.
|
|
|
|
The outline file (from the scene agent's PROMPT A) is optional; it is auto-detected by
|
|
its "scenes" key. When present, fragment ids, durations, and dialogue are checked
|
|
against it in order. Fenced markdown JSON (```json ... ```) also parses.
|
|
"""
|
|
import argparse
|
|
import json
|
|
import os
|
|
import sys
|
|
|
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
import verify_plan_rules as vpr # noqa: E402
|
|
|
|
|
|
def load_json_file(path):
|
|
try:
|
|
with open(path, encoding="utf-8-sig") as fh:
|
|
return vpr.load_json_text(fh.read(), path)
|
|
except (OSError, ValueError) as exc:
|
|
raise SystemExit(f"{path}: cannot read JSON ({exc})")
|
|
|
|
|
|
def looks_like_outline(obj):
|
|
return (isinstance(obj, dict)
|
|
and isinstance(obj.get("scenes"), list)
|
|
and bool(obj["scenes"])
|
|
and all(isinstance(row, dict) and "id" in row for row in obj["scenes"]))
|
|
|
|
|
|
def extract_shots(obj, label):
|
|
"""Return the list of shot objects held in a fragment file."""
|
|
if isinstance(obj, list):
|
|
return obj
|
|
if isinstance(obj, dict):
|
|
if isinstance(obj.get("shots"), list):
|
|
return obj["shots"]
|
|
if "prompt" in obj or "_handoff" in obj:
|
|
return [obj]
|
|
raise SystemExit(f"{label}: not a fragment file (need a shot object, a list of "
|
|
f"shots, or an object with a 'shots' array)")
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser(
|
|
description="Merge H3 scene-agent fragments into a validated plan JSON.")
|
|
ap.add_argument("files", nargs="*",
|
|
help="outline JSON (optional, auto-detected) then fragment "
|
|
"files in story order")
|
|
ap.add_argument("-o", "--out", default=None,
|
|
help="write the merged plan here (default: print to stdout)")
|
|
ap.add_argument("--duration", type=float, default=10.0,
|
|
help="defaults.duration_seconds when no outline is given")
|
|
ap.add_argument("--steps", type=int, default=20,
|
|
help="defaults.steps when no outline is given")
|
|
ap.add_argument("--check", metavar="PLAN", default=None,
|
|
help="validate an existing plan JSON and exit")
|
|
ap.add_argument("--clips", nargs="?", const="clips", default=None, metavar="DIR",
|
|
help="also write one single-shot plan JSON per scene here "
|
|
"(multi-clip rendering; default dir: clips)")
|
|
args = ap.parse_args()
|
|
|
|
if args.check:
|
|
plan = load_json_file(args.check)
|
|
print(f"Checking plan: {args.check}")
|
|
vpr.validate_plan(plan)
|
|
vpr.check_h3_sections(plan)
|
|
print("PLAN OK")
|
|
return
|
|
|
|
if not args.files:
|
|
ap.error("give fragment files (optionally an outline first), or --check PLAN")
|
|
|
|
outline = None
|
|
shots_in = []
|
|
for path in args.files:
|
|
obj = load_json_file(path)
|
|
if outline is None and looks_like_outline(obj):
|
|
outline = obj
|
|
print(f"outline: {path} ({len(obj['scenes'])} scenes)")
|
|
continue
|
|
shots_in.extend((path, shot) for shot in extract_shots(obj, path))
|
|
|
|
n = len(shots_in)
|
|
if n == 0:
|
|
raise SystemExit("no fragments found")
|
|
if n > vpr.MAX_SHOTS:
|
|
raise SystemExit(f"{n} fragments exceed MAX_SHOTS={vpr.MAX_SHOTS}")
|
|
if outline and len(outline["scenes"]) != n:
|
|
raise SystemExit(f"outline has {len(outline['scenes'])} scenes but {n} "
|
|
f"fragments were given")
|
|
|
|
defaults = {"duration_seconds": args.duration, "steps": args.steps}
|
|
if outline and isinstance(outline.get("defaults"), dict):
|
|
d = outline["defaults"]
|
|
defaults = {"duration_seconds": d.get("duration_seconds", args.duration),
|
|
"steps": int(d.get("steps", args.steps))}
|
|
|
|
prev = None
|
|
final_shots = []
|
|
for i, (path, shot) in enumerate(shots_in, 1):
|
|
expect = None
|
|
if outline:
|
|
row = outline["scenes"][i - 1]
|
|
expect = {"id": row.get("id"),
|
|
"duration_seconds": row.get("duration_seconds"),
|
|
"dialogue": row.get("dialogue") or []}
|
|
print(f"\nfragment {i}/{n} from {path}:")
|
|
prev = vpr.validate_fragment(shot, index=i, total=n,
|
|
prev_handoff=prev, expect=expect)
|
|
merged = {k: shot[k] for k in ("id", "prompt", "duration_seconds") if k in shot}
|
|
for extra in ("steps", "seed"):
|
|
if extra in shot:
|
|
merged[extra] = shot[extra]
|
|
final_shots.append(merged) # _handoff stripped by construction
|
|
|
|
plan = {"prompt_prefix": [""], "defaults": defaults, "shots": final_shots}
|
|
|
|
print("\nMerged plan:")
|
|
vpr.validate_plan(plan)
|
|
vpr.check_h3_sections(plan)
|
|
|
|
out_text = json.dumps(plan, indent=2, ensure_ascii=False) + "\n"
|
|
if args.out:
|
|
with open(args.out, "w", encoding="utf-8") as fh:
|
|
fh.write(out_text)
|
|
print(f"\nwrote {args.out} - paste its full contents into plan_json_input")
|
|
else:
|
|
print("\n" + out_text)
|
|
|
|
if args.clips:
|
|
os.makedirs(args.clips, exist_ok=True)
|
|
for i, shot in enumerate(final_shots, 1):
|
|
clip = {"prompt_prefix": [""], "defaults": dict(defaults), "shots": [shot]}
|
|
print(f"\nclip {i}/{n} -> {args.clips}/clip_{i:02d}.json "
|
|
f"(id={shot.get('id')})")
|
|
vpr.validate_plan(clip)
|
|
vpr.check_h3_sections(clip)
|
|
with open(os.path.join(args.clips, f"clip_{i:02d}.json"), "w",
|
|
encoding="utf-8") as fh:
|
|
fh.write(json.dumps(clip, indent=2, ensure_ascii=False) + "\n")
|
|
print(f"\nwrote {n} single-scene clip plans -> {args.clips}/ - render each "
|
|
f"clip_NN.json through plan_json_input as its own video, then stitch "
|
|
f"the clips in order (each clip plays at its full duration)")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|