From ac0138269d0dff35e95fcce3c67dc3337eceb818 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Wed, 19 Aug 2026 14:28:19 +0200 Subject: [PATCH] feat(hook): auto-burn AI hooks on generated clips + working emoji + editor polish MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Auto-hook (opt-in per job, dashboard default ON): - /api/process accepts auto_hook + auto_hook_style; absent means off, so API/MCP/webhook callers keep byte-identical output. - main.py auto_hook_clip burns each clip's viral_hook_text (Gemini already produced it, it was only used to pre-fill the modal) into the canonical clip in place — after reframe, under watermark and captions — so every derived-name convention (subtitled_/recut_ walk-backs, R2 archive, restore) keeps working untouched. Fail-open like auto_caption_clip. - Burned hook recorded as clip.auto_hook in metadata; the hook modal warns before stacking a second one. - MediaInput: 'auto hook titles' toggle + style select in advanced options, persisted in localStorage. Emoji that actually render: - Gemini prompt now asks for 1-2 emojis in viral_hook_text. - Dockerfile installs fonts-noto-color-emoji — without it prod silently stripped every emoji (no candidate font existed in the image). - hooks.py supports fixed-bitmap color fonts (NotoColorEmoji only loads at its 109px strike; Apple Color Emoji at 160): glyphs render at native size and are Lanczos-rescaled to the text size instead of being treated as unavailable. macOS system font added for local dev. Editor polish: - HookModal persists last style/position/size/entrance (always reset to classic before, which read as the picker being broken). - Remotion preview positions aligned to hooks.py (top 20%, bottom 70%). - Warning when a bottom hook will overlap burned/preview captions. - Entrance-animation control greyed out with a note when the clip re-renders on the server, where the hook is static. --- Dockerfile | 1 + app.py | 16 +++- dashboard/src/App.jsx | 4 + dashboard/src/components/HookModal.jsx | 55 +++++++++--- dashboard/src/components/MediaInput.jsx | 41 ++++++++- dashboard/src/components/ResultCard.jsx | 3 + .../src/remotion/compositions/HookOverlay.tsx | 6 +- hooks.py | 88 ++++++++++++++----- main.py | 56 +++++++++++- 9 files changed, 234 insertions(+), 36 deletions(-) diff --git a/Dockerfile b/Dockerfile index 683fd7a..7fc111d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -50,6 +50,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ git \ fontconfig \ fonts-liberation \ + fonts-noto-color-emoji \ && rm -rf /var/lib/apt/lists/* # Deno JS runtime — required by yt-dlp for some extractor challenges. diff --git a/app.py b/app.py index 46c844b..e22dcd0 100644 --- a/app.py +++ b/app.py @@ -1452,7 +1452,9 @@ async def process_endpoint( webhook_secret: Optional[str] = Form(None), target_clips: Optional[str] = Form(None), clip_min_seconds: Optional[str] = Form(None), - clip_max_seconds: Optional[str] = Form(None) + clip_max_seconds: Optional[str] = Form(None), + auto_hook: Optional[str] = Form(None), + auto_hook_style: Optional[str] = Form(None) ): api_key = await resolve_gemini(request) if not api_key: @@ -1475,6 +1477,8 @@ async def process_endpoint( target_clips = body.get("target_clips") clip_min_seconds = body.get("clip_min_seconds") clip_max_seconds = body.get("clip_max_seconds") + auto_hook = body.get("auto_hook") + auto_hook_style = body.get("auto_hook_style") # Normalize output format (auto = keep pipeline default). if output_format not in ("vertical", "horizontal", "square"): @@ -1553,6 +1557,16 @@ async def process_endpoint( if chosen: print(f"[layouts] job={job_id} enabled={sorted(chosen)}") + # Auto-hook: burn each clip's Gemini hook text during the render. Off when + # the field is absent, so API/MCP/webhook callers keep their old output + # byte-for-byte; the dashboard sends an explicit value either way. + if str(auto_hook).lower() in ("1", "true", "yes"): + env["AUTO_HOOK"] = "1" + from hooks import HOOK_STYLES + if auto_hook_style in HOOK_STYLES: + env["AUTO_HOOK_STYLE"] = auto_hook_style + print(f"[auto-hook] job={job_id} style={env.get('AUTO_HOOK_STYLE', 'classic')}") + # Manual generation controls (discussion #65): optional clip-count target # and duration band, forwarded to the selection prompts via the same env # overrides the A/B harness already reads (clip_selection.py). All three diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index 49eb87d..3972a53 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -655,6 +655,10 @@ function App() { target_clips: data.targetClips || null, clip_min_seconds: data.clipMinSeconds || null, clip_max_seconds: data.clipMaxSeconds || null, + // Sent explicitly both ways: absent means off for raw API callers, + // but the dashboard always states the user's choice. + auto_hook: data.autoHook ? '1' : '0', + auto_hook_style: data.autoHook ? (data.autoHookStyle || 'classic') : null, }; if (data.type === 'url') { diff --git a/dashboard/src/components/HookModal.jsx b/dashboard/src/components/HookModal.jsx index 5259dc3..1be2ce5 100644 --- a/dashboard/src/components/HookModal.jsx +++ b/dashboard/src/components/HookModal.jsx @@ -33,12 +33,19 @@ const SIZE_OPTIONS = [ { value: 'L', label: 'Large' }, ]; -export default function HookModal({ isOpen, onClose, onGenerate, isProcessing, videoUrl, initialText, durationInSeconds, existingSubtitles }) { +// Last-used hook settings, restored on the next open (style always reset to +// classic otherwise, which users read as the picker being broken). +function loadHookPrefs() { + try { return JSON.parse(localStorage.getItem('os_hook_prefs')) || {}; } catch { return {}; } +} + +export default function HookModal({ isOpen, onClose, onGenerate, isProcessing, videoUrl, initialText, durationInSeconds, existingSubtitles, hasCaptions, serverRender, burnedHook }) { + const prefs = loadHookPrefs(); const [text, setText] = useState(initialText || 'POV: You are using the viral hook feature'); - const [position, setPosition] = useState('top'); - const [size, setSize] = useState('M'); - const [style, setStyle] = useState('classic'); - const [entranceAnimation, setEntranceAnimation] = useState('spring'); + const [position, setPosition] = useState(prefs.position || 'top'); + const [size, setSize] = useState(prefs.size || 'M'); + const [style, setStyle] = useState(prefs.style || 'classic'); + const [entranceAnimation, setEntranceAnimation] = useState(prefs.entranceAnimation || 'spring'); const [displayDuration, setDisplayDuration] = useState(5); if (!isOpen) return null; @@ -159,6 +166,12 @@ export default function HookModal({ isOpen, onClose, onGenerate, isProcessing, v onChange={setPosition} size="sm" /> + {position === 'bottom' && hasCaptions && ( +

+ This clip has captions near the bottom — the hook may + overlap them (and TikTok's UI). Top is the safe zone. +

+ )} {/* Size Control */} @@ -173,7 +186,7 @@ export default function HookModal({ isOpen, onClose, onGenerate, isProcessing, v {/* Entrance Animation (new) */} -
+

Entrance

+ {serverRender && ( +

+ This clip re-renders on the server, where the hook is + static — the entrance animation won't apply. +

+ )}
{/* Display Duration (new) */} @@ -204,6 +223,13 @@ export default function HookModal({ isOpen, onClose, onGenerate, isProcessing, v
+ {burnedHook && ( +
+ This clip already has a hook burned in ("{burnedHook}"). + Adding another will stack on top of it. +
+ )} +
Tip: keep it short and punchy. Using "POV:" or specific questions works best for retention.
@@ -214,11 +240,18 @@ export default function HookModal({ isOpen, onClose, onGenerate, isProcessing, v cancel @@ -270,6 +284,31 @@ export default function MediaInput({ onProcess, isProcessing }) { Targets, not guarantees: the AI returns fewer clips when the material doesn't hold them. Leave blank to let it decide.

+
+ + {autoHook && ( + + )} +
)} diff --git a/dashboard/src/components/ResultCard.jsx b/dashboard/src/components/ResultCard.jsx index 5d98a39..6b334eb 100644 --- a/dashboard/src/components/ResultCard.jsx +++ b/dashboard/src/components/ResultCard.jsx @@ -1004,6 +1004,9 @@ export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostK initialText={clip.viral_hook_text} durationInSeconds={clip.end && clip.start ? clip.end - clip.start : 30} existingSubtitles={activeLayers.subtitles} + hasCaptions={!!activeLayers.subtitles || /(^|_)subtitled_/.test(serverVideoFile || '')} + serverRender={hasServerBurns} + burnedHook={clip.auto_hook?.text} /> = { L: 1.3, }; +// Percentages must match hooks.py's overlay_y math (top 20% / bottom 70%), +// or the preview drifts from what the server path renders. const POSITION_STYLE: Record = { - top: { top: "18%", bottom: "auto" }, + top: { top: "20%", bottom: "auto" }, center: { top: "50%", bottom: "auto", transform: "translateY(-50%)" }, - bottom: { top: "68%", bottom: "auto" }, + bottom: { top: "70%", bottom: "auto" }, }; // Must mirror hooks.py HOOK_STYLES (the server-side FFmpeg fallback). diff --git a/hooks.py b/hooks.py index 196fa7e..73c1a59 100644 --- a/hooks.py +++ b/hooks.py @@ -37,28 +37,41 @@ _EMOJI_RE = re.compile( "]+" ) -# Emoji-capable fonts, probed at runtime (Windows, WSL, Linux/Docker). +# Emoji-capable fonts, probed at runtime (Windows, WSL, Linux/Docker, macOS). _EMOJI_FONT_CANDIDATES = [ "C:\\Windows\\Fonts\\seguiemj.ttf", "/mnt/c/Windows/Fonts/seguiemj.ttf", "/usr/share/fonts/truetype/noto/NotoColorEmoji.ttf", "/usr/share/fonts/noto-emoji/NotoColorEmoji.ttf", + "/System/Library/Fonts/Apple Color Emoji.ttc", ] -def _load_emoji_font(font_size): - """Return an emoji-capable font at the requested size, or None. +# Bitmap strike sizes color-emoji fonts ship with. NotoColorEmoji (the font +# the Docker image installs) ONLY loads at its strike size — asking for an +# arbitrary size raises "invalid pixel size" — so glyphs are rendered at the +# native size and rescaled at draw time. +_EMOJI_BITMAP_SIZES = [109, 128, 136, 160, 96, 72, 64, 32] - Fonts that only support a fixed bitmap size (e.g. NotoColorEmoji) fail to - load at arbitrary sizes; those are treated as unavailable rather than - breaking the layout with wrongly-sized glyphs.""" + +def _load_emoji_font(font_size): + """Return (font, native_size) for an emoji-capable font, or None. + + native_size == font_size for scalable fonts (Segoe UI Emoji); for + fixed-bitmap fonts (NotoColorEmoji) it is the strike size the font + actually loaded at, and the renderer scales glyphs down from it.""" for path in _EMOJI_FONT_CANDIDATES: if not os.path.exists(path): continue try: - return ImageFont.truetype(path, font_size) + return ImageFont.truetype(path, font_size), font_size except Exception: - continue + pass + for native in _EMOJI_BITMAP_SIZES: + try: + return ImageFont.truetype(path, native), native + except Exception: + continue return None @@ -76,28 +89,63 @@ def _split_emoji_runs(text): return runs +def _emoji_scale(font, emoji_font): + """Draw-time scale factor from the emoji font's native size to the text + size. 1.0 for scalable emoji fonts; < 1 for fixed-bitmap strikes.""" + efont, native = emoji_font + target = getattr(font, "size", native) + return target / float(native) if native else 1.0 + + def _measure_width(draw, text, font, emoji_font): - """Pixel width of a line, measuring emoji runs with the emoji font.""" + """Pixel width of a line, measuring emoji runs with the emoji font. + + emoji_font is the (font, native_size) pair from _load_emoji_font, or None.""" width = 0.0 for is_emoji, chunk in _split_emoji_runs(text): - use_font = emoji_font if (is_emoji and emoji_font) else font - width += draw.textlength(chunk, font=use_font) + if is_emoji and emoji_font: + width += (draw.textlength(chunk, font=emoji_font[0]) + * _emoji_scale(font, emoji_font)) + else: + width += draw.textlength(chunk, font=font) return width -def _draw_mixed(draw, xy, text, font, emoji_font, fill, outline=None): - """Draw a line, rendering emoji runs with the emoji font (in color if - supported). outline: optional (color, px) stroke drawn under the text.""" +def _render_emoji_chunk(chunk, emoji_font, scale, fill): + """Rasterize an emoji run at the font's native size, scaled to the text + size. Returns an RGBA image ready to alpha-composite, or None.""" + efont, native = emoji_font + probe = ImageDraw.Draw(Image.new('RGBA', (1, 1))) + w = int(probe.textlength(chunk, font=efont)) + if w <= 0: + return None + # Emoji glyphs can overshoot the em box slightly; 1.3x covers it. + tmp = Image.new('RGBA', (w, int(native * 1.3)), (0, 0, 0, 0)) + d = ImageDraw.Draw(tmp) + try: + d.text((0, 0), chunk, font=efont, embedded_color=True) + except TypeError: + d.text((0, 0), chunk, font=efont, fill=fill) + if scale == 1.0: + return tmp + return tmp.resize((max(int(w * scale), 1), max(int(tmp.height * scale), 1)), + Image.LANCZOS) + + +def _draw_mixed(img, draw, xy, text, font, emoji_font, fill, outline=None): + """Draw a line onto img, rendering emoji runs with the emoji font (in + color if supported, rescaled when the font is a fixed-size bitmap). + outline: optional (color, px) stroke drawn under the text.""" x, y = xy stroke_w = outline[1] if outline else 0 stroke_fill = outline[0] if outline else None for is_emoji, chunk in _split_emoji_runs(text): if is_emoji and emoji_font: - try: - draw.text((x, y), chunk, font=emoji_font, embedded_color=True) - except TypeError: - draw.text((x, y), chunk, font=emoji_font, fill=fill) - x += draw.textlength(chunk, font=emoji_font) + scale = _emoji_scale(font, emoji_font) + rendered = _render_emoji_chunk(chunk, emoji_font, scale, fill) + if rendered is not None: + img.alpha_composite(rendered, (int(x), int(y))) + x += draw.textlength(chunk, font=emoji_font[0]) * scale else: if stroke_w: draw.text((x, y), chunk, font=font, fill=fill, @@ -314,7 +362,7 @@ def create_hook_image(text, target_width, output_image_path="hook_overlay.png", x = 20 + int(box_width - line_w) // 2 # Draw text in the style's color (emoji runs use the emoji font) - _draw_mixed(draw_final, (x, current_y), line, font, emoji_font, + _draw_mixed(img, draw_final, (x, current_y), line, font, emoji_font, fill=text_fill, outline=outline) current_y += line_h + line_spacing diff --git a/main.py b/main.py index 50e8862..f63ea69 100644 --- a/main.py +++ b/main.py @@ -72,7 +72,7 @@ OUTPUT — RETURN ONLY VALID JSON (no markdown, no comments). Order clips by pre "video_description_for_tiktok": "", "video_description_for_instagram": "", "video_title_for_youtube_short": "", - "viral_hook_text": "<SHORT punchy text overlay (max 10 words). MUST BE IN THE SAME LANGUAGE AS THE VIDEO TRANSCRIPT. Examples: 'POV: You realized...', 'Did you know?', 'Stop doing this!'>" + "viral_hook_text": "<SHORT punchy text overlay (max 10 words) with 1-2 fitting emojis. MUST BE IN THE SAME LANGUAGE AS THE VIDEO TRANSCRIPT. Examples: 'POV: You realized... 😳', 'Did you know? 🤯', 'Stop doing this! 🚫'>" }} ] }} @@ -882,6 +882,47 @@ def auto_caption_clip(clip_path, transcript, clip_start, clip_end): return None +def auto_hook_clip(clip_path, clip): + """Burn the clip's Gemini hook text into the finished clip (AUTO_HOOK=1). + + In-place on the canonical clip file, BEFORE the watermark and captions + layers, so every existing derived-name convention (subtitled_/recut_ + walk-backs, R2 archive, restore after redeploy) keeps working untouched. + + Returns the burned hook config dict, or None when skipped or failed — a + hook problem must never cost the user the clip itself (same fail-open + contract as auto_caption_clip).""" + text = (clip.get('viral_hook_text') or '').strip() + if not text: + return None + style = os.environ.get("AUTO_HOOK_STYLE", "classic") + try: + seconds = float(os.environ.get("AUTO_HOOK_SECONDS", "5")) + except ValueError: + seconds = 5.0 + try: + from hooks import add_hook_to_video, HOOK_STYLES + if style not in HOOK_STYLES: + style = "classic" + output_dir = os.path.dirname(clip_path) + tmp_path = os.path.join( + output_dir, f"temp_autohook_{uuid.uuid4().hex[:8]}.mp4") + try: + add_hook_to_video(clip_path, text, tmp_path, position="top", + duration=seconds, style=style) + os.replace(tmp_path, clip_path) + finally: + if os.path.exists(tmp_path): + os.remove(tmp_path) + print(f" 🪝 Hook burned ({style}, {seconds:g}s): {text}") + return {"text": text, "style": style, "position": "top", + "duration_seconds": seconds} + except Exception as e: + print(f" ⚠️ Auto-hook failed ({type(e).__name__}: {e}) — " + f"delivering the clip without it.") + return None + + def render_clip(input_video, final_output_video, output_format="auto", force_strategy=None, crop_overrides=None): """Route a cut clip through the right renderer for the chosen output format. @@ -1586,6 +1627,13 @@ if __name__ == '__main__': subprocess.run(cut_command, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) success = render_clip(clip_temp_path, clip_final_path, output_format) + # Hook first, under the watermark, and captions always + # last. Each worker writes only its own clip dict, so the + # re-dump after the pool is race-free. + if success and os.environ.get("AUTO_HOOK") == "1": + burned = auto_hook_clip(clip_final_path, clip) + if burned: + clip['auto_hook'] = burned if success and os.environ.get("WATERMARK") == "1": apply_watermark(clip_final_path) if success: @@ -1610,6 +1658,12 @@ if __name__ == '__main__': except Exception as e: print(f" ❌ Clip {i+1} failed: {type(e).__name__}: {e}") + # 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): + with open(metadata_file, 'w') as f: + json.dump(clips_data, f, indent=2) + # Clean up original if requested if args.url and not args.keep_original and os.path.exists(input_video): os.remove(input_video)