feat: version song analysis contract and preserve lyric lines
This commit is contained in:
@ -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")
|
||||
|
||||
Reference in New Issue
Block a user