"""Stem separation endpoint with preset support.""" import json import shutil from pathlib import Path from typing import Optional from fastapi import APIRouter, File, Form, UploadFile, HTTPException from .. import job_manager as jm from ..config import ( UPLOAD_DIR, ALL_MODELS, ALL_MODEL_IDS, OUTPUT_FORMATS, DEFAULT_MODEL, DEFAULT_OUTPUT_FORMAT, PRESET_TYPES, STATIC_OPTIONS, IMPORTS_DIR, ) from ..services.separator_service import run_separation router = APIRouter(prefix="/api/separate", tags=["separate"]) VALID_FORMATS = {f["id"] for f in OUTPUT_FORMATS} VALID_PRESETS = {p["id"] for p in PRESET_TYPES} VALID_STATIC_OPTIONS = {o["id"] for o in STATIC_OPTIONS} @router.get("/models") def get_models(): return ALL_MODELS @router.get("/formats") def get_formats(): return OUTPUT_FORMATS @router.get("/presets") def get_presets(): """Get available preset types and options.""" return { "preset_types": PRESET_TYPES, "static_options": STATIC_OPTIONS, } @router.post("") async def separate( file: UploadFile = File(...), model: str = Form(DEFAULT_MODEL), output_format: str = Form(DEFAULT_OUTPUT_FORMAT), # Preset options preset_type: str = Form("stems_only"), static_option: Optional[str] = Form(None), dynamic_levels: Optional[str] = Form(None), # JSON string: {"vocals": 1.0, ...} # Project naming project_name: Optional[str] = Form(None), # Power preset sep_power_preset: str = Form("standard"), ): """ Separate audio into stems with optional preset mixing. Args: file: Audio file to process model: Separation model ID output_format: Output audio format preset_type: Type of preset mix to create (stems_only, instrumental, static, dynamic) static_option: For static preset, which stems to remove dynamic_levels: For dynamic preset, JSON dict of stem name to volume multiplier (0.0-2.0) project_name: Override auto-generated project name """ # Validate inputs if model not in ALL_MODEL_IDS: raise HTTPException(status_code=400, detail=f"Unknown model: {model}") if output_format not in VALID_FORMATS: raise HTTPException(status_code=400, detail=f"Unknown format: {output_format}") if preset_type not in VALID_PRESETS: raise HTTPException(status_code=400, detail=f"Unknown preset type: {preset_type}") if preset_type == 'static' and static_option and static_option not in VALID_STATIC_OPTIONS: raise HTTPException(status_code=400, detail=f"Unknown static option: {static_option}") # Parse dynamic levels JSON parsed_dynamic_levels = None if dynamic_levels: try: parsed_dynamic_levels = json.loads(dynamic_levels) except json.JSONDecodeError: raise HTTPException(status_code=400, detail="Invalid dynamic_levels JSON") # Create job job_id = jm.create_job("separate") upload_dir = UPLOAD_DIR / job_id upload_dir.mkdir(parents=True, exist_ok=True) # Save uploaded file upload_path = upload_dir / file.filename with open(upload_path, "wb") as f: shutil.copyfileobj(file.file, f) # Submit job with all options jm.submit_gpu( run_separation, job_id, str(upload_path), model, output_format, preset_type=preset_type, static_option=static_option, dynamic_levels=parsed_dynamic_levels, project_name_override=project_name, sep_power_preset=sep_power_preset, ) return { "job_id": job_id, "preset_type": preset_type, "project_name": project_name, } @router.post("/existing") async def separate_existing( project_name: str = Form(..., description="Project name to process"), model: str = Form(DEFAULT_MODEL), output_format: str = Form(DEFAULT_OUTPUT_FORMAT), preset_type: str = Form("stems_only"), static_option: Optional[str] = Form(None), dynamic_levels: Optional[str] = Form(None), sep_power_preset: str = Form("standard"), ): """ Re-run separation on an existing project (if source audio exists). """ from ..config import PROJECTS_DIR if model not in ALL_MODEL_IDS: raise HTTPException(status_code=400, detail=f"Unknown model: {model}") if output_format not in VALID_FORMATS: raise HTTPException(status_code=400, detail=f"Unknown format: {output_format}") if preset_type not in VALID_PRESETS: raise HTTPException(status_code=400, detail=f"Unknown preset type: {preset_type}") project_dir = PROJECTS_DIR / project_name if not project_dir.exists(): raise HTTPException(status_code=404, detail=f"Project not found: {project_name}") # Look for source audio file source_file = None for ext in ['.mp3', '.flac', '.wav', '.m4a', '.ogg']: candidate = project_dir / f"{project_name}{ext}" if candidate.exists(): source_file = candidate break # Check for any file with source-like name for f in project_dir.iterdir(): if f.suffix.lower() == ext and 'source' in f.name.lower(): source_file = f break if source_file: break if not source_file: # Check uploads for the original file upload_dirs = list(UPLOAD_DIR.iterdir()) if UPLOAD_DIR.exists() else [] for ud in sorted(upload_dirs, key=lambda x: x.stat().st_mtime, reverse=True): for f in ud.iterdir(): if f.suffix.lower() in ['.mp3', '.flac', '.wav', '.m4a', '.ogg']: source_file = f break if source_file: break if not source_file: raise HTTPException(status_code=404, detail="Source audio file not found") # Parse dynamic levels parsed_dynamic_levels = None if dynamic_levels: try: parsed_dynamic_levels = json.loads(dynamic_levels) except json.JSONDecodeError: raise HTTPException(status_code=400, detail="Invalid dynamic_levels JSON") # Create job job_id = jm.create_job("separate") jm.submit( run_separation, job_id, str(source_file), model, output_format, preset_type=preset_type, static_option=static_option, dynamic_levels=parsed_dynamic_levels, project_name_override=project_name, sep_power_preset=sep_power_preset, ) return { "job_id": job_id, "preset_type": preset_type, "project_name": project_name, } @router.post("/from-path") async def separate_from_path( file_path: str = Form(...), model: str = Form(DEFAULT_MODEL), output_format: str = Form(DEFAULT_OUTPUT_FORMAT), preset_type: str = Form("stems_only"), static_option: Optional[str] = Form(None), dynamic_levels: Optional[str] = Form(None), project_name: Optional[str] = Form(None), sep_power_preset: str = Form("standard"), ): """ Separate a server-side audio file (e.g., imported from Subsonic). Only files inside IMPORTS_DIR are accepted for security. """ if model not in ALL_MODEL_IDS: raise HTTPException(status_code=400, detail=f"Unknown model: {model}") if output_format not in VALID_FORMATS: raise HTTPException(status_code=400, detail=f"Unknown format: {output_format}") if preset_type not in VALID_PRESETS: raise HTTPException(status_code=400, detail=f"Unknown preset type: {preset_type}") source = Path(file_path) if not source.exists() or not source.is_file(): raise HTTPException(status_code=404, detail="File not found") # Security: reject paths that escape IMPORTS_DIR try: source.resolve().relative_to(IMPORTS_DIR.resolve()) except ValueError: raise HTTPException(status_code=403, detail="File is not in the imports directory") parsed_dynamic_levels = None if dynamic_levels: try: parsed_dynamic_levels = json.loads(dynamic_levels) except json.JSONDecodeError: raise HTTPException(status_code=400, detail="Invalid dynamic_levels JSON") job_id = jm.create_job("separate") jm.submit_gpu( run_separation, job_id, str(source), model, output_format, preset_type=preset_type, static_option=static_option, dynamic_levels=parsed_dynamic_levels, project_name_override=project_name or source.stem, sep_power_preset=sep_power_preset, ) return {"job_id": job_id, "preset_type": preset_type} # Per-instrument models for targeted reprocessing PER_INSTRUMENT_MODELS = [ {"id": "mdxnet_voc_ft", "label": "MDX-Net Vocals FT", "instrument": "vocals", "description": "Specialized vocals separation model"}, {"id": "mdxnet_inst_hq_1", "label": "MDX-Net Inst HQ 1", "instrument": "instrumental", "description": "High-quality instrumental separation"}, {"id": "mdxnet_inst_hq_2", "label": "MDX-Net Inst HQ 2", "instrument": "instrumental", "description": "Alternative high-quality instrumental model"}, {"id": "mdxnet_karaoke", "label": "MDX-Net Karaoke", "instrument": "vocals", "description": "Optimized for karaoke vocal removal"}, {"id": "mel_band_vocals", "label": "MelBand Vocals", "instrument": "vocals", "description": "MelBand RoFormer vocals separation"}, {"id": "mel_band_dereverb", "label": "MelBand Dereverb", "instrument": "vocals", "description": "Remove reverb from vocals"}, {"id": "mel_band_karaoke", "label": "MelBand Karaoke", "instrument": "vocals", "description": "Lead/backing vocals separation"}, {"id": "bs_roformer_chorus", "label": "BS-RoFormer Chorus", "instrument": "vocals", "description": "Male/female chorus separation"}, ] @router.get("/per-instrument-models") def get_per_instrument_models(): """Get models suitable for per-instrument/stem reprocessing.""" return PER_INSTRUMENT_MODELS