import os import sys import uuid import json import shutil import asyncio import subprocess import threading from pathlib import Path from typing import Optional, Dict import uvicorn from fastapi import FastAPI, UploadFile, File, Form, HTTPException, BackgroundTasks from fastapi.responses import HTMLResponse, JSONResponse, FileResponse from fastapi.staticfiles import StaticFiles from fastapi.middleware.cors import CORSMiddleware from starlette.responses import StreamingResponse app = FastAPI(title="VocalZero - AI Audio Separation & Background Restorer") app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) WORKSPACE_DIR = Path(__file__).parent.resolve() UPLOAD_DIR = WORKSPACE_DIR / "uploads" OUTPUT_DIR = WORKSPACE_DIR / "outputs" STATIC_DIR = WORKSPACE_DIR / "static" UPLOAD_DIR.mkdir(parents=True, exist_ok=True) OUTPUT_DIR.mkdir(parents=True, exist_ok=True) STATIC_DIR.mkdir(parents=True, exist_ok=True) # In-memory job tracker jobs: Dict[str, dict] = {} def get_media_info(input_file: Path) -> dict: """Inspects media file audio and video streams using ffmpeg.""" cmd = ["ffmpeg", "-hide_banner", "-i", str(input_file)] res = subprocess.run(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE, text=True, encoding="utf-8", errors="ignore") output = res.stderr info = { "has_video": "Video:" in output, "sample_rate": "44100 Hz", "channels": "Stereo", "codec": "AAC", "duration": "Unknown", "bitrate": "Unknown" } for line in output.splitlines(): line_strip = line.strip() if "Duration:" in line_strip and info["duration"] == "Unknown": parts = line_strip.split(",") if len(parts) > 0: info["duration"] = parts[0].replace("Duration:", "").strip() if "Stream #" in line_strip and "Audio:" in line_strip: tokens = [t.strip() for t in line_strip.split(",")] for t in tokens: if "Hz" in t: info["sample_rate"] = t elif any(c in t for c in ["stereo", "mono", "5.1", "7.1", "channels"]): info["channels"] = t elif "Audio:" in t: info["codec"] = t.split("Audio:")[-1].strip() elif "kb/s" in t: info["bitrate"] = t return info def execute_separation_pipeline(job_id: str, input_path: Path, mode: str, lufs: float, option: str, speed_profile: str = "fast"): """Worker task that executes the 4-phase audio processing pipeline with speed optimizations.""" job = jobs[job_id] cpu_cores = os.cpu_count() or 4 def log(msg, phase=None, progress=None): if phase: job["phase"] = phase if progress is not None: job["progress"] = progress job["logs"].append(msg) print(f"[{job_id}] {msg}") try: log(f"Inspecting media container and audio streams (Using {cpu_cores} CPU cores)...", phase="extracting", progress=5) media_info = get_media_info(input_path) job["media_info"] = media_info log(f"Stream Properties: Codec={media_info['codec']} | Rate={media_info['sample_rate']} | Channels={media_info['channels']} | Duration={media_info['duration']}") # Setup working folders job_temp = WORKSPACE_DIR / "temp" / job_id job_temp.mkdir(parents=True, exist_ok=True) job_out = OUTPUT_DIR / job_id job_out.mkdir(parents=True, exist_ok=True) extracted_wav = job_temp / f"{input_path.stem}_lossless.wav" # Phase 1: Extracting Audio log("Phase 1/4: Extracting audio stream losslessly (24-bit PCM Master)...", phase="extracting", progress=15) extract_cmd = [ "ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-i", str(input_path), "-vn", "-c:a", "pcm_s24le", str(extracted_wav) ] subprocess.run(extract_cmd, check=True) log("Phase 1 Complete: Audio stream extracted successfully.", progress=25) raw_background_wav = job_temp / "no_vocals.wav" # Phase 2: Separating Vocals if speed_profile == "turbo": log("Phase 2/4: Running Instant Turbo Separation (Center-Channel Vocal Cancellation)...", phase="separating", progress=45) log("Applying high-speed phase cancellation to remove center-panned speech/dialogue in seconds...") # Instant Mid-Side / Center Cancellation via FFmpeg turbo_cmd = [ "ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-i", str(extracted_wav), "-af", "pan=stereo|c0=c0-c1|c1=c1-c0", "-c:a", "pcm_s24le", str(raw_background_wav) ] subprocess.run(turbo_cmd, check=True) log("Instant separation complete! Zero AI latency.", progress=70) else: # Neural AI Separation model_name = "mdx_q" if speed_profile == "fast" else "htdemucs" overlap = 0.1 if speed_profile in ("fast", "balanced") else 0.25 log(f"Phase 2/4: Separating Vocals via Neural Engine [{model_name.upper()}] with {cpu_cores} parallel threads...", phase="separating", progress=35) log(f"Settings: Model={model_name} | Overlap={overlap} | Threads={cpu_cores} | Tuning={mode.upper()}") other_method = "minus" if mode == "aggressive" else "add" demucs_cmd = [ "demucs", "-n", model_name, "--two-stems", "vocals", "--other-method", other_method, "-j", str(cpu_cores), "--overlap", str(overlap), "-o", str(job_temp), str(extracted_wav) ] if speed_profile == "balanced": demucs_cmd.extend(["--shifts", "1"]) # Run Demucs process process = subprocess.Popen( demucs_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding="utf-8", errors="ignore" ) for line in process.stdout: line_str = line.strip() if line_str: if "%" in line_str: log(f"Separation: {line_str}", progress=55) elif "Separating" in line_str or "Selected model" in line_str: log(line_str) process.wait() if process.returncode != 0: raise RuntimeError("Demucs separation failed with non-zero exit code.") # Find separated background track candidates = list(job_temp.glob("**/no_vocals.wav")) if not candidates: raise FileNotFoundError("Could not find Demucs separated 'no_vocals.wav' stem.") raw_background_wav = candidates[0] log("Phase 2 Complete: Vocals successfully eliminated. Background audio isolated.", progress=70) # Phase 3: Rebuilding Ambience & Mastering log("Phase 3/4: Rebuilding Ambience & Mastering background soundscape...", phase="mastering", progress=75) log(f"Applying EBU R128 Loudness Normalization (Target: {lufs} LUFS) & Soft Limiter (-1.5 dBTP)...") enhanced_wav = job_out / f"{input_path.stem}_background_enhanced.wav" filter_chain = f"loudnorm=I={lufs}:TP=-1.5:LRA=11,alimiter=limit=-1.5dB:level=false" master_cmd = [ "ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-i", str(raw_background_wav), "-af", filter_chain, "-c:a", "pcm_s24le", str(enhanced_wav) ] subprocess.run(master_cmd, check=True) log("Phase 3 Complete: Ambience restored and mastered without distortion.", progress=85) master_cmd = [ "ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-i", str(raw_background_wav), "-af", filter_chain, "-c:a", "pcm_s24le", str(enhanced_wav) ] subprocess.run(master_cmd, check=True) log("Phase 3 Complete: Ambience restored and mastered without distortion.", progress=85) # Phase 4: Master Export log("Phase 4/4: Exporting High-Res Audio & Video Remux...", phase="finalizing", progress=90) # Audio MP3 (320kbps) clean_mp3 = job_out / f"{input_path.stem}_background_320k.mp3" mp3_cmd = [ "ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-i", str(enhanced_wav), "-b:a", "320k", str(clean_mp3) ] subprocess.run(mp3_cmd, check=True) job["outputs"]["audio_wav"] = f"/api/download/{job_id}/{enhanced_wav.name}" job["outputs"]["audio_mp3"] = f"/api/download/{job_id}/{clean_mp3.name}" job["outputs"]["audio_wav_name"] = enhanced_wav.name job["outputs"]["audio_mp3_name"] = clean_mp3.name # Video Remux if input has video if media_info["has_video"] and option in ("both", "video"): ext = input_path.suffix if input_path.suffix.lower() in [".mp4", ".mkv", ".mov"] else ".mp4" remuxed_video = job_out / f"{input_path.stem}_no_vocals{ext}" log("Remuxing mastered background audio into video (direct stream copy - zero video re-encoding)...") remux_cmd = [ "ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-i", str(input_path), "-i", str(enhanced_wav), "-c:v", "copy", "-c:a", "aac", "-b:a", "320k", "-map", "0:v:0", "-map", "1:a:0", "-shortest", str(remuxed_video) ] subprocess.run(remux_cmd, check=True) job["outputs"]["video_remux"] = f"/api/download/{job_id}/{remuxed_video.name}" job["outputs"]["video_remux_name"] = remuxed_video.name # Clean temporary stems to save disk space try: shutil.rmtree(job_temp) except Exception: pass log("Pipeline finished successfully! Background soundscape is ready.", phase="ready", progress=100) job["status"] = "completed" except Exception as e: log(f"[ERROR] Pipeline execution error: {str(e)}", phase="error") job["status"] = "failed" job["error"] = str(e) @app.get("/", response_class=HTMLResponse) async def get_index(): index_file = STATIC_DIR / "index.html" if not index_file.exists(): return HTMLResponse("