feat(eval): note onset snapping, melisma segmentation and youtube audio retrieval
This commit is contained in:
6
.gitignore
vendored
6
.gitignore
vendored
@ -41,6 +41,12 @@ testdata/
|
||||
*.flac
|
||||
*.ogg
|
||||
|
||||
# Local evaluation data and reports
|
||||
testset.local.toml
|
||||
eval_runs/
|
||||
eval_report.*
|
||||
.downloads/
|
||||
|
||||
# Allow synthetic demo audio
|
||||
!examples/demo_song/stems/*.wav
|
||||
pragmatic_readme_template*.md
|
||||
|
||||
@ -26,9 +26,55 @@ def run_evaluation(testset_config: Path, output_report_dir: Path | None = None)
|
||||
|
||||
for song_entry in songs:
|
||||
name = song_entry.get("name", "Unnamed")
|
||||
audio_path = Path(song_entry["audio"]).resolve()
|
||||
ref_path = Path(song_entry["reference"]).resolve()
|
||||
lang = song_entry.get("lang", "de")
|
||||
if not ref_path.exists():
|
||||
results.append(
|
||||
{
|
||||
"name": name,
|
||||
"status": "failed",
|
||||
"error": f"Reference file not found: {ref_path}",
|
||||
"elapsed_sec": 0.0,
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
ref_song = parse_ultrastar(ref_path)
|
||||
lang = song_entry.get("lang")
|
||||
if not lang:
|
||||
ref_lang = ref_song.headers.get("LANGUAGE", "").lower()
|
||||
if "english" in ref_lang or ref_lang == "en":
|
||||
lang = "en"
|
||||
elif "german" in ref_lang or ref_lang == "de":
|
||||
lang = "de"
|
||||
else:
|
||||
lang = "de"
|
||||
|
||||
audio_str = song_entry.get("audio")
|
||||
audio_path = Path(audio_str).resolve() if audio_str else None
|
||||
|
||||
if not audio_path or not audio_path.exists():
|
||||
from unmix.sources import download_url_audio, is_url
|
||||
|
||||
yt_url = ref_song.youtube_url or (audio_str if audio_str and is_url(audio_str) else None)
|
||||
if yt_url:
|
||||
dl_dir = report_dir / ".downloads"
|
||||
dl_dir.mkdir(parents=True, exist_ok=True)
|
||||
safe_name = "".join(c if c.isalnum() else "_" for c in name)
|
||||
downloaded_file = dl_dir / f"{safe_name}.wav"
|
||||
if not downloaded_file.exists():
|
||||
temp_wav, _ = download_url_audio(yt_url, dl_dir)
|
||||
temp_wav.rename(downloaded_file)
|
||||
audio_path = downloaded_file
|
||||
else:
|
||||
results.append(
|
||||
{
|
||||
"name": name,
|
||||
"status": "failed",
|
||||
"error": f"Audio file not found: {audio_str} and no #VIDEO tag in reference",
|
||||
"elapsed_sec": 0.0,
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
song_out_dir = report_dir / "eval_runs" / name
|
||||
ctx = PipelineContext(
|
||||
@ -58,7 +104,6 @@ def run_evaluation(testset_config: Path, output_report_dir: Path | None = None)
|
||||
with open(vocals_json, encoding="utf-8") as vf:
|
||||
pred_vocals = VocalsDocument.model_validate(json.load(vf))
|
||||
|
||||
ref_song = parse_ultrastar(ref_path)
|
||||
metrics = evaluate_vocals(pred_vocals, ref_song)
|
||||
metrics["name"] = name
|
||||
metrics["status"] = "success"
|
||||
|
||||
@ -243,6 +243,18 @@ class UltraStarSong:
|
||||
def gap_ms(self) -> float:
|
||||
return float(self.headers.get("GAP", "0").replace(",", "."))
|
||||
|
||||
@property
|
||||
def youtube_url(self) -> str | None:
|
||||
video_tag = self.headers.get("VIDEO", "")
|
||||
if not video_tag:
|
||||
return None
|
||||
match = re.search(r"(?:a=|v=|/watch\?v=|youtu\.be/)([a-zA-Z0-9_-]{11})", video_tag)
|
||||
if match:
|
||||
return f"https://www.youtube.com/watch?v={match.group(1)}"
|
||||
if "youtube.com" in video_tag or "youtu.be" in video_tag:
|
||||
return video_tag.strip()
|
||||
return None
|
||||
|
||||
|
||||
def parse_ultrastar(file_path: Path) -> UltraStarSong:
|
||||
"""Parse an UltraStar .txt file into structured notes and absolute times in seconds."""
|
||||
|
||||
@ -140,11 +140,17 @@ class LyricsStage(Stage):
|
||||
download_root=str(models_dir),
|
||||
)
|
||||
|
||||
vad_params = {
|
||||
"min_silence_duration_ms": 400,
|
||||
"speech_pad_ms": 150,
|
||||
}
|
||||
|
||||
segments, info = model.transcribe(
|
||||
str(vocals_wav),
|
||||
language=lang,
|
||||
word_timestamps=True,
|
||||
vad_filter=True,
|
||||
vad_parameters=vad_params,
|
||||
)
|
||||
|
||||
lines: list[dict[str, Any]] = []
|
||||
|
||||
@ -1,9 +1,10 @@
|
||||
"""Stage 4: Pitch tracking with CREPE -> median MIDI pitch per syllable."""
|
||||
"""Stage 4: Pitch tracking with CREPE -> median MIDI pitch per syllable with acoustic onset snapping."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import librosa
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
import torch
|
||||
@ -57,11 +58,101 @@ def correct_octave_errors(syllables: list[dict[str, Any]]) -> list[dict[str, Any
|
||||
return syllables
|
||||
|
||||
|
||||
def snap_onset(
|
||||
target_t: float,
|
||||
w_min: float,
|
||||
w_max: float,
|
||||
acoustic_onsets: np.ndarray,
|
||||
candidate_onsets: np.ndarray,
|
||||
frame_times: np.ndarray,
|
||||
is_voiced: np.ndarray,
|
||||
hop_sec: float,
|
||||
is_line_start: bool = False,
|
||||
) -> float:
|
||||
"""Snap target timestamp to nearest vocal onset, acoustic transient, or voicing edge."""
|
||||
idx_target = int(round(target_t / hop_sec)) if hop_sec > 0 else 0
|
||||
if 0 <= idx_target < len(is_voiced):
|
||||
if is_line_start:
|
||||
lookback_idx = max(0, idx_target - int(1.2 / hop_sec))
|
||||
k = idx_target
|
||||
if not is_voiced[k]:
|
||||
fwd_limit = min(len(is_voiced), idx_target + int(0.5 / hop_sec))
|
||||
found_v = None
|
||||
for j in range(k, fwd_limit):
|
||||
if is_voiced[j]:
|
||||
found_v = j
|
||||
break
|
||||
if found_v is not None:
|
||||
k = found_v
|
||||
if is_voiced[k]:
|
||||
while k > lookback_idx and (is_voiced[k - 1] or (k > 2 and is_voiced[k - 2])):
|
||||
k -= 1
|
||||
voiced_t = float(frame_times[k])
|
||||
cands = acoustic_onsets[(acoustic_onsets >= voiced_t - 0.08) & (acoustic_onsets <= voiced_t + 0.08)]
|
||||
if len(cands) > 0:
|
||||
return float(cands[np.argmin(np.abs(cands - voiced_t))])
|
||||
return voiced_t
|
||||
|
||||
if not is_voiced[idx_target]:
|
||||
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])
|
||||
cands = acoustic_onsets[(acoustic_onsets >= first_voiced - 0.06) & (acoustic_onsets <= first_voiced + 0.06)]
|
||||
if len(cands) > 0:
|
||||
return float(cands[np.argmin(np.abs(cands - first_voiced))])
|
||||
return first_voiced
|
||||
|
||||
cands = candidate_onsets[(candidate_onsets >= w_min) & (candidate_onsets <= w_max)]
|
||||
if len(cands) == 0:
|
||||
return target_t
|
||||
return float(cands[np.argmin(np.abs(cands - target_t))])
|
||||
|
||||
|
||||
def segment_melisma(
|
||||
s_start: float,
|
||||
s_end: float,
|
||||
frame_times: np.ndarray,
|
||||
midi_frames: np.ndarray,
|
||||
is_voiced: np.ndarray,
|
||||
hop_sec: float,
|
||||
min_len: float = 0.15,
|
||||
min_pitch_jump: float = 1.0,
|
||||
) -> 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
|
||||
if not np.any(mask):
|
||||
return [(s_start, s_end, 60.0)]
|
||||
|
||||
sub_times = frame_times[mask]
|
||||
sub_midis = midi_frames[mask]
|
||||
min_frames = int(min_len / hop_sec) if hop_sec > 0 else 1
|
||||
|
||||
if len(sub_times) < 2 * min_frames:
|
||||
return [(s_start, s_end, float(np.median(sub_midis)))]
|
||||
|
||||
best_split = None
|
||||
best_diff = 0.0
|
||||
for k in range(min_frames, len(sub_times) - min_frames):
|
||||
p1 = np.median(sub_midis[:k])
|
||||
p2 = np.median(sub_midis[k:])
|
||||
diff = abs(p2 - p1)
|
||||
if diff >= min_pitch_jump and diff > best_diff:
|
||||
best_diff = diff
|
||||
best_split = float(sub_times[k])
|
||||
|
||||
if best_split is not None:
|
||||
p1 = float(np.median(sub_midis[sub_times < best_split]))
|
||||
p2 = float(np.median(sub_midis[sub_times >= best_split]))
|
||||
return [(s_start, best_split, p1), (best_split, s_end, p2)]
|
||||
|
||||
return [(s_start, s_end, float(np.median(sub_midis)))]
|
||||
|
||||
|
||||
class PitchStage(Stage):
|
||||
"""Stage 4 extracts vocal fundamental frequency and assigns median pitch per syllable."""
|
||||
|
||||
name = "s4_pitch"
|
||||
version = "1.0.0"
|
||||
version = "1.1.0"
|
||||
model_name = "torchcrepe-full"
|
||||
model_version = "1.0.0"
|
||||
dependencies = ["s3_lyrics"]
|
||||
@ -103,7 +194,7 @@ class PitchStage(Stage):
|
||||
crepe_model = params["crepe_model"]
|
||||
self.model_name = f"torchcrepe-{crepe_model}"
|
||||
|
||||
# Load audio using soundfile (resample to 16000 Hz for CREPE)
|
||||
# Load audio using soundfile
|
||||
audio_data, sr = sf.read(str(vocals_wav), dtype="float32")
|
||||
if audio_data.ndim > 1:
|
||||
# Downmix to mono
|
||||
@ -111,8 +202,16 @@ class PitchStage(Stage):
|
||||
|
||||
crepe_sr = 16000
|
||||
hop_length = int(crepe_sr * (hop_length_ms / 1000.0))
|
||||
hop_sec = hop_length / crepe_sr
|
||||
|
||||
# Convert to torch tensor
|
||||
# Compute acoustic onsets using librosa
|
||||
try:
|
||||
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")
|
||||
except Exception:
|
||||
acoustic_onsets = np.array([], dtype=np.float32)
|
||||
|
||||
# Convert to torch tensor for CREPE
|
||||
audio_tensor = torch.from_numpy(audio_data).unsqueeze(0)
|
||||
if sr != crepe_sr:
|
||||
import julius
|
||||
@ -141,50 +240,94 @@ class PitchStage(Stage):
|
||||
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)
|
||||
frame_times = np.arange(len(pitch_hz)) * hop_sec
|
||||
midi_frames = hz_to_midi(pitch_hz)
|
||||
|
||||
# Candidate onsets from voicing edges and pitch jumps
|
||||
is_voiced = (periodicity >= voicing_thresh) & (pitch_hz > 50)
|
||||
voiced_diff = np.diff(is_voiced.astype(int), prepend=0)
|
||||
voicing_starts = frame_times[voiced_diff == 1]
|
||||
|
||||
pitch_diff = np.zeros_like(midi_frames)
|
||||
pitch_diff[1:] = np.abs(np.diff(midi_frames))
|
||||
pitch_jump_onsets = frame_times[(pitch_diff >= 1.0) & is_voiced]
|
||||
|
||||
candidate_onsets = np.unique(np.concatenate([acoustic_onsets, voicing_starts, pitch_jump_onsets]))
|
||||
candidate_onsets.sort()
|
||||
|
||||
# Process each line and syllable
|
||||
vocal_lines: list[VocalLine] = []
|
||||
line_counter = 0
|
||||
syl_counter = 0
|
||||
|
||||
for line_dict in lyrics_data.get("lines", []):
|
||||
sylls = line_dict.get("syllables", [])
|
||||
if not sylls:
|
||||
continue
|
||||
|
||||
line_counter += 1
|
||||
line_syllables_raw = []
|
||||
prev_end = 0.0
|
||||
|
||||
for syl_dict in line_dict.get("syllables", []):
|
||||
s_start = float(syl_dict["start"])
|
||||
s_end = float(syl_dict["end"])
|
||||
text = syl_dict["text"]
|
||||
w_end = syl_dict.get("word_end", False)
|
||||
for idx, s in enumerate(sylls):
|
||||
s_start = float(s["start"])
|
||||
s_end = float(s["end"])
|
||||
|
||||
# Frames within syllable
|
||||
mask = (frame_times >= s_start) & (frame_times <= s_end)
|
||||
voiced_mask = mask & (periodicity >= voicing_thresh) & (pitch_hz > 50)
|
||||
w_min = max(prev_end, s_start - 0.12)
|
||||
w_max = s_start + (0.50 if idx == 0 else 0.20)
|
||||
|
||||
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)),
|
||||
"word_end": w_end,
|
||||
}
|
||||
snapped_start = snap_onset(
|
||||
s_start,
|
||||
w_min,
|
||||
w_max,
|
||||
acoustic_onsets=acoustic_onsets,
|
||||
candidate_onsets=candidate_onsets,
|
||||
frame_times=frame_times,
|
||||
is_voiced=is_voiced,
|
||||
hop_sec=hop_sec,
|
||||
is_line_start=(idx == 0),
|
||||
)
|
||||
if snapped_start < prev_end:
|
||||
snapped_start = prev_end
|
||||
|
||||
real_end = max(snapped_start + 0.08, s_end)
|
||||
|
||||
segs = segment_melisma(
|
||||
snapped_start,
|
||||
real_end,
|
||||
frame_times=frame_times,
|
||||
midi_frames=midi_frames,
|
||||
is_voiced=is_voiced,
|
||||
hop_sec=hop_sec,
|
||||
)
|
||||
|
||||
for seg_idx, (seg_start, seg_end, seg_midi) in enumerate(segs):
|
||||
is_melisma = seg_idx > 0
|
||||
txt = "~ " if is_melisma else s["text"]
|
||||
is_word_end = s.get("word_end", False) if seg_idx == len(segs) - 1 else False
|
||||
|
||||
s_mask = (frame_times >= seg_start) & (frame_times <= seg_end)
|
||||
if np.any(s_mask):
|
||||
conf = float(np.mean(periodicity[s_mask]))
|
||||
else:
|
||||
conf = 0.5
|
||||
|
||||
line_syllables_raw.append(
|
||||
{
|
||||
"text": txt,
|
||||
"start": seg_start,
|
||||
"end": seg_end,
|
||||
"midi": seg_midi,
|
||||
"confidence": float(np.clip(conf, 0.0, 1.0)),
|
||||
"word_end": is_word_end,
|
||||
}
|
||||
)
|
||||
prev_end = line_syllables_raw[-1]["end"]
|
||||
|
||||
# Prevent overlapping within line
|
||||
for i in range(len(line_syllables_raw) - 1):
|
||||
if line_syllables_raw[i]["end"] > line_syllables_raw[i + 1]["start"]:
|
||||
line_syllables_raw[i]["end"] = line_syllables_raw[i + 1]["start"]
|
||||
|
||||
# Apply octave error correction within phrase
|
||||
corrected_sylls = correct_octave_errors(line_syllables_raw)
|
||||
@ -214,8 +357,8 @@ class PitchStage(Stage):
|
||||
VocalLine(
|
||||
id=f"l_{line_counter:04d}",
|
||||
voice=0,
|
||||
start=line_dict["start"],
|
||||
end=line_dict["end"],
|
||||
start=syl_objects[0].start,
|
||||
end=syl_objects[-1].end,
|
||||
syllables=syl_objects,
|
||||
)
|
||||
)
|
||||
@ -240,7 +383,6 @@ class PitchStage(Stage):
|
||||
try:
|
||||
from unmix.schema.vocals_f0 import VocalsF0Document
|
||||
|
||||
hop_sec = hop_length / crepe_sr
|
||||
f0_hz: list[float | None] = [
|
||||
round(float(h), 2) if p >= voicing_thresh and h > 50 else None
|
||||
for h, p in zip(pitch_hz, periodicity, strict=False)
|
||||
|
||||
9
testset.example.toml
Normal file
9
testset.example.toml
Normal file
@ -0,0 +1,9 @@
|
||||
# Beispiel-Konfiguration für unmix eval
|
||||
# Lokale Testsets können als testset.local.toml angelegt werden (in .gitignore).
|
||||
|
||||
[[songs]]
|
||||
name = "Demo Song"
|
||||
# audio ist optional: wenn weggelassen, wird die Audio-Quelle automatisch über den #VIDEO: Tag der Referenz-Datei via yt-dlp bezogen.
|
||||
# audio = "songs/demo.mp3"
|
||||
reference = "songs/reference_ultrastar.txt"
|
||||
lang = "de"
|
||||
Reference in New Issue
Block a user