feat(dual-track): ground-truth packaging, training diff and import-ultrastar
This commit is contained in:
10
README.md
10
README.md
@ -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)
|
# Analyse direkt von YouTube/Web-URL (benötigt yt-dlp)
|
||||||
unmix analyze "https://www.youtube.com/watch?v=..." -o output_song/ --lang en
|
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
|
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]
|
> [!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.
|
> **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.
|
||||||
|
|
||||||
|
|||||||
159
src/unmix/cli.py
159
src/unmix/cli.py
@ -57,6 +57,11 @@ def analyze(
|
|||||||
title: str | None = typer.Option(None, "--title", help="Song title metadata"),
|
title: str | None = typer.Option(None, "--title", help="Song title metadata"),
|
||||||
artist: str | None = typer.Option(None, "--artist", help="Song artist 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"),
|
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(
|
export_ultrastar_flag: bool = typer.Option(
|
||||||
True, "--export-ultrastar/--no-export-ultrastar", help="Export UltraStar song.txt to export/"
|
True, "--export-ultrastar/--no-export-ultrastar", help="Export UltraStar song.txt to export/"
|
||||||
),
|
),
|
||||||
@ -121,46 +126,95 @@ def analyze(
|
|||||||
language=meta.language,
|
language=meta.language,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Evaluation against reference if requested
|
# Evaluation against reference & Dual-Track ground-truth packaging
|
||||||
if reference is not None:
|
if reference is not None:
|
||||||
ref_path = reference.resolve()
|
ref_path = reference.resolve()
|
||||||
if not ref_path.exists():
|
if not ref_path.exists():
|
||||||
console.print(f"[yellow][WARN][/yellow] Reference file not found: {ref_path}")
|
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:
|
else:
|
||||||
from unmix.eval.metrics import evaluate_vocals
|
from unmix.eval.metrics import generate_training_diff
|
||||||
from unmix.export.ultrastar import parse_ultrastar
|
from unmix.export.ultrastar import export_ultrastar, parse_ultrastar, ultrastar_to_vocals
|
||||||
from unmix.schema.vocals import VocalsDocument
|
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)
|
ref_song = parse_ultrastar(ref_path)
|
||||||
eval_metrics = evaluate_vocals(pred_vocals, ref_song)
|
|
||||||
|
|
||||||
# Store in meta.json
|
# 1. AI Vocals evaluation & Training Diff (Track B)
|
||||||
meta.reference_eval = eval_metrics
|
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)
|
ctx.save_meta(meta)
|
||||||
|
|
||||||
# Display evaluation table
|
# Re-export song.txt from authoritative vocals.json
|
||||||
table = Table(title="UltraStar Referenz-Evaluierung")
|
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("Metrik", style="cyan")
|
||||||
table.add_column("Wert", style="bold green")
|
table.add_column("Wert", style="bold green")
|
||||||
|
|
||||||
table.add_row("Referenz-Silben", str(eval_metrics["num_ref_syllables"]))
|
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("KI-Vorhersage 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(
|
||||||
|
"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 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 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 <= 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 <= 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("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("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("Systematischer Dauer-Drift", f"{biases['mean_duration_bias_ms']:+.1f} ms")
|
||||||
table.add_row("Tonklasse gleich", f"{eval_metrics['pitch_class_accuracy'] * 100:.1f} %")
|
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("Median Oktavabweichung", f"{eval_metrics['median_octave_offset']:+.0f}")
|
||||||
table.add_row("WER (Word Error Rate)", f"{eval_metrics['wer']:.2f}")
|
table.add_row("WER (Word Error Rate)", f"{eval_metrics['wer']:.2f}")
|
||||||
console.print(table)
|
console.print(table)
|
||||||
|
console.print(
|
||||||
|
f"[dim]Trainings-Differenzprotokoll gespeichert in: {output_dir / 'training_diff.json'}[/dim]"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
# Cleanup temporary download directory
|
# Cleanup temporary download directory
|
||||||
if temp_dir_obj is not None:
|
if temp_dir_obj is not None:
|
||||||
@ -203,6 +257,79 @@ def export_ultrastar_cmd(
|
|||||||
print(str(res))
|
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")
|
@app.command(name="eval")
|
||||||
def eval_cmd(
|
def eval_cmd(
|
||||||
testset_config: Path = typer.Argument(..., help="Path to testset.toml", exists=True),
|
testset_config: Path = typer.Argument(..., help="Path to testset.toml", exists=True),
|
||||||
|
|||||||
@ -223,3 +223,113 @@ def evaluate_vocals(
|
|||||||
"line_end_mae_ms": line_end_mae_ms,
|
"line_end_mae_ms": line_end_mae_ms,
|
||||||
"wer": wer_score,
|
"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,
|
||||||
|
}
|
||||||
|
|
||||||
|
|||||||
@ -324,3 +324,129 @@ def parse_ultrastar(file_path: Path) -> UltraStarSong:
|
|||||||
note.midi = float(note.pitch + 60)
|
note.midi = float(note.pitch + 60)
|
||||||
|
|
||||||
return UltraStarSong(headers=headers, lines=lines)
|
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
|
||||||
|
|
||||||
|
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")
|
||||||
|
except Exception:
|
||||||
|
acoustic_onsets = None
|
||||||
|
|
||||||
|
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),
|
||||||
|
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
|
||||||
|
|
||||||
|
|||||||
@ -77,6 +77,11 @@ class ExtractStage(Stage):
|
|||||||
output_wav = self.get_outputs(ctx)[0]
|
output_wav = self.get_outputs(ctx)[0]
|
||||||
output_wav.parent.mkdir(parents=True, exist_ok=True)
|
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:
|
# ffmpeg extraction command:
|
||||||
# -y : overwrite output
|
# -y : overwrite output
|
||||||
# -i <source>
|
# -i <source>
|
||||||
|
|||||||
@ -90,6 +90,9 @@ class MetaDocument(SongPackageBase):
|
|||||||
stages_done: list[str] = Field(default_factory=list)
|
stages_done: list[str] = Field(default_factory=list)
|
||||||
stages_failed: dict[str, str] = Field(default_factory=dict)
|
stages_failed: dict[str, str] = Field(default_factory=dict)
|
||||||
reference_eval: dict[str, Any] | None = None
|
reference_eval: dict[str, Any] | None = None
|
||||||
|
vocals_source: Literal["ai", "reference_ultrastar"] = "ai"
|
||||||
|
training_diff: dict[str, Any] | None = None
|
||||||
|
|
||||||
|
|
||||||
# Backward compatibility helper
|
# Backward compatibility helper
|
||||||
@property
|
@property
|
||||||
|
|||||||
@ -84,3 +84,10 @@ def test_config_device_detection(monkeypatch):
|
|||||||
# Test explicit CUDA requested on non-CUDA system falls back to cpu
|
# Test explicit CUDA requested on non-CUDA system falls back to cpu
|
||||||
monkeypatch.setenv("UNMIX_DEVICE_S2", "cuda:99")
|
monkeypatch.setenv("UNMIX_DEVICE_S2", "cuda:99")
|
||||||
assert cfg.get_device("s2_stems") == "cpu"
|
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
|
||||||
|
|
||||||
|
|||||||
@ -6,6 +6,7 @@ from unmix.eval.metrics import (
|
|||||||
evaluate_vocals,
|
evaluate_vocals,
|
||||||
extract_text_from_reference,
|
extract_text_from_reference,
|
||||||
extract_text_from_vocals,
|
extract_text_from_vocals,
|
||||||
|
generate_training_diff,
|
||||||
normalize_text_for_wer,
|
normalize_text_for_wer,
|
||||||
)
|
)
|
||||||
from unmix.export.ultrastar import UltraStarNote, UltraStarSong
|
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
|
# Median octave offset should be -1.0
|
||||||
assert metrics["median_octave_offset"] == pytest.approx(-1.0)
|
assert metrics["median_octave_offset"] == pytest.approx(-1.0)
|
||||||
assert metrics["wer"] == pytest.approx(0.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)
|
||||||
|
|
||||||
|
|||||||
@ -4,7 +4,7 @@ from pathlib import Path
|
|||||||
|
|
||||||
import pytest
|
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.meta import MetaDocument, SourceFileInfo
|
||||||
from unmix.schema.tempo import TempoAnchor, TempoDocument
|
from unmix.schema.tempo import TempoAnchor, TempoDocument
|
||||||
from unmix.schema.vocals import VocalLine, VocalsDocument, VocalSyllable
|
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]
|
last_note = parsed.lines[1][0]
|
||||||
assert last_note.start_sec == pytest.approx(250.0, abs=0.15)
|
assert last_note.start_sec == pytest.approx(250.0, abs=0.15)
|
||||||
assert last_note.end_sec == pytest.approx(258.7, 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"
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user