Files
stimmwerk/tools/song_analysis/backends.py
wlkns-dev 438266d780 Song-Analyse: eigenständiges Werkzeug und Lese-Schnittstelle in Rust
- tools/analyze + tools/song_analysis: Trennung in Stems, Takte, Akkorde, Tonhöhe und Text mit Wortzeiten
  (eigene Python-3.11-Umgebung, README, Tests)
- schemas/song-analysis-v1: JSON-Schemas der Ausgabe
- src/lib.rs, src/song_analysis.rs: liest die Ausgabe (Version 1); Integrationstest in tests/
- .gitignore: Umgebung, Modelle und Zwischenspeicher des Werkzeugs

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 08:56:23 +01:00

185 lines
8.2 KiB
Python

"""Adapters for the optional audio models and command-line tools."""
import json
import os
import statistics
import subprocess
import tempfile
from pathlib import Path
from .core import parse_chordino
def command(args: list[str], *, capture: bool = False, env: dict[str, str] | None = None) -> str:
try:
result = subprocess.run([str(a) for a in args], check=True, text=True,
stdout=subprocess.PIPE if capture else None,
stderr=subprocess.PIPE if capture else None, env=env)
except subprocess.CalledProcessError as exc:
message = (exc.stderr or "").strip().splitlines()
raise RuntimeError(f"{args[0]} fehlgeschlagen: {message[-1] if message else exc}") from exc
return result.stdout or ""
def duration_of(audio: Path) -> float:
result = command(["ffprobe", "-v", "error", "-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1", audio], capture=True)
return float(result.strip())
def normalize(source: Path, target: Path, duration: float | None = None) -> None:
target.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(dir=target.parent) as tmp:
staged = Path(tmp) / "audio.wav"
args = ["ffmpeg", "-nostdin", "-y", "-v", "error", "-i", source,
"-ar", "44100", "-ac", "2"]
if duration is not None:
args += ["-af", "apad", "-t", str(duration)]
command(args + [staged])
staged.replace(target)
def separate(audio: Path, target_dir: Path, stems: list[str], model: str,
separator_bin: str, model_dir: Path | None, duration: float,
force: bool = False) -> None:
with tempfile.TemporaryDirectory(dir=target_dir.parent) as tmp:
tmpdir = Path(tmp)
args = [separator_bin, str(audio), "--model_filename", model,
"--output_dir", str(tmpdir), "--output_format", "WAV",
"--custom_output_names", json.dumps({s.title(): s for s in stems})]
if model_dir:
args += ["--model_file_dir", str(model_dir)]
command(args)
missing = [s for s in stems if not (tmpdir / f"{s}.wav").exists()]
if missing:
raise RuntimeError("Separator lieferte keine Stems: " + ", ".join(missing))
target_dir.mkdir(parents=True, exist_ok=True)
for stem in stems:
target = target_dir / f"{stem}.wav"
if force or not target.exists():
normalize(tmpdir / f"{stem}.wav", target, duration)
def detect_beats(audio: Path) -> tuple[dict, float | None]:
try:
from madmom_infer.features.downbeats import RNNDownBeatProcessor, DBNDownBeatTrackingProcessor
except ImportError:
from madmom.features.downbeats import RNNDownBeatProcessor, DBNDownBeatTrackingProcessor
activations = RNNDownBeatProcessor()(str(audio))
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
return {"beats": beats, "downbeats": downbeats}, bpm
def detect_key(audio: Path) -> str:
try:
from madmom_infer.features.key import CNNKeyRecognitionProcessor, key_prediction_to_label
except ImportError:
from madmom.features.key import CNNKeyRecognitionProcessor, key_prediction_to_label
return str(key_prediction_to_label(CNNKeyRecognitionProcessor()(str(audio))))
def detect_chords(audio: Path, duration: float) -> list[dict]:
env = os.environ.copy()
local_vamp = Path(__file__).resolve().parent / "vamp"
if (local_vamp / "nnls-chroma.so").is_file():
env["VAMP_PATH"] = str(local_vamp) + (os.pathsep + env["VAMP_PATH"] if env.get("VAMP_PATH") else "")
output = command(["vamp-simple-host", "nnls-chroma:chordino:simplechord", audio], capture=True, env=env)
chords = parse_chordino(output, duration)
if not chords:
raise RuntimeError("Chordino lieferte keine Akkorde; ist das Vamp-Plugin nnls-chroma installiert?")
return chords
def detect_pitch(audio: Path) -> dict:
import numpy as np
import soundfile as sf
import torch
import torchcrepe
from scipy.signal import resample_poly
samples, rate = sf.read(audio, dtype="float32", always_2d=True)
mono = samples.mean(axis=1)
# CREPE arbeitet bei 16 kHz; scipy vermeidet eine zweite Audiodekodierung.
from math import gcd
divisor = gcd(rate, 16000)
mono = resample_poly(mono, 16000 // divisor, rate // divisor)
signal = torch.from_numpy(np.asarray(mono, dtype="float32")).unsqueeze(0)
devices = ["cuda", "cpu"] if torch.cuda.is_available() else ["cpu"]
for device in devices:
try:
hz, confidence = torchcrepe.predict(signal, 16000, hop_length=160,
fmin=50, fmax=1000, model="full",
device=device, return_periodicity=True,
batch_size=512)
break
except RuntimeError:
if device == "cpu":
raise
torch.cuda.empty_cache()
hz = hz.squeeze(0).cpu().numpy()
confidence = np.clip(confidence.squeeze(0).cpu().numpy(), 0, 1)
return {"hop_ms": 10, "hz": [round(float(f), 3) if c >= 0.5 else 0.0
for f, c in zip(hz, confidence)],
"conf": [round(float(c), 4) for c in confidence]}
def transcribe_midi(audio: Path, target: Path) -> None:
from basic_pitch.inference import predict
_, midi, _ = predict(str(audio))
with tempfile.TemporaryDirectory(dir=target.parent) as tmp:
staged = Path(tmp) / target.name
midi.write(str(staged))
staged.replace(target)
def lyrics_words(audio: Path, lyrics: Path | None, language: str,
model_name: str) -> tuple[list[dict], bool]:
import torch
import whisperx
audio_data = whisperx.load_audio(str(audio))
devices = ["cuda", "cpu"] if torch.cuda.is_available() else ["cpu"]
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
aligner, metadata = whisperx.load_align_model(language_code=language, device=device)
aligned = whisperx.align(segments, aligner, metadata, audio_data, device,
return_char_alignments=False)
words = []
for item in aligned.get("word_segments", []):
if "start" not in item or "end" not in item or not item.get("word", "").strip():
continue
words.append({"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})
if not words:
raise RuntimeError("WhisperX lieferte keine ausgerichteten Wörter")
return words, verified
except (RuntimeError, MemoryError) as exc:
last_error = exc
if device == "cuda":
torch.cuda.empty_cache()
continue
raise
raise RuntimeError(f"WhisperX fehlgeschlagen: {last_error}")