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

resolve_title.pyskills/reel-builder/scripts/

#!/usr/bin/env python3
"""Put a Fusion title (.comp from fusion_title.py) on a Resolve timeline, above the footage.

A Fusion composition needs a clip to live on. This adds a short "host" clip on
the requested video track at the timeline start — by default the first clip of
V1, trimmed to the title's duration; its picture is never shown because the
comp has no MediaIn and outputs only the graphic with alpha — then imports the
.comp onto it, replacing any comp already there. Re-run after regenerating the
.comp; wording and timing changes are otherwise editable in the Inspector.

Track order matters: captions (the PNG card sequence from gen_captions.py) must
sit ABOVE the title track or the title's dark band dims them. With captions on
V2, first move them to V3 (`--captions-to 3`), then apply the title on V2.

Why not Timeline.InsertFusionCompositionIntoTimeline(): it inserts at the
playhead with a ripple on EVERY track, shifting captions and audio by the
clip's length. Appending a host clip on an empty track is an overwrite.

Two ways to reach Resolve, same code either way:

  From a shell: Resolve STUDIO must be running with the project open
  (external scripting is gated to Studio); `resolve_bridge.connect()` finds
  the scripting module and connects.

  From a Resolve MCP session (`run_script` / `run_script_unsafe`): the MCP
  pre-injects `resolve` and `project`; pass them in and nothing is imported:

      import runpy, sys
      sys.path.insert(0, "<skill>/scripts")
      mod = runpy.run_path("<skill>/scripts/resolve_title.py", run_name="resolve_title")
      mod["apply"](mod["parse"](["apply", "--timeline", "r04_master",
                                  "--comp", "/abs/path/title_r04.comp", "--track", "2"]),
                   resolve=resolve)

Timeline frames: endFrame is exclusive; recordFrame includes the timeline's
start frame (01:00:00:00 = 108000 at 30 fps).

Usage:
  resolve_title.py apply --timeline r04_master --comp work/motion/title_r04.comp --track 2
  resolve_title.py apply --timeline r04_master --comp work/motion/title_r04.comp --track 2 --captions-to 3
  resolve_title.py apply ... --duration 4 --at 0
  resolve_title.py remove --timeline r04_master --track 2
"""

import argparse
import sys
import time
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from resolve_bridge import project_fps  # noqa: E402


def get_resolve(resolve=None):
    """The injected Resolve object (MCP sessions), else a fresh scripting connection."""
    if resolve is not None:
        return resolve
    from resolve_bridge import connect

    return connect()


def find_timeline(project, name):
    if not name:
        tl = project.GetCurrentTimeline()
        if tl is None:
            sys.exit("No timeline open in Resolve.")
        return tl
    for i in range(1, project.GetTimelineCount() + 1):
        cand = project.GetTimelineByIndex(i)
        if cand and cand.GetName() == name:
            return cand
    sys.exit(f"No timeline named {name!r} in {project.GetName()!r}.")


def move_track(tl, pool, src, dst, start):
    """Re-append every item of video track src on track dst (same positions), then delete the originals."""
    items = tl.GetItemListInTrack("video", src) or []
    if not items:
        return 0
    while tl.GetTrackCount("video") < dst:
        tl.AddTrack("video")
    if tl.GetItemListInTrack("video", dst):
        sys.exit(f"Video track {dst} is not empty; pick another --captions-to track.")
    clips = []
    for it in items:
        mpi = it.GetMediaPoolItem()
        if mpi is None:
            sys.exit(
                f"{it.GetName()!r} on V{src} has no media pool item (generator/title?) — move it by hand."
            )
        clips.append(
            {
                "mediaPoolItem": mpi,
                "startFrame": it.GetLeftOffset(),
                "endFrame": it.GetLeftOffset() + it.GetDuration(),
                "recordFrame": it.GetStart(),
                "trackIndex": dst,
                "mediaType": 1,
            }
        )
    tl.DeleteClips(items, False)
    time.sleep(0.2)
    added = pool.AppendToTimeline(clips) or []
    if len(added) != len(clips):
        sys.exit(
            f"Moving V{src} to V{dst}: appended {len(added)} of {len(clips)} items. Check the timeline."
        )
    return len(added)


def apply(a, resolve=None):
    resolve = get_resolve(resolve)
    project = resolve.GetProjectManager().GetCurrentProject()
    if project is None:
        sys.exit("No project open in Resolve.")
    pool = project.GetMediaPool()
    tl = find_timeline(project, a.timeline)
    project.SetCurrentTimeline(tl)
    fps = project_fps(project)
    start = tl.GetStartFrame()
    frames = round(a.duration * fps)
    at = start + round(a.at * fps)
    comp = Path(a.comp).resolve()
    if not comp.is_file():
        sys.exit(f"Comp not found: {comp}")

    if a.captions_to:
        n = move_track(tl, pool, a.track, a.captions_to, start)
        print(f"moved {n} item(s) from V{a.track} to V{a.captions_to}", file=sys.stderr)

    while tl.GetTrackCount("video") < a.track:
        tl.AddTrack("video")
    existing = [
        it
        for it in (tl.GetItemListInTrack("video", a.track) or [])
        if it.GetStart() < at + frames and it.GetEnd() > at
    ]
    if existing and not a.replace:
        sys.exit(
            f"V{a.track} already has {len(existing)} item(s) in that range; pass --replace to swap them."
        )
    if existing:
        tl.DeleteClips(existing, False)
        time.sleep(0.2)

    v1 = tl.GetItemListInTrack("video", 1) or []
    host_media = next(
        (it.GetMediaPoolItem() for it in v1 if it.GetMediaPoolItem() is not None), None
    )
    if host_media is None:
        sys.exit("V1 has no clip with a media pool item to host the comp on.")
    added = (
        pool.AppendToTimeline(
            [
                {
                    "mediaPoolItem": host_media,
                    "startFrame": 0,
                    "endFrame": frames,
                    "recordFrame": at,
                    "trackIndex": a.track,
                    "mediaType": 1,
                }
            ]
        )
        or []
    )
    if not added:
        sys.exit("Resolve refused to append the host clip.")
    host = added[0]
    for name in host.GetFusionCompNameList() or []:
        host.DeleteFusionCompByName(name)
    if not host.ImportFusionComp(str(comp)):
        sys.exit(f"ImportFusionComp failed for {comp}")
    n_tools = len(host.GetFusionCompByIndex(1).GetToolList(False) or {})
    print(
        f"{tl.GetName()}: title on V{a.track} at {a.at:.2f}s for {a.duration:.2f}s "
        f"({frames} frames, {n_tools} Fusion tools) from {comp.name}"
    )


def remove(a, resolve=None):
    resolve = get_resolve(resolve)
    project = resolve.GetProjectManager().GetCurrentProject()
    tl = find_timeline(project, a.timeline)
    items = tl.GetItemListInTrack("video", a.track) or []
    hosts = [it for it in items if it.GetFusionCompCount() > 0]
    if hosts:
        tl.DeleteClips(hosts, False)
    print(f"{tl.GetName()}: removed {len(hosts)} title clip(s) from V{a.track}")


def parse(argv=None):
    ap = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
    )
    sub = ap.add_subparsers(dest="cmd", required=True)
    p = sub.add_parser("apply")
    p.add_argument("--timeline", help="timeline name (default: the open one)")
    p.add_argument("--comp", required=True)
    p.add_argument("--track", type=int, default=2, help="video track for the title (default 2)")
    p.add_argument(
        "--captions-to", type=int, help="first move whatever is on --track to this track"
    )
    p.add_argument("--duration", type=float, default=4.0)
    p.add_argument("--at", type=float, default=0.0, help="seconds from timeline start")
    p.add_argument(
        "--replace", action="store_true", help="replace clips already in that range on --track"
    )
    p.set_defaults(func=apply)
    r = sub.add_parser("remove")
    r.add_argument("--timeline")
    r.add_argument("--track", type=int, default=2)
    r.set_defaults(func=remove)
    return ap.parse_args(argv)


def main(argv=None, resolve=None):
    a = parse(argv)
    a.func(a, resolve=resolve)


if __name__ == "__main__":
    main()

skills

tile.json