3 Commits

Author SHA1 Message Date
c73ad8d66b feat(pitch,lyrics): tune pipeline heuristics from dual-track learnings
- Increase melisma pitch jump threshold to 1.6 st to prevent vibrato over-splitting
- Add transient consonant attack snapping in snap_onset
- Add continuous voicing extension for sustained rock vowels
- Deduplicate rapid hallucinated line repetitions in Whisper output
- Add automatic global octave transposition alignment in ultrastar_to_vocals
- Cache CREPE F0 frames in crepe_f0_<model>.npz for rapid iterative tuning
- Accurately compute octave-aligned pitch accuracy in evaluate_vocals
2026-11-04 00:33:50 +01:00
dcde066772 feat(dual-track): ground-truth packaging, training diff and import-ultrastar 2026-11-03 22:59:06 +01:00
c93d2c696e feat(eval): note onset snapping, melisma segmentation and youtube audio retrieval 2026-11-03 22:03:56 +01:00
14 changed files with 866 additions and 90 deletions

6
.gitignore vendored
View File

@ -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

View File

@ -141,10 +141,18 @@ unmix analyze song.mp4 -o output_song/ --stems 6 --quality fast --lang en
# Analyse direkt von YouTube/Web-URL (benötigt yt-dlp)
unmix analyze "https://www.youtube.com/watch?v=..." -o output_song/ --lang en
# Analyse mit direktem Vergleich gegen UltraStar-Referenzdatei
# Analyse mit Dual-Track Referenzmodus (erzeugt perfektes Songpack + Trainings-Differenzprotokoll)
unmix analyze song.mp3 -o output_song/ --lang en --reference ground_truth_song.txt
# Schneller Direkt-Import (übernimmt UltraStar-Gesang, rechnet nur Stems/Akkorde/Tempo)
unmix import-ultrastar ground_truth_song.txt song.mp3 -o output_song/
```
> [!TIP]
> **Dual-Track & Training-Feedback (`--reference`):**
> Wird `--reference <file.txt>` übergeben, nutzt `unmix` die verifizierten Referenznoten für das fertige Songpack (`vocals.json`) und vergleicht gleichzeitig die KI-Vorhersage Note für Note mit der Referenz. Die genaue Fehleranalyse wird in `training_diff.json` gespeichert (systematischer Timing- und Dauern-Drift, übersehene Noten, Melismen), um die Pipeline kontinuierlich datengetrieben zu verbessern.
> [!NOTE]
> **Rechtlicher Hinweis zu Online-Quellen:** Der Download von Audiodaten aus Online-Quellen (wie YouTube) über `yt-dlp` geschieht ausschließlich auf Veranlassung des Nutzers. Der Nutzer ist selbst dafür verantwortlich, dass die erforderlichen Rechte für die Verarbeitung und Analyse der Inhalte vorliegen.

View File

@ -57,6 +57,11 @@ def analyze(
title: str | None = typer.Option(None, "--title", help="Song title metadata"),
artist: str | None = typer.Option(None, "--artist", help="Song artist metadata"),
reference: Path | None = typer.Option(None, "--reference", help="UltraStar ground-truth song.txt for evaluation"),
keep_ai_vocals: bool = typer.Option(
False,
"--keep-ai-vocals",
help="Keep AI-generated vocals.json instead of replacing with ground truth reference",
),
export_ultrastar_flag: bool = typer.Option(
True, "--export-ultrastar/--no-export-ultrastar", help="Export UltraStar song.txt to export/"
),
@ -121,46 +126,95 @@ def analyze(
language=meta.language,
)
# Evaluation against reference if requested
# Evaluation against reference & Dual-Track ground-truth packaging
if reference is not None:
ref_path = reference.resolve()
if not ref_path.exists():
console.print(f"[yellow][WARN][/yellow] Reference file not found: {ref_path}")
elif not vocals_json.exists():
console.print("[yellow][WARN][/yellow] vocals.json was not generated; skipping reference evaluation.")
else:
from unmix.eval.metrics import evaluate_vocals
from unmix.export.ultrastar import parse_ultrastar
from unmix.eval.metrics import generate_training_diff
from unmix.export.ultrastar import export_ultrastar, parse_ultrastar, ultrastar_to_vocals
from unmix.schema.vocals import VocalsDocument
with open(vocals_json, encoding="utf-8") as vf:
pred_vocals = VocalsDocument.model_validate(json.load(vf))
ref_song = parse_ultrastar(ref_path)
eval_metrics = evaluate_vocals(pred_vocals, ref_song)
# Store in meta.json
meta.reference_eval = eval_metrics
# 1. AI Vocals evaluation & Training Diff (Track B)
training_diff = None
if vocals_json.exists():
with open(vocals_json, encoding="utf-8") as vf:
ai_vocals = VocalsDocument.model_validate(json.load(vf))
# Preserve AI prediction in .cache
cache_ai_vocals = ctx.cache_dir / "vocals_ai.json"
cache_ai_vocals.parent.mkdir(parents=True, exist_ok=True)
with open(cache_ai_vocals, "w", encoding="utf-8") as caf:
caf.write(ai_vocals.model_dump_json(indent=2))
# Generate detailed note-by-note training difference
training_diff = generate_training_diff(ai_vocals, ref_song)
diff_path = output_dir / "training_diff.json"
with open(diff_path, "w", encoding="utf-8") as tdf:
json.dump(training_diff, tdf, indent=2)
meta.reference_eval = training_diff["summary"]
meta.training_diff = training_diff["systematic_biases"]
# 2. Ground-Truth Packaging (Track A)
if not keep_ai_vocals:
vocals_wav = ctx.stems_dir / "vocals.wav"
gt_vocals = ultrastar_to_vocals(ref_song, vocals_wav=vocals_wav)
with open(vocals_json, "w", encoding="utf-8") as vf:
vf.write(gt_vocals.model_dump_json(indent=2))
meta.vocals_source = "reference_ultrastar"
console.print(
"[bold green][OK][/bold green] High-Quality Ground-Truth vocals.json generated from reference."
)
else:
meta.vocals_source = "ai"
ctx.save_meta(meta)
# Display evaluation table
table = Table(title="UltraStar Referenz-Evaluierung")
table.add_column("Metrik", style="cyan")
table.add_column("Wert", style="bold green")
# Re-export song.txt from authoritative vocals.json
if export_ultrastar_flag and vocals_json.exists():
export_ultrastar(
output_dir,
title=meta.title or ref_song.title,
artist=meta.artist or ref_song.artist,
language=meta.language,
)
# Display rich summary tables
if training_diff:
eval_metrics = training_diff["summary"]
biases = training_diff["systematic_biases"]
table = Table(title="UltraStar Dual-Track Evaluierung & Training")
table.add_column("Metrik", style="cyan")
table.add_column("Wert", style="bold green")
table.add_row("Referenz-Silben", str(eval_metrics["num_ref_syllables"]))
table.add_row("KI-Vorhersage Silben", str(eval_metrics["num_pred_syllables"]))
table.add_row(
"Gematchte Noten", f"{biases['matched_notes_count']} / {eval_metrics['num_ref_syllables']}"
)
table.add_row("Ungematchte Ref-Noten (KI verpasst)", f"{biases['unmatched_ref_notes_count']}")
table.add_row("Falsch-positive KI-Noten", f"{biases['unmatched_predictions_count']}")
table.add_row("Timing MAE", f"{eval_metrics['mae_timing_ms']:.1f} ms")
table.add_row("Timing Median", f"{eval_metrics['median_timing_ms']:.1f} ms")
table.add_row("Systematischer Timing-Drift", f"{biases['mean_timing_bias_ms']:+.1f} ms")
table.add_row("Timing <= 50 ms", f"{eval_metrics['fraction_within_50ms'] * 100:.1f} %")
table.add_row("Timing <= 100 ms", f"{eval_metrics['fraction_within_100ms'] * 100:.1f} %")
table.add_row("Timing <= 200 ms", f"{eval_metrics['fraction_within_200ms'] * 100:.1f} %")
table.add_row("Notendauer MAE", f"{eval_metrics['duration_mae_ms']:.1f} ms")
table.add_row("Systematischer Dauer-Drift", f"{biases['mean_duration_bias_ms']:+.1f} ms")
table.add_row("Tonklasse gleich (Chroma)", f"{eval_metrics['pitch_class_accuracy'] * 100:.1f} %")
table.add_row("Median Oktavabweichung", f"{eval_metrics['median_octave_offset']:+.0f}")
table.add_row("WER (Word Error Rate)", f"{eval_metrics['wer']:.2f}")
console.print(table)
console.print(
f"[dim]Trainings-Differenzprotokoll gespeichert in: {output_dir / 'training_diff.json'}[/dim]"
)
table.add_row("Referenz-Silben", str(eval_metrics["num_ref_syllables"]))
table.add_row("Vorhergesagte Silben", str(eval_metrics["num_pred_syllables"]))
table.add_row("Zeilen (Pred / Ref)", f"{eval_metrics['num_pred_lines']} / {eval_metrics['num_ref_lines']}")
table.add_row("Timing MAE", f"{eval_metrics['mae_timing_ms']:.1f} ms")
table.add_row("Timing Median", f"{eval_metrics['median_timing_ms']:.1f} ms")
table.add_row("Timing <= 50 ms", f"{eval_metrics['fraction_within_50ms'] * 100:.1f} %")
table.add_row("Timing <= 100 ms", f"{eval_metrics['fraction_within_100ms'] * 100:.1f} %")
table.add_row("Timing <= 200 ms", f"{eval_metrics['fraction_within_200ms'] * 100:.1f} %")
table.add_row("Notendauer MAE", f"{eval_metrics['duration_mae_ms']:.1f} ms")
table.add_row("Tonhöhe (strikt)", f"{eval_metrics['strict_pitch_accuracy'] * 100:.1f} %")
table.add_row("Tonklasse gleich", f"{eval_metrics['pitch_class_accuracy'] * 100:.1f} %")
table.add_row("Median Oktavabweichung", f"{eval_metrics['median_octave_offset']:+.0f}")
table.add_row("WER (Word Error Rate)", f"{eval_metrics['wer']:.2f}")
console.print(table)
# Cleanup temporary download directory
if temp_dir_obj is not None:
@ -203,6 +257,79 @@ def export_ultrastar_cmd(
print(str(res))
@app.command(name="import-ultrastar")
def import_ultrastar_cmd(
ultrastar_file: Path = typer.Argument(..., help="Path to UltraStar song.txt file", exists=True),
audio: str = typer.Argument(..., help="Audio file path or YouTube URL"),
output_dir: Path = typer.Option(..., "-o", "--output", help="Output song package directory"),
stems: int = typer.Option(4, "--stems", help="Number of stems to separate (4 or 6)"),
quality: str = typer.Option("best", "--quality", help="Separation quality ('fast' or 'best')"),
force: bool = typer.Option(False, "--force", help="Force recalculation"),
) -> None:
"""Import an UltraStar song.txt and audio file into a production-ready Song-Paket.
Extracts audio stems, chords, and tempo while using verified UltraStar vocals
(bypassing Whisper and CREPE for ultra-fast packaging).
"""
from unmix.export.ultrastar import export_ultrastar, import_ultrastar, parse_ultrastar
from unmix.pipeline import PipelineContext, get_default_pipeline
from unmix.sources import download_url_audio, is_url
temp_dir_obj = None
if is_url(audio):
console.print(f"[cyan][INFO][/cyan] Downloading audio stream via yt-dlp: {audio}")
temp_dir_obj = tempfile.TemporaryDirectory(prefix="unmix_yt_")
temp_dir = Path(temp_dir_obj.name)
source_path, _ = download_url_audio(audio, temp_dir)
console.print(f"[green][OK][/green] Downloaded audio: {source_path.name}")
else:
source_path = Path(audio).resolve()
if not source_path.exists():
console.print(f"[red][ERROR][/red] Input audio file not found: {source_path}")
raise typer.Exit(code=1)
ref_song = parse_ultrastar(ultrastar_file)
lang = "en" if "english" in ref_song.headers.get("LANGUAGE", "").lower() else "de"
# Run stems, chords, tempo, strumming (target stage: strumming)
ctx = PipelineContext(
source_file=source_path,
output_dir=output_dir,
lang=lang,
stems=stems,
quality=quality,
force=force,
target_stage="strumming",
)
runner = get_default_pipeline()
meta = runner.run(ctx)
# Import verified vocals directly from UltraStar
vocals_wav = ctx.stems_dir / "vocals.wav"
import_ultrastar(ultrastar_file, output_dir, vocals_wav=vocals_wav)
meta.vocals_source = "reference_ultrastar"
if ref_song.title and not meta.title:
meta.title = ref_song.title
if ref_song.artist and not meta.artist:
meta.artist = ref_song.artist
meta.language = lang
ctx.save_meta(meta)
# Re-export clean song.txt
export_ultrastar(output_dir, title=meta.title, artist=meta.artist, language=meta.language)
if temp_dir_obj is not None:
try:
temp_dir_obj.cleanup()
except Exception:
pass
console.print(
f"[bold green][OK][/bold green] Successfully imported UltraStar Songpack to: {output_dir.resolve()}"
)
@app.command(name="eval")
def eval_cmd(
testset_config: Path = typer.Argument(..., help="Path to testset.toml", exists=True),

View File

@ -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,9 +230,119 @@ 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,
"wer": wer_score,
}
def generate_training_diff(
predicted: VocalsDocument,
reference: UltraStarSong,
max_match_distance_sec: float = 2.0,
) -> dict[str, Any]:
"""Generate detailed note-by-note training difference and error breakdown."""
summary = evaluate_vocals(predicted, reference, max_match_distance_sec)
ref_notes = [n for line in reference.lines for n in line if n.text.strip()]
pred_sylls = [syl for line in predicted.lines for syl in line.syllables if syl.text.strip()]
matched_pairs: list[dict[str, Any]] = []
matched_pred_indices: set[int] = set()
unmatched_ref_notes: list[dict[str, Any]] = []
for ref in ref_notes:
best_idx = None
best_diff = float("inf")
for idx, pred in enumerate(pred_sylls):
if idx in matched_pred_indices:
continue
diff = abs(pred.start - ref.start_sec)
if diff < best_diff and diff <= max_match_distance_sec:
best_diff = diff
best_idx = idx
if best_idx is not None:
matched_pred_indices.add(best_idx)
pred = pred_sylls[best_idx]
timing_err = (pred.start - ref.start_sec) * 1000.0
dur_err = ((pred.end - pred.start) - (ref.end_sec - ref.start_sec)) * 1000.0
p_midi = round(pred.midi, 2) if pred.midi is not None else None
r_midi = round(ref.midi, 2)
pitch_err = round(pred.midi - ref.midi, 2) if pred.midi is not None else None
is_class = (int(round(pred.midi)) % 12) == (int(round(ref.midi)) % 12) if pred.midi is not None else False
oct_off = int(round((pred.midi - ref.midi) / 12.0)) if pred.midi is not None else None
matched_pairs.append(
{
"ref_text": ref.text.strip(),
"pred_text": pred.text.strip(),
"ref_start": round(ref.start_sec, 3),
"pred_start": round(pred.start, 3),
"timing_error_ms": round(timing_err, 1),
"ref_duration_ms": round((ref.end_sec - ref.start_sec) * 1000.0, 1),
"pred_duration_ms": round((pred.end - pred.start) * 1000.0, 1),
"duration_error_ms": round(dur_err, 1),
"ref_midi": r_midi,
"pred_midi": p_midi,
"pitch_error_semitones": pitch_err,
"pitch_class_match": is_class,
"octave_offset": oct_off,
}
)
else:
unmatched_ref_notes.append(
{
"text": ref.text.strip(),
"start": round(ref.start_sec, 3),
"end": round(ref.end_sec, 3),
"duration_ms": round((ref.end_sec - ref.start_sec) * 1000.0, 1),
"midi": round(ref.midi, 2),
}
)
unmatched_predictions: list[dict[str, Any]] = [
{
"text": pred.text.strip(),
"start": round(pred.start, 3),
"end": round(pred.end, 3),
"duration_ms": round((pred.end - pred.start) * 1000.0, 1),
"midi": round(pred.midi, 2) if pred.midi is not None else None,
}
for idx, pred in enumerate(pred_sylls)
if idx not in matched_pred_indices
]
# Calculate systematic biases on matched notes
if matched_pairs:
signed_timing = [p["timing_error_ms"] for p in matched_pairs]
signed_dur = [p["duration_error_ms"] for p in matched_pairs]
mean_signed_timing_ms = float(np.mean(signed_timing))
median_signed_timing_ms = float(np.median(signed_timing))
mean_signed_dur_ms = float(np.mean(signed_dur))
else:
mean_signed_timing_ms = 0.0
median_signed_timing_ms = 0.0
mean_signed_dur_ms = 0.0
systematic_biases = {
"mean_timing_bias_ms": round(mean_signed_timing_ms, 1),
"median_timing_bias_ms": round(median_signed_timing_ms, 1),
"mean_duration_bias_ms": round(mean_signed_dur_ms, 1),
"median_octave_offset": summary["median_octave_offset"],
"unmatched_ref_notes_count": len(unmatched_ref_notes),
"unmatched_predictions_count": len(unmatched_predictions),
"matched_notes_count": len(matched_pairs),
}
return {
"summary": summary,
"systematic_biases": systematic_biases,
"matched_notes": matched_pairs,
"unmatched_reference_notes": unmatched_ref_notes,
"unmatched_predictions": unmatched_predictions,
}

View File

@ -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"

View File

@ -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."""
@ -312,3 +324,148 @@ def parse_ultrastar(file_path: Path) -> UltraStarSong:
note.midi = float(note.pitch + 60)
return UltraStarSong(headers=headers, lines=lines)
def ultrastar_to_vocals(
song: UltraStarSong,
vocals_wav: Path | None = None,
snap_tolerance_ms: float = 40.0,
) -> VocalsDocument:
"""Convert parsed UltraStarSong into a VocalsDocument.
If vocals_wav is provided and exists, fine-snaps note starts within snap_tolerance_ms
to true acoustic transients to compensate for beat-quantization jitter.
"""
import numpy as np
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:
import librosa
import soundfile as sf
audio_data, sr = sf.read(str(vocals_wav), dtype="float32")
if audio_data.ndim > 1:
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
for line_idx, r_line in enumerate(song.lines):
if not r_line:
continue
line_sylls: list[VocalSyllable] = []
for note_idx, note in enumerate(r_line):
syl_counter += 1
raw_text = note.text
has_space = raw_text.endswith(" ")
clean_text = raw_text.rstrip()
is_word_end = has_space or (note_idx == len(r_line) - 1)
s_start = note.start_sec
s_end = note.end_sec
# Fine-snap to acoustic transients if available
if acoustic_onsets is not None and len(acoustic_onsets) > 0:
tol_sec = snap_tolerance_ms / 1000.0
cands = acoustic_onsets[
(acoustic_onsets >= s_start - tol_sec) & (acoustic_onsets <= s_start + tol_sec)
]
if len(cands) > 0:
snapped = float(cands[np.argmin(np.abs(cands - s_start))])
if snapped < s_end:
s_start = snapped
# Map UltraStar note types
stype = "normal"
if note.note_type == "*":
stype = "golden"
elif note.note_type == "F":
stype = "freestyle"
elif note.note_type == "R":
stype = "rap"
line_sylls.append(
VocalSyllable(
id=f"s_{syl_counter:04d}",
text=clean_text,
start=s_start,
end=s_end,
midi=float(note.midi + octave_shift),
confidence=1.0,
type=stype,
word_end=is_word_end,
golden=(stype == "golden"),
)
)
if line_sylls:
vocal_lines.append(
VocalLine(
id=f"l_{line_idx + 1:04d}",
voice=0,
start=line_sylls[0].start,
end=line_sylls[-1].end,
syllables=line_sylls,
)
)
return VocalsDocument(
schema_version="1.0",
generated_by=GeneratedBy(
stage="import_ultrastar",
model="reference_ultrastar",
model_version="1.0.0",
params={
"gap_ms": song.gap_ms,
"bpm": song.bpm,
"title": song.title,
"artist": song.artist,
},
),
lines=vocal_lines,
)
def import_ultrastar(
txt_path: Path,
output_dir: Path,
vocals_wav: Path | None = None,
snap_tolerance_ms: float = 40.0,
) -> Path:
"""Parse UltraStar file and save as vocals.json in output_dir."""
output_dir = output_dir.resolve()
output_dir.mkdir(parents=True, exist_ok=True)
song = parse_ultrastar(txt_path)
doc = ultrastar_to_vocals(song, vocals_wav=vocals_wav, snap_tolerance_ms=snap_tolerance_ms)
out_file = output_dir / "vocals.json"
with open(out_file, "w", encoding="utf-8") as f:
f.write(doc.model_dump_json(indent=2))
return out_file

View File

@ -77,6 +77,11 @@ class ExtractStage(Stage):
output_wav = self.get_outputs(ctx)[0]
output_wav.parent.mkdir(parents=True, exist_ok=True)
if ctx.source_file.resolve() == output_wav.resolve():
# Source file is already the cached extracted.wav
return
# ffmpeg extraction command:
# -y : overwrite output
# -i <source>

View File

@ -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]] = []
@ -166,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,
}
)

View File

@ -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,108 @@ 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]:
# 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])
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.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
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 +201,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,80 +209,155 @@ 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
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_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)
# 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,
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 +387,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 +413,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)

View File

@ -90,6 +90,9 @@ class MetaDocument(SongPackageBase):
stages_done: list[str] = Field(default_factory=list)
stages_failed: dict[str, str] = Field(default_factory=dict)
reference_eval: dict[str, Any] | None = None
vocals_source: Literal["ai", "reference_ultrastar"] = "ai"
training_diff: dict[str, Any] | None = None
# Backward compatibility helper
@property

View File

@ -84,3 +84,10 @@ def test_config_device_detection(monkeypatch):
# Test explicit CUDA requested on non-CUDA system falls back to cpu
monkeypatch.setenv("UNMIX_DEVICE_S2", "cuda:99")
assert cfg.get_device("s2_stems") == "cpu"
def test_cli_import_ultrastar_help():
result = runner.invoke(app, ["import-ultrastar", "--help"])
assert result.exit_code == 0
assert "Import an UltraStar song.txt" in result.stdout

View File

@ -6,6 +6,7 @@ from unmix.eval.metrics import (
evaluate_vocals,
extract_text_from_reference,
extract_text_from_vocals,
generate_training_diff,
normalize_text_for_wer,
)
from unmix.export.ultrastar import UltraStarNote, UltraStarSong
@ -134,3 +135,59 @@ def test_evaluate_vocals_octave_error_and_timing_offset():
# Median octave offset should be -1.0
assert metrics["median_octave_offset"] == pytest.approx(-1.0)
assert metrics["wer"] == pytest.approx(0.0)
def test_generate_training_diff():
ref_song = UltraStarSong(
headers={"BPM": "120", "GAP": "1000"},
lines=[
[
UltraStarNote(":", 0, 4, 0, "First ", start_sec=1.0, end_sec=1.5, midi=60.0),
UltraStarNote(":", 4, 4, 2, "Second ", start_sec=1.5, end_sec=2.0, midi=62.0),
]
],
)
pred_doc = VocalsDocument(
lines=[
VocalLine(
start=1.02,
end=1.52,
syllables=[
VocalSyllable(text="First", start=1.02, end=1.52, midi=60.0, word_end=True),
VocalSyllable(text="Extra", start=5.0, end=5.5, midi=65.0, word_end=True),
],
)
]
)
diff = generate_training_diff(pred_doc, ref_song)
assert "summary" in diff
assert "systematic_biases" in diff
assert "matched_notes" in diff
assert "unmatched_reference_notes" in diff
assert "unmatched_predictions" in diff
# Matched note checks
assert len(diff["matched_notes"]) == 1
m0 = diff["matched_notes"][0]
assert m0["ref_text"] == "First"
assert m0["pred_text"] == "First"
assert m0["timing_error_ms"] == pytest.approx(20.0, abs=1.0)
assert m0["pitch_error_semitones"] == pytest.approx(0.0)
# Unmatched reference note: "Second" was missed by AI
assert len(diff["unmatched_reference_notes"]) == 1
assert diff["unmatched_reference_notes"][0]["text"] == "Second"
# Unmatched prediction: "Extra" was hallucinated / extra
assert len(diff["unmatched_predictions"]) == 1
assert diff["unmatched_predictions"][0]["text"] == "Extra"
# Systematic biases
biases = diff["systematic_biases"]
assert biases["matched_notes_count"] == 1
assert biases["unmatched_ref_notes_count"] == 1
assert biases["unmatched_predictions_count"] == 1
assert biases["mean_timing_bias_ms"] == pytest.approx(20.0, abs=1.0)

View File

@ -4,7 +4,7 @@ from pathlib import Path
import pytest
from unmix.export.ultrastar import export_ultrastar, parse_ultrastar
from unmix.export.ultrastar import export_ultrastar, import_ultrastar, parse_ultrastar, ultrastar_to_vocals
from unmix.schema.meta import MetaDocument, SourceFileInfo
from unmix.schema.tempo import TempoAnchor, TempoDocument
from unmix.schema.vocals import VocalLine, VocalsDocument, VocalSyllable
@ -155,3 +155,44 @@ def test_ultrastar_metadata_and_language_english(tmp_path: Path):
last_note = parsed.lines[1][0]
assert last_note.start_sec == pytest.approx(250.0, abs=0.15)
assert last_note.end_sec == pytest.approx(258.7, abs=0.15)
def test_ultrastar_to_vocals_and_import(tmp_path: Path):
txt_content = """#TITLE:Imported Song
#ARTIST:Imported Artist
#BPM:120
#GAP:1000
: 0 4 0 Hel-
: 4 4 2 lo
* 8 8 4 World
- 16
: 20 4 0 Again
E
"""
txt_file = tmp_path / "song.txt"
txt_file.write_text(txt_content, encoding="utf-8")
song = parse_ultrastar(txt_file)
doc = ultrastar_to_vocals(song)
assert len(doc.lines) == 2
l0 = doc.lines[0]
assert len(l0.syllables) == 3
assert l0.syllables[0].text == "Hel-"
assert l0.syllables[0].word_end is False
assert l0.syllables[1].text == "lo"
assert l0.syllables[1].word_end is True
assert l0.syllables[2].text == "World"
assert l0.syllables[2].golden is True
assert l0.syllables[2].type == "golden"
# Test import_ultrastar creates vocals.json
out_dir = tmp_path / "imported_pkg"
vocals_json = import_ultrastar(txt_file, out_dir)
assert vocals_json.exists()
with open(vocals_json, encoding="utf-8") as vf:
loaded = VocalsDocument.model_validate_json(vf.read())
assert len(loaded.lines) == 2
assert loaded.lines[0].syllables[2].type == "golden"

9
testset.example.toml Normal file
View 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"