Files
stemengine_old/backend/routers/transcribe.py
T
2026-03-03 14:52:19 +09:00

89 lines
3.0 KiB
Python
Executable File

"""MIDI transcription endpoint."""
import shutil
from pathlib import Path
from fastapi import APIRouter, File, Form, UploadFile, HTTPException
from .. import job_manager as jm
from ..config import UPLOAD_DIR, PROJECTS_DIR, TRANSCRIBE_MODES, DEFAULT_TRANSCRIBE_MODE
from ..services.transcriber_service import run_transcription
router = APIRouter(prefix="/api/transcribe", tags=["transcribe"])
VALID_MODES = {m["id"] for m in TRANSCRIBE_MODES}
# 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"}
@router.get("/modes")
def get_modes():
return TRANSCRIBE_MODES
@router.post("")
async def transcribe(
file: UploadFile = File(...),
mode: str = Form(DEFAULT_TRANSCRIBE_MODE),
):
if mode not in VALID_MODES:
raise HTTPException(status_code=400, detail=f"Unknown mode: {mode}")
job_id = jm.create_job("transcribe")
upload_path = UPLOAD_DIR / job_id / file.filename
upload_path.parent.mkdir(parents=True, exist_ok=True)
with open(upload_path, "wb") as f:
shutil.copyfileobj(file.file, f)
jm.submit_gpu(run_transcription, job_id, str(upload_path), mode)
return {"job_id": job_id}
@router.post("/from-project")
async def transcribe_from_project(
project_name: str = Form(...),
mode: str = Form(DEFAULT_TRANSCRIBE_MODE),
):
"""
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}")
stems_dir = PROJECTS_DIR / project_name / "Stems"
if not stems_dir.exists():
raise HTTPException(status_code=404, detail=f"Stems folder not found for project: {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)
return {"job_id": job_id, "stem": stem_file.name}