fix: marca de agua sobre el contenido + resistencia a la pérdida del disco de trabajo

1. Watermark al 40% de la altura en vez de arriba del todo: ahí caía en la
   banda negra/desenfocada del 9:16, espacio muerto que se recorta sin tocar
   la imagen. Un 16:9 letterboxed ocupa del 34% al 66%, así que ahora quitarla
   obliga a cortar vídeo de verdad.

2. OUTPUT_DIR no es durable en prod (cada redeploy lo vacía), y los endpoints
   que leen ficheros del job devolvían 404 en proyectos que el usuario sigue
   viendo en su biblioteca: transcript, download-all, subtítulos, hooks,
   efectos, doblaje y publicación. Nuevo _ensure_job_files() que rehidrata
   desde R2 bajo demanda reutilizando el flujo de /restore. Se deja fuera el
   polling de /api/status para no machacar R2.

3. download-all no encontraba ningún clip en proyectos restaurados: el
   metadata.json en disco nunca lleva video_url (se inyecta solo en memoria),
   así que derivaba nombres vacíos. Ahora usa el registro en memoria (que
   además refleja ediciones subtitled_/hook_) y cae al nombre canónico.

Verificado en local con docker compose contra R2 real: transcript 200 con 103
palabras y ZIP de 6,2 MB con los 4 clips, sobre un proyecto sin ficheros en
disco.
This commit is contained in:
juancarlos.cavero 2026-07-20 22:00:11 +02:00
parent d2fd9d3d1b
commit e8cfa5fdd7
2 changed files with 58 additions and 6 deletions

48
app.py
View file

@ -1075,6 +1075,7 @@ async def get_source_video(job_id: str):
@app.get("/api/jobs/{job_id}/download-all") @app.get("/api/jobs/{job_id}/download-all")
async def download_all_clips(job_id: str, request: Request): async def download_all_clips(job_id: str, request: Request):
"""Bundle the current version of every clip of a job into one ZIP.""" """Bundle the current version of every clip of a job into one ZIP."""
await _ensure_job_files(job_id, request)
if job_id in jobs: if job_id in jobs:
await _assert_job_owner(request, jobs[job_id]) await _assert_job_owner(request, jobs[job_id])
@ -1086,9 +1087,20 @@ async def download_all_clips(job_id: str, request: Request):
with open(json_files[0], 'r', encoding='utf-8') as f: with open(json_files[0], 'r', encoding='utf-8') as f:
data = json.load(f) data = json.load(f)
# The metadata file on disk never carries video_url — the pipeline doesn't
# write it, it's injected into the in-memory job record. So prefer the live
# record (it also tracks edits like subtitled_/hook_ renames) and fall back
# to the canonical name a job/restore rebuilds, instead of finding nothing.
base_name = os.path.basename(json_files[0]).replace('_metadata.json', '')
mem_clips = ((jobs.get(job_id) or {}).get('result') or {}).get('clips') or []
files = [] files = []
for i, clip in enumerate(data.get('shorts', [])): for i, clip in enumerate(data.get('shorts', [])):
filename = os.path.basename(clip.get('video_url', '').split('/')[-1]) url = None
if i < len(mem_clips):
url = (mem_clips[i] or {}).get('video_url')
url = url or clip.get('video_url')
filename = os.path.basename(url.split('/')[-1]) if url else f"{base_name}_clip_{i+1}.mp4"
path = os.path.join(output_dir, filename) path = os.path.join(output_dir, filename)
if filename and os.path.exists(path): if filename and os.path.exists(path):
files.append((i, path)) files.append((i, path))
@ -1220,6 +1232,33 @@ async def restore_project(job_id: str, request: Request):
} }
async def _ensure_job_files(job_id: str, request: Request) -> bool:
"""Make a completed job usable again after its working files vanished.
OUTPUT_DIR is not durable — a container restart or redeploy wipes it — so
endpoints that read a job's files would 404 on a project the user can still
see in their library. Pull it back from R2 on demand (same path as the
explicit /restore), so editing keeps working instead of dead-ending.
Returns True when the job is available afterwards. Never raises: callers
keep their own 404s for jobs that genuinely don't exist.
"""
job_dir = os.path.join(OUTPUT_DIR, job_id)
if job_id in jobs and glob.glob(os.path.join(job_dir, "*_metadata.json")):
return True
if not BILLING_ENABLED:
return False
try:
await restore_project(job_id, request)
print(f"♻️ Auto-restored {job_id} from the library (working files were gone).")
return True
except HTTPException:
return False
except Exception as e:
print(f"⚠️ Auto-restore failed for {job_id}: {e}")
return False
from editor import VideoEditor from editor import VideoEditor
from subtitles import generate_srt, generate_ass, burn_subtitles, generate_srt_from_video from subtitles import generate_srt, generate_ass, burn_subtitles, generate_srt_from_video
from hooks import add_hook_to_video from hooks import add_hook_to_video
@ -1246,6 +1285,7 @@ async def edit_clip(
if not final_api_key: if not final_api_key:
raise gemini_missing_error() raise gemini_missing_error()
await _ensure_job_files(req.job_id, request)
if req.job_id not in jobs: if req.job_id not in jobs:
raise HTTPException(status_code=404, detail="Job not found") raise HTTPException(status_code=404, detail="Job not found")
@ -1407,6 +1447,7 @@ class SubtitleRequest(BaseModel):
@app.get("/api/clip/{job_id}/{clip_index}/transcript") @app.get("/api/clip/{job_id}/{clip_index}/transcript")
async def get_clip_transcript(job_id: str, clip_index: int, request: Request): async def get_clip_transcript(job_id: str, clip_index: int, request: Request):
"""Return word-level captions for a specific clip, formatted for Remotion.""" """Return word-level captions for a specific clip, formatted for Remotion."""
await _ensure_job_files(job_id, request)
if job_id not in jobs: if job_id not in jobs:
raise HTTPException(status_code=404, detail="Job not found") raise HTTPException(status_code=404, detail="Job not found")
@ -1504,6 +1545,7 @@ async def generate_effects_config(
if not final_api_key: if not final_api_key:
raise gemini_missing_error() raise gemini_missing_error()
await _ensure_job_files(req.job_id, request)
if req.job_id not in jobs: if req.job_id not in jobs:
raise HTTPException(status_code=404, detail="Job not found") raise HTTPException(status_code=404, detail="Job not found")
@ -1612,6 +1654,7 @@ async def generate_effects_config(
@app.post("/api/subtitle") @app.post("/api/subtitle")
async def add_subtitles(req: SubtitleRequest, request: Request): async def add_subtitles(req: SubtitleRequest, request: Request):
await require_managed_entitlement(request) await require_managed_entitlement(request)
await _ensure_job_files(req.job_id, request)
if req.job_id not in jobs: if req.job_id not in jobs:
raise HTTPException(status_code=404, detail="Job not found") raise HTTPException(status_code=404, detail="Job not found")
@ -1773,6 +1816,7 @@ class HookRequest(BaseModel):
@app.post("/api/hook") @app.post("/api/hook")
async def add_hook(req: HookRequest, request: Request): async def add_hook(req: HookRequest, request: Request):
await require_managed_entitlement(request) await require_managed_entitlement(request)
await _ensure_job_files(req.job_id, request)
if req.job_id not in jobs: if req.job_id not in jobs:
raise HTTPException(status_code=404, detail="Job not found") raise HTTPException(status_code=404, detail="Job not found")
@ -1881,6 +1925,7 @@ async def translate_clip(
if not x_elevenlabs_key: if not x_elevenlabs_key:
raise HTTPException(status_code=400, detail="Missing X-ElevenLabs-Key header") raise HTTPException(status_code=400, detail="Missing X-ElevenLabs-Key header")
await _ensure_job_files(req.job_id, request)
if req.job_id not in jobs: if req.job_id not in jobs:
raise HTTPException(status_code=404, detail="Job not found") raise HTTPException(status_code=404, detail="Job not found")
@ -1975,6 +2020,7 @@ import httpx
@app.post("/api/social/post") @app.post("/api/social/post")
async def post_to_socials(req: SocialPostRequest, request: Request): async def post_to_socials(req: SocialPostRequest, request: Request):
await _ensure_job_files(req.job_id, request)
if req.job_id not in jobs: if req.job_id not in jobs:
raise HTTPException(status_code=404, detail="Job not found") raise HTTPException(status_code=404, detail="Job not found")

16
main.py
View file

@ -687,11 +687,17 @@ def render_clip(input_video, final_output_video, output_format="auto"):
return process_video_to_vertical(input_video, final_output_video, aspect_ratio=aspect) return process_video_to_vertical(input_video, final_output_video, aspect_ratio=aspect)
# Watermark geometry, as fractions of the clip width/height. Top-left (not # Watermark geometry, as fractions of the clip width/height.
# bottom) on purpose: the bottom strip is what gets cropped away when a clip is #
# re-posted, so a bottom mark is trivially removed. # Vertical placement is the whole point: the top and bottom strips of a 9:16
# clip are either black bars or blurred filler (GENERAL layout), so a mark up
# there is cropped away without touching a single pixel of real footage. At 40%
# of the height it sits inside the content band — a 16:9 source letterboxed
# into 9:16 spans roughly 34%-66% — so removing the mark means cutting into the
# picture. Left-aligned, like OpusClip's.
WATERMARK_WIDTH_RATIO = 0.30 WATERMARK_WIDTH_RATIO = 0.30
WATERMARK_MARGIN_RATIO = 0.05 WATERMARK_MARGIN_RATIO = 0.05
WATERMARK_Y_RATIO = 0.40
WATERMARK_OPACITY = 0.85 WATERMARK_OPACITY = 0.85
@ -722,8 +728,8 @@ def apply_watermark(video_path):
return False return False
wm_w = max(80, int(vw * WATERMARK_WIDTH_RATIO)) wm_w = max(80, int(vw * WATERMARK_WIDTH_RATIO))
# Same pixel inset on both axes so the corner gap reads as square. x = int(vw * WATERMARK_MARGIN_RATIO)
x = y = int(vw * WATERMARK_MARGIN_RATIO) y = int(vh * WATERMARK_Y_RATIO)
filt = ( filt = (
f"[1:v]scale={wm_w}:-1,format=rgba," f"[1:v]scale={wm_w}:-1,format=rgba,"
f"colorchannelmixer=aa={WATERMARK_OPACITY}[wm];" f"colorchannelmixer=aa={WATERMARK_OPACITY}[wm];"