diff --git a/CLAUDE.md b/CLAUDE.md index 6ed4ded..2ede5a4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -120,6 +120,21 @@ Gemini era de las medidas continuas, no del modelo. `layout_picker.apply()` sólo **añade**: una elección explícita del usuario nunca se desactiva porque el modelo diga `none`. +### Hook grounding for on-screen clips (`hook_grounding.py`) + +The hook and title come from the detail pass, which only reads the +transcript, so on a clip whose meaning is on the screen (a settings dialog, +a spreadsheet) they summarise the video's topic instead of naming what is +shown. After the render, if the `.layout.json` sidecar says at least +25% of the clip is `screencast` / `wide` / `inset`, three frames from those +stretches at 1024px plus the clip's own words go to Gemini +(`GroundedHook`) and `viral_hook_text` / `video_title_for_youtube_short` +are rewritten in place before `auto_hook_clip` burns them; the originals +stay under `hook_grounding.before`. Gemini-only (frames): with just a local +LLM it logs one line and keeps the transcript hook. `HOOK_GROUNDING=0` +disables it. The detail prompt itself now carries the rule "about this +moment, not the video", which is the cheap half of the same fix. + ### Local LLM for the moment picker (`llm_backend.py`) `LLM_BASE_URL` (+ `LLM_MODEL`, `LLM_API_KEY`) routes the two transcript diff --git a/gemini_worker.py b/gemini_worker.py index e687dc8..c4383f0 100644 --- a/gemini_worker.py +++ b/gemini_worker.py @@ -82,6 +82,44 @@ to worst by how likely they are to stop a viewer scrolling. """ +# Grounded rewrite of hook + title for a clip whose meaning lives on screen +# (SCREENCAST / WIDE / INSET stretches): the detail pass never saw a frame, +# so its hook summarises the topic instead of naming what is being shown. +class GroundedHook(BaseModel): + on_screen: str + viral_hook_text: str + video_title_for_youtube_short: str + + +GROUNDED_HOOK_PROMPT = """ +These frames come from ONE short clip (the whole clip, in order) and the +transcript below is exactly what is said during it. Most of this clip's +meaning is on the screen, not in the face. + +1. `on_screen`: one line naming what is shown — the app, window, product, + document, code, chart or on-screen text — as specifically as the frames + allow (read visible titles and labels). +2. `viral_hook_text`: max 10 words, in TRANSCRIPT_LANGUAGE. It MUST mention + the thing you named in `on_screen` (or the action being done to it: set + up, connect, compare, fix, type). Never a summary of the video's general + topic, never a slogan that would fit any clip of this video. +3. `video_title_for_youtube_short`: max 100 chars, same rule, in + TRANSCRIPT_LANGUAGE, no fake claims. + +The current hook and title below were written WITHOUT seeing the frames and +are the kind of topic summary you must replace. Do not reuse their wording. + +TRANSCRIPT_LANGUAGE: {language} +CURRENT_HOOK (to replace): {current_hook} +CURRENT_TITLE (to replace): {current_title} +TRANSCRIPT: +{transcript} + +Return only: +{{"on_screen": "", "viral_hook_text": "", "video_title_for_youtube_short": ""}} +""" + + class LayoutChoice(BaseModel): layout: str confidence: float @@ -274,6 +312,11 @@ HOOK PLAYBOOK — pick the strongest fitting pattern for `viral_hook_text` (max - Story loop: "This one email almost ruined me." - POV / pattern interrupt: "POV: you finally understand it." (These are English PATTERNS — always write the actual hook in TRANSCRIPT_LANGUAGE.) +- ABOUT THIS MOMENT, NOT THE VIDEO: the hook and the title name the concrete + thing that happens inside this clip — the tool being set up, the action, + the number, the claim, the name. A line that could sit on any clip of this + video ("I automated my clips with AI") is wrong. If nothing concrete can be + named, quote the clip's strongest sentence instead of summarising the topic. COPY RULES — ALL text fields (descriptions, title, hook) MUST be written in TRANSCRIPT_LANGUAGE ({language}): - Descriptions (TikTok + Instagram): 1-2 punchy sentences that tease the payoff diff --git a/hook_grounding.py b/hook_grounding.py new file mode 100644 index 0000000..1151b95 --- /dev/null +++ b/hook_grounding.py @@ -0,0 +1,169 @@ +"""Rewrite a clip's hook and title from what is actually on its screen. + +The moment picker chooses clips and writes their hook from the transcript +alone; it never sees a frame. On a talking head that is fine. On a clip the +reframe rendered as SCREENCAST / WIDE / INSET the meaning is on the screen +(a settings dialog, a spreadsheet, a terminal) and the hook comes out as a +summary of the video's topic ("I automated my clips with AI") while the +viewer is watching an MCP connector being configured. + +So, for those clips only, once the render has said which stretches live on +the screen (the ``.layout.json`` sidecar), three frames from those +stretches at 1024px plus the clip's own transcript go to Gemini and the hook +and title are rewritten to name what is shown. Same principle as the layout +picker: a few frames at a legible resolution answering one concrete +question. About 3k tokens per clip. + +Frames need a model that can see, so this is Gemini-only: with just a local +LLM (``LLM_BASE_URL``) the function returns None and the transcript-based +hook stands. Never raises: a hook problem must never cost the clip. +""" +from __future__ import annotations + +import json +import os +from typing import Optional + +SCREEN_LAYOUTS = {"screencast", "wide", "inset"} +FRAMES = int(os.environ.get("HOOK_GROUNDING_FRAMES", "3")) +WIDTH = int(os.environ.get("HOOK_GROUNDING_WIDTH", "1024")) +# Ignore a blip: the screen stretches must cover this share of the clip. +MIN_SHARE = float(os.environ.get("HOOK_GROUNDING_MIN_SHARE", "0.25")) + + +def enabled() -> bool: + return os.environ.get("HOOK_GROUNDING", "1").strip() != "0" + + +def screen_ranges(ranges): + """(start, end) pairs, clip seconds, of the stretches rendered on-screen.""" + import layout_ranges + return [(r["start"], r["end"]) for r in layout_ranges.normalise(ranges) + if r["layout"] in SCREEN_LAYOUTS] + + +def wanted(ranges, clip_duration) -> bool: + """True when enough of the clip lives on the screen to reground the hook.""" + if not enabled() or not clip_duration or clip_duration <= 0: + return False + covered = sum(e - s for s, e in screen_ranges(ranges)) + return covered / float(clip_duration) >= MIN_SHARE + + +def clip_words(transcript, start, end) -> str: + """What is said between ``start`` and ``end`` (source seconds).""" + out = [] + for seg in (transcript or {}).get("segments", []) or []: + words = seg.get("words") or [] + if words: + out.extend(w.get("word", "") for w in words + if w.get("end", 0) > start and w.get("start", 0) < end) + elif seg.get("end", 0) > start and seg.get("start", 0) < end: + out.append(seg.get("text", "")) + return " ".join(t.strip() for t in out if t and t.strip()) + + +def sample_times(ranges, clip_duration, n=None): + """``n`` timestamps spread over the on-screen stretches (whole clip if + the sidecar has none), never on the very first frame of a stretch, where + a cut is still settling.""" + n = n or FRAMES + spans = screen_ranges(ranges) or [(0.0, float(clip_duration))] + total = sum(e - s for s, e in spans) or float(clip_duration) + times = [] + for i in range(n): + target = total * (i + 0.5) / n + for s, e in spans: + if target <= e - s: + times.append(s + target) + break + target -= e - s + return times + + +def frames_at(video_path, times, width=None): + """JPEG bytes of the frame at each timestamp, at ``width`` px wide.""" + import cv2 + + width = width or WIDTH + cap = cv2.VideoCapture(video_path) + out = [] + try: + for t in times: + cap.set(cv2.CAP_PROP_POS_MSEC, float(t) * 1000.0) + ok, frame = cap.read() + if not ok: + continue + h, w = frame.shape[:2] + scaled = cv2.resize(frame, (width, max(2, int(h * width / w))), + interpolation=cv2.INTER_AREA) + ok, buf = cv2.imencode(".jpg", scaled, [cv2.IMWRITE_JPEG_QUALITY, 80]) + if ok: + out.append(buf.tobytes()) + finally: + cap.release() + return out + + +def _ask_gemini(frames, prompt, api_key): + """One vision call; returns the parsed dict. Split out so tests can stub it.""" + from google import genai + from google.genai import types as genai_types + import gemini_worker + + client = genai.Client(api_key=api_key) + model_name = os.environ.get("GEMINI_MODEL") or "gemini-3.1-flash-lite" + parts = [genai_types.Part.from_bytes(data=b, mime_type="image/jpeg") for b in frames] + response = client.models.generate_content( + model=model_name, + contents=parts + [prompt], + config=genai_types.GenerateContentConfig( + response_mime_type="application/json", + response_schema=gemini_worker.GroundedHook, + )) + gemini_worker.raise_if_blocked(response) + return json.loads(response.text) or {} + + +def reground(clip_path, clip, transcript, start, end) -> Optional[dict]: + """Rewrite ``clip['viral_hook_text']`` / ``video_title_for_youtube_short`` + in place from the clip's frames. Returns what changed (also stored under + ``clip['hook_grounding']``), or None when skipped or failed.""" + api_key = os.getenv("GEMINI_API_KEY") + if not api_key: + print(" 🪝 Hook grounding skipped: needs a Gemini key (frames), " + "keeping the transcript hook.") + return None + try: + import gemini_worker + + times = sample_times(clip.get("layout_ranges"), float(end) - float(start)) + frames = frames_at(clip_path, times) + if not frames: + return None + language = str((transcript or {}).get("language") or "unknown") + prompt = gemini_worker.GROUNDED_HOOK_PROMPT.format( + language=language, + current_hook=clip.get("viral_hook_text") or "", + current_title=clip.get("video_title_for_youtube_short") or "", + transcript=clip_words(transcript, start, end)[:4000] or "(no speech)") + answer = _ask_gemini(frames, prompt, api_key) + hook = str(answer.get("viral_hook_text") or "").strip() + title = str(answer.get("video_title_for_youtube_short") or "").strip() + if not hook: + return None + before = {"viral_hook_text": clip.get("viral_hook_text"), + "video_title_for_youtube_short": clip.get("video_title_for_youtube_short")} + clip["viral_hook_text"] = hook + if title: + clip["video_title_for_youtube_short"] = title[:100] + clip["hook_grounding"] = { + "on_screen": str(answer.get("on_screen") or "")[:200], + "before": before, + "frames": len(frames), + } + print(f" 🪝 Hook regrounded on screen ({clip['hook_grounding']['on_screen'][:60]}): {hook}") + return clip["hook_grounding"] + except Exception as e: + print(f" ⚠️ Hook grounding failed ({type(e).__name__}: {e}) — keeping the transcript hook.") + return None diff --git a/main.py b/main.py index 1a67df8..ad5dc7f 100644 --- a/main.py +++ b/main.py @@ -22,6 +22,7 @@ from google import genai from google.genai import types as genai_types import gemini_worker +import hook_grounding import layout_picker import llm_backend from clip_selection import (build_transcript_windows, clip_count_targets, @@ -1984,6 +1985,11 @@ if __name__ == '__main__': # seam there, and /api/subtitle needs it again later. import layout_ranges as _layouts clip['layout_ranges'] = _layouts.read(clip_final_path) + # The hook was written from the transcript alone. When the + # render put this clip's meaning on the screen, rewrite hook + # and title from three of its frames BEFORE burning them. + if success and hook_grounding.wanted(clip['layout_ranges'], end - start): + hook_grounding.reground(clip_final_path, clip, transcript, start, end) if success and os.environ.get("AUTO_HOOK") == "1": hooked = auto_hook_clip(clip_final_path, clip) if hooked: @@ -2022,7 +2028,7 @@ if __name__ == '__main__': # Persist per-clip render results added by the workers (auto_hook) # so the editor can see what is already burned into each clip. - if any('auto_hook' in c for c in shorts): + if any('auto_hook' in c or 'hook_grounding' in c for c in shorts): with open(metadata_file, 'w') as f: json.dump(clips_data, f, indent=2) diff --git a/tests/test_hook_grounding.py b/tests/test_hook_grounding.py new file mode 100644 index 0000000..8cb0ee7 --- /dev/null +++ b/tests/test_hook_grounding.py @@ -0,0 +1,133 @@ +"""Hook grounding: rewrite hook + title from a clip's frames when the render +put its meaning on the screen (hook_grounding.py). + +The bug this fixes: a SCREENCAST clip of someone configuring an MCP +connector shipped with the hook "I automated my clips with AI", because the +detail pass only ever reads the transcript. +""" +import pytest + +import gemini_worker +import hook_grounding as hg + + +SCREEN = [{"start": 0, "end": 30, "layout": "screencast"}] +FACE = [{"start": 0, "end": 30, "layout": "track"}] +MIXED = [{"start": 0, "end": 5, "layout": "track"}, + {"start": 5, "end": 30, "layout": "wide"}] + + +# --- when to run ----------------------------------------------------------- + +def test_screen_layouts_trigger_and_face_layouts_do_not(): + assert hg.wanted(SCREEN, 30) is True + assert hg.wanted(MIXED, 30) is True + assert hg.wanted(FACE, 30) is False + assert hg.wanted([], 30) is False + + +def test_a_blip_is_not_enough(monkeypatch): + blip = [{"start": 0, "end": 2, "layout": "screencast"}, + {"start": 2, "end": 30, "layout": "track"}] + assert hg.wanted(blip, 30) is False + + +def test_env_switch_disables(monkeypatch): + monkeypatch.setenv("HOOK_GROUNDING", "0") + assert hg.wanted(SCREEN, 30) is False + + +# --- inputs to the model --------------------------------------------------- + +def test_frames_are_sampled_inside_the_screen_stretches(): + times = hg.sample_times(MIXED, 30, n=3) + assert len(times) == 3 + assert all(5 <= t <= 30 for t in times) + assert times == sorted(times) + + +def test_without_sidecar_frames_spread_over_the_clip(): + assert hg.sample_times([], 60, n=3) == [10, 30, 50] + + +def test_clip_words_uses_word_timestamps_and_falls_back_to_segment_text(): + transcript = {"segments": [ + {"start": 0, "end": 10, "text": "hello there", + "words": [{"word": "hello", "start": 0, "end": 1}, + {"word": "there", "start": 9, "end": 10}]}, + {"start": 10, "end": 20, "text": "no words here"}, + {"start": 40, "end": 50, "text": "outside"}, + ]} + assert hg.clip_words(transcript, 8, 15) == "there no words here" + + +# --- the rewrite ----------------------------------------------------------- + +@pytest.fixture +def gemini(monkeypatch): + monkeypatch.setenv("GEMINI_API_KEY", "k") + monkeypatch.setattr(hg, "frames_at", lambda path, times, width=None: [b"jpg"] * len(times)) + seen = {} + + def fake(frames, prompt, api_key): + seen["frames"] = frames + seen["prompt"] = prompt + return {"on_screen": "Claude settings, MCP connector dialog for OpenShorts", + "viral_hook_text": "Conectando OpenShorts a Claude por MCP", + "video_title_for_youtube_short": "Así se conecta OpenShorts a Claude (MCP)"} + + monkeypatch.setattr(hg, "_ask_gemini", fake) + return seen + + +def test_rewrites_hook_and_title_and_keeps_the_originals(gemini): + clip = {"viral_hook_text": "He automatizado la creación de mis clips con IA.", + "video_title_for_youtube_short": "Clips con IA", + "layout_ranges": SCREEN} + transcript = {"language": "es", "segments": [ + {"start": 100, "end": 110, "text": "añadimos el conector de OpenShorts"}]} + + changed = hg.reground("clip.mp4", clip, transcript, 100, 130) + + assert clip["viral_hook_text"] == "Conectando OpenShorts a Claude por MCP" + assert clip["video_title_for_youtube_short"].startswith("Así se conecta") + assert clip["hook_grounding"]["before"]["viral_hook_text"].startswith("He automatizado") + assert changed["on_screen"].startswith("Claude settings") + assert len(gemini["frames"]) == 3 + assert "añadimos el conector" in gemini["prompt"] + assert "He automatizado" in gemini["prompt"] # the model sees the current hook + assert "TRANSCRIPT_LANGUAGE: es" in gemini["prompt"] + + +def test_without_a_gemini_key_the_transcript_hook_stands(monkeypatch): + monkeypatch.delenv("GEMINI_API_KEY", raising=False) + clip = {"viral_hook_text": "old", "layout_ranges": SCREEN} + assert hg.reground("clip.mp4", clip, {"segments": []}, 0, 30) is None + assert clip["viral_hook_text"] == "old" and "hook_grounding" not in clip + + +def test_model_failure_never_touches_the_clip(monkeypatch): + monkeypatch.setenv("GEMINI_API_KEY", "k") + monkeypatch.setattr(hg, "frames_at", lambda *a, **k: [b"jpg"]) + monkeypatch.setattr(hg, "_ask_gemini", lambda *a: (_ for _ in ()).throw(RuntimeError("503"))) + clip = {"viral_hook_text": "old", "layout_ranges": SCREEN} + assert hg.reground("clip.mp4", clip, {"segments": []}, 0, 30) is None + assert clip["viral_hook_text"] == "old" + + +def test_empty_answer_keeps_the_old_hook(monkeypatch): + monkeypatch.setenv("GEMINI_API_KEY", "k") + monkeypatch.setattr(hg, "frames_at", lambda *a, **k: [b"jpg"]) + monkeypatch.setattr(hg, "_ask_gemini", lambda *a: {"viral_hook_text": ""}) + clip = {"viral_hook_text": "old", "layout_ranges": SCREEN} + assert hg.reground("clip.mp4", clip, {"segments": []}, 0, 30) is None + assert clip["viral_hook_text"] == "old" + + +# --- the cheap half: the detail prompt itself ------------------------------- + +def test_detail_prompt_forbids_topic_summary_hooks(): + assert "ABOUT THIS MOMENT, NOT THE VIDEO" in gemini_worker.DETAIL_PROMPT_TEMPLATE + assert "{on_screen" not in gemini_worker.DETAIL_PROMPT_TEMPLATE # no stray placeholders + gemini_worker.GROUNDED_HOOK_PROMPT.format( + language="es", current_hook="a", current_title="b", transcript="c")