Compare commits
3 Commits
feat/refer
...
3fdd639f47
| Author | SHA1 | Date | |
|---|---|---|---|
| 3fdd639f47 | |||
| 4024b74953 | |||
| 769910286f |
2
.gitignore
vendored
2
.gitignore
vendored
@ -42,7 +42,7 @@ testdata/
|
||||
*.ogg
|
||||
|
||||
# Local evaluation data and reports
|
||||
testset.local.toml
|
||||
testset*.local.toml
|
||||
eval_runs/
|
||||
eval_report.*
|
||||
.downloads/
|
||||
|
||||
@ -207,6 +207,9 @@ def analyze(
|
||||
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(
|
||||
"Noten exakt (oktav-korrigiert)", f"{eval_metrics['octave_equiv_pitch_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("WER (Word Error Rate)", f"{eval_metrics['wer']:.2f}")
|
||||
|
||||
@ -118,8 +118,8 @@ def run_evaluation(testset_config: Path, output_report_dir: Path | None = None)
|
||||
f"Konfiguration: `{testset_config.name}`",
|
||||
f"Getestete Songs: {len(results)}",
|
||||
"",
|
||||
"| Song | Status | Timing MAE (ms) | <= 50ms | <= 100ms | Noten (strikt) | Tonklasse | Oktav-Median | Dauer MAE | WER | Zeilen (P/R) | Laufzeit (s) |",
|
||||
"|---|---|---|---|---|---|---|---|---|---|---|---|",
|
||||
"| Song | Status | Timing MAE (ms) | <= 50ms | <= 100ms | Noten (strikt) | Noten (oktav-korr.) | Tonklasse | Oktav-Median | Dauer MAE | WER | Zeilen (P/R) | Laufzeit (s) |",
|
||||
"|---|---|---|---|---|---|---|---|---|---|---|---|---|",
|
||||
]
|
||||
|
||||
for r in results:
|
||||
@ -129,6 +129,7 @@ def run_evaluation(testset_config: Path, output_report_dir: Path | None = None)
|
||||
f"{r.get('fraction_within_50ms', 0.0) * 100:.1f}% | "
|
||||
f"{r['fraction_within_100ms'] * 100:.1f}% | "
|
||||
f"{r['strict_pitch_accuracy'] * 100:.1f}% | "
|
||||
f"{r.get('octave_equiv_pitch_accuracy', r['strict_pitch_accuracy']) * 100:.1f}% | "
|
||||
f"{r.get('pitch_class_accuracy', 0.0) * 100:.1f}% | "
|
||||
f"{r.get('median_octave_offset', 0.0):+.0f} | "
|
||||
f"{r.get('duration_mae_ms', 0.0):.1f} ms | "
|
||||
@ -138,7 +139,7 @@ def run_evaluation(testset_config: Path, output_report_dir: Path | None = None)
|
||||
)
|
||||
else:
|
||||
md_lines.append(
|
||||
f"| {r.get('name', 'Song')} | FEHLER ({r.get('error')}) | - | - | - | - | - | - | - | - | - | {r.get('elapsed_sec', 0.0):.1f}s |"
|
||||
f"| {r.get('name', 'Song')} | FEHLER ({r.get('error')}) | - | - | - | - | - | - | - | - | - | - | {r.get('elapsed_sec', 0.0):.1f}s |"
|
||||
)
|
||||
|
||||
report_md_path = report_dir / "eval_report.md"
|
||||
|
||||
@ -48,6 +48,101 @@ def hyphenate_word(word_text: str, dic: pyphen.Pyphen) -> list[str]:
|
||||
return res
|
||||
|
||||
|
||||
def split_into_vocal_lines(
|
||||
syllables: list[dict[str, Any]],
|
||||
gap_sec: float = 0.6,
|
||||
max_line_sec: float = 6.0,
|
||||
min_split_gap_sec: float = 0.1,
|
||||
) -> list[list[dict[str, Any]]]:
|
||||
"""Split a Whisper segment into singable lines.
|
||||
|
||||
Whisper segments follow sentence/breath logic and often span several sung lines. Lines are
|
||||
first cut at pauses between words longer than ``gap_sec``. Chunks that are still longer than
|
||||
``max_line_sec`` are cut recursively at their largest internal word gap (at the word
|
||||
boundary closest to the middle if no gap reaches ``min_split_gap_sec``).
|
||||
"""
|
||||
if not syllables:
|
||||
return []
|
||||
|
||||
chunks: list[list[dict[str, Any]]] = [[syllables[0]]]
|
||||
for prev, cur in zip(syllables, syllables[1:], strict=False):
|
||||
if prev.get("word_end", True) and cur["start"] - prev["end"] > gap_sec:
|
||||
chunks.append([])
|
||||
chunks[-1].append(cur)
|
||||
|
||||
def split_long(chunk: list[dict[str, Any]]) -> list[list[dict[str, Any]]]:
|
||||
if chunk[-1]["end"] - chunk[0]["start"] <= max_line_sec:
|
||||
return [chunk]
|
||||
candidates = [i for i in range(1, len(chunk)) if chunk[i - 1].get("word_end", True)]
|
||||
if not candidates:
|
||||
return [chunk]
|
||||
best = max(candidates, key=lambda i: chunk[i]["start"] - chunk[i - 1]["end"])
|
||||
if chunk[best]["start"] - chunk[best - 1]["end"] < min_split_gap_sec:
|
||||
mid = (chunk[0]["start"] + chunk[-1]["end"]) / 2.0
|
||||
best = min(candidates, key=lambda i: abs(chunk[i]["start"] - mid))
|
||||
return split_long(chunk[:best]) + split_long(chunk[best:])
|
||||
|
||||
result: list[list[dict[str, Any]]] = []
|
||||
for c in chunks:
|
||||
result.extend(split_long(c))
|
||||
return result
|
||||
|
||||
|
||||
def pop_trailing_orphan(
|
||||
chunks: list[list[dict[str, Any]]],
|
||||
max_orphan_sec: float = 1.0,
|
||||
) -> tuple[list[list[dict[str, Any]]], list[dict[str, Any]] | None]:
|
||||
"""Detach a mistimed single trailing word from a segment's lines.
|
||||
|
||||
Whisper sometimes assigns the first word of the *next* line to the end of a segment and gives
|
||||
it a start time inside (or just after) the preceding line, or emits it as a segment of its own.
|
||||
If the last chunk of a segment is a single short word, it is returned separately so it can be
|
||||
attached to the following segment.
|
||||
"""
|
||||
if not chunks:
|
||||
return chunks, None
|
||||
last = chunks[-1]
|
||||
is_single_word = sum(1 for s in last if s.get("word_end", True)) == 1
|
||||
if is_single_word and last[-1]["end"] - last[0]["start"] <= max_orphan_sec:
|
||||
return chunks[:-1], last
|
||||
return chunks, None
|
||||
|
||||
|
||||
def merge_leading_orphan(
|
||||
chunks: list[list[dict[str, Any]]],
|
||||
max_orphan_sec: float = 1.0,
|
||||
) -> list[list[dict[str, Any]]]:
|
||||
"""Merge a mistimed single leading word of a segment into the line that follows it."""
|
||||
if len(chunks) < 2:
|
||||
return chunks
|
||||
first = chunks[0]
|
||||
if sum(1 for s in first if s.get("word_end", True)) == 1 and first[-1]["end"] - first[0]["start"] <= max_orphan_sec:
|
||||
return prepend_orphan(first, chunks[1:])
|
||||
return chunks
|
||||
|
||||
|
||||
def prepend_orphan(
|
||||
orphan: list[dict[str, Any]],
|
||||
chunks: list[list[dict[str, Any]]],
|
||||
max_orphan_sec: float = 0.5,
|
||||
) -> list[list[dict[str, Any]]]:
|
||||
"""Merge ``orphan`` into the first chunk, re-timed into the start of that chunk's first syllable.
|
||||
|
||||
The line keeps its start time (Whisper's first word of the following line is usually close to
|
||||
the true line start); the orphan only takes the leading part of the first syllable.
|
||||
"""
|
||||
first = chunks[0][0]
|
||||
span = first["end"] - first["start"]
|
||||
total = min(max_orphan_sec, 0.2 * len(orphan), 0.5 * span)
|
||||
step = total / len(orphan)
|
||||
t0 = first["start"]
|
||||
for i, syl in enumerate(orphan):
|
||||
syl["start"] = round(t0 + i * step, 3)
|
||||
syl["end"] = round(t0 + (i + 1) * step, 3)
|
||||
first["start"] = round(t0 + total, 3)
|
||||
return [orphan + chunks[0], *chunks[1:]]
|
||||
|
||||
|
||||
def split_word_into_syllables_timed(
|
||||
word_text: str, start: float, end: float, dic: pyphen.Pyphen
|
||||
) -> list[dict[str, Any]]:
|
||||
@ -84,11 +179,78 @@ def split_word_into_syllables_timed(
|
||||
return timed
|
||||
|
||||
|
||||
def segments_to_lines(
|
||||
segments: list[dict[str, Any]],
|
||||
dic: pyphen.Pyphen,
|
||||
split_lines: bool = True,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Turn raw Whisper segments (with word timestamps) into timed, syllabified lines.
|
||||
|
||||
With ``split_lines=False`` every Whisper segment becomes one line (legacy behaviour).
|
||||
"""
|
||||
lines: list[dict[str, Any]] = []
|
||||
prev_seg: tuple[str, float] | None = None
|
||||
pending_orphan: list[dict[str, Any]] | None = None
|
||||
|
||||
for seg in segments:
|
||||
seg_syllables: list[dict[str, Any]] = []
|
||||
words = seg.get("words") or []
|
||||
if words:
|
||||
for idx, w in enumerate(words):
|
||||
# Attach space to word text if not the last word in segment
|
||||
w_text = w["word"].strip()
|
||||
if idx < len(words) - 1:
|
||||
w_text += " "
|
||||
seg_syllables.extend(split_word_into_syllables_timed(w_text, w["start"], w["end"], dic))
|
||||
else:
|
||||
# Segment without word timestamps fallback
|
||||
seg_syllables.extend(split_word_into_syllables_timed(seg["text"].strip(), seg["start"], seg["end"], dic))
|
||||
|
||||
if not seg_syllables:
|
||||
continue
|
||||
|
||||
clean_text = seg["text"].strip()
|
||||
seg_dur = max(0.01, seg["end"] - seg["start"])
|
||||
|
||||
# Skip Whisper hallucinated repetition at segment boundaries / audio fadeout
|
||||
if prev_seg is not None and prev_seg[0] == clean_text.lower():
|
||||
prev_dur = max(0.01, prev_seg[1])
|
||||
# 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
|
||||
prev_seg = (clean_text.lower(), seg_dur)
|
||||
|
||||
if not split_lines:
|
||||
lines.append({"start": seg["start"], "end": seg["end"], "text": clean_text, "syllables": seg_syllables})
|
||||
continue
|
||||
|
||||
seg_chunks = merge_leading_orphan(split_into_vocal_lines(seg_syllables))
|
||||
if pending_orphan is not None:
|
||||
seg_chunks = prepend_orphan(pending_orphan, seg_chunks)
|
||||
pending_orphan = None
|
||||
seg_chunks, pending_orphan = pop_trailing_orphan(seg_chunks)
|
||||
for chunk in seg_chunks:
|
||||
lines.append(_chunk_to_line(chunk))
|
||||
|
||||
if pending_orphan is not None:
|
||||
lines.append(_chunk_to_line(pending_orphan))
|
||||
return lines
|
||||
|
||||
|
||||
def _chunk_to_line(chunk: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
return {
|
||||
"start": chunk[0]["start"],
|
||||
"end": chunk[-1]["end"],
|
||||
"text": "".join(x["text"] for x in chunk).strip(),
|
||||
"syllables": chunk,
|
||||
}
|
||||
|
||||
|
||||
class LyricsStage(Stage):
|
||||
"""Stage 3 transcribes vocals into word-aligned syllables using Whisper and pyphen."""
|
||||
|
||||
name = "s3_lyrics"
|
||||
version = "1.0.0"
|
||||
version = "1.1.0"
|
||||
model_name = "whisper-large-v3"
|
||||
model_version = "1.0.0"
|
||||
dependencies = ["s2_stems"]
|
||||
@ -153,43 +315,21 @@ class LyricsStage(Stage):
|
||||
vad_parameters=vad_params,
|
||||
)
|
||||
|
||||
lines: list[dict[str, Any]] = []
|
||||
raw_segments = [
|
||||
{
|
||||
"start": seg.start,
|
||||
"end": seg.end,
|
||||
"text": seg.text,
|
||||
"words": [{"word": w.word, "start": w.start, "end": w.end} for w in (seg.words or [])],
|
||||
}
|
||||
for seg in segments
|
||||
]
|
||||
segments_file = ctx.cache_dir / "whisper_segments.json"
|
||||
segments_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(segments_file, "w", encoding="utf-8") as f:
|
||||
json.dump(raw_segments, f, indent=2, ensure_ascii=False)
|
||||
|
||||
for seg in segments:
|
||||
seg_syllables: list[dict[str, Any]] = []
|
||||
if seg.words:
|
||||
for idx, w in enumerate(seg.words):
|
||||
# Attach space to word text if not the last word in segment
|
||||
w_text = w.word.strip()
|
||||
if idx < len(seg.words) - 1:
|
||||
w_text += " "
|
||||
|
||||
w_sylls = split_word_into_syllables_timed(w_text, w.start, w.end, dic)
|
||||
seg_syllables.extend(w_sylls)
|
||||
else:
|
||||
# Segment without word timestamps fallback
|
||||
w_sylls = split_word_into_syllables_timed(seg.text.strip(), seg.start, seg.end, dic)
|
||||
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": clean_text,
|
||||
"syllables": seg_syllables,
|
||||
}
|
||||
)
|
||||
lines = segments_to_lines(raw_segments, dic, split_lines=True)
|
||||
|
||||
output_data = {
|
||||
"language": lang,
|
||||
|
||||
@ -37,3 +37,57 @@ def test_split_word_into_syllables_timed():
|
||||
# Syllables should be "Hel" and "lo "
|
||||
assert timed[0]["text"] == "Hel"
|
||||
assert timed[1]["text"] == "lo "
|
||||
|
||||
|
||||
def test_split_into_vocal_lines_by_gap_and_length():
|
||||
from unmix.pipeline.s3_lyrics import split_into_vocal_lines
|
||||
|
||||
def syl(text, start, end, word_end=True):
|
||||
return {"text": text, "start": start, "end": end, "word_end": word_end}
|
||||
|
||||
# Pause of 1.0 s between words -> two lines
|
||||
sylls = [syl("a ", 0.0, 0.5), syl("b ", 0.5, 1.0), syl("c ", 2.0, 2.5)]
|
||||
assert [len(c) for c in split_into_vocal_lines(sylls)] == [2, 1]
|
||||
|
||||
# No pause but > max_line_sec -> split at word boundary, never inside a word
|
||||
long_line = [syl("x", 0.0, 2.0, word_end=False), syl("y ", 2.0, 4.0), syl("z ", 4.0, 6.0), syl("w ", 6.0, 8.0)]
|
||||
chunks = split_into_vocal_lines(long_line)
|
||||
assert len(chunks) >= 2
|
||||
assert chunks[0][-1]["word_end"] is True
|
||||
assert sum(len(c) for c in chunks) == 4
|
||||
|
||||
assert split_into_vocal_lines([]) == []
|
||||
|
||||
|
||||
def test_orphan_trailing_word_moves_to_next_segment():
|
||||
from unmix.pipeline.s3_lyrics import pop_trailing_orphan, prepend_orphan
|
||||
|
||||
def syl(text, start, end, word_end=True):
|
||||
return {"text": text, "start": start, "end": end, "word_end": word_end}
|
||||
|
||||
chunks = [[syl("any ", 34.7, 36.1)], [syl("If ", 37.0, 37.8)]]
|
||||
rest, orphan = pop_trailing_orphan(chunks)
|
||||
assert len(rest) == 1 and orphan is not None
|
||||
|
||||
nxt = prepend_orphan(orphan, [[syl("I ", 40.9, 41.1), syl("lay ", 41.1, 41.4)]])
|
||||
assert [s["text"] for s in nxt[0]] == ["If ", "I ", "lay "]
|
||||
assert nxt[0][0]["start"] == 40.9
|
||||
assert nxt[0][1]["start"] >= nxt[0][0]["end"]
|
||||
|
||||
# Long single word (> 1 s) stays a line of its own
|
||||
chunks2 = [[syl("a ", 1.0, 2.0)], [syl("b ", 5.0, 7.5)]]
|
||||
assert pop_trailing_orphan(chunks2) == (chunks2, None)
|
||||
|
||||
|
||||
def test_merge_leading_orphan():
|
||||
from unmix.pipeline.s3_lyrics import merge_leading_orphan
|
||||
|
||||
def syl(text, start, end, word_end=True):
|
||||
return {"text": text, "start": start, "end": end, "word_end": word_end}
|
||||
|
||||
chunks = [[syl("If ", 37.0, 37.8)], [syl("I ", 40.9, 41.1), syl("lay ", 41.1, 41.4)]]
|
||||
merged = merge_leading_orphan(chunks)
|
||||
assert len(merged) == 1
|
||||
assert [s["text"] for s in merged[0]] == ["If ", "I ", "lay "]
|
||||
assert merged[0][0]["start"] == 40.9
|
||||
assert len(merge_leading_orphan([[syl("a ", 0.0, 0.5)]])) == 1
|
||||
|
||||
Reference in New Issue
Block a user