diff --git a/src/unmix/eval/metrics.py b/src/unmix/eval/metrics.py index b5cbdc5..e5dbebe 100644 --- a/src/unmix/eval/metrics.py +++ b/src/unmix/eval/metrics.py @@ -165,6 +165,19 @@ def evaluate_vocals( else: median_octave_offset = 0.0 + # Octave-aligned pitch accuracy (strict match after adjusting for song's median octave offset) + if matched_pairs and median_octave_offset != 0.0: + oct_aligned_correct = [] + for r, p in matched_pairs: + ref_m = int(round(r.midi)) + pred_m = int(round(p.midi - median_octave_offset * 12.0)) if p.midi is not None else -999 + oct_aligned_correct.append(1.0 if pred_m == ref_m else 0.0) + for _ in range(len(ref_notes) - len(matched_pairs)): + oct_aligned_correct.append(0.0) + octave_equiv_pitch_acc = float(np.mean(oct_aligned_correct)) + else: + octave_equiv_pitch_acc = strict_pitch_acc + # 3. Line metrics ref_lines_valid = [r_line for r_line in reference.lines if any(n.text.strip() for n in r_line)] pred_lines_valid = [p_line for p_line in predicted.lines if any(s.text.strip() for s in p_line.syllables)] @@ -217,7 +230,7 @@ def evaluate_vocals( "duration_mae_ms": duration_mae_ms, "strict_pitch_accuracy": strict_pitch_acc, "pitch_class_accuracy": pitch_class_acc, - "octave_equiv_pitch_accuracy": pitch_class_acc, + "octave_equiv_pitch_accuracy": octave_equiv_pitch_acc, "median_octave_offset": median_octave_offset, "line_start_mae_ms": line_start_mae_ms, "line_end_mae_ms": line_end_mae_ms, diff --git a/src/unmix/export/ultrastar.py b/src/unmix/export/ultrastar.py index c5fab70..c12345e 100644 --- a/src/unmix/export/ultrastar.py +++ b/src/unmix/export/ultrastar.py @@ -341,6 +341,7 @@ def ultrastar_to_vocals( from unmix.schema.base import GeneratedBy from unmix.schema.vocals import VocalLine, VocalSyllable + octave_shift = 0.0 acoustic_onsets = None if vocals_wav and Path(vocals_wav).exists(): try: @@ -352,8 +353,26 @@ def ultrastar_to_vocals( audio_data = audio_data.mean(axis=-1) onset_env = librosa.onset.onset_strength(y=audio_data, sr=sr) acoustic_onsets = librosa.onset.onset_detect(onset_envelope=onset_env, sr=sr, units="time") + + # Check for global octave transposition between audio and UltraStar notes + mid_sec = len(audio_data) / (2.0 * sr) + w_start = max(0, int((mid_sec - 20) * sr)) + w_end = min(len(audio_data), int((mid_sec + 25) * sr)) + sample = audio_data[w_start:w_end] + if len(sample) > sr * 5: + f0 = librosa.yin(sample, fmin=65, fmax=600, sr=sr) + valid_f0 = f0[(f0 > 65) & (f0 < 600)] + if len(valid_f0) > 100: + med_audio_midi = float(69.0 + 12.0 * np.log2(np.median(valid_f0) / 440.0)) + all_ref_midis = [n.midi for song_line in song.lines for n in song_line if n.midi is not None] + if all_ref_midis: + med_ref_midi = float(np.median(all_ref_midis)) + diff_octaves = round((med_ref_midi - med_audio_midi) / 12.0) + if abs(diff_octaves) >= 1: + octave_shift = -diff_octaves * 12.0 except Exception: acoustic_onsets = None + octave_shift = 0.0 vocal_lines: list[VocalLine] = [] syl_counter = 0 @@ -398,7 +417,7 @@ def ultrastar_to_vocals( text=clean_text, start=s_start, end=s_end, - midi=float(note.midi), + midi=float(note.midi + octave_shift), confidence=1.0, type=stype, word_end=is_word_end, diff --git a/src/unmix/pipeline/s3_lyrics.py b/src/unmix/pipeline/s3_lyrics.py index 8e10a93..7800139 100644 --- a/src/unmix/pipeline/s3_lyrics.py +++ b/src/unmix/pipeline/s3_lyrics.py @@ -172,11 +172,21 @@ class LyricsStage(Stage): seg_syllables.extend(w_sylls) if seg_syllables: + clean_text = seg.text.strip() + seg_dur = max(0.01, seg.end - seg.start) + + # Skip Whisper hallucinated repetition at segment boundaries / audio fadeout + if lines and lines[-1]["text"].strip().lower() == clean_text.lower(): + prev_dur = max(0.01, lines[-1]["end"] - lines[-1]["start"]) + # If this duplicate is unnaturally rushed or short (<2s or < 50% prev duration) + if seg_dur < 2.0 or (seg_dur < prev_dur * 0.5): + continue + lines.append( { "start": seg.start, "end": seg.end, - "text": seg.text.strip(), + "text": clean_text, "syllables": seg_syllables, } ) diff --git a/src/unmix/pipeline/s4_pitch.py b/src/unmix/pipeline/s4_pitch.py index 290fc7c..af55216 100644 --- a/src/unmix/pipeline/s4_pitch.py +++ b/src/unmix/pipeline/s4_pitch.py @@ -94,6 +94,13 @@ def snap_onset( return voiced_t if not is_voiced[idx_target]: + # Check if there is an acoustic transient near the target (e.g. consonant attack) + ac_near = acoustic_onsets[ + (acoustic_onsets >= max(w_min, target_t - 0.08)) & (acoustic_onsets <= min(w_max, target_t + 0.06)) + ] + if len(ac_near) > 0: + return float(ac_near[np.argmin(np.abs(ac_near - target_t))]) + fwd_mask = (frame_times >= target_t) & (frame_times <= w_max) & is_voiced if np.any(fwd_mask): first_voiced = float(frame_times[fwd_mask][0]) @@ -115,8 +122,8 @@ def segment_melisma( midi_frames: np.ndarray, is_voiced: np.ndarray, hop_sec: float, - min_len: float = 0.15, - min_pitch_jump: float = 1.0, + min_len: float = 0.20, + min_pitch_jump: float = 1.6, ) -> list[tuple[float, float, float]]: """Segment multi-pitch syllables into base syllable + melisma continuation note.""" mask = (frame_times >= s_start) & (frame_times <= s_end) & is_voiced @@ -218,26 +225,33 @@ class PitchStage(Stage): 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) + crepe_cache_file = ctx.cache_dir / f"crepe_f0_{crepe_model}.npz" + if crepe_cache_file.exists(): + cached_data = np.load(crepe_cache_file) + pitch_hz = cached_data["pitch_hz"] + periodicity = cached_data["periodicity"] + else: + 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, - ) + # Run CREPE pitch prediction + pitch_hz_tensor, periodicity_tensor = 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() + pitch_hz = pitch_hz_tensor.squeeze(0).cpu().numpy() + periodicity = periodicity_tensor.squeeze(0).cpu().numpy() + np.savez_compressed(crepe_cache_file, pitch_hz=pitch_hz, periodicity=periodicity) # Frame timestamps: t_k = k * (hop_length / crepe_sr) frame_times = np.arange(len(pitch_hz)) * hop_sec @@ -292,6 +306,22 @@ class PitchStage(Stage): real_end = max(snapped_start + 0.08, s_end) + # Extend held vowels if singer continues voicing beyond Whisper speech boundary + next_start_limit = ( + float(sylls[idx + 1]["start"]) - 0.04 if idx < len(sylls) - 1 else real_end + 3.0 + ) + if real_end < next_start_limit: + idx_end = int(round(real_end / hop_sec)) if hop_sec > 0 else 0 + while ( + idx_end < len(is_voiced) + and is_voiced[idx_end] + and frame_times[idx_end] < next_start_limit + ): + idx_end += 1 + extended_end = float(frame_times[min(len(frame_times) - 1, idx_end)]) + if extended_end > real_end: + real_end = min(next_start_limit, extended_end) + segs = segment_melisma( snapped_start, real_end,