diff --git a/app.py b/app.py index e22dcd0..aaacc19 100644 --- a/app.py +++ b/app.py @@ -381,11 +381,15 @@ def _canonical_clip_file(output_dir, base_name, index): """ clean = f"{base_name}_clip_{index + 1}.mp4" try: - # subtitled_*_{clean} also matches subtitled__recut__{clean}, - # i.e. a captioned recut; the bare recut_ pattern covers recuts that - # shipped uncaptioned. + # subtitled_*_{clean} also matches subtitled__recut__{clean} + # and subtitled__hooked__{clean}, i.e. captioned recuts and + # captioned hooks; the bare recut_/hooked_/hook_ patterns cover + # derivations that shipped uncaptioned (hook_ is the legacy manual- + # hook prefix, kept so old jobs still resolve). derived = (glob.glob(os.path.join(output_dir, f"subtitled_*_{clean}")) - + glob.glob(os.path.join(output_dir, f"recut_*_{clean}"))) + + glob.glob(os.path.join(output_dir, f"recut_*_{clean}")) + + glob.glob(os.path.join(output_dir, f"hooked_*_{clean}")) + + glob.glob(os.path.join(output_dir, f"hook_{clean}"))) except Exception: derived = [] if not derived: @@ -408,6 +412,18 @@ def _strip_burned_captions(output_dir, filename): filename = m.group(1) +def _strip_burned_hook(output_dir, filename): + """Walk ``hooked__`` (and legacy ``hook_``) prefixes back to the file + without a burned hook. Same fail-safe contract as _strip_burned_captions: + the name is returned unchanged when there is nothing to strip or the + underlying file is gone.""" + while True: + m = re.match(r'^(?:hooked_\d+_|hook_)(.+)$', filename) + if not m or not os.path.exists(os.path.join(output_dir, m.group(1))): + return filename + filename = m.group(1) + + def _reapply_captions(job_id, clip_index, video_path): """Re-burn the default captions onto a freshly derived file. @@ -2044,7 +2060,7 @@ async def edit_clip( # Zooms would crop burned-in captions/hooks off screen, so tell # the editor when the source already carries them. `filename` is # the original clip name (safe_input_path is an ASCII temp copy). - has_captions = ("subtitled_" in filename) or ("hook_" in filename) + has_captions = ("subtitled_" in filename) or ("hook_" in filename) or ("hooked_" in filename) filter_data = editor.get_ffmpeg_filter(vid_file, duration, fps=fps, width=width, height=height, transcript=transcript, has_captions=has_captions) # 4. Apply @@ -3284,12 +3300,13 @@ async def remove_subtitles(req: RemoveSubtitlesRequest, request: Request): class HookRequest(BaseModel): job_id: str clip_index: int - text: str + text: Optional[str] = "" input_filename: Optional[str] = None position: Optional[str] = "top" # top, center, bottom size: Optional[str] = "M" # S, M, L duration_seconds: Optional[float] = None # None = hook visible for the whole clip style: Optional[str] = "classic" # classic/dark/yellow/red/outline/outline_yellow + remove: Optional[bool] = False # strip the burned hook instead of adding one @app.post("/api/hook") async def add_hook(req: HookRequest, request: Request): @@ -3328,44 +3345,55 @@ async def add_hook(req: HookRequest, request: Request): if not os.path.exists(input_path): raise HTTPException(status_code=404, detail=f"Video file not found: {input_path}") - # Same invariant as /api/edit: overlay onto the clip WITHOUT its burned + if not req.remove and not (req.text or "").strip(): + raise HTTPException(status_code=400, detail="Hook text is required") + + # Same invariant as /api/edit: derive from the clip WITHOUT its burned # captions, then put them back on top, so a later restyle never stacks a - # second caption layer (see _reapply_captions). + # second caption layer (see _reapply_captions). The hook layer is stripped + # too: a new hook REPLACES the burned one (auto-hook or a previous manual + # one) instead of stacking on top of it. clean_name = _strip_burned_captions(output_dir, filename) had_captions = clean_name != filename - if had_captions: - filename = clean_name - input_path = os.path.join(output_dir, clean_name) + clean_name = _strip_burned_hook(output_dir, clean_name) + filename = clean_name + input_path = os.path.join(output_dir, clean_name) - # Output video - output_filename = f"hook_{filename}" - output_path = os.path.join(output_dir, output_filename) - - # Map Size to Scale - size_map = {"S": 0.8, "M": 1.0, "L": 1.3} - font_scale = size_map.get(req.size, 1.0) + if req.remove: + # Nothing to burn: the hook-less file is the target; captions (if the + # clip had them) go back on below. + output_filename = filename + output_path = input_path + reservation_id = None + else: + output_filename = f"hooked_{int(time.time())}_{filename}" + output_path = os.path.join(output_dir, output_filename) - # Meter the FFmpeg overlay re-encode (no-op for BYOK / self-host). - hook_minutes = _cloud_config.HOOK_MINUTES if BILLING_ENABLED else 0 - reservation_id = await reserve_managed_action( - request, hook_minutes, req.job_id, "hook") + # Map Size to Scale + size_map = {"S": 0.8, "M": 1.0, "L": 1.3} + font_scale = size_map.get(req.size, 1.0) - try: - # Run in thread pool - def run_hook(): - add_hook_to_video(input_path, req.text, output_path, position=req.position, font_scale=font_scale, duration=req.duration_seconds, style=req.style) + # Meter the FFmpeg overlay re-encode (no-op for BYOK / self-host). + hook_minutes = _cloud_config.HOOK_MINUTES if BILLING_ENABLED else 0 + reservation_id = await reserve_managed_action( + request, hook_minutes, req.job_id, "hook") - loop = asyncio.get_event_loop() - await loop.run_in_executor(None, run_hook) + try: + # Run in thread pool + def run_hook(): + add_hook_to_video(input_path, req.text, output_path, position=req.position, font_scale=font_scale, duration=req.duration_seconds, style=req.style) + + loop = asyncio.get_event_loop() + await loop.run_in_executor(None, run_hook) + + except Exception as e: + print(f"❌ Hook Error: {e}") + if reservation_id: + await _metering.release_reservation(reservation_id) + raise HTTPException(status_code=500, detail=str(e)) - except Exception as e: - print(f"❌ Hook Error: {e}") if reservation_id: - await _metering.release_reservation(reservation_id) - raise HTTPException(status_code=500, detail=str(e)) - - if reservation_id: - await _metering.commit_reservation(reservation_id) + await _metering.commit_reservation(reservation_id) # Captions back on top (see /api/edit for the same invariant). if had_captions: @@ -3374,11 +3402,26 @@ async def add_hook(req: HookRequest, request: Request): if recap: output_filename = os.path.basename(recap) + # Record the burned hook so the editor knows what the clip carries (the + # auto-hook pipeline writes the same key). + if req.remove: + clip_data.pop('auto_hook', None) + else: + clip_data['auto_hook'] = { + "text": req.text, "style": req.style, "position": req.position, + "duration_seconds": req.duration_seconds, + } + # Update Persistence (Same logic as subtitles) # Update InMemory Jobs if req.clip_index < len(job['result']['clips']): - job['result']['clips'][req.clip_index]['video_url'] = f"/videos/{req.job_id}/{output_filename}" - + mem_clip = job['result']['clips'][req.clip_index] + mem_clip['video_url'] = f"/videos/{req.job_id}/{output_filename}" + if req.remove: + mem_clip.pop('auto_hook', None) + else: + mem_clip['auto_hook'] = clip_data['auto_hook'] + # Update Metadata on Disk try: if req.clip_index < len(clips): @@ -3394,7 +3437,8 @@ async def add_hook(req: HookRequest, request: Request): return { "success": True, - "new_video_url": f"/videos/{req.job_id}/{output_filename}" + "new_video_url": f"/videos/{req.job_id}/{output_filename}", + "burned_hook": None if req.remove else clip_data['auto_hook'], } class TranslateRequest(BaseModel): diff --git a/cloud/videos.py b/cloud/videos.py index f2d7a87..f084fd1 100644 --- a/cloud/videos.py +++ b/cloud/videos.py @@ -4,6 +4,7 @@ purge after the subscription grace period. import asyncio import glob import os +import re from datetime import timedelta from fastapi import APIRouter, HTTPException, Request @@ -72,6 +73,20 @@ async def archive_job(user_id, job_id, clips, output_dir): except Exception as e: print(f"⚠️ R2 upload failed for {clean_key}: {e}") + # A captioned hook is a chain (subtitled__hooked__): + # the hooked_ intermediate must come back too, or a restored project's + # caption restyle cannot walk back to the hook-only file and would + # silently drop or stack layers. + m = re.match(r'^subtitled_\d+_((?:hooked_\d+_|hook_).+)$', filename) + if m: + mid_path = os.path.join(output_dir, m.group(1)) + if os.path.exists(mid_path): + mid_key = storage.job_key(user_id, job_id, m.group(1)) + try: + await asyncio.to_thread(storage.upload_file, mid_path, mid_key) + except Exception as e: + print(f"⚠️ R2 upload failed for {mid_key}: {e}") + if not uploaded: return async with database.session() as s: @@ -128,6 +143,19 @@ async def archive_clip_edit(user_id, job_id, clip_index, output_dir, new_filenam new_key = storage.job_key(user_id, job_id, new_filename) await asyncio.to_thread(storage.upload_file, local_path, new_key) + # Same chain rule as archive_job: a captioned hook needs its hooked_ + # intermediate archived too, or the restored project cannot re-style. + m = re.match(r'^subtitled_\d+_((?:hooked_\d+_|hook_).+)$', new_filename) + if m: + mid_path = os.path.join(output_dir, m.group(1)) + if os.path.exists(mid_path): + try: + await asyncio.to_thread( + storage.upload_file, mid_path, + storage.job_key(user_id, job_id, m.group(1))) + except Exception as e: + print(f"⚠️ R2 upload failed for hook intermediate of {job_id}: {e}") + metadata_r2_key = None meta_files = glob.glob(os.path.join(output_dir, "*_metadata.json")) if meta_files: diff --git a/dashboard/src/components/HookModal.jsx b/dashboard/src/components/HookModal.jsx index 1be2ce5..827a8a5 100644 --- a/dashboard/src/components/HookModal.jsx +++ b/dashboard/src/components/HookModal.jsx @@ -39,7 +39,7 @@ 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 }) { +export default function HookModal({ isOpen, onClose, onGenerate, onRemove, 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(prefs.position || 'top'); @@ -224,9 +224,20 @@ 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. +
+

+ This clip has a hook burned in ("{burnedHook}"). + Generating replaces it with the new one. +

+ {onRemove && ( + + )}
)} diff --git a/dashboard/src/components/ResultCard.jsx b/dashboard/src/components/ResultCard.jsx index 6b334eb..c06ab96 100644 --- a/dashboard/src/components/ResultCard.jsx +++ b/dashboard/src/components/ResultCard.jsx @@ -48,7 +48,7 @@ export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostK // subtitled file (double-subtitle bug). const stripBurns = (filename) => { let f = filename || '', prev; - do { prev = f; f = f.replace(/^subtitled_\d+_/, '').replace(/^hook_/, ''); } while (f !== prev); + do { prev = f; f = f.replace(/^subtitled_\d+_/, '').replace(/^hooked_\d+_/, '').replace(/^hook_/, ''); } while (f !== prev); return f; }; const originalVideoUrl = getApiUrl((clip.video_url || '').replace(/[^/]+$/, stripBurns((clip.video_url || '').split('/').pop()))); @@ -158,7 +158,12 @@ export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostK // True when the current server file already carries burned-in content. // Browser (Remotion) renders compose over the ORIGINAL clip, so using them // here would silently drop those burns — chain via server FFmpeg instead. - const hasServerBurns = /(^|_)(subtitled|hook)_/.test(serverVideoFile || ''); + const hasServerBurns = /(^|_)(subtitled|hook|hooked)_/.test(serverVideoFile || ''); + + // The hook currently burned into the server file (auto-hook or a manual + // one). /api/hook REPLACES it; tracked locally so the modal stays honest + // after edits without refetching the job. + const [burnedHook, setBurnedHook] = useState(clip.auto_hook?.text || null); // Fetch clip duration from transcript endpoint useEffect(() => { @@ -463,6 +468,39 @@ export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostK if (data.new_video_url) { setCurrentVideoUrl(getApiUrl(data.new_video_url)); setServerVideoFile(data.new_video_url.split('/').pop()); + setBurnedHook(data.burned_hook?.text ?? payload.text ?? null); + if (videoRef.current) videoRef.current.load(); + setShowHookModal(false); + } + } catch (e) { + setEditError(e.message); + setTimeout(() => setEditError(null), 5000); + } finally { + setIsHooking(false); + } + }; + + // Strip the burned hook (auto-hook or manual) off the server file. + const handleRemoveHook = async () => { + setIsHooking(true); + setEditError(null); + try { + const res = await apiFetch('/api/hook', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + job_id: jobId, + clip_index: index, + remove: true, + input_filename: serverVideoFile, + }), + }); + if (!res.ok) throw new Error(await res.text()); + const data = await res.json(); + if (data.new_video_url) { + setCurrentVideoUrl(getApiUrl(data.new_video_url)); + setServerVideoFile(data.new_video_url.split('/').pop()); + setBurnedHook(null); if (videoRef.current) videoRef.current.load(); setShowHookModal(false); } @@ -1006,7 +1044,8 @@ export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostK existingSubtitles={activeLayers.subtitles} hasCaptions={!!activeLayers.subtitles || /(^|_)subtitled_/.test(serverVideoFile || '')} serverRender={hasServerBurns} - burnedHook={clip.auto_hook?.text} + burnedHook={burnedHook} + onRemove={burnedHook ? handleRemoveHook : null} /> _" (21), -# "temp_hook__" (19), "autosubs__" + ".ass" (24). Budgeting 120 bytes -# leaves room for all of them stacked and still lands well under the limit. +# "hooked__" (18), "temp_hook__" (19), "autosubs__" + ".ass" (24). +# Budgeting 120 bytes leaves room for all of them stacked (worst chain: +# subtitled__hooked___clip_NN.mp4 ≈ 171 bytes) under the limit. # # The old cap was 100 CHARACTERS, which is 300 bytes of Bengali or Arabic — over # the limit before any decoration. It surfaced as OSError 36 killing the hook @@ -883,13 +884,15 @@ def auto_caption_clip(clip_path, transcript, clip_start, clip_end): def auto_hook_clip(clip_path, clip): - """Burn the clip's Gemini hook text into the finished clip (AUTO_HOOK=1). + """Burn the clip's Gemini hook text as a DERIVED file (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. + Writes ``hooked__`` next to the canonical clip, exactly + like captions write ``subtitled__...``: the canonical stays clean, so + the hook can later be replaced or removed by walking the prefix back + (app.py `_strip_burned_hook`). Captions are then burned ON TOP of the + hooked file, keeping the "captions are always the last layer" invariant. - Returns the burned hook config dict, or None when skipped or failed — a + Returns (hooked_path, hook_config), 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() @@ -905,18 +908,13 @@ def auto_hook_clip(clip_path, clip): 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) + out_path = os.path.join( + output_dir, f"hooked_{int(time.time())}_{os.path.basename(clip_path)}") + add_hook_to_video(clip_path, text, out_path, position="top", + duration=seconds, style=style) print(f" 🪝 Hook burned ({style}, {seconds:g}s): {text}") - return {"text": text, "style": style, "position": "top", - "duration_seconds": seconds} + return out_path, {"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.") @@ -1627,19 +1625,21 @@ 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 + # Layer order: watermark burns into the canonical (so any + # later hook replacement, which re-derives from it, keeps + # the branding), the hook is a derived hooked_ file, and + # captions go last on top of whichever is current. Each + # worker writes only its own clip dict, so the re-dump + # after the pool is race-free. if success and os.environ.get("WATERMARK") == "1": apply_watermark(clip_final_path) + deliver_path = clip_final_path + if success and os.environ.get("AUTO_HOOK") == "1": + hooked = auto_hook_clip(clip_final_path, clip) + if hooked: + deliver_path, clip['auto_hook'] = hooked if success: - # Captions last, so they sit on top of the watermark and - # the canonical file stays clean for re-styling. - auto_caption_clip(clip_final_path, transcript, start, end) + auto_caption_clip(deliver_path, transcript, start, end) print(f" ✅ Clip {i+1} ready: {clip_final_path}") return success finally: