import os import llm_backend import re import sys import uuid import subprocess import threading import json import shutil import glob import time import zipfile 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 FileResponse, JSONResponse from starlette.background import BackgroundTask from pydantic import BaseModel import httpx from s3_uploader import upload_job_artifacts import recut import layout_ranges import watermarked import media_auth import postiz 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")) # Upload size cap, in MB. 0 (the default) means unlimited: a self-hoster's own # disk should not impose an artificial ceiling. Set MAX_FILE_SIZE_MB to a # positive number to reinstate the 413 guard on the upload paths. MAX_FILE_SIZE_MB = int(os.environ.get("MAX_FILE_SIZE_MB", "0") or "0") # 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") # Server credentials the pipeline subprocesses (main.py, quality_probe.py) never # read: main.py and everything it imports use GEMINI_API_KEY / LLM_* / the # proxies / YOUTUBE_COOKIES. A child that runs yt-dlp and ffmpeg on # user-supplied URLs and files has no business holding the Stripe key, the JWT # signing secret or the database password; one exploit in that stack would # otherwise hand over all of them. CHILD_ENV_DENYLIST = frozenset({ "DATABASE_URL", "POSTGRES_PASSWORD", "JWT_SECRET", "STRIPE_SECRET_KEY", "STRIPE_WEBHOOK_SECRET", "SMTP_USER", "SMTP_PASSWORD", "TELEGRAM_BOT_TOKEN", "TELEGRAM_CHAT_ID", "GOOGLE_CLIENT_SECRET", "AGENTLEDGER_API_KEY", "MANAGED_GEMINI_API_KEY", "POSTIZ_API_KEY", "POSTIZ_URL", "R2_ACCESS_KEY_ID", "R2_SECRET_ACCESS_KEY", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "OPENPANEL_CLIENT_SECRET", "ELEVENLABS_API_KEY", }) def child_env(base=None): """A copy of the environment for a pipeline subprocess, minus the server secrets in CHILD_ENV_DENYLIST. Callers add GEMINI_API_KEY themselves.""" env = dict(os.environ if base is None else base) for name in CHILD_ENV_DENYLIST: env.pop(name, None) return env 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 # 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. JOB_RETENTION_SECONDS = int( os.environ.get("JOB_RETENTION_SECONDS", "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)) ) async def resolve_gemini(request: Request) -> Optional[str]: """Resolve the Gemini API key for a request: the ``X-Gemini-Key`` header wins, else the env fallback. This fork is BYOK / self-host only.""" header = request.headers.get("X-Gemini-Key") if header: return header return os.environ.get("GEMINI_API_KEY") def resolve_postiz(request: Request): """Resolve the Postiz base URL + API key for a request. Returns ``(base_url, api_key)``. Priority is the per-request headers the dashboard sends (``X-Postiz-Url`` / ``X-Postiz-Key``), then the self-host env fallback (``POSTIZ_URL`` / ``POSTIZ_API_KEY``). Postiz is self-hosted and BYOK in this fork, so there is no managed-key branch and no built-in host: a missing URL or key is a 400 rather than silently shipping the caller's key to an instance we chose. """ base = (request.headers.get("X-Postiz-Url") or os.environ.get("POSTIZ_URL") or "").strip() key = (request.headers.get("X-Postiz-Key") or os.environ.get("POSTIZ_API_KEY") or "").strip() if not base: raise HTTPException(status_code=400, detail="Missing Postiz URL") if not key: raise HTTPException(status_code=400, detail="Missing Postiz API key") return base, key def postiz_http_error(exc: postiz.PostizError) -> HTTPException: """Translate a Postiz client failure into the same shape FastAPI raises.""" return HTTPException(status_code=exc.status_code, detail=exc.detail) def gemini_missing_error(): """The 4xx when no Gemini key could be resolved: the BYOK header is missing.""" return HTTPException(status_code=400, detail="Missing X-Gemini-Key header") async def reserve_process_minutes(*a, **k): """Self-host shim: BYOK requests don't consume managed minutes. Returns the same tuple the metering path did: (user_id, priority, reservation_id, plan, partial).""" return None, 2, None, None, None async def reserve_managed_action(*a, **k): """Self-host shim: nothing is metered.""" return None async def require_managed_entitlement(request, *a, **k): """Self-host shim: every request is allowed.""" return None async def _owner_id(request): """Self-host shim: there is no account to scope a job to.""" return None async def _assert_job_owner(request, record): """Self-host shim: single-user app, every job belongs to the caller.""" return # 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) # Queue position + ETA for /api/status. ``_admitting`` holds jobs already taken # off the queue that wait for a free slot / GPU room: they go before anything # still queued. Durations are a rolling sample of this instance's finished jobs. _admitting: set = set() _recent_job_seconds: list = [] DEFAULT_JOB_SECONDS = 240 def _record_job_duration(seconds): if seconds and seconds > 0: _recent_job_seconds.append(float(seconds)) del _recent_job_seconds[:-30] def queue_estimate(ahead: int, running: int, slots: int, typical_seconds: float) -> int: """Seconds until a job with ``ahead`` jobs in front of it starts. With a slot free it starts right away (a few seconds of admission); otherwise each full round of ``slots`` jobs ahead costs about one typical job, since the running ones are on average half done. """ slots = max(1, int(slots)) free = max(0, slots - int(running)) if ahead < free: return 15 waiting = ahead - free + 1 rounds = waiting / slots return int(max(30, round(typical_seconds * (0.5 + rounds - 1 / slots)))) def queue_snapshot(job_id): """``{position, ahead, eta_seconds}`` for a queued job, else None.""" job = jobs.get(job_id) or {} if job.get('status') != 'queued': return None try: entries = sorted(job_queue._queue) # (priority, seq, job_id) except Exception: entries = [] queued_ids = [e[2] for e in entries if (jobs.get(e[2]) or {}).get('status') == 'queued'] if job_id in _admitting: ahead = len([j for j in _admitting if j != job_id]) elif job_id in queued_ids: ahead = len(_admitting) + queued_ids.index(job_id) else: return None sample = sorted(_recent_job_seconds) typical = sample[len(sample) // 2] if sample else DEFAULT_JOB_SECONDS return { "position": ahead + 1, "ahead": ahead, "eta_seconds": queue_estimate(ahead, len(_running_jobs), MAX_CONCURRENT_JOBS, typical), } 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). # wm_*{clean} is the free plan's marked copy of any of those (or of # the clean file itself: the * matches nothing), written last. 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}")) + glob.glob(os.path.join(output_dir, f"wm_*{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_watermark_copy(output_dir, filename): """``wm_`` -> ```` when the clean twin is on disk. The free plan serves a marked copy of the final file and keeps the clean one next to it (see the ``watermarked`` module); every derivation starts from the clean one, so the mark is always the outermost layer to strip. Same fail-safe contract as the other walk-backs: unchanged when there is nothing to strip or the twin is gone.""" if watermarked.is_marked(filename): clean = watermarked.clean_name(filename) if os.path.exists(os.path.join(output_dir, clean)): return clean return filename 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). """ filename = _strip_watermark_copy(output_dir, filename) 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.""" filename = _strip_watermark_copy(output_dir, filename) 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) async def _deliver(request, job_id, filename): """Self-host shim: clips are always served clean (no watermark).""" return filename def _media_guard(path: str) -> bool: """``/videos`` allowlist: deliverable types only (media_auth).""" if not media_auth.is_servable(path): return False job_id, _, filename = path.replace("\\", "/").strip("/").partition("/") if not filename or not watermarked.is_clean_deliverable(filename): return True return not watermarked.job_is_marked(os.path.join(OUTPUT_DIR, job_id)) 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 if os.path.isfile(os.path.join(job_path, _RESUME_FILE)): continue # in flight (interrupted or on the other instance): resume, not recover 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': _TimedLog(["♻️ 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 _jobs_busy_elsewhere(now=None) -> int: """How many jobs another instance is running right now (fresh heartbeat). During a deploy the old container keeps running its jobs while it drains, on the same GPU. Counting them is what stops the new container from stacking its own full MAX_CONCURRENT_JOBS on top: 22-sep-2026, 7 old + 3 new jobs filled the 20 GB card and 5 of 12 jobs died of CUDA OOM. """ now = time.time() if now is None else now busy = 0 try: entries = os.listdir(OUTPUT_DIR) except FileNotFoundError: return 0 for name in entries: path = os.path.join(OUTPUT_DIR, name, _RESUME_FILE) if not os.path.exists(path): continue m = _read_manifest(name) if m and _manifest_busy_elsewhere(m, now): busy += 1 return busy SHARED_GPU_WAIT_SECONDS = 5 SHARED_GPU_MAX_WAIT = DRAIN_TIMEOUT_SECONDS + 120 # Free VRAM a new job needs before it starts. A job peaks at ~4-6 GB while it # transcribes; starting one on a nearly full card is what made NVENC and # TransNetV2 of the jobs already running fail with CUDA OOM. 0 disables. GPU_MIN_FREE_MB = int(os.environ.get("GPU_MIN_FREE_MB", "4500")) _gpu_free_cache = {"at": 0.0, "mb": None} def _gpu_free_mb(): """Free memory on GPU 0 in MiB, or None when there is no nvidia-smi (CPU host, self-host without a GPU): then only the job count limits.""" now = time.monotonic() if now - _gpu_free_cache["at"] < 2: return _gpu_free_cache["mb"] mb = None try: out = subprocess.run( ["nvidia-smi", "--query-gpu=memory.free", "--format=csv,noheader,nounits", "-i", "0"], capture_output=True, text=True, timeout=5) if out.returncode == 0 and out.stdout.strip(): mb = int(float(out.stdout.strip().splitlines()[0])) except Exception: mb = None _gpu_free_cache.update(at=now, mb=mb) return mb def gpu_has_room(running_here: int, busy_elsewhere: int, free_mb) -> bool: """Whether a new job may start now. The job count covers both instances during a deploy handover. The free VRAM check covers what the count cannot see: jobs differ by an order of magnitude in memory. With nothing running anywhere the job always starts, so a card held by something outside our control can never stall the queue. """ total = running_here + busy_elsewhere if total >= MAX_CONCURRENT_JOBS: return False if total == 0 or GPU_MIN_FREE_MB <= 0 or free_mb is None: return True return free_mb >= GPU_MIN_FREE_MB async def _wait_for_shared_gpu(): """Hold a new job until the GPU has room for it: this instance's jobs plus the ones another instance is still draining must fit MAX_CONCURRENT_JOBS, and the card must have GPU_MIN_FREE_MB free. Bounded: a killed instance stops heartbeating within HEARTBEAT_STALE_AFTER, a drain cannot outlive DRAIN_TIMEOUT_SECONDS, and past SHARED_GPU_MAX_WAIT the job starts anyway rather than wait forever.""" waited = 0.0 logged = False loop = asyncio.get_event_loop() while waited < SHARED_GPU_MAX_WAIT: elsewhere = _jobs_busy_elsewhere() free_mb = await loop.run_in_executor(None, _gpu_free_mb) if gpu_has_room(len(_running_jobs), elsewhere, free_mb): return if not logged: print(f"⏳ Holding the next job: {len(_running_jobs)} running here, " f"{elsewhere} on a draining instance, " f"{free_mb if free_mb is not None else '?'} MiB GPU free " f"(needs {GPU_MIN_FREE_MB}).") logged = True await asyncio.sleep(SHARED_GPU_WAIT_SECONDS) waited += SHARED_GPU_WAIT_SECONDS 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, webhook_url=None, webhook_secret=None, base_url=None, partial=None, source_cap_minutes=None, skip_statics=False): 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, "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, # Same reason for the whole-video jobs' safety cap. "source_cap_minutes": source_cap_minutes, # The probe's "statics bot-checked for this video" verdict. "skip_statics": bool(skip_statics), }, 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 # A manifest outlives only an interrupted run (the job wrapper drops it # at every terminal state), so a metadata file next to it means the job # was stopped mid-render, not that it finished: resume it too. 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. Self-host # uses its own env GEMINI_API_KEY (already present via child_env). env = child_env() 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) if m.get("source_cap_minutes"): env["SOURCE_CAP_MINUTES"] = str(m["source_cap_minutes"]) else: env.pop("SOURCE_CAP_MINUTES", None) if m.get("skip_statics"): env["DOWNLOAD_SKIP_STATICS"] = "1" else: env.pop("DOWNLOAD_SKIP_STATICS", 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': _TimedLog([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, '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() # 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) _admitting.add(job_id) await concurrency_semaphore.acquire() if _draining: _admitting.discard(job_id) concurrency_semaphore.release() job_queue.task_done() print(f"⏸️ Draining — leaving {job_id} for the next instance.") continue # The old container may still be draining its jobs on this GPU. await _wait_for_shared_gpu() _admitting.discard(job_id) 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) 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) interrupted = False started = time.monotonic() try: if job: await run_job(job_id, job) if job.get('status') == 'completed': _record_job_duration(time.monotonic() - started) except asyncio.CancelledError: # The server is shutting down (drain timeout of a deploy) and took this # task with it. Not a failure: the manifest stays on disk and the next # instance resumes the job (22-sep-2026: 6 jobs were marked failed and # refunded at once this way instead). interrupted = True except Exception as e: print(f"❌ Job wrapper error {job_id}: {e}") finally: if interrupted or (_stopping and job and job.get('status') != 'completed'): _running_jobs.discard(job_id) concurrency_semaphore.release() job_queue.task_done() print(f"♻️ Server stopping: leaving {job_id} for the next instance.") if interrupted: raise asyncio.CancelledError() return if _should_auto_retry(job): _schedule_auto_retry(job_id, job) _running_jobs.discard(job_id) concurrency_semaphore.release() job_queue.task_done() print(f"🔁 Released slot for job {job_id} (auto-retry scheduled).") return # 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) # Fire the caller's webhook (self-host has no R2 archive step). await _notify_job_webhook(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}") # --- Automatic retry of transient failures ---------------------------------- # A job that dies of a condition on OUR side (a full GPU, an NVENC session # refused, a Gemini 5xx) is run once more by itself instead of showing the user # "failed". Content problems (no audio, private video, nothing clip-shaped, # policy block) fail as before: retrying cannot fix them. AUTO_RETRY_LIMIT = int(os.environ.get("AUTO_RETRY_LIMIT", "1")) AUTO_RETRY_DELAY_SECONDS = float(os.environ.get("AUTO_RETRY_DELAY_SECONDS", "30")) _TRANSIENT_MARKERS = ( "out of memory", "outofmemory", "cuda", "cublas", "cudnn", "nvenc", "generic error in an external library", "exit code 187", "broken pipe", "no clips could be rendered", "resource_exhausted", "resource exhausted", "503", "502", "500 internal", "overloaded", "deadline exceeded", "exit code -9", "exit code -15", "killed", ) _PERMANENT_MARKERS = ( "no audio", "no_audio", "video unavailable", "private video", "members-only", "prohibited_content", "blocked this video", "blocked its answer", "did not return usable clips", "clip detection failed", "short-form content", "sign in to confirm your age", "not available in your country", ) def is_transient_failure(logs) -> bool: """Whether a failed job's logs describe something a second run can fix.""" text = _job_error_text(list(logs or [])).lower() if any(m in text for m in _PERMANENT_MARKERS): return False return any(m in text for m in _TRANSIENT_MARKERS) def _should_auto_retry(job) -> bool: return bool(job and job.get('status') == 'failed' and not _draining and int(job.get('auto_retries') or 0) < AUTO_RETRY_LIMIT and job.get('cmd') and is_transient_failure(job.get('logs'))) def _clean_for_retry(output_dir): """Drop the half-made outputs of a failed run; keep the source, the transcript checkpoint (the retry skips transcription), owner and manifest.""" try: names = os.listdir(output_dir) except OSError: return for name in names: if ("_clip_" in name or name.endswith("_metadata.json") or name.startswith(("temp_", "hooked_", "autosubs_"))): try: os.remove(os.path.join(output_dir, name)) except OSError: pass def _schedule_auto_retry(job_id, job): job['auto_retries'] = int(job.get('auto_retries') or 0) + 1 job['status'] = 'queued' job['result'] = None job['ready_files'] = {} job['logs'].append("🔁 A temporary server problem interrupted your video. " "Retrying it automatically, no minutes are charged twice.") _clean_for_retry(job.get('output_dir') or os.path.join(OUTPUT_DIR, job_id)) m = _read_manifest(job_id) or {} priority = int(m.get("priority", 1)) print(f"🔁 Auto-retry {job['auto_retries']}/{AUTO_RETRY_LIMIT} for {job_id} " f"in {AUTO_RETRY_DELAY_SECONDS:.0f}s.") async def _later(): await asyncio.sleep(AUTO_RETRY_DELAY_SECONDS) if job_id in jobs and jobs[job_id].get('status') == 'queued': _enqueue_job(job_id, priority) asyncio.create_task(_later()) # 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:]) # --- Job completion webhooks -------------------------------------------------- # Agents and pipelines (n8n, cron, scripts) 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 as absolute URLs.""" 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, }) 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'))) @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). _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()) yield # Cleanup (optional: cancel worker) app = FastAPI(lifespan=lifespan) # Free public tools behind the /tools SEO pages: YouTube transcript (existing # captions only, never the GPU) and the title/description/tag generator. import free_tools as _free_tools app.include_router(_free_tools.router) # Enable CORS for frontend. Self-host allows any origin (permissive wildcard). app.add_middleware( CORSMiddleware, allow_origins=["*"], 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. ``guard`` refuses non-deliverables # (``*_metadata.json``, ``.owner``, ``.resume.json``) so they are never served. from restoring_static import RestoringStaticFiles app.mount("/videos", RestoringStaticFiles( directory=OUTPUT_DIR, guard=_media_guard), 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) class _TimedLog(list): """A job's log lines plus the time each one arrived (``.times``). The dashboard used to stamp every line with the time it was RENDERED, so all of them showed the same clock and it changed on every poll. """ def __init__(self, lines=()): super().__init__(lines) self.times = [time.time()] * len(self) def append(self, line): super().append(line) self.times.append(time.time()) def extend(self, lines): lines = list(lines) super().extend(lines) self.times.extend([time.time()] * len(lines)) def _visible_logs_timed(logs): """(lines, times) to surface to the client. Self-host shows the full pipeline output so people running their own instance can debug.""" times = getattr(logs, "times", None) if times is not None and len(times) != len(logs): times = None return list(logs), list(times) if times is not None else None 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="): # Internal downloader marker: never shown to the user. continue if decoded_line.startswith("PROXY_ROUTE="): # Internal downloader marker (proxy route): never shown. 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: try: await asyncio.sleep(2) except asyncio.CancelledError: # Shutting down: stop the child so it cannot keep writing into # the job dir while the next instance resumes the same job. try: process.kill() except Exception: pass raise 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.") # Silent AWS S3 backup (optional; a no-op when S3 is unconfigured). 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. 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, # Kept for a stale dashboard build; the self-host app has no billing. "billingEnabled": False, "jobRetentionSeconds": JOB_RETENTION_SECONDS, # Self-host: tells the dashboard the Gemini key is optional # because the moment picker runs on an OpenAI-compatible server. "localLlm": 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, env=child_env(), ) 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) async def _validate_source_url(url: str): """400 unless ``url`` is safe to hand to yt-dlp: http(s) on a globally routable host (security_utils) and, on YouTube, one video rather than a search / playlist / channel page (yt_clients). The download and the metering probe check the same things again; this is the one in front of the quality probe, which used to have none.""" from security_utils import assert_public_url, UnsafeURLError from yt_clients import youtube_non_video_reason try: await asyncio.get_event_loop().run_in_executor(None, assert_public_url, url) except UnsafeURLError as e: raise HTTPException(status_code=400, detail=f"This URL can't be processed: {e}") reason = youtube_non_video_reason(url) if reason: raise HTTPException(status_code=400, detail=( f"This link is {reason}. Paste the link of one video " "(youtube.com/watch?v=... or youtu.be/...).")) async def _quality_gate(url: str, force_low: bool): """Run the pre-flight probe: raises 400 for a too-short source, returns the needs_confirmation response for a low-resolution one, else None.""" 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")), }, }) return None async def _drop_unstarted_job(reservation_id, job_output_dir): """Undo a submission refused after its working dir was created.""" shutil.rmtree(job_output_dir, ignore_errors=True) 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 # (e.g. a 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) 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 limit_bytes and 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).""" slot = pending_uploads.get(upload_id) if not slot or 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 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(): # 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") 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.") # Refuse a URL no server-side fetch may touch before anything fetches it: # the quality probe below used to run yt-dlp on it unvalidated (tailnet # hosts included) and ahead of the balance / rate checks. if url: await _validate_source_url(url) # 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 = child_env() 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. 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/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 limit_bytes and 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) # 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. It runs AFTER the # metering step (entitlement, job limit, balance, the hourly probe cap), so # an account with no minutes cannot use it as a free yt-dlp runner; a # rejection hands the reservation back. if url and (QUALITY_GATE_MIN_HEIGHT > 0 or MIN_SOURCE_SECONDS > 0): try: gate = await _quality_gate(url, force_low) except BaseException: await _drop_unstarted_job(reservation_id, job_output_dir) raise if gate is not None: await _drop_unstarted_job(reservation_id, job_output_dir) return gate # A metered URL job never processes more than it paid for: the duration # came from the metering probe, but the download is a second request and # a server can answer it with a much longer file. main.py cuts anything # clearly past the reserved minutes (partial jobs already carry a cut). source_cap = getattr(request.state, "reserved_minutes", None) if url and source_cap and not partial: env["SOURCE_CAP_MINUTES"] = str(source_cap) else: env.pop("SOURCE_CAP_MINUTES", None) source_cap = None skip_statics = bool(url) and bool(getattr(request.state, "skip_statics", False)) if skip_statics: env["DOWNLOAD_SKIP_STATICS"] = "1" else: env.pop("DOWNLOAD_SKIP_STATICS", None) 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"]) # 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': _TimedLog([f"Job {job_id} queued."]), 'cmd': cmd, 'env': env, 'output_dir': job_output_dir, 'attestation': attestation, 'user_id': user_id, 'reservation_id': reservation_id, 'partial': partial, 'webhook_url': webhook_url, 'webhook_secret': webhook_secret, 'base_url': api_base, 'user_plan': user_plan, } # 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, webhook_url=webhook_url, webhook_secret=webhook_secret, base_url=api_base, partial=partial, source_cap_minutes=source_cap, skip_statics=skip_statics) _enqueue_job(job_id, priority) return {"job_id": job_id, "status": "queued", "partial": partial, "first_video": bool(getattr(request.state, "first_video", False))} 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 m = _read_manifest(job_id) if m is None: if glob.glob(os.path.join(job_path, "*_metadata.json")): _recover_jobs_from_disk() return jobs.get(job_id) 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': _TimedLog(["♻️ 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) _logs_view = _visible_logs_timed(job['logs']) return { "status": _presented_status(job_id, job), "logs": _logs_view[0], # When each line arrived (epoch seconds, parallel to "logs"), or None. "log_times": _logs_view[1], "result": job.get('result'), # Position in line and a rough wait while the job is still queued. "queue": queue_snapshot(job_id), # 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 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 _source_url(job_id: str) -> str: """The plain URL to hand a ``