Files
2026-04-14 16:32:36 +09:00

110 lines
4.0 KiB
Python
Executable File

"""Full pipeline endpoint: separate → transcribe → ABC."""
from pathlib import Path
from fastapi import APIRouter, Depends, File, Form, UploadFile, HTTPException
from pydantic import BaseModel
from .. import job_manager as jm
from ..config import (
UPLOAD_DIR, ALL_MODEL_IDS, OUTPUT_FORMATS, TRANSCRIBE_MODES,
DEFAULT_MODEL, DEFAULT_OUTPUT_FORMAT, DEFAULT_TRANSCRIBE_MODE,
)
from ..security import require_admin_token
from .models import get_runtime_availability
from ..services.instrument_models import parse_instrument_models_json
from ..services.pipeline_service import run_pipeline
from ..services.upload_io import save_upload_file
router = APIRouter(prefix="/api/pipeline", tags=["pipeline"])
VALID_FORMATS = {f["id"] for f in OUTPUT_FORMATS}
VALID_MODES = {m["id"] for m in TRANSCRIBE_MODES}
_ALLOWED_AUDIO_UPLOAD_EXTS = {".mp3", ".wav", ".flac", ".m4a", ".ogg", ".aac", ".wma"}
_MAX_UPLOAD_FILENAME_LEN = 128
def _safe_basename(raw: str | None, fallback: str = "upload") -> str:
name = Path((raw or "").strip()).name.strip()
if not name or name.startswith("."):
name = fallback
if len(name) > _MAX_UPLOAD_FILENAME_LEN:
stem = Path(name).stem
ext = Path(name).suffix
keep_stem_len = max(1, _MAX_UPLOAD_FILENAME_LEN - len(ext))
name = f"{stem[:keep_stem_len]}{ext}" if ext else stem[:_MAX_UPLOAD_FILENAME_LEN]
return name
def _safe_audio_upload_filename(raw: str | None) -> str:
name = _safe_basename(raw, fallback="upload.mp3")
ext = Path(name).suffix.lower()
if ext not in _ALLOWED_AUDIO_UPLOAD_EXTS:
raise HTTPException(
status_code=400,
detail=(
f"Unsupported upload extension '{ext or '(none)'}'. "
f"Allowed: {sorted(_ALLOWED_AUDIO_UPLOAD_EXTS)}"
),
)
return name
class PipelineJobResponse(BaseModel):
"""Response returned when a pipeline job is successfully enqueued."""
job_id: str
@router.post("", response_model=PipelineJobResponse)
async def pipeline(
file: UploadFile = File(...),
sep_model: str = Form(DEFAULT_MODEL),
sep_format: str = Form(DEFAULT_OUTPUT_FORMAT),
transcribe_mode: str = Form(DEFAULT_TRANSCRIBE_MODE),
song_title: str = Form(""),
instrument_models: str = Form(""),
lyric_engine: str = Form(""),
lyric_model: str = Form(""),
_admin_guard: None = Depends(require_admin_token),
):
if sep_model not in ALL_MODEL_IDS:
raise HTTPException(status_code=400, detail=f"Unknown model: {sep_model}")
sep_available, sep_reason = get_runtime_availability(sep_model)
if not sep_available:
raise HTTPException(status_code=400, detail=sep_reason or f"Model '{sep_model}' is unavailable in this runtime")
if sep_format not in VALID_FORMATS:
raise HTTPException(status_code=400, detail=f"Unknown format: {sep_format}")
if transcribe_mode not in VALID_MODES:
raise HTTPException(status_code=400, detail=f"Unknown mode: {transcribe_mode}")
try:
parsed_instrument_models = parse_instrument_models_json(instrument_models)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
safe_upload_name = _safe_audio_upload_filename(file.filename)
# Fall back to filename as song title
effective_title = song_title.strip() or Path(safe_upload_name).stem
parsed_lyric_engine = (lyric_engine or "").strip() or None
parsed_lyric_model = (lyric_model or "").strip() or None
job_id = jm.create_job("pipeline")
upload_path = UPLOAD_DIR / job_id / safe_upload_name
upload_path.parent.mkdir(parents=True, exist_ok=True)
await save_upload_file(file, upload_path)
jm.submit_gpu(
run_pipeline,
job_id,
str(upload_path),
sep_model,
sep_format,
transcribe_mode,
effective_title,
instrument_models=parsed_instrument_models,
lyric_engine=parsed_lyric_engine,
lyric_model=parsed_lyric_model,
)
return PipelineJobResponse(job_id=job_id)