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

library.pyskills/reel-builder/scripts/

#!/usr/bin/env python3
"""A searchable footage library across reel projects — reuse what was already
looked at, instead of re-watching the archive.

Indexes analysis that already exists; it never copies or re-analyses media:

  moments   every plan/selects.json entry: clip + range + what happens,
            purpose, value, concerns, optional "who" / "shot" when the editor
            recorded them (references/selects.md)
  speech    every transcript beside a project (*.words.json under work/ and
            raw/, and shortlist sources), one record per sentence with timing
  clips     every probed clip (work/clips.json) with its contact sheet

Each record keeps the SOURCE path (resolved through raw/ symlinks), the time
range, the project it came from, and the file's fingerprint, so a search hit
says whether the footage is still where it was.

search ranks records by how many query words they contain (light stemming,
stop words dropped), weighting a moment's "what" above its other fields. It is
retrieval, not judgment: read the hits, open their contact sheets, and choose.

use links a hit's source file into the current project (raw/library/, a
symlink — never a copy) and appends it to plan/selects.json as a select with
the hit's range; re-probe afterwards so the pipeline sees the new clip.

Index: --index (default ../footage-library.json, beside the project folders).
Schema: references/state-schema.md.

Exit codes: 0 ok; 1 bad input or no index. JSON on stdout.

Usage:
  library.py index --root ~/reels                    # every project folder under it
  library.py search "exhausted finish line reaction" [--kind moment] [--limit 10]
  library.py use m:race-recap:3 --purpose reaction --what "collapses past the line"
"""

import argparse
import json
import re
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from provenance import file_fp, fp_matches  # noqa: E402

SCHEMA_VERSION = 1
STOP = {
    "a",
    "an",
    "the",
    "and",
    "or",
    "of",
    "to",
    "in",
    "on",
    "at",
    "for",
    "with",
    "is",
    "it",
    "this",
    "that",
    "find",
    "me",
    "my",
    "some",
    "shot",
    "clip",
    "footage",
}
FIELD_WEIGHT = {
    "what": 3.0,
    "who": 2.0,
    "shot": 2.0,
    "purpose": 1.0,
    "concerns": 0.5,
    "text": 1.0,
    "project": 0.5,
}


def stem(word):
    w = word.lower()
    for suf in ("ing", "ed", "es", "s", "ly"):
        if len(w) > len(suf) + 2 and w.endswith(suf):
            return w[: -len(suf)]
    return w


def tokens(text):
    return {stem(t) for t in re.findall(r"[a-zA-Z0-9']+", text or "") if t.lower() not in STOP}


def resolve(project, path):
    """A clip path as written in a project, resolved through its raw/ symlink."""
    p = Path(path)
    p = p if p.is_absolute() else Path(project) / p
    return p.resolve()


def sentences(words):
    out, cur = [], []
    for w in words:
        cur.append(w)
        if re.search(r"[.!?]$", w["text"].strip()):
            out.append(cur)
            cur = []
    if cur:
        out.append(cur)
    return [(s[0]["start"], s[-1]["end"], " ".join(x["text"] for x in s)) for s in out]


def load_words_file(path):
    data = json.loads(Path(path).read_text())
    if isinstance(data, dict):
        data = data.get("words") or [
            w for s in data.get("segments", []) for w in s.get("words", [])
        ]
    return [
        {
            "text": (w.get("word") or w.get("text") or "").strip(),
            "start": float(w["start"]),
            "end": float(w["end"]),
        }
        for w in data
        if (w.get("word") or w.get("text"))
    ]


def media_for_words(words_path):
    """The recording a transcript belongs to: same stem, a video/audio extension."""
    base = Path(str(words_path).removesuffix(".words.json").removesuffix(".json"))
    for ext in (".mp4", ".mov", ".m4v", ".wav", ".m4a", ".mp3"):
        for cand in (base.with_suffix(ext), base.parent.parent / "raw" / (base.name + ext)):
            if cand.is_file():
                return cand
    return None


def index_project(proj):
    proj = Path(proj)
    name, recs = proj.name, []
    clips = {}
    cj = proj / "work" / "clips.json"
    if cj.is_file():
        for c in json.loads(cj.read_text()).get("clips", []):
            if "error" in c:
                continue
            src = resolve(proj, c["file"])
            sheet = proj / "work" / "sheets" / f"{Path(c['file']).stem}_sheet.png"
            clips[Path(c["file"]).stem] = src
            recs.append(
                {
                    "id": f"c:{name}:{Path(c['file']).stem}",
                    "kind": "clip",
                    "project": name,
                    "source": str(src),
                    "fp": file_fp(src),
                    "start": 0.0,
                    "end": float(c.get("duration") or 0),
                    "text": Path(c["file"]).stem,
                    "sheet": str(sheet) if sheet.is_file() else None,
                }
            )
    sj = proj / "plan" / "selects.json"
    if sj.is_file():
        for n, s in enumerate(json.loads(sj.read_text()).get("selects", []), 1):
            key = str(s.get("clip", ""))
            src = clips.get(Path(key).stem) or resolve(proj, key)
            sheet = proj / "work" / "sheets" / f"{Path(key).stem}_sheet.png"
            recs.append(
                {
                    "id": f"m:{name}:{n}",
                    "kind": "moment",
                    "project": name,
                    "source": str(src),
                    "fp": file_fp(src),
                    "start": float(s.get("in", 0)),
                    "end": float(s.get("out", 0)),
                    **{
                        k: s.get(k) for k in ("what", "purpose", "value", "concerns", "who", "shot")
                    },
                    "sheet": str(sheet) if sheet.is_file() else None,
                }
            )
    for wp in sorted(
        list(proj.glob("work/*.words.json"))
        + list(proj.glob("raw/*.words.json"))
        + list(proj.glob("work/vo.json"))
    ):
        try:
            words = load_words_file(wp)
        except (OSError, json.JSONDecodeError, KeyError, ValueError):
            continue
        media = media_for_words(wp)
        for k, (a, b, text) in enumerate(sentences(words), 1):
            recs.append(
                {
                    "id": f"s:{name}:{wp.stem}:{k}",
                    "kind": "speech",
                    "project": name,
                    "source": str(media.resolve()) if media else None,
                    "fp": file_fp(media) if media else None,
                    "start": a,
                    "end": b,
                    "text": text,
                    "transcript": str(wp),
                }
            )
    return recs


def build_index(roots):
    projects = sorted({p.parent for r in roots for p in Path(r).expanduser().glob("**/state.json")})
    recs = [r for p in projects for r in index_project(p)]
    return {
        "schema_version": SCHEMA_VERSION,
        "roots": [str(Path(r).expanduser()) for r in roots],
        "projects": [str(p) for p in projects],
        "records": recs,
    }


def score(rec, query):
    q = tokens(query)
    if not q:
        return 0.0
    total = 0.0
    for field, w in FIELD_WEIGHT.items():
        total += w * len(q & tokens(str(rec.get(field) or "")))
    if rec["kind"] == "moment" and isinstance(rec.get("value"), int):
        total *= 1 + 0.05 * rec["value"]
    return round(total, 3)


def search(index, query, kind=None, limit=10):
    hits = []
    for rec in index.get("records", []):
        if kind and rec["kind"] != kind:
            continue
        s = score(rec, query)
        if s > 0:
            hits.append({**rec, "score": s, "available": fp_matches(rec.get("fp"))})
    hits.sort(key=lambda h: (-h["score"], h["id"]))
    return hits[:limit]


def use(index, hit_id, purpose, what, value=3, project: "str | Path" = "."):
    rec = next((r for r in index.get("records", []) if r["id"] == hit_id), None)
    if rec is None:
        raise ValueError(f"no record {hit_id!r} in the index — search again")
    if not rec.get("source") or not fp_matches(rec.get("fp")):
        raise ValueError(
            f"{hit_id}: its source changed or is gone ({rec.get('source')}) — "
            "re-index, or relink the footage"
        )
    proj = Path(project)
    lib = proj / "raw" / "library"
    lib.mkdir(parents=True, exist_ok=True)
    src = Path(rec["source"])
    link = lib / f"{rec['project']}__{src.name}"
    if not link.exists():
        link.symlink_to(src)
    sel_path = proj / "plan" / "selects.json"
    doc = (
        json.loads(sel_path.read_text())
        if sel_path.exists()
        else {"schema_version": 1, "selects": []}
    )
    doc["selects"].append(
        {
            "clip": link.stem,
            "in": rec["start"],
            "out": rec["end"],
            "what": what or rec.get("what") or rec.get("text"),
            "purpose": purpose,
            "value": value,
            "from_library": hit_id,
        }
    )
    sel_path.parent.mkdir(parents=True, exist_ok=True)
    sel_path.write_text(json.dumps(doc, indent=2) + "\n")
    return link


def main():
    ap = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
    )
    ap.add_argument("--index", default="../footage-library.json")
    sub = ap.add_subparsers(dest="cmd", required=True)
    i = sub.add_parser("index")
    i.add_argument("--root", action="append", required=True, help="folder holding project folders")
    s = sub.add_parser("search")
    s.add_argument("query")
    s.add_argument("--kind", choices=("moment", "speech", "clip"))
    s.add_argument("--limit", type=int, default=10)
    u = sub.add_parser("use")
    u.add_argument("id")
    u.add_argument("--purpose", required=True)
    u.add_argument("--what", help="what happens, for this reel (default: the indexed description)")
    u.add_argument("--value", type=int, default=3)
    a = ap.parse_args()
    try:
        if a.cmd == "index":
            idx = build_index(a.root)
            Path(a.index).write_text(json.dumps(idx, indent=1) + "\n")
            kinds = {}
            for r in idx["records"]:
                kinds[r["kind"]] = kinds.get(r["kind"], 0) + 1
            print(
                json.dumps(
                    {"ok": True, "index": a.index, "projects": len(idx["projects"]), **kinds}
                )
            )
            return
        idx = json.loads(Path(a.index).read_text())
        if idx.get("schema_version") != SCHEMA_VERSION:
            raise ValueError(f"{a.index}: schema_version must be {SCHEMA_VERSION} — re-index")
        if a.cmd == "search":
            print(json.dumps({"ok": True, "hits": search(idx, a.query, a.kind, a.limit)}, indent=1))
            return
        link = use(idx, a.id, a.purpose, a.what, a.value)
        print(
            json.dumps(
                {
                    "ok": True,
                    "linked": str(link),
                    "next": "re-probe (pipeline.py next) so the clip is normalized",
                }
            )
        )
    except (ValueError, OSError, json.JSONDecodeError) as e:
        print(json.dumps({"ok": False, "error": str(e)}))
        sys.exit(1)


if __name__ == "__main__":
    main()

skills

tile.json