feat(hook): replace semantics — a new hook swaps the burned one, plus remove

The auto-hook was burned into the canonical clip in place, so editing the
hook stacked a second overlay on top of the first. Hooks now follow the
exact derivation pattern captions use:

- main.py: auto_hook_clip writes hooked_<ts>_<clean>.mp4 next to the clean
  canonical instead of mutating it; captions burn on top of the hooked file
  (subtitled_<ts>_hooked_<ts>_<clean>). Watermark moves BEFORE the hook so
  the branding lives in the canonical and survives hook replacement.
- app.py: _strip_burned_hook walks hooked_/legacy hook_ prefixes back like
  _strip_burned_captions; /api/hook strips captions AND the old hook before
  burning, so a new hook always REPLACES the previous one. New remove flag
  strips the hook entirely (captions re-applied, no metering). Burned hook
  recorded/cleared in clip metadata (auto_hook key) and returned as
  burned_hook. _canonical_clip_file resolves hooked_*/hook_* derivations.
- cloud/videos.py: archive the hooked_ intermediate of a captioned hook so
  restored projects keep the walk-back chain editable.
- ResultCard: stripBurns knows hooked_<ts>_ (the Remotion preview now
  composes over the truly clean clip — no more stacked preview), burned
  hook tracked in state, remove handler wired to the modal.
- HookModal: warning now says replace, plus a 'remove hook from clip'
  action when one is burned.
This commit is contained in:
juancarlos.cavero 2026-08-19 16:01:53 +02:00
parent ac0138269d
commit 2b2e287a9b
5 changed files with 195 additions and 73 deletions

70
app.py
View file

@ -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_<ts>_recut_<ts>_{clean},
# i.e. a captioned recut; the bare recut_ pattern covers recuts that
# shipped uncaptioned.
# subtitled_*_{clean} also matches subtitled_<ts>_recut_<ts>_{clean}
# and subtitled_<ts>_hooked_<ts>_{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_<ts>_`` (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,17 +3345,28 @@ 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:
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}"
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)
# Map Size to Scale
@ -3374,10 +3402,25 @@ 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:
@ -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):

View file

@ -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_<ts>_hooked_<ts>_<clean>):
# 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:

View file

@ -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
</div>
{burnedHook && (
<div className="p-3 border border-rule rounded-input text-xs text-warn">
This clip already has a hook burned in ("{burnedHook}").
Adding another will stack on top of it.
<div className="p-3 border border-rule rounded-input text-xs text-muted space-y-2">
<p>
This clip has a hook burned in ("{burnedHook}").
Generating replaces it with the new one.
</p>
{onRemove && (
<button
onClick={onRemove}
disabled={isProcessing}
className="text-warn underline underline-offset-2 hover:opacity-80 transition-opacity"
>
remove hook from clip
</button>
)}
</div>
)}

View file

@ -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}
/>
<TranslateModal

52
main.py
View file

@ -577,8 +577,9 @@ def get_video_resolution(video_path):
# Byte budget for the sanitized video title used as the stem of every derived
# file. Filesystems cap a name in BYTES (255 on ext4), not characters, and the
# pipeline decorates this stem: "_clip_10.mp4" (12), "subtitled_<ts>_" (21),
# "temp_hook_<hex8>_" (19), "autosubs_<ts>_" + ".ass" (24). Budgeting 120 bytes
# leaves room for all of them stacked and still lands well under the limit.
# "hooked_<ts>_" (18), "temp_hook_<hex8>_" (19), "autosubs_<ts>_" + ".ass" (24).
# Budgeting 120 bytes leaves room for all of them stacked (worst chain:
# subtitled_<ts>_hooked_<ts>_<stem>_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_<ts>_<clip filename>`` next to the canonical clip, exactly
like captions write ``subtitled_<ts>_...``: 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,17 +908,12 @@ 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",
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)
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",
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}) — "
@ -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: