Skip to content
Python

React clips: no on-video credit, exact 1080x1920, cam edge snapping, face tracking, skip non-gameplay, slur and swear masking

Bodila512aee0c6568f0
diff --git a/README.md b/README.md
index c7d93c8..cb3a317 100644
--- a/README.md
+++ b/README.md
@@ -28,7 +28,7 @@ Two lines in Claude Code. In 10 minutes you have: the tools installed, your page
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.
+with hooks, check them against the campaign rules, and tell me what to post where.
```
## Two ways to make money
@@ -44,7 +44,7 @@ No income is promised. Your result depends on speed, picks and hooks, and the sc
- 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.
+- Make it yours: hook, tip, commentary. Never a plain re-upload. Credit the creator in your post.
- 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.
@@ -60,9 +60,9 @@ No income is promised. Your result depends on speed, picks and hooks, and the sc
| `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 |
| `twitch-reaction` | Reaction clips like the viral ones: the streamer's face on top, the game below, a big title on the seam. Finds the top GTA 6 Twitch streams with no account, reads chat and finds the webcam by itself |
-| `clip-cutter` | 1080x1920 clip: word-by-word captions, hook box, credit line, -14 LUFS. Fill, blurred background or facecam on top |
+| `clip-cutter` | 1080x1920 clip: word-by-word captions, hook box, -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 |
+| `rule-check` | Length, format, hashtags and banned content checked before you post |
| `multilang` | One clip in 5 languages: translated word-by-word captions and hook in ES, PT, DE, RU, optional stock-voice hook. Non-English GTA pages are almost empty |
| `questions-to-posts` | Pulls repeated questions from GTA subreddits and your comments, turns the answered ones into HOW TO posts |
| `secrets-map` | Builds a database of hidden spots, money, cars and collectibles from clips, with timestamp and credit. Verified ones become evergreen tip posts |
@@ -83,7 +83,7 @@ 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/cut.py jobs/<id> --pick 2 --layout facecam --hook "Nobody noticed this"
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
```
diff --git a/scripts/check.py b/scripts/check.py
index a9a1ead..c71ad73 100644
--- a/scripts/check.py
+++ b/scripts/check.py
@@ -69,10 +69,6 @@ def main():
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))
diff --git a/scripts/cut.py b/scripts/cut.py
index 8f38584..926ae82 100644
--- a/scripts/cut.py
+++ b/scripts/cut.py
@@ -1,9 +1,9 @@
"""Cut one candidate into a finished vertical clip.
-1080x1920, 30 fps, word-by-word burned captions, hook box in the first seconds, credit line,
+1080x1920, 30 fps, word-by-word burned captions (slurs and swears masked), hook box in the first seconds,
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|react] [--hook "TEXT"] [--credit "@creator"]
+usage: python cut.py jobs/<id> --pick 1 [--layout fill|blur|facecam|react] [--hook "TEXT"]
[--cam auto|x:y:w:h] [--title "TEXT" --title-style box|outline --title-secs 0] [--captions word|bubble|none]
"""
import argparse, sys
@@ -19,6 +19,24 @@ def ts(t):
return f"{h}:{m:02d}:{s:05.2f}"
+import re as _re
+_SLURS = _re.compile(r"\b(nigg\w*|n[i1]gg?a\w*|f[a@]gg?\w*|retard\w*|tranny\w*|chink\w*|spic\w*|kike\w*)\b", _re.I)
+
+
+_SWEARS = _re.compile(r"\b(fuck\w*|motherfuck\w*|shit\w*|bitch\w*|cunt\w*|dick\w*|pussy\w*|asshole\w*|bastard\w*|whore\w*|slut\w*)\b", _re.I)
+
+
+def _mask(m):
+ w = m.group(0)
+ return w[0] + '*' * (len(w) - 1)
+
+
+def clean(s, profanity=False):
+ """Slurs are always masked (n-word -> n****); hard swears too unless profanity=True."""
+ s = _SLURS.sub(_mask, s)
+ return s if profanity else _SWEARS.sub(_mask, s)
+
+
def esc(s):
return s.replace("\\", "").replace("{", "(").replace("}", ")").replace("\n", " ")
@@ -33,7 +51,7 @@ def wrap(text, width):
return lines + ([cur] if cur else [])
-def build_ass(words, s0, e0, hook, credit, cap_y, title=None, caps='word'):
+def build_ass(words, s0, e0, hook, cap_y, title=None, caps='word', profanity=False):
hdr = f"""[Script Info]
ScriptType: v4.00+
PlayResX: {W}
@@ -44,7 +62,6 @@ WrapStyle: 0
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
Style: TitleBox,Arial Black,66,&H00000000,&H00000000,&H00FFFFFF,&H00FFFFFF,-1,0,0,0,100,100,0,0,1,0,0,5,40,40,0,1
Style: TitleOut,Arial Black,80,&H00FFFFFF,&H00FFFFFF,&H00000000,&H64000000,-1,0,0,0,100,100,0,0,1,9,2,8,50,50,0,1
Style: Bubble,Arial,58,&H00000000,&H00000000,&H00FFFFFF,&H00FFFFFF,-1,0,0,0,100,100,0,0,3,16,0,5,60,60,0,1
@@ -53,7 +70,7 @@ Style: Bubble,Arial,58,&H00000000,&H00000000,&H00FFFFFF,&H00FFFFFF,-1,0,0,0,100,
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"]]
+ ws = [dict(w, w=clean(w["w"], profanity)) 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:
@@ -94,16 +111,19 @@ Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
hook = ''
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"
CAP_Y = {"fill": 1380, "blur": 1460, "facecam": 1120, "react": 1560}
-TOP = int(H * 0.38) # react layout: facecam height
+TOP = 730 # react layout: face panel height = seam y (even)
+GAME_H = H - TOP # 1190
+
+
+def even(n):
+ return int(n) // 2 * 2
-def video_filter(layout, cam, ass, band=None, cam_side='right'):
+def video_filter(layout, cam, ass, band=None, cam_side='right', src=None, game_x=None, face_expr=None):
"""Layout + burned-caption filter graph ending in [vo]. Reused by translate.py."""
if layout == "fill":
v = f"[0:v]scale=-2:{H},crop={W}:{H}[v]"
@@ -111,10 +131,18 @@ def video_filter(layout, cam, ass, band=None, cam_side='right'):
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]")
elif layout == 'react':
- x, y, w, h = map(float, cam.split(':'))
- gx = 'iw-ow' if cam_side == 'left' else '0' # crop the gameplay away from the webcam corner
- v = (f"[0:v]split[a][b];[a]crop=iw*{w}:ih*{h}:iw*{x}:ih*{y},scale={W}:{TOP}:force_original_aspect_ratio=increase,"
- f"crop={W}:{TOP}[cam];[b]scale=-2:{H - TOP},crop={W}:{H - TOP}:{gx}:0[game];[cam][game]vstack[v]")
+ sw, sh = src
+ if face_expr: # tracked face crop (no cam frame)
+ cw, chh, ex, ey = face_expr
+ top = f"crop={cw}:{chh}:{ex}:{ey}"
+ else:
+ x, y, w, h = map(float, cam.split(':'))
+ cw, chh = even(sw * w), even(sh * h)
+ top = f"crop={cw}:{chh}:{even(sw * x)}:{even(sh * y)}"
+ gw = even(sw * GAME_H / sh) if sw * GAME_H / sh >= W else W
+ gx = game_x if game_x is not None else ((gw - W) if cam_side == 'left' else 0)
+ v = (f"[0:v]split[a][b];[a]{top},scale={W}:{TOP}:force_original_aspect_ratio=increase,crop={W}:{TOP},setsar=1[cam];"
+ f"[b]scale={gw}:{GAME_H},crop={W}:{GAME_H}:{even(gx)}:0,setsar=1[game];[cam][game]vstack[v]")
if band:
y0, bh, secs = band
en = f":enable='lte(t,{secs})'" if secs > 0 else ''
@@ -127,6 +155,47 @@ def video_filter(layout, cam, ass, band=None, cam_side='right'):
return v + f";[v]fps=30,subtitles='{sub}'[vo]"
+def game_offset(video, s0, e0, src, cam_box):
+ """Pick the x offset of the 1080-wide game crop that avoids static overlays (viewer counters,
+ alerts, chat boxes) and the webcam. Static = pixels that barely change across sampled frames
+ but carry edges (text/graphics)."""
+ try:
+ import cv2, numpy as np
+ except ImportError:
+ return None
+ sw, sh = src
+ gw = even(sw * GAME_H / sh)
+ if gw <= W:
+ return 0
+ cap = cv2.VideoCapture(str(video)); frames = []
+ for k in range(12):
+ cap.set(cv2.CAP_PROP_POS_MSEC, (s0 + (e0 - s0) * (k + 0.5) / 12) * 1000)
+ ok, f = cap.read()
+ if ok:
+ frames.append(cv2.resize(cv2.cvtColor(f, cv2.COLOR_BGR2GRAY), (gw, GAME_H)).astype(np.float32))
+ cap.release()
+ if len(frames) < 4:
+ return None
+ st = np.stack(frames)
+ std = st.std(0); med = np.median(st, 0)
+ edges = cv2.Canny(med.astype(np.uint8), 60, 160) > 0
+ bad = (std < 6) & cv2.dilate(edges.astype(np.uint8), np.ones((9, 9), np.uint8)).astype(bool)
+ x, y, w, h = cam_box # the cam itself also counts as overlay
+ bad[int(y * GAME_H):int((y + h) * GAME_H), int(x * gw):int((x + w) * gw)] = True
+ col = bad.sum(0).astype(np.float64); cs = np.concatenate([[0], np.cumsum(col)])
+ best, bx = None, 0
+ camcols = np.zeros(gw); camcols[int(x * gw):int((x + w) * gw)] = 1; cc = np.concatenate([[0], np.cumsum(camcols)])
+ for ox in range(0, gw - W + 1, 8):
+ # never show the cam twice; otherwise stay near the centre (game subtitles and action sit there),
+ # moving off-centre only when that clearly removes a static overlay (counters, alerts, chat)
+ if cc[ox + W] - cc[ox] > 0 and (cc[-1] < gw - W):
+ continue
+ cost = (cs[ox + W] - cs[ox]) * 0.2 + abs(ox - (gw - W) / 2) * GAME_H * 0.05
+ if best is None or cost < best:
+ best, bx = cost, ox
+ return bx
+
+
def main():
ap = argparse.ArgumentParser()
ap.add_argument("job"); ap.add_argument("--pick", type=int, default=1)
@@ -135,7 +204,8 @@ def main():
ap.add_argument("--title-style", choices=["box", "outline"], default="box")
ap.add_argument("--title-secs", type=float, default=0, help="0 = whole clip")
ap.add_argument("--captions", choices=["word", "bubble", "none"], default="word")
- ap.add_argument("--hook", default=""); ap.add_argument("--credit", default="")
+ ap.add_argument("--hook", default="")
+ ap.add_argument("--allow-profanity", action="store_true", help="keep swear words in captions (slurs are always masked)")
ap.add_argument("--cam", default="auto", help="auto (find the webcam) or x:y:w:h fractions")
ap.add_argument("--start", type=float); ap.add_argument("--end", type=float)
a = ap.parse_args()
@@ -145,9 +215,24 @@ def main():
words = load_json(d / "transcript.json")
out = d / "edits"; out.mkdir(exist_ok=True)
layout, cam, side = a.layout, a.cam, 'right'
+ face_expr = None
if layout in ('react', 'facecam') and cam == 'auto':
from facecam import find_cam
r = find_cam(c['source'], s0, e0)
+ if layout == 'react' and r.get('mode') not in ('cam', 'face'):
+ sys.exit(f"skipped: no streamer face over gameplay in this moment ({r.get('mode')}: {r.get('reason', '')}). "
+ "React clips need the game on screen with the cam as a separate box. Pick another moment or stream.")
+ if layout == 'react':
+ from facecam import has_gameplay, face_crop_expr
+ if not has_gameplay(c['source'], s0, e0, r['box']):
+ sys.exit("skipped: the area outside the webcam is not gameplay (same scene or no game on screen). "
+ "Pick a moment where GTA 6 is on screen.")
+ if r.get('mode') == 'face' and r.get('face_track'):
+ from common import ffprobe as _fp
+ _vs = [x for x in _fp(c['source'])['streams'] if x.get('codec_type') == 'video'][0]
+ fe = face_crop_expr(r['face_track'], int(_vs['width']), int(_vs['height']), W, TOP)
+ face_expr = (fe['w'], fe['h'], fe['x'], fe['y'])
+ print(f"facecam: no clean cam frame, tracking the face ({r.get('summary', '')})")
if r.get('mode') in ('cam', 'face'):
bx = list(r['box'])
if r['mode'] == 'face': # no webcam frame: widen the face crop so it is not a blurry close-up
@@ -175,8 +260,14 @@ def main():
ass = out / f"clip_{a.pick}.ass"
caps = a.captions
cap_words = words if caps != 'none' else []
- ass.write_text(build_ass(cap_words, s0, e0, a.hook, a.credit, cap_y, title=title, caps=caps), encoding="utf-8")
- v = video_filter(layout, cam, ass, band=band, cam_side=side)
+ ass.write_text(build_ass(cap_words, s0, e0, a.hook, cap_y, title=title, caps=caps, profanity=a.allow_profanity), encoding="utf-8")
+ src = None; gx = None
+ if layout == 'react':
+ from common import ffprobe
+ vs = [x for x in ffprobe(c['source'])['streams'] if x.get('codec_type') == 'video'][0]
+ src = (int(vs['width']), int(vs['height']))
+ gx = game_offset(c['source'], s0, e0, src, [float(t) for t in cam.split(':')])
+ v = video_filter(layout, cam, ass, band=band, cam_side=side, src=src, game_x=gx, face_expr=face_expr)
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",
@@ -184,7 +275,7 @@ def main():
"-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": layout, "hook": a.hook or a.title, "title": a.title, "cam": cam,
- "credit": a.credit, "source_url": info.get("webpage_url"), "source_title": info.get("title"),
+ "source_url": info.get("webpage_url"), "source_title": info.get("title"),
"source_channel": info.get("channel") or info.get("uploader")})
print(mp4)
diff --git a/scripts/facecam.py b/scripts/facecam.py
index 2316b82..21b0185 100644
--- a/scripts/facecam.py
+++ b/scripts/facecam.py
@@ -196,6 +196,244 @@ def refine_with_frame_edges(rect, w, h, face):
return rect
+SNAP_FRAMES = 20
+SNAP_RANGE = 80 # px (at MAX_W analysis width) searched around each edge
+SNAP_SHRINK = 2 # px moved inside so no sliver of game/background remains
+
+
+def _edge_profile(M, S, p_lo, p_hi, span, vertical):
+ """Score candidate border positions p in [p_lo,p_hi) of a vertical (x) or horizontal (y) edge.
+ M = median colour image (float32 HxWx3), S = temporal std map (HxW), span = (a,b) along the line.
+ p = first pixel after the change: step between [p-3,p) and [p,p+3).
+ Evidence: (1) straight line: the colour step holds on most pixels along the span (static edge / constant colour line),
+ (2) temporal change: cam region and game region differ in temporal behaviour across the line."""
+ a, b = span
+ if not vertical:
+ M = M.transpose(1, 0, 2); S = S.T
+ Ms = M[a:b]; Ss = S[a:b]
+ n = Ms.shape[1]
+ ps = np.arange(max(p_lo, 4), min(p_hi, n - 3))
+ if len(ps) == 0:
+ return ps, np.zeros(0)
+ cs = np.concatenate([np.zeros((Ms.shape[0], 1, 3), np.float32), np.cumsum(Ms, axis=1)], axis=1)
+ right = (cs[:, ps + 3] - cs[:, ps]) / 3; left = (cs[:, ps] - cs[:, ps - 3]) / 3
+ step = np.abs(right - left).sum(axis=2) # rows x candidates
+ cons = (step > 24).mean(axis=0) # fraction of the line that shows the step
+ mag = np.clip(np.median(step, axis=0) / 45.0, 0, 1)
+ cs2 = np.concatenate([np.zeros((Ss.shape[0], 1), np.float32), np.cumsum(Ss, axis=1)], axis=1)
+ k0 = np.clip(ps - 10, 0, n); k1 = np.clip(ps - 2, 0, n); k2 = np.clip(ps + 2, 0, n); k3 = np.clip(ps + 10, 0, n)
+ sl = (cs2[:, k1] - cs2[:, k0]) / np.maximum(1, k1 - k0); sr = (cs2[:, k3] - cs2[:, k2]) / np.maximum(1, k3 - k2)
+ rel = np.abs(sl - sr) / (sl + sr + 2.0)
+ tcons = (rel > 0.35).mean(axis=0)
+ tmag = np.clip(np.median(rel, axis=0) * 2, 0, 1)
+ return ps, cons * mag + 0.6 * tcons * tmag
+
+
+def snap_edges(frames, box, search=SNAP_RANGE, shrink=SNAP_SHRINK, face=None):
+ """Snap [L,T,R,B] (px of the analysis frames) to the real webcam border. Returns (L,T,R,B,raw_edges)."""
+ h, w = frames[0].shape[:2]
+ L, T, R, B = [int(round(v)) for v in box]
+ idx = np.linspace(0, len(frames) - 1, min(len(frames), SNAP_FRAMES)).astype(int)
+ fs = [frames[i] for i in idx]
+ M = np.median(np.array(fs), axis=0).astype(np.float32)
+ S = np.array([cv2.cvtColor(f, cv2.COLOR_BGR2GRAY) for f in fs]).astype(np.float32).std(axis=0)
+ M = cv2.GaussianBlur(M, (3, 3), 0); S = cv2.GaussianBlur(S, (3, 3), 0)
+ H, W = B - T, R - L
+ yspan = (int(T + 0.15 * H), int(B - 0.15 * H)); xspan = (int(L + 0.15 * W), int(R - 0.15 * W))
+ out = {}
+ for name, p0, vertical, span in (("L", L, True, yspan), ("R", R, True, yspan), ("T", T, False, xspan), ("B", B, False, xspan)):
+ lim = w if vertical else h
+ if p0 <= 3 or p0 >= lim - 3: # docked to the frame edge: nothing to snap
+ out[name] = 0 if p0 <= 3 else lim
+ continue
+ ps, sc = _edge_profile(M, S, p0 - search, p0 + search + 1, span, vertical)
+ if len(ps) == 0 or sc.max() < 0.25:
+ out[name] = p0
+ continue
+ sc = sc - 0.05 * np.abs(ps - p0) / search # weak prior: stay near the first estimate
+ # strong plateaus (runs within 90% of the best); the cam border is the one nearest the face: a stronger line
+ # further out (game UI card, window edge) lies beyond a flat dead strip that is not part of the cam
+ strong = sc >= 0.9 * sc.max()
+ if face is not None:
+ fx, fy, fw_, fh_ = face
+ lim_in = {"L": fx - 0.3 * fw_, "R": fx + 1.3 * fw_, "T": fy - 0.3 * fh_, "B": fy + 1.3 * fh_}[name]
+ ok = (ps < lim_in) if name in ("L", "T") else (ps > lim_in)
+ if (strong & ok).any():
+ strong &= ok
+ idx = np.flatnonzero(strong)
+ runs = np.split(idx, np.flatnonzero(np.diff(idx) > 1) + 1)
+ run = runs[-1] if name in ("L", "T") else runs[0]
+ # the step window is 3+3 px wide, so the true border is the centre of the plateau
+ out[name] = int(round((ps[run[0]] + ps[run[-1]]) / 2))
+ nL = out["L"] if out["L"] <= 3 else out["L"] + shrink
+ nT = out["T"] if out["T"] <= 3 else out["T"] + shrink
+ nR = out["R"] if out["R"] >= w - 3 else out["R"] - shrink
+ nB = out["B"] if out["B"] >= h - 3 else out["B"] - shrink
+ return nL, nT, nR, nB, out
+
+
+FACE_MAX_DRIFT = 0.03 # of frame width per second (face centre), same relative rate for face size
+
+
+def _median_filter(a, k=5):
+ pad = k // 2
+ p = np.pad(a, pad, mode="edge")
+ return np.array([np.median(p[i:i + k]) for i in range(len(a))])
+
+
+def track_face(video, start, end, face, fps=2.0):
+ """Face centre and size over time -> [{t, cx, cy, size}] (fractions of the frame; size = face height / frame height;
+ t = seconds from `start`). Detections near the stable face are kept, gaps are interpolated, then median + exponential
+ smoothing + a slew limit (max drift FACE_MAX_DRIFT of frame width per second) so the crop never jumps."""
+ dur = duration(video)
+ s = max(0.0, start or 0.0)
+ e = min(end if end is not None else dur, dur) if dur else (end or s + 20)
+ if e <= s:
+ e = s + 1
+ n = int(min(240, max(2, round((e - s) * fps) + 1)))
+ ts = np.linspace(s, e - min(0.05, (e - s) / 10), n)
+ cap = cv2.VideoCapture(str(video))
+ det = cv2.FaceDetectorYN.create(model_path(), "", (320, 320), 0.7, 0.3, 5000)
+ fx, fy, fw, fh = face
+ raw = []
+ W = H = None
+ ref = np.array([fx + fw / 2, fy + fh / 2, fh], float) # px of the analysis frame
+ for t in ts:
+ cap.set(cv2.CAP_PROP_POS_MSEC, t * 1000)
+ ok, f = cap.read()
+ if not ok or f is None:
+ raw.append(None); continue
+ h, w = f.shape[:2]
+ sc = min(1.0, MAX_W / w)
+ if sc < 1:
+ f = cv2.resize(f, (int(w * sc), int(h * sc)), interpolation=cv2.INTER_AREA); h, w = f.shape[:2]
+ W, H = w, h
+ det.setInputSize((w, h))
+ _, fs = det.detect(f)
+ best = None
+ for r in ([] if fs is None else fs):
+ cx, cy, hh = r[0] + r[2] / 2, r[1] + r[3] / 2, r[3]
+ if np.hypot(cx - ref[0], cy - ref[1]) < 1.6 * ref[2] and 0.6 < hh / ref[2] < 1.67:
+ d = np.hypot(cx - ref[0], cy - ref[1])
+ if best is None or d < best[0]:
+ best = (d, cx, cy, hh)
+ if best:
+ raw.append(best[1:]); ref = 0.6 * ref + 0.4 * np.array(best[1:])
+ else:
+ raw.append(None)
+ cap.release()
+ if not W or sum(r is not None for r in raw) < 2:
+ return []
+ ok_i = [i for i, r in enumerate(raw) if r is not None]
+ arr = np.array([raw[i] for i in ok_i], float)
+ rel_t = ts - s
+ cx = np.interp(np.arange(n), ok_i, arr[:, 0]); cy = np.interp(np.arange(n), ok_i, arr[:, 1]); sz = np.interp(np.arange(n), ok_i, arr[:, 2])
+ out = []
+ for v in (cx, cy, sz):
+ v[:] = _median_filter(v, 5)
+ for i in range(1, n): # exponential smoothing
+ v[i] = 0.25 * v[i] + 0.75 * v[i - 1]
+ lim = FACE_MAX_DRIFT * W
+ for i in range(1, n): # slew limit: drift per second, in px
+ dt = max(1e-3, rel_t[i] - rel_t[i - 1])
+ for v, L_ in ((cx, lim), (cy, lim), (sz, 0.06 * max(sz[i - 1], 1))):
+ d = v[i] - v[i - 1]; m = L_ * dt
+ v[i] = v[i - 1] + max(-m, min(m, d))
+ return [{"t": round(float(rel_t[i]), 3), "cx": round(float(cx[i] / W), 4), "cy": round(float(cy[i] / H), 4),
+ "size": round(float(sz[i] / H), 4)} for i in range(n)]
+
+
+def _pw(ts, vs):
+ """Piecewise-linear ffmpeg expression in t (commas escaped for a filtergraph)."""
+ if len(ts) == 1:
+ return f"{vs[0]:.2f}"
+ expr = f"{vs[-1]:.2f}"
+ for i in range(len(ts) - 2, -1, -1):
+ dt = max(1e-3, ts[i + 1] - ts[i])
+ expr = f"if(lt(t\\,{ts[i + 1]:.3f})\\,{vs[i]:.2f}+({vs[i + 1] - vs[i]:.2f})*(t-{ts[i]:.3f})/{dt:.3f}\\,{expr})"
+ return expr
+
+
+def face_crop_expr(track, src_w, src_h, out_w, out_h, eyes_at=0.40, head_fill=0.38):
+ """ffmpeg crop for a face panel of aspect out_w:out_h that follows the smoothed face.
+ head_fill = face box height / crop height (0.38 shows head and shoulders). Eyes sit at eyes_at of the panel height,
+ the face is horizontally centred, the face box never leaves the crop and the crop never leaves the frame.
+ Returns {"w","h" (even ints, fixed: ffmpeg cannot animate crop size), "x","y" (expressions in t, commas escaped as \\,
+ so they drop straight into a filtergraph), "filter": "crop=w:h:x:y"}. track t is seconds from the cut start (use after -ss)."""
+ if not track:
+ return None
+ ar = out_w / out_h
+ size = float(np.median([k["size"] for k in track])) * src_h # face height px
+ ch = min(size / head_fill, src_h, src_w / ar)
+ cw = ch * ar
+ cw = max(2, int(cw) // 2 * 2); ch = max(2, int(round(cw / ar)) // 2 * 2)
+ if ch > src_h:
+ ch = src_h // 2 * 2; cw = max(2, int(ch * ar) // 2 * 2)
+ xs, ys, ts = [], [], []
+ for k in track:
+ fcx, fcy = k["cx"] * src_w, k["cy"] * src_h
+ fh_ = k["size"] * src_h; fw_ = 0.8 * fh_
+ x = fcx - cw / 2
+ y = (fcy - 0.12 * fh_) - eyes_at * ch # eyes sit ~0.12 face heights above the box centre
+ lo, hi = max(0, fcx + fw_ / 2 - cw), min(src_w - cw, fcx - fw_ / 2) # keep the whole face box inside
+ if lo <= hi: x = min(max(x, lo), hi)
+ lo, hi = max(0, fcy + fh_ / 2 - ch), min(src_h - ch, fcy - fh_ / 2)
+ if lo <= hi: y = min(max(y, lo), hi)
+ xs.append(min(max(x, 0), src_w - cw)); ys.append(min(max(y, 0), src_h - ch)); ts.append(k["t"])
+ x_e, y_e = _pw(ts, xs), _pw(ts, ys)
+ return {"w": cw, "h": ch, "x": x_e, "y": y_e, "filter": f"crop={cw}:{ch}:{x_e}:{y_e}"}
+
+
+def has_gameplay(video, start, end, cam_box, info=False):
+ """True when the area outside the cam box is game footage that differs from the cam scene.
+ cam_box = [x,y,w,h] fractions. None, or a box covering most of the frame, means a full-screen camera -> False.
+ A face-mode box is a crop of the same room, so its outside matches it (similar colour histograms) -> False."""
+ def ret(v, d):
+ return (v, d) if info else v
+ if not cam_box:
+ return ret(False, {"why": "no cam box"})
+ frames = sample_frames(video, start, end, 8)
+ if len(frames) < 3:
+ return ret(False, {"why": "too few frames"})
+ h, w = frames[0].shape[:2]
+ x, y, bw, bh = cam_box
+ if bw * bh > 0.55:
+ return ret(False, {"why": "cam covers the frame"})
+ x0, y0, x1, y1 = int(x * w), int(y * h), int((x + bw) * w), int((y + bh) * h)
+ inside = np.zeros((h, w), np.uint8); inside[y0:y1, x0:x1] = 255
+ outside = 255 - inside
+ # ignore a thin margin so the cam border does not leak into the outside histogram
+ outside = cv2.erode(outside, np.ones((9, 9), np.uint8))
+ hist = lambda m, hsv: cv2.normalize(cv2.calcHist([hsv], [0, 1, 2], m, [12, 4, 6], [0, 180, 0, 256, 0, 256]), None, 1, 0, cv2.NORM_L1).flatten()
+ sims = []
+ for f in frames:
+ hsv = cv2.cvtColor(f, cv2.COLOR_BGR2HSV)
+ sims.append(cv2.compareHist(hist(inside, hsv), hist(outside, hsv), cv2.HISTCMP_BHATTACHARYYA))
+ dist = float(np.median(sims)) # 0 = same scene, 1 = nothing in common
+ gray = np.array([cv2.cvtColor(f, cv2.COLOR_BGR2GRAY) for f in frames]).astype(np.float32)
+ om = outside > 0
+ content = float(gray.mean(axis=0)[om].std()) # spatial variety outside
+ motion = float(np.abs(np.diff(gray, axis=0))[:, om].mean()) # frame-to-frame change outside
+ # the picture just outside the cam is a continuation of it for IRL footage: a plain-colour or flat outside is not gameplay
+ # an overlay has a hard straight border all around; a crop of one IRL scene is continuous across the box edge
+ Mg = cv2.GaussianBlur(np.median(np.array(frames), axis=0).astype(np.float32), (3, 3), 0)
+ fr_ = []
+ for p, vert, (a, b) in ((x0, 1, (y0, y1)), (x1, 1, (y0, y1)), (y0, 0, (x0, x1)), (y1, 0, (x0, x1))):
+ if p <= 4 or p >= (w if vert else h) - 4:
+ continue # docked to the frame edge: no border there
+ m = int(0.1 * (b - a)); a, b = a + m, b - m
+ best = 0.0
+ for q in range(p - 3, p + 4):
+ if vert: s = np.abs(Mg[a:b, q + 1:q + 4].mean(1) - Mg[a:b, q - 3:q].mean(1)).sum(1)
+ else: s = np.abs(Mg[q + 1:q + 4, a:b].mean(0) - Mg[q - 3:q, a:b].mean(0)).sum(1)
+ best = max(best, float((s > 30).mean()))
+ fr_.append(best)
+ border = float(np.median(fr_)) if fr_ else 0.0
+ has_content = content > 12 or motion > 3
+ res = has_content and ((border >= 0.65 and dist > 0.38) or dist > 0.6)
+ return ret(bool(res), {"hist_dist": round(dist, 3), "border": round(border, 2), "content": round(content, 1), "motion": round(motion, 2)})
+
+
def where(box):
x, y, bw, bh = box
cx, cy = x + bw / 2, y + bh / 2
@@ -219,7 +457,11 @@ def find_cam(video, start=None, end=None):
fx, fy, fw, fh = face
fracface = [round(fx / w, 4), round(fy / h, 4), round(fw / w, 4), round(fh / h, 4)]
if fw / w > 0.5:
- return {"mode": "none", "confidence": 0.0, "face": fracface,
+ try:
+ track = track_face(video, start, end, face)
+ except Exception:
+ track = []
+ return {"mode": "none", "confidence": 0.0, "face": fracface, "face_track": track,
"reason": "stable face is huge (full-frame talking head, not a webcam overlay)"}
stab = hits / len(frames)
@@ -239,7 +481,15 @@ def find_cam(video, start=None, end=None):
contains = L <= fx and R >= fx + fw and T <= fy and B >= fy + fh
sane = 0.08 < bw / w < 0.6 and 0.08 < bh / h < 0.7 and contains and bw > fw * 1.2 and bh > fh * 1.2
if sane:
- box = [round(L / w, 4), round(T / h, 4), round(bw / w, 4), round(bh / h, 4)]
+ try:
+ sf = sample_frames(video, start, end, SNAP_FRAMES)
+ nL, nT, nR, nB, raw = snap_edges(sf if len(sf) >= 8 else frames, (L, T, R, B), face=(fx, fy, fw, fh))
+ if nR - nL > fw * 1.2 and nB - nT > fh * 1.2 and nL <= fx and nR >= fx + fw and nT <= fy and nB >= fy + fh:
+ L, T, R, B = nL, nT, nR, nB; bw, bh = R - L, B - T
+ r["notes"] = list(r["notes"]) + [f"snapped {raw}"]
+ except Exception as ex: # snapping is a refinement: never lose the cam over it
+ r["notes"] = list(r["notes"]) + [f"snap failed: {ex}"]
+ box =[round(L / w, 4), round(T / h, 4), round(bw / w, 4), round(bh / h, 4)]
conf = round(min(1.0, 0.55 + 0.25 * stab + 0.2 * (1 if n_found == 4 else 0.5)), 2)
return {"mode": "cam", "box": box, "face": fracface, "confidence": conf,
"reason": f"face stable in {hits}/{len(frames)} frames, rectangle edges found on {n_found}/4 sides {r['notes']}",
@@ -252,7 +502,11 @@ def find_cam(video, start=None, end=None):
x0 = min(max(0, ccx - cw / 2), w - cw); y0 = min(max(0, ccy - ch / 2), h - ch)
box = [round(x0 / w, 4), round(y0 / h, 4), round(cw / w, 4), round(ch / h, 4)]
conf = round(min(0.8, 0.35 + 0.4 * stab), 2)
- return {"mode": "face", "box": box, "face": fracface, "confidence": conf,
+ try:
+ track = track_face(video, start, end, face)
+ except Exception:
+ track = []
+ return {"mode": "face", "box": box, "face": fracface, "confidence": conf, "face_track": track,
"reason": f"face stable in {hits}/{len(frames)} frames but no clean rectangle ({n_found}/4 sides found); face-centred crop",
"summary": f"face (no cam border): {where(box)}"}
diff --git a/scripts/translate.py b/scripts/translate.py
index ab19ac9..c9776af 100644
--- a/scripts/translate.py
+++ b/scripts/translate.py
@@ -4,7 +4,7 @@ Translates the spoken lines (word-by-word captions) and the hook of an already c
jobs/<id>/edits/clip_<n>_<lang>.mp4 with the same layout as cut.py, plus clip_<n>_captions.md with
per-platform captions in each language.
-usage: python translate.py jobs/<id> --pick <n> --langs es,pt,de,ru [--voice] [--layout ...] [--hook "..."] [--credit "..."]
+usage: python translate.py jobs/<id> --pick <n> --langs es,pt,de,ru [--voice] [--layout ...] [--hook "..."]
--voice adds a stock text-to-speech voice (edge-tts, Microsoft neural stock voices) that speaks the
translated hook only, over the first 2.5 s, with the original audio ducked under it. It never clones
@@ -103,7 +103,7 @@ def render(src, s0, e0, layout, cam, ass, mp4, voice_mp3=None):
def platform_block(lang, hook, credit, url):
line = hook or ""
- cred = f"clip: {credit}" if credit else ""
+ cred = ""
src = f"\n{url}" if url else ""
x = "\n".join(p for p in [line, cred] if p) + src
ig = "\n".join(p for p in [line, cred, " ".join(HASHTAGS[:4])] if p)
@@ -118,7 +118,7 @@ def main():
ap.add_argument("--langs", default="es,pt,de,ru")
ap.add_argument("--voice", action="store_true")
ap.add_argument("--layout", choices=["fill", "blur", "facecam"])
- ap.add_argument("--cam"); ap.add_argument("--hook"); ap.add_argument("--credit")
+ ap.add_argument("--cam"); ap.add_argument("--hook")
a = ap.parse_args()
d = Path(a.job); out = d / "edits"
side = out / f"clip_{a.pick}.json"
@@ -130,20 +130,18 @@ def main():
layout = a.layout or meta.get("layout", "blur")
cam = a.cam or "0.70:0.68:0.30:0.32"
hook = a.hook if a.hook is not None else meta.get("hook", "")
- credit = a.credit if a.credit is not None else meta.get("credit", "")
- if not credit:
- sys.exit("No credit line. Pass --credit (or cut with one). Never post a clip without credit.")
+ credit = ""
words = [w for w in load_json(d / "transcript.json") if s0 <= w["s"] < e0 and w["w"]]
langs = [x.strip() for x in a.langs.split(",") if x.strip()]
caps = ["# Captions, one clip in several languages\n",
f"Source: {meta.get('source_title') or ''} ({meta.get('source_channel') or ''})\n",
- "Translations are machine translated. Read each one before posting. Keep the credit line.\n"]
+ "Translations are machine translated. Read each one before posting.\n"]
for lang in langs:
t = translator(lang)
h = tr(t, hook) if hook else ""
tw = translate_words(t, words)
ass = out / f"clip_{a.pick}_{lang}.ass"
- ass.write_text(build_ass(tw, s0, e0, h, credit, CAP_Y[layout]), encoding="utf-8")
+ ass.write_text(build_ass(tw, s0, e0, h, CAP_Y[layout]), encoding="utf-8")
mp4 = out / f"clip_{a.pick}_{lang}.mp4"
mp3 = None
if a.voice and h:
diff --git a/skills/clip-cutter/SKILL.md b/skills/clip-cutter/SKILL.md
index 0f77e5f..bf38643 100644
--- a/skills/clip-cutter/SKILL.md
+++ b/skills/clip-cutter/SKILL.md
@@ -1,13 +1,13 @@
---
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".
+description: Cut a picked moment into a finished 1080x1920 vertical clip with word-by-word captions, and a hook box. 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"`
+`python "${CLAUDE_PLUGIN_ROOT}/scripts/cut.py" jobs/<id> --pick <n> --layout fill|blur|facecam --hook "TEXT"`
- `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.
@@ -16,11 +16,10 @@ Run:
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.
+1. Output is an mp4 in `media/edits`. Check it is 1080x1920, the hook shows in the first 2 seconds, captions are readable. No credit text is burned into the video; the poster credits the creator in the post.
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.
+4. Show the human the file, and the caption text, and ask for "yes". Do not upload anything.
diff --git a/skills/hook-writer/SKILL.md b/skills/hook-writer/SKILL.md
index f2c3d4d..b15d5fe 100644
--- a/skills/hook-writer/SKILL.md
+++ b/skills/hook-writer/SKILL.md
@@ -41,4 +41,4 @@ Describe what happens on screen. Never put words in the streamer's mouth: no quo
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.
+Return the 3 options and mark your pick.
diff --git a/skills/moment-finder/SKILL.md b/skills/moment-finder/SKILL.md
index 70c1a38..9778ea9 100644
--- a/skills/moment-finder/SKILL.md
+++ b/skills/moment-finder/SKILL.md
@@ -18,4 +18,4 @@ Then:
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.
+Record the source link and creator in `media/raw` notes. Credit the creator in the post caption.
diff --git a/skills/multilang/SKILL.md b/skills/multilang/SKILL.md
index f078ac6..1e22bc0 100644
--- a/skills/multilang/SKILL.md
+++ b/skills/multilang/SKILL.md
@@ -13,13 +13,12 @@ Run after `clip-cutter` (the clip must already exist as `jobs/<id>/edits/clip_<n
Output in `jobs/<id>/edits/`: `clip_<n>_<lang>.mp4` per language and one `clip_<n>_captions.md` with X, Instagram and TikTok/Shorts captions per language.
-- Layout, hook box, credit line and loudness match the original cut. Override with `--layout`, `--hook`, `--credit` if needed.
+- Layout, hook box and loudness match the original cut. Override with `--layout`, `--hook` if needed.
- `--voice` adds a stock text-to-speech voice (edge-tts: es-ES-AlvaroNeural, pt-BR-AntonioNeural, de-DE-ConradNeural, ru-RU-DmitryNeural) that reads the translated hook only, in the first 2.5 seconds, with the original audio ducked under it.
- Never clone or imitate a real person's or streamer's voice. Stock voices only, and do not present the voiceover as the creator speaking.
Rules:
-1. Keep the credit line in every language. No credit, no post.
2. Translate facts, do not invent. Do not add claims, dates, prices or names that are not in the original clip or hook. Machine translation can slip: read each language's captions and hook before the human posts, and fix wrong or odd lines (ask the human if a language is unfamiliar).
3. Run `rule-check` on each language version, same as the original.
4. Post localized versions on separate localized pages or accounts, or as multi-language uploads where the platform supports them (for example YouTube multiple audio tracks and translated titles). Do not spam the same page with five versions of one clip.
diff --git a/skills/rule-check/SKILL.md b/skills/rule-check/SKILL.md
index b27b898..8fc4895 100644
--- a/skills/rule-check/SKILL.md
+++ b/skills/rule-check/SKILL.md
@@ -9,12 +9,12 @@ 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).
+It checks: length, 1080x1920, audio present, 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.
+3. Read the caption yourself too. It must credit the creator in the text, 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/twitch-reaction/SKILL.md b/skills/twitch-reaction/SKILL.md
index ce4987f..b18aea9 100644
--- a/skills/twitch-reaction/SKILL.md
+++ b/skills/twitch-reaction/SKILL.md
@@ -20,7 +20,7 @@ Face on top, game below, a big title on the seam. The format of most viral GTA 6
```
python "${CLAUDE_PLUGIN_ROOT}/scripts/cut.py" jobs/<id> --pick 1 --layout react --cam auto \
- --title "Speed REALIZED why GTA 6 took ROCKSTAR 13 YEARS" --title-style box --captions bubble --credit "@<streamer>"
+ --title "Speed REALIZED why GTA 6 took ROCKSTAR 13 YEARS" --title-style box --captions bubble
```
- `--cam auto` finds the streamer's webcam itself (face detection plus the webcam frame around it). It prints where it found the cam. If it finds no stable face it falls back to the blur layout and says so. Check the first frame once; if the crop is wrong, pass `--cam x:y:w:h` fractions.
@@ -30,6 +30,6 @@ python "${CLAUDE_PLUGIN_ROOT}/scripts/cut.py" jobs/<id> --pick 1 --layout react
## Rules
-- Clip a streamer only inside their campaign or with permission. Credit every clip.
+- Clip a streamer only inside their campaign or with permission. Credit them in the post caption, not on the video.
- Titles describe what happened. Never invent a quote or an opinion.
- Run `rule-check` before posting. No spoilers in the title during launch week.