Skip to content
Python

GTA 6 clipping desk for Claude Code: trends, streams, moments, 9:16 cutter, rule check, playbook

Bodila511f66066bf7de
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
new file mode 100644
index 0000000..57373f9
--- /dev/null
+++ b/.claude-plugin/marketplace.json
@@ -0,0 +1,18 @@
+{
+ "name": "gtavi-claudecode",
+ "description": "A faceless GTA 6 clipping desk: find campaigns, trends and moments, cut captioned vertical clips, check the rules, learn from real numbers.",
+ "owner": {
+ "name": "Bodila51",
+ "url": "https://github.com/Bodila51"
+ },
+ "plugins": [
+ {
+ "name": "gtavi-claudecode",
+ "source": "./",
+ "description": "Run a faceless GTA 6 clipping page with the fewest human actions. You approve every post.",
+ "version": "0.1.0",
+ "category": "productivity",
+ "tags": ["gta6", "clipping", "video", "shorts", "whop"]
+ }
+ ]
+}
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
new file mode 100644
index 0000000..a052a14
--- /dev/null
+++ b/.claude-plugin/plugin.json
@@ -0,0 +1,13 @@
+{
+ "name": "gtavi-claudecode",
+ "displayName": "GTA 6 Clip Desk",
+ "version": "0.1.0",
+ "description": "Run a faceless GTA 6 clipping page with the fewest human actions. You approve every post.",
+ "author": {
+ "name": "Bodila51",
+ "url": "https://github.com/Bodila51"
+ },
+ "repository": "https://github.com/Bodila51/gtavi-claudecode",
+ "keywords": ["gta6", "clipping", "video", "shorts", "whop"],
+ "skills": ["./skills/"]
+}
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..b8b56dc
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,8 @@
+.venv/
+__pycache__/
+jobs/
+test/
+*.mp4
+*.wav
+*.ts
+!docs/*.mp4
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..3cf144a
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,9 @@
+MIT License
+
+Copyright (c) 2026 Bodila51
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..405f394
--- /dev/null
+++ b/README.md
@@ -0,0 +1,82 @@
+# gtavi-claudecode
+
+**Turn GTA 6 streams into paid clips while everyone else is still scrubbing VODs.**
+
+```
+/plugin marketplace add Bodila51/gtavi-claudecode
+/plugin install gtavi-claudecode@gtavi-claudecode
+```
+
+Two lines in Claude Code. In 10 minutes you have: the tools installed, your page folder, today's trending GTA 6 videos, the best moments picked and your first vertical clips ready to post.
+
+<p>
+<img src="docs/demo-frame-1.jpg" width="240" alt="hook box in the first second">
+<img src="docs/demo-frame-2.jpg" width="240" alt="word-by-word captions and credit line">
+</p>
+
+Made by this repo in one run: trend-radar picked the video, moment-finder picked the moment, clip-cutter added the hook, captions and credit. Source: [Hazard, "GTA 6 Just Got a MASSIVE Last Minute Info Dump..."](https://www.youtube.com/watch?v=jwwDSn-HW0o). All rights to the footage belong to its creator.
+
+## First run: paste this into Claude Code
+
+```
+Use gtavi-claudecode. Set up my GTA 6 clip page, ask me your 4 questions in one message,
+then do everything after one "yes": find live clipping campaigns, show today's trending
+GTA 6 videos and live streams, find the best moments in the top one, cut my first 3 clips
+with hooks and credits, check them against the campaign rules, and tell me what to post where.
+```
+
+## Two ways to make money
+
+**1. Paid clipping campaigns (fastest).** Streamers and brands pay clippers per 1,000 views on approved clips. On Whop Content Rewards around $1 per 1K views is common; every campaign shows its own rate, budget left and rules. `campaign-finder` reads them live and never guesses a number. You read the rules, clip only that creator, post, submit the link.
+
+**2. Your own faceless GTA 6 page (bigger, slower).** The built-in playbook runs it: daily content mix, credit rules, caption templates, the launch-day "be first" plan and a learning loop. Platforms don't pay for reposted clips, so the page grows on speed, useful tips and credited clips, then earns through campaigns and partnerships.
+
+No income is promised. Your result depends on speed, picks and hooks, and the scoreboard shows what works.
+
+## The rules that make clips win
+
+- Hook in the first second. Say why to keep watching ("the hidden car nobody found").
+- 7 to 30 seconds. Cut dead air at the start, end on the payoff.
+- Big captions in the safe area. Most people watch muted.
+- Credit line on every clip. Make it yours: hook, tip, commentary. Never a plain re-upload.
+- Launch day (Nov 19): players in New Zealand and Australia unlock first. Clip their streams, post to X first, then Reels, TikTok and Shorts, every 1 to 2 hours for 48 hours.
+- Every repeated question in your comments becomes a HOW TO post.
+- One test per day. No verdict before 24 hours, prefer the 72 h numbers.
+
+## What's inside
+
+| Skill | What you get |
+|---|---|
+| `setup` | Installs ffmpeg, yt-dlp and faster-whisper, asks 4 questions, builds your page folder |
+| `campaign-finder` | Live campaigns: rate per 1K views, budget left, rules, link |
+| `trend-radar` | GTA 6 videos from the last 24 h ranked by views per hour |
+| `stream-finder` | Who is streaming GTA 6 right now, ranked by viewers |
+| `moment-finder` | Best 15 to 40 s moments, scored by loudness spikes, hype words, YouTube "most replayed" and chat spikes |
+| `live-mode` | Records a live stream and cuts a clip every time chat explodes |
+| `clip-cutter` | 1080x1920 clip: word-by-word captions, hook box, credit line, -14 LUFS. Fill, blurred background or facecam on top |
+| `hook-writer` | 3 hook options per clip |
+| `rule-check` | Length, format, credit, hashtags and banned content checked before you post |
+| `playbook` | Your full daily routine and launch-day plan |
+| `learning-loop` | Scoreboard, one test per day, payouts from real numbers only |
+
+Nothing is uploaded automatically. You approve every post.
+
+## Hard rules
+
+No leaks, no "play early" or "free download" posts, no piracy, no GTA Online money or AFK bots, no fake news, never pretends to be Rockstar. Every fact needs an official source.
+
+## Run the scripts yourself
+
+```
+pip install -r requirements.txt
+python scripts/trends.py --query "gta 6" --hours 24
+python scripts/streams.py --query "gta 6"
+python scripts/moments.py "https://www.youtube.com/watch?v=..." --top 8
+python scripts/cut.py jobs/<id> --pick 2 --layout facecam --hook "Nobody noticed this" --credit "@creator"
+python scripts/check.py jobs/<id>/edits/clip_2.mp4 --campaign campaigns.md
+python scripts/live.py "https://www.youtube.com/watch?v=<live>" --minutes 60
+```
+
+Windows, macOS or Linux, Python 3.10+. An NVIDIA GPU makes transcription faster; on the CPU a 12-minute video takes about 5 minutes.
+
+MIT license.
diff --git a/docs/demo-frame-1.jpg b/docs/demo-frame-1.jpg
new file mode 100644
index 0000000..1a6655d
Binary files /dev/null and b/docs/demo-frame-1.jpg differ
diff --git a/docs/demo-frame-2.jpg b/docs/demo-frame-2.jpg
new file mode 100644
index 0000000..cfc84b6
Binary files /dev/null and b/docs/demo-frame-2.jpg differ
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000..623277e
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,4 @@
+faster-whisper>=1.1
+numpy>=1.26
+requests>=2.31
+yt-dlp[default]>=2026.10.26
diff --git a/scripts/check.py b/scripts/check.py
new file mode 100644
index 0000000..a9a1ead
--- /dev/null
+++ b/scripts/check.py
@@ -0,0 +1,96 @@
+"""Pre-post check of a finished clip.
+
+usage: python check.py <clip.mp4> [--campaign campaigns.md] [--caption "text"]
+Reads clip_<n>.json (written by cut.py) next to the clip if present. Exit code 1 on any FAIL.
+campaigns.md lines understood: min_seconds: 15 / max_seconds: 60 / required_hashtags: #a #b / required_mention: @x
+"""
+import argparse, re, sys
+from pathlib import Path
+sys.path.insert(0, str(Path(__file__).parent))
+from common import ffprobe, load_json
+
+BANNED = ["leak", "leaked build", "play early", "early access download", "free download", "crack", "piracy",
+ "mod menu", "money glitch", "afk bot"]
+
+
+def parse_campaign(path):
+ rules = {"min": 7.0, "max": 60.0, "tags": [], "mention": None}
+ if not path or not Path(path).exists():
+ return rules, False
+ txt = Path(path).read_text(encoding="utf-8", errors="replace")
+ m = re.search(r"min_seconds:\s*(\d+(?:\.\d+)?)", txt, re.I)
+ if m: rules["min"] = float(m.group(1))
+ m = re.search(r"max_seconds:\s*(\d+(?:\.\d+)?)", txt, re.I)
+ if m: rules["max"] = float(m.group(1))
+ m = re.search(r"required_hashtags:\s*(.+)", txt, re.I)
+ if m: rules["tags"] = re.findall(r"#\w+", m.group(1))
+ m = re.search(r"required_mention:\s*(@\w+)", txt, re.I)
+ if m: rules["mention"] = m.group(1)
+ return rules, True
+
+
+def fps_of(s):
+ try:
+ a, b = s.split("/"); return float(a) / float(b)
+ except Exception:
+ return 0.0
+
+
+def banned_in(text):
+ low = text.lower()
+ return [b for b in BANNED if b in low]
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("clip"); ap.add_argument("--campaign"); ap.add_argument("--caption", default="")
+ a = ap.parse_args()
+ clip = Path(a.clip)
+ res = [] # (name, ok, detail)
+
+ def add(name, ok, detail=""):
+ res.append((name, ok, detail))
+
+ if not clip.exists():
+ sys.exit(f"FAIL file not found: {clip}")
+ side = clip.with_suffix(".json")
+ meta = load_json(side) if side.exists() else {}
+ rules, have_campaign = parse_campaign(a.campaign)
+ p = ffprobe(clip)
+ streams = p.get("streams", [])
+ v = next((s for s in streams if s.get("codec_type") == "video"), None)
+ au = next((s for s in streams if s.get("codec_type") == "audio"), None)
+ dur = float(p.get("format", {}).get("duration", 0) or 0)
+
+ add("resolution 1080x1920", bool(v) and (v.get("width"), v.get("height")) == (1080, 1920),
+ f"{v.get('width')}x{v.get('height')}" if v else "no video")
+ f = fps_of(v.get("r_frame_rate", "0/1")) if v else 0
+ add("fps about 30", 29 <= f <= 31, f"{f:.2f}")
+ add("has audio", au is not None)
+ add(f"duration {rules['min']:g}-{rules['max']:g}s" + ("" if have_campaign else " (default)"),
+ rules["min"] <= dur <= rules["max"], f"{dur:.1f}s")
+ if side.exists():
+ add("credit present", bool(str(meta.get("credit", "")).strip()), meta.get("credit", "") or "empty")
+ else:
+ add("credit present", False, f"no sidecar {side.name}; cannot verify credit")
+ hook = meta.get("hook", "")
+ hits = banned_in(hook + " " + a.caption)
+ add("no banned terms in caption/hook", not hits, ", ".join(hits))
+ if rules["tags"]:
+ miss = [t for t in rules["tags"] if t.lower() not in a.caption.lower()]
+ add("required hashtags", not miss, ("missing " + " ".join(miss)) if miss else " ".join(rules["tags"]))
+ if rules["mention"]:
+ ok = rules["mention"].lower() in a.caption.lower()
+ add("required mention", ok, rules["mention"])
+ if not have_campaign:
+ add("campaign rules file", True, "none given, defaults used (NOT a rules check)")
+
+ for n, ok, d in res:
+ print(f"{'PASS' if ok else 'FAIL'} {n}" + (f" [{d}]" if d else ""))
+ bad = [r for r in res if not r[1]]
+ print("RESULT: " + ("FAIL" if bad else "PASS"))
+ sys.exit(1 if bad else 0)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/common.py b/scripts/common.py
new file mode 100644
index 0000000..30e03d5
--- /dev/null
+++ b/scripts/common.py
@@ -0,0 +1,62 @@
+"""Shared helpers: paths, tool lookup, yt-dlp and ffmpeg wrappers."""
+import hashlib, json, os, re, shutil, subprocess, sys
+from pathlib import Path
+
+ROOT = Path(os.environ.get("CLIP_DESK_HOME", Path.cwd()))
+JOBS = ROOT / "jobs"
+
+
+def tool(name):
+ p = shutil.which(name)
+ if not p:
+ sys.exit(f"{name} not found. Run the setup skill first (it installs ffmpeg and yt-dlp).")
+ return p
+
+
+def run(cmd, check=True, capture=False):
+ r = subprocess.run(cmd, check=False, text=True, encoding="utf-8", errors="replace",
+ stdout=subprocess.PIPE if capture else None, stderr=subprocess.PIPE if capture else None)
+ if check and r.returncode != 0:
+ msg = (r.stderr or "")[-1500:] if capture else ""
+ sys.exit(f"command failed ({r.returncode}): {' '.join(map(str, cmd))[:200]}\n{msg}")
+ return r
+
+
+def ytdlp_base():
+ import importlib.util
+ exe = [sys.executable, "-m", "yt_dlp"] if importlib.util.find_spec("yt_dlp") else [tool("yt-dlp")]
+ base = exe + ["--no-warnings", "--no-progress"]
+ if sys.platform == "win32":
+ base += ["--compat-options", "no-certifi"] # use the Windows certificate store
+ return base
+
+
+def ytdlp_json(url, extra=()):
+ r = run(ytdlp_base() + ["-J", *extra, url], capture=True)
+ return json.loads(r.stdout)
+
+
+def is_url(s):
+ return bool(re.match(r"https?://", s))
+
+
+def job_dir(src):
+ key = hashlib.sha1(src.encode()).hexdigest()[:8]
+ stem = re.sub(r"[^a-z0-9]+", "-", Path(src).stem.lower() if not is_url(src) else src.split("v=")[-1].split("/")[-1].lower())[:24].strip("-")
+ d = JOBS / f"{stem or 'job'}-{key}"
+ d.mkdir(parents=True, exist_ok=True)
+ return d
+
+
+def ffprobe(path):
+ r = run([tool("ffprobe"), "-v", "error", "-show_entries", "format=duration:stream=codec_type,width,height,r_frame_rate",
+ "-of", "json", str(path)], capture=True)
+ return json.loads(r.stdout)
+
+
+def save_json(path, obj):
+ Path(path).write_text(json.dumps(obj, ensure_ascii=False, indent=1), encoding="utf-8")
+
+
+def load_json(path):
+ return json.loads(Path(path).read_text(encoding="utf-8"))
diff --git a/scripts/cut.py b/scripts/cut.py
new file mode 100644
index 0000000..5fef822
--- /dev/null
+++ b/scripts/cut.py
@@ -0,0 +1,113 @@
+"""Cut one candidate into a finished vertical clip.
+
+1080x1920, 30 fps, word-by-word burned captions, hook box in the first seconds, credit line,
+loudness normalised to -14 LUFS. Writes jobs/<id>/edits/clip_<n>.mp4 + .json (metadata for check.py).
+
+usage: python cut.py jobs/<id> --pick 1 [--layout fill|blur|facecam] [--hook "TEXT"] [--credit "@creator"]
+ [--cam x:y:w:h] (facecam box as fractions of the source frame, default bottom-right 0.70:0.68:0.30:0.32)
+"""
+import argparse, sys
+from pathlib import Path
+sys.path.insert(0, str(Path(__file__).parent))
+from common import load_json, run, save_json, tool
+
+W, H = 1080, 1920
+
+
+def ts(t):
+ t = max(0, t); h = int(t // 3600); m = int(t % 3600 // 60); s = t % 60
+ return f"{h}:{m:02d}:{s:05.2f}"
+
+
+def esc(s):
+ return s.replace("\\", "").replace("{", "(").replace("}", ")").replace("\n", " ")
+
+
+def build_ass(words, s0, e0, hook, credit, cap_y):
+ hdr = f"""[Script Info]
+ScriptType: v4.00+
+PlayResX: {W}
+PlayResY: {H}
+WrapStyle: 0
+
+[V4+ Styles]
+Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
+Style: Cap,Arial Black,92,&H00FFFFFF,&H0000E5FF,&H00000000,&H64000000,-1,0,0,0,100,100,0,0,1,7,3,5,60,60,0,1
+Style: Hook,Arial Black,68,&H00000000,&H00000000,&H00FFFFFF,&H00FFFFFF,-1,0,0,0,100,100,0,0,3,18,0,8,70,70,170,1
+Style: Credit,Arial,40,&H00FFFFFF,&H00FFFFFF,&H00000000,&H78000000,-1,0,0,0,100,100,0,0,1,3,1,2,40,40,90,1
+
+[Events]
+Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
+"""
+ ev = []
+ ws = [w for w in words if s0 <= w["s"] < e0 and w["w"]]
+ # groups of up to 3 words, break on punctuation or pauses
+ groups, cur = [], []
+ for w in ws:
+ if cur and (len(cur) == 3 or w["s"] - cur[-1]["e"] > 0.6 or cur[-1]["w"][-1:] in ".?!,"):
+ groups.append(cur); cur = []
+ cur.append(w)
+ if cur:
+ groups.append(cur)
+ hook_end = 2.6 if hook else 0
+ for gi, g in enumerate(groups):
+ g_end = groups[gi + 1][0]["s"] if gi + 1 < len(groups) else g[-1]["e"] + 0.4
+ g_end = min(g_end, g[-1]["e"] + 0.8)
+ for k, w in enumerate(g):
+ a = w["s"] - s0; b = (g[k + 1]["s"] - s0) if k + 1 < len(g) else g_end - s0
+ if b <= a:
+ continue
+ parts = []
+ for j, x in enumerate(g):
+ t = esc(x["w"].upper())
+ parts.append("{\\c&H0000E5FF&}" + t + "{\\c&H00FFFFFF&}" if j == k else t)
+ pop = "{\\fscx112\\fscy112\\t(0,90,\\fscx100\\fscy100)}" if k == 0 else ""
+ ev.append(f"Dialogue: 0,{ts(a)},{ts(b)},Cap,,0,0,0,,{{\\pos({W // 2},{cap_y})}}{pop}{' '.join(parts)}")
+ if hook:
+ ev.append(f"Dialogue: 1,{ts(0)},{ts(hook_end)},Hook,,0,0,0,,{{\\fad(0,180)\\fscx92\\fscy92\\t(0,120,\\fscx100\\fscy100)}}{esc(hook)}")
+ if credit:
+ ev.append(f"Dialogue: 1,{ts(0)},{ts(e0 - s0)},Credit,,0,0,0,,{esc('clip: ' + credit)}")
+ return hdr + "\n".join(ev) + "\n"
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("job"); ap.add_argument("--pick", type=int, default=1)
+ ap.add_argument("--layout", choices=["fill", "blur", "facecam"], default="blur")
+ ap.add_argument("--hook", default=""); ap.add_argument("--credit", default="")
+ ap.add_argument("--cam", default="0.70:0.68:0.30:0.32")
+ ap.add_argument("--start", type=float); ap.add_argument("--end", type=float)
+ a = ap.parse_args()
+ d = Path(a.job); c = load_json(d / "candidates.json")
+ pick = next(x for x in c["candidates"] if x["n"] == a.pick)
+ s0 = a.start if a.start is not None else pick["start"]; e0 = a.end if a.end is not None else pick["end"]
+ words = load_json(d / "transcript.json")
+ out = d / "edits"; out.mkdir(exist_ok=True)
+ cap_y = {"fill": 1380, "blur": 1460, "facecam": 1120}[a.layout]
+ ass = out / f"clip_{a.pick}.ass"
+ ass.write_text(build_ass(words, s0, e0, a.hook, a.credit, cap_y), encoding="utf-8")
+ if a.layout == "fill":
+ v = f"[0:v]scale=-2:{H},crop={W}:{H}[v]"
+ elif a.layout == "blur":
+ v = (f"[0:v]split[a][b];[a]scale=-2:{H},crop={W}:{H},boxblur=24:2,eq=brightness=-0.08[bg];"
+ f"[b]scale={W}:-2[fg];[bg][fg]overlay=(W-w)/2:(H-h)/2-80[v]")
+ else:
+ x, y, w, h = map(float, a.cam.split(":"))
+ v = (f"[0:v]split[a][b];[a]crop=iw*{w}:ih*{h}:iw*{x}:ih*{y},scale={W}:{int(H * 0.38)}:force_original_aspect_ratio=increase,"
+ f"crop={W}:{int(H * 0.38)}[cam];[b]scale=-2:{H - int(H * 0.38)},crop={W}:{H - int(H * 0.38)}[game];[cam][game]vstack[v]")
+ sub = str(ass).replace("\\", "/").replace(":", "\\:")
+ v += f";[v]fps=30,subtitles='{sub}'[vo]"
+ mp4 = out / f"clip_{a.pick}.mp4"
+ run([tool("ffmpeg"), "-y", "-v", "error", "-ss", f"{s0:.2f}", "-to", f"{e0:.2f}", "-i", c["source"],
+ "-filter_complex", v, "-map", "[vo]", "-map", "0:a?", "-af", "loudnorm=I=-14:TP=-1.5:LRA=11",
+ "-c:v", "libx264", "-preset", "medium", "-crf", "20", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "160k",
+ "-ar", "48000", "-movflags", "+faststart", str(mp4)])
+ info = c.get("info", {})
+ save_json(out / f"clip_{a.pick}.json", {"file": str(mp4), "start": s0, "end": e0, "layout": a.layout, "hook": a.hook,
+ "credit": a.credit, "source_url": info.get("webpage_url"), "source_title": info.get("title"),
+ "source_channel": info.get("channel") or info.get("uploader")})
+ print(mp4)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/live.py b/scripts/live.py
new file mode 100644
index 0000000..c5a203b
--- /dev/null
+++ b/scripts/live.py
@@ -0,0 +1,249 @@
+"""Record a YouTube live stream and auto-cut clips when live chat spikes.
+
+Records the stream in 60 s segments into jobs/<id>/live/, reads live chat as it arrives, and on a chat
+spike cuts [spike-before, spike+after] into live/spike_<n>.mp4 and appends a row to live/spikes.md.
+Run moments.py / cut.py on the spike clips afterwards.
+
+usage: python live.py <youtube-live-url> --minutes 60 [--before 15 --after 20 --window 10 --baseline 300
+ --ratio 3 --min-msgs 8 --lag 8 --cooldown 45]
+Stop early with Ctrl+C. Pending spikes are still cut on shutdown.
+"""
+import argparse, json, re, subprocess, sys, time
+from collections import Counter
+from datetime import datetime, timezone
+from pathlib import Path
+sys.path.insert(0, str(Path(__file__).parent))
+from common import job_dir, run, save_json, tool, ytdlp_base
+
+HYPE = re.compile(r"(?i:LMAO|KEKW|LOL|CLIP|HOLY|NO WAY)|\bW+\b|[πŸ’€πŸ˜‚πŸ”₯]")
+NOISE = re.compile(r"(?i)giveaway|\braid(ing|ed)?\b|\bbrb\b|be right back|ad break|sponsor|subscribe|discord\.gg|https?://|promo code|follow me")
+STOP = set("the a an and or to of is it in i you that this on for with was are be so but not my me we he she they what just like at as if do get".split())
+WORD = re.compile(r"[\w']{2,}|[πŸ’€πŸ˜‚πŸ”₯]")
+
+
+def now():
+ return time.time()
+
+
+def extract_text(renderer):
+ out = []
+ for r in (renderer.get("message") or {}).get("runs", []):
+ if "text" in r:
+ out.append(r["text"])
+ elif "emoji" in r:
+ e = r["emoji"]
+ out.append(e.get("emojiId") if len(e.get("emojiId", "")) <= 2 else (e.get("shortcuts") or [""])[0])
+ return "".join(out).strip()
+
+
+class ChatTail:
+ """Tails yt-dlp's live_chat output (.part, .part-FragN or final file) and collects per-second counts."""
+
+ def __init__(self, d, start_wall):
+ self.d, self.start = d, start_wall
+ self.pos, self.buf, self.seen = {}, {}, set()
+ self.raw, self.wgt, self.words = Counter(), Counter(), {} # keyed by int unix second
+
+ def poll(self):
+ for f in sorted(self.d.glob("chat.live_chat.json*")):
+ try:
+ with open(f, "rb") as fh:
+ fh.seek(self.pos.get(f.name, 0))
+ data = fh.read()
+ except OSError:
+ continue
+ if not data:
+ continue
+ self.pos[f.name] = self.pos.get(f.name, 0) + len(data)
+ buf = self.buf.get(f.name, b"") + data
+ *lines, rest = buf.split(b"\n")
+ self.buf[f.name] = rest
+ for ln in lines:
+ self.handle(ln)
+
+ def handle(self, ln):
+ try:
+ acts = json.loads(ln)["replayChatItemAction"]["actions"]
+ except Exception:
+ return
+ for a in acts:
+ r = (((a.get("addChatItemAction") or {}).get("item")) or {}).get("liveChatTextMessageRenderer")
+ if not r or r.get("id") in self.seen:
+ continue
+ self.seen.add(r.get("id"))
+ try:
+ ts = int(r["timestampUsec"]) / 1e6
+ except Exception:
+ ts = now()
+ txt = extract_text(r)
+ if ts < self.start - 5 or not txt or NOISE.search(txt): # history backlog / ads / raids
+ continue
+ s = int(ts)
+ self.raw[s] += 1
+ self.wgt[s] += 2 if HYPE.search(txt) else 1
+ self.words.setdefault(s, []).append(txt)
+
+ def total(self, c, a, b):
+ return sum(c.get(s, 0) for s in range(a, b + 1))
+
+ def top_words(self, a, b, n=3):
+ cnt = Counter()
+ for s in range(a, b + 1):
+ for t in self.words.get(s, []):
+ cnt.update(w.lower() for w in WORD.findall(t) if w.lower() not in STOP)
+ return [w for w, _ in cnt.most_common(n)]
+
+
+class Recorder:
+ def __init__(self, ld, url, minutes):
+ self.ld, self.csv = ld, ld / "segments.csv"
+ r = run(ytdlp_base() + ["-g", "-f", "b[height<=720]/bv*[height<=720]+ba/b", url], capture=True)
+ urls = [u for u in r.stdout.split() if u.startswith("http")]
+ if not urls:
+ sys.exit("could not get a stream URL (is the video live?)")
+ cmd = [tool("ffmpeg"), "-y", "-loglevel", "warning"]
+ for u in urls:
+ cmd += ["-reconnect", "1", "-reconnect_streamed", "1", "-reconnect_delay_max", "5", "-i", u]
+ for i in range(len(urls)):
+ cmd += ["-map", str(i)]
+ cmd += ["-c", "copy", "-t", str(int(minutes * 60)), "-f", "segment", "-segment_time", "60",
+ "-segment_format", "mpegts", "-reset_timestamps", "1", "-segment_list", str(self.csv),
+ "-segment_list_type", "csv", str(ld / "seg_%05d.ts")]
+ self.proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, creationflags=getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0))
+ self.t0 = None
+
+ def alive(self):
+ return self.proc.poll() is None
+
+ def stop(self):
+ if self.alive():
+ try:
+ self.proc.stdin.write(b"q\n"); self.proc.stdin.flush()
+ except OSError:
+ pass
+ try:
+ self.proc.wait(20)
+ except subprocess.TimeoutExpired:
+ self.proc.terminate()
+ try: self.proc.wait(5)
+ except subprocess.TimeoutExpired: self.proc.kill()
+
+ def segments(self):
+ """[(path, start, end, mtime, complete)] with cumulative timeline starts (seconds since recording began)."""
+ done, t = [], 0.0
+ if self.csv.exists():
+ for ln in self.csv.read_text(errors="ignore").splitlines():
+ p = ln.split(",")
+ if len(p) >= 3 and (self.ld / p[0]).exists():
+ dur = float(p[2]) - float(p[1])
+ f = self.ld / p[0]
+ done.append((f, t, t + dur, f.stat().st_mtime, True)); t += dur
+ names = {s[0].name for s in done}
+ for f in sorted(self.ld.glob("seg_*.ts")):
+ if f.name not in names: # in-progress segment: end unknown, treat as open-ended
+ done.append((f, t, float("inf"), f.stat().st_mtime, False))
+ return done
+
+
+def cut(rec, wall, before, after, lag, out):
+ """Cut around wall-clock time `wall`. Returns (offset_seconds, ok)."""
+ segs = rec.segments()
+ comp = [s for s in segs if s[4]]
+ if not comp:
+ return None, False
+ f, st, en, mt, _ = comp[-1]
+ center = en - (mt - wall) + lag # stream position of the event: reception time of last full segment anchors the clock
+ t0, t1 = max(0.0, center - before), center + after
+ pick = [s for s in segs if s[2] > t0 and s[1] < t1]
+ if not pick:
+ return center, False
+ lst = out.with_suffix(".txt")
+ lst.write_text("".join(f"file '{s[0].resolve().as_posix()}'\n" for s in pick), encoding="utf-8")
+ r = run([tool("ffmpeg"), "-y", "-v", "error", "-f", "concat", "-safe", "0", "-i", str(lst),
+ "-ss", f"{max(0.0, t0 - pick[0][1]):.2f}", "-t", f"{t1 - t0:.2f}", "-c", "copy",
+ "-avoid_negative_ts", "make_zero", "-movflags", "+faststart", str(out)], check=False, capture=True)
+ lst.unlink(missing_ok=True)
+ return center, r.returncode == 0 and out.exists() and out.stat().st_size > 0
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("url"); ap.add_argument("--minutes", type=float, default=60)
+ ap.add_argument("--before", type=float, default=15); ap.add_argument("--after", type=float, default=20)
+ ap.add_argument("--window", type=int, default=10); ap.add_argument("--baseline", type=int, default=300)
+ ap.add_argument("--ratio", type=float, default=3); ap.add_argument("--min-msgs", type=int, default=8)
+ ap.add_argument("--cooldown", type=float, default=45)
+ ap.add_argument("--lag", type=float, default=8, help="seconds to shift the clip later: stream delay + chat reaction time")
+ a = ap.parse_args()
+
+ d = job_dir(a.url)
+ ld = d / "live"
+ ld.mkdir(exist_ok=True)
+ for f in list(ld.glob("seg_*.ts")) + list(ld.glob("chat.live_chat.json*")) + [ld / "segments.csv"]:
+ f.unlink(missing_ok=True)
+ spikes_md = ld / "spikes.md"
+ if not spikes_md.exists():
+ spikes_md.write_text("| UTC time | offset | msgs/%ds | top words | file |\n|---|---|---|---|---|\n" % a.window, encoding="utf-8")
+ n = len(list(ld.glob("spike_*.mp4")))
+ start = now()
+ end_at = start + a.minutes * 60 + 30
+
+ rec = Recorder(ld, a.url, a.minutes)
+ chat = subprocess.Popen(ytdlp_base() + ["--skip-download", "--write-subs", "--sub-langs", "live_chat",
+ "-o", str(ld / "chat"), a.url],
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
+ creationflags=getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0))
+ tail = ChatTail(ld, start)
+ pending, last_spike, spikes = [], 0.0, 0
+ print(f"recording {a.minutes:g} min -> {ld} (Ctrl+C to stop)", flush=True)
+
+ def finish_one(item, final=False):
+ nonlocal spikes
+ num, wall, rate, words = item
+ out = ld / f"spike_{num}.mp4"
+ center, ok = cut(rec, wall, a.before, a.after, a.lag, out)
+ iso = datetime.fromtimestamp(wall, timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
+ off = "-" if center is None else f"{int(center // 60)}:{int(center % 60):02d}"
+ row = f"| {iso} | {off} | {rate} | {', '.join(words)} | {out.name if ok else 'CUT FAILED'} |\n"
+ with open(spikes_md, "a", encoding="utf-8") as fh:
+ fh.write(row)
+ print(("clip " + out.name if ok else "cut failed") + f" (spike at {off}, {rate} msgs/{a.window}s, {words})", flush=True)
+
+ try:
+ while now() < end_at and rec.alive():
+ time.sleep(1)
+ tail.poll()
+ t = now()
+ if rec.t0 is None and any(ld.glob("seg_*.ts")):
+ rec.t0 = t
+ e = int(t) - 3 # let chat batches land before judging a second
+ elapsed_chat = e - int(start)
+ if elapsed_chat >= a.window + 30 and t - last_spike >= a.cooldown and rec.t0:
+ raw = tail.total(tail.raw, e - a.window + 1, e)
+ w = tail.total(tail.wgt, e - a.window + 1, e)
+ nb = min(a.baseline, elapsed_chat - a.window)
+ bw = tail.total(tail.wgt, e - a.window - nb + 1, e - a.window) / nb
+ rate_w = w / a.window
+ if raw >= a.min_msgs and rate_w >= a.ratio * max(bw, 0.02):
+ n += 1; spikes += 1; last_spike = t
+ words = tail.top_words(e - a.window + 1, e)
+ print(f"SPIKE #{n}: {raw} msgs/{a.window}s vs baseline {bw * a.window:.1f} weighted", flush=True)
+ pending.append((n, float(e), raw, words, t + a.after + max(a.lag, 0)))
+ for p in [p for p in pending if p[4] <= t]:
+ pending.remove(p); finish_one(p[:4])
+ except KeyboardInterrupt:
+ print("stopping...", flush=True)
+ finally:
+ rec.stop()
+ if chat.poll() is None:
+ chat.terminate()
+ try: chat.wait(10)
+ except subprocess.TimeoutExpired: chat.kill()
+ for p in pending:
+ finish_one(p[:4], final=True)
+ save_json(ld / "live.json", {"url": a.url, "spikes": spikes, "minutes": a.minutes})
+ print(f"done: {spikes} spike(s). See {spikes_md}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/moments.py b/scripts/moments.py
new file mode 100644
index 0000000..e2baabd
--- /dev/null
+++ b/scripts/moments.py
@@ -0,0 +1,183 @@
+"""Find the best clip moments in a video or VOD.
+
+Signals per second: loudness spikes, YouTube "most replayed" heatmap, live-chat spikes
+(YouTube VOD chat replay or a TwitchDownloader chat.json) and hype words in the transcript.
+Writes jobs/<id>/candidates.md + candidates.json.
+
+usage: python moments.py <url-or-file> [--top 8] [--min 15] [--max 40] [--chat chat.json] [--max-minutes 90]
+"""
+import argparse, json, math, re, sys, wave
+from pathlib import Path
+import numpy as np
+sys.path.insert(0, str(Path(__file__).parent))
+from common import ffprobe, is_url, job_dir, load_json, run, save_json, tool, ytdlp_base, ytdlp_json
+
+HYPE = re.compile(r"\b(no way|oh my god|omg|what|wait|bro|let'?s go|holy|insane|crazy|yo+|wtf|dude|look at|nah|run|go go)\b", re.I)
+CHAT_HYPE = re.compile(r"(LMAO|LOL|KEKW|OMEGALUL|W+\b|CLIP|πŸ’€|πŸ˜‚|πŸ”₯|NO WAY|HOLY)", re.I)
+
+
+def fetch(src, d, max_min):
+ info = {}
+ if is_url(src):
+ info = ytdlp_json(src)
+ save_json(d / "info.json", {k: info.get(k) for k in ("id", "title", "uploader", "channel", "uploader_id", "webpage_url",
+ "duration", "view_count", "upload_date", "heatmap", "is_live", "was_live")})
+ vid = d / "source.mp4"
+ if not vid.exists():
+ args = ytdlp_base() + ["-f", "bv*[height<=1080][ext=mp4]+ba[ext=m4a]/b[height<=1080]/b", "--merge-output-format", "mp4",
+ "-o", str(vid)]
+ if (info.get("duration") or 0) > max_min * 60:
+ args += ["--download-sections", f"*0-{max_min * 60}"]
+ run(args + [src])
+ if info.get("was_live") and not (d / "chat.json").exists(): # YouTube chat replay
+ run(ytdlp_base() + ["--skip-download", "--write-subs", "--sub-langs", "live_chat", "-o", str(d / "chat"), src], check=False)
+ else:
+ vid = Path(src).resolve()
+ save_json(d / "info.json", {"title": vid.stem, "webpage_url": str(vid)})
+ return vid, info
+
+
+def audio_rms(vid, d):
+ wav = d / "audio.wav"
+ if not wav.exists():
+ run([tool("ffmpeg"), "-y", "-v", "error", "-i", str(vid), "-ac", "1", "-ar", "16000", str(wav)])
+ with wave.open(str(wav)) as w:
+ x = np.frombuffer(w.readframes(w.getnframes()), dtype=np.int16).astype(np.float32) / 32768
+ n = len(x) // 16000
+ rms = np.sqrt((x[: n * 16000].reshape(n, 16000) ** 2).mean(1) + 1e-9)
+ return wav, 20 * np.log10(rms)
+
+
+def transcribe(wav, d):
+ out = d / "transcript.json"
+ if out.exists():
+ return load_json(out)
+ from faster_whisper import WhisperModel
+ try:
+ import ctranslate2
+ cuda = ctranslate2.get_cuda_device_count() > 0
+ except Exception:
+ cuda = False
+ with wave.open(str(wav)) as w: # pass samples directly (16 kHz mono), no extra decoder needed
+ pcm = np.frombuffer(w.readframes(w.getnframes()), dtype=np.int16).astype(np.float32) / 32768
+
+ def run_on(device):
+ model = WhisperModel("small", device=device, compute_type="float16" if device == "cuda" else "int8")
+ segs, _ = model.transcribe(pcm, word_timestamps=True, vad_filter=True)
+ return [{"w": w.word.strip(), "s": round(w.start, 2), "e": round(w.end, 2)} for s in segs for w in (s.words or [])]
+ try:
+ words = run_on("cuda" if cuda else "cpu")
+ except RuntimeError as e: # GPU present but CUDA libraries missing: fall back to CPU
+ print(f"GPU transcription unavailable ({str(e)[:80]}), using CPU")
+ words = run_on("cpu")
+ save_json(out, words)
+ return words
+
+
+def chat_series(d, n, chat_arg, info):
+ """Messages per second from YouTube live_chat json lines or a TwitchDownloader chat.json."""
+ c = np.zeros(n)
+ yt = list(d.glob("chat*.live_chat.json"))
+ if yt:
+ for line in yt[0].read_text(encoding="utf-8", errors="ignore").splitlines():
+ try:
+ a = json.loads(line)["replayChatItemAction"]
+ t = int(a["videoOffsetTimeMsec"]) / 1000
+ txt = json.dumps(a["actions"], ensure_ascii=False)
+ except Exception:
+ continue
+ if 0 <= t < n:
+ c[int(t)] += 2 if CHAT_HYPE.search(txt) else 1
+ elif chat_arg:
+ js = load_json(chat_arg)
+ for m in js.get("comments", []):
+ t = m.get("content_offset_seconds", 0)
+ body = (m.get("message") or {}).get("body", "")
+ if 0 <= t < n:
+ c[int(t)] += 2 if CHAT_HYPE.search(body) else 1
+ return c
+
+
+def z(a):
+ a = np.asarray(a, dtype=float)
+ if a.std() < 1e-9:
+ return np.zeros_like(a)
+ return (a - np.median(a)) / (a.std() + 1e-9)
+
+
+def smooth(a, k):
+ k = max(1, int(k))
+ return np.convolve(a, np.ones(k) / k, mode="same")
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("src"); ap.add_argument("--top", type=int, default=8)
+ ap.add_argument("--min", type=float, default=15); ap.add_argument("--max", type=float, default=40)
+ ap.add_argument("--chat"); ap.add_argument("--max-minutes", type=int, default=90)
+ a = ap.parse_args()
+ d = job_dir(a.src)
+ vid, info = fetch(a.src, d, a.max_minutes)
+ dur = float(ffprobe(vid)["format"]["duration"])
+ wav, db = audio_rms(vid, d)
+ n = len(db)
+ words = transcribe(wav, d)
+ # signals
+ loud = smooth(np.clip(z(db - smooth(db, 30)), 0, None), 3) # jumps above the local level
+ hype = np.zeros(n)
+ for w in words:
+ if HYPE.search(w["w"]) and int(w["s"]) < n:
+ hype[int(w["s"])] += 1
+ hype = smooth(hype, 5)
+ heat = np.zeros(n)
+ for h in (info.get("heatmap") or []):
+ heat[int(h["start_time"]):int(math.ceil(h["end_time"]))] = h["value"]
+ chat = chat_series(d, n, a.chat, info)
+ chatz = smooth(np.clip(z(smooth(chat, 10)), 0, None), 3)
+ w_heat = 2.0 if heat.any() else 0
+ w_chat = 1.5 if chat.any() else 0
+ score = 1.0 * loud + 0.8 * z(hype).clip(0) + w_heat * z(heat).clip(0) + w_chat * chatz
+ # pick non-overlapping windows around peaks
+ starts = [x["s"] for x in words]
+ picks, used = [], np.zeros(n, bool)
+ order = np.argsort(-score)
+ for p in order:
+ if len(picks) >= a.top or score[p] <= 0:
+ break
+ s0 = max(0, p - 0.55 * a.max); e0 = min(dur, s0 + a.max)
+ # snap start to the first word after s0 and end to a word end, keep length in [min, max]
+ ws = [x for x in words if x["s"] >= s0 and x["e"] <= e0]
+ if ws:
+ s0 = max(0, ws[0]["s"] - 0.3); e0 = min(dur, ws[-1]["e"] + 0.6)
+ if e0 - s0 < a.min:
+ e0 = min(dur, s0 + a.min)
+ e0 = min(e0, s0 + a.max)
+ if used[int(s0):int(e0)].any():
+ continue
+ used[int(s0):int(e0)] = True
+ text = " ".join(x["w"] for x in words if s0 <= x["s"] < e0)
+ why = []
+ if loud[p] > 1: why.append("loudness spike")
+ if hype[p] > 0: why.append("hype words")
+ if heat[p] > 0.5: why.append(f"most replayed {heat[p]:.2f}")
+ if w_chat and chatz[p] > 1: why.append("chat spike")
+ picks.append({"n": len(picks) + 1, "start": round(s0, 2), "end": round(e0, 2), "peak": int(p),
+ "score": round(float(score[p]), 2), "why": why or ["overall energy"], "text": text[:400]})
+ picks.sort(key=lambda x: x["start"])
+ for i, x in enumerate(picks, 1):
+ x["n"] = i
+ meta = load_json(d / "info.json")
+ save_json(d / "candidates.json", {"source": str(vid), "info": meta, "duration": dur, "candidates": picks,
+ "signals": {"heatmap": bool(w_heat), "chat": bool(w_chat), "words": len(words)}})
+ fmt = lambda t: f"{int(t // 60)}:{int(t % 60):02d}"
+ md = [f"# Candidates: {meta.get('title', '')}", f"source: {meta.get('webpage_url', '')}",
+ f"signals: loudness, transcript ({len(words)} words)" + (", most replayed" if w_heat else "") + (", chat" if w_chat else ""), ""]
+ for x in picks:
+ md += [f"## {x['n']}. {fmt(x['start'])}-{fmt(x['end'])} ({x['end'] - x['start']:.0f}s) score {x['score']}",
+ f"why: {', '.join(x['why'])}", f"> {x['text']}", ""]
+ (d / "candidates.md").write_text("\n".join(md), encoding="utf-8")
+ print(f"job: {d}\n{len(picks)} candidates -> {d / 'candidates.md'}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/payouts.py b/scripts/payouts.py
new file mode 100644
index 0000000..d40f79a
--- /dev/null
+++ b/scripts/payouts.py
@@ -0,0 +1,59 @@
+"""Payout log. Only numbers the human typed; rates are never invented.
+
+usage: python payouts.py add --platform tiktok --post-url URL --views 12000 --rate-per-1k 0.5 --campaign NAME [--status pending]
+ python payouts.py report
+File: payouts.csv in the current folder (override with --file).
+"""
+import argparse, csv, sys
+from collections import defaultdict
+from datetime import date
+from pathlib import Path
+
+FIELDS = ["date", "campaign", "platform", "post_url", "views", "rate_per_1k", "est_payout", "status"]
+
+
+def read(path):
+ if not Path(path).exists():
+ return []
+ with open(path, newline="", encoding="utf-8") as f:
+ return list(csv.DictReader(f))
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--file", default="payouts.csv")
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ a_ = sub.add_parser("add")
+ a_.add_argument("--platform", required=True); a_.add_argument("--post-url", required=True)
+ a_.add_argument("--views", type=int, required=True); a_.add_argument("--rate-per-1k", type=float, required=True)
+ a_.add_argument("--campaign", required=True); a_.add_argument("--status", default="pending")
+ sub.add_parser("report")
+ a = ap.parse_args()
+
+ if a.cmd == "add":
+ est = round(a.views / 1000 * a.rate_per_1k, 2)
+ new = not Path(a.file).exists()
+ with open(a.file, "a", newline="", encoding="utf-8") as f:
+ w = csv.DictWriter(f, FIELDS)
+ if new: w.writeheader()
+ w.writerow({"date": date.today().isoformat(), "campaign": a.campaign, "platform": a.platform,
+ "post_url": a.post_url, "views": a.views, "rate_per_1k": a.rate_per_1k,
+ "est_payout": f"{est:.2f}", "status": a.status})
+ print(f"added: {a.campaign} / {a.platform} {a.views} views x {a.rate_per_1k}/1k = {est:.2f} ({a.status})")
+ return
+
+ rows = read(a.file)
+ if not rows:
+ print("no payouts logged yet"); return
+ tot = defaultdict(lambda: [0, 0, 0.0])
+ for r in rows:
+ t = tot[r["campaign"]]; t[0] += 1; t[1] += int(r["views"]); t[2] += float(r["est_payout"])
+ print(f"{'campaign':24} {'posts':>5} {'views':>9} {'est_payout':>11}")
+ for c, (n, v, p) in sorted(tot.items()):
+ print(f"{c[:24]:24} {n:>5} {v:>9} {p:>11.2f}")
+ print(f"{'TOTAL':24} {sum(t[0] for t in tot.values()):>5} {sum(t[1] for t in tot.values()):>9} {sum(t[2] for t in tot.values()):>11.2f}")
+ print("est_payout = views/1000 x the rate you typed. Estimates, not confirmed earnings.")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/streams.py b/scripts/streams.py
new file mode 100644
index 0000000..f04efef
--- /dev/null
+++ b/scripts/streams.py
@@ -0,0 +1,133 @@
+"""Find live streams about a topic, ranked by concurrent viewers.
+
+usage: python streams.py --query "gta 6" --limit 20 --out streams.md
+YouTube always. Twitch only if TWITCH_CLIENT_ID and TWITCH_TOKEN are set. Kick is tried once, skipped silently on failure.
+Viewer counts are exactly what the platform returned at run time.
+"""
+import argparse, json, os, sys, time
+from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
+from urllib.parse import quote_plus
+sys.path.insert(0, str(Path(__file__).parent))
+from common import ytdlp_base, ytdlp_json, run
+
+try:
+ import truststore
+ truststore.inject_into_ssl()
+except Exception:
+ pass
+
+
+def fmt_dur(sec):
+ if not sec or sec < 0:
+ return ""
+ sec = int(sec)
+ return f"{sec // 3600}h{sec % 3600 // 60:02d}m"
+
+
+def youtube(query, limit):
+ url = f"https://www.youtube.com/results?search_query={quote_plus(query)}&sp=EgJAAQ%253D%253D"
+ r = run(ytdlp_base() + ["--flat-playlist", "-J", "--playlist-end", str(limit), url], capture=True, check=False)
+ if r.returncode != 0 or not r.stdout.strip():
+ print(f"youtube search failed: {(r.stderr or '')[-300:]}", file=sys.stderr)
+ return []
+ ids = []
+ for e in json.loads(r.stdout).get("entries") or []:
+ if e and e.get("id"):
+ ids.append(e.get("url") or f"https://www.youtube.com/watch?v={e['id']}")
+
+ def one(u):
+ try:
+ return ytdlp_json(u)
+ except BaseException: # run() calls sys.exit on failure
+ return None
+
+ with ThreadPoolExecutor(max_workers=8) as ex:
+ infos = list(ex.map(one, ids))
+ now = time.time(); out = []
+ for i in infos:
+ if not i or not i.get("is_live"):
+ continue
+ start = i.get("release_timestamp") or i.get("timestamp")
+ out.append({"platform": "YouTube", "channel": i.get("channel") or i.get("uploader") or "",
+ "title": i.get("title") or "", "url": i.get("webpage_url") or "",
+ "viewers": i.get("concurrent_view_count"), "live_for": fmt_dur(now - start) if start else ""})
+ return out
+
+
+def twitch(query):
+ cid, tok = os.environ.get("TWITCH_CLIENT_ID"), os.environ.get("TWITCH_TOKEN")
+ if not (cid and tok):
+ return None
+ import requests
+ h = {"Client-Id": cid, "Authorization": f"Bearer {tok}"}
+ try:
+ g = requests.get("https://api.twitch.tv/helix/games", params={"name": "Grand Theft Auto VI"}, headers=h, timeout=15).json()
+ if not g.get("data"):
+ return []
+ gid = g["data"][0]["id"]
+ s = requests.get("https://api.twitch.tv/helix/streams", params={"game_id": gid, "first": 100}, headers=h, timeout=15).json()
+ except Exception as e:
+ print(f"twitch failed: {e}", file=sys.stderr)
+ return []
+ now = time.time(); out = []
+ for x in s.get("data", []):
+ try:
+ st = time.mktime(time.strptime(x["started_at"], "%Y-%m-%dT%H:%M:%SZ")) - time.timezone
+ except Exception:
+ st = None
+ out.append({"platform": "Twitch", "channel": x.get("user_name", ""), "title": x.get("title", ""),
+ "url": f"https://twitch.tv/{x.get('user_login', '')}", "viewers": x.get("viewer_count"),
+ "live_for": fmt_dur(now - st) if st else ""})
+ return out
+
+
+def kick(query):
+ """Public API is often blocked; one try, silent on any failure."""
+ try:
+ import requests
+ r = requests.get("https://kick.com/api/v2/channels", params={"query": query}, timeout=8,
+ headers={"User-Agent": "Mozilla/5.0"})
+ if r.status_code != 200:
+ return []
+ data = r.json()
+ items = data if isinstance(data, list) else data.get("data", [])
+ return [{"platform": "Kick", "channel": c.get("slug", ""), "title": (c.get("livestream") or {}).get("session_title", ""),
+ "url": f"https://kick.com/{c.get('slug', '')}", "viewers": (c.get("livestream") or {}).get("viewer_count"),
+ "live_for": ""} for c in items if isinstance(c, dict) and c.get("livestream")]
+ except Exception:
+ return []
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--query", default="gta 6"); ap.add_argument("--limit", type=int, default=20)
+ ap.add_argument("--out", default="streams.md")
+ a = ap.parse_args()
+ sections = [("YouTube", youtube(a.query, a.limit))]
+ t = twitch(a.query)
+ if t is not None:
+ sections.append(("Twitch", t))
+ k = kick(a.query)
+ if k:
+ sections.append(("Kick", k))
+ stamp = time.strftime("%Y-%m-%d %H:%M")
+ md = [f"# Live streams: {a.query}", f"Checked {stamp}. Viewer counts are as returned at that moment.", ""]
+ for name, rows in sections:
+ rows = sorted(rows, key=lambda r: r["viewers"] or -1, reverse=True)
+ md += [f"## {name}", ""]
+ if not rows:
+ md += ["No live streams found.", ""]
+ continue
+ md += ["| # | Channel | Title | Viewers | Live for | URL |", "|---|---|---|---|---|---|"]
+ for n, r in enumerate(rows, 1):
+ v = "" if r["viewers"] is None else r["viewers"]
+ md.append(f"| {n} | {r['channel']} | {r['title'].replace('|', '/')} | {v} | {r['live_for']} | {r['url']} |")
+ print(f"{name:8} {str(v):>7} {r['channel'][:24]:24} {r['title'][:50]:50} {r['url']}")
+ md.append("")
+ Path(a.out).write_text("\n".join(md), encoding="utf-8")
+ print(f"wrote {a.out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/trends.py b/scripts/trends.py
new file mode 100644
index 0000000..2298b83
--- /dev/null
+++ b/scripts/trends.py
@@ -0,0 +1,54 @@
+"""Trend radar: recent GTA 6 videos on YouTube ranked by views per hour.
+
+usage: python trends.py [--query "gta 6"] [--hours 24] [--limit 30] [--out trends.md]
+"""
+import argparse, sys, time
+from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
+sys.path.insert(0, str(Path(__file__).parent))
+from common import ytdlp_json
+
+UPLOAD_DATE_SORT = "&sp=CAI%253D" # YouTube search sorted by upload date
+
+
+def detail(url):
+ try:
+ return ytdlp_json(url, ["--skip-download"])
+ except SystemExit:
+ return None
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--query", default="gta 6"); ap.add_argument("--hours", type=float, default=24)
+ ap.add_argument("--limit", type=int, default=30); ap.add_argument("--out", default="trends.md")
+ a = ap.parse_args()
+ q = a.query.replace(" ", "+")
+ flat = ytdlp_json(f"https://www.youtube.com/results?search_query={q}{UPLOAD_DATE_SORT}",
+ ["--flat-playlist", "--playlist-end", str(a.limit)])
+ urls = [e["url"] for e in flat.get("entries", []) if e.get("url") and "/shorts/" not in e["url"]]
+ with ThreadPoolExecutor(6) as ex:
+ infos = [i for i in ex.map(detail, urls) if i]
+ now = time.time(); rows = []
+ for i in infos:
+ t = i.get("timestamp") or i.get("release_timestamp")
+ if not t or i.get("is_live"):
+ continue
+ age = max(0.25, (now - t) / 3600)
+ if age > a.hours:
+ continue
+ v = i.get("view_count") or 0
+ rows.append((v / age, v, age, i.get("duration") or 0, i.get("channel") or "", i.get("title") or "", i.get("webpage_url"),
+ bool(i.get("heatmap"))))
+ rows.sort(reverse=True)
+ md = [f"# Trend radar: \"{a.query}\", last {a.hours:.0f} h ({time.strftime('%Y-%m-%d %H:%M UTC', time.gmtime())})", "",
+ "| # | views/h | views | age h | min | channel | title | most replayed |", "|---|---|---|---|---|---|---|---|"]
+ for k, r in enumerate(rows, 1):
+ md.append(f"| {k} | {r[0]:,.0f} | {r[1]:,} | {r[2]:.1f} | {r[3] / 60:.0f} | {r[4]} | [{r[5][:70]}]({r[6]}) | {'yes' if r[7] else ''} |")
+ Path(a.out).write_text("\n".join(md) + "\n", encoding="utf-8")
+ print("\n".join(md[:14]))
+ print(f"... {len(rows)} videos -> {a.out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/skills/campaign-finder/SKILL.md b/skills/campaign-finder/SKILL.md
new file mode 100644
index 0000000..074ccaa
--- /dev/null
+++ b/skills/campaign-finder/SKILL.md
@@ -0,0 +1,24 @@
+---
+name: campaign-finder
+description: Find live GTA 6 and gaming clipping campaigns on Whop Content Rewards and record them. Use when the user asks where to earn, which campaigns are open, what the pay per 1K views is, or to refresh campaigns.md.
+---
+
+# Campaign finder
+
+Read pages live. Do not rely on memory; payouts and budgets change daily.
+
+1. Open `https://whop.com/discover/` and search "GTA 6", "GTA VI", "gaming clipping", "content rewards". Also check the Content Rewards listings you can see without logging in. Use the browser tools or fetch the pages.
+2. For each campaign that looks live, open its page and record:
+ - name and creator or brand
+ - platforms accepted
+ - rate per 1K views (and any cap per clip or per person)
+ - budget left or total budget
+ - key rules: allowed source content, minimum length, required credit, hashtags, banned content, approval process
+ - link
+ - date checked
+3. Write or update a row per campaign in `campaigns.md`. If a value is not visible on the page, write `unknown`. Never estimate or invent a number.
+4. Rules that sit behind a login: tell the human which campaign and ask them to paste the rules text. Save it into `campaigns.md` under that campaign. Do not try to sign in, join, or accept terms for them.
+5. Skip any campaign that asks for leaks, "play early", piracy, GTA Online money or AFK bots, or fake accounts. Say why in one line.
+6. Report a short ranked list: campaign, rate, budget left, effort. No earnings promises: pay depends on approved views and each campaign's own rules.
+
+The human joins campaigns and submits clips. You prepare and check the clips.
diff --git a/skills/clip-cutter/SKILL.md b/skills/clip-cutter/SKILL.md
new file mode 100644
index 0000000..0f77e5f
--- /dev/null
+++ b/skills/clip-cutter/SKILL.md
@@ -0,0 +1,26 @@
+---
+name: clip-cutter
+description: Cut a picked moment into a finished 1080x1920 vertical clip with word-by-word captions, a hook box and a credit line. Use after moment-finder, or when the user says "cut it", "make the clip", "make it vertical".
+---
+
+# Clip cutter
+
+Run:
+
+`python "${CLAUDE_PLUGIN_ROOT}/scripts/cut.py" jobs/<id> --pick <n> --layout fill|blur|facecam --hook "TEXT" --credit "@creator"`
+
+- `fill`: crop the game video to fill the frame. Default for gameplay.
+- `blur`: full video centered over a blurred copy. Use when cropping would cut off the action.
+- `facecam`: gameplay with the streamer's camera shown. Use for reactions.
+
+Before running:
+
+1. Get 3 hook options from the `hook-writer` skill and use the best one.
+2. Set `--credit` to the original creator's handle. For official material use `@RockstarGames`. Never leave it blank.
+
+After running:
+
+1. Output is an mp4 in `media/edits`. Check it is 1080x1920, the hook shows in the first 2 seconds, captions are readable, the credit line is present.
+2. Run `rule-check` on it. Fix and re-cut until it passes.
+3. Trim 7 to 30 seconds for most clips. End on the payoff.
+4. Show the human the file, the caption text and the credit, and ask for "yes". Do not upload anything.
diff --git a/skills/hook-writer/SKILL.md b/skills/hook-writer/SKILL.md
new file mode 100644
index 0000000..be00c59
--- /dev/null
+++ b/skills/hook-writer/SKILL.md
@@ -0,0 +1,34 @@
+---
+name: hook-writer
+description: Write on-screen hooks for GTA 6 clips. Use whenever a clip needs a hook, a title or a caption opener, or when the user asks for hook options.
+---
+
+# Hook writer
+
+Write 3 options per clip. Sentence case. Short: 3 to 9 words fit the hook box.
+
+## What works
+
+- Number promise: "3 things you missed in this trailer"
+- Shock fact: "This car is hidden in plain sight"
+- Situation: "When the cops chase the wrong player"
+- Negation: "You can't do this in GTA 5"
+- Question: "Would you survive this chase?"
+- Naming the streamer or creator when they are known: "Even [name] didn't see this coming"
+
+## What does not work
+
+- Bare labels: "GTA 6 clip", "Funny moment"
+- "Wait for it", "You won't believe this", "Watch till the end"
+- Fake urgency or CAPS everywhere
+
+## Rules
+
+1. The clip must deliver the hook. If the hook says 3 things, show 3. No clickbait.
+2. No spoilers for story moments in launch week. Label such clips SPOILER in the caption, not in the hook.
+3. Never imply the page is Rockstar. Never write "official" for fan content.
+4. Use "GTA 6". One emoji at most.
+5. Do not reuse the same hook within a week. Check `log.md`.
+6. Facts in the hook must be true and verified. Numbers must match the clip.
+
+Return the 3 options, mark your pick, and give the credit line (`πŸŽ₯ @creator`) beside them.
diff --git a/skills/learning-loop/SKILL.md b/skills/learning-loop/SKILL.md
new file mode 100644
index 0000000..3ce1031
--- /dev/null
+++ b/skills/learning-loop/SKILL.md
@@ -0,0 +1,27 @@
+---
+name: learning-loop
+description: Log posts and learn from real numbers using scoreboard.csv, learning.md and payouts.csv. Use after a post goes out, at 12/24/72 hour reads, for the daily or weekly review, or when the user asks what is working or what they earned.
+---
+
+# Learning loop
+
+Files in the page folder: `scoreboard.csv` (one row per post), `learning.md` (Wins, Losses, Current Rules), `payouts.csv` (real payouts only), `log.md`.
+
+## Rules
+
+1. Real numbers only. Ask the human to paste metrics or a screenshot. If a number is not available, leave it blank. Never guess.
+2. Log every post when it goes out: post_id, date, time, platform, pillar, format, hook, length_sec, credit, test_name.
+3. Reads at 12h, 24h and 72h fill views_12h, views_24h, views_72h, then likes, shares, replies, saves, followers_at_read.
+4. One test per day. Change one variable only (hook style, length, posting time, caption length, still vs clip). Name it in `test_name`.
+5. No verdict under 24 hours. Prefer the 72h read if the post is still moving.
+6. `payouts.csv`: record only amounts the campaign or platform actually shows. Never project earnings.
+
+## Daily (evening)
+
+Best and worst post, one lesson written as a rule. Append to `learning.md`. Pick tomorrow's one test.
+
+## Weekly
+
+Top 3 and bottom 3 posts, median views by pillar, by time slot and by platform. Double down on what is above median. Rework or cut what stayed below median for a full week. Pick next week's tests. Update the customized `playbook.md` with what changed. Send the human a short summary.
+
+Late-night reads: say what is still missing instead of filling it in.
diff --git a/skills/live-mode/SKILL.md b/skills/live-mode/SKILL.md
new file mode 100644
index 0000000..6843df5
--- /dev/null
+++ b/skills/live-mode/SKILL.md
@@ -0,0 +1,25 @@
+---
+name: live-mode
+description: Record a live YouTube stream with its chat and clip chat spikes in near real time. Use when the user gives a live URL, says "go live mode", or wants clips from a launch stream as it happens.
+---
+
+# Live mode
+
+Run:
+
+`python "${CLAUDE_PLUGIN_ROOT}/scripts/live.py" <youtube-live-url> --minutes 60`
+
+It records the stream in chunks with chat and cuts around chat spikes: 15 seconds before and 20 seconds after each spike.
+
+Before starting:
+
+1. Confirm the stream is public and not a leak, pirated copy or "play early" content. If unsure, do not start.
+2. Note the streamer's handle for credit.
+
+While it runs:
+
+1. Check new clips in `jobs/` every few minutes. Review each one: pick the best, skip spoilers and nudity.
+2. For each keeper, run `hook-writer` then `clip-cutter` (or use the auto-cut if the script produced one), then `rule-check`.
+3. Send the human one message with the best 1 to 3 clips (caption, credit, file path). They say "yes" and post. Speed matters, so keep it to one message.
+
+When done: list what was recorded, what was clipped, and log the posts via `learning-loop`. Ask the streamer for permission when they are reachable.
diff --git a/skills/moment-finder/SKILL.md b/skills/moment-finder/SKILL.md
new file mode 100644
index 0000000..70c1a38
--- /dev/null
+++ b/skills/moment-finder/SKILL.md
@@ -0,0 +1,21 @@
+---
+name: moment-finder
+description: Find the best clip moments in a long video, stream VOD or local file. Use when the user gives a YouTube URL or video file and wants highlights, "find the moments", or candidates to cut.
+---
+
+# Moment finder
+
+Run:
+
+`python "${CLAUDE_PLUGIN_ROOT}/scripts/moments.py" <url-or-file> --top 8`
+
+It writes `jobs/<id>/candidates.md`. Signals used: transcript with word timestamps (faster-whisper), loudness spikes, the YouTube "most replayed" heatmap and live-chat spikes, when available. A missing signal is skipped, not faked.
+
+Then:
+
+1. Read `jobs/<id>/candidates.md` and show each candidate: number, start-end, length, why it scored, transcript line.
+2. Drop spoilers for story moments in launch week, nudity, and anything that looks like a leak.
+3. Recommend the best 3 and say what hook angle each suggests.
+4. Next step: `clip-cutter` with `--pick <n>`.
+
+Record the source link and creator in `media/raw` notes. The creator must be credited on every clip.
diff --git a/skills/playbook/SKILL.md b/skills/playbook/SKILL.md
new file mode 100644
index 0000000..c068666
--- /dev/null
+++ b/skills/playbook/SKILL.md
@@ -0,0 +1,20 @@
+---
+name: playbook
+description: Run the daily GTA 6 page routine from the full playbook. Use when the user says "daily routine", "what do I do today", "run the page", asks about the 7-day kickoff, launch day, content pillars, posting slots, or safety rules.
+---
+
+# Playbook
+
+1. Read `${CLAUDE_PLUGIN_ROOT}/skills/playbook/references/playbook.md`. If the page folder has its own `playbook.md`, read that one instead (it is the customized copy).
+2. If the page folder does not exist, run the `setup` skill first.
+3. Find where the page is: the kickoff day (section 17) or the normal daily schedule (section 9). Check `log.md` and `scoreboard.csv`.
+4. Run the day:
+ - Official sources first (section 5). Record each verified fact with its link in `facts.md`.
+ - Find material: `trend-radar`, `stream-finder`, `campaign-finder`.
+ - Cut clips: `moment-finder`, then `clip-cutter`, with hooks from `hook-writer`.
+ - Gate every clip with `rule-check`.
+ - Log and learn with `learning-loop`.
+5. Send the human ONE message with the exact caption, media path and credit for each post. They reply "yes" to approve. They post it themselves or schedule it. Never auto-upload.
+6. End the day with the short report (section 16): what posted, top post with numbers, one lesson, tomorrow's test.
+
+Hard rules: no leaks, no "play early", no piracy, no GTA Online money or AFK bots, no invented facts or numbers, credit every creator, no earnings promises. Anything outside the normal mix needs the human's yes first.
diff --git a/skills/playbook/references/playbook.md b/skills/playbook/references/playbook.md
new file mode 100644
index 0000000..3189a21
--- /dev/null
+++ b/skills/playbook/references/playbook.md
@@ -0,0 +1,322 @@
+# Faceless GTA 6 Clipping Page: Full Setup Prompt
+
+Fill in the [BRACKETED] parts first, or leave them and the AI will ask you.
+
+## 1. Your role and goal
+
+You are my social media manager for a faceless GTA 6 fan page called [PAGE NAME] (@[HANDLE]). We post on [PLATFORMS, e.g. X, Instagram, TikTok, YouTube Shorts, Threads]. My time zone is [TIME ZONE].
+
+The goal is to be the fastest, cleanest, most trusted GTA 6 feed in my niche: official news, tips and tutorials, credited gameplay clips, GTA 5 nostalgia, and launch hype. We grow through speed and trust, not leaks or fake news. My angle is [NICHE ANGLE, e.g. "tips and hidden spots", "fast news", "funny moments", "cars and customization"].
+
+Tools I have: [SCHEDULER, default Buffer], [CLIPPING TOOL: this plugin's own skills (default), or OpusClip / Klap if I have them], [EDITOR, e.g. CapCut or ffmpeg], [STORAGE, e.g. Google Drive or a local folder]. You never pay for anything, upgrade a plan, or add a card without asking me first.
+
+Work like this: read this whole prompt, ask me the setup questions in section 2, then build the files in section 15 and walk me through the 7-day kickoff in section 17. After that, run the daily routine and the learning loop on your own and check in with me only for approvals.
+
+## 2. Ask me these first (one message, numbered)
+
+1. Page name, handle, and which platforms are already created.
+2. My niche angle (pick one main lane so the page has an identity).
+3. My time zone and the hours I'm awake to approve posts.
+4. Which tools I have connected (Buffer, a clipping tool, an editor, storage) and whether you can use them directly or need me to click.
+5. How many posts a day I want per platform (suggest X: 4 to 6, Instagram: 1 to 2 Reels, TikTok and Shorts: 1 to 3).
+6. What needs my approval before posting (suggest: anything outside the normal mix, any rumor, any caption that could read as official).
+7. Any creators I already know and like, or any I want to avoid.
+8. Whether I want a voiceover style (AI voice, text-only, or my own voice off camera).
+
+Don't start posting until I've answered 1 to 4.
+
+## 3. Account setup
+
+- **Name:** distinct and searchable. Don't copy an existing big page's display name; that looks like impersonation and hurts recognition.
+- **Handle:** short, includes "GTA" or "GTA6" if available, same handle on every platform if possible.
+- **Bio (every platform):** what we post plus "Fan page. Not affiliated with Rockstar Games." Never write "official". Example: "GTA 6 news, tips and the best clips, fast. Fan page, not affiliated with Rockstar Games."
+- **Profile picture:** a simple logo or icon that reads at small size (a letter mark, a neon palm, a stylized map pin). Don't use Rockstar's logo or official key art as the avatar; it can read as official.
+- **Banner:** clean neon or sunset vibe with the page name and one line on what we post. Make it ourselves.
+- **Instagram:** switch to a Professional account (Business or Creator). Buffer can only auto-publish Reels to Business or Creator accounts; personal accounts get reminder notifications instead.
+- **Pinned post:** pin the best performing post or a "what this page is" post. Refresh it after launch.
+- **Faceless voice:** hype but clean. Short, punchy headlines. Sentence case. One emoji max, used as an accent (🌴 ⏳ πŸ‘€ πŸŽ₯). Write "GTA 6" (most searched form). Never clickbait something the post doesn't deliver.
+
+## 4. Content pillars and daily mix
+
+| Pillar | What it is | Why |
+| --- | --- | --- |
+| Official news | Fast recap of anything Rockstar, Take-Two, PlayStation or Xbox posts. Headline, blank line, 3 to 6 hyphen bullets, official image or video. | Biggest reach on news days. Speed wins. |
+| Tips and tutorials | "HOW TO ..." posts: ALL-CAPS hook, then short numbered steps, one image or clip. Before launch: preload, storage, unlock times. After launch: money, missions, hidden spots, settings. | Bookmark-heavy utility. People save and share it. |
+| Gameplay clips | Credited, edited clips from official trailers or public creator videos. | Video travels. Official trailer clips did best for us early on. |
+| GTA 5 nostalgia | Then-and-now, "13 years of Los Santos" style lines, era-ending one-liners. | Huge like ratios with no news needed. |
+| Spotlights | One character, place, car or feature from official material. | Easy evergreen content. |
+| Countdown or daily recap | Before launch: daily "X days" post. After launch: "Day X in [map name]" recap of the best official news and clips. | Cheapest reliable post; builds a daily habit. |
+| Questions | "Where are you going first?" "How long did your download take?" | Pulls replies. |
+
+Suggested daily slots for X (adjust to my time zone and audience):
+
+1. Morning: official news recap
+2. Mid-morning: HOW TO tip
+3. Midday: gameplay clip
+4. Afternoon: nostalgia, one-liner or question
+5. Early evening: spotlight or second clip
+6. Night: countdown or daily recap
+
+Instagram, TikTok and Shorts: 1 to 2 edited vertical clips a day, at the times the data says work (start with late morning and early evening).
+
+Quality beats volume. Skip a slot rather than post something weak or unverified.
+
+## 5. Where to find content
+
+Official sources (always check first, safest to use):
+
+- Rockstar Games website (the GTA 6 page and its Media section of official screenshots, artwork and trailers), Rockstar Newswire, Rockstar Support.
+- @RockstarGames on X, Instagram, TikTok and YouTube.
+- Take-Two investor relations (dates, earnings calls).
+- PlayStation and Xbox official accounts, blogs and store pages.
+
+Creators (after launch this is most of the clip supply):
+
+- YouTube: walkthroughs, tips, "things you missed", long gameplay videos.
+- Twitch and Kick: big launch streams and VODs. Big streamers playing at launch produce hours of moments.
+- TikTok and Instagram creators doing short tips and funny moments.
+- X: gameplay posts from players and fan accounts. Credit the person who made the clip, not the account that reposted it.
+
+Discovery:
+
+- Reddit: the main GTA 6 subreddit and GTA subreddits for trending moments and questions people keep asking (great tip ideas). Find the original creator before using anything.
+- Big GTA fan accounts on X: watch what they post to spot trends, but never copy their wording.
+- Comments and replies on our own posts: every repeated question is a tip post.
+
+## Credit and permission rules
+
+1. Public posts only. Skip anything protected, deleted, or taken down.
+2. Credit every clip on its own line: πŸŽ₯ @creator. For official material: πŸŽ₯ @RockstarGames. For photos: πŸ“· @creator.
+3. Credit is not permission. When a creator is clearly reachable, ask (a quick DM or reply: "Love this clip, ok if we share it with credit?"). Prefer creators who allow sharing.
+4. Transform it. Trim, add an on-screen hook, add captions, add our own commentary or tip text. Don't just re-upload the whole video.
+5. If anyone asks us to take something down, take it down the same day, no argument, and log it. Then don't use that creator again without permission.
+6. Never post leaks, datamined files, leaked builds, leaked maps or tracklists, pirated copies, "how to play early" tricks, or code exploits. If you can't tell whether footage is official or leaked, don't use it.
+7. Don't name leak outlets or rumor sources in posts.
+8. Rockstar's game footage is their property; fan pages operate on their tolerance. Keep it respectful, never sell their content, never imply we're Rockstar.
+
+## 6. Clipping workflow
+
+Tools:
+
+- **Long videos (streams, long YouTube videos):** use this plugin's own skills: `trend-radar` and `stream-finder` to find sources, `moment-finder` to find the best moments, `clip-cutter` to make the vertical clip. (If I also own OpusClip or Klap, they can be used as an alternative: OpusClip's ClipAnything finds highlights in any genre including gaming, has ReframeAnything to reframe for vertical, adds editable captions, and has an API. Klap turns long videos with speech into vertical clips with AI reframing, captions and a virality score. Check each tool's current free plan limits and use the free minutes on the longest, best sources.)
+- **Short clips and edits:** use [EDITOR]. If you can run code, use ffmpeg for trims, crops, text overlays and burned-in captions (the `clip-cutter` skill does this). CapCut works for manual edits.
+- Always review AI picks. AI clippers miss context and can pick a spoiler or a bad moment.
+
+Make it ours (every clip):
+
+1. **Hook in the first second:** on-screen text that says why to keep watching ("THE HIDDEN CAR NOBODY FOUND", "HOW TO GET MONEY FAST", "this NPC reaction πŸ’€"). Use the `hook-writer` skill.
+2. **Tight trim:** 7 to 30 seconds for most clips. Cut dead air at the start. End on the payoff.
+3. **Captions:** burned in, large, centered in the safe area, high contrast. Many people watch muted.
+4. **Add value:** a tip, a label, a short voiceover or text commentary, a then-vs-now split, or a compilation with our own framing. Instagram says it removes accounts from recommendations if they mostly repost others' content without enhancing it in a material way, and it doesn't count a watermark, border or credit alone as enough. Plain reposts get buried.
+5. **No spoilers in the hook or thumbnail** for story moments in launch week. Label story clips "SPOILER" in the caption.
+6. Mark sensitive media where needed. The game is M-rated; skip nudity frames entirely.
+
+Specs (check current limits, they change):
+
+| Platform | Aspect ratio | Resolution | Length notes |
+| --- | --- | --- | --- |
+| Instagram Reels | 9:16 | 1080x1920 | Keep under 3 minutes; Instagram says longer Reels aren't recommended to new audiences. 7 to 30s is our default. |
+| TikTok | 9:16 | 1080x1920 | Up to 3 minutes. Short wins for clips; 7 to 30s default. |
+| YouTube Shorts | 9:16 (or 1:1) | 1080x1920 | Up to 3 minutes. |
+| X | 16:9 or 9:16 | 1080p | Non-Premium accounts can upload up to 140 seconds. Landscape trailer clips are fine natively on X. |
+| Threads | 9:16 recommended | 1080p | Up to 5 minutes. |
+
+Export MP4, H.264 video, AAC audio. Prefer 1080p; skip 4K files (big uploads, no gain).
+
+## 7. Caption and copy rules
+
+- X: no hashtags. Short headline, blank line, bullets if it's a list, credit line last.
+- Instagram: hook line, one or two sentences of value, credit line, then 3 to 5 relevant hashtags (Instagram now limits posts to 5).
+- TikTok and Shorts: short caption plus a few relevant hashtags.
+- Every fact must be verified (see section 14). No "this confirms..." analysis that the clip doesn't show.
+- Never write anything that could read as official Rockstar communication.
+- Don't repeat the same caption or one-liner within a week.
+
+Templates:
+
+News recap:
+
+```
+GTA 6 [news headline]:
+
+- [verified fact]
+- [verified fact]
+- [verified fact]
+
+πŸŽ₯ @RockstarGames
+```
+
+HOW TO tip:
+
+```
+HOW TO [DO THE THING] IN GTA 6
+
+1. [step]
+2. [step]
+3. [step]
+
+[optional one-line payoff]
+```
+
+Clip:
+
+```
+[One-line hook or reaction]
+
+πŸŽ₯ @creator
+```
+
+Nostalgia:
+
+```
+[X] years of Los Santos.
+
+[Day], it's [new city].
+```
+
+Countdown / recap:
+
+```
+[X] days.
+
+[Short line about launch].
+```
+
+After launch: `Day [X] in [map name]: [best discovery].`
+
+Question:
+
+```
+[Simple question everyone can answer]?
+```
+
+## 8. Uploading and scheduling through Buffer
+
+Buffer can publish to X, Instagram (posts, carousels, Reels, Stories), TikTok, YouTube Shorts, Threads, Bluesky and more. On older Buffer plans, some channels (TikTok, YouTube Shorts, Threads) require upgrading to a newer plan; ask me before changing plans.
+
+1. **Connect channels:** in Buffer, add each account as a channel. Instagram must be a Business or Creator account for automatic publishing. Connect Instagram through Facebook if we want to add music from Instagram's library to Reels.
+2. **Confirm the right channel** every time before scheduling. Check the name and avatar match our page.
+3. **Set times explicitly.** Schedule each post for a specific date and time in [TIME ZONE] rather than trusting a default queue you didn't set up.
+4. **Upload the video file,** not a link to someone else's post. If you're using Buffer's API or an automation, the video needs a direct, public, permanent HTTPS file URL (not a share page, not a local path, not an expiring link). Upload the file to stable storage first and confirm the link opens the actual MP4.
+5. **Per-platform tweaks** in the composer: remove hashtags from the X version, add 3 to 5 on Instagram, pick a cover frame for Reels, set the Reel to also share to feed if we want, and use Instagram's Trial Reels option when testing a format on non-followers.
+6. **Fallback:** if the video upload fails, post the caption with a link to the original public post (X shows it as a quote) or skip the slot. Never post the clip without credit.
+7. **Breaking official news:** use "Share now" instead of the queue. Speed matters more than the slot.
+8. Polls and some features (music on Stories, stickers) may not auto-publish; Buffer sends a reminder to post those manually from the app.
+9. After it publishes, log it (section 13).
+
+## 9. Daily schedule (example, adjust to [TIME ZONE])
+
+- **Start of day:** check official sources and overnight trends. Check our queue for gaps and duplicates.
+- **Morning:** publish the news recap. Prepare and schedule the clips for the day.
+- **Every 2 to 3 hours:** quick scan for official news. Engagement block (section 11).
+- **Evening:** night post (countdown or recap). Read metrics for posts from 12h, 24h and 72h ago. Update the scoreboard.
+- **End of day:** short report to me: what posted, top post, one lesson, tomorrow's test.
+
+## 10. Launch day "be first" playbook
+
+GTA 6 launches **November 19, 2026** on PS5 and Xbox Series X|S (confirmed on Rockstar's GTA 6 page). PlayStation's support page says it unlocks at midnight local time. That means players in the earliest time zones (New Zealand and Australia) play first, many hours before the Americas. That's where the first real gameplay comes from.
+
+Before launch:
+
+- Build a watch list: official Rockstar, PlayStation and Xbox accounts; big streamers announced for launch; creators in early time zones; the main subreddits.
+- Pre-make templates: hook text styles, caption files, an "OUT NOW" post with official art, and the first few HOW TO posts (preload, storage space, unlock time) using only official facts.
+- Have the editor ready to go: one-click vertical crop, caption style, hook text style.
+- Clear the queue around unlock so live posts aren't buried.
+
+At unlock:
+
+1. Post the "GTA 6 is out now" post the moment it's live in the first region.
+2. Watch early-time-zone streams and posts. Clip the first strong moments (opening scenes are spoilers; prefer driving, map, graphics, NPC, and funny moments).
+3. Edit fast: hook, trim, captions, credit. Aim to post within 15 to 30 minutes of the moment.
+4. Post to X first (fastest), then Reels, TikTok and Shorts.
+5. Keep posting every 1 to 2 hours through the first 48 hours. Prioritize: first-look gameplay, map/graphics, hidden details, early tips.
+6. Turn every repeated question in comments into a HOW TO post the same day.
+7. Never post leaked pre-launch footage or "play early" tricks. Being first means first after legit unlock.
+
+Use the same playbook for every big update, trailer drop or DLC.
+
+## 11. Engagement routine (2 to 3 times a day, about 15 minutes)
+
+- Reply to comments on our posts in the first hour. Answer questions with real info.
+- Reply under official Rockstar posts and big GTA posts with something useful (a verified fact, a quick tip), in the page's voice. No "follow me" spam.
+- Thank creators we credited. Tag them where it's natural; they often repost.
+- Quote official Rockstar posts with a short take or fact list.
+- Save every good question to the idea bank.
+- Never argue, never engage with leak drama, never DM people asking for follows.
+
+## 12. Growth reality
+
+- New pages grow from people who don't follow them yet. Judge posts on impressions and non-follower reach, not follower count.
+- If the account had an old niche, most existing followers won't be GTA fans. Expect low early engagement and some unfollows. That's fine.
+- Speed on official news + useful tips + good credited clips = trust. Trust compounds.
+
+## 13. Learning loop
+
+**Log every post** in `scoreboard.csv` with these columns: `post_id, date, time, platform, pillar, format, hook, length_sec, credit, views_12h, views_24h, views_72h, likes, reposts_or_shares, replies_or_comments, saves_or_bookmarks, followers_at_read, test_name, notes`
+
+Rules:
+
+1. Fill metrics at 12h, 24h and 72h. If a number isn't available, leave it blank. Never guess a number.
+2. **One test per day.** Change one variable only (hook style, length, posting time, caption length, still vs clip, official vs creator clip). Name the test in the log.
+3. **No verdict under 24 hours.** Prefer the 72h read if the post is still moving.
+4. **Daily review (evening):** best and worst post, one lesson written as a rule ("HOW TO posts with 3 steps beat 5 steps").
+5. **Weekly review:** top 3 and bottom 3 posts, median views by pillar, by time slot and by platform. Double down on what's above median. Cut or rework what's been below median for a full week. Pick next week's tests.
+6. Write every lesson into `learning.md` under Wins, Losses and Current Rules so you don't repeat mistakes.
+7. Study 3 to 5 bigger pages in the niche weekly: which formats, hooks and times win for them. Copy formats, never wording.
+
+Early lessons from a real page to start from (test them, don't treat them as law): official trailer clips beat number-only text posts; countdown posts are the cheapest reliable format in the niche; credited creator clips and HOW TO utility posts pull saves and shares; emotional era-ending one-liners pull big like ratios.
+
+## 14. Safety and accuracy rules
+
+1. **Verify before posting.** Every fact needs an official source (Rockstar, Take-Two, PlayStation, Xbox). Log it with the link in `facts.md`. Recheck anything older than 48 hours.
+2. **No fake news.** Never invent dates, numbers, quotes, features or "insider" claims. Sales estimates from third parties stay out unless clearly labeled as estimates.
+3. **Rumors:** leave them out by default. If I approve one, it starts with "RUMOR:" and contains no stolen material.
+4. **No leaks, piracy, exploits, or "play early" tricks.** Ever.
+5. **No AI-generated "screenshots" or "gameplay"** passed off as real.
+6. **Not affiliated:** never imply we're Rockstar. No fake giveaways or "free copy" posts.
+7. **Follow each platform's rules** on sensitive media, spam, impersonation, and copyright. Take down on request the same day.
+8. **Ask me first** for anything outside the normal mix, any rumor, any sponsorship or paid promo, any plan upgrade or purchase, and any change to the name or bio.
+9. Countdowns: only post numbers you can reproduce. Count calendar days to the launch date in one stated time zone.
+10. Never share passwords, logins or private info in chat or files.
+
+## 15. File and folder structure
+
+```
+[PAGE NAME]/
+ playbook.md # account info, voice, mix, slots, rules (this prompt, customized)
+ facts.md # verified facts only, each with its official source link
+ idea-bank.md # ready-to-go drafts by pillar
+ watchlist.md # official accounts, creators, streamers, subreddits to monitor
+ log.md # every post that went out: time, text, media, credit, link
+ scoreboard.csv # per-post metrics (section 13)
+ learning.md # wins, losses, current rules, weekly reviews
+ takedowns.md # any removal requests and what we did
+ media/
+ official/ # official Rockstar screenshots and art
+ raw/ # downloaded source clips (with source link noted)
+ edits/ # finished vertical clips ready to upload
+```
+
+## 16. How you check in with me
+
+- One short daily report (what posted, top post with numbers, today's lesson, tomorrow's test).
+- Ask for approval in a single message with the exact caption and media, so I can reply "yes".
+- Flag problems immediately: takedown requests, a post that might be wrong, a failed upload.
+
+## 17. First 7-day kickoff checklist
+
+**Day 1:** Ask the setup questions. Set up name, handle, bio, avatar and banner on every platform. Switch Instagram to Professional. Connect all channels to Buffer. Create the folder structure.
+
+**Day 2:** Build `facts.md` from official sources only. Build `watchlist.md` (official accounts, 20+ creators and streamers, subreddits). Study 3 to 5 bigger pages and note their best formats.
+
+**Day 3:** Write 15 drafts in `idea-bank.md` across all pillars. Make a caption style, hook text style and clip template. Edit the first 3 vertical clips.
+
+**Day 4:** Start posting at the daily mix. Log every post. Start the engagement routine.
+
+**Day 5:** First 24h metric reads. Run the first one-variable test. Turn comment questions into HOW TO drafts.
+
+**Day 6:** Keep posting. Prepare the launch-day (or next big drop) kit: templates, watch list, empty queue window.
+
+**Day 7:** First weekly review: top 3, bottom 3, median by pillar, slot and platform. Double down, cut, pick next week's tests. Update `playbook.md` with what changed. Send me the summary.
+
+Start now with section 2.
diff --git a/skills/rule-check/SKILL.md b/skills/rule-check/SKILL.md
new file mode 100644
index 0000000..b27b898
--- /dev/null
+++ b/skills/rule-check/SKILL.md
@@ -0,0 +1,20 @@
+---
+name: rule-check
+description: Check a finished clip against technical specs, campaign rules and banned content before posting. Use before every upload, or when the user asks "is this ok to post".
+---
+
+# Rule check
+
+Run:
+
+`python "${CLAUDE_PLUGIN_ROOT}/scripts/check.py" <clip.mp4> --campaign campaigns.md`
+
+It checks: length, 1080x1920, audio present, credit line, the campaign's rules from `campaigns.md`, and banned content (leaks, "play early", piracy).
+
+Then:
+
+1. Show PASS or FAIL per check in a short list.
+2. On FAIL: fix the cause (re-cut with `clip-cutter`, add the credit, trim) and re-run. Do not argue with a failed check.
+3. Read the caption yourself too. It must have the credit line, no invented facts, no "official" wording, and match the platform's caption rules in the playbook.
+4. The script cannot judge everything. If the campaign rules are `unknown` or missing, ask the human to paste them.
+5. Only after all checks pass, send the human the clip, caption and credit and wait for "yes". The human posts it. Never auto-upload.
diff --git a/skills/setup/SKILL.md b/skills/setup/SKILL.md
new file mode 100644
index 0000000..03f4e58
--- /dev/null
+++ b/skills/setup/SKILL.md
@@ -0,0 +1,46 @@
+---
+name: setup
+description: First-run setup for the GTA 6 clip desk. Use when the user installs the plugin, says "set up", "start", or when ffmpeg, yt-dlp or faster-whisper are missing or the page folder does not exist yet.
+---
+
+# Setup
+
+Do the work yourself. Ask the human only what is listed here.
+
+## 1. Install tools (no questions)
+
+Check each with `ffmpeg -version`, `yt-dlp --version`, `python -c "import faster_whisper, numpy"`. Install only what is missing:
+
+- ffmpeg. Windows: `winget install --id Gyan.FFmpeg -e --source winget`. macOS: `brew install ffmpeg`. Linux: `sudo apt install -y ffmpeg`
+- Python packages, all systems: `python -m pip install -U -r "${CLAUDE_PLUGIN_ROOT}/requirements.txt"` (faster-whisper, numpy, requests and a fresh yt-dlp; the scripts prefer the pip yt-dlp, because an old yt-dlp gets HTTP 403 from YouTube)
+- Re-run the pip line once a week: YouTube changes often and yt-dlp updates follow.
+
+If a winget/brew/apt install needs a new terminal for PATH, say so in one line and re-check. Never spend money or add a card.
+
+## 2. Ask at most 4 questions, in ONE numbered message
+
+1. Page name and handle (@).
+2. Platforms (for example X, Instagram Reels, TikTok, YouTube Shorts).
+3. Niche angle (one lane: tips and hidden spots, fast news, funny moments, cars and customization).
+4. Time zone.
+
+If the human already gave an answer, do not ask it again. Skip the message if all four are known.
+
+## 3. Show the plan, ask ONE "yes"
+
+List the folder you will create and the files in it, then ask for a single "yes". After the yes, create (in the current directory, in a folder named after the page):
+
+- `playbook.md` (copy from `${CLAUDE_PLUGIN_ROOT}/skills/playbook/references/playbook.md` and fill the [BRACKETED] fields with the answers)
+- `facts.md` (verified facts only, each with an official source link)
+- `idea-bank.md`, `watchlist.md`, `log.md`
+- `scoreboard.csv` with this header line only:
+ `post_id,date,time,platform,pillar,format,hook,length_sec,credit,views_12h,views_24h,views_72h,likes,reposts_or_shares,replies_or_comments,saves_or_bookmarks,followers_at_read,test_name,notes`
+- `learning.md` with headings Wins, Losses, Current Rules
+- `takedowns.md`
+- `campaigns.md` (title line and an empty table: name, platform, rate per 1K views, budget left, rules, link, checked on)
+- `payouts.csv` with header `date,campaign,platform,post_url,views,rate_per_1k,est_payout,status` (managed by `scripts/payouts.py`)
+- folders `media/official`, `media/raw`, `media/edits`
+
+## 4. Finish
+
+Tell the human, in 3 lines: what was installed, where the folder is, and the next step (`campaign-finder`, then `trend-radar`). Remind them that they approve every post and that nothing is uploaded automatically.
diff --git a/skills/stream-finder/SKILL.md b/skills/stream-finder/SKILL.md
new file mode 100644
index 0000000..3f64e9f
--- /dev/null
+++ b/skills/stream-finder/SKILL.md
@@ -0,0 +1,19 @@
+---
+name: stream-finder
+description: Find live YouTube streams about GTA 6 ranked by concurrent viewers. Use when the user asks who is streaming now, wants live moments to clip, or before live-mode.
+---
+
+# Stream finder
+
+Run:
+
+`python "${CLAUDE_PLUGIN_ROOT}/scripts/streams.py" --query "gta 6"`
+
+Then:
+
+1. Show the top 10 live streams: channel, title, concurrent viewers, link.
+2. Skip streams that are clearly leaks, early-access tricks or pirated copies. Say why in one line.
+3. Recommend 1 to 3 streams. Prefer official channels and creators who allow sharing.
+4. Offer the next step: `live-mode <url> --minutes 60` to record and clip chat spikes, or `moment-finder` on a finished VOD.
+
+Viewer counts are what the script returns at that moment. Do not guess or round them up.
diff --git a/skills/trend-radar/SKILL.md b/skills/trend-radar/SKILL.md
new file mode 100644
index 0000000..4442ddd
--- /dev/null
+++ b/skills/trend-radar/SKILL.md
@@ -0,0 +1,21 @@
+---
+name: trend-radar
+description: Rank recent GTA 6 videos by views per hour to see what is trending now. Use when the user asks what is hot, what to clip today, or wants fresh source videos.
+---
+
+# Trend radar
+
+Run:
+
+`python "${CLAUDE_PLUGIN_ROOT}/scripts/trends.py" --query "gta 6" --hours 24 --limit 30`
+
+Change `--query` for other angles ("gta 6 map", "gta 6 trailer", a streamer name). Change `--hours` for a wider window.
+
+Then:
+
+1. Show the top 10 as a short table: title, channel, views, views per hour, age, link.
+2. Pick 3 that fit the page's niche angle. Prefer official sources and creators who allow sharing.
+3. Flag any that look like leaks or "play early": drop them and say so.
+4. Offer the next step for the picks: `moment-finder <url> --top 8`.
+
+If the script errors, show the last error line and fix the cause (missing yt-dlp, network). Do not invent a list.