"""Séparation voix / instrumental avec Demucs sur un Space Hugging Face (CPU). Même contrat d'API que modal_app.py, pour que le front Next.js marche sans changement : POST /jobs {"audio_url": "..."} -> {"job_id": "..."} (Bearer API_TOKEN) GET /jobs/{id} -> {"status": ..., "files": {...}} (Bearer API_TOKEN) GET /files/{id}/{stem}.flac?exp=...&sig=... (lien signé) Les tâches passent une par une dans une file (le CPU gratuit n'en supporte pas plus). """ import hashlib import hmac import os import queue import re import shutil import subprocess import sys import threading import time import urllib.parse import urllib.request import uuid from pathlib import Path from fastapi import Depends, FastAPI, Header, HTTPException, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse from pydantic import BaseModel, Field MODEL = os.environ.get("DEMUCS_MODEL", "htdemucs") # --shifts : moyenne de plusieurs passes décalées, moins d'artefacts (temps × shifts). SHIFTS = int(os.environ.get("DEMUCS_SHIFTS", 2)) STEMS = ["vocals", "no_vocals"] OUTPUT_DIR = Path(os.environ.get("OUTPUT_DIR", "/tmp/stem-outputs")) MAX_DURATION_S = int(os.environ.get("MAX_DURATION_S", 10 * 60)) MAX_DOWNLOAD_BYTES = 100 * 1024 * 1024 LINK_TTL_S = 3600 RETENTION_S = 24 * 3600 # Tâches en attente au-delà desquelles on refuse (429) : protège le CPU partagé. MAX_QUEUE = int(os.environ.get("MAX_QUEUE", 5)) # Hôtes autorisés pour le fichier source (anti-SSRF) : par défaut, Vercel Blob public uniquement. ALLOWED_SOURCE_SUFFIXES = tuple( s.strip().lower() for s in os.environ.get( "ALLOWED_SOURCE_SUFFIXES", ".public.blob.vercel-storage.com").split(",") if s.strip() ) JOB_ID_RE = re.compile(r"^[a-f0-9]{32}$") OUTPUT_DIR.mkdir(parents=True, exist_ok=True) jobs: dict[str, dict] = {} jobs_lock = threading.Lock() work_queue: "queue.Queue[str]" = queue.Queue() def _allowed_source(url: str) -> bool: try: u = urllib.parse.urlsplit(url) except ValueError: return False host = (u.hostname or "").lower() return u.scheme == "https" and any(host.endswith(sfx) for sfx in ALLOWED_SOURCE_SUFFIXES) class _SafeRedirect(urllib.request.HTTPRedirectHandler): """Refuse toute redirection vers un hôte non autorisé.""" def redirect_request(self, req, fp, code, msg, headers, newurl): if not _allowed_source(newurl): raise ValueError("Redirection vers un hôte non autorisé") return super().redirect_request(req, fp, code, msg, headers, newurl) _opener = urllib.request.build_opener(_SafeRedirect) def _set(job_id: str, **fields) -> None: with jobs_lock: jobs[job_id].update(fields, updated_at=time.time()) # --------------------------------------------------------------------------- traitement def _extract_audio(src: Path, work: Path) -> Path: """Extrait la 1re piste audio (d'un fichier audio ou vidéo) en WAV stéréo 44,1 kHz pour Demucs.""" streams = subprocess.run( ["ffprobe", "-v", "error", "-select_streams", "a", "-show_entries", "stream=index", "-of", "csv=p=0", str(src)], capture_output=True, text=True, ).stdout.strip() if not streams: raise ValueError("Aucune piste audio dans ce fichier") out = work / "audio.wav" proc = subprocess.run( ["ffmpeg", "-nostdin", "-v", "error", "-y", "-i", str(src), "-map", "0:a:0", "-vn", "-ac", "2", "-ar", "44100", "-c:a", "pcm_s16le", str(out)], capture_output=True, text=True, ) if proc.returncode != 0: print(f"[error] ffmpeg: {proc.stderr[-1000:]}", flush=True) raise ValueError("Conversion audio impossible") src.unlink(missing_ok=True) return out def _separate(job_id: str) -> None: job = jobs[job_id] started = time.time() work = OUTPUT_DIR / f"work-{job_id}" work.mkdir(parents=True, exist_ok=True) try: src = work / "input" with _opener.open(urllib.request.Request(job["source_url"], headers={"User-Agent": "stem-separator/1.0"}), timeout=60) as resp, open(src, "wb") as f: total = 0 while chunk := resp.read(1 << 20): total += len(chunk) if total > MAX_DOWNLOAD_BYTES: raise ValueError("Fichier trop volumineux") f.write(chunk) # Vidéo ou audio, tout est ramené à une piste WAV avant la séparation. src = _extract_audio(src, work) probe = subprocess.run( ["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=nw=1:nk=1", str(src)], capture_output=True, text=True, ) duration = float(probe.stdout.strip() or 0) if duration <= 0: raise ValueError("Fichier audio illisible") if duration > MAX_DURATION_S: raise ValueError(f"Morceau trop long ({duration:.0f}s > {MAX_DURATION_S}s)") _set(job_id, audio_duration=duration) proc = subprocess.run( [sys.executable, "-m", "demucs", "-n", MODEL, "--two-stems=vocals", "-d", "cpu", "--shifts", str(SHIFTS), "--flac", "-o", str(work / "out"), str(src)], capture_output=True, text=True, ) if proc.returncode != 0: print(f"[error] job={job_id} demucs: {proc.stderr[-2000:]}", flush=True) raise RuntimeError("Échec de la séparation") produced = work / "out" / MODEL / src.stem dest = OUTPUT_DIR / job_id dest.mkdir(parents=True, exist_ok=True) for stem in STEMS: shutil.move(str(produced / f"{stem}.flac"), dest / f"{stem}.flac") elapsed = time.time() - started print(f"[metrics] job={job_id} duration={duration:.1f}s cpu_time={elapsed:.1f}s", flush=True) _set(job_id, status="done", processing_seconds=elapsed) except Exception as e: # noqa: BLE001 print(f"[error] job={job_id} {e}", flush=True) _set(job_id, status="error", error=str(e)) finally: shutil.rmtree(work, ignore_errors=True) def _worker() -> None: while True: job_id = work_queue.get() _set(job_id, status="running") _separate(job_id) work_queue.task_done() def _cleanup() -> None: while True: cutoff = time.time() - RETENTION_S with jobs_lock: expired = [j for j, st in jobs.items() if st["created_at"] < cutoff] for j in expired: jobs.pop(j) for j in expired: shutil.rmtree(OUTPUT_DIR / j, ignore_errors=True) if expired: print(f"[cleanup] {len(expired)} tâche(s) supprimée(s)", flush=True) time.sleep(3600) threading.Thread(target=_worker, daemon=True).start() threading.Thread(target=_cleanup, daemon=True).start() # --------------------------------------------------------------------------- liens signés def _sign(job_id: str, stem: str, exp: int) -> str: key = os.environ["SIGNING_KEY"].encode() return hmac.new(key, f"{job_id}/{stem}:{exp}".encode(), hashlib.sha256).hexdigest() def _public_base(request: Request) -> str: if os.environ.get("PUBLIC_URL"): return os.environ["PUBLIC_URL"].rstrip("/") base = str(request.base_url).rstrip("/") # Derrière le proxy Hugging Face, la requête arrive en http : on force https. if base.startswith("http://") and request.url.hostname not in ("localhost", "127.0.0.1"): base = "https://" + base[len("http://"):] return base # --------------------------------------------------------------------------- API app = FastAPI(title="Stem separator API") # Le mixeur du navigateur lit les stems via fetch() : CORS nécessaire sur les liens signés. app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["GET"], allow_headers=["*"]) def require_token(authorization: str = Header(default="")): expected = f"Bearer {os.environ['API_TOKEN']}" if not hmac.compare_digest(authorization, expected): raise HTTPException(401, "Unauthorized") class JobIn(BaseModel): audio_url: str = Field(max_length=2048) @app.get("/") def health(): return {"ok": True, "model": MODEL, "shifts": SHIFTS, "queue": work_queue.qsize(), "max_queue": MAX_QUEUE} @app.post("/jobs", dependencies=[Depends(require_token)]) def create_job(body: JobIn): if not _allowed_source(body.audio_url): raise HTTPException(400, "source_not_allowed") if work_queue.qsize() >= MAX_QUEUE: raise HTTPException(429, "queue_full") job_id = uuid.uuid4().hex with jobs_lock: jobs[job_id] = {"status": "queued", "source_url": body.audio_url, "created_at": time.time()} work_queue.put(job_id) return {"job_id": job_id} @app.get("/jobs/{job_id}", dependencies=[Depends(require_token)]) def get_job(job_id: str, request: Request): if not JOB_ID_RE.match(job_id): raise HTTPException(400, "job_id invalide") with jobs_lock: st = dict(jobs.get(job_id) or {}) if not st: raise HTTPException(404, "Tâche inconnue (le Space a peut-être redémarré)") out = {k: st.get(k) for k in ("status", "error", "source_url", "audio_duration", "processing_seconds")} out["job_id"] = job_id if st["status"] == "queued": out["queue_position"] = list(work_queue.queue).index(job_id) + 1 if job_id in work_queue.queue else 0 if st["status"] == "done": exp = int(time.time()) + LINK_TTL_S base = _public_base(request) out["files"] = { stem: f"{base}/files/{job_id}/{stem}.flac?exp={exp}&sig={_sign(job_id, stem, exp)}" for stem in STEMS } return out @app.get("/files/{job_id}/{stem}.flac") def get_file(job_id: str, stem: str, exp: int, sig: str): if stem not in STEMS or not JOB_ID_RE.match(job_id): raise HTTPException(404) if exp < time.time() or not hmac.compare_digest(sig, _sign(job_id, stem, exp)): raise HTTPException(403, "Lien expiré ou invalide") path = OUTPUT_DIR / job_id / f"{stem}.flac" if not path.exists(): raise HTTPException(404) return FileResponse(path, media_type="audio/flac", filename=f"{stem}.flac")