CtrlK
BlogDocsLog inGet started
Tessl Logo
PluginPublic

gamussa/reels-producer-skill

Write talking-head scripts and produce Instagram reels and YouTube shorts

1.07x
Quality

96%

Does it follow best practices?

Impact

98%

1.07x

Average score across 8 eval scenarios

SecuritybySnyk

Low

Low-risk findings worth noting

Overview
Quality
Evals
Security
Files

import_timeline.pyskills/reel-builder/scripts/

#!/usr/bin/env python3
"""Import an FCPXML timeline back into cut_plan.json (round trip from an NLE).

Reads fcpxml exported by Final Cut Pro or DaVinci Resolve after manual edits
and rebuilds the plan: spine clip order/in-points/durations become segments,
a connected audio clip (lane != 0) becomes the music track. Accepts flat
.fcpxml files and .fcpxmld bundles (FCP 11's default export).

Only cuts survive the round trip: clip order, source in-points, durations,
music offset. NLE-side effects, transitions, retimes, and titles are ignored
with a warning — apply looks via --grade at render time instead.

Usage:
  import_timeline.py plan/reel_edited.fcpxml --out plan/cut_plan.json \
      [--base-plan plan/cut_plan.json]   # inherit music/bpm if timeline lacks them
"""

import argparse
import sys
import xml.etree.ElementTree as ET
from pathlib import Path
from urllib.parse import unquote, urlparse

sys.path.insert(0, str(Path(__file__).resolve().parent))
import plan_schema  # noqa: E402  — owner of cut_plan.json reads and writes

from export_timeline import VOICE_LANE  # noqa: E402  — where export puts the plan's voice

CARRIED = ("vo", "audio")  # plan keys an NLE round trip cannot express
ENDING = ("speech_end", "fade_out")  # carried only while the reel keeps its length
LENGTH_TOLERANCE = 0.05  # s

IGNORED = {
    "transition",
    "title",
    "video",
    "audio",
    "spine",
}  # non asset-clip spine items we warn on


def secs(v):
    """Parse fcpxml rational time: '2800/3000s' | '8s' | '1.5s' -> float seconds."""
    if not v:
        return 0.0
    v = v.rstrip("s")
    if "/" in v:
        n, d = v.split("/")
        return float(n) / float(d)
    return float(v)


def uri_to_path(src):
    if src.startswith("file:"):
        p = unquote(urlparse(src).path)
        return p
    return src


def relativize(path):
    try:
        return str(Path(path).resolve().relative_to(Path.cwd()))
    except ValueError:
        return path


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("fcpxml", help=".fcpxml file or .fcpxmld bundle")
    ap.add_argument("--out", default="plan/cut_plan.json")
    ap.add_argument(
        "--base-plan",
        help="Existing plan to inherit music/music_start/bpm from "
        "when the timeline doesn't carry them",
    )
    args = ap.parse_args()

    src = Path(args.fcpxml)
    if src.is_dir():  # .fcpxmld bundle
        inner = next(iter(src.glob("*.fcpxml")), None)
        if not inner:
            sys.exit(f"No .fcpxml inside bundle {src}")
        src = inner
    root = ET.parse(src).getroot()

    # asset id -> media path (media-rep child, or src attr in older exports)
    asset_path = {}
    for a in root.iter("asset"):
        rep = a.find("media-rep")
        loc = (rep.get("src") if rep is not None else None) or a.get("src")
        if loc:
            asset_path[a.get("id")] = uri_to_path(loc)

    spine = next(root.iter("spine"), None)
    if spine is None:
        sys.exit("No <spine> found — is this a timeline export?")

    base = {}
    if args.base_plan and Path(args.base_plan).exists():
        base = plan_schema.load_or_exit(args.base_plan)
    base_vo = base.get("vo") if isinstance(base.get("vo"), dict) else None
    voice_file = relativize(base_vo["file"]) if base_vo and base_vo.get("file") else None

    segments, music, music_start, warnings = [], None, 0.0, []
    voice = None  # {"file", "start"} from the voice lane, if the edit kept one
    for el in spine:
        tag = el.tag
        if tag == "gap":
            warnings.append(
                f"gap at offset {el.get('offset')} dropped — the "
                "renderer butts segments together; re-time in the plan if intended"
            )
            continue
        if tag not in ("asset-clip", "clip"):
            warnings.append(f"<{tag}> in spine ignored (only cuts survive the round trip)")
            continue
        ref = el.get("ref")
        if ref is None and tag == "clip":  # FCP sometimes nests the ref
            inner = next((c for c in el.iter() if c.get("ref")), None)
            ref = inner.get("ref") if inner is not None else None
        path = asset_path.get(ref)
        if not path:
            warnings.append(f"clip '{el.get('name')}' has no resolvable media — skipped")
            continue
        segments.append(
            {
                "clip": relativize(path),
                "in": round(secs(el.get("start")), 3),
                "duration": round(secs(el.get("duration")), 3),
                "note": el.get("name", ""),
            }
        )
        # connected clips: the voice lane (or the base plan's voice file) is the
        # voice; the first other audio lane is the music
        for child in el:
            if child.tag != "asset-clip" or not child.get("lane"):
                continue
            mp = asset_path.get(child.get("ref"))
            if not mp:
                continue
            is_voice = child.get("lane") == VOICE_LANE or relativize(mp) == voice_file
            if is_voice and voice is None:
                voice = {"file": relativize(mp), "start": round(secs(child.get("start")), 3)}
            elif not is_voice and music is None:
                music = relativize(mp)
                music_start = round(secs(child.get("start")), 3)

    if not segments:
        sys.exit("No clips found in the spine.")

    plan = {
        "music": music or base.get("music", ""),
        "music_start": music_start if music else base.get("music_start", 0.0),
        **({"bpm": base["bpm"]} if "bpm" in base else {}),
        "total_duration": round(sum(s["duration"] for s in segments), 2),
        "segments": segments,
    }
    # What the NLE does not carry comes back from the base plan: the continuous
    # voice and the declared audio edit always; the ending only while the edit
    # kept the reel's length, since speech_end is a time in the reel.
    for key in CARRIED:
        if key in base:
            plan[key] = base[key]
    # the voice as the NLE left it: its file and start come from the timeline,
    # anything the timeline cannot hold (words) from the base plan
    if voice and base_vo and voice["file"] != voice_file:
        # a different recording: the base plan's transcript and ending describe the old one
        plan["vo"] = voice
        warnings.append(
            f"the voice is now {voice['file']} (was {base_vo.get('file')}) — its words, "
            "speech_end and fade_out described the old recording and were dropped; "
            "transcribe the new voice and set the ending again"
        )
        base = {k: v for k, v in base.items() if k not in ENDING}
    elif voice:
        plan["vo"] = {**(base_vo or {}), **voice}
        if base_vo and abs(float(base_vo.get("start", 0.0)) - voice["start"]) > LENGTH_TOLERANCE:
            warnings.append(
                f"the voice now starts at {voice['start']:.2f}s in its file (was "
                f"{float(base_vo.get('start', 0.0)):.2f}s) — speech_end/fade_out dropped; "
                "set them again"
            )
            base = {k: v for k, v in base.items() if k not in ENDING}
    elif base_vo:
        warnings.append(
            "the voice lane is gone from the timeline — kept the base plan's voice; "
            'remove "vo" from the plan if the edit meant to drop it'
        )
    if "speech_end" in base or "fade_out" in base:
        base_total = base.get("total_duration") or sum(
            float(s["duration"]) for s in base.get("segments", [])
        )
        if abs(plan["total_duration"] - float(base_total)) <= LENGTH_TOLERANCE:
            for key in ENDING:
                if key in base:
                    plan[key] = base[key]
        else:
            warnings.append(
                f"the edit changed the reel from {base_total:.2f}s to "
                f"{plan['total_duration']:.2f}s — speech_end/fade_out dropped; set "
                "them again for the new ending"
            )
    out = Path(args.out)
    out.parent.mkdir(parents=True, exist_ok=True)
    if out.exists():
        backup = out.with_suffix(".json.bak")
        backup.write_text(out.read_text())
        print(f"Existing plan backed up to {backup}")
    plan_schema.write(out, plan)

    print(f"Imported {len(segments)} segments, {plan['total_duration']:.1f}s -> {out}")
    if not plan["music"]:
        print(
            '  NOTE: no music track found in the timeline — set "music" in the '
            "plan or pass --base-plan."
        )
    for w in warnings:
        print(f"  WARNING: {w}")
    print("Render a preview + check_cuts.py before showing the human.")


if __name__ == "__main__":
    main()

skills

tile.json