Compare commits
3 Commits
3fdd639f47
...
bcae76279b
| Author | SHA1 | Date | |
|---|---|---|---|
| bcae76279b | |||
| 861f6a29f2 | |||
| 904ce6253f |
@ -57,6 +57,17 @@ 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"),
|
||||
ultrastar: Path | None = typer.Option(
|
||||
None,
|
||||
"--ultrastar",
|
||||
help="UltraStar song.txt: its notes and timings become the result (same as --reference)",
|
||||
),
|
||||
lyrics: Path | None = typer.Option(
|
||||
None,
|
||||
"--lyrics",
|
||||
help="Known lyrics (plain text, one sung line per line, or an UltraStar .txt): align them to the vocals "
|
||||
"instead of transcribing with Whisper (languages: en, de)",
|
||||
),
|
||||
keep_ai_vocals: bool = typer.Option(
|
||||
False,
|
||||
"--keep-ai-vocals",
|
||||
@ -88,6 +99,27 @@ def analyze(
|
||||
console.print(f"[red][ERROR][/red] Input file not found: {source_path}")
|
||||
raise typer.Exit(code=1)
|
||||
|
||||
if ultrastar is not None:
|
||||
if reference is not None and reference.resolve() != ultrastar.resolve():
|
||||
console.print("[red][ERROR][/red] --ultrastar und --reference nur einzeln angeben.")
|
||||
raise typer.Exit(code=1)
|
||||
reference = ultrastar
|
||||
if lyrics is not None and reference is not None:
|
||||
console.print("[red][ERROR][/red] --lyrics und --ultrastar schließen sich aus: genau einen Modus wählen.")
|
||||
raise typer.Exit(code=1)
|
||||
if lyrics is not None and not lyrics.exists():
|
||||
console.print(f"[red][ERROR][/red] Lyrics file not found: {lyrics}")
|
||||
raise typer.Exit(code=1)
|
||||
if lyrics is not None:
|
||||
from unmix.pipeline.align import is_ultrastar_file
|
||||
|
||||
if is_ultrastar_file(lyrics):
|
||||
console.print(
|
||||
"[red][ERROR][/red] Das ist eine UltraStar-Datei. Dafür --ultrastar nutzen "
|
||||
"(Noten und Zeiten werden übernommen). --lyrics ist für reinen Text gedacht."
|
||||
)
|
||||
raise typer.Exit(code=1)
|
||||
|
||||
ctx = PipelineContext(
|
||||
source_file=source_path,
|
||||
output_dir=output_dir,
|
||||
@ -96,9 +128,22 @@ def analyze(
|
||||
quality=quality,
|
||||
force=force,
|
||||
target_stage=stage,
|
||||
lyrics_file=lyrics,
|
||||
)
|
||||
from unmix.pipeline.source_modes import (
|
||||
invalidate_pitch_cache,
|
||||
mode_label,
|
||||
previous_vocals_source,
|
||||
)
|
||||
|
||||
if reference is None and previous_vocals_source(ctx.meta_file) == "reference_ultrastar":
|
||||
# vocals.json still holds the ground truth of an earlier --ultrastar run: recompute pitch
|
||||
invalidate_pitch_cache(ctx.cache_dir)
|
||||
runner = get_default_pipeline()
|
||||
meta = runner.run(ctx)
|
||||
if reference is None:
|
||||
meta.vocals_source = mode_label(lyrics is not None)
|
||||
ctx.save_meta(meta)
|
||||
|
||||
# Persist title/artist overrides if provided
|
||||
updated_meta = False
|
||||
@ -134,22 +179,14 @@ def analyze(
|
||||
else:
|
||||
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
|
||||
from unmix.pipeline.source_modes import invalidate_pitch_cache, prepare_ai_vocals
|
||||
|
||||
ref_song = parse_ultrastar(ref_path)
|
||||
|
||||
# 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))
|
||||
|
||||
ai_vocals = prepare_ai_vocals(output_dir, ctx.cache_dir, meta.vocals_source)
|
||||
if ai_vocals is not None:
|
||||
# Generate detailed note-by-note training difference
|
||||
training_diff = generate_training_diff(ai_vocals, ref_song)
|
||||
diff_path = output_dir / "training_diff.json"
|
||||
@ -165,12 +202,13 @@ def analyze(
|
||||
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))
|
||||
invalidate_pitch_cache(ctx.cache_dir)
|
||||
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"
|
||||
meta.vocals_source = "whisper"
|
||||
|
||||
ctx.save_meta(meta)
|
||||
|
||||
|
||||
@ -76,12 +76,17 @@ def run_evaluation(testset_config: Path, output_report_dir: Path | None = None)
|
||||
)
|
||||
continue
|
||||
|
||||
# lyrics = "reference": align the reference's text and line breaks (not its timings) instead of Whisper
|
||||
lyrics_entry = song_entry.get("lyrics")
|
||||
lyrics_file = ref_path if lyrics_entry == "reference" else (Path(lyrics_entry) if lyrics_entry else None)
|
||||
|
||||
song_out_dir = report_dir / "eval_runs" / name
|
||||
ctx = PipelineContext(
|
||||
source_file=audio_path,
|
||||
output_dir=song_out_dir,
|
||||
lang=lang,
|
||||
target_stage="s4_pitch",
|
||||
lyrics_file=lyrics_file,
|
||||
)
|
||||
|
||||
t0 = time.perf_counter()
|
||||
|
||||
@ -295,9 +295,16 @@ def parse_ultrastar(file_path: Path) -> UltraStarSong:
|
||||
continue
|
||||
|
||||
# Note line: : 10 4 2 text
|
||||
match = re.match(r"^([:*FR])\s+(-?\d+)\s+(\d+)\s+(-?\d+)\s*(.*)$", line)
|
||||
# The lyric starts after exactly one separator space; further leading spaces mark a word start
|
||||
# (leading-space convention) and are normalised to a trailing space on the previous note below.
|
||||
match = re.match(r"^([:*FR])\s+(-?\d+)\s+(\d+)\s+(-?\d+)(?: (.*))?$", line)
|
||||
if match:
|
||||
ntype, s_beat, dur, pitch, text = match.groups()
|
||||
text = text or ""
|
||||
if text.startswith(" "):
|
||||
text = text.lstrip(" ")
|
||||
if current_line and not current_line[-1].text.endswith(" "):
|
||||
current_line[-1].text += " "
|
||||
note = UltraStarNote(
|
||||
note_type=ntype,
|
||||
start_beat=int(s_beat),
|
||||
|
||||
199
src/unmix/pipeline/align.py
Normal file
199
src/unmix/pipeline/align.py
Normal file
@ -0,0 +1,199 @@
|
||||
"""Text-guided word alignment: place given lyrics on the vocals stem with CTC forced alignment.
|
||||
|
||||
Used by stage 3 when ``--lyrics`` is given instead of transcribing with Whisper. The lyrics file is either
|
||||
plain text (one sung line per line) or an UltraStar ``.txt`` (its line structure and text are used, its timings
|
||||
are ignored).
|
||||
"""
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import soundfile as sf
|
||||
|
||||
# wav2vec2 CTC models with a character vocabulary, already used elsewhere via the torch hub cache.
|
||||
ALIGN_BUNDLES = {
|
||||
"en": "WAV2VEC2_ASR_BASE_960H",
|
||||
"de": "VOXPOPULI_ASR_BASE_10K_DE",
|
||||
}
|
||||
STRIDE = 320 # samples per wav2vec2 frame at 16 kHz
|
||||
SAMPLE_RATE = 16000
|
||||
FRAME_SEC = STRIDE / SAMPLE_RATE
|
||||
|
||||
_SECTION_MARKER = re.compile(r"^\s*[\[(].*[\])]\s*$")
|
||||
|
||||
|
||||
def supported_languages() -> list[str]:
|
||||
return sorted(ALIGN_BUNDLES)
|
||||
|
||||
|
||||
def read_lyrics_lines(path: Path) -> list[list[str]]:
|
||||
"""Read lyrics as a list of lines, each a list of display words (original case and punctuation)."""
|
||||
text = Path(path).read_text(encoding="utf-8", errors="replace")
|
||||
if is_ultrastar_file(Path(path)):
|
||||
return _lines_from_ultrastar(Path(path))
|
||||
lines: list[list[str]] = []
|
||||
for raw in text.splitlines():
|
||||
line = raw.strip()
|
||||
if not line or _SECTION_MARKER.match(line):
|
||||
continue
|
||||
words = line.split()
|
||||
if words:
|
||||
lines.append(words)
|
||||
return lines
|
||||
|
||||
|
||||
def is_ultrastar_file(path: Path) -> bool:
|
||||
text = Path(path).read_text(encoding="utf-8", errors="replace")
|
||||
head = text.lstrip("")[:2000]
|
||||
return bool(re.search(r"^#(TITLE|ARTIST|BPM):", head, flags=re.MULTILINE)) and bool(
|
||||
re.search(r"^[:*FR] +-?\d+ +\d+ +-?\d+", text, flags=re.MULTILINE)
|
||||
)
|
||||
|
||||
|
||||
def _lines_from_ultrastar(path: Path) -> list[list[str]]:
|
||||
from unmix.export.ultrastar import parse_ultrastar
|
||||
|
||||
song = parse_ultrastar(path)
|
||||
lines: list[list[str]] = []
|
||||
for line in song.lines:
|
||||
words: list[str] = []
|
||||
cur = ""
|
||||
for note in line:
|
||||
cur += note.text.replace("~", "")
|
||||
if note.text.endswith(" ") and cur.strip():
|
||||
words.append(cur.strip())
|
||||
cur = ""
|
||||
if cur.strip():
|
||||
words.append(cur.strip())
|
||||
if words:
|
||||
lines.append(words)
|
||||
return lines
|
||||
|
||||
|
||||
def clean_word(word: str, labels: tuple[str, ...] | list[str], lang: str) -> str:
|
||||
"""Reduce a display word to the character set of the alignment model."""
|
||||
allowed = set(labels) - {"-", "|"}
|
||||
w = word.strip().replace("’", "'").replace("`", "'").replace("´", "'")
|
||||
w = w.upper() if any(c.isupper() for c in allowed) else w.lower()
|
||||
return "".join(c for c in w if c in allowed)
|
||||
|
||||
|
||||
def compute_emissions(wav_path: Path, model: Any, bundle: Any, window_sec: float = 30.0, ctx_sec: float = 2.0) -> Any:
|
||||
"""Frame-wise log-probabilities for the whole file, computed in overlapping windows."""
|
||||
import torch
|
||||
import torchaudio
|
||||
|
||||
data, sr = sf.read(str(wav_path), dtype="float32")
|
||||
if data.ndim > 1:
|
||||
data = data.mean(axis=-1)
|
||||
wav = torch.from_numpy(data)
|
||||
if sr != bundle.sample_rate:
|
||||
wav = torchaudio.functional.resample(wav, sr, bundle.sample_rate)
|
||||
n = wav.shape[0]
|
||||
win = int(window_sec * SAMPLE_RATE) // STRIDE * STRIDE
|
||||
ctx = int(ctx_sec * SAMPLE_RATE) // STRIDE * STRIDE
|
||||
out = torch.zeros(n // STRIDE + 1, len(bundle.get_labels()))
|
||||
normalize = bool(getattr(bundle, "_normalize_waveform", False))
|
||||
with torch.inference_mode():
|
||||
for s0 in range(0, n, win):
|
||||
a = max(0, s0 - ctx) # always a multiple of STRIDE, so frame indices stay absolute
|
||||
b = min(n, s0 + win + ctx)
|
||||
chunk = wav[a:b]
|
||||
if normalize:
|
||||
chunk = torch.nn.functional.layer_norm(chunk, chunk.shape)
|
||||
logits, _ = model(chunk.unsqueeze(0))
|
||||
logp = torch.log_softmax(logits, dim=-1)[0]
|
||||
f0 = a // STRIDE
|
||||
lo = s0 // STRIDE - f0
|
||||
hi = min(logp.shape[0], min(n, s0 + win) // STRIDE - f0)
|
||||
out[f0 + lo : f0 + hi] = logp[lo:hi]
|
||||
return out
|
||||
|
||||
|
||||
def align_words(
|
||||
emissions: Any, clean_lines: list[list[str]], labels: tuple[str, ...] | list[str]
|
||||
) -> dict[tuple[int, int], tuple[float, float]]:
|
||||
"""CTC forced alignment. Returns {(line_idx, word_idx): (start_sec, end_sec)} for every non-empty word."""
|
||||
import torch
|
||||
import torchaudio.functional as F
|
||||
|
||||
idx = {c: i for i, c in enumerate(labels)}
|
||||
tokens: list[int] = []
|
||||
owner: list[tuple[int, int]] = []
|
||||
for li, words in enumerate(clean_lines):
|
||||
for wi, w in enumerate(words):
|
||||
for c in w:
|
||||
tokens.append(idx[c])
|
||||
owner.append((li, wi))
|
||||
if not tokens:
|
||||
return {}
|
||||
if emissions.shape[0] < len(tokens):
|
||||
raise ValueError(
|
||||
f"Lyrics too long for the audio: {len(tokens)} characters but only {emissions.shape[0]} audio frames."
|
||||
)
|
||||
targets = torch.tensor([tokens], dtype=torch.int32)
|
||||
aligned, scores = F.forced_align(emissions.unsqueeze(0), targets, blank=0)
|
||||
spans = F.merge_tokens(aligned[0], scores[0].exp())
|
||||
if len(spans) != len(tokens):
|
||||
raise ValueError("Forced alignment returned an unexpected number of token spans.")
|
||||
result: dict[tuple[int, int], tuple[float, float]] = {}
|
||||
for span, key in zip(spans, owner, strict=True):
|
||||
s, e = span.start * FRAME_SEC, span.end * FRAME_SEC
|
||||
cur = result.get(key)
|
||||
result[key] = (s, e) if cur is None else (min(cur[0], s), max(cur[1], e))
|
||||
return result
|
||||
|
||||
|
||||
def load_aligner(lang: str) -> tuple[Any, Any]:
|
||||
"""Return (bundle, model) for a language or raise ValueError for unsupported languages."""
|
||||
import torchaudio
|
||||
|
||||
key = (lang or "").lower()[:2]
|
||||
if key not in ALIGN_BUNDLES:
|
||||
raise ValueError(
|
||||
f"--lyrics alignment supports languages {supported_languages()}, got '{lang}'. "
|
||||
"Run without --lyrics to transcribe with Whisper."
|
||||
)
|
||||
bundle = getattr(torchaudio.pipelines, ALIGN_BUNDLES[key])
|
||||
return bundle, bundle.get_model().eval()
|
||||
|
||||
|
||||
def lyrics_to_timed_lines(
|
||||
lyrics: list[list[str]],
|
||||
vocals_wav: Path,
|
||||
lang: str,
|
||||
syllabify: Any,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Align ``lyrics`` to the vocals stem and return stage-3 style lines.
|
||||
|
||||
``syllabify(word_text, start, end)`` splits a timed word into syllable dicts.
|
||||
"""
|
||||
bundle, model = load_aligner(lang)
|
||||
labels = bundle.get_labels()
|
||||
key = lang.lower()[:2]
|
||||
clean = [[clean_word(w, labels, key) for w in line] for line in lyrics]
|
||||
emissions = compute_emissions(vocals_wav, model, bundle)
|
||||
timing = align_words(emissions, clean, labels)
|
||||
|
||||
lines: list[dict[str, Any]] = []
|
||||
for li, words in enumerate(lyrics):
|
||||
# Words without alignable characters (e.g. "-", digits) get no time and are skipped.
|
||||
timed = [(wi, w) for wi, w in enumerate(words) if (li, wi) in timing]
|
||||
if not timed:
|
||||
continue
|
||||
syllables: list[dict[str, Any]] = []
|
||||
for pos, (wi, w) in enumerate(timed):
|
||||
start, end = timing[(li, wi)]
|
||||
text = w + (" " if pos < len(timed) - 1 else "")
|
||||
syllables.extend(syllabify(text, start, max(end, start + 0.02)))
|
||||
if syllables:
|
||||
lines.append(
|
||||
{
|
||||
"start": syllables[0]["start"],
|
||||
"end": syllables[-1]["end"],
|
||||
"text": " ".join(w for _, w in timed),
|
||||
"syllables": syllables,
|
||||
}
|
||||
)
|
||||
return lines
|
||||
@ -35,8 +35,10 @@ class PipelineContext:
|
||||
quality: str = "best",
|
||||
force: bool = False,
|
||||
target_stage: str | None = None,
|
||||
lyrics_file: Path | None = None,
|
||||
):
|
||||
self.source_file = source_file.resolve()
|
||||
self.lyrics_file = lyrics_file.resolve() if lyrics_file else None
|
||||
self.output_dir = output_dir.resolve()
|
||||
self.lang = lang
|
||||
self.stems = stems
|
||||
|
||||
@ -259,7 +259,10 @@ class LyricsStage(Stage):
|
||||
self.model_name = model_name
|
||||
|
||||
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
|
||||
return [ctx.stems_dir / "vocals.wav"]
|
||||
inputs = [ctx.stems_dir / "vocals.wav"]
|
||||
if ctx.lyrics_file is not None:
|
||||
inputs.append(ctx.lyrics_file) # content hash invalidates the cache when the lyrics change
|
||||
return inputs
|
||||
|
||||
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
|
||||
return [ctx.cache_dir / "lyrics_raw.json"]
|
||||
@ -268,8 +271,30 @@ class LyricsStage(Stage):
|
||||
return {
|
||||
"lang": ctx.lang or "de",
|
||||
"model_size": "base" if ctx.quality == "fast" else "large-v3",
|
||||
"mode": "aligned" if ctx.lyrics_file is not None else "whisper",
|
||||
}
|
||||
|
||||
def _run_aligned(self, ctx: PipelineContext, vocals_wav: Path, lang: str, dic: pyphen.Pyphen) -> None:
|
||||
"""Place the given lyrics on the vocals stem (CTC forced alignment) instead of transcribing."""
|
||||
from unmix.pipeline.align import lyrics_to_timed_lines, read_lyrics_lines
|
||||
|
||||
assert ctx.lyrics_file is not None
|
||||
lyrics = read_lyrics_lines(ctx.lyrics_file)
|
||||
if not lyrics:
|
||||
raise ValueError(f"No lyrics found in {ctx.lyrics_file}")
|
||||
self.model_name = "wav2vec2-ctc-forced-alignment"
|
||||
lines = lyrics_to_timed_lines(
|
||||
lyrics,
|
||||
vocals_wav,
|
||||
lang,
|
||||
lambda text, start, end: split_word_into_syllables_timed(text, start, end, dic),
|
||||
)
|
||||
output_data = {"language": lang, "detected_language": lang, "lines": lines}
|
||||
output_file = self.get_outputs(ctx)[0]
|
||||
output_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(output_file, "w", encoding="utf-8") as f:
|
||||
json.dump(output_data, f, indent=2, ensure_ascii=False)
|
||||
|
||||
def run(self, ctx: PipelineContext) -> None:
|
||||
from faster_whisper import WhisperModel
|
||||
|
||||
@ -289,6 +314,10 @@ class LyricsStage(Stage):
|
||||
except Exception:
|
||||
dic = pyphen.Pyphen(lang="en_US")
|
||||
|
||||
if ctx.lyrics_file is not None:
|
||||
self._run_aligned(ctx, vocals_wav, lang, dic)
|
||||
return
|
||||
|
||||
# Determine compute device
|
||||
device_str = config.get_device(self.name)
|
||||
compute_type = "float16" if device_str.startswith("cuda") else "int8"
|
||||
|
||||
@ -14,6 +14,53 @@ from unmix.pipeline.runner import PipelineContext, Stage
|
||||
from unmix.schema.base import GeneratedBy
|
||||
from unmix.schema.vocals import VocalLine, VocalsDocument, VocalSyllable
|
||||
|
||||
# Line ends: follow strictly voiced frames (CREPE periodicity) after the last word.
|
||||
# Short dropouts are always bridged; longer ones (up to the max) only if voicing resumes for a while,
|
||||
# i.e. a held note with a dropout rather than a breath or consonant.
|
||||
LINE_END_VOICING_THRESHOLD = 0.7
|
||||
LINE_END_MAX_GAP_SEC = 0.1
|
||||
LINE_END_RESUME_MAX_GAP_SEC = 0.3
|
||||
LINE_END_RESUME_MIN_RUN_SEC = 0.3
|
||||
|
||||
|
||||
def voiced_run_end(
|
||||
is_voiced: np.ndarray,
|
||||
t0: float,
|
||||
hop_sec: float,
|
||||
max_gap_sec: float,
|
||||
cap_t: float,
|
||||
resume_max_gap_sec: float = 0.0,
|
||||
resume_min_run_sec: float = 0.0,
|
||||
) -> float:
|
||||
"""End time of the voiced run starting at ``t0``.
|
||||
|
||||
Unvoiced gaps up to ``max_gap_sec`` are always bridged. Gaps up to ``resume_max_gap_sec`` are
|
||||
bridged if the voiced run that follows lasts at least ``resume_min_run_sec``.
|
||||
"""
|
||||
n = len(is_voiced)
|
||||
k = int(t0 / hop_sec) if hop_sec > 0 else 0
|
||||
last = k
|
||||
while k < n and k * hop_sec < cap_t:
|
||||
if is_voiced[k]:
|
||||
last = k
|
||||
k += 1
|
||||
continue
|
||||
j = k
|
||||
while j < n and not is_voiced[j]:
|
||||
j += 1
|
||||
if j >= n or j * hop_sec >= cap_t:
|
||||
break
|
||||
gap = (j - k) * hop_sec
|
||||
r = j
|
||||
while r < n and is_voiced[r]:
|
||||
r += 1
|
||||
run = (r - j) * hop_sec
|
||||
if gap <= max_gap_sec or (gap <= resume_max_gap_sec and run >= resume_min_run_sec):
|
||||
k = j
|
||||
else:
|
||||
break
|
||||
return (last + 1) * hop_sec
|
||||
|
||||
|
||||
def hz_to_midi(hz: np.ndarray) -> np.ndarray:
|
||||
"""Convert frequency in Hz to fractional MIDI note numbers."""
|
||||
@ -159,7 +206,7 @@ class PitchStage(Stage):
|
||||
"""Stage 4 extracts vocal fundamental frequency and assigns median pitch per syllable."""
|
||||
|
||||
name = "s4_pitch"
|
||||
version = "1.1.0"
|
||||
version = "1.3.0"
|
||||
model_name = "torchcrepe-full"
|
||||
model_version = "1.0.0"
|
||||
dependencies = ["s3_lyrics"]
|
||||
@ -274,10 +321,18 @@ class PitchStage(Stage):
|
||||
line_counter = 0
|
||||
syl_counter = 0
|
||||
|
||||
for line_dict in lyrics_data.get("lines", []):
|
||||
all_lines = lyrics_data.get("lines", [])
|
||||
is_voiced_strict = (periodicity >= LINE_END_VOICING_THRESHOLD) & (pitch_hz > 50)
|
||||
|
||||
for line_pos, line_dict in enumerate(all_lines):
|
||||
sylls = line_dict.get("syllables", [])
|
||||
if not sylls:
|
||||
continue
|
||||
next_line_start = None
|
||||
for later in all_lines[line_pos + 1 :]:
|
||||
if later.get("syllables"):
|
||||
next_line_start = float(later["syllables"][0]["start"])
|
||||
break
|
||||
|
||||
line_counter += 1
|
||||
line_syllables_raw = []
|
||||
@ -322,6 +377,20 @@ class PitchStage(Stage):
|
||||
if extended_end > real_end:
|
||||
real_end = min(next_start_limit, extended_end)
|
||||
|
||||
if idx == len(sylls) - 1:
|
||||
# Line end: end of the strictly voiced run after the last word (holds sustained vowels)
|
||||
cap_t = next_line_start - 0.05 if next_line_start is not None else s_end + 3.0
|
||||
strict_end = voiced_run_end(
|
||||
is_voiced_strict,
|
||||
s_start,
|
||||
hop_sec,
|
||||
LINE_END_MAX_GAP_SEC,
|
||||
cap_t,
|
||||
resume_max_gap_sec=LINE_END_RESUME_MAX_GAP_SEC,
|
||||
resume_min_run_sec=LINE_END_RESUME_MIN_RUN_SEC,
|
||||
)
|
||||
real_end = max(snapped_start + 0.08, min(strict_end, cap_t))
|
||||
|
||||
segs = segment_melisma(
|
||||
snapped_start,
|
||||
real_end,
|
||||
|
||||
56
src/unmix/pipeline/source_modes.py
Normal file
56
src/unmix/pipeline/source_modes.py
Normal file
@ -0,0 +1,56 @@
|
||||
"""Input modes of a song package.
|
||||
|
||||
Mode 1 (audio only): Whisper transcribes the lyrics. vocals_source = "whisper"
|
||||
Mode 2 (UltraStar): notes and timings of the .txt are the result. vocals_source = "reference_ultrastar"
|
||||
Mode 3 (lyrics): given text is aligned to the audio. vocals_source = "lyrics_aligned"
|
||||
|
||||
Mode 2 overwrites vocals.json with the ground truth. Without the helpers below, a later run would take that
|
||||
ground truth for the AI prediction and keep a stale pitch cache.
|
||||
"""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from unmix.schema.vocals import VocalsDocument
|
||||
|
||||
PITCH_CACHE = "s4_pitch.json"
|
||||
AI_BACKUP = "vocals_ai.json"
|
||||
GROUND_TRUTH = "reference_ultrastar"
|
||||
|
||||
|
||||
def mode_label(lyrics_given: bool) -> str:
|
||||
return "lyrics_aligned" if lyrics_given else "whisper"
|
||||
|
||||
|
||||
def previous_vocals_source(meta_file: Path) -> str | None:
|
||||
if not meta_file.exists():
|
||||
return None
|
||||
try:
|
||||
return json.loads(meta_file.read_text(encoding="utf-8")).get("vocals_source")
|
||||
except (OSError, ValueError, AttributeError):
|
||||
return None
|
||||
|
||||
|
||||
def prepare_ai_vocals(output_dir: Path, cache_dir: Path, vocals_source: str) -> VocalsDocument | None:
|
||||
"""Return the AI prediction for evaluation, never a ground truth written by an earlier run.
|
||||
|
||||
While vocals.json holds the AI result, a copy is kept in the cache. Once it holds the ground truth,
|
||||
only that copy is valid. Returns None if no AI result is available.
|
||||
"""
|
||||
backup = cache_dir / AI_BACKUP
|
||||
if vocals_source == GROUND_TRUTH:
|
||||
if not backup.exists():
|
||||
return None
|
||||
return VocalsDocument.model_validate(json.loads(backup.read_text(encoding="utf-8")))
|
||||
vocals_json = output_dir / "vocals.json"
|
||||
if not vocals_json.exists():
|
||||
return None
|
||||
doc = VocalsDocument.model_validate(json.loads(vocals_json.read_text(encoding="utf-8")))
|
||||
cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
backup.write_text(doc.model_dump_json(indent=2), encoding="utf-8")
|
||||
return doc
|
||||
|
||||
|
||||
def invalidate_pitch_cache(cache_dir: Path) -> None:
|
||||
"""Drop the cached pitch stage so the next run recomputes vocals.json instead of reusing a ground truth."""
|
||||
(cache_dir / PITCH_CACHE).unlink(missing_ok=True)
|
||||
@ -90,7 +90,7 @@ 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"
|
||||
vocals_source: Literal["whisper", "lyrics_aligned", "reference_ultrastar", "ai"] = "ai"
|
||||
training_diff: dict[str, Any] | None = None
|
||||
|
||||
|
||||
|
||||
100
tests/test_align.py
Normal file
100
tests/test_align.py
Normal file
@ -0,0 +1,100 @@
|
||||
"""Unit tests for text-guided lyrics alignment (CTC forced alignment, lyrics file parsing)."""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from unmix.pipeline import align
|
||||
from unmix.pipeline.align import align_words, clean_word, lyrics_to_timed_lines, read_lyrics_lines
|
||||
|
||||
LABELS = ("-", "|", "A", "B", "C", "D", "E", "'")
|
||||
|
||||
|
||||
def test_read_plain_lyrics_skips_blank_lines_and_section_markers(tmp_path):
|
||||
f = tmp_path / "lyrics.txt"
|
||||
f.write_text("[Verse 1]\nWe'll do it all\n\n Everything on our own \n(Chorus)\nIf I lay here\n", encoding="utf-8")
|
||||
assert read_lyrics_lines(f) == [
|
||||
["We'll", "do", "it", "all"],
|
||||
["Everything", "on", "our", "own"],
|
||||
["If", "I", "lay", "here"],
|
||||
]
|
||||
|
||||
|
||||
def test_read_lyrics_from_ultrastar_uses_text_and_line_structure(tmp_path):
|
||||
f = tmp_path / "song.txt"
|
||||
f.write_text(
|
||||
"#TITLE:T\n#ARTIST:A\n#BPM:120\n#GAP:0\n"
|
||||
": 0 4 4 We \n: 5 4 4 do \n: 10 4 4 it\n- 20\n: 24 4 4 Ev\n: 28 4 4 ~ery \n: 32 4 4 day\nE\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
assert read_lyrics_lines(f) == [["We", "do", "it"], ["Every", "day"]]
|
||||
|
||||
|
||||
def test_clean_word_maps_to_model_alphabet():
|
||||
assert clean_word("Bad'e,", LABELS, "en") == "BAD'E"
|
||||
assert clean_word("Ad’e", LABELS, "en") == "AD'E" # typographic apostrophe
|
||||
assert clean_word("1234!", LABELS, "en") == "" # nothing alignable
|
||||
|
||||
|
||||
def _emissions(frames: list[str]) -> torch.Tensor:
|
||||
"""Log-probs that put (almost) all mass on the given label per frame; '-' is the CTC blank."""
|
||||
idx = {c: i for i, c in enumerate(LABELS)}
|
||||
em = torch.full((len(frames), len(LABELS)), -20.0)
|
||||
for t, c in enumerate(frames):
|
||||
em[t, idx[c]] = 0.0
|
||||
return em
|
||||
|
||||
|
||||
def test_align_words_returns_monotonic_word_times():
|
||||
# frame: 0 1 2 3 4 5 6 7 8
|
||||
frames = ["-", "A", "B", "-", "-", "C", "D", "D", "-"]
|
||||
em = _emissions(frames)
|
||||
res = align_words(em, [["AB"], ["CD"]], LABELS)
|
||||
(s1, e1), (s2, e2) = res[(0, 0)], res[(1, 0)]
|
||||
assert s1 == pytest.approx(1 * align.FRAME_SEC)
|
||||
assert e1 <= s2
|
||||
assert s2 == pytest.approx(5 * align.FRAME_SEC)
|
||||
assert e2 > s2
|
||||
|
||||
|
||||
def test_align_words_rejects_too_long_text():
|
||||
em = _emissions(["A", "B"])
|
||||
with pytest.raises(ValueError, match="too long"):
|
||||
align_words(em, [["ABABAB"]], LABELS)
|
||||
|
||||
|
||||
def test_lyrics_to_timed_lines_builds_syllables_and_skips_unalignable_words(monkeypatch, tmp_path):
|
||||
class FakeBundle:
|
||||
sample_rate = 16000
|
||||
|
||||
def get_labels(self):
|
||||
return LABELS
|
||||
|
||||
frames = ["-", "A", "B", "-", "-", "C", "D", "-", "-", "-"]
|
||||
monkeypatch.setattr(align, "load_aligner", lambda lang: (FakeBundle(), object()))
|
||||
monkeypatch.setattr(align, "compute_emissions", lambda wav, model, bundle: _emissions(frames))
|
||||
|
||||
def syllabify(text, start, end):
|
||||
return [{"text": text, "start": start, "end": end, "word_end": text.endswith(" ")}]
|
||||
|
||||
lines = lyrics_to_timed_lines([["ab", "...", "cd"]], tmp_path / "v.wav", "en", syllabify)
|
||||
assert len(lines) == 1
|
||||
texts = [s["text"] for s in lines[0]["syllables"]]
|
||||
assert texts == ["ab ", "cd"] # "..." has no alignable characters and is skipped
|
||||
assert lines[0]["text"] == "ab cd"
|
||||
assert lines[0]["start"] < lines[0]["end"]
|
||||
|
||||
|
||||
def test_unsupported_language_gives_clear_error():
|
||||
with pytest.raises(ValueError, match="supports languages"):
|
||||
align.load_aligner("fr")
|
||||
|
||||
|
||||
def test_is_ultrastar_file_detects_ultrastar_but_not_plain_text(tmp_path):
|
||||
from unmix.pipeline.align import is_ultrastar_file
|
||||
|
||||
us = tmp_path / "us.txt"
|
||||
us.write_text("#TITLE:T\n#BPM:120\n#GAP:0\n: 0 4 4 We \nE\n", encoding="utf-8")
|
||||
plain = tmp_path / "plain.txt"
|
||||
plain.write_text("We do it all\nEverything on our own\n", encoding="utf-8")
|
||||
assert is_ultrastar_file(us)
|
||||
assert not is_ultrastar_file(plain)
|
||||
@ -39,3 +39,37 @@ def test_no_correction_for_legitimate_contour():
|
||||
]
|
||||
corrected = correct_octave_errors(syllables)
|
||||
assert corrected[1]["midi"] == 64.0
|
||||
|
||||
|
||||
def test_voiced_run_end_bridges_short_gaps():
|
||||
import numpy as np
|
||||
|
||||
from unmix.pipeline.s4_pitch import voiced_run_end
|
||||
|
||||
hop = 0.01
|
||||
v = np.zeros(300, dtype=bool)
|
||||
v[100:150] = True # 1.00-1.50 s
|
||||
v[155:200] = True # gap of 0.05 s, then voiced until 2.00 s
|
||||
v[260:290] = True # separate run after a 0.6 s gap
|
||||
|
||||
assert voiced_run_end(v, 1.0, hop, max_gap_sec=0.1, cap_t=5.0) == pytest.approx(2.0)
|
||||
assert voiced_run_end(v, 1.0, hop, max_gap_sec=0.0, cap_t=5.0) == pytest.approx(1.5)
|
||||
# cap stops the run
|
||||
assert voiced_run_end(v, 1.0, hop, max_gap_sec=0.1, cap_t=1.3) <= 1.31
|
||||
|
||||
|
||||
def test_voiced_run_end_bridges_longer_gap_only_if_voicing_resumes():
|
||||
import numpy as np
|
||||
|
||||
from unmix.pipeline.s4_pitch import voiced_run_end
|
||||
|
||||
hop = 0.01
|
||||
v = np.zeros(400, dtype=bool)
|
||||
v[100:150] = True # 1.00-1.50 s
|
||||
v[170:230] = True # gap 0.20 s, then a long run (0.60 s) until 2.30 s
|
||||
v[250:260] = True # gap 0.20 s, then a short run (0.10 s)
|
||||
|
||||
kwargs = {"resume_max_gap_sec": 0.3, "resume_min_run_sec": 0.3}
|
||||
assert voiced_run_end(v, 1.0, hop, 0.1, 5.0, **kwargs) == pytest.approx(2.3)
|
||||
# without the resume rule the 0.2 s gap ends the run
|
||||
assert voiced_run_end(v, 1.0, hop, 0.1, 5.0) == pytest.approx(1.5)
|
||||
|
||||
76
tests/test_source_modes.py
Normal file
76
tests/test_source_modes.py
Normal file
@ -0,0 +1,76 @@
|
||||
"""Tests for the input modes: AI backup vs. ground truth in vocals.json, pitch cache invalidation."""
|
||||
|
||||
import json
|
||||
|
||||
from unmix.pipeline.source_modes import (
|
||||
invalidate_pitch_cache,
|
||||
mode_label,
|
||||
prepare_ai_vocals,
|
||||
previous_vocals_source,
|
||||
)
|
||||
from unmix.schema.vocals import VocalLine, VocalsDocument, VocalSyllable
|
||||
|
||||
|
||||
def _doc(text: str, start: float = 1.0) -> VocalsDocument:
|
||||
syl = VocalSyllable(text=text, start=start, end=start + 0.5, midi=60.0, word_end=True)
|
||||
return VocalsDocument(lines=[VocalLine(start=start, end=start + 0.5, syllables=[syl])])
|
||||
|
||||
|
||||
def _text(doc: VocalsDocument) -> str:
|
||||
return doc.lines[0].syllables[0].text
|
||||
|
||||
|
||||
def test_first_run_returns_ai_and_backs_it_up(tmp_path):
|
||||
out = tmp_path / "out"
|
||||
out.mkdir()
|
||||
(out / "vocals.json").write_text(_doc("ai").model_dump_json(), encoding="utf-8")
|
||||
|
||||
ai = prepare_ai_vocals(out, out / ".cache", "whisper")
|
||||
|
||||
assert _text(ai) == "ai"
|
||||
assert (out / ".cache" / "vocals_ai.json").exists()
|
||||
|
||||
|
||||
def test_run_after_ground_truth_write_uses_backup_not_reference(tmp_path):
|
||||
out = tmp_path / "out"
|
||||
cache = out / ".cache"
|
||||
out.mkdir()
|
||||
(out / "vocals.json").write_text(_doc("ai").model_dump_json(), encoding="utf-8")
|
||||
prepare_ai_vocals(out, cache, "whisper") # first --ultrastar run backs up the AI result
|
||||
(out / "vocals.json").write_text(_doc("ground-truth").model_dump_json(), encoding="utf-8")
|
||||
|
||||
# second run in the same folder: vocals.json now holds the reference
|
||||
ai = prepare_ai_vocals(out, cache, "reference_ultrastar")
|
||||
|
||||
assert _text(ai) == "ai"
|
||||
|
||||
|
||||
def test_reference_source_without_backup_gives_no_ai(tmp_path):
|
||||
out = tmp_path / "out"
|
||||
out.mkdir()
|
||||
(out / "vocals.json").write_text(_doc("ground-truth").model_dump_json(), encoding="utf-8")
|
||||
|
||||
assert prepare_ai_vocals(out, out / ".cache", "reference_ultrastar") is None
|
||||
|
||||
|
||||
def test_invalidate_pitch_cache_removes_only_pitch_stage(tmp_path):
|
||||
(tmp_path / "s4_pitch.json").write_text("{}", encoding="utf-8")
|
||||
(tmp_path / "s3_lyrics.json").write_text("{}", encoding="utf-8")
|
||||
|
||||
invalidate_pitch_cache(tmp_path)
|
||||
invalidate_pitch_cache(tmp_path) # no error when already gone
|
||||
|
||||
assert not (tmp_path / "s4_pitch.json").exists()
|
||||
assert (tmp_path / "s3_lyrics.json").exists()
|
||||
|
||||
|
||||
def test_previous_vocals_source_and_mode_label(tmp_path):
|
||||
meta = tmp_path / "meta.json"
|
||||
assert previous_vocals_source(meta) is None
|
||||
meta.write_text(json.dumps({"vocals_source": "reference_ultrastar"}), encoding="utf-8")
|
||||
assert previous_vocals_source(meta) == "reference_ultrastar"
|
||||
meta.write_text("not json", encoding="utf-8")
|
||||
assert previous_vocals_source(meta) is None
|
||||
|
||||
assert mode_label(False) == "whisper"
|
||||
assert mode_label(True) == "lyrics_aligned"
|
||||
@ -196,3 +196,23 @@ E
|
||||
assert len(loaded.lines) == 2
|
||||
assert loaded.lines[0].syllables[2].type == "golden"
|
||||
|
||||
|
||||
|
||||
def test_parse_ultrastar_leading_space_word_convention(tmp_path):
|
||||
from unmix.eval.metrics import extract_text_from_reference
|
||||
from unmix.export.ultrastar import parse_ultrastar
|
||||
|
||||
f = tmp_path / "lead.txt"
|
||||
f.write_text(
|
||||
"#TITLE:T\n#ARTIST:A\n#BPM:120\n#GAP:0\n"
|
||||
": 0 4 4 She\n: 8 6 9 came\n: 18 2 9 to\n: 22 4 9 ~r\n- 30\n: 32 4 2 me\nE\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
song = parse_ultrastar(f)
|
||||
assert extract_text_from_reference(song) == "She came to~r me"
|
||||
assert song.lines[0][0].text == "She "
|
||||
assert song.lines[0][1].text == "came "
|
||||
# trailing-space convention is unchanged
|
||||
g = tmp_path / "trail.txt"
|
||||
g.write_text("#BPM:120\n#GAP:0\n: 0 4 4 We \n: 5 4 4 do \nE\n", encoding="utf-8")
|
||||
assert extract_text_from_reference(parse_ultrastar(g)) == "We do"
|
||||
|
||||
Reference in New Issue
Block a user