import os import llm_backend import re import sys import uuid import subprocess import threading import json import shutil import glob import hashlib import hmac import time import zipfile import math import itertools import functools import asyncio import signal import socket from datetime import datetime, timezone, timedelta from dotenv import load_dotenv from typing import Any, Dict, Optional, List from contextlib import asynccontextmanager from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Request, Header, BackgroundTasks from fastapi.middleware.cors import CORSMiddleware from fastapi.staticfiles import StaticFiles from fastapi.responses import HTMLResponse, FileResponse, JSONResponse from starlette.background import BackgroundTask from pydantic import BaseModel from s3_uploader import upload_job_artifacts, list_all_clips, upload_actor_to_s3, list_actor_gallery, upload_video_to_gallery, list_video_gallery import recut import layout_ranges load_dotenv() # Constants UPLOAD_DIR = "uploads" OUTPUT_DIR = "output" os.makedirs(UPLOAD_DIR, exist_ok=True) os.makedirs(OUTPUT_DIR, exist_ok=True) # Configuration # Default to 1 if not set, but user can set higher for powerful servers MAX_CONCURRENT_JOBS = int(os.environ.get("MAX_CONCURRENT_JOBS", "5")) MAX_FILE_SIZE_MB = 2048 # 2GB limit # How TikTok receives our uploads. MEDIA_UPLOAD lands the video in the user's # TikTok drafts so they finish the post inside TikTok's own editor; DIRECT_POST # publishes straight to their feed, which is Upload-Post's default. # # Drafts are the safer default for an automated pipeline: nothing reaches an # audience without the account owner seeing it first, and TikTok's own editor is # where covers, sounds and hashtags actually get chosen. The UI must say so — # a user who expects a published post and finds a draft will read it as a bug. TIKTOK_POST_MODE = os.environ.get("TIKTOK_POST_MODE", "MEDIA_UPLOAD").strip() # Ceiling for the working directory once it lives on a persistent volume: the # age-based sweep alone can't stop a burst of long videos from filling the disk. # 0 disables the cap. OUTPUT_MAX_GB = int(os.environ.get("OUTPUT_MAX_GB", "25")) # Same idea for source uploads, which are the biggest single files on disk. UPLOADS_MAX_GB = int(os.environ.get("UPLOADS_MAX_GB", "15")) # Pre-flight quality gate: warn before processing a YouTube source below this # height (0 disables). Only applies to URLs; uploads are whatever the user gave. QUALITY_GATE_MIN_HEIGHT = int(os.environ.get("QUALITY_GATE_MIN_HEIGHT", "720")) # Reject sources shorter than this before starting (0 disables). A 24s YouTube # Short cannot yield 15-60s clips: Gemini returns nothing, the job burns # managed minutes and dies with "no usable clips" (prod 20-ago: 3 of 5 recent # failures were exactly this, one user retrying the same 24s video). MIN_SOURCE_SECONDS = int(os.environ.get("MIN_SOURCE_SECONDS", "45")) QUALITY_PROBE_SCRIPT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "quality_probe.py") DISABLE_YOUTUBE_URL = os.environ.get("DISABLE_YOUTUBE_URL", "false").lower() in ("1", "true", "yes") # Every log line in this module is emoji-prefixed, and a Windows console is # cp1252 by default. _recover_jobs_from_disk() prints one during startup, so # without this the server dies before it ever listens: # # UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-1 # ERROR: Application startup failed. Exiting. # # subtitles._configure_stdio solved this for the transcription path; the server # needs it too, and needs it before the first print. for _stream in (sys.stdout, sys.stderr): if hasattr(_stream, "reconfigure"): try: _stream.reconfigure(encoding="utf-8", errors="replace") except Exception: pass # ---- Cloud billing (paid / managed-keys) integration -------------------------- # All paid-mode code lives in the optional `cloud/` package and is imported ONLY # when BILLING_ENABLED is set. With the flag off, the app behaves exactly as the # self-hosted BYOK app does today (no extra dependencies required). BILLING_ENABLED = os.environ.get("BILLING_ENABLED", "").lower() in ("1", "true", "yes") # Job/file retention (issue #46). Self-host defaults to 24h: the 1h sweep kept # deleting finished projects under users who never touched their env, and the # OUTPUT_MAX_GB / UPLOADS_MAX_GB caps below already bound the disk. Cloud keeps # the tight default because clips are archived to R2 as soon as a job finishes. JOB_RETENTION_SECONDS = int( os.environ.get("JOB_RETENTION_SECONDS", "3600" if BILLING_ENABLED else "86400") ) # The retained download of a URL job (--keep-original) is the one artifact that # is a full copy of someone else's video rather than something we made, so it # can be aged out ahead of the clips it produced. Defaults to the job clock, # i.e. no change: dropping it earlier costs the clip editor, whose rerender, # reframe, scenes and EDL endpoints all read that file and answer 409 once it # is gone. Lower it only if you would rather lose in-session re-edits than # keep the original around. Uploads are deliberately untouched: that file is # the user's own content, which they attested to owning. SOURCE_RETENTION_SECONDS = int( os.environ.get("SOURCE_RETENTION_SECONDS", str(JOB_RETENTION_SECONDS)) ) # Force full pipeline logs to the client even under billing (local debugging). DEBUG_LOGS = os.environ.get("DEBUG_LOGS", "").lower() in ("1", "true", "yes") if BILLING_ENABLED: import cloud from cloud import managed_keys, metering as _metering, config as _cloud_config, alerts as _alerts from cloud.auth import get_current_user_optional else: cloud = None managed_keys = None _metering = None _cloud_config = None _alerts = None async def get_current_user_optional(request: Request): # No-op dependency in self-host mode: every request is anonymous / BYOK. return None async def _user_from_request(request: Request): """Load the authenticated cloud user (or None). Cheap indexed lookup.""" return await get_current_user_optional(request) async def resolve_gemini(request: Request) -> Optional[str]: """Resolve the Gemini API key for a request. Cloud (hosted) is PAID-ONLY: there is no BYOK for the core pipeline, so the ``X-Gemini-Key`` header is ignored — an entitled user (active plan or trial) gets the managed server key, everyone else gets ``None`` (→ 402, start trial). Self-host keeps BYOK: header wins, else the env fallback. """ if BILLING_ENABLED: user = await _user_from_request(request) if managed_keys.has_active_entitlement(user): return managed_keys.gemini_key() return None header = request.headers.get("X-Gemini-Key") if header: return header return os.environ.get("GEMINI_API_KEY") async def resolve_upload_post(request: Request, body_key: Optional[str] = None): """Resolve the Upload-Post key and the profile to post as. Returns ``(api_key, forced_profile_username_or_None)``. Cloud is paid-only: an entitled user gets the managed key + their own forced profile (body key / user_id ignored); a non-entitled user gets ``(None, None)``. Self-host keeps BYOK: header, then body key, then env. """ if BILLING_ENABLED: user = await _user_from_request(request) if managed_keys.has_active_entitlement(user): profile = await cloud.social_profiles.ensure_profile(user) return managed_keys.upload_post_key(), profile return None, None header = request.headers.get("X-Upload-Post-Key") key = header or body_key or os.environ.get("UPLOAD_POST_API_KEY") return key, None def resolve_post_profile(forced_profile: Optional[str], client_profile: Optional[str]) -> str: """The Upload-Post profile to act as, for posting/scheduling/analytics. Fails closed on purpose. Every call site used to read ``forced_profile or client_profile``, which quietly honours whatever profile the *client* asked for if the server ever failed to resolve its own — one refactor of ``resolve_upload_post`` away from letting a cloud user schedule into someone else's connected accounts. In cloud mode the client value is never consulted: either the server knows the caller's profile or the request is refused. """ if BILLING_ENABLED: if not forced_profile: raise HTTPException( status_code=503, detail="Could not resolve your social profile. Please try again.") return forced_profile # Self-host: no user model, the caller owns the Upload-Post account whose # key resolved above, so it picks its own profile. profile = forced_profile or client_profile if not profile: raise HTTPException(status_code=400, detail="Missing Upload-Post user profile") return profile def gemini_missing_error(): """The right 4xx when no Gemini key could be resolved. 402 for a signed-in-but-not-entitled cloud user (needs a plan); 400 otherwise (BYOK header simply missing). """ if BILLING_ENABLED: return HTTPException(status_code=402, detail={ "error": "no_plan", "message": "This action needs an active plan. Choose a plan or add your own API key.", }) return HTTPException(status_code=400, detail="Missing X-Gemini-Key header") # Probe rate limiter. In-memory, resets on restart by design — the hard monthly # quota lives in the metering ledger; this only stops someone hammering the # proxy with metadata probes. _probe_times: dict = {} # user_id -> [monotonic timestamps] PROBES_PER_HOUR = 15 # Out-of-minutes upsell email: at most one per user per day (a client may # retry the same 402 many times). _last_quota_email: dict = {} _QUOTA_EMAIL_COOLDOWN = 24 * 3600 def _maybe_send_quota_email(user): if user is None or user.plan != "free" or not user.email: return now = time.monotonic() last = _last_quota_email.get(str(user.id)) if last is not None and now - last < _QUOTA_EMAIL_COOLDOWN: return _last_quota_email[str(user.id)] = now from cloud.emails import send_out_of_minutes_email upgrade_url = f"{_cloud_config.settings.frontend_url}/#/pricing" asyncio.create_task(send_out_of_minutes_email(user.email, upgrade_url)) def _check_probe_rate(user_id): now = time.monotonic() times = _probe_times.setdefault(str(user_id), []) times[:] = [t for t in times if now - t < 3600] if len(times) >= PROBES_PER_HOUR: raise HTTPException(status_code=429, detail="Too many requests this hour. Please slow down.") times.append(now) def partial_offer(minutes_required: float, minutes_remaining: float) -> int: """Minutes of the source we can offer to clip instead of a 402, or 0. The offer is the caller's whole remaining balance, floored to full minutes (the reservation is in whole minutes), and only when it is both worth clipping (``PARTIAL_MIN_MINUTES``) and actually shorter than the source. """ from cloud import config as _cfg # plain constants; importable with billing off offer = int(math.floor(max(0.0, float(minutes_remaining or 0)))) if offer < _cfg.PARTIAL_MIN_MINUTES or offer >= minutes_required: return 0 return offer def plan_partial_minutes(minutes_required: int, minutes_remaining: float, max_minutes): """How many minutes to reserve for a source of ``minutes_required``. Returns ``(reserve, partial)``: ``partial`` is None for a normal whole-video job, or ``{"processed_minutes", "total_minutes"}`` when the caller asked (``max_minutes``) to clip only the first part. The slice is capped by the balance as well as by the request, so a client cannot name a bigger cut than it can pay for; when the slice would be too small the request falls through to the ordinary quota check (and its 402). """ if max_minutes is None: return minutes_required, None try: asked = float(max_minutes) except (TypeError, ValueError): return minutes_required, None from cloud import config as _cfg cap = int(math.floor(min(asked, max(0.0, float(minutes_remaining or 0))))) if minutes_required <= cap or cap < _cfg.PARTIAL_MIN_MINUTES: return minutes_required, None return cap, {"processed_minutes": cap, "total_minutes": minutes_required} async def reserve_process_minutes(request, url, input_path, job_id, max_minutes=None): """Meter a managed /api/process request. Returns (user_id, priority, reservation_id, plan, partial). ``partial`` is None unless the caller asked (``max_minutes``) to clip only the first part of a source its balance cannot cover whole; then it is the ``plan_partial_minutes`` dict and only that many minutes are reserved. BYOK / self-host requests don't consume minutes (priority 2, no reservation). For a managed (entitled, no BYOK header) request this probes the input duration, enforces the per-user concurrent-job limit, and reserves minutes — raising 402 (quota) or 429 (too many jobs) as needed. NOTE: in cloud mode ``resolve_gemini`` ignores ``X-Gemini-Key`` (paid-only, no BYOK), so we must NOT skip metering just because that header is present — otherwise a client could send a dummy header and run unlimited managed jobs on the operator's key for free. Only skip metering when billing is off. """ if not BILLING_ENABLED: return None, 2, None, None, None user = await _user_from_request(request) if not managed_keys.has_active_entitlement(user): return None, 2, None, None, None # shouldn't happen (resolve_gemini would have 402'd) priority = _cloud_config.PLAN_PRIORITY.get(user.plan, 1) # Per-user simultaneous job cap. limit = _cloud_config.PLAN_JOB_LIMIT.get(user.plan, 2) active = sum(1 for j in jobs.values() if j.get('user_id') == user.id and j.get('status') in ('queued', 'processing')) if active >= limit: raise HTTPException(status_code=429, detail="You already have the maximum number of jobs running. Please wait.") # Out of minutes -> 402 before probing. The probe is a real yt-dlp metadata # fetch through the download proxies, and every job costs at least one # minute, so a user at zero can be turned away without spending bandwidth on # a duration we are about to reject anyway (4 of 12 submissions in the # 21-aug-2026 sample were quota 402s that had already paid for their probe). balance = await _metering.get_balance(user.id) if balance["remaining"] < 1: _maybe_send_quota_email(user) raise HTTPException(status_code=402, detail={ "error": "quota_exceeded", "minutes_required": 1, "minutes_remaining": balance["remaining"], "partial_minutes": 0, }) # Probe rate limit: probing costs a (cheap) proxied metadata call. The # 20-minute monthly quota is the real bound on free usage; there is no daily # job cap. _check_probe_rate(user.id) # Probe input duration (blocking → run in a thread). When today's paid # traffic is over budget, the probe (and below, the job itself) runs # without the per-GB proxy: statics or nothing. try: from cloud import proxy_ledger as _pl paid_allowed = not await _pl.budget_exceeded() except Exception: pass loop = asyncio.get_event_loop() try: if url: minutes = await loop.run_in_executor( None, functools.partial(_metering.probe_url_minutes, url, allow_paid=paid_allowed)) else: minutes = await loop.run_in_executor(None, _metering.probe_file_minutes, input_path) except Exception as e: from yt_clients import NotASingleVideo if isinstance(e, NotASingleVideo): raise HTTPException(status_code=400, detail=( f"{e} Paste the link of one video (youtube.com/watch?v=... " "or youtu.be/...).")) raise HTTPException(status_code=400, detail="Could not determine the video duration. Try a different source.") finally: # A probe that had to reach the paid proxy leaves an event behind; # record it (DB row + Telegram) whether or not the probe succeeded. try: from cloud import proxy_ledger as _pl await _pl.drain_probe_events() except Exception: pass minutes = max(1, math.ceil(minutes)) # A source longer than the balance can be clipped in part instead of # refused: the wall offers "the first N minutes" (``partial_minutes`` in # the 402 below) and the client resubmits with ``max_minutes``. reserve, partial = plan_partial_minutes(minutes, balance["remaining"], max_minutes) try: reservation_id = await _metering.reserve_minutes(user.id, reserve, job_id) except _metering.QuotaExceeded as e: _maybe_send_quota_email(user) raise HTTPException(status_code=402, detail={ "error": "quota_exceeded", "minutes_required": e.required, "minutes_remaining": e.remaining, "partial_minutes": partial_offer(e.required, e.remaining), }) return user.id, priority, reservation_id, user.plan, partial async def reserve_managed_action(request, minutes, job_id, job_type): """Reserve quota for a synchronous managed action (e.g. thumbnail image gen). Returns a reservation_id to commit/release around the work, or None for BYOK / self-host. Raises 402 when the user is out of minutes. """ if not BILLING_ENABLED: return None if minutes <= 0: # Free action (e.g. burning captions). Skip the ledger entirely rather # than writing a 0-minute row on every call — the endpoint's own # entitlement gate is what bounds it. return None user = await _user_from_request(request) if not managed_keys.has_active_entitlement(user): return None # BYOK header path (self-host) — not metered try: return await _metering.reserve_minutes(user.id, minutes, job_id, job_type) except _metering.QuotaExceeded as e: _maybe_send_quota_email(user) raise HTTPException(status_code=402, detail={ "error": "quota_exceeded", "minutes_required": e.required, "minutes_remaining": e.remaining, }) async def require_managed_entitlement(request): """Gate a managed compute endpoint that doesn't resolve a Gemini key itself. Some endpoints (subtitle/hook FFmpeg re-encodes, render proxy, the thumbnail upload that kicks off a YouTube download + Whisper) do expensive server work without ever calling ``resolve_gemini``, so nothing was stopping an anonymous or non-entitled caller from driving unbounded compute in cloud mode. In cloud mode this rejects them with 402; it's a no-op for self-host (BILLING off). """ if not BILLING_ENABLED: return None user = await _user_from_request(request) if not managed_keys.has_active_entitlement(user): raise gemini_missing_error() return user async def _owner_id(request): """The authenticated cloud user's id to stamp on a new job/session, or None for self-host / BYOK / anonymous (BILLING off → nothing to scope).""" if not BILLING_ENABLED: return None user = await _user_from_request(request) return user.id if user else None async def _assert_job_owner(request, record): """Cloud multi-tenant guard: reject unless the caller owns this in-memory job/session record. No-op for self-host (BILLING off) and for records with no owner stamped (BYOK / self-host jobs never set ``user_id``). Returns 404 rather than 403 so a non-owner can't even confirm the id exists. UUID ids already make these stores hard to enumerate; this closes the gap for a shared/leaked id. """ if not BILLING_ENABLED: return owner = record.get("user_id") if isinstance(record, dict) else None if owner is None: return user = await _user_from_request(request) # Compare as strings: live jobs store a uuid.UUID, but jobs recovered from # the .owner sidecar store its string form — UUID != str is always True. if user is None or str(user.id) != str(owner): raise HTTPException(status_code=404, detail="Not found") # Application State # PriorityQueue holds (priority, seq, job_id). Lower priority dispatches first: # pro=0, starter/creator=1, BYOK/anonymous/self-host=2. The seq counter keeps # FIFO order within a priority and makes the tuples always comparable. With # BILLING disabled every job enqueues at priority 2 → plain FIFO as before. job_queue = asyncio.PriorityQueue() _job_seq = itertools.count() jobs: Dict[str, Dict] = {} thumbnail_sessions: Dict[str, Dict] = {} publish_jobs: Dict[str, Dict] = {} # {publish_id: {status, result, error}} # Semester to limit concurrency to MAX_CONCURRENT_JOBS concurrency_semaphore = asyncio.Semaphore(MAX_CONCURRENT_JOBS) def _enqueue_job(job_id: str, priority: int = 2): job_queue.put_nowait((priority, next(_job_seq), job_id)) def _relocate_root_job_artifacts(job_id: str, job_output_dir: str) -> bool: """ Backward-compat rescue: If main.py accidentally wrote metadata/clips into OUTPUT_DIR root (e.g. output/_...), move them into output// so the API can find and serve them. """ try: os.makedirs(job_output_dir, exist_ok=True) root = OUTPUT_DIR pattern = os.path.join(root, f"{job_id}_*_metadata.json") meta_candidates = sorted(glob.glob(pattern), key=lambda p: os.path.getmtime(p), reverse=True) if not meta_candidates: return False # Move the newest metadata and its associated clips. metadata_path = meta_candidates[0] base_name = os.path.basename(metadata_path).replace("_metadata.json", "") # Move metadata dest_metadata = os.path.join(job_output_dir, os.path.basename(metadata_path)) if os.path.abspath(metadata_path) != os.path.abspath(dest_metadata): shutil.move(metadata_path, dest_metadata) # Move any clips that match the same base_name into the job folder clip_pattern = os.path.join(root, f"{base_name}_clip_*.mp4") for clip_path in glob.glob(clip_pattern): dest_clip = os.path.join(job_output_dir, os.path.basename(clip_path)) if os.path.abspath(clip_path) != os.path.abspath(dest_clip): shutil.move(clip_path, dest_clip) # Also move any temp_ clips that might remain temp_clip_pattern = os.path.join(root, f"temp_{base_name}_clip_*.mp4") for clip_path in glob.glob(temp_clip_pattern): dest_clip = os.path.join(job_output_dir, os.path.basename(clip_path)) if os.path.abspath(clip_path) != os.path.abspath(dest_clip): shutil.move(clip_path, dest_clip) return True except Exception: return False def _canonical_clip_file(output_dir, base_name, index): """The file to serve for clip ``index``, preferring a derived version. The pipeline writes the clean reframe as ``_clip_.mp4`` and any post-processing (auto-captions, /api/subtitle re-styles, and clip-editor recuts) as ``subtitled__.mp4`` / ``recut__.mp4``, keeping the original for re-styling. Every place that rebuilds the canonical name from disk — restore after a restart, the R2 upload, the download bundle — must therefore resolve to the newest derived file, or clips silently lose their captions (or their recut) on a redeploy. """ clean = f"{base_name}_clip_{index + 1}.mp4" try: # 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"hooked_*_{clean}")) + glob.glob(os.path.join(output_dir, f"hook_{clean}"))) except Exception: derived = [] if not derived: return clean # Highest timestamp wins — that's the most recent styling. return os.path.basename(max(derived, key=os.path.getmtime)) def _clips_actually_rendered(job_id, output_dir, base_name, clips): """Keep only the clips whose file is really on disk. Returns (kept, missing). The metadata JSON is written BEFORE any clip renders, and main.py's worker pool swallows a per-clip exception (it only prints "❌ Clip N failed") and still exits 0. So ``shorts`` is what Gemini promised, not what ffmpeg produced, and ``_canonical_clip_file`` happily returns the name of a file that was never written. Handing those back as delivered clips is what let a job that rendered NOTHING be marked completed: the minutes were committed, ClipsDelivered fired, ``archive_job`` skipped every missing file and uploaded the metadata alone — which, because it returns before writing the Project row, left the job unrestorable and invisible in history — and the dashboard offered clips whose only existence was a title, so "download all" answered 404 "No clip files found for this job" (ticket #4711, job 89d76bbc, 6-sep-2026). Measured over the R2 archive on 7-sep-2026: 195 of 1687 archived jobs held a metadata file and not one clip, across 184 users. Trust the disk, not the promise. """ # main.py announces the file it actually finished for each clip # (CLIP_READY, printed after the whole reframe/watermark/hook/caption # chain). Prefer it over rebuilding the name: the marker is what the file # IS, _canonical_clip_file is a guess from the naming convention. ready_files = (jobs.get(job_id) or {}).get('ready_files') or {} kept = [] for i, clip in enumerate(clips): clip_filename = (ready_files.get(i) or _canonical_clip_file(output_dir, base_name, i)) clip_path = os.path.join(output_dir, clip_filename) try: present = os.path.getsize(clip_path) > 0 except OSError: present = False if not present: print(f"⚠️ Clip {i + 1} of {job_id} never rendered " f"({clip_filename}) — dropping it from the result.") continue clip['video_url'] = f"/videos/{job_id}/{clip_filename}" kept.append(clip) return kept, len(clips) - len(kept) def _strip_burned_captions(output_dir, filename): """Walk ``subtitled__`` prefixes back to the file without burned captions. Returns the name unchanged when there is nothing to strip (or when the underlying file is gone, e.g. a library restore that only kept the current version). """ while True: m = re.match(r'^subtitled_\d+_(.+)$', filename) if not m or not os.path.exists(os.path.join(output_dir, m.group(1))): return 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. Captions must always be the LAST layer. Editing or hooking a clip that already had them burned in produced `edited_subtitled_<...>`, and the next subtitle pass then stacked a second caption layer on top of the first — visibly doubled and unreadable in real user clips (26-jul-2026). So the derivation runs on the clean file and captions go back on afterwards. Returns the captioned path, or None if there was nothing to caption. """ try: meta_files = glob.glob(os.path.join(OUTPUT_DIR, job_id, "*_metadata.json")) if not meta_files: return None with open(meta_files[0], 'r') as f: data = json.load(f) transcript = data.get('transcript') clips = data.get('shorts', []) if not transcript or clip_index >= len(clips): return None clip = clips[clip_index] import main as _main # A recut clip is a concatenation of source segments, so the flat # start..end window is wrong for it — caption against the clip-relative # remapped transcript instead (same trick /api/subtitle uses). recipe_segments = (clip.get('recipe') or {}).get('segments') if recipe_segments: v_transcript = recut.virtual_transcript(transcript, recipe_segments) return _main.auto_caption_clip( video_path, v_transcript, 0.0, recut.total_duration(recipe_segments)) return _main.auto_caption_clip(video_path, transcript, clip['start'], clip['end']) except Exception as e: print(f"⚠️ Could not re-apply captions to {video_path}: {e}") return None def _recover_jobs_from_disk(): """Rebuild completed jobs from OUTPUT_DIR after a restart (issue #46 / #18). Jobs live in memory, so a restart used to orphan finished clips that are still on disk: the frontend restores the job_id from localStorage but every endpoint answers 404 "Job not found". Rebuild a minimal completed record for each job directory that has a metadata JSON. """ recovered = 0 try: entries = os.listdir(OUTPUT_DIR) except FileNotFoundError: return for job_id in entries: job_path = os.path.join(OUTPUT_DIR, job_id) if not os.path.isdir(job_path) or job_id in jobs: continue json_files = glob.glob(os.path.join(job_path, "*_metadata.json")) if not json_files: continue try: with open(json_files[0], 'r') as f: data = json.load(f) base_name = os.path.basename(json_files[0]).replace('_metadata.json', '') clips = data.get('shorts', []) for i, clip in enumerate(clips): if not clip.get('video_url'): clip['video_url'] = ( f"/videos/{job_id}/" f"{_canonical_clip_file(job_path, base_name, i)}") owner = None owner_path = os.path.join(job_path, ".owner") if os.path.exists(owner_path): with open(owner_path) as f: raw = f.read().strip() owner = int(raw) if raw.isdigit() else (raw or None) jobs[job_id] = { 'status': 'completed', 'logs': ["♻️ Job recovered from disk after server restart."], 'output_dir': job_path, 'user_id': owner, 'result': {'clips': clips, 'cost_analysis': data.get('cost_analysis')}, } recovered += 1 except Exception as e: print(f"⚠️ Could not recover job {job_id}: {e}") if recovered: print(f"♻️ Recovered {recovered} completed job(s) from disk.") # --- Mid-flight job resume (survive a redeploy without losing work) ---------- # A job lives only in memory, so killing the container mid-processing used to # lose it: the user's clip just stops. We persist a tiny manifest per job and, # on startup, re-enqueue any that were interrupted — the user sees it resume # instead of vanish. Bounded by MAX_RESUME_ATTEMPTS so a video that reliably # crashes the worker can't crashloop the service. _RESUME_FILE = ".resume.json" MAX_RESUME_ATTEMPTS = 2 # --- Deploy handover (two instances, one disk) ------------------------------- # Coolify starts the NEW container before it stops the old one (rolling # update), and both see the same OUTPUT_DIR. Without coordination the new one # re-enqueued, at startup, the very jobs the old one was still rendering — # and the old one had 30 s to live anyway. Now: # * every instance stamps OUTPUT_DIR/.instance with its id at startup; an # instance that sees another id there knows it is the OLD one and DRAINS: # it finishes what it is running, starts nothing new, and leaves queued # manifests for the new instance to pick up; # * a running job writes a heartbeat into its manifest every few seconds, # so the new instance skips manifests that are alive elsewhere and resumes # only the stale ones (an instance killed mid-job stops heartbeating); # * SIGTERM (docker stop) also drains, up to DRAIN_TIMEOUT_SECONDS — keep it # under the Coolify stop grace period — before letting uvicorn exit. INSTANCE_ID = os.environ.get("INSTANCE_ID") or socket.gethostname() _INSTANCE_MARKER = ".instance" HEARTBEAT_EVERY = 10 # seconds between manifest heartbeats HEARTBEAT_STALE_AFTER = 60 # no heartbeat for this long = nobody has it RESUME_SCAN_INTERVAL = 30 # seconds between looks for stale manifests HANDOVER_CHECK_INTERVAL = 5 # seconds between looks at the marker DRAIN_TIMEOUT_SECONDS = int(os.environ.get("DRAIN_TIMEOUT_SECONDS", "840")) # After the jobs are drained, keep SERVING this long with /health/ready at 503 # before closing the socket: the proxy only drops a container once its Docker # healthcheck has failed interval*retries times (15 s with the Coolify # settings), and closing the socket earlier sends that many seconds of # requests to a dead port. Measured 2026-08-25: ~60 s of alternating 502/200 # per deploy with retries=12 and no grace at all. PROXY_DRAIN_SECONDS = float(os.environ.get("PROXY_DRAIN_SECONDS", "20")) # Once uvicorn has the signal it closes within --timeout-graceful-shutdown # (15 s), but the interpreter then waits for non-daemon threads, and a # request cancelled mid-flight can leave an executor thread stuck in a # network probe (yt-dlp) for as long as that takes. Seen 2026-08-25: "Finished # server process" printed, container alive until the 900 s SIGKILL, deploy # stuck in "Removing old containers". So the process is ended outright a # little after uvicorn was told to stop. Jobs are already drained by then. HARD_EXIT_SECONDS = float(os.environ.get("HARD_EXIT_SECONDS", "30")) _draining = False _stopping = False # SIGTERM received: report not-ready so the # proxy stops routing here before the # listening socket closes _running_jobs: set = set() # job ids with a live subprocess here def _manifest_path(job_id): return os.path.join(OUTPUT_DIR, job_id, _RESUME_FILE) def _read_manifest(job_id): try: with open(_manifest_path(job_id)) as f: return json.load(f) except FileNotFoundError: return None except Exception as e: print(f"⚠️ Bad resume manifest for {job_id}: {e}") return None def _touch_manifest(job_id, now=None): """Stamp 'this instance is running it, as of now' into the manifest.""" m = _read_manifest(job_id) if m is None: return m["heartbeat"] = now if now is not None else time.time() m["instance"] = INSTANCE_ID try: with open(_manifest_path(job_id), "w") as f: json.dump(m, f) except Exception as e: print(f"⚠️ Could not heartbeat manifest for {job_id}: {e}") def _manifest_busy_elsewhere(m, now=None): """True when ANOTHER instance heartbeated this job recently. Our own id with a fresh heartbeat is a job WE were running before a restart of this same container (same hostname) — that one must be resumed, not skipped.""" now = time.time() if now is None else now return (m.get("instance") not in (None, INSTANCE_ID) and now - float(m.get("heartbeat") or 0) < HEARTBEAT_STALE_AFTER) def _write_instance_marker(): try: os.makedirs(OUTPUT_DIR, exist_ok=True) with open(os.path.join(OUTPUT_DIR, _INSTANCE_MARKER), "w") as f: f.write(INSTANCE_ID) except Exception as e: print(f"⚠️ Could not write instance marker: {e}") def _read_instance_marker(): try: with open(os.path.join(OUTPUT_DIR, _INSTANCE_MARKER)) as f: return f.read().strip() except Exception: return None def _begin_drain(reason): global _draining if not _draining: _draining = True print(f"⏸️ Draining ({reason}): finishing {len(_running_jobs)} running job(s), " f"starting none.") def _check_instance_marker(): """A different id in the marker means a newer instance is up: drain.""" other = _read_instance_marker() if other and other != INSTANCE_ID: _begin_drain(f"newer instance {other} is up") return True return False async def _handover_watch(): while not _draining: await asyncio.sleep(HANDOVER_CHECK_INTERVAL) _check_instance_marker() async def _resume_scan(): """Keep looking for manifests nobody is running (the old instance left them queued, or was killed at the end of its grace period).""" while True: await asyncio.sleep(RESUME_SCAN_INTERVAL) if _draining: continue try: _resume_interrupted_jobs() except Exception as e: print(f"⚠️ Resume scan failed: {e}") async def _drain_then_exit(previous_handler, timeout=None, proxy_grace=None, hard_exit_after=None): """Wait for running jobs (bounded), let the proxy notice we are not ready, then hand the signal to uvicorn.""" timeout = DRAIN_TIMEOUT_SECONDS if timeout is None else timeout proxy_grace = PROXY_DRAIN_SECONDS if proxy_grace is None else proxy_grace hard_exit_after = HARD_EXIT_SECONDS if hard_exit_after is None else hard_exit_after deadline = time.time() + timeout while _running_jobs and time.time() < deadline: await asyncio.sleep(1) if _running_jobs: print(f"⏱️ Drain timeout after {timeout}s with {len(_running_jobs)} job(s) still " f"running — they will resume on the next instance.") else: print("✅ Drained: no running jobs.") if proxy_grace > 0: print(f"⏳ Serving {proxy_grace:.0f}s more while the proxy drops this instance.") await asyncio.sleep(proxy_grace) print("👋 Shutting down.") if hard_exit_after > 0: import threading threading.Timer(hard_exit_after, _hard_exit).start() if callable(previous_handler): previous_handler(signal.SIGTERM, None) else: os._exit(0) def _hard_exit(): print(f"⛔ Still alive {HARD_EXIT_SECONDS:.0f}s after the stop signal (a thread " f"is hanging) — exiting now.", flush=True) os._exit(0) def _install_drain_signal_handler(): """Replace uvicorn's SIGTERM handler with drain-first. uvicorn's own handler closes the listening socket at once, which would make Traefik send half the traffic to a refused port for the whole drain.""" previous = signal.getsignal(signal.SIGTERM) loop = asyncio.get_running_loop() def on_sigterm(): global _stopping _stopping = True _begin_drain("SIGTERM") asyncio.ensure_future(_drain_then_exit(previous)) try: loop.add_signal_handler(signal.SIGTERM, on_sigterm) except (NotImplementedError, RuntimeError, ValueError) as e: print(f"⚠️ Drain-on-SIGTERM unavailable ({e}); jobs will resume on restart instead.") def _write_resume_manifest(job_id, cmd, priority, user_id, reservation_id, watermark, webhook_url=None, webhook_secret=None, base_url=None, partial=None): try: path = os.path.join(OUTPUT_DIR, job_id, _RESUME_FILE) with open(path, "w") as f: json.dump({ "cmd": cmd, "priority": priority, "user_id": None if user_id is None else str(user_id), "reservation_id": reservation_id, "watermark": bool(watermark), "attempts": 0, # The caller's webhook must survive a redeploy: a pipeline that # relies on the callback would otherwise hang forever on a job # that resumed fine. The secret is the caller's own HMAC value, # stored next to their video on the same disk — not a server # credential (those are rebuilt from os.environ on resume). "webhook_url": webhook_url, "webhook_secret": webhook_secret, "base_url": base_url, # A resumed job downloads the source again, so the cut must # travel with it: only these minutes were reserved. "partial": partial, }, f) except Exception as e: print(f"⚠️ Could not write resume manifest for {job_id}: {e}") def _clear_resume_manifest(job_id): """Drop the manifest once a job reaches a terminal state, so it is never re-run on a later restart. Only an interrupted (still-running) job keeps it.""" try: os.remove(os.path.join(OUTPUT_DIR, job_id, _RESUME_FILE)) except FileNotFoundError: pass except Exception as e: print(f"⚠️ Could not clear resume manifest for {job_id}: {e}") def _resume_interrupted_jobs() -> set: """Re-enqueue jobs that were mid-processing when the server last stopped. Runs after _recover_jobs_from_disk: a job whose clips already finished has a metadata JSON and is recovered as 'completed', so we only resume manifests with no metadata yet (analysis never finished). Also called periodically (_resume_scan): a manifest another instance is heartbeating is left alone until that heartbeat goes stale, and a job this instance already holds is never enqueued twice. Returns the set of reservation ids for every manifest still on disk — resumed here or alive on the other instance — so the caller can keep them out of the orphaned-reservation refund. Does NO DB work — the DB engine isn't up yet at this point in startup. A poison job (too many attempts) is simply not resumed; its reservation is then refunded as a normal orphan. """ keep_reservations: set = set() try: entries = os.listdir(OUTPUT_DIR) except FileNotFoundError: return keep_reservations resumed = 0 for job_id in entries: job_path = os.path.join(OUTPUT_DIR, job_id) manifest_path = os.path.join(job_path, _RESUME_FILE) if not os.path.isfile(manifest_path): continue if glob.glob(os.path.join(job_path, "*_metadata.json")): # Finished after all — recovered as completed already. _clear_resume_manifest(job_id) continue try: with open(manifest_path) as f: m = json.load(f) except Exception as e: print(f"⚠️ Bad resume manifest for {job_id}: {e}") continue if m.get("reservation_id"): keep_reservations.add(str(m["reservation_id"])) if job_id in jobs: continue # already ours (queued, running or recovered) if _manifest_busy_elsewhere(m): continue # the other instance is on it; we take over if it goes stale attempts = int(m.get("attempts", 0)) + 1 user_id = m.get("user_id") reservation_id = m.get("reservation_id") if attempts > MAX_RESUME_ATTEMPTS: # Poison job: don't resume. Leaving its reservation out of the keep # set lets the orphan sweep refund it, and the user can retry by hand. print(f"🛑 Job {job_id} exceeded {MAX_RESUME_ATTEMPTS} resume attempts — giving up.") _clear_resume_manifest(job_id) if reservation_id: keep_reservations.discard(str(reservation_id)) # let the sweep refund it continue # Rebuild env from scratch — the manifest holds no secrets. Managed # (cloud) jobs get the server key; self-host falls back to its env key. env = os.environ.copy() try: from cloud import proxy_ledger as _pl if BILLING_ENABLED and _pl.budget_exceeded_sync(): env.pop("PROXY_URL", None) # daily paid-proxy budget hit except Exception: pass if BILLING_ENABLED and user_id is not None: try: env["GEMINI_API_KEY"] = managed_keys.gemini_key() except Exception: pass if m.get("watermark"): env["WATERMARK"] = "1" else: env.pop("WATERMARK", None) partial = m.get("partial") if partial and partial.get("processed_minutes"): env["MAX_SOURCE_MINUTES"] = str(partial["processed_minutes"]) else: env.pop("MAX_SOURCE_MINUTES", None) m["attempts"] = attempts try: with open(manifest_path, "w") as f: json.dump(m, f) except Exception: pass jobs[job_id] = { 'status': 'queued', 'logs': [f"♻️ Resuming your video after a server update (attempt {attempts})."], 'cmd': m.get("cmd"), 'env': env, 'output_dir': job_path, 'user_id': None if user_id is None else user_id, 'reservation_id': reservation_id, 'watermark': bool(m.get("watermark")), 'partial': partial or None, 'webhook_url': m.get("webhook_url"), 'webhook_secret': m.get("webhook_secret"), 'base_url': m.get("base_url"), } _enqueue_job(job_id, int(m.get("priority", 2))) resumed += 1 if resumed: print(f"♻️ Re-enqueued {resumed} interrupted job(s) after restart.") return keep_reservations def _dir_size(path: str) -> int: total = 0 for root, _dirs, files in os.walk(path): for f in files: try: total += os.path.getsize(os.path.join(root, f)) except OSError: pass return total # A job dir older than JOB_RETENTION_SECONDS can still be alive: on a busy day # a free job waits over an hour in the queue, and a long render runs past the # hour too. The sweeps used to delete those by age alone, under the worker's # feet: no clips, and the minute reservation stayed held until the 3 h stuck # sweep (22-sep-2026: 21 free jobs lost that way, most of them the user's # first). A manifest pins its dir for at most this long, so one nobody will # ever resume cannot keep a directory on disk forever. ACTIVE_JOB_MAX_SECONDS = int(os.environ.get("ACTIVE_JOB_MAX_SECONDS", str(24 * 3600))) def _job_is_active(job_id, now=None) -> bool: """True while a job is queued or running here, or its resume manifest says it has not reached a terminal state yet (the other instance's jobs during a handover included). The disk sweeps must never touch such a job.""" if job_id in _running_jobs: return True if (jobs.get(job_id) or {}).get('status') in ('queued', 'processing'): return True try: age = (time.time() if now is None else now) - os.path.getmtime(_manifest_path(job_id)) except OSError: return False return age <= ACTIVE_JOB_MAX_SECONDS def _upload_job_id(filename: str) -> str: """Source uploads are stored as ``_``.""" return filename.split("_", 1)[0] def _sweep_expired_job_dirs(now): """Drop job dirs older than JOB_RETENTION_SECONDS, except live jobs.""" for job_id in os.listdir(OUTPUT_DIR): # Not a job: the thumbnails dir backs a StaticFiles mount, so # deleting it would 500 every /thumbnails request until reboot. if job_id == os.path.basename(THUMBNAILS_DIR): continue job_path = os.path.join(OUTPUT_DIR, job_id) if not os.path.isdir(job_path): continue try: expired = now - os.path.getmtime(job_path) > JOB_RETENTION_SECONDS except OSError: continue if not expired or _job_is_active(job_id, now): continue print(f"🧹 Purging old job: {job_id}") shutil.rmtree(job_path, ignore_errors=True) jobs.pop(job_id, None) def _sweep_expired_uploads(now): """Drop source uploads older than JOB_RETENTION_SECONDS, except the source of a job that is still queued or running.""" for filename in os.listdir(UPLOAD_DIR): file_path = os.path.join(UPLOAD_DIR, filename) try: if (now - os.path.getmtime(file_path) > JOB_RETENTION_SECONDS and not _job_is_active(_upload_job_id(filename), now)): os.remove(file_path) except Exception: pass def _enforce_uploads_size_cap(): """Delete the oldest source uploads while UPLOAD_DIR is over UPLOADS_MAX_GB. Sources are only needed while a job runs (and for the preview afterwards), but they're the biggest files on disk — up to MAX_FILE_SIZE_MB each. """ cap = UPLOADS_MAX_GB * 1024 ** 3 if cap <= 0: return used = _dir_size(UPLOAD_DIR) if used <= cap: return files = [] for name in os.listdir(UPLOAD_DIR): p = os.path.join(UPLOAD_DIR, name) if os.path.isfile(p) and not _job_is_active(_upload_job_id(name)): try: files.append((os.path.getmtime(p), p, os.path.getsize(p))) except OSError: pass files.sort() print(f"🧹 Uploads at {used / 1024**3:.1f} GB (cap {UPLOADS_MAX_GB} GB) — trimming.") for _mtime, path, size in files: if used <= cap: break try: os.remove(path) used -= size print(f"🧹 Size cap: removed upload {os.path.basename(path)}") except OSError: pass def _enforce_output_size_cap(): """Delete the oldest job dirs while OUTPUT_DIR is over OUTPUT_MAX_GB.""" cap = OUTPUT_MAX_GB * 1024 ** 3 if cap <= 0: return used = _dir_size(OUTPUT_DIR) if used <= cap: return thumbs = os.path.basename(THUMBNAILS_DIR) candidates = [] for job_id in os.listdir(OUTPUT_DIR): if job_id == thumbs: continue p = os.path.join(OUTPUT_DIR, job_id) if os.path.isdir(p) and not _job_is_active(job_id): try: candidates.append((os.path.getmtime(p), p, job_id)) except OSError: pass candidates.sort() # oldest first print(f"🧹 Output dir at {used / 1024**3:.1f} GB (cap {OUTPUT_MAX_GB} GB) — trimming.") for _mtime, path, job_id in candidates: if used <= cap: break size = _dir_size(path) shutil.rmtree(path, ignore_errors=True) jobs.pop(job_id, None) used -= size print(f"🧹 Size cap: purged {job_id} ({size / 1024**2:.0f} MB)") def _sweep_retained_sources(now=None): """Delete retained downloads older than SOURCE_RETENTION_SECONDS. Only the ``source_video`` a URL job kept in its own directory: an upload is the user's own file and ages out with the job like everything else. Yields the job ids it emptied. A no-op unless the knob is set below the job clock. """ if SOURCE_RETENTION_SECONDS >= JOB_RETENTION_SECONDS: return now = time.time() if now is None else now for job_id in os.listdir(OUTPUT_DIR): if job_id == os.path.basename(THUMBNAILS_DIR): continue try: metas = glob.glob(os.path.join(OUTPUT_DIR, job_id, "*_metadata.json")) if not metas: continue with open(metas[0]) as f: name = json.load(f).get('source_video') if not name: continue src = os.path.join(OUTPUT_DIR, job_id, os.path.basename(name)) if (os.path.exists(src) and now - os.path.getmtime(src) > SOURCE_RETENTION_SECONDS): os.remove(src) yield job_id except Exception: continue async def cleanup_jobs(): """Background task to remove old jobs and files.""" import time print("🧹 Cleanup task started.") while True: try: await asyncio.sleep(300) # Check every 5 minutes now = time.time() # Simple directory cleanup based on modification time # Check OUTPUT_DIR _sweep_expired_job_dirs(now) for job_id in _sweep_retained_sources(now): print(f"🧹 Dropped retained source for job {job_id}") # Hard disk cap. The time-based sweep above bounds the *age* of what # we keep, not its size: a burst of long videos can fill the volume # inside one retention window. Drop the oldest jobs until we're back # under the cap — clips are already archived to R2 and get restored # on demand, so this only costs a re-download. _enforce_output_size_cap() _enforce_uploads_size_cap() # Cleanup SaaSShorts jobs from memory try: saas_expired = [ jid for jid, jdata in list(saas_jobs.items()) if jdata.get("status") in ("completed", "failed") and jdata.get("output_dir") and os.path.isdir(jdata["output_dir"]) and now - os.path.getmtime(jdata["output_dir"]) > JOB_RETENTION_SECONDS ] for jid in saas_expired: del saas_jobs[jid] except NameError: pass # Agent upload slots: expire with their file (the file sweep below # removes it; a slot whose file is gone or too old is dropped). for uid in _sweep_pending_uploads(now): print(f"🧹 Expired agent upload slot {uid}") # Cleanup Uploads _sweep_expired_uploads(now) except Exception as e: print(f"⚠️ Cleanup error: {e}") async def process_queue(): """Background worker to process jobs from the queue with concurrency limit.""" print(f"🚀 Job Queue Worker started with {MAX_CONCURRENT_JOBS} concurrent slots.") while True: try: # Wait for a job (priority, seq, job_id) — lowest priority first. _priority, _seq, job_id = await job_queue.get() if _draining: # Leave it on disk for the next instance (manifest, no heartbeat). print(f"⏸️ Draining — leaving {job_id} for the next instance.") job_queue.task_done() continue # Acquire semaphore slot (waits if max jobs are running) await concurrency_semaphore.acquire() if _draining: concurrency_semaphore.release() job_queue.task_done() print(f"⏸️ Draining — leaving {job_id} for the next instance.") continue print(f"🔄 Acquired slot for job: {job_id}") _running_jobs.add(job_id) _touch_manifest(job_id) # Process in background task to not block the loop (allowing other slots to fill) asyncio.create_task(run_job_wrapper(job_id)) except Exception as e: print(f"❌ Queue dispatch error: {e}") await asyncio.sleep(1) # Monthly proxy bandwidth counter (in-memory; an alert threshold, not a bill — # losing it on a deploy just means the alert re-arms from 0 mid-month). _proxy_month = {"month": None, "bytes": 0, "alerted": False} PROXY_ALERT_GB = 100 def _job_source_url(job) -> Optional[str]: """The ``-u`` argument of the job's main.py command, if it was a URL job.""" cmd = list((job or {}).get('cmd') or []) # The command is ``python -u main.py -u ``: skip past the script # name first or the interpreter's own ``-u`` flag is what gets matched. start = next((i + 1 for i, a in enumerate(cmd) if str(a).endswith('main.py')), 0) for i in range(start, len(cmd) - 1): if cmd[i] in ('-u', '--url'): return cmd[i + 1] return None async def _track_proxy_usage(job_id): job = jobs.get(job_id) or {} # Durable trail + Telegram page whenever the per-GB proxy carried bytes # (cloud mode only: self-host has no DB and pays nobody per GB). if BILLING_ENABLED and job.get('proxy_route'): try: from cloud import proxy_ledger as _pl await _pl.record_download(job_id, job.get('proxy_route'), _job_source_url(job)) except Exception as e: print(f"⚠️ proxy ledger failed for {job_id}: {e}") nbytes = job.get('proxy_bytes') or 0 if not nbytes: return month = datetime.now(timezone.utc).strftime("%Y-%m") if _proxy_month["month"] != month: _proxy_month.update(month=month, bytes=0, alerted=False) _proxy_month["bytes"] += nbytes gb = _proxy_month["bytes"] / 1e9 if gb >= PROXY_ALERT_GB and not _proxy_month["alerted"] and _alerts: _proxy_month["alerted"] = True try: await _alerts.send_admin_alert( "Proxy bandwidth threshold", f"Managed downloads have used {gb:.1f} GB of proxy bandwidth in {month} " f"(threshold {PROXY_ALERT_GB} GB). Review free-plan usage.", ) except Exception as e: print(f"⚠️ Proxy alert failed: {e}") async def run_job_wrapper(job_id): """Wrapper to run job and release semaphore""" # Keep the record itself: run_job writes its status into this same dict, # and if the entry is dropped from ``jobs`` mid-run the reservation must # still be settled (released) instead of staying held for hours. job = jobs.get(job_id) try: if job: await run_job(job_id, job) except Exception as e: print(f"❌ Job wrapper error {job_id}: {e}") finally: # The subprocess returned (success or genuine failure) — a terminal # state, so drop the resume manifest. It only survives if the container # was killed mid-run, which is exactly when we want to resume. _clear_resume_manifest(job_id) # Settle the minute reservation (managed jobs only): commit on success, # release otherwise so the minutes go back to the user. await _settle_reservation(job_id, job) # Archive the completed clips to the user's durable R2 library (history). await _archive_managed_job(job_id) # Autopilot bookkeeping + autopublish (before the generic clips-ready # email, which it replaces for its own jobs). await _autopilot_job_finished(job_id, job) # Fire the caller's webhook (after archive, so durable links exist). await _notify_job_webhook(job_id) # Operational alerting for managed jobs (proxy out of credits / failures). await _record_job_alert(job_id) # Accumulate proxy bandwidth for the monthly cost alert. await _track_proxy_usage(job_id) # Tell the owner their clips are ready (managed jobs, once per job). await _notify_clips_ready(job_id) # Telegram pulse for high-signal activity (first clip / paid user). await _notify_clip_activity(job_id) # Always release semaphore and mark queue task done _running_jobs.discard(job_id) concurrency_semaphore.release() job_queue.task_done() print(f"✅ Released slot for job: {job_id}") async def _archive_managed_job(job_id): if not BILLING_ENABLED: return job = jobs.get(job_id) or {} if not job.get('user_id') or job.get('status') != 'completed': return clips = (job.get('result') or {}).get('clips') or [] if not clips: return try: await cloud.videos.archive_job(job['user_id'], job_id, clips, job['output_dir']) except Exception as e: print(f"⚠️ R2 archive error for {job_id}: {e}") def _archive_clip_edit_bg(job_id: str, clip_index: int, filename: str): """Fire-and-forget R2 re-archive of an edited clip (managed jobs only). Keeps the user's durable library (history/projects) pointing at the current version of each clip without blocking the edit response.""" if not BILLING_ENABLED: return user_id = (jobs.get(job_id) or {}).get('user_id') if not user_id: return output_dir = os.path.join(OUTPUT_DIR, job_id) async def _run(): try: await cloud.videos.archive_clip_edit(user_id, job_id, clip_index, output_dir, filename) except Exception as e: print(f"⚠️ R2 edit archive error for {job_id}: {e}") asyncio.create_task(_run()) async def _autopilot_job_finished(job_id, job): if not BILLING_ENABLED or not job or not job.get('user_id'): return try: reason = None if job.get('status') != 'completed': reason = _alerts._classify_failure(_job_error_text(job.get('logs', []))) await cloud.autopilot.on_job_finished(job_id, job, reason) except Exception as e: print(f"⚠️ Autopilot completion error for {job_id}: {e}") async def _notify_clips_ready(job_id): """Email the owner when their clips finish — processing takes minutes, so this lets them close the tab. Once per job (email_sent flag).""" if not BILLING_ENABLED: return job = jobs.get(job_id) or {} if not job.get('user_id') or job.get('status') != 'completed' or job.get('email_sent'): return clips = (job.get('result') or {}).get('clips') or [] if not clips: return job['email_sent'] = True try: from cloud.database import session as cloud_session from cloud.models import User from cloud.emails import send_clips_ready_email async with cloud_session() as s: user = await s.get(User, job['user_id']) if not user or not user.email: return title = clips[0].get('video_title_for_youtube_short') or clips[0].get('title') or "Your video" # #app opens the app itself. The bare frontend URL showed the marketing # landing to anyone whose browser had not already set the skip flag, # which is the wrong page for someone clicking "View my clips". await send_clips_ready_email(user.email, title, len(clips), f"{_cloud_config.settings.frontend_url}/#app") except Exception as e: print(f"⚠️ Clips-ready email error for {job_id}: {e}") async def _notify_clip_activity(job_id): """Telegram pulse when a PAID user's clips are created. Free-tier activity (including first clips) is deliberately silent: at current signup volume it drowned the ops channel without being actionable. Telegram-only (best effort, no email).""" if not BILLING_ENABLED: return job = jobs.get(job_id) or {} if not job.get('user_id') or job.get('status') != 'completed': return clips = (job.get('result') or {}).get('clips') or [] if not clips: return try: from cloud.database import session as cloud_session from cloud.models import User from cloud import metering async with cloud_session() as s: user = await s.get(User, job['user_id']) if not user: return sub = await metering._active_subscription(s, user.id) if sub is None: return title = clips[0].get('video_title_for_youtube_short') or clips[0].get('title') or "video" n = len(clips) await _alerts.send_telegram( f"🎬 Clips created\n{user.email} ({sub.plan}) — “{title}” ({n} clip{'s' if n != 1 else ''})") except Exception as e: print(f"⚠️ Clip-activity notify error for {job_id}: {e}") # Markers that identify a line as an actual error rather than progress noise. # "Error:" (capital E) catches raised exception lines — RuntimeError:, # DownloadError:, GeminiBlockedError: — which "ERROR:" alone missed, leaving # alerts with a bare "Traceback ... exit code 1" and no cause (prod 20-ago). _ERROR_MARKERS = ("❌", "ERROR:", "Error:", "Traceback", "FATAL", "Exception", "Process failed with exit code", "No metadata file generated", "Execution error:", # A clip render dies in two steps: reframe_v2 raises (it has # no False return, only `return True`), main.py prints this # and falls back to the v1 loop, and only if v1 ALSO fails # does "❌ Clip N failed" appear. The ❌ line then carries # v1's exception, not the one that started it, so without # this marker the alert names the fallback and hides the # cause. Both lines are wanted. "Reframe v2 failed") def _job_error_text(logs) -> str: """The lines that explain WHY a job failed, for the alert's classifier. The tail of the log is usually progress noise (scene detection, ffmpeg banners), which made alerts blame whatever word happened to be nearby — a silent upload got reported as a broken download path, and a Gemini blip as an ffmpeg problem. Pick the error-bearing lines instead, newest last. """ # Per-attempt download warnings are only noise when a later attempt # RECOVERED: HD-direct fails on every job (banned server IP) and a static # proxy takes over, yet its "Video unavailable" made whole alerts read as # download outages when the job actually died in Gemini. When no attempt # succeeded, those lines carry the real cause and must stay. recovered = any("Download succeeded" in ln for ln in logs) hits = [ln for ln in logs if any(m in ln for m in _ERROR_MARKERS) and not (recovered and "Download attempt" in ln)] if not hits: return " ".join(logs[-10:]) # nothing recognisable — fall back to the tail return " ".join(hits[-6:]) async def _record_job_alert(job_id): if not BILLING_ENABLED: return job = jobs.get(job_id) or {} if not job.get('user_id'): return # only track managed jobs ok = job.get('status') == 'completed' err = "" if ok else _job_error_text(job.get('logs', [])) try: await _alerts.record_job_outcome(ok, err) except Exception as e: print(f"⚠️ Alert recording error for {job_id}: {e}") await _track_job_outcome(job, ok, err) async def _track_job_outcome(job, ok, err): """Report the job to OpenPanel, with the user's job index. The index is what makes the retention question answerable: on 26-jul-2026, 491 of 564 users who ever processed a video did it exactly once. Counting distinct users at index 1 versus index >= 2 measures whether the clip quality work moved that, which nothing in the stack could do before. Client-side analytics cannot cover this: a render finishes minutes later, often after the tab is closed, and ad-blockers eat a share of the rest. """ try: from cloud import analytics as _an from sqlalchemy import text as _sa_text from cloud import database as _db user_id = job.get('user_id') job_index = None try: async with _db.session() as s: job_index = (await s.execute(_sa_text( "select count(*) from usage_ledger " "where user_id = :uid and job_type = 'process'"), {"uid": user_id})).scalar() except Exception: pass # an index we cannot read is not worth failing a job over clips = len(((job.get('result') or {}).get('clips')) or []) _an.track( "ClipsDelivered" if ok else "JobFailed", user_id=user_id, job_index=job_index, clips=clips if ok else None, plan=job.get('user_plan'), source="url" if _job_source_url(job) else "upload", reason=(_alerts._classify_failure(err) if not ok and err else None), ) except Exception as e: print(f"⚠️ Analytics error: {e}") # --- Job completion webhooks -------------------------------------------------- # Agents and pipelines (n8n, cron, MCP clients) need push, not poll: a caller # passes webhook_url on /api/process and gets one POST when the job reaches a # terminal state. The URL goes through assert_public_url both at submit and at # delivery time — the second check is what defeats DNS rebinding between them. WEBHOOK_TIMEOUT = 10.0 WEBHOOK_RETRY_DELAYS = (0, 10, 60) # seconds before each attempt def _sign_webhook(body: bytes, secret: str) -> str: import hmac as _hmac import hashlib as _hashlib return "sha256=" + _hmac.new(secret.encode(), body, _hashlib.sha256).hexdigest() async def _webhook_clip_entries(job_id, job): """The payload's clip list: absolute URLs, plus durable R2 links when the job was archived (a webhook consumer usually fetches later, after the 1-hour local retention would have expired the /videos path).""" base = (job.get('base_url') or os.environ.get("PUBLIC_API_URL", "")).rstrip("/") clips = (job.get('result') or {}).get('clips') or [] entries = [] for i, clip in enumerate(clips): rel = clip.get('video_url') or "" entries.append({ "index": i, "title": clip.get('title') or clip.get('video_title_for_youtube_short'), "video_url": f"{base}{rel}" if rel.startswith("/") and base else rel, }) if BILLING_ENABLED and job.get('user_id'): try: from sqlalchemy import select as _select from cloud.database import session as cloud_session from cloud.models import UserVideo from cloud import storage as _storage async with cloud_session() as s: vids = list((await s.execute( _select(UserVideo).where(UserVideo.job_id == job_id) )).scalars()) for v in vids: if v.clip_index is not None and v.clip_index < len(entries): entries[v.clip_index]["download_url"] = _storage.presigned_get( v.r2_key, expires=24 * 3600) except Exception as e: print(f"⚠️ Webhook R2 links failed for {job_id}: {e}") return entries async def _deliver_webhook(url, body: bytes, secret): headers = {"Content-Type": "application/json", "User-Agent": "OpenShorts-Webhook/1.0"} if secret: headers["X-OpenShorts-Signature"] = _sign_webhook(body, secret) from security_utils import assert_public_url, UnsafeURLError loop = asyncio.get_event_loop() for attempt, delay in enumerate(WEBHOOK_RETRY_DELAYS, 1): if delay: await asyncio.sleep(delay) try: # Re-resolve on every attempt: the submit-time check is stale by now. await loop.run_in_executor(None, assert_public_url, url) async with httpx.AsyncClient(timeout=WEBHOOK_TIMEOUT, follow_redirects=False) as client: resp = await client.post(url, content=body, headers=headers) if resp.status_code < 300: print(f"🪝 Webhook delivered to {url} (attempt {attempt})") return print(f"⚠️ Webhook attempt {attempt} to {url}: HTTP {resp.status_code}") except UnsafeURLError as e: print(f"🛑 Webhook URL no longer safe, dropping: {e}") return except Exception as e: print(f"⚠️ Webhook attempt {attempt} to {url} failed: {e}") print(f"❌ Webhook to {url} gave up after {len(WEBHOOK_RETRY_DELAYS)} attempts.") async def _notify_job_webhook(job_id): """Fire the caller's webhook for a terminal job. Runs inside run_job_wrapper's finally AFTER the R2 archive, so durable links exist; the actual delivery (with its retry sleeps) is detached so the worker slot frees immediately.""" job = jobs.get(job_id) or {} url = job.get('webhook_url') if not url or job.get('webhook_sent'): return job['webhook_sent'] = True completed = job.get('status') == 'completed' payload = { "event": "job.completed" if completed else "job.failed", "job_id": job_id, "status": job.get('status'), "clips": (await _webhook_clip_entries(job_id, job)) if completed else [], } if not completed: payload["error"] = _job_error_text(job.get('logs', []))[-500:] body = json.dumps(payload).encode() asyncio.create_task(_deliver_webhook(url, body, job.get('webhook_secret'))) async def _settle_reservation(job_id, job=None): if not BILLING_ENABLED: return job = job if job is not None else (jobs.get(job_id) or {}) reservation_id = job.get('reservation_id') if not reservation_id: return try: if job.get('status') == 'completed': await cloud.metering.commit_reservation(reservation_id) else: await cloud.metering.release_reservation(reservation_id) except Exception as e: print(f"⚠️ Reservation settle error for {job_id}: {e}") def _owned_by(record, uid: str) -> bool: owner = record.get('user_id') if isinstance(record, dict) else None return owner is not None and str(owner) == uid def _rm_under(base_dir: str, relative: str): """Remove a file or directory, refusing anything that escapes ``base_dir``.""" target = _safe_under(base_dir, relative) if not target or target == os.path.realpath(base_dir): return if os.path.isdir(target): shutil.rmtree(target, ignore_errors=True) else: try: os.remove(target) except OSError: pass def _purge_local_jobs_for_user(user_id) -> int: """Delete this user's working files and in-memory records from local disk. Called by cloud/account.py when an account is erased. The durable copies live on R2 and are deleted there; these are the working files on the API's own disk, which would otherwise sit around until the one-hour cleanup sweep — and thumbnails not even then, because that sweep skips their directory. Three stores, because each records ownership differently: - clip jobs: the ``.owner`` file every managed job writes, so jobs recovered from disk after a restart (no in-memory record) count too; - SaaSShorts jobs (``output/saas_``): ``saas_jobs`` only, no marker file, so a restart loses the link and those age out on the sweep; - thumbnail sessions (``output/thumbnails/`` plus the source video in ``uploads/``): likewise in-memory only. Blocking: rmtree over gigabytes of video. Callers must run it in a thread. """ uid = str(user_id) removed = 0 job_ids = {jid for jid, job in list(jobs.items()) if _owned_by(job, uid)} thumbs_dir_name = os.path.basename(THUMBNAILS_DIR) try: entries = os.listdir(OUTPUT_DIR) except OSError: entries = [] for job_id in entries: # Never a job, and it backs a StaticFiles mount: deleting the directory # itself 500s every /thumbnails request until the process restarts. if job_id == thumbs_dir_name: continue try: with open(os.path.join(OUTPUT_DIR, job_id, ".owner")) as f: if f.read().strip() == uid: job_ids.add(job_id) except OSError: continue for job_id in job_ids: _rm_under(OUTPUT_DIR, job_id) jobs.pop(job_id, None) # Source uploads are named "_" (see /api/process). for path in glob.glob(os.path.join(UPLOAD_DIR, f"{glob.escape(job_id)}_*")): try: os.remove(path) except OSError: pass removed += 1 for jid, job in list(saas_jobs.items()): if not _owned_by(job, uid): continue out = job.get('output_dir') if out: _rm_under(OUTPUT_DIR, os.path.basename(out)) saas_jobs.pop(jid, None) removed += 1 for sid, sess in list(thumbnail_sessions.items()): if not _owned_by(sess, uid): continue # Generated thumbnails are served publicly at /thumbnails//... and # nothing else ever deletes them. _rm_under(THUMBNAILS_DIR, sid) video_path = sess.get('video_path') if video_path: _rm_under(UPLOAD_DIR, os.path.basename(video_path)) thumbnail_sessions.pop(sid, None) removed += 1 if removed: print(f"🗑️ Purged {removed} local work item(s) for erased user {uid}.") return removed @asynccontextmanager async def lifespan(app: FastAPI): # Rehydrate finished jobs from disk before serving (survives restarts). _recover_jobs_from_disk() # Re-enqueue jobs that were mid-processing when we stopped (redeploy). Their # reservations must survive the orphan sweep so the resumed run can settle them. _resumed_reservation_ids = _resume_interrupted_jobs() # Deploy handover: claim the marker (any older instance sees it and drains), # keep watching it in case a newer one appears, keep looking for manifests # left behind, and drain instead of dying on docker stop. _write_instance_marker() _install_drain_signal_handler() asyncio.create_task(_handover_watch()) asyncio.create_task(_resume_scan()) # Start worker and cleanup worker_task = asyncio.create_task(process_queue()) cleanup_task = asyncio.create_task(cleanup_jobs()) if BILLING_ENABLED: await cloud.setup_async(app, keep_reservation_ids=_resumed_reservation_ids) # Account erasure lives in cloud/, which can't import app.py; hand it the # one thing only this module can do — wipe the local working files. cloud.account.register_local_purge(_purge_local_jobs_for_user) # Autopilot: watch connected YouTube channels for new videos. Paused # while this instance drains so only the new container submits jobs. cloud.autopilot.start(app, is_active=lambda: not _draining) # Nag on Telegram while the residential proxy is down/out of credits — # a single job-failure alert is easy to miss and ingest stays broken # until someone tops the balance up. asyncio.create_task(_alerts.proxy_watch_loop()) yield # Cleanup (optional: cancel worker) app = FastAPI(lifespan=lifespan) # Cloud mode: attach middleware + routers at import time (before the app serves). if BILLING_ENABLED: cloud.setup_sync(app) # MCP server (/mcp): the pipeline as agent-callable tools. Works in both modes — # cloud requires an osk_ API key, self-host keeps BYOK (see mcp_server.py). import mcp_server as _mcp_server app.include_router(_mcp_server.router) # Enable CORS for frontend. Cloud mode locks this down to the configured origins; # self-host keeps the permissive wildcard it has always used. app.add_middleware( CORSMiddleware, allow_origins=cloud.settings.allowed_origins if BILLING_ENABLED else ["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], # Without this the browser hides them from fetch(), so the clip download had # no total to measure against and could not show progress. Safelisted or not, # they only become readable to JS once they are named here. expose_headers=["Content-Length", "Content-Range", "Accept-Ranges"], ) # Mount static files for serving videos. A miss under /videos// first # tries to bring the job back from R2 (see restoring_static.py): the players # of a reopened project used to 404 while the transcript requests were still # restoring it. Late-bound lambda: the restorer is defined further down. from restoring_static import RestoringStaticFiles import media_auth app.mount("/videos", RestoringStaticFiles( directory=OUTPUT_DIR, guard=media_auth.is_servable, restorer=lambda job_id: _restore_for_public_path(job_id)), name="videos") # Mount static files for serving thumbnails THUMBNAILS_DIR = os.path.join(OUTPUT_DIR, "thumbnails") os.makedirs(THUMBNAILS_DIR, exist_ok=True) app.mount("/thumbnails", StaticFiles(directory=THUMBNAILS_DIR), name="thumbnails") def _safe_under(base_dir: str, user_rel_path: str) -> Optional[str]: """Resolve ``user_rel_path`` under ``base_dir`` and reject path traversal. Returns the absolute path only if it stays inside ``base_dir`` (after following ``..``); otherwise None. Used to sanitize client-supplied file references so ``../../.env`` can't escape the output directories. """ base = os.path.realpath(base_dir) target = os.path.realpath(os.path.join(base, user_rel_path)) if target == base or target.startswith(base + os.sep): return target return None class ProcessRequest(BaseModel): url: str # Masks user:password credentials embedded in any URL (e.g. the residential # proxy URL that yt-dlp echoes in its verbose debug output) before the line is # ever printed to the server console or stored in the job log. _CREDENTIAL_URL_RE = re.compile(r'(\w+://)[^:/@\s]+:[^@/\s]+@') def _scrub_secrets(line: str) -> str: return _CREDENTIAL_URL_RE.sub(r'\1***:***@', line) # Cloud users don't need (and shouldn't see) implementation details: the ingest # plumbing (proxy / downloader / cookies) OR which AI model powers it, token # usage and cost. These are dropped from the client view even when the line is # emoji-prefixed. Never applied under DEBUG_LOGS (local dev sees everything). _SENSITIVE_LOG_RE = re.compile( # Ingest plumbing r'proxy|yt[-_ ]?dlp|youtube-?dl|cookie|residential|po[_ ]?token' r'|player_client|extractor|\bdownload|descarg' # AI model / provider / cost / pipeline internals r'|gemini|openai|anthropic|\bflash\b|\bmodel\b|token|thinking' r'|\bcost\b|\$\s*[0-9]|scoring window|shortlist', re.IGNORECASE, ) def _visible_logs(logs): """Logs to surface to the client. Self-host (BILLING off) shows the full pipeline output so people running their own instance can debug. Cloud shows a curated whitelist view (log_view.friendly_logs): plain progress for normal users — transcription percentage, clip counters — with no file paths, model names or pipeline internals. DEBUG_LOGS=true forces the full output even under billing — for local dev where you run in paid mode but still want the raw logs. """ if not BILLING_ENABLED or DEBUG_LOGS: return logs from log_view import friendly_logs return friendly_logs(logs) def enqueue_output(out, job_id): """Reads output from a subprocess and appends it to jobs logs.""" try: for line in iter(out.readline, b''): decoded_line = _scrub_secrets(line.decode('utf-8').strip()) if decoded_line: # Internal marker from main.py's downloader, not a log line. # Internal marker: a clip finished its whole chain and this is # the file to serve for it. Consumed here like PROXY_BYTES so it # never reaches the user's log. if decoded_line.startswith("CLIP_READY "): try: _, index, filename = decoded_line.split(" ", 2) if job_id in jobs: jobs[job_id].setdefault('ready_files', {})[int(index)] = filename except ValueError: pass continue if decoded_line.startswith("PROXY_BYTES="): try: if job_id in jobs: jobs[job_id]['proxy_bytes'] = int(decoded_line.split("=", 1)[1]) except ValueError: pass continue if decoded_line.startswith("PROXY_ROUTE="): # Which download attempt won and why the free ones failed; # persisted at job end (cloud/proxy_ledger). Not shown to clients. try: from cloud import proxy_ledger as _pl route = _pl.parse_route_line(decoded_line) if route is not None and job_id in jobs: jobs[job_id]['proxy_route'] = route except Exception: pass continue print(f"📝 [Job Output] {decoded_line}") if job_id in jobs: jobs[job_id]['logs'].append(decoded_line) except Exception as e: print(f"Error reading output for job {job_id}: {e}") finally: out.close() async def run_job(job_id, job_data): """Executes the subprocess for a specific job.""" cmd = job_data['cmd'] env = job_data['env'] output_dir = job_data['output_dir'] jobs[job_id]['status'] = 'processing' jobs[job_id]['logs'].append("Job started by worker.") print(f"🎬 [run_job] Executing command for {job_id}: {' '.join(cmd)}") try: process = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, # Merge stderr to stdout env=env, cwd=os.getcwd() ) # We need to capture logs in a thread because Popen isn't async t_log = threading.Thread(target=enqueue_output, args=(process.stdout, job_id)) t_log.daemon = True t_log.start() # Async wait for process with incremental updates start_wait = time.time() last_heartbeat = time.time() while process.poll() is None: await asyncio.sleep(2) if time.time() - last_heartbeat >= HEARTBEAT_EVERY: _touch_manifest(job_id) last_heartbeat = time.time() # Check for partial results every 2 seconds # Look for metadata file try: json_files = glob.glob(os.path.join(output_dir, "*_metadata.json")) if json_files: target_json = json_files[0] # Read metadata (it might be being written to, so simple try/except or just read) # Use a lock or just robust read? json.load might fail if file is partial. # Usually main.py writes it once at start (based on my review). if os.path.getsize(target_json) > 0: with open(target_json, 'r') as f: data = json.load(f) base_name = os.path.basename(target_json).replace('_metadata.json', '') clips = data.get('shorts', []) cost_analysis = data.get('cost_analysis') # Check which clips actually exist on disk # Only clips main.py has announced as finished. It names # the file itself, so a clip shows up WITH its hook and # captions instead of as the bare reframe, and it is never # served while ffmpeg is still writing it. A clip whose # marker never arrives (it failed) simply stays hidden # until the job ends and the result is rebuilt from disk. ready_files = (jobs.get(job_id) or {}).get('ready_files') or {} ready_clips = [] for i, clip in enumerate(clips): clip_filename = ready_files.get(i) if not clip_filename: continue clip_path = os.path.join(output_dir, clip_filename) if os.path.exists(clip_path) and os.path.getsize(clip_path) > 0: clip['video_url'] = f"/videos/{job_id}/{clip_filename}" ready_clips.append(clip) if ready_clips: jobs[job_id]['result'] = {'clips': ready_clips, 'cost_analysis': cost_analysis} except Exception as e: # Ignore read errors during processing pass returncode = process.returncode if returncode == 0: jobs[job_id]['status'] = 'completed' jobs[job_id]['logs'].append("Process finished successfully.") # Self-host: silent AWS S3 backup. Cloud mode stores to R2 instead # (see _archive_managed_job), so skip the redundant/paid AWS upload. if not BILLING_ENABLED: loop = asyncio.get_event_loop() loop.run_in_executor(None, upload_job_artifacts, output_dir, job_id) # Find result JSON json_files = glob.glob(os.path.join(output_dir, "*_metadata.json")) if not json_files: # Backward-compat rescue if outputs were written to OUTPUT_DIR root if _relocate_root_job_artifacts(job_id, output_dir): json_files = glob.glob(os.path.join(output_dir, "*_metadata.json")) if json_files: target_json = json_files[0] with open(target_json, 'r') as f: data = json.load(f) # Enhance result with video URLs base_name = os.path.basename(target_json).replace('_metadata.json', '') clips = data.get('shorts', []) cost_analysis = data.get('cost_analysis') rendered, missing = _clips_actually_rendered( job_id, output_dir, base_name, clips) if not rendered: # Nothing to hand over: fail the job so _settle_reservation # releases the minutes instead of committing them. jobs[job_id]['status'] = 'failed' jobs[job_id]['logs'].append( "No clips could be rendered from this video.") else: if missing: jobs[job_id]['logs'].append( f"⚠️ {missing} of {len(clips)} clips failed to render.") jobs[job_id]['result'] = {'clips': rendered, 'cost_analysis': cost_analysis} else: jobs[job_id]['status'] = 'failed' jobs[job_id]['logs'].append("No metadata file generated.") else: jobs[job_id]['status'] = 'failed' jobs[job_id]['logs'].append(_scrub_secrets(f"Process failed with exit code {returncode}")) except Exception as e: jobs[job_id]['status'] = 'failed' # Exception text can embed URLs with credentials (e.g. the proxy URL # inside a yt-dlp/httpx error) — scrub before it reaches client logs. jobs[job_id]['logs'].append(_scrub_secrets(f"Execution error: {str(e)}")) @app.get("/health") async def health(): """Lightweight liveness probe for uptime monitoring.""" return {"status": "ok"} @app.get("/health/ready") async def health_ready(): """Readiness probe for the Docker HEALTHCHECK (Dockerfile). Traefik's docker provider drops a container from the load balancer as soon as it turns unhealthy, so answering 503 from the moment SIGTERM arrives pulls this instance out of rotation while it can still serve, instead of after its socket is gone. Only SIGTERM flips it: a drain triggered by the instance marker starts while the new container is still booting, and going unready then would leave nobody routable.""" if _stopping: return JSONResponse({"status": "stopping"}, status_code=503) return {"status": "ready"} @app.get("/api/config") async def get_config(): return { "youtubeUrlEnabled": not DISABLE_YOUTUBE_URL, "billingEnabled": BILLING_ENABLED, "googleAuthEnabled": bool(BILLING_ENABLED and cloud.settings.google_auth_enabled), "jobRetentionSeconds": JOB_RETENTION_SECONDS, # Self-host only: tells the dashboard the Gemini key is optional # because the moment picker runs on an OpenAI-compatible server. "localLlm": None if BILLING_ENABLED else llm_backend.describe(), } async def _probe_youtube_quality(url: str) -> dict: """Run quality_probe.py in a worker thread; {} on any failure (fail-open).""" def _run(): try: proc = subprocess.run( [sys.executable, QUALITY_PROBE_SCRIPT, "--url", url], capture_output=True, timeout=75, ) return json.loads(proc.stdout.decode(errors="replace").strip() or "{}") except Exception as e: print(f"⚠️ Quality probe failed ({e}); starting job without gate.") return {} loop = asyncio.get_event_loop() return await loop.run_in_executor(None, _run) def _media_duration_seconds(path: str) -> float: """Container duration via ffprobe; 0.0 on any failure (fail-open).""" try: proc = subprocess.run( ["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", path], capture_output=True, timeout=30) return float(proc.stdout.decode().strip() or 0) except Exception: return 0.0 def _reject_short_source(duration: float): raise HTTPException(status_code=400, detail=( f"This video is only {int(duration)}s long — clip generation needs at " f"least {MIN_SOURCE_SECONDS}s of material to cut from. It already is " f"short-form content.")) # Layouts the caller can let the renderer choose from, mapped to the env var # each one is gated on. The renderer only ever picks between layouts that are # switched on here. # # This is opt-in per job, not a detector running on every video, because the # detection is not good enough to be trusted unprompted: measured over the # 48-clip corpus, routing every video through the on-screen-content check fixed # 13 clips and spoiled 13 others (talking heads and corner tickers demoted to a # layout they do not need). Asking the person who knows what they uploaded costs # them one click and removes that whole class of error. It is also what OpusClip # does — its "applicable auto layout" panel lets the user pick which layouts the # AI may apply. LAYOUT_ENV = { "split": "SPLIT_LAYOUT", # two speakers stacked "screencast": "SCREENCAST_LAYOUT", # slides/screen share over the speaker "speaker_cut": "SPEAKER_CUT", # hard cuts to whoever is talking "punch_in": "PUNCH_IN", # small push on the clip's beats } # Stacking and cutting both need to know who is speaking. LAYOUT_IMPLIES = { "split": ["SPEAKER_SIGNAL"], "speaker_cut": ["SPEAKER_SIGNAL"], } # --------------------------------------------------------------------------- # # Agent uploads: a two-step path for callers that hold a video FILE, not a URL # (an MCP client handed the file by the user). POST reserves an id and returns # a PUT URL; the client streams the raw bytes there with no auth beyond the # unguessable id (so `curl -T` works from any agent runtime); /api/process then # takes the upload_id. Files live in UPLOAD_DIR under the same retention sweep # as every other source upload, and the owner recorded at POST is checked at # process time so a leaked id cannot start a job on someone else's account. # --------------------------------------------------------------------------- # pending_uploads: Dict[str, Dict] = {} # Unconsumed slots are gone after this; a consumed one becomes the job's # input and follows the job's own retention instead. UPLOAD_TTL_SECONDS = int(os.environ.get("UPLOAD_TTL_SECONDS", str(6 * 3600))) def _upload_url_base(request): return os.environ.get("PUBLIC_API_URL", "").rstrip("/") or str(request.base_url).rstrip("/") @app.post("/api/uploads") async def create_upload(request: Request): """Reserve an upload slot. Body (JSON, optional): {"filename": "..."}.""" user_id = await _owner_id(request) if BILLING_ENABLED and user_id is None: raise HTTPException(status_code=401, detail="Sign in or use an API key to upload") try: body = await request.json() except Exception: body = {} filename = os.path.basename(str((body or {}).get("filename") or "video.mp4")) or "video.mp4" upload_id = str(uuid.uuid4()) pending_uploads[upload_id] = { "user_id": user_id, "filename": filename, "path": os.path.join(UPLOAD_DIR, f"pending_{upload_id}_{filename}"), "created": time.time(), "bytes": 0, "complete": False, } return { "upload_id": upload_id, "upload_url": f"{_upload_url_base(request)}/api/uploads/{upload_id}", "method": "PUT", "max_mb": MAX_FILE_SIZE_MB, "expires_in": UPLOAD_TTL_SECONDS, "hint": "PUT the raw video bytes to upload_url (e.g. curl -T video.mp4 ), " "then call /api/process (or the process_video tool) with this upload_id. " "The slot and file are deleted after expires_in seconds if unused, or " "DELETE this URL to drop them sooner.", } @app.put("/api/uploads/{upload_id}") async def put_upload(upload_id: str, request: Request): """Receive the raw video body for a reserved slot. Streams to disk, capped at MAX_FILE_SIZE_MB; a second PUT replaces the first.""" slot = pending_uploads.get(upload_id) if not slot or time.time() - slot["created"] > UPLOAD_TTL_SECONDS: pending_uploads.pop(upload_id, None) raise HTTPException(status_code=404, detail="Unknown or expired upload_id") limit_bytes = MAX_FILE_SIZE_MB * 1024 * 1024 size = 0 with open(slot["path"], "wb") as out: async for chunk in request.stream(): size += len(chunk) if size > limit_bytes: out.close() os.remove(slot["path"]) raise HTTPException(status_code=413, detail=f"File too large. Max size {MAX_FILE_SIZE_MB}MB") out.write(chunk) if size == 0: os.remove(slot["path"]) raise HTTPException(status_code=400, detail="Empty body") slot.update({"bytes": size, "complete": True}) duration = await asyncio.get_event_loop().run_in_executor(None, _media_duration_seconds, slot["path"]) if duration <= 0: os.remove(slot["path"]) slot["complete"] = False raise HTTPException(status_code=400, detail="The body is not a readable video file") return {"upload_id": upload_id, "bytes": size, "duration_seconds": round(duration, 1), "hint": "Now call /api/process with upload_id."} @app.delete("/api/uploads/{upload_id}") async def delete_upload(upload_id: str, request: Request): """Drop a slot and its file before it expires (owner only in cloud mode).""" slot = pending_uploads.get(upload_id) if not slot or (BILLING_ENABLED and slot.get("user_id") != await _owner_id(request)): raise HTTPException(status_code=404, detail="Unknown or expired upload_id") pending_uploads.pop(upload_id, None) try: os.remove(slot["path"]) except OSError: pass return {"deleted": upload_id} def _sweep_pending_uploads(now=None): """Expire agent upload slots older than UPLOAD_TTL_SECONDS (file included). Returns the ids removed. Called from the cleanup loop; pure enough to test.""" now = now or time.time() gone = [] for uid, slot in list(pending_uploads.items()): if now - slot["created"] > UPLOAD_TTL_SECONDS: pending_uploads.pop(uid, None) try: os.remove(slot["path"]) except OSError: pass gone.append(uid) return gone def _take_pending_upload(upload_id, user_id): """The completed upload for this caller, or an HTTPException.""" slot = pending_uploads.get(upload_id) if not slot or (BILLING_ENABLED and slot.get("user_id") != user_id): raise HTTPException(status_code=404, detail="Unknown or expired upload_id") if not slot.get("complete") or not os.path.exists(slot["path"]): raise HTTPException(status_code=409, detail="Upload not received yet: PUT the video to upload_url first") return slot def layout_env(requested): """Env overrides for the layouts this job allows. Unknown names are ignored rather than rejected: a newer dashboard must not break an older API. The special value "auto" hands the choice to Gemini (one call per video). It composes with explicit picks: layout_picker only ever adds, so asking for "auto,punch_in" means "decide the layout yourself, and punch in regardless". "none" is the opposite: it switches the picker OFF for this job even when the deployment runs with AUTO_LAYOUT=1, for the user who wants the plain single crop and nothing clever. """ env = {} for name in requested or []: key = str(name).strip().lower() if key == "auto": env["AUTO_LAYOUT"] = "1" continue if key == "none": env["AUTO_LAYOUT"] = "0" continue var = LAYOUT_ENV.get(key) if not var: continue env[var] = "1" for extra in LAYOUT_IMPLIES.get(key, []): env[extra] = "1" return env @app.post("/api/process") async def process_endpoint( request: Request, file: Optional[UploadFile] = File(None), url: Optional[str] = Form(None), acknowledged: Optional[str] = Form(None), output_format: Optional[str] = Form(None), layouts: Optional[str] = Form(None), force_low_quality: Optional[str] = Form(None), webhook_url: Optional[str] = Form(None), 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), auto_hook: Optional[str] = Form(None), auto_hook_style: Optional[str] = Form(None), thumbnail_session_id: Optional[str] = Form(None), captions: Optional[str] = Form(None), upload_id: Optional[str] = Form(None), max_minutes: Optional[str] = Form(None), ): api_key = await resolve_gemini(request) if not api_key and not (llm_backend.active() and not BILLING_ENABLED): # Self-host with an OpenAI-compatible server configured needs no # Google key for the core pipeline: the moment picker runs there and # the frame-based stages degrade on their own (layout_picker returns # "none", silent videos fail with a message that says why). raise gemini_missing_error() ack_flag = str(acknowledged).lower() in ("1", "true", "yes") # May be lowered by the paid-proxy budget check in the metering block # below; self-host never runs that block, so it must default here. paid_allowed = True force_low = str(force_low_quality).lower() in ("1", "true", "yes") # Handle JSON body manually for URL payload content_type = request.headers.get("content-type", "") if "application/json" in content_type: body = await request.json() url = body.get("url") ack_flag = bool(body.get("acknowledged")) force_low = bool(body.get("force_low_quality")) output_format = body.get("output_format") layouts = body.get("layouts") webhook_url = body.get("webhook_url") webhook_secret = body.get("webhook_secret") 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") thumbnail_session_id = body.get("thumbnail_session_id") captions = body.get("captions") upload_id = body.get("upload_id") max_minutes = body.get("max_minutes") # Normalize output format (auto = keep pipeline default). if output_format not in ("vertical", "horizontal", "square"): output_format = "auto" # Accepts a JSON list or a comma-separated form field. if isinstance(layouts, str): layouts = [p for p in layouts.split(",") if p.strip()] elif not isinstance(layouts, list): layouts = [] # Module handover (issue #68): reuse the Thumbnail Studio source video and # its transcript so publishing to YouTube can flow straight into clip # generation without re-uploading or re-transcribing. thumb_session = None if thumbnail_session_id and not url and not file: thumb_session = thumbnail_sessions.get(thumbnail_session_id) if not thumb_session: raise HTTPException(status_code=404, detail="Thumbnail session not found or expired") await _assert_job_owner(request, thumb_session) src = thumb_session.get("video_path") if not src or not os.path.exists(src): raise HTTPException(status_code=404, detail="Source video for this session is no longer on disk") # Agent upload (POST /api/uploads + PUT): the file is already on disk. upload_slot = None if upload_id and not url and not file and not thumb_session: upload_slot = _take_pending_upload(upload_id, await _owner_id(request)) if not url and not file and not thumb_session and not upload_slot: raise HTTPException(status_code=400, detail="Must provide URL, File or upload_id") # Completion callback: reject unsafe targets NOW (clear 400) — delivery # re-validates anyway, but failing at submit is the debuggable behavior. if webhook_url: from security_utils import assert_public_url, UnsafeURLError try: await asyncio.get_event_loop().run_in_executor( None, assert_public_url, webhook_url) except UnsafeURLError as e: raise HTTPException(status_code=400, detail=f"Invalid webhook_url: {e}") if not ack_flag: raise HTTPException(status_code=400, detail="You must confirm you own the content or have rights to process it.") if url and DISABLE_YOUTUBE_URL: raise HTTPException(status_code=403, detail="YouTube URL ingest is disabled on this deployment. Please upload a file you own.") # Pre-flight quality gate: probe the offered resolution BEFORE starting, so # the user can abort (refresh cookies / update yt-dlp) instead of burning # 20 min on a 360p-only source. Fail-open: any probe error starts normally. # The probe also runs under force_low_quality so the short-source check # can't be bypassed through the quality-gate confirm. if url and (QUALITY_GATE_MIN_HEIGHT > 0 or MIN_SOURCE_SECONDS > 0): probe = await _probe_youtube_quality(url) # Hard reject, no confirm-and-retry: a too-short source fails the same # way on every retry, so letting the user force it just burns the job. source_duration = int(probe.get("duration") or 0) if MIN_SOURCE_SECONDS > 0 and 0 < source_duration < MIN_SOURCE_SECONDS: _reject_short_source(source_duration) max_height = int(probe.get("max_height") or 0) if not force_low and QUALITY_GATE_MIN_HEIGHT > 0 \ and 0 < max_height < QUALITY_GATE_MIN_HEIGHT: print(f"⚠️ Quality gate: only {max_height}p available for {url} — asking user first.") return JSONResponse({ "needs_confirmation": True, "quality_check": { "max_height": max_height, "min_height": QUALITY_GATE_MIN_HEIGHT, "cookies_invalid": bool(probe.get("cookies_invalid")), }, }) # Capture attestation context for legal record (IP + timestamp + UA) client_ip = request.client.host if request.client else "unknown" fwd = request.headers.get("x-forwarded-for") if fwd: client_ip = fwd.split(",")[0].strip() user_agent = request.headers.get("user-agent", "") attestation = { "acknowledged": True, "ip": client_ip, "user_agent": user_agent, "timestamp": time.time(), "source": ("thumbnail_session" if thumb_session else "upload_id" if upload_slot else "url" if url else "file"), } job_id = str(uuid.uuid4()) job_output_dir = os.path.join(OUTPUT_DIR, job_id) os.makedirs(job_output_dir, exist_ok=True) # Prepare Command # sys.executable, not "python": bare "python" resolves against PATH, which # outside Docker is whatever interpreter happens to be first — not the venv # running this server. Every job then dies on `import cv2`. The quality # probe above already gets this right. cmd = [sys.executable, "-u", "main.py"] # -u for unbuffered env = os.environ.copy() if not paid_allowed: # Daily paid-proxy budget hit: this job runs on the free routes only. env.pop("PROXY_URL", None) if api_key: env["GEMINI_API_KEY"] = api_key # Override with key from request else: env.pop("GEMINI_API_KEY", None) # local-LLM job: main.py must not find a stale key # The stdio fix above only covers this process. main.py prints an emoji on # its first line and configures nothing, so on a cp1252 console the child # still dies before it renders anything -- the server starts and every job # fails instead. setdefault, so an explicit PYTHONIOENCODING still wins. env.setdefault("PYTHONIOENCODING", "utf-8") # Optional layouts are per job. The renderer reads these at import time in # the subprocess, so they must be set before Popen — same path WATERMARK # already takes. chosen = layout_env(layouts) env.update(chosen) 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 # are honest TARGETS, not guarantees — the model may return fewer clips # when the material doesn't hold them. Bad values 400 instead of silently # producing something the user didn't ask for. def _gen_control(raw, name, lo, hi, integer=False): if raw in (None, ""): return None try: val = float(raw) except (TypeError, ValueError): raise HTTPException(status_code=400, detail=f"{name} must be a number") if integer and val != int(val): raise HTTPException(status_code=400, detail=f"{name} must be an integer") if not (lo <= val <= hi): raise HTTPException(status_code=400, detail=f"{name} must be between {lo:g} and {hi:g}") return int(val) if integer else val n_clips = _gen_control(target_clips, "target_clips", 1, 15, integer=True) min_secs = _gen_control(clip_min_seconds, "clip_min_seconds", 5, 175) max_secs = _gen_control(clip_max_seconds, "clip_max_seconds", 10, 180) if min_secs is not None and max_secs is not None and max_secs < min_secs + 5: raise HTTPException(status_code=400, detail="clip_max_seconds must be at least 5s above clip_min_seconds") if n_clips is not None: env["CLIP_TARGET_MIN"] = env["CLIP_TARGET_MAX"] = str(n_clips) if min_secs is not None: env["CLIP_MIN_SECONDS"] = str(min_secs) if max_secs is not None: env["CLIP_MAX_SECONDS"] = str(max_secs) if n_clips is not None or min_secs is not None or max_secs is not None: print(f"[gen-controls] job={job_id} clips={n_clips} band={min_secs}-{max_secs}") # captions=false: the source already carries burned-in subtitles (or the # caller adds its own later), so skip the free auto-caption pass instead # of stacking a second layer. Absent → the deployment default (on). if captions is not None and str(captions).lower() in ("0", "false", "no"): env["AUTO_CAPTIONS"] = "0" print(f"[captions] job={job_id} auto-captions off") input_path = None if url: # Keep the downloaded source inside the job dir: the clip editor's # re-render path cuts new segments from it, and it ages out with the # rest of the job (retention window + OUTPUT_MAX_GB cap) either way. cmd.extend(["-u", url, "--keep-original"]) elif thumb_session: # Hardlink (or copy) the session's video under the job's name so source # lookup, the clip editor and the preview treat it exactly like a normal # upload; the transcript rides along so the pipeline skips Whisper. src = thumb_session["video_path"] src_duration = _media_duration_seconds(src) if MIN_SOURCE_SECONDS > 0 and 0 < src_duration < MIN_SOURCE_SECONDS: shutil.rmtree(job_output_dir, ignore_errors=True) _reject_short_source(src_duration) input_path = os.path.join(UPLOAD_DIR, f"{job_id}_{os.path.basename(src)}") try: os.link(src, input_path) except OSError: shutil.copyfile(src, input_path) cmd.extend(["-i", input_path]) # An empty transcript (e.g. a silent or music-only source) is not worth # forwarding: main.py would reject it and retranscribe anyway. if thumb_session.get("transcript_ready") and (thumb_session.get("transcript") or {}).get("segments"): transcript_path = os.path.join(job_output_dir, "source_transcript.json") with open(transcript_path, "w") as f: json.dump(thumb_session["transcript"], f) cmd.extend(["--transcript", transcript_path]) elif upload_slot: # Move the pre-uploaded file under the job's name so it is cleaned up # with the job like any other upload; the slot is consumed. src = upload_slot["path"] src_duration = _media_duration_seconds(src) if MIN_SOURCE_SECONDS > 0 and 0 < src_duration < MIN_SOURCE_SECONDS: shutil.rmtree(job_output_dir, ignore_errors=True) _reject_short_source(src_duration) input_path = os.path.join(UPLOAD_DIR, f"{job_id}_{upload_slot['filename']}") os.replace(src, input_path) pending_uploads.pop(upload_id, None) cmd.extend(["-i", input_path]) else: # Save uploaded file with size limit check. # basename() strips any path components from the client-supplied # filename so a name like "../../main.py" can't escape UPLOAD_DIR. safe_name = os.path.basename(file.filename or "upload") or "upload" input_path = os.path.join(UPLOAD_DIR, f"{job_id}_{safe_name}") # Read file in chunks to check size size = 0 limit_bytes = MAX_FILE_SIZE_MB * 1024 * 1024 with open(input_path, "wb") as buffer: while content := await file.read(1024 * 1024): # Read 1MB chunks size += len(content) if size > limit_bytes: os.remove(input_path) shutil.rmtree(job_output_dir) raise HTTPException(status_code=413, detail=f"File too large. Max size {MAX_FILE_SIZE_MB}MB") buffer.write(content) upload_duration = _media_duration_seconds(input_path) if MIN_SOURCE_SECONDS > 0 and 0 < upload_duration < MIN_SOURCE_SECONDS: os.remove(input_path) shutil.rmtree(job_output_dir, ignore_errors=True) _reject_short_source(upload_duration) cmd.extend(["-i", input_path]) cmd.extend(["-o", job_output_dir]) if output_format and output_format != "auto": cmd.extend(["--format", output_format]) print(f"[attestation] job={job_id} ip={attestation['ip']} source={attestation['source']} ack=true") # Meter + reserve minutes for managed users (no-op for BYOK / self-host). user_id, priority, reservation_id, user_plan, partial = await reserve_process_minutes( request, url, input_path, job_id, max_minutes=max_minutes) if partial: # main.py cuts the source down to this many minutes before anything # reads it, so the whole pipeline (and the editor) sees a short video. env["MAX_SOURCE_MINUTES"] = str(partial["processed_minutes"]) if user_plan == "free": # Free-plan clips carry a burned-in watermark (applied by the main.py # subprocess after each clip renders). env["WATERMARK"] = "1" # Absolute-URL base for the webhook payload: explicit env wins (the API may # sit behind a proxy whose forwarded headers we can't trust), else what the # caller connected to. api_base = os.environ.get("PUBLIC_API_URL", "").rstrip("/") or str(request.base_url).rstrip("/") # Enqueue Job jobs[job_id] = { 'status': 'queued', 'logs': [f"Job {job_id} queued."], 'cmd': cmd, 'env': env, 'output_dir': job_output_dir, 'attestation': attestation, 'user_id': user_id, 'reservation_id': reservation_id, 'watermark': env.get("WATERMARK") == "1", 'partial': partial, 'webhook_url': webhook_url, 'webhook_secret': webhook_secret, 'base_url': api_base, # Read by the ClipsDelivered/JobFailed analytics event (plan). 'user_plan': user_plan, } # Persist the owner so recovered jobs keep their multi-tenant guard after a # restart (see _recover_jobs_from_disk). if user_id is not None: try: os.makedirs(job_output_dir, exist_ok=True) with open(os.path.join(job_output_dir, ".owner"), "w") as f: f.write(str(user_id)) except Exception as e: print(f"⚠️ Could not persist job owner for {job_id}: {e}") # Resume manifest: enough to re-run this job if the container dies mid-flight # (a redeploy). No secrets — the env is rebuilt from os.environ on resume. _write_resume_manifest(job_id, cmd, priority, user_id, reservation_id, watermark=jobs[job_id]['watermark'], webhook_url=webhook_url, webhook_secret=webhook_secret, base_url=api_base, partial=partial) _enqueue_job(job_id, priority) return {"job_id": job_id, "status": "queued", "partial": partial} def _job_view_from_disk(job_id): """What the disk says about a job this instance does not hold in memory. During a deploy handover a poll can land on either instance; the one that did not accept the job must still answer from the shared directory: a metadata JSON means completed (recovered like at startup), a manifest means the other instance has it (heartbeat) or will pick it up (queued). """ job_path = os.path.join(OUTPUT_DIR, job_id) if not os.path.isdir(job_path): return None if glob.glob(os.path.join(job_path, "*_metadata.json")): _recover_jobs_from_disk() return jobs.get(job_id) m = _read_manifest(job_id) if m is None: return None alive = time.time() - float(m.get("heartbeat") or 0) < HEARTBEAT_STALE_AFTER owner = m.get("user_id") return { 'status': 'processing' if alive else 'queued', 'logs': ["♻️ The server was updated; your video continues on the new instance."], 'user_id': (int(owner) if isinstance(owner, str) and owner.isdigit() else owner), 'result': None, } def _presented_status(job_id, job): """A job we hold as 'queued' while draining is really the next instance's: if it has started it, say so instead of showing a queue that never moves.""" if job.get('status') == 'queued' and _draining: m = _read_manifest(job_id) if m and _manifest_busy_elsewhere(m): return 'processing' return job['status'] @app.get("/api/status/{job_id}") async def get_status(job_id: str, request: Request): job = jobs.get(job_id) if job is None: job = _job_view_from_disk(job_id) if job is None: raise HTTPException(status_code=404, detail="Job not found") await _assert_job_owner(request, job) return { "status": _presented_status(job_id, job), "logs": _visible_logs(job['logs']), "result": job.get('result'), # Set when only the first part of the source was clipped (quota wall # offer), so the dashboard can say so next to the clips. "partial": job.get('partial'), } def _locate_source(job_id: str): """Find a job's source video on disk, or None. Upload jobs keep it in uploads/{job_id}_*; URL jobs keep the download in the job dir (--keep-original) under the name recorded as ``source_video`` in metadata.json. Either way it ages out with the normal retention caps. """ matches = [ f for f in glob.glob(os.path.join(UPLOAD_DIR, f"{glob.escape(job_id)}_*")) if not os.path.basename(f).startswith("thumb_") ] if matches: return matches[0] try: meta_files = glob.glob(os.path.join(OUTPUT_DIR, job_id, "*_metadata.json")) if meta_files: with open(meta_files[0], 'r') as f: name = json.load(f).get('source_video') if name: candidate = os.path.join(OUTPUT_DIR, job_id, os.path.basename(name)) if os.path.exists(candidate): return candidate except Exception: pass return None # How long a signed source URL stays valid. Long enough to survive an editing # session and a page reload, short enough that a link leaked through a log, a # referer or a shared screenshot is dead by the time anyone tries it. SOURCE_URL_TTL_SECONDS = int(os.environ.get("SOURCE_URL_TTL_SECONDS", "21600")) def _source_signature(job_id: str, exp: int) -> str: """HMAC tying a job id to an expiry, keyed on the app's JWT secret.""" secret = (_cloud_config.settings.jwt_secret if BILLING_ENABLED else "") or "" msg = f"{job_id}:{exp}".encode() return hmac.new(secret.encode(), msg, hashlib.sha256).hexdigest()[:32] def _job_record(job_id: str): """The in-memory job record, or what the shared disk says about it.""" return jobs.get(job_id) or _job_view_from_disk(job_id) def _signed_source_url(job_id: str) -> str: """The URL to hand a `