Files
2026-07-09 10:58:09 +09:00

146 lines
5.4 KiB
Python
Executable File

"""MIDI transcription endpoint."""
from pathlib import Path
from fastapi import APIRouter, Depends, File, Form, UploadFile, HTTPException
from .. import job_manager as jm
from ..config import UPLOAD_DIR, PROJECTS_DIR, TRANSCRIBE_MODES, DEFAULT_TRANSCRIBE_MODE, OMNIZART_ENABLED
from ..security import require_admin_token
from ..services.transcriber_service import run_transcription
from ..services.upload_io import save_upload_file
router = APIRouter(prefix="/api/transcribe", tags=["transcribe"])
VALID_MODES = {m["id"] for m in TRANSCRIBE_MODES}
_VALID_BEND_POLICIES = {"auto", "force_on", "force_off"}
# Preferred stem order for transcription (drums are skipped; vocals last since
# Omnizart's "music" mode is most useful on pitched instruments).
_STEM_PREFERENCE = ["other", "piano", "guitar", "bass", "vocals"]
_AUDIO_EXTS = {".mp3", ".wav", ".flac"}
_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 _AUDIO_EXTS:
raise HTTPException(
status_code=400,
detail=f"Unsupported upload extension '{ext or '(none)'}'. Allowed: {sorted(_AUDIO_EXTS)}",
)
return name
def _safe_project_name(raw: str) -> str:
cleaned = Path(raw).name.strip()
if not cleaned or cleaned in {".", ".."}:
raise HTTPException(status_code=400, detail="Invalid project_name")
return cleaned
@router.get("/modes")
def get_modes():
"""Return all transcription modes with an 'available' flag.
Omnizart modes are marked available=False when OMNIZART_ENABLED is not set,
so the frontend can grey them out without a second request.
"""
return [
{
**m,
"available": True if m["engine"] == "basic-pitch" else OMNIZART_ENABLED,
}
for m in TRANSCRIBE_MODES
]
@router.post("")
async def transcribe(
file: UploadFile = File(...),
mode: str = Form(DEFAULT_TRANSCRIBE_MODE),
bend_policy: str = Form("auto"),
_admin_guard: None = Depends(require_admin_token),
):
if mode not in VALID_MODES:
raise HTTPException(status_code=400, detail=f"Unknown mode: {mode}")
if mode.startswith("omnizart-") and not OMNIZART_ENABLED:
raise HTTPException(status_code=503, detail="Omnizart is not available on this server (OMNIZART_ENABLED=false).")
if bend_policy not in _VALID_BEND_POLICIES:
raise HTTPException(status_code=400, detail=f"Unknown bend_policy: {bend_policy}")
job_id = jm.create_job("transcribe")
upload_path = UPLOAD_DIR / job_id / _safe_audio_upload_filename(file.filename)
upload_path.parent.mkdir(parents=True, exist_ok=True)
await save_upload_file(file, upload_path)
jm.submit_gpu(run_transcription, job_id, str(upload_path), mode, bend_policy)
return {"job_id": job_id}
@router.post("/from-project")
async def transcribe_from_project(
project_name: str = Form(...),
mode: str = Form(DEFAULT_TRANSCRIBE_MODE),
bend_policy: str = Form("auto"),
_admin_guard: None = Depends(require_admin_token),
):
"""
Transcribe a stem from an existing separation project.
Picks the best non-drum stem (other > piano > guitar > bass > vocals).
"""
if mode not in VALID_MODES:
raise HTTPException(status_code=400, detail=f"Unknown mode: {mode}")
if mode.startswith("omnizart-") and not OMNIZART_ENABLED:
raise HTTPException(status_code=503, detail="Omnizart is not available on this server (OMNIZART_ENABLED=false).")
if bend_policy not in _VALID_BEND_POLICIES:
raise HTTPException(status_code=400, detail=f"Unknown bend_policy: {bend_policy}")
safe_project_name = _safe_project_name(project_name)
stems_dir = PROJECTS_DIR / safe_project_name / "Stems"
if not stems_dir.exists():
raise HTTPException(status_code=404, detail=f"Stems folder not found for project: {safe_project_name}")
# Find the best non-drum stem in order of preference
candidates: dict[str, Path] = {}
for f in stems_dir.iterdir():
if f.is_file() and f.suffix.lower() in _AUDIO_EXTS and "drum" not in f.name.lower():
name_lower = f.stem.lower()
for pref in _STEM_PREFERENCE:
if pref in name_lower:
candidates.setdefault(pref, f)
stem_file: Path | None = None
for pref in _STEM_PREFERENCE:
if pref in candidates:
stem_file = candidates[pref]
break
# Fallback: any non-drum audio file
if stem_file is None:
for f in stems_dir.iterdir():
if f.is_file() and f.suffix.lower() in _AUDIO_EXTS and "drum" not in f.name.lower():
stem_file = f
break
if stem_file is None:
raise HTTPException(status_code=404, detail="No suitable (non-drum) stem found in project")
job_id = jm.create_job("transcribe")
jm.submit_gpu(run_transcription, job_id, str(stem_file), mode, bend_policy)
return {"job_id": job_id, "stem": stem_file.name}