""" MIDI transcription via basic-pitch (in-process Python API). Supports two modes mapped to inference parameter presets: polyphonic — general multi-instrument transcription melody — single-voice / vocal melody (melodia trick, min frequency) """ from pathlib import Path from .. import job_manager as jm from ..config import JOBS_DIR, TRANSCRIBE_PRESETS def run_transcription(job_id: str, input_path: str, mode: str): """ Background task: transcribe audio to MIDI using basic-pitch. mode: 'polyphonic' | 'melody' """ from basic_pitch.inference import predict from basic_pitch import ICASSP_2022_MODEL_PATH output_dir = JOBS_DIR / job_id output_dir.mkdir(parents=True, exist_ok=True) jm.update_job(job_id, status=jm.JobStatus.RUNNING, progress="Loading basic-pitch model...") try: if jm.should_cancel(job_id): jm.update_job(job_id, status=jm.JobStatus.CANCELLED, progress="Cancelled.") return params = TRANSCRIBE_PRESETS.get(mode, TRANSCRIBE_PRESETS["polyphonic"]) jm.update_job(job_id, progress=f"Transcribing with basic-pitch ({mode})...") _, midi_data, _ = predict( input_path, ICASSP_2022_MODEL_PATH, **params, ) if jm.should_cancel(job_id): jm.update_job(job_id, status=jm.JobStatus.CANCELLED, progress="Cancelled.") return output_name = f"{Path(input_path).stem}-{mode}.mid" dest = output_dir / output_name midi_data.write(str(dest)) jm.update_job( job_id, status=jm.JobStatus.DONE, progress="Transcription complete.", files=[{"name": dest.name, "path": str(dest)}], ) except Exception as exc: jm.update_job(job_id, status=jm.JobStatus.ERROR, error=str(exc), progress="Error.")