feat: version song analysis contract and preserve lyric lines
This commit is contained in:
@ -28,21 +28,27 @@ Die obigen PyTorch-Builds laufen auf der CPU. Für GPU-Betrieb ist ein zur Grafi
|
||||
Aufruf (mit dieser Umgebung):
|
||||
|
||||
```bash
|
||||
tools/song_analysis/.venv/bin/python tools/analyze song.mp3 --out songs/song/ --lyrics lyrics.txt
|
||||
tools/song_analysis/.venv/bin/python tools/analyze song.mp3 --out songs/song/ --lyrics lyrics.txt --title "Songtitel"
|
||||
tools/song_analysis/.venv/bin/python tools/analyze song.mp3 --out songs/song/ --force
|
||||
```
|
||||
|
||||
Optionen: `--language en` für die WhisperX-Sprache, `--whisper-model large-v3`, `--separator-bin /pfad/audio-separator`, `--model-dir /pfad/modelle`, `--roformer-model DATEI`. Wenn der BS-RoFormer bereits unter `~/AI/models/maestro/ckpts/roformer/` liegt, kann dieser Ordner mit `--model-dir` verwendet werden. Das Demucs-Modell heißt `htdemucs_ft.yaml`.
|
||||
Optionen: `--title "Songtitel"`, `--language en` für die WhisperX-Sprache, `--whisper-model large-v3`, `--separator-bin /pfad/audio-separator`, `--model-dir /pfad/modelle`, `--roformer-model DATEI`. Wenn der BS-RoFormer bereits unter `~/AI/models/maestro/ckpts/roformer/` liegt, kann dieser Ordner mit `--model-dir` verwendet werden. Das Demucs-Modell heißt `htdemucs_ft.yaml`.
|
||||
|
||||
## Ablauf und Dateien
|
||||
|
||||
1. ffmpeg erzeugt `_cache/original.wav` mit 44,1 kHz und Stereo. Dessen Beginn ist für alle Zeiten Sekunde 0.
|
||||
1. ffmpeg erzeugt `_cache/original.wav` mit 44,1 kHz und Stereo. Der Beginn des decodierten Quell-Audiostücks bleibt Sekunde 0; ffmpeg fügt keinen Pipeline-Versatz hinzu. `meta.source_offset_s` ist deshalb 0.0. Ein bereits im Quellmedium vorhandener Encoder-Vorlauf wird nicht herausgerechnet. `apad` verlängert Stems nur am Ende.
|
||||
2. `audio-separator` trennt Vocals und Instrumental mit BS-RoFormer; `htdemucs_ft` trennt das Instrumental in Drums, Bass und Other. Die vier Stems liegen unter `stems/`. `_cache/instrumental.wav` ist ein Zwischenprodukt für Wiederaufnahmen.
|
||||
3. madmom Downbeat Tracking berechnet `beats.json` und BPM. `vamp-simple-host` mit Chordino berechnet `chords.json`. Chordino liefert keine Kalibrierung der Akkordsicherheit; `conf` ist deshalb `null`.
|
||||
3. madmom Downbeat Tracking berechnet `beats.json` und BPM. Der Decoder sucht derzeit nur 3/4- und 4/4-Takte; 5/4 und andere Metren benötigen eine Erweiterung. `vamp-simple-host` mit Chordino berechnet `chords.json`. Dessen `simplechord`-Ausgabe liefert keine kalibrierte Akkordsicherheit; `conf` ist deshalb `null`. Ein Abstand zum zweitbesten Akkord wäre ohne Kalibrierung keine verlässliche Wahrscheinlichkeit. Akkordgrenzen bleiben auf den von Chordino erkannten Zeiten; die App darf sie zur Anzeige optional auf Beats einrasten, ohne die Rohdaten zu ändern. `N` bedeutet „kein erkannter Akkord“. Spannen unter 0,5 s sollte ein Verbraucher als mögliche Ausreißer markieren oder für eine vereinfachte Anzeige ausblenden; in der Datei bleiben sie erhalten.
|
||||
4. torchcrepe (PyTorch-Implementierung von CREPE) liefert `pitch.json` mit 10-ms-Raster. Frequenzen unter 0,5 Konfidenz werden als 0 Hz (unvoiced) geschrieben; die tatsächliche Konfidenz bleibt in `conf`. Basic Pitch verarbeitet denselben Vocal-Stem separat für `melody.mid` und den Other-Stem für `guitar.mid`.
|
||||
5. WhisperX richtet den gelieferten Text wortweise aus. Ohne `--lyrics` transkribiert WhisperX selbst, und `lyrics.json` trägt `verified: false`. Wörter ohne Zeiten werden ausgelassen. Die Zeilen entstehen aus Pausen über 0,6 s, Taktgrenzen und etwa 40 Zeichen.
|
||||
5. Mit `--lyrics` transkribiert WhisperX zunächst zeitgestempelte Phrasen. Jede nichtleere Eingabezeile wird anschließend in einem passenden Phrasenfenster einzeln ausgerichtet. `source_line` (1-basiert) und die letzte Abschnittsmarke wie `[Verse]` in `section` bleiben erhalten. Fehlt ein sicher passendes Fenster oder gelingen keine Wortzeiten, hat die Zeile `start: null`, `end: null`, leere `words` und `alignment_conf: null`; ein Mensch muss sie nachbearbeiten. `alignment_conf` ist der Mittelwert vorhandener Wort-Scores, multipliziert mit dem Anteil ausgerichteter Wörter. `verified: true` besagt nur, dass der Text vorgegeben wurde, nicht dass die Zeitzuordnung geprüft ist. Ohne `--lyrics` entsteht ein **ungeprüfter Entwurf** (`verified: false`); Wortlaut und Wortzeiten müssen kontrolliert werden. Diese automatischen Zeilen entstehen aus Pausen über 0,6 s, Taktgrenzen und etwa 40 Zeichen. Wörter ohne Zeiten werden ausgelassen. Ein echter Lauf mit `--lyrics` über einen ganzen Song wurde bisher nicht gegen Referenzwerte geprüft.
|
||||
6. madmom schätzt die Tonart für `meta.json`; bei fehlender Erkennung ist `key` null. Alle JSON-Dateien werden gegen `schemas/song-analysis-v1/` geprüft.
|
||||
|
||||
Jeder Schritt prüft seine Ausgabedateien. Ein normaler erneuter Lauf lässt vorhandene Dateien unverändert, einschließlich manueller Korrekturen. `--force` berechnet sie neu. Fehlgeschlagene Schritte stehen unter `meta.json.errors`; die CLI beendet sich dann mit Status 1. Unabhängige Schritte laufen weiter. `meta.json` wird für den aktuellen Fehlerstatus aktualisiert; seine manuell gesetzten Werte für `title`, `bpm`, `key` und `duration` bleiben ohne `--force` erhalten.
|
||||
Jeder Schritt prüft seine Ausgabedateien. Ein normaler erneuter Lauf lässt vorhandene Dateien unverändert, einschließlich manueller Korrekturen. `--force` berechnet sie neu. Fehlgeschlagene Schritte stehen unter `meta.json.errors`; die CLI beendet sich dann mit Status 1. Unabhängige Schritte laufen weiter. `meta.json` wird für den aktuellen Fehlerstatus aktualisiert. Ein manuell gesetztes BPM muss `bpm_source: "manual"` tragen; sonst wird es aus `beats.json` neu berechnet. `--title` setzt einen expliziten Titel. Manuell gesetzte Titel, Tonarten und Dauern bleiben ohne `--force` erhalten.
|
||||
|
||||
Die JSON-Strukturen haben `schema_version: 1` in `meta.json`. Alle Zeiten sind Sekunden als Fließkommazahlen. Für das Tool sind `conf: null` und fehlende Dateien mögliche Zustände. MIDI enthält normale Noten-Events; insbesondere die Gitarrentranskription ist keine Tabulatur. Die genannten Qualitätszahlen hängen stark vom Material ab und sind keine vom Werkzeug garantierten Fehlerschranken.
|
||||
Neue Ausgaben haben `schema_version: 2` in `meta.json`; der Rust-Lader akzeptiert auch v1. Die zugehörigen Schemas liegen unter `schemas/song-analysis-v2/`. Alle Zeiten sind Sekunden als Fließkommazahlen. Für das Tool sind `conf: null` und fehlende Dateien mögliche Zustände. MIDI enthält normale Noten-Events; insbesondere die Gitarrentranskription ist keine Tabulatur. Die genannten Qualitätszahlen hängen stark vom Material ab und sind keine vom Werkzeug garantierten Fehlerschranken.
|
||||
|
||||
## Tests und Ressourcen
|
||||
|
||||
Die leichten Vertragstests benötigen nur Python 3.11 und `jsonschema`: `PYTHONPATH=tools python -m unittest tools.test_song_analysis`. Die Gitea-CI führt sie bei Änderungen am Werkzeug oder Schema aus. Mit vollständig installierter Audio-Umgebung kann `PYTHONPATH=tools tools/song_analysis/.venv/bin/python -m unittest tools.test_song_analysis_smoke` einen erzeugten 1-Sekunden-Ton mit CREPE prüfen.
|
||||
|
||||
Beobachtung am 216-Sekunden-Beispiel auf Oberon (AMD Radeon 890M, isolierte Umgebung mit PyTorch `2.5.1+cpu`, also **GPU: nein**): BS-RoFormer etwa 11:55 min, Demucs `htdemucs_ft` etwa 6:19 min, CREPE mit 512-Frame-Batches etwa 2:32 min. Bei CREPE wurden maximal 1,99 GB Prozess-RSS gemessen; vor der Batch-Begrenzung erreichte der Gesamtprozess rund 22 GB und erzeugte Speicherdruck. Für Beats, Chordino, Basic Pitch und WhisperX liegen keine getrennt gemessenen Laufzeiten oder RSS-Spitzen vor. Diese Zahlen sind Messwerte eines Laufs, keine Zusicherung für andere Rechner oder Songs.
|
||||
|
||||
@ -2,12 +2,11 @@
|
||||
|
||||
import json
|
||||
import os
|
||||
import statistics
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from .core import parse_chordino
|
||||
from .core import bpm_from_beats, make_aligned_line, match_lyric_windows, parse_chordino, parse_lyrics
|
||||
|
||||
|
||||
def command(args: list[str], *, capture: bool = False, env: dict[str, str] | None = None) -> str:
|
||||
@ -70,8 +69,7 @@ def detect_beats(audio: Path) -> tuple[dict, float | None]:
|
||||
positions = DBNDownBeatTrackingProcessor(beats_per_bar=[3, 4], fps=100)(activations)
|
||||
beats = [float(row[0]) for row in positions]
|
||||
downbeats = [float(row[0]) for row in positions if int(row[1]) == 1]
|
||||
gaps = [b - a for a, b in zip(beats, beats[1:]) if 0.2 <= b - a <= 2]
|
||||
bpm = round(60 / statistics.median(gaps), 2) if gaps else None
|
||||
bpm = bpm_from_beats(beats)
|
||||
return {"beats": beats, "downbeats": downbeats}, bpm
|
||||
|
||||
|
||||
@ -138,8 +136,7 @@ def transcribe_midi(audio: Path, target: Path) -> None:
|
||||
staged.replace(target)
|
||||
|
||||
|
||||
def lyrics_words(audio: Path, lyrics: Path | None, language: str,
|
||||
model_name: str) -> tuple[list[dict], bool]:
|
||||
def lyrics_words(audio: Path, language: str, model_name: str) -> list[dict]:
|
||||
import torch
|
||||
import whisperx
|
||||
|
||||
@ -148,20 +145,11 @@ def lyrics_words(audio: Path, lyrics: Path | None, language: str,
|
||||
last_error = None
|
||||
for device in devices:
|
||||
try:
|
||||
if lyrics:
|
||||
text = " ".join(line.strip() for line in lyrics.read_text(encoding="utf-8").splitlines()
|
||||
if line.strip() and not line.lstrip().startswith(("#", "[")))
|
||||
if not text:
|
||||
raise ValueError("Liedtext enthält keine Wörter")
|
||||
segments = [{"start": 0.0, "end": len(audio_data) / 16000, "text": text}]
|
||||
verified = True
|
||||
else:
|
||||
model = whisperx.load_model(model_name, device, compute_type="float16" if device == "cuda" else "int8")
|
||||
result = model.transcribe(audio_data, batch_size=8 if device == "cuda" else 2,
|
||||
language=language)
|
||||
segments = result["segments"]
|
||||
verified = False
|
||||
del model
|
||||
model = whisperx.load_model(model_name, device, compute_type="float16" if device == "cuda" else "int8")
|
||||
result = model.transcribe(audio_data, batch_size=8 if device == "cuda" else 2,
|
||||
language=language)
|
||||
segments = result["segments"]
|
||||
del model
|
||||
aligner, metadata = whisperx.load_align_model(language_code=language, device=device)
|
||||
aligned = whisperx.align(segments, aligner, metadata, audio_data, device,
|
||||
return_char_alignments=False)
|
||||
@ -174,7 +162,7 @@ def lyrics_words(audio: Path, lyrics: Path | None, language: str,
|
||||
"conf": float(item["score"]) if item.get("score") is not None else None})
|
||||
if not words:
|
||||
raise RuntimeError("WhisperX lieferte keine ausgerichteten Wörter")
|
||||
return words, verified
|
||||
return words
|
||||
except (RuntimeError, MemoryError) as exc:
|
||||
last_error = exc
|
||||
if device == "cuda":
|
||||
@ -182,3 +170,40 @@ def lyrics_words(audio: Path, lyrics: Path | None, language: str,
|
||||
continue
|
||||
raise
|
||||
raise RuntimeError(f"WhisperX fehlgeschlagen: {last_error}")
|
||||
|
||||
|
||||
def align_lyric_lines(audio: Path, lyrics: Path, language: str, model_name: str) -> list[dict]:
|
||||
"""Use timed draft phrases to keep each supplied line inside its own audio window."""
|
||||
import torch
|
||||
import whisperx
|
||||
|
||||
source_lines = parse_lyrics(lyrics.read_text(encoding="utf-8"))
|
||||
if not source_lines:
|
||||
raise ValueError("Liedtext enthält keine Wörter")
|
||||
audio_data = whisperx.load_audio(str(audio))
|
||||
devices = ["cuda", "cpu"] if torch.cuda.is_available() else ["cpu"]
|
||||
for device in devices:
|
||||
try:
|
||||
model = whisperx.load_model(model_name, device,
|
||||
compute_type="float16" if device == "cuda" else "int8")
|
||||
draft = model.transcribe(audio_data, batch_size=8 if device == "cuda" else 2,
|
||||
language=language)
|
||||
del model
|
||||
windows = match_lyric_windows(source_lines, draft["segments"])
|
||||
aligner, metadata = whisperx.load_align_model(language_code=language, device=device)
|
||||
result = []
|
||||
for source_line, window in zip(source_lines, windows):
|
||||
if window is None:
|
||||
result.append(make_aligned_line(source_line, []))
|
||||
continue
|
||||
start, end = window
|
||||
segment = [{"start": start, "end": end, "text": source_line["text"]}]
|
||||
aligned = whisperx.align(segment, aligner, metadata, audio_data, device,
|
||||
return_char_alignments=False)
|
||||
result.append(make_aligned_line(source_line, aligned.get("word_segments", [])))
|
||||
return result
|
||||
except (RuntimeError, MemoryError):
|
||||
if device == "cpu":
|
||||
raise
|
||||
torch.cuda.empty_cache()
|
||||
raise RuntimeError("WhisperX konnte keine Lyrics ausrichten")
|
||||
|
||||
@ -6,7 +6,7 @@ import sys
|
||||
from pathlib import Path
|
||||
|
||||
from . import backends
|
||||
from .core import group_words, run_step, validate_json, validate_outputs, write_json
|
||||
from .core import bpm_from_beats, group_words, run_step, validate_json, validate_outputs, write_json
|
||||
|
||||
|
||||
def resolve_separator_bin(value: str) -> str:
|
||||
@ -18,6 +18,7 @@ def resolve_separator_bin(value: str) -> str:
|
||||
|
||||
|
||||
def analyze(source: Path, out: Path, lyrics: Path | None = None, *, force: bool = False,
|
||||
title: str | None = None,
|
||||
separator_bin: str = "audio-separator", model_dir: Path | None = None,
|
||||
roformer_model: str = "model_bs_roformer_ep_317_sdr_12.9755.ckpt",
|
||||
language: str = "en", whisper_model: str = "large-v3") -> dict:
|
||||
@ -91,14 +92,18 @@ def analyze(source: Path, out: Path, lyrics: Path | None = None, *, force: bool
|
||||
lambda: backends.transcribe_midi(vocals, out / "melody.mid"), errors, force)
|
||||
lyrics_path = out / "lyrics.json"
|
||||
def lyrics_step():
|
||||
words, verified = backends.lyrics_words(vocals, lyrics, language, whisper_model)
|
||||
downbeats = []
|
||||
if (out / "beats.json").exists():
|
||||
try:
|
||||
downbeats = json.loads((out / "beats.json").read_text(encoding="utf-8"))["downbeats"]
|
||||
except (OSError, ValueError, KeyError):
|
||||
pass
|
||||
value = {"verified": verified, "lines": group_words(words, downbeats)}
|
||||
if lyrics:
|
||||
value = {"verified": True,
|
||||
"lines": backends.align_lyric_lines(vocals, lyrics, language, whisper_model)}
|
||||
else:
|
||||
words = backends.lyrics_words(vocals, language, whisper_model)
|
||||
downbeats = []
|
||||
if (out / "beats.json").exists():
|
||||
try:
|
||||
downbeats = json.loads((out / "beats.json").read_text(encoding="utf-8"))["downbeats"]
|
||||
except (OSError, ValueError, KeyError):
|
||||
pass
|
||||
value = {"verified": False, "lines": group_words(words, downbeats)}
|
||||
validate_json("lyrics", value)
|
||||
write_json(lyrics_path, value)
|
||||
run_step("lyrics", [lyrics_path], lyrics_step, errors, force)
|
||||
@ -108,18 +113,20 @@ def analyze(source: Path, out: Path, lyrics: Path | None = None, *, force: bool
|
||||
lambda: backends.transcribe_midi(stems / "other.wav", out / "guitar.mid"),
|
||||
errors, force)
|
||||
|
||||
bpm = previous.get("bpm")
|
||||
bpm = None
|
||||
if (out / "beats.json").exists():
|
||||
try:
|
||||
beat_times = json.loads((out / "beats.json").read_text(encoding="utf-8"))["beats"]
|
||||
gaps = [b - a for a, b in zip(beat_times, beat_times[1:]) if 0.2 <= b - a <= 2]
|
||||
if gaps:
|
||||
import statistics
|
||||
bpm = round(60 / statistics.median(gaps), 2)
|
||||
bpm = bpm_from_beats(beat_times)
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
pass
|
||||
if not force and previous.get("bpm") is not None:
|
||||
bpm_source = previous.get("bpm_source", "automatic")
|
||||
if previous.get("schema_version") == 1 and previous.get("bpm") is not None:
|
||||
bpm_source = "manual" if previous["bpm"] != bpm else "automatic"
|
||||
if not force and bpm_source == "manual" and previous.get("bpm") is not None:
|
||||
bpm = previous["bpm"]
|
||||
elif force:
|
||||
bpm_source = "automatic"
|
||||
validate_outputs(out, errors)
|
||||
key = previous.get("key")
|
||||
if mix.exists() and (force or key is None):
|
||||
@ -127,10 +134,10 @@ def analyze(source: Path, out: Path, lyrics: Path | None = None, *, force: bool
|
||||
key = backends.detect_key(mix)
|
||||
except Exception as exc:
|
||||
errors["key"] = f"{type(exc).__name__}: {exc}"
|
||||
meta = {"title": previous.get("title", source.stem) if not force else source.stem,
|
||||
"bpm": bpm, "key": key,
|
||||
meta = {"title": title if title is not None else (previous.get("title", source.stem) if not force else source.stem),
|
||||
"bpm": bpm, "bpm_source": bpm_source, "key": key,
|
||||
"duration": previous.get("duration", duration) if not force and previous.get("duration", 0) > 0 else duration,
|
||||
"schema_version": 1, "errors": errors}
|
||||
"source_offset_s": 0.0, "schema_version": 2, "errors": errors}
|
||||
try:
|
||||
validate_json("meta", meta)
|
||||
except Exception as exc:
|
||||
@ -144,6 +151,7 @@ def main(argv: list[str] | None = None) -> int:
|
||||
parser.add_argument("audio", type=Path)
|
||||
parser.add_argument("--out", required=True, type=Path)
|
||||
parser.add_argument("--lyrics", type=Path)
|
||||
parser.add_argument("--title")
|
||||
parser.add_argument("--force", action="store_true")
|
||||
parser.add_argument("--separator-bin", default="audio-separator")
|
||||
parser.add_argument("--model-dir", type=Path)
|
||||
@ -152,7 +160,7 @@ def main(argv: list[str] | None = None) -> int:
|
||||
parser.add_argument("--whisper-model", default="large-v3")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
meta = analyze(args.audio, args.out, args.lyrics, force=args.force,
|
||||
meta = analyze(args.audio, args.out, args.lyrics, force=args.force, title=args.title,
|
||||
separator_bin=args.separator_bin, model_dir=args.model_dir,
|
||||
roformer_model=args.roformer_model, language=args.language,
|
||||
whisper_model=args.whisper_model)
|
||||
|
||||
@ -2,9 +2,16 @@
|
||||
|
||||
import json
|
||||
import re
|
||||
import statistics
|
||||
from difflib import SequenceMatcher
|
||||
from pathlib import Path
|
||||
|
||||
SCHEMA_DIR = Path(__file__).resolve().parents[2] / "schemas" / "song-analysis-v1"
|
||||
SCHEMA_DIR = Path(__file__).resolve().parents[2] / "schemas" / "song-analysis-v2"
|
||||
|
||||
|
||||
def bpm_from_beats(beats: list[float]) -> float | None:
|
||||
gaps = [b - a for a, b in zip(beats, beats[1:]) if 0.2 <= b - a <= 2]
|
||||
return round(60 / statistics.median(gaps), 2) if gaps else None
|
||||
|
||||
|
||||
def write_json(path: Path, value: object) -> None:
|
||||
@ -51,6 +58,66 @@ def group_words(words: list[dict], downbeats: list[float], max_chars: int = 40)
|
||||
return lines
|
||||
|
||||
|
||||
def parse_lyrics(text: str) -> list[dict]:
|
||||
"""Preserve sung line numbers and the most recent bracketed section label."""
|
||||
lines = []
|
||||
section = None
|
||||
for number, raw in enumerate(text.splitlines(), 1):
|
||||
stripped = raw.strip()
|
||||
if stripped.startswith("#") or not stripped:
|
||||
continue
|
||||
if stripped.startswith("[") and stripped.endswith("]"):
|
||||
section = stripped[1:-1].strip() or None
|
||||
continue
|
||||
lines.append({"text": stripped, "source_line": number, "section": section})
|
||||
return lines
|
||||
|
||||
|
||||
def match_lyric_windows(lines: list[dict], phrases: list[dict]) -> list[tuple[float, float] | None]:
|
||||
"""Match each input line to a later ASR phrase; leave uncertain lines unmatched."""
|
||||
windows = []
|
||||
cursor_phrase = 0
|
||||
cursor_word = 0
|
||||
for line in lines:
|
||||
target = re.findall(r"\w+", line["text"].casefold())
|
||||
best = (0.0, None)
|
||||
for index in range(cursor_phrase, len(phrases)):
|
||||
candidate = re.findall(r"\w+", phrases[index].get("text", "").casefold())
|
||||
for start in range(cursor_word if index == cursor_phrase else 0, len(candidate)):
|
||||
for length in range(max(1, len(target) - 2), len(target) + 3):
|
||||
end = min(len(candidate), start + length)
|
||||
score = SequenceMatcher(None, target, candidate[start:end]).ratio()
|
||||
if score > best[0]:
|
||||
best = (score, (index, start, end, len(candidate)))
|
||||
if best[0] >= 0.55 and best[1] is not None:
|
||||
index, start_word, end_word, count = best[1]
|
||||
phrase = phrases[index]
|
||||
start_time, end_time = float(phrase["start"]), float(phrase["end"])
|
||||
span = end_time - start_time
|
||||
windows.append((max(start_time, start_time + span * start_word / count - 0.3),
|
||||
min(end_time, start_time + span * end_word / count + 0.3)))
|
||||
cursor_phrase, cursor_word = index, end_word
|
||||
else:
|
||||
windows.append(None)
|
||||
return windows
|
||||
|
||||
|
||||
def make_aligned_line(source: dict, aligned: list[dict]) -> dict:
|
||||
words = [{"w": item["word"].strip(), "start": float(item["start"]),
|
||||
"end": float(item["end"]),
|
||||
"conf": float(item["score"]) if item.get("score") is not None else None}
|
||||
for item in aligned if item.get("word", "").strip()
|
||||
and item.get("start") is not None and item.get("end") is not None]
|
||||
scores = [word["conf"] for word in words if word["conf"] is not None]
|
||||
source_count = len(re.findall(r"\w+", source["text"]))
|
||||
coverage = min(1.0, len(words) / source_count) if source_count else 0.0
|
||||
return {"start": words[0]["start"] if words else None,
|
||||
"end": words[-1]["end"] if words else None,
|
||||
"source_line": source["source_line"], "section": source["section"],
|
||||
"alignment_conf": round(sum(scores) / len(scores) * coverage, 4) if scores else None,
|
||||
"words": words}
|
||||
|
||||
|
||||
_CHORD_EVENT = re.compile(r'^\s*([0-9]+(?:\.[0-9]+)?)\s*:\s*"?([^"\r\n]+?)"?\s*$')
|
||||
|
||||
|
||||
@ -88,8 +155,13 @@ def validate_json(kind: str, value: object) -> None:
|
||||
raise ValueError("beats: Zeiten sind nicht sortiert")
|
||||
if kind in ("chords", "lyrics"):
|
||||
spans = value if kind == "chords" else value["lines"]
|
||||
if any(item["end"] < item["start"] for item in spans):
|
||||
if any(item["end"] < item["start"] for item in spans
|
||||
if item["start"] is not None and item["end"] is not None):
|
||||
raise ValueError(f"{kind}: negativer Zeitbereich")
|
||||
if kind == "lyrics" and any((line["start"] is None) != (line["end"] is None)
|
||||
or (line["start"] is None and line["words"])
|
||||
for line in value["lines"]):
|
||||
raise ValueError("lyrics: nicht ausgerichtete Zeile braucht null-Zeiten und leere Wörter")
|
||||
|
||||
|
||||
def validate_outputs(out: Path, errors: dict[str, str]) -> None:
|
||||
|
||||
@ -10,7 +10,7 @@ transformers>=4.40,<5 # Version 5 deaktiviert PyTorch 2.5
|
||||
patchelf>=0.19.1 # Repariert bei Bedarf das GNU_STACK-Flag von CTranslate2 4.4
|
||||
scipy>=1.10
|
||||
soundfile>=0.12
|
||||
madmom-infer @ git+https://github.com/openmirlab/madmom-infer.git
|
||||
madmom-infer @ git+https://github.com/openmirlab/madmom-infer.git@bffead9be61857fd44b2e0d3a2510d9d94c8f2d2
|
||||
torchcrepe>=0.0.24
|
||||
basic-pitch>=0.4
|
||||
whisperx>=3.3
|
||||
|
||||
@ -5,9 +5,9 @@ import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from song_analysis.core import group_words, parse_chordino, run_step, validate_json
|
||||
from song_analysis.core import group_words, parse_chordino, parse_lyrics, match_lyric_windows, make_aligned_line, bpm_from_beats, run_step, validate_json
|
||||
from song_analysis.cli import analyze, resolve_separator_bin
|
||||
from song_analysis.backends import detect_beats, detect_pitch
|
||||
from song_analysis.backends import detect_beats
|
||||
|
||||
|
||||
class SongAnalysisTests(unittest.TestCase):
|
||||
@ -23,6 +23,37 @@ class SongAnalysisTests(unittest.TestCase):
|
||||
[["Hello", "there"], ["again"], ["friend"]])
|
||||
self.assertEqual(lines[0]["start"], 0.1)
|
||||
|
||||
def test_lyrics_preserve_source_lines_and_sections(self):
|
||||
lines = parse_lyrics("[Verse 1]\nHello there\n\n# comment\n[Chorus]\nSing along\n")
|
||||
self.assertEqual(lines, [
|
||||
{"text": "Hello there", "source_line": 2, "section": "Verse 1"},
|
||||
{"text": "Sing along", "source_line": 6, "section": "Chorus"},
|
||||
])
|
||||
|
||||
def test_lyrics_match_timed_phrases_without_inventing_missing_window(self):
|
||||
lines = parse_lyrics("[verse]\nHello there\nUnknown passage\nSing along")
|
||||
phrases = [{"start": 1.0, "end": 2.0, "text": "Hello there"},
|
||||
{"start": 9.0, "end": 10.0, "text": "Sing along"}]
|
||||
self.assertEqual(match_lyric_windows(lines, phrases), [(1.0, 2.0), None, (9.0, 10.0)])
|
||||
|
||||
def test_multiple_input_lines_can_match_one_long_phrase(self):
|
||||
lines = parse_lyrics("Hello there\nSing along")
|
||||
phrase = [{"start": 10.0, "end": 14.0, "text": "Hello there and sing along"}]
|
||||
windows = match_lyric_windows(lines, phrase)
|
||||
self.assertIsNotNone(windows[0])
|
||||
self.assertIsNotNone(windows[1])
|
||||
self.assertLess(windows[0][0], windows[1][0])
|
||||
|
||||
def test_lyric_line_quality_uses_available_word_scores(self):
|
||||
source = {"text": "Hello there", "source_line": 2, "section": "verse"}
|
||||
aligned = [{"word": "Hello", "start": 1.1, "end": 1.3, "score": 0.8},
|
||||
{"word": "there", "start": 1.4, "end": 1.6, "score": 0.6}]
|
||||
line = make_aligned_line(source, aligned)
|
||||
self.assertEqual(line["alignment_conf"], 0.7)
|
||||
self.assertEqual(line["source_line"], 2)
|
||||
self.assertEqual(line["start"], 1.1)
|
||||
self.assertEqual(make_aligned_line(source, [])["start"], None)
|
||||
|
||||
def test_chordino_events_end_at_next_event_or_duration(self):
|
||||
text = '0.000000: "C"\n1.250000: "Am"\n2.000000: "N"\n'
|
||||
self.assertEqual(parse_chordino(text, 3.0), [
|
||||
@ -62,23 +93,15 @@ class SongAnalysisTests(unittest.TestCase):
|
||||
with self.assertRaises(ValueError):
|
||||
validate_json("pitch", {"hop_ms": 10, "hz": [440, 441], "conf": [0.9]})
|
||||
|
||||
def test_pitch_inference_limits_batch_size(self):
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
import torch
|
||||
def test_lyric_line_cannot_have_one_missing_boundary(self):
|
||||
with self.assertRaises(ValueError):
|
||||
validate_json("lyrics", {"verified": True, "lines": [
|
||||
{"start": None, "end": 1.0, "words": []}
|
||||
]})
|
||||
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
audio = Path(d) / "vocals.wav"
|
||||
sf.write(audio, np.zeros(16000, dtype=np.float32), 16000)
|
||||
def predict(signal, sample_rate, **kwargs):
|
||||
self.assertEqual(sample_rate, 16000)
|
||||
self.assertLessEqual(kwargs["batch_size"], 512)
|
||||
frames = 1 + signal.shape[1] // kwargs["hop_length"]
|
||||
return torch.zeros((1, frames)), torch.ones((1, frames))
|
||||
with patch("torchcrepe.predict", side_effect=predict):
|
||||
result = detect_pitch(audio)
|
||||
self.assertEqual(len(result["hz"]), 101)
|
||||
self.assertEqual(len(result["conf"]), 101)
|
||||
def test_bpm_from_beats_uses_median_of_plausible_intervals(self):
|
||||
self.assertEqual(bpm_from_beats([0, 0.5, 1.0, 10.0]), 120.0)
|
||||
self.assertIsNone(bpm_from_beats([]))
|
||||
|
||||
def test_madmom_decoder_receives_its_100_hz_frame_rate(self):
|
||||
module = types.ModuleType("madmom_infer.features.downbeats")
|
||||
@ -125,12 +148,34 @@ class SongAnalysisTests(unittest.TestCase):
|
||||
analyze(source, out)
|
||||
meta_path = out / "meta.json"
|
||||
meta = json.loads(meta_path.read_text())
|
||||
meta.update(title="Mein Titel", bpm=97.0, key="G major", duration=2.9)
|
||||
meta.update(title="Mein Titel", bpm=97.0, bpm_source="manual", key="G major", duration=2.9)
|
||||
meta_path.write_text(json.dumps(meta))
|
||||
result = analyze(source, out)
|
||||
self.assertEqual((result["title"], result["bpm"], result["key"], result["duration"]),
|
||||
("Mein Titel", 97.0, "G major", 2.9))
|
||||
self.assertIn("separator fehlt", result["errors"]["vocals"])
|
||||
self.assertEqual(result["schema_version"], 2)
|
||||
self.assertEqual(result["source_offset_s"], 0.0)
|
||||
self.assertEqual(result["bpm_source"], "manual")
|
||||
|
||||
def test_automatic_bpm_refreshes_from_edited_beats(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
out = Path(d)
|
||||
source = out / "input.wav"
|
||||
source.write_bytes(b"audio")
|
||||
(out / "_cache").mkdir()
|
||||
(out / "_cache" / "original.wav").write_bytes(b"wav")
|
||||
(out / "beats.json").write_text(json.dumps({"beats": [0, 0.5, 1], "downbeats": [0]}))
|
||||
with patch("song_analysis.backends.separate", side_effect=RuntimeError("skip")), \
|
||||
patch("song_analysis.backends.duration_of", return_value=2.0), \
|
||||
patch("song_analysis.backends.detect_key", return_value="C major"):
|
||||
first = analyze(source, out, title="Custom title")
|
||||
(out / "beats.json").write_text(json.dumps({"beats": [0, 1, 2], "downbeats": [0]}))
|
||||
second = analyze(source, out)
|
||||
self.assertEqual(first["bpm"], 120.0)
|
||||
self.assertEqual(second["bpm"], 60.0)
|
||||
self.assertEqual(second["bpm_source"], "automatic")
|
||||
self.assertEqual(second["title"], "Custom title")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
42
tools/test_song_analysis_smoke.py
Normal file
42
tools/test_song_analysis_smoke.py
Normal file
@ -0,0 +1,42 @@
|
||||
"""Optional audio backend smoke test; run only in the full analysis environment."""
|
||||
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
import torch
|
||||
|
||||
from song_analysis.backends import detect_pitch
|
||||
|
||||
|
||||
class AudioSmokeTests(unittest.TestCase):
|
||||
def test_one_second_tone_has_a_bounded_pitch_batch(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
audio = Path(d) / "tone.wav"
|
||||
t = np.arange(16000, dtype=np.float32) / 16000
|
||||
sf.write(audio, 0.2 * np.sin(2 * np.pi * 440 * t), 16000)
|
||||
def predict(signal, sample_rate, **kwargs):
|
||||
self.assertEqual(sample_rate, 16000)
|
||||
self.assertLessEqual(kwargs["batch_size"], 512)
|
||||
frames = 1 + signal.shape[1] // kwargs["hop_length"]
|
||||
return torch.full((1, frames), 440.0), torch.ones((1, frames))
|
||||
with patch("torchcrepe.predict", side_effect=predict):
|
||||
result = detect_pitch(audio)
|
||||
self.assertEqual(len(result["hz"]), 101)
|
||||
self.assertEqual(result["hz"][50], 440.0)
|
||||
|
||||
def test_one_second_tone_runs_crepe(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
audio = Path(d) / "tone.wav"
|
||||
t = np.arange(16000, dtype=np.float32) / 16000
|
||||
sf.write(audio, 0.2 * np.sin(2 * np.pi * 440 * t), 16000)
|
||||
result = detect_pitch(audio)
|
||||
self.assertEqual(len(result["hz"]), 101)
|
||||
self.assertTrue(any(400 < hz < 480 for hz in result["hz"]))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user