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

publish_log.pyskills/reel-builder/scripts/

#!/usr/bin/env python3
"""The publishing log: what each post tested, what happened, what to try next.

One log per series, outside any single reel's folder (default
../publish-log.json — the folder holding the project folders), so posts can be
compared with their peers. Schema: references/state-schema.md.

What it records per post: platform, date, structure and duration, the hook
variant used, the audience hypothesis (the brief's viewer + promise), dated
observations (views, average watch %, 3-second retention %, saves, shares,
comments, and meaningful responses in words), and the next experiment.

compare groups posts by platform, structure and duration band and reports
within a group only. There are no universal retention targets: a 20 s montage
and a 70 s tutorial on different apps are not the same measurement, so the
script refuses to rank across groups.

Editorial memory (schema 2): `add --project-dir` records the decisions behind
the post — the chosen hook variant and whether its first line was recorded or a
pickup, the series format, structure, grade, captions and caption animation —
so results can be read against them. `import` takes manually supplied or
exported analytics as CSV with an explicit --map from column to metric (no
guessing at platform export headers). `suggest` shows, inside one comparison
group, how each decision's values went, with counts: evidence to choose the
next experiment from, never a rule and never causation. Nothing here publishes.

Dates are passed in, never read from the clock.

Exit codes: 0 ok, 1 bad input (unknown id, unreadable log). JSON on stdout.

Usage:
  publish_log.py add --platform ig_reels --posted 2026-11-08 --hook "Your easy runs aren't easy" \\
      --brief plan/brief.json --duration 46 --project easy-runs [--url URL]
  publish_log.py observe easy-runs/ig_reels --at 2026-11-10 --views 4200 --avg-watch-pct 61 \\
      --retention-3s-pct 78 --saves 40 --shares 12 --comments 9 --notes "3 people asked for the watch app"
  publish_log.py next easy-runs/ig_reels "same promise, hook opens on the watch face"
  publish_log.py compare --platform ig_reels [--structure demonstration]
  publish_log.py add ... --project-dir .            # also record the editorial decisions
  publish_log.py import stats.csv --at 2026-11-15 --id-column post \
      --map "Views=views,Avg % viewed=avg_watch_pct"
  publish_log.py suggest --platform ig_reels --structure demonstration
"""

import argparse
import csv
import json
import statistics
import sys
from pathlib import Path

SCHEMA_VERSION = 2  # v2: posts carry "decisions" (v1 records upgrade with {})
MIN_PER_VALUE = 2  # fewer posts per decision value than this: too few to read
METRICS = ("views", "avg_watch_pct", "retention_3s_pct", "saves", "shares", "comments")
BANDS = (
    (0, 30, "<=30s"),
    (30, 60, "31-60s"),
    (60, 90, "61-90s"),
    (90, 180, "91-180s"),
    (180, float("inf"), ">180s"),
)


def band(duration):
    for lo, hi, name in BANDS:
        if lo < duration <= hi or (lo == 0 and duration <= hi):
            return name
    return BANDS[-1][2]


def load(path):
    p = Path(path)
    if not p.exists():
        return {"schema_version": SCHEMA_VERSION, "posts": []}
    try:
        log = json.loads(p.read_text())
    except json.JSONDecodeError as e:
        raise ValueError(f"{path} is not valid JSON: {e}") from None
    version = log.get("schema_version")
    if version == 1:  # owner upgrade: decisions were not recorded yet
        for post in log.get("posts", []):
            post.setdefault("decisions", {})
        log["schema_version"] = SCHEMA_VERSION
    elif version != SCHEMA_VERSION:
        raise ValueError(
            f"{path} has schema_version {version}; this script reads 1-{SCHEMA_VERSION}"
        )
    return log


def save(path, log):
    p = Path(path)
    tmp = p.with_name(p.name + ".tmp")
    tmp.write_text(json.dumps(log, indent=2) + "\n")
    tmp.rename(p)


def find(log, post_id):
    for post in log["posts"]:
        if post["id"] == post_id:
            return post
    raise ValueError(
        f"no post {post_id!r} — ids: {', '.join(p['id'] for p in log['posts']) or 'none'}"
    )


def decisions_from(project_dir):
    """The editorial decisions recorded in a project's plan and state."""
    d, pdir = {}, Path(project_dir)

    def read(rel):
        try:
            return json.loads((pdir / rel).read_text())
        except (OSError, json.JSONDecodeError):
            return None

    hooks = read("plan/hooks.json") or {}
    chosen = hooks.get("chosen") or {}
    if chosen:
        var = next((v for v in hooks.get("variants", []) if v.get("id") == chosen.get("id")), {})
        d["hook_variant"] = chosen.get("id")
        d["hook_line_kind"] = (var.get("first_line") or {}).get("kind")
        d["hook_on_screen_text"] = bool((var.get("on_screen_text") or "").strip())
    ser = read("plan/series.json") or {}
    if ser.get("format"):
        d["series"] = ser["format"]
    st = read("state.json") or {}
    if st:
        d["grade"] = st.get("grade") or ("clean" if st.get("mode") == "talking-head" else "gritty")
        d["captions"] = st.get("captions")
    phrases = pdir / "work" / "captions" / "phrases.json"
    if phrases.exists() and st.get("captions"):
        d["captions_burned"] = True
    return d


def add(
    log, project, platform, posted, hook, duration, structure, hypothesis, url=None, decisions=None
):
    post_id = f"{project}/{platform}"
    if any(p["id"] == post_id for p in log["posts"]):
        raise ValueError(
            f"{post_id} is already logged — observe it, or log the repost under a new project name"
        )
    post = {
        "id": post_id,
        "project": project,
        "platform": platform,
        "posted": posted,
        "url": url,
        "structure": structure,
        "duration_s": duration,
        "band": band(duration),
        "hook": hook,
        "hypothesis": hypothesis,
        "observations": [],
        "next_experiment": None,
        "decisions": decisions or {},
    }
    log["posts"].append(post)
    return post


def observe(log, post_id, at, metrics, notes=None):
    post = find(log, post_id)
    obs = {"at": at, **{k: v for k, v in metrics.items() if v is not None}}
    if notes:
        obs["notes"] = notes
    post["observations"].append(obs)
    return post


def import_csv(log, path, at, id_column, mapping):
    """Observations from a CSV: one row per post, columns mapped to METRICS."""
    added, unknown = [], []
    with open(path, newline="") as f:
        rows = list(csv.DictReader(f))
    if rows and id_column not in rows[0]:
        raise ValueError(f"no column {id_column!r} in {path} — columns: {', '.join(rows[0])}")
    for col, metric in mapping.items():
        if metric not in METRICS:
            raise ValueError(f"--map target {metric!r} is not one of {', '.join(METRICS)}")
        if rows and col not in rows[0]:
            raise ValueError(f"no column {col!r} in {path}")
    for row in rows:
        key = (row.get(id_column) or "").strip()
        post = next((p for p in log["posts"] if key in (p["id"], p.get("url"))), None)
        if post is None:
            unknown.append(key)
            continue
        metrics = {}
        for col, metric in mapping.items():
            raw = (row.get(col) or "").strip().rstrip("%").replace(",", "")
            if raw:
                try:
                    metrics[metric] = float(raw)
                except ValueError:
                    raise ValueError(
                        f"{path}: {col!r} for {key!r} is not a number: {raw!r}"
                    ) from None
        observe(log, post["id"], at, metrics, "imported from " + Path(path).name)
        added.append(post["id"])
    return added, unknown


def suggest(log, platform, structure=None, metric="avg_watch_pct"):
    """Per comparison group, how each decision's values went on one metric."""
    out = []
    for g in compare(log, platform, structure):
        posts = [
            p
            for p in log["posts"]
            if p["platform"] == platform
            and p["structure"] == g["structure"]
            and p["band"] == g["band"]
        ]
        fields = sorted({k for p in posts for k in (p.get("decisions") or {})})
        table = {}
        for f in fields:
            by_value = {}
            for p in posts:
                latest = p["observations"][-1] if p["observations"] else {}
                if metric in latest:
                    by_value.setdefault(str((p.get("decisions") or {}).get(f)), []).append(
                        latest[metric]
                    )
            if len(by_value) < 2:
                continue  # a decision that never varied tells nothing
            table[f] = {
                v: {
                    "n": len(xs),
                    "median": statistics.median(xs),
                    "enough": len(xs) >= MIN_PER_VALUE,
                }
                for v, xs in sorted(by_value.items())
            }
        out.append(
            {
                "structure": g["structure"],
                "band": g["band"],
                "metric": metric,
                "posts": len(posts),
                "varied_decisions": table,
                "caveat": "observations from different posts, not a controlled test; "
                "differences may come from topic, timing or chance",
            }
        )
    return out


def compare(log, platform, structure=None):
    """Groups of comparable posts with each post's latest observation and medians."""
    groups = {}
    for post in log["posts"]:
        if post["platform"] != platform or (structure and post["structure"] != structure):
            continue
        groups.setdefault((post["structure"], post["band"]), []).append(post)
    out = []
    for (struct, b), posts in sorted(groups.items()):
        rows = []
        for post in posts:
            latest = post["observations"][-1] if post["observations"] else {}
            rows.append(
                {
                    "id": post["id"],
                    "hook": post["hook"],
                    "posted": post["posted"],
                    **{m: latest.get(m) for m in METRICS},
                    "next_experiment": post["next_experiment"],
                }
            )
        medians = {}
        for m in METRICS:
            vals = [r[m] for r in rows if isinstance(r[m], (int, float))]
            medians[m] = statistics.median(vals) if vals else None
        out.append(
            {
                "platform": platform,
                "structure": struct,
                "band": b,
                "posts": rows,
                "medians": medians,
                "comparable": len([r for r in rows if r["views"] is not None]) >= 2,
            }
        )
    return out


def main():
    ap = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
    )
    ap.add_argument("--log", default="../publish-log.json")
    sub = ap.add_subparsers(dest="cmd", required=True)
    a_add = sub.add_parser("add")
    a_add.add_argument("--project", default=Path.cwd().name)
    a_add.add_argument("--platform", required=True)
    a_add.add_argument("--posted", required=True, help="YYYY-MM-DD")
    a_add.add_argument("--hook", required=True, help="the opening line or on-screen hook used")
    a_add.add_argument("--duration", type=float, required=True, help="seconds")
    a_add.add_argument("--brief", help="plan/brief.json for structure + hypothesis")
    a_add.add_argument("--structure")
    a_add.add_argument("--url")
    a_add.add_argument(
        "--project-dir", help="record this project's editorial decisions with the post"
    )
    a_imp = sub.add_parser("import")
    a_imp.add_argument("csv")
    a_imp.add_argument("--at", required=True, help="YYYY-MM-DD the numbers were exported")
    a_imp.add_argument("--id-column", required=True, help="column holding the post id or URL")
    a_imp.add_argument(
        "--map", required=True, help="'Column=metric,...' — metrics: " + ", ".join(METRICS)
    )
    a_sug = sub.add_parser("suggest")
    a_sug.add_argument("--platform", required=True)
    a_sug.add_argument("--structure")
    a_sug.add_argument("--metric", choices=METRICS, default="avg_watch_pct")
    a_obs = sub.add_parser("observe")
    a_obs.add_argument("id")
    a_obs.add_argument("--at", required=True, help="YYYY-MM-DD the numbers were read")
    for m in METRICS:
        a_obs.add_argument(f"--{m.replace('_', '-')}", type=float)
    a_obs.add_argument("--notes", help="meaningful responses, in words")
    a_next = sub.add_parser("next")
    a_next.add_argument("id")
    a_next.add_argument("experiment")
    a_cmp = sub.add_parser("compare")
    a_cmp.add_argument("--platform", required=True)
    a_cmp.add_argument("--structure")
    a = ap.parse_args()

    try:
        log = load(a.log)
        if a.cmd == "add":
            structure, hypothesis = a.structure, None
            if a.brief:
                b = json.loads(Path(a.brief).read_text())
                structure = structure or b.get("structure")
                hypothesis = f"{b.get('viewer')}: {b.get('promise')}"
            if not structure:
                raise ValueError(
                    "pass --structure or --brief so the post can be compared with its peers"
                )
            result = add(
                log,
                a.project,
                a.platform,
                a.posted,
                a.hook,
                a.duration,
                structure,
                hypothesis,
                a.url,
                decisions_from(a.project_dir) if a.project_dir else None,
            )
        elif a.cmd == "import":
            mapping = {}
            for pair in a.map.split(","):
                col, sep, metric = pair.partition("=")
                if not sep:
                    raise ValueError(f"--map entry {pair!r} must read Column=metric")
                mapping[col.strip()] = metric.strip()
            added, unknown = import_csv(log, a.csv, a.at, a.id_column, mapping)
            result = {"observed": added, "unmatched_rows": unknown}
        elif a.cmd == "suggest":
            print(json.dumps({"groups": suggest(log, a.platform, a.structure, a.metric)}, indent=2))
            return
        elif a.cmd == "observe":
            metrics = {m: getattr(a, m) for m in METRICS}
            result = observe(log, a.id, a.at, metrics, a.notes)
        elif a.cmd == "next":
            result = find(log, a.id)
            result["next_experiment"] = a.experiment
        else:
            print(json.dumps({"groups": compare(log, a.platform, a.structure)}, indent=2))
            return
    except (ValueError, OSError, json.JSONDecodeError) as e:
        print(json.dumps({"ok": False, "error": str(e)}))
        sys.exit(1)
    save(a.log, log)
    print(json.dumps({"ok": True, "post": result}, indent=2))


if __name__ == "__main__":
    main()

skills

tile.json