vocalremover / app.py
sarak855's picture
Upload 2 files
24ea487 verified
Raw History Blame Contribute Delete
15.2 kB
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("<h1>UI file not found.</h1>", status_code=404)
return HTMLResponse(index_file.read_text(encoding="utf-8"))
@app.post("/api/inspect-path")
async def inspect_path(path: str = Form(...)):
p = Path(path.strip(' "')).resolve()
if not p.exists():
raise HTTPException(status_code=404, detail="File path does not exist on disk.")
info = get_media_info(p)
info["file_name"] = p.name
info["file_size_mb"] = round(p.stat().st_size / (1024 * 1024), 2)
return info
@app.post("/api/start-process")
async def start_process(
file: Optional[UploadFile] = File(None),
local_path: Optional[str] = Form(None),
mode: str = Form("balanced"),
lufs: float = Form(-16.0),
option: str = Form("both"),
speed_profile: str = Form("fast")
):
job_id = str(uuid.uuid4())[:8]
if file and file.filename:
# Save uploaded file
saved_path = UPLOAD_DIR / f"{job_id}_{file.filename}"
with open(saved_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
target_path = saved_path
elif local_path and local_path.strip():
p = Path(local_path.strip(' "')).resolve()
if not p.exists():
raise HTTPException(status_code=400, detail="Specified local file does not exist.")
target_path = p
else:
raise HTTPException(status_code=400, detail="No file or local path provided.")
jobs[job_id] = {
"job_id": job_id,
"input_filename": target_path.name,
"status": "processing",
"phase": "queued",
"progress": 0,
"logs": [],
"media_info": {},
"outputs": {},
"error": None
}
# Start background processing thread
thread = threading.Thread(
target=execute_separation_pipeline,
args=(job_id, target_path, mode, lufs, option, speed_profile),
daemon=True
)
thread.start()
return {"job_id": job_id, "status": "processing"}
@app.get("/api/job/{job_id}")
async def get_job_status(job_id: str):
if job_id not in jobs:
raise HTTPException(status_code=404, detail="Job not found.")
return jobs[job_id]
@app.get("/api/download/{job_id}/{filename}")
async def download_file(job_id: str, filename: str):
file_path = OUTPUT_DIR / job_id / filename
if not file_path.exists():
raise HTTPException(status_code=404, detail="File not found.")
return FileResponse(
path=str(file_path),
filename=filename,
media_type="application/octet-stream"
)
@app.get("/api/stream/{job_id}/{filename}")
async def stream_file(job_id: str, filename: str):
file_path = OUTPUT_DIR / job_id / filename
if not file_path.exists():
raise HTTPException(status_code=404, detail="File not found.")
media_type = "video/mp4"
if filename.endswith(".wav"):
media_type = "audio/wav"
elif filename.endswith(".mp3"):
media_type = "audio/mpeg"
return FileResponse(
path=str(file_path),
media_type=media_type
)
def find_available_port(start_port=8088):
import socket
for port in range(start_port, start_port + 50):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
if s.connect_ex(('127.0.0.1', port)) != 0:
return port
return start_port
def main():
import webbrowser
env_port = os.environ.get("PORT")
host = os.environ.get("HOST", "0.0.0.0" if env_port else "127.0.0.1")
port = int(env_port) if env_port else find_available_port(8088)
url = f"http://{'localhost' if host == '0.0.0.0' else host}:{port}"
print(f"\n========================================================")
print(f" VocalZero AI - Studio Vocal Remover & Ambience Restorer")
print(f" Web UI active: {url} (Host: {host}:{port})")
print(f"========================================================\n")
# Launch browser only on local desktop (not headless container)
if not env_port:
def open_browser():
import time
time.sleep(1.2)
try:
webbrowser.open(url)
except Exception:
pass
threading.Thread(target=open_browser, daemon=True).start()
uvicorn.run(app, host=host, port=port, log_level="info")
if __name__ == "__main__":
main()