diff --git a/src/songsplit/pipeline/s4_pitch.py b/src/songsplit/pipeline/s4_pitch.py index 40ed4b2..e96b878 100644 --- a/src/songsplit/pipeline/s4_pitch.py +++ b/src/songsplit/pipeline/s4_pitch.py @@ -1,30 +1,222 @@ """Stage 4: Pitch tracking with CREPE -> median MIDI pitch per syllable.""" +import json from pathlib import Path from typing import Any +import numpy as np +import soundfile as sf +import torch + +from songsplit.config import config from songsplit.pipeline.runner import PipelineContext, Stage +from songsplit.schema.base import GeneratedBy +from songsplit.schema.vocals import VocalLine, VocalsDocument, VocalSyllable + + +def hz_to_midi(hz: np.ndarray) -> np.ndarray: + """Convert frequency in Hz to fractional MIDI note numbers.""" + valid = hz > 0 + midi = np.zeros_like(hz, dtype=np.float32) + midi[valid] = 69.0 + 12.0 * np.log2(hz[valid] / 440.0) + return midi + + +def correct_octave_errors(syllables: list[dict[str, Any]]) -> list[dict[str, Any]]: + """Correct isolated octave doubling/halving jumps relative to melodic context.""" + if len(syllables) < 3: + return syllables + + pitches = [s["midi"] for s in syllables] + corrected = list(pitches) + + for i in range(1, len(syllables) - 1): + prev_p = corrected[i - 1] + next_p = pitches[i + 1] + cur_p = pitches[i] + + local_mean = (prev_p + next_p) / 2.0 + diff = cur_p - local_mean + + # Check for +12 (octave too high) + if 10.5 <= diff <= 13.5: + corrected[i] = cur_p - 12.0 + # Check for -12 (octave too low) + elif -13.5 <= diff <= -10.5: + corrected[i] = cur_p + 12.0 + # Check for +24 (two octaves too high) + elif 22.5 <= diff <= 25.5: + corrected[i] = cur_p - 24.0 + # Check for -24 (two octaves too low) + elif -25.5 <= diff <= -22.5: + corrected[i] = cur_p + 24.0 + + for s, p in zip(syllables, corrected, strict=False): + s["midi"] = float(p) + + return syllables class PitchStage(Stage): + """Stage 4 extracts vocal fundamental frequency and assigns median pitch per syllable.""" + name = "s4_pitch" version = "1.0.0" model_name = "torchcrepe-full" model_version = "1.0.0" dependencies = ["s3_lyrics"] + def __init__(self, model_name: str = "torchcrepe-full"): + self.model_name = model_name + def get_inputs(self, ctx: PipelineContext) -> list[Path]: return [ ctx.stems_dir / "vocals.wav", - ctx.output_dir / ".cache" / "lyrics_raw.json", + ctx.cache_dir / "lyrics_raw.json", ] def get_outputs(self, ctx: PipelineContext) -> list[Path]: return [ctx.output_dir / "vocals.json"] def get_params(self, ctx: PipelineContext) -> dict[str, Any]: - return {"hop_length_ms": 10, "viterbi": True} + return { + "hop_length_ms": 10, + "voicing_threshold": 0.25, + "crepe_model": "tiny" if ctx.quality == "fast" else "full", + } def run(self, ctx: PipelineContext) -> None: - # Implementation in M2 - raise NotImplementedError("Stage s4_pitch will be implemented in M2.") + import torchcrepe + + vocals_wav, lyrics_json = self.get_inputs(ctx) + if not vocals_wav.exists(): + raise FileNotFoundError(f"Vocals stem not found: {vocals_wav}") + if not lyrics_json.exists(): + raise FileNotFoundError(f"Lyrics file not found: {lyrics_json}") + + with open(lyrics_json, encoding="utf-8") as f: + lyrics_data = json.load(f) + + params = self.get_params(ctx) + hop_length_ms = params["hop_length_ms"] + voicing_thresh = params["voicing_threshold"] + crepe_model = params["crepe_model"] + self.model_name = f"torchcrepe-{crepe_model}" + + # Load audio using soundfile (resample to 16000 Hz for CREPE) + audio_data, sr = sf.read(str(vocals_wav), dtype="float32") + if audio_data.ndim > 1: + # Downmix to mono + audio_data = audio_data.mean(axis=-1) + + crepe_sr = 16000 + hop_length = int(crepe_sr * (hop_length_ms / 1000.0)) + + # Convert to torch tensor + audio_tensor = torch.from_numpy(audio_data).unsqueeze(0) + if sr != crepe_sr: + import julius + + audio_tensor = julius.resample_frac(audio_tensor, sr, crepe_sr) + + device_str = config.get_device(self.name) + if device_str.startswith("cuda") and not torch.cuda.is_available(): + device_str = "cpu" + device = torch.device(device_str) + + # Run CREPE pitch prediction + pitch_hz, periodicity = torchcrepe.predict( + audio_tensor.to(device), + crepe_sr, + hop_length=hop_length, + fmin=50, + fmax=1006, + model=crepe_model, + batch_size=2048, + device=device, + return_periodicity=True, + ) + + pitch_hz = pitch_hz.squeeze(0).cpu().numpy() + periodicity = periodicity.squeeze(0).cpu().numpy() + + # Frame timestamps: t_k = k * (hop_length / crepe_sr) + frame_times = np.arange(len(pitch_hz)) * (hop_length / crepe_sr) + midi_frames = hz_to_midi(pitch_hz) + + # Process each line and syllable + vocal_lines: list[VocalLine] = [] + + for line_dict in lyrics_data.get("lines", []): + line_syllables_raw = [] + + for syl_dict in line_dict.get("syllables", []): + s_start = float(syl_dict["start"]) + s_end = float(syl_dict["end"]) + text = syl_dict["text"] + + # Frames within syllable + mask = (frame_times >= s_start) & (frame_times <= s_end) + voiced_mask = mask & (periodicity >= voicing_thresh) & (pitch_hz > 50) + + if np.any(voiced_mask): + voiced_midis = midi_frames[voiced_mask] + voiced_confs = periodicity[voiced_mask] + median_midi = float(np.median(voiced_midis)) + conf = float(np.mean(voiced_confs)) + elif np.any(mask): + median_midi = float(np.median(midi_frames[mask])) + conf = float(np.mean(periodicity[mask])) * 0.5 + else: + median_midi = 60.0 + conf = 0.1 + + line_syllables_raw.append( + { + "text": text, + "start": s_start, + "end": s_end, + "midi": median_midi, + "confidence": float(np.clip(conf, 0.0, 1.0)), + } + ) + + # Apply octave error correction within phrase + corrected_sylls = correct_octave_errors(line_syllables_raw) + + syl_objects = [ + VocalSyllable( + text=s["text"], + start=s["start"], + end=s["end"], + midi=s["midi"], + confidence=s["confidence"], + source="auto", + ) + for s in corrected_sylls + ] + + if syl_objects: + vocal_lines.append( + VocalLine( + start=line_dict["start"], + end=line_dict["end"], + syllables=syl_objects, + ) + ) + + doc = VocalsDocument( + schema_version="1.0", + generated_by=GeneratedBy( + stage=self.name, + model=self.model_name, + model_version=self.version, + params=params, + ), + lines=vocal_lines, + ) + + output_file = self.get_outputs(ctx)[0] + output_file.parent.mkdir(parents=True, exist_ok=True) + with open(output_file, "w", encoding="utf-8") as f: + f.write(doc.model_dump_json(indent=2)) diff --git a/tests/test_pitch.py b/tests/test_pitch.py new file mode 100644 index 0000000..ff68032 --- /dev/null +++ b/tests/test_pitch.py @@ -0,0 +1,41 @@ +"""Unit tests for Stage 4 pitch processing (Hz to MIDI and octave error correction).""" + +import numpy as np +import pytest + +from songsplit.pipeline.s4_pitch import correct_octave_errors, hz_to_midi + + +def test_hz_to_midi_standards(): + # A4 = 440 Hz -> MIDI 69 + # A3 = 220 Hz -> MIDI 57 + # C4 = 261.6256 Hz -> MIDI 60 + hz = np.array([440.0, 220.0, 261.6256]) + midi = hz_to_midi(hz) + assert midi[0] == pytest.approx(69.0, abs=0.01) + assert midi[1] == pytest.approx(57.0, abs=0.01) + assert midi[2] == pytest.approx(60.0, abs=0.01) + + +def test_correct_octave_errors(): + # Line with an octave spike in the middle: 60, 72 (+12 jump), 61 + syllables = [ + {"text": "A", "midi": 60.0}, + {"text": "B", "midi": 72.0}, # Isolated octave jump + {"text": "C", "midi": 61.0}, + ] + corrected = correct_octave_errors(syllables) + assert corrected[0]["midi"] == 60.0 + assert corrected[1]["midi"] == pytest.approx(60.0) # Corrected from 72 down to 60 + assert corrected[2]["midi"] == 61.0 + + +def test_no_correction_for_legitimate_contour(): + # Gradual rise: 60 -> 64 -> 67 (C major triad arpeggio) + syllables = [ + {"text": "A", "midi": 60.0}, + {"text": "B", "midi": 64.0}, + {"text": "C", "midi": 67.0}, + ] + corrected = correct_octave_errors(syllables) + assert corrected[1]["midi"] == 64.0