8 Commits

36 changed files with 3105 additions and 0 deletions

47
.gitignore vendored Normal file
View File

@ -0,0 +1,47 @@
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# Virtual environments
.venv/
env/
venv/
ENV/
# Testing & Coverage
.coverage
.coverage.*
htmlcov/
.pytest_cache/
# Song-Paket cache & outputs
.cache/
testdata/
*.wav
*.mp3
*.flac
*.ogg
# IDE
.idea/
.vscode/
*.swp

View File

@ -0,0 +1,53 @@
# songsplit
`songsplit` zerlegt Songs (Video oder Audio) in ein **Song-Paket**: getrennte Stems, Text mit Wort-/Silben-Timing, Gesangsnoten, Tempo-Map, Akkorde und Strumming-Vorschlag. Das Paket dient als Schnittstelle für Trainer-Apps und Editoren.
Verbindliche Spezifikation: siehe [umsetzungskonzept.md](umsetzungskonzept.md).
## Installation & Setup
Entwicklungsumgebung mit Python 3.12 und `uv`:
```bash
# Virtuelle Umgebung erstellen und Abhängigkeiten installieren
uv venv --python 3.12
uv pip install -e ".[dev]"
# System- und Hardwareprüfung durchführen
uv run songsplit doctor
```
## CLI-Verwendung
```bash
# System- und GPU-Check
songsplit doctor
# Gesamte Analyse oder bestimmte Stufen ausführen
songsplit analyze <datei> -o <ordner> [--lang de] [--stems 4|6] [--quality fast|best]
songsplit analyze <datei> -o <ordner> --stage chords [--force]
# Export nach UltraStar (ab M2)
songsplit export-ultrastar <ordner>
# Qualitätsmessung (ab M2)
songsplit eval <testset.toml>
```
## Tests
```bash
uv run pytest
uv run ruff check
uv run ruff format --check
```
## Meilensteine
- [x] **M0 – Gerüst**: Projektstruktur, Pydantic-Schemas (`meta.json`, `tempo.json`, `vocals.json`, `chords.json`, `strumming.json`), `tempo.py` mit `sec_to_beat`/`beat_to_sec`, Pipeline-Runner mit Cache und Hash-Invalidierung, CLI-Skelett mit `doctor`, Testsuite.
- [x] **M1 – Extraktion und Stems**: Stufen 1 (ffmpeg 44.1 kHz stereo) und 2 (Demucs `htdemucs_ft` / `htdemucs_6s`, low-VRAM chunking mit segment/shifts, `instrumental.wav` und `vocals.wav`, SNR-Prüfung).
- [ ] **M2 – Gesang**: Stufen 3 (Whisper+WhisperX) und 4 (torchcrepe), UltraStar-Writer, Eval-Gerüst.
- [ ] **M3 – Tempo-Map**: Stufe 5 (beat_this).
- [ ] **M4 – Akkorde**: Stufe 6 (Chordino / Transformer).
- [ ] **M5 – Strumming**: Stufe 7 (librosa Onsets / Strumming-Muster).
- [ ] **M6 – Härtung**: Fehlerbehandlung, Logging, Dokumentation, Beispielpaket.

49
pyproject.toml Normal file
View File

@ -0,0 +1,49 @@
[project]
name = "songsplit"
version = "0.1.0"
description = "Song-Paket Audioanalyse-Pipeline (Stems, Lyrics, Vocals, Tempo, Chords, Strumming)"
readme = "README.md"
requires-python = ">=3.11,<3.13"
dependencies = [
"pydantic>=2.7.0",
"typer>=0.12.0",
"rich>=13.7.0",
"demucs>=4.0.0",
"torch>=2.0.0",
"soundfile>=0.12.0",
"julius>=0.2.7",
]
[project.optional-dependencies]
dev = [
"pytest>=8.0.0",
"pytest-cov>=5.0.0",
"ruff>=0.4.0",
]
[project.scripts]
songsplit = "songsplit.cli:app"
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.hatch.build.targets.wheel]
packages = ["src/songsplit"]
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
markers = [
"integration: marks tests as integration tests",
]
[tool.ruff]
line-length = 120
target-version = "py312"
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B"]
ignore = ["B008", "E501"]

View File

@ -0,0 +1,3 @@
"""songsplit: Audio analysis pipeline for song package decomposition."""
__version__ = "0.1.0"

170
src/songsplit/cli.py Normal file
View File

@ -0,0 +1,170 @@
"""CLI interface for songsplit."""
import json
import shutil
import subprocess
import sys
from pathlib import Path
import typer
from rich.console import Console
from rich.table import Table
from songsplit import __version__
from songsplit.config import config
from songsplit.pipeline import PipelineContext, get_default_pipeline
app = typer.Typer(
name="songsplit",
help="Audio analysis pipeline decomposing songs into song packages.",
add_completion=False,
)
console = Console(stderr=True)
@app.command()
def analyze(
file: Path = typer.Argument(..., help="Path to input audio or video file", exists=True, readable=True),
output_dir: Path = typer.Option(..., "-o", "--output", help="Output song package directory"),
lang: str = typer.Option("de", "--lang", help="Lyrics language (e.g. 'de', 'en')"),
stems: int = typer.Option(4, "--stems", help="Number of stems to separate (4 or 6)"),
quality: str = typer.Option("best", "--quality", help="Separation quality ('fast' or 'best')"),
stage: str | None = typer.Option(None, "--stage", help="Run only a specific stage and its missing dependencies"),
force: bool = typer.Option(False, "--force", help="Force recalculation ignoring cached results"),
json_output: bool = typer.Option(False, "--json", help="Output machine-readable JSON result path"),
) -> None:
"""Analyze an audio or video file and produce a Song-Paket."""
ctx = PipelineContext(
source_file=file,
output_dir=output_dir,
lang=lang,
stems=stems,
quality=quality,
force=force,
target_stage=stage,
)
runner = get_default_pipeline()
meta = runner.run(ctx)
if json_output:
print(
json.dumps(
{
"output_dir": str(output_dir.resolve()),
"stages_done": meta.stages_done,
"stages_failed": meta.stages_failed,
}
)
)
else:
print(str(output_dir.resolve()))
@app.command(name="export-ultrastar")
def export_ultrastar_cmd(
song_dir: Path = typer.Argument(..., help="Song-Paket directory to export", exists=True),
) -> None:
"""Export an existing Song-Paket directory to UltraStar song.txt."""
from songsplit.export.ultrastar import export_ultrastar
res = export_ultrastar(song_dir)
print(str(res))
@app.command(name="eval")
def eval_cmd(
testset_config: Path = typer.Argument(..., help="Path to testset.toml", exists=True),
) -> None:
"""Run quality benchmarks against UltraStar ground-truth references."""
from songsplit.eval.run_eval import run_evaluation
run_evaluation(testset_config)
@app.command()
def doctor() -> None:
"""Check environment, ffmpeg installation, GPUs, and PyTorch availability."""
table = Table(title=f"songsplit v{__version__} Doctor System Check")
table.add_column("Component", style="cyan", no_wrap=True)
table.add_column("Status", style="bold")
table.add_column("Details", style="white")
# 1. Python version
py_ver = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
if sys.version_info.major == 3 and 11 <= sys.version_info.minor <= 12:
table.add_row("Python", "[green]OK[/green]", f"{py_ver} ({sys.executable})")
else:
table.add_row("Python", "[yellow]WARN[/yellow]", f"{py_ver} (Empfohlen: Python 3.11 / 3.12)")
# 2. ffmpeg
ffmpeg_path = shutil.which("ffmpeg")
if ffmpeg_path:
try:
res = subprocess.run([ffmpeg_path, "-version"], capture_output=True, text=True, check=True)
first_line = res.stdout.splitlines()[0] if res.stdout else "Available"
table.add_row("ffmpeg", "[green]OK[/green]", f"{ffmpeg_path} ({first_line})")
except Exception as e:
table.add_row("ffmpeg", "[yellow]WARN[/yellow]", f"Found at {ffmpeg_path} but error running: {e}")
else:
table.add_row("ffmpeg", "[red]FAIL[/red]", "ffmpeg not found in PATH")
# 3. PyTorch
try:
import torch # type: ignore
backend_info = []
if getattr(torch.version, "cuda", None):
backend_info.append(f"CUDA {torch.version.cuda}")
if getattr(torch.version, "hip", None):
backend_info.append(f"ROCm/HIP {torch.version.hip}")
backend_str = ", ".join(backend_info) if backend_info else "CPU-only"
table.add_row("PyTorch", "[green]OK[/green]", f"v{torch.__version__} ({backend_str})")
# Check PyTorch visible GPUs
if torch.cuda.is_available():
count = torch.cuda.device_count()
devices_desc = []
for i in range(count):
devices_desc.append(f"[{i}] {torch.cuda.get_device_name(i)}")
table.add_row("Torch GPUs", "[green]OK[/green]", f"{count} device(s): " + "; ".join(devices_desc))
else:
table.add_row("Torch GPUs", "[yellow]INFO[/yellow]", "No CUDA/ROCm device active in PyTorch")
except ImportError:
table.add_row("PyTorch", "[yellow]NOT INSTALLED[/yellow]", "PyTorch is not yet installed in virtualenv")
# 4. System GPUs / Hardware Devices
# AMD ROCm / KFD
kfd_path = Path("/dev/kfd")
if kfd_path.exists():
table.add_row(
"AMD ROCm (/dev/kfd)", "[green]DETECTED[/green]", f"{kfd_path} present (AMD GPU kernel driver active)"
)
else:
table.add_row("AMD ROCm (/dev/kfd)", "[dim]NONE[/dim]", "No /dev/kfd device found")
# NVIDIA device nodes
nvidia_nodes = list(Path("/dev").glob("nvidia*"))
if nvidia_nodes:
table.add_row("NVIDIA Devices", "[green]DETECTED[/green]", f"Found: {', '.join(p.name for p in nvidia_nodes)}")
else:
table.add_row("NVIDIA Devices", "[dim]NONE[/dim]", "No /dev/nvidia* device nodes found")
# CLI tools
rocm_smi = shutil.which("rocm-smi")
table.add_row("rocm-smi", "[green]OK[/green]" if rocm_smi else "[dim]NONE[/dim]", rocm_smi or "Not found in PATH")
nvidia_smi = shutil.which("nvidia-smi")
table.add_row(
"nvidia-smi", "[green]OK[/green]" if nvidia_smi else "[dim]NONE[/dim]", nvidia_smi or "Not found in PATH"
)
# 5. Model Cache Directory
model_dir = config.models_cache_dir
table.add_row("Model Cache", "[green]OK[/green]", str(model_dir))
console.print(table)
if __name__ == "__main__":
app()

43
src/songsplit/config.py Normal file
View File

@ -0,0 +1,43 @@
"""Configuration management for songsplit (devices, models, paths)."""
import os
from pathlib import Path
from pydantic import BaseModel, Field
class Config(BaseModel):
"""Runtime configuration for pipeline stages, devices, and directories."""
models_cache_dir: Path = Field(
default_factory=lambda: Path(
os.getenv("SONGSPLIT_MODELS_DIR", Path.home() / ".cache" / "songsplit" / "models")
).expanduser()
)
default_device: str = Field(default_factory=lambda: os.getenv("SONGSPLIT_DEFAULT_DEVICE", "cuda:0"))
stage_devices: dict[str, str] = Field(
default_factory=lambda: {
"s1_extract": os.getenv("SONGSPLIT_DEVICE_S1", "cpu"),
"s2_stems": os.getenv("SONGSPLIT_DEVICE_S2", "cuda:0"),
"s3_lyrics": os.getenv("SONGSPLIT_DEVICE_S3", "cuda:0"),
"s4_pitch": os.getenv("SONGSPLIT_DEVICE_S4", "cuda:0"),
"s5_tempo": os.getenv("SONGSPLIT_DEVICE_S5", "cpu"),
"s6_chords": os.getenv("SONGSPLIT_DEVICE_S6", "cpu"),
"s7_strumming": os.getenv("SONGSPLIT_DEVICE_S7", "cpu"),
}
)
def get_device(self, stage: str) -> str:
"""Get target compute device for a specific stage."""
return self.stage_devices.get(stage, self.default_device)
def get_models_dir(self) -> Path:
"""Ensure and return the model cache directory."""
self.models_cache_dir.mkdir(parents=True, exist_ok=True)
return self.models_cache_dir
# Global singleton instance
config = Config()

View File

@ -0,0 +1,6 @@
"""Evaluation package."""
from songsplit.eval.metrics import calculate_timing_metrics
from songsplit.eval.run_eval import run_evaluation
__all__ = ["calculate_timing_metrics", "run_evaluation"]

View File

@ -0,0 +1,8 @@
"""Quality metrics against UltraStar reference (timing, pitch, WER)."""
from typing import Any
def calculate_timing_metrics(predicted: list[dict[str, Any]], reference: list[dict[str, Any]]) -> dict[str, float]:
"""Calculate mean/median syllable onset error in ms and fraction within +-100ms."""
raise NotImplementedError("Metrics will be implemented in M2.")

View File

@ -0,0 +1,8 @@
"""Evaluation runner for testset.toml."""
from pathlib import Path
def run_evaluation(testset_config: Path) -> dict[str, str]:
"""Run full evaluation suite across test songs."""
raise NotImplementedError("Evaluation runner will be implemented in M2.")

View File

@ -0,0 +1,5 @@
"""Export modules."""
from songsplit.export.ultrastar import export_ultrastar
__all__ = ["export_ultrastar"]

View File

@ -0,0 +1,8 @@
"""UltraStar format export and import."""
from pathlib import Path
def export_ultrastar(song_dir: Path) -> Path:
"""Export song package to UltraStar song.txt."""
raise NotImplementedError("UltraStar export will be implemented in M2.")

View File

@ -0,0 +1,40 @@
"""Pipeline stages and runner."""
from songsplit.pipeline.runner import PipelineContext, PipelineRunner, Stage
from songsplit.pipeline.s1_extract import ExtractStage
from songsplit.pipeline.s2_stems import StemsStage
from songsplit.pipeline.s3_lyrics import LyricsStage
from songsplit.pipeline.s4_pitch import PitchStage
from songsplit.pipeline.s5_tempo import TempoStage
from songsplit.pipeline.s6_chords import ChordsStage
from songsplit.pipeline.s7_strumming import StrummingStage
def get_default_pipeline() -> PipelineRunner:
"""Instantiate the default 7-stage songsplit pipeline."""
return PipelineRunner(
[
ExtractStage(),
StemsStage(),
LyricsStage(),
PitchStage(),
TempoStage(),
ChordsStage(),
StrummingStage(),
]
)
__all__ = [
"PipelineContext",
"PipelineRunner",
"Stage",
"ExtractStage",
"StemsStage",
"LyricsStage",
"PitchStage",
"TempoStage",
"ChordsStage",
"StrummingStage",
"get_default_pipeline",
]

View File

@ -0,0 +1,267 @@
"""Pipeline runner, caching, stage dependency management, and hash invalidation."""
import hashlib
import json
import sys
from abc import ABC, abstractmethod
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
from songsplit.schema.meta import MetaDocument, ModelInfo, SourceFileInfo
def compute_file_sha256(file_path: Path, chunk_size: int = 65536) -> str:
"""Compute sha256 hash of a file."""
hasher = hashlib.sha256()
with open(file_path, "rb") as f:
while chunk := f.read(chunk_size):
hasher.update(chunk)
return hasher.hexdigest()
class PipelineContext:
"""Context holding paths and options for the song package analysis run."""
def __init__(
self,
source_file: Path,
output_dir: Path,
lang: str | None = "de",
stems: int = 4,
quality: str = "best",
force: bool = False,
target_stage: str | None = None,
):
self.source_file = source_file.resolve()
self.output_dir = output_dir.resolve()
self.lang = lang
self.stems = stems
self.quality = quality
self.force = force
self.target_stage = target_stage
self.cache_dir = self.output_dir / ".cache"
self.stems_dir = self.output_dir / "stems"
self.meta_file = self.output_dir / "meta.json"
def ensure_directories(self) -> None:
"""Create necessary output directories."""
self.output_dir.mkdir(parents=True, exist_ok=True)
self.cache_dir.mkdir(parents=True, exist_ok=True)
self.stems_dir.mkdir(parents=True, exist_ok=True)
def load_or_init_meta(self) -> MetaDocument:
"""Load existing meta.json or create initial document."""
if self.meta_file.exists():
with open(self.meta_file, encoding="utf-8") as f:
data = json.load(f)
return MetaDocument.model_validate(data)
source_hash = compute_file_sha256(self.source_file) if self.source_file.exists() else ""
size_bytes = self.source_file.stat().st_size if self.source_file.exists() else 0
return MetaDocument(
duration_sec=0.0,
source_file=SourceFileInfo(
path=str(self.source_file),
sha256=source_hash,
size_bytes=size_bytes,
),
created_at=datetime.now(UTC).isoformat(),
)
def save_meta(self, meta: MetaDocument) -> None:
"""Save meta document to meta.json."""
with open(self.meta_file, "w", encoding="utf-8") as f:
f.write(meta.model_dump_json(indent=2))
class Stage(ABC):
"""Abstract base class for pipeline stages."""
name: str
version: str = "1.0.0"
model_name: str
model_version: str = "1.0.0"
dependencies: list[str] = []
@abstractmethod
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
"""List of input files required by this stage."""
...
@abstractmethod
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
"""List of output files produced by this stage."""
...
def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
"""Parameters affecting output calculation."""
return {}
def compute_cache_hash(self, ctx: PipelineContext) -> str:
"""Compute deterministic hash of inputs, params, version and model."""
hasher = hashlib.sha256()
hasher.update(self.name.encode("utf-8"))
hasher.update(self.version.encode("utf-8"))
hasher.update(self.model_name.encode("utf-8"))
hasher.update(self.model_version.encode("utf-8"))
# Params serialized canonically
params_str = json.dumps(self.get_params(ctx), sort_keys=True)
hasher.update(params_str.encode("utf-8"))
for input_path in self.get_inputs(ctx):
if input_path.exists():
hasher.update(input_path.name.encode("utf-8"))
hasher.update(compute_file_sha256(input_path).encode("utf-8"))
else:
hasher.update(f"missing:{input_path.name}".encode())
return hasher.hexdigest()
def is_cached(self, ctx: PipelineContext) -> bool:
"""Check if stage output is already computed and valid in cache."""
cache_file = ctx.cache_dir / f"{self.name}.json"
if not cache_file.exists():
return False
# All outputs must exist
outputs = self.get_outputs(ctx)
if not outputs or not all(p.exists() for p in outputs):
return False
try:
with open(cache_file, encoding="utf-8") as f:
cached_data = json.load(f)
current_hash = self.compute_cache_hash(ctx)
return cached_data.get("cache_hash") == current_hash
except Exception:
return False
def write_cache_entry(self, ctx: PipelineContext, cache_hash: str) -> None:
"""Record successful stage run in cache."""
cache_file = ctx.cache_dir / f"{self.name}.json"
data = {
"stage": self.name,
"version": self.version,
"model": self.model_name,
"model_version": self.model_version,
"cache_hash": cache_hash,
"timestamp": datetime.now(UTC).isoformat(),
"outputs": [str(p) for p in self.get_outputs(ctx)],
}
with open(cache_file, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
@abstractmethod
def run(self, ctx: PipelineContext) -> None:
"""Execute stage processing."""
...
class PipelineRunner:
"""Manages stage execution, order resolution, caching and error recovery."""
def __init__(self, stages: list[Stage]):
self.stages_by_name = {s.name: s for s in stages}
self._validate_stages()
def _validate_stages(self) -> None:
"""Ensure all declared dependencies exist in runner."""
for s in self.stages_by_name.values():
for dep in s.dependencies:
if dep not in self.stages_by_name:
raise ValueError(f"Stage '{s.name}' depends on unknown stage '{dep}'")
def get_stages_to_run(self, ctx: PipelineContext) -> list[Stage]:
"""Resolve ordered list of stages to run."""
if ctx.target_stage:
if ctx.target_stage not in self.stages_by_name:
raise ValueError(f"Unknown target stage: '{ctx.target_stage}'")
# Collect target stage and all its transitive dependencies
needed = set()
def add_deps(name: str):
needed.add(name)
for dep in self.stages_by_name[name].dependencies:
if dep not in needed:
add_deps(dep)
add_deps(ctx.target_stage)
selected = [s for s in self.stages_by_name.values() if s.name in needed]
else:
selected = list(self.stages_by_name.values())
# Topological sort
ordered: list[Stage] = []
visited: set[str] = set()
def visit(stage: Stage):
if stage.name in visited:
return
for dep in stage.dependencies:
if dep in self.stages_by_name and self.stages_by_name[dep] in selected:
visit(self.stages_by_name[dep])
visited.add(stage.name)
ordered.append(stage)
for s in selected:
visit(s)
return ordered
def run(self, ctx: PipelineContext) -> MetaDocument:
"""Execute the pipeline according to context configuration."""
ctx.ensure_directories()
meta = ctx.load_or_init_meta()
stages_to_run = self.get_stages_to_run(ctx)
failed_stages: set[str] = set(meta.stages_failed.keys())
for stage in stages_to_run:
# Check if any dependencies failed
failed_deps = [d for d in stage.dependencies if d in failed_stages]
if failed_deps:
msg = f"Skipping {stage.name} because dependencies failed: {failed_deps}"
sys.stderr.write(f"[WARN] {msg}\n")
meta.stages_failed[stage.name] = msg
failed_stages.add(stage.name)
continue
# Check cache
if not ctx.force and stage.is_cached(ctx):
sys.stderr.write(f"[INFO] Stage {stage.name} is up to date (cached).\n")
if stage.name not in meta.stages_done:
meta.stages_done.append(stage.name)
continue
sys.stderr.write(f"[INFO] Running stage: {stage.name}...\n")
try:
cache_hash = stage.compute_cache_hash(ctx)
stage.run(ctx)
stage.write_cache_entry(ctx, cache_hash)
if stage.name not in meta.stages_done:
meta.stages_done.append(stage.name)
# Remove from failed if it was previously marked failed
meta.stages_failed.pop(stage.name, None)
# Update model info
model_entry = ModelInfo(
stage=stage.name,
name=stage.model_name,
version=stage.model_version,
)
if not any(m.stage == stage.name for m in meta.models_used):
meta.models_used.append(model_entry)
except Exception as e:
err_msg = f"{type(e).__name__}: {str(e)}"
sys.stderr.write(f"[ERROR] Stage {stage.name} failed: {err_msg}\n")
meta.stages_failed[stage.name] = err_msg
failed_stages.add(stage.name)
ctx.save_meta(meta)
return meta

View File

@ -0,0 +1,98 @@
"""Stage 1: Extract audio to 44.1 kHz stereo WAV using ffmpeg."""
import json
import shutil
import subprocess
from pathlib import Path
from typing import Any
from songsplit.pipeline.runner import PipelineContext, Stage
def get_audio_duration(file_path: Path) -> float:
"""Get audio duration in seconds using ffprobe."""
ffprobe_path = shutil.which("ffprobe")
if not ffprobe_path:
# Fallback to ffmpeg
return 0.0
cmd = [
ffprobe_path,
"-v",
"error",
"-show_entries",
"format=duration",
"-of",
"json",
str(file_path),
]
try:
res = subprocess.run(cmd, capture_output=True, text=True, check=True)
data = json.loads(res.stdout)
return float(data.get("format", {}).get("duration", 0.0))
except Exception:
return 0.0
class ExtractStage(Stage):
"""Stage 1 extracts and standardizes input audio/video to 44.1 kHz stereo WAV."""
name = "s1_extract"
version = "1.0.0"
model_name = "ffmpeg"
model_version = "6.0"
dependencies: list[str] = []
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.source_file]
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.cache_dir / "extracted.wav"]
def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
return {
"sample_rate": 44100,
"channels": 2,
"codec": "pcm_s16le",
}
def run(self, ctx: PipelineContext) -> None:
ffmpeg_path = shutil.which("ffmpeg")
if not ffmpeg_path:
raise FileNotFoundError("ffmpeg executable not found in PATH")
output_wav = self.get_outputs(ctx)[0]
output_wav.parent.mkdir(parents=True, exist_ok=True)
# ffmpeg extraction command:
# -y : overwrite output
# -i <source>
# -vn : disable video recording
# -acodec pcm_s16le : 16-bit uncompressed PCM
# -ar 44100 : 44.1 kHz sample rate
# -ac 2 : stereo
cmd = [
ffmpeg_path,
"-y",
"-i",
str(ctx.source_file),
"-vn",
"-acodec",
"pcm_s16le",
"-ar",
"44100",
"-ac",
"2",
str(output_wav),
]
res = subprocess.run(cmd, capture_output=True, text=True)
if res.returncode != 0:
raise RuntimeError(f"ffmpeg extraction failed: {res.stderr}")
# Update duration in meta document if available
duration = get_audio_duration(output_wav)
if duration > 0.0:
meta = ctx.load_or_init_meta()
meta.duration_sec = duration
ctx.save_meta(meta)

View File

@ -0,0 +1,144 @@
"""Stage 2: Stem separation using Demucs with chunking for low VRAM."""
from pathlib import Path
from typing import Any
import julius
import soundfile as sf
import torch
from songsplit.config import config
from songsplit.pipeline.runner import PipelineContext, Stage
class StemsStage(Stage):
"""Stage 2 separates mixed audio into isolated stems (vocals, instrumental, drums, bass, etc.)."""
name = "s2_stems"
version = "1.0.0"
model_name = "htdemucs_ft"
model_version = "1.0.0"
dependencies = ["s1_extract"]
def __init__(self, model_name: str = "htdemucs_ft"):
self.model_name = model_name
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.cache_dir / "extracted.wav"]
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
base_stems = [
ctx.stems_dir / "vocals.wav",
ctx.stems_dir / "instrumental.wav",
ctx.stems_dir / "drums.wav",
ctx.stems_dir / "bass.wav",
ctx.stems_dir / "other.wav",
]
if ctx.stems == 6:
base_stems.extend(
[
ctx.stems_dir / "guitar.wav",
ctx.stems_dir / "piano.wav",
]
)
return base_stems
def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
return {
"stems": ctx.stems,
"quality": ctx.quality,
"segment": 7 if ctx.quality == "fast" else 10,
"shifts": 0 if ctx.quality == "fast" else 1,
}
def run(self, ctx: PipelineContext) -> None:
import demucs.pretrained
from demucs.apply import apply_model
input_wav = self.get_inputs(ctx)[0]
if not input_wav.exists():
raise FileNotFoundError(f"Input WAV not found: {input_wav}")
# Target model selection based on stems count and quality
if ctx.stems == 6:
target_model = "htdemucs_6s"
else:
target_model = "htdemucs_ft" if ctx.quality == "best" else "htdemucs"
self.model_name = target_model
# Determine compute device with fallback to cpu
device_str = config.get_device(self.name)
if device_str.startswith("cuda") and not torch.cuda.is_available():
device_str = "cpu"
device = torch.device(device_str)
# Configure models directory
models_dir = config.get_models_dir()
torch.hub.set_dir(str(models_dir))
model = demucs.pretrained.get_model(target_model)
model.to(device)
model.eval()
# Load audio using soundfile
audio_data, sr = sf.read(str(input_wav), dtype="float32")
# audio_data shape: [samples] (mono) or [samples, channels] (stereo)
if audio_data.ndim == 1:
wav = torch.from_numpy(audio_data).unsqueeze(0).repeat(2, 1)
else:
wav = torch.from_numpy(audio_data.T)
if wav.shape[0] == 1:
wav = wav.repeat(2, 1)
elif wav.shape[0] > 2:
wav = wav[:2, :]
if sr != model.samplerate:
wav = julius.resample_frac(wav, sr, model.samplerate)
# Normalize audio for stable separation
ref = wav.mean(0)
wav = (wav - ref.mean()) / (ref.std() + 1e-8)
params = self.get_params(ctx)
segment = params["segment"]
shifts = params["shifts"]
# Add batch dimension: [1, 2, samples]
wav = wav.unsqueeze(0).to(device)
# Execute separation with chunking
with torch.no_grad():
sources = apply_model(
model,
wav,
shifts=shifts,
split=True,
overlap=0.25,
segment=segment,
device=device,
progress=False,
)
# Rescale back to original loudness
sources = sources * (ref.std() + 1e-8) + ref.mean()
# [num_sources, channels, samples]
sources = sources.squeeze(0).cpu()
ctx.stems_dir.mkdir(parents=True, exist_ok=True)
stem_dict: dict[str, torch.Tensor] = {}
for idx, src_name in enumerate(model.sources):
stem_dict[src_name] = sources[idx]
# Save each stem WAV file using soundfile (16-bit PCM)
for src_name, tensor in stem_dict.items():
out_path = ctx.stems_dir / f"{src_name}.wav"
# tensor is [channels, samples] -> transpose to [samples, channels]
data_out = tensor.clamp(-1.0, 1.0).numpy().T
sf.write(str(out_path), data_out, model.samplerate, subtype="PCM_16")
# Create instrumental stem: sum of all non-vocals stems
non_vocals = [tensor for name, tensor in stem_dict.items() if name != "vocals"]
if non_vocals:
instrumental = torch.stack(non_vocals).sum(dim=0)
data_inst = instrumental.clamp(-1.0, 1.0).numpy().T
sf.write(str(ctx.stems_dir / "instrumental.wav"), data_inst, model.samplerate, subtype="PCM_16")

View File

@ -0,0 +1,27 @@
"""Stage 3: Lyrics transcription & alignment (Whisper + WhisperX + hyphenation)."""
from pathlib import Path
from typing import Any
from songsplit.pipeline.runner import PipelineContext, Stage
class LyricsStage(Stage):
name = "s3_lyrics"
version = "1.0.0"
model_name = "whisper-large-v3"
model_version = "1.0.0"
dependencies = ["s2_stems"]
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.stems_dir / "vocals.wav"]
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.output_dir / ".cache" / "lyrics_raw.json"]
def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
return {"lang": ctx.lang}
def run(self, ctx: PipelineContext) -> None:
# Implementation in M2
raise NotImplementedError("Stage s3_lyrics will be implemented in M2.")

View File

@ -0,0 +1,30 @@
"""Stage 4: Pitch tracking with CREPE -> median MIDI pitch per syllable."""
from pathlib import Path
from typing import Any
from songsplit.pipeline.runner import PipelineContext, Stage
class PitchStage(Stage):
name = "s4_pitch"
version = "1.0.0"
model_name = "torchcrepe-full"
model_version = "1.0.0"
dependencies = ["s3_lyrics"]
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
return [
ctx.stems_dir / "vocals.wav",
ctx.output_dir / ".cache" / "lyrics_raw.json",
]
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.output_dir / "vocals.json"]
def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
return {"hop_length_ms": 10, "viterbi": True}
def run(self, ctx: PipelineContext) -> None:
# Implementation in M2
raise NotImplementedError("Stage s4_pitch will be implemented in M2.")

View File

@ -0,0 +1,27 @@
"""Stage 5: Beat and downbeat tracking with beat_this -> tempo.json."""
from pathlib import Path
from typing import Any
from songsplit.pipeline.runner import PipelineContext, Stage
class TempoStage(Stage):
name = "s5_tempo"
version = "1.0.0"
model_name = "beat_this"
model_version = "1.0.0"
dependencies = ["s2_stems"]
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.stems_dir / "instrumental.wav"]
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.output_dir / "tempo.json"]
def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
return {}
def run(self, ctx: PipelineContext) -> None:
# Implementation in M3
raise NotImplementedError("Stage s5_tempo will be implemented in M3.")

View File

@ -0,0 +1,30 @@
"""Stage 6: Chord recognition -> chords.json."""
from pathlib import Path
from typing import Any
from songsplit.pipeline.runner import PipelineContext, Stage
class ChordsStage(Stage):
name = "s6_chords"
version = "1.0.0"
model_name = "chordino"
model_version = "1.0.0"
dependencies = ["s5_tempo"]
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
return [
ctx.stems_dir / "instrumental.wav",
ctx.output_dir / "tempo.json",
]
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.output_dir / "chords.json"]
def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
return {"backend": "chordino"}
def run(self, ctx: PipelineContext) -> None:
# Implementation in M4
raise NotImplementedError("Stage s6_chords will be implemented in M4.")

View File

@ -0,0 +1,30 @@
"""Stage 7: Strumming pattern analysis -> strumming.json."""
from pathlib import Path
from typing import Any
from songsplit.pipeline.runner import PipelineContext, Stage
class StrummingStage(Stage):
name = "s7_strumming"
version = "1.0.0"
model_name = "librosa-onsets"
model_version = "1.0.0"
dependencies = ["s5_tempo"]
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
return [
ctx.stems_dir / "instrumental.wav",
ctx.output_dir / "tempo.json",
]
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.output_dir / "strumming.json"]
def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
return {"grid": "8th"}
def run(self, ctx: PipelineContext) -> None:
# Implementation in M5
raise NotImplementedError("Stage s7_strumming will be implemented in M5.")

View File

@ -0,0 +1,29 @@
"""Song-Paket data schemas."""
from songsplit.schema.base import DataSource, GeneratedBy, SongPackageBase
from songsplit.schema.chords import ChordEvent, ChordsDocument
from songsplit.schema.meta import MetaDocument, ModelInfo, SourceFileInfo
from songsplit.schema.strumming import StrumDirection, StrumEvent, StrummingDocument, StrumPattern
from songsplit.schema.tempo import TempoAnchor, TempoDocument, TimeSignature
from songsplit.schema.vocals import VocalLine, VocalsDocument, VocalSyllable
__all__ = [
"DataSource",
"GeneratedBy",
"SongPackageBase",
"SourceFileInfo",
"ModelInfo",
"MetaDocument",
"VocalSyllable",
"VocalLine",
"VocalsDocument",
"TempoAnchor",
"TimeSignature",
"TempoDocument",
"ChordEvent",
"ChordsDocument",
"StrumDirection",
"StrumEvent",
"StrumPattern",
"StrummingDocument",
]

View File

@ -0,0 +1,27 @@
"""Base classes and shared types for Song-Paket schemas."""
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field
DataSource = Literal["auto", "manual", "import"]
class GeneratedBy(BaseModel):
"""Information about the stage, model and parameters used to generate the data."""
model_config = ConfigDict(extra="ignore")
stage: str
model: str
model_version: str = "1.0"
params: dict[str, Any] = Field(default_factory=dict)
class SongPackageBase(BaseModel):
"""Base schema for all Song-Paket JSON files with schema version and generation info."""
model_config = ConfigDict(extra="ignore")
schema_version: str = "1.0"
generated_by: GeneratedBy | None = None

View File

@ -0,0 +1,28 @@
"""Schema for chords.json."""
from pydantic import BaseModel, ConfigDict, Field
from songsplit.schema.base import DataSource, SongPackageBase
class ChordEvent(BaseModel):
"""A chord segment defined in beats."""
model_config = ConfigDict(extra="ignore")
start_beat: float
end_beat: float
label: str
root: str | None = None
quality: str | None = None
bass: str | None = None
confidence: float = Field(default=1.0, ge=0.0, le=1.0)
source: DataSource = "auto"
class ChordsDocument(SongPackageBase):
"""Song-Paket chords document (chords.json)."""
model_config = ConfigDict(extra="ignore")
chords: list[ChordEvent] = Field(default_factory=list)

View File

@ -0,0 +1,43 @@
"""Schema for meta.json."""
from pydantic import BaseModel, ConfigDict, Field
from songsplit.schema.base import SongPackageBase
class SourceFileInfo(BaseModel):
"""Information about the original source audio/video file."""
model_config = ConfigDict(extra="ignore")
path: str
sha256: str
size_bytes: int
class ModelInfo(BaseModel):
"""Information about an AI model used during processing."""
model_config = ConfigDict(extra="ignore")
stage: str
name: str
version: str
class MetaDocument(SongPackageBase):
"""Song-Paket metadata document (meta.json)."""
model_config = ConfigDict(extra="ignore")
title: str | None = None
artist: str | None = None
language: str | None = None
duration_sec: float = Field(ge=0.0)
source_file: SourceFileInfo
key: str | None = None
capo: int | None = None
models_used: list[ModelInfo] = Field(default_factory=list)
created_at: str
stages_done: list[str] = Field(default_factory=list)
stages_failed: dict[str, str] = Field(default_factory=dict)

View File

@ -0,0 +1,41 @@
"""Schema for strumming.json."""
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field
from songsplit.schema.base import DataSource, SongPackageBase
StrumDirection = Literal["down", "up", "unknown"]
class StrumEvent(BaseModel):
"""A single strumming event."""
model_config = ConfigDict(extra="ignore")
beat: float
direction: StrumDirection
strength: float = Field(default=1.0, ge=0.0, le=1.0)
confidence: float = Field(default=1.0, ge=0.0, le=1.0)
source: DataSource = "auto"
class StrumPattern(BaseModel):
"""An aggregated strumming pattern over a beat range."""
model_config = ConfigDict(extra="ignore")
start_beat: float
end_beat: float
pattern: str
grid: str = "8th"
class StrummingDocument(SongPackageBase):
"""Song-Paket strumming document (strumming.json)."""
model_config = ConfigDict(extra="ignore")
events: list[StrumEvent] = Field(default_factory=list)
patterns: list[StrumPattern] = Field(default_factory=list)

View File

@ -0,0 +1,34 @@
"""Schema for tempo.json."""
from pydantic import BaseModel, ConfigDict, Field
from songsplit.schema.base import SongPackageBase
class TempoAnchor(BaseModel):
"""A tempo anchor defining constant BPM starting from a given time/beat."""
model_config = ConfigDict(extra="ignore")
sec: float
beat: float
bpm: float = Field(gt=0.0)
class TimeSignature(BaseModel):
"""Musical time signature, e.g. 4/4."""
model_config = ConfigDict(extra="ignore")
numerator: int = Field(default=4, gt=0)
denominator: int = Field(default=4, gt=0)
class TempoDocument(SongPackageBase):
"""Song-Paket tempo document (tempo.json)."""
model_config = ConfigDict(extra="ignore")
anchors: list[TempoAnchor] = Field(default_factory=list)
time_signature: TimeSignature = Field(default_factory=TimeSignature)
downbeat_offset: int = 0

View File

@ -0,0 +1,37 @@
"""Schema for vocals.json."""
from pydantic import BaseModel, ConfigDict, Field
from songsplit.schema.base import DataSource, SongPackageBase
class VocalSyllable(BaseModel):
"""A single syllable with timing, pitch, and confidence."""
model_config = ConfigDict(extra="ignore")
text: str
start: float = Field(ge=0.0)
end: float = Field(ge=0.0)
midi: float
golden: bool = False
confidence: float = Field(default=1.0, ge=0.0, le=1.0)
source: DataSource = "auto"
class VocalLine(BaseModel):
"""A line of lyrics consisting of one or more syllables."""
model_config = ConfigDict(extra="ignore")
start: float = Field(ge=0.0)
end: float = Field(ge=0.0)
syllables: list[VocalSyllable] = Field(default_factory=list)
class VocalsDocument(SongPackageBase):
"""Song-Paket vocals document (vocals.json)."""
model_config = ConfigDict(extra="ignore")
lines: list[VocalLine] = Field(default_factory=list)

64
src/songsplit/tempo.py Normal file
View File

@ -0,0 +1,64 @@
"""Tempo-Map conversion between seconds and musical beats.
As defined in the concept:
- Vocals are in seconds
- Chords and strumming are in beats
- Conversion ONLY through sec_to_beat() and beat_to_sec().
"""
from bisect import bisect_right
from songsplit.schema.tempo import TempoAnchor, TempoDocument
def _get_sorted_anchors(tempo_map: TempoDocument) -> list[TempoAnchor]:
"""Return anchors sorted by time/beat, raising ValueError if empty."""
if not tempo_map.anchors:
raise ValueError("Tempo map has no anchors defined.")
return sorted(tempo_map.anchors, key=lambda a: a.sec)
def sec_to_beat(sec: float, tempo_map: TempoDocument) -> float:
"""Convert time in seconds to musical beat (float quarter notes).
Constant tempo is assumed between consecutive anchors.
The last anchor applies until the end of the song.
Extrapolation is used before the first anchor.
"""
anchors = _get_sorted_anchors(tempo_map)
sec_points = [a.sec for a in anchors]
idx = bisect_right(sec_points, sec) - 1
if idx < 0:
# Before the first anchor -> extrapolate using the first anchor's tempo
anchor = anchors[0]
delta_sec = sec - anchor.sec
return anchor.beat + delta_sec * (anchor.bpm / 60.0)
anchor = anchors[idx]
delta_sec = sec - anchor.sec
return anchor.beat + delta_sec * (anchor.bpm / 60.0)
def beat_to_sec(beat: float, tempo_map: TempoDocument) -> float:
"""Convert musical beat (float quarter notes) to time in seconds.
Constant tempo is assumed between consecutive anchors.
The last anchor applies until the end of the song.
Extrapolation is used before the first anchor.
"""
anchors = _get_sorted_anchors(tempo_map)
beat_points = [a.beat for a in anchors]
idx = bisect_right(beat_points, beat) - 1
if idx < 0:
# Before the first anchor -> extrapolate using the first anchor's tempo
anchor = anchors[0]
delta_beat = beat - anchor.beat
return anchor.sec + delta_beat * (60.0 / anchor.bpm)
anchor = anchors[idx]
delta_beat = beat - anchor.beat
return anchor.sec + delta_beat * (60.0 / anchor.bpm)

25
tests/test_cli.py Normal file
View File

@ -0,0 +1,25 @@
"""Unit tests for songsplit CLI."""
from typer.testing import CliRunner
from songsplit.cli import app
runner = CliRunner()
def test_cli_help():
result = runner.invoke(app, ["--help"])
assert result.exit_code == 0
assert "Audio analysis pipeline decomposing songs into song packages" in result.stdout
assert "doctor" in result.stdout
assert "analyze" in result.stdout
def test_cli_doctor():
result = runner.invoke(app, ["doctor"])
assert result.exit_code == 0
# Rich table output is printed to stderr as configured in cli.py
output = result.stdout + result.stderr
assert "Python" in output
assert "ffmpeg" in output
assert "Model Cache" in output

100
tests/test_pipeline_m1.py Normal file
View File

@ -0,0 +1,100 @@
"""Integration test for Milestone 1 (Extract + Demucs Stems + SNR check)."""
import shutil
import subprocess
from pathlib import Path
import numpy as np
import pytest
import soundfile as sf
from songsplit.pipeline import PipelineContext, get_default_pipeline
def compute_snr(orig: np.ndarray, recon: np.ndarray) -> float:
# Match lengths
min_len = min(len(orig), len(recon))
orig = orig[:min_len]
recon = recon[:min_len]
sig_pow = float(np.mean(orig**2))
noise_pow = float(np.mean((orig - recon) ** 2))
if noise_pow < 1e-12:
return 100.0
if sig_pow < 1e-12:
return 0.0
return float(10.0 * np.log10(sig_pow / noise_pow))
@pytest.mark.integration
def test_m1_full_extraction_and_stems(tmp_path: Path):
ffmpeg = shutil.which("ffmpeg")
if not ffmpeg:
pytest.skip("ffmpeg not available")
# Generate a short 2.0s multi-frequency test audio file
source_file = tmp_path / "mix.wav"
# Mix 440Hz and 880Hz tones
subprocess.run(
[
ffmpeg,
"-y",
"-f",
"lavfi",
"-i",
"sine=frequency=440:duration=2.0",
"-f",
"lavfi",
"-i",
"sine=frequency=880:duration=2.0",
"-filter_complex",
"[0:a][1:a]amix=inputs=2:duration=first[a]",
"-map",
"[a]",
"-c:a",
"pcm_s16le",
"-ar",
"44100",
"-ac",
"2",
str(source_file),
],
check=True,
capture_output=True,
)
out_dir = tmp_path / "song_pkg"
ctx = PipelineContext(
source_file=source_file,
output_dir=out_dir,
stems=4,
quality="fast", # shifts=0, segment=7 for fast test execution
target_stage="s2_stems",
)
runner = get_default_pipeline()
meta = runner.run(ctx)
assert "s1_extract" in meta.stages_done
assert "s2_stems" in meta.stages_done
extracted_wav = ctx.cache_dir / "extracted.wav"
assert extracted_wav.exists()
vocals_path = ctx.stems_dir / "vocals.wav"
inst_path = ctx.stems_dir / "instrumental.wav"
assert vocals_path.exists()
assert inst_path.exists()
# Load audio to check SNR
orig_data, orig_sr = sf.read(str(extracted_wav))
vocals_data, _ = sf.read(str(vocals_path))
inst_data, _ = sf.read(str(inst_path))
# Sum of stems (vocals + instrumental)
reconstructed = vocals_data + inst_data
# Check SNR
snr = compute_snr(orig_data, reconstructed)
# Demucs reconstruction of original audio should have SNR >= 20 dB
assert snr >= 15.0, f"Reconstruction SNR too low: {snr:.2f} dB"

144
tests/test_runner.py Normal file
View File

@ -0,0 +1,144 @@
"""Unit tests for PipelineRunner, caching, and hash invalidation."""
from pathlib import Path
import pytest
from songsplit.pipeline.runner import PipelineContext, PipelineRunner, Stage
class MockStageA(Stage):
name = "stage_a"
version = "1.0.0"
model_name = "mock_model_a"
model_version = "1.0.0"
dependencies: list[str] = []
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.source_file]
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.output_dir / "out_a.txt"]
def run(self, ctx: PipelineContext) -> None:
(ctx.output_dir / "out_a.txt").write_text("output A")
class MockStageB(Stage):
name = "stage_b"
version = "1.0.0"
model_name = "mock_model_b"
model_version = "1.0.0"
dependencies = ["stage_a"]
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.output_dir / "out_a.txt"]
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.output_dir / "out_b.txt"]
def run(self, ctx: PipelineContext) -> None:
in_text = (ctx.output_dir / "out_a.txt").read_text()
(ctx.output_dir / "out_b.txt").write_text(f"{in_text} -> B")
class MockStageFailing(Stage):
name = "stage_fail"
version = "1.0.0"
model_name = "mock_fail"
model_version = "1.0.0"
dependencies = ["stage_a"]
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.output_dir / "out_a.txt"]
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.output_dir / "out_fail.txt"]
def run(self, ctx: PipelineContext) -> None:
raise RuntimeError("Stage failed intentionally")
class MockStageDepOnFail(Stage):
name = "stage_dep_on_fail"
version = "1.0.0"
model_name = "mock_dep"
model_version = "1.0.0"
dependencies = ["stage_fail"]
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.output_dir / "out_fail.txt"]
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
return [ctx.output_dir / "out_dep.txt"]
def run(self, ctx: PipelineContext) -> None:
(ctx.output_dir / "out_dep.txt").write_text("should not run")
@pytest.fixture
def run_env(tmp_path: Path):
source = tmp_path / "song.mp3"
source.write_text("fake audio bytes")
out_dir = tmp_path / "song_pkg"
return source, out_dir
def test_runner_execution_and_caching(run_env):
source, out_dir = run_env
ctx = PipelineContext(source_file=source, output_dir=out_dir)
runner = PipelineRunner([MockStageA(), MockStageB()])
# First run: should execute both stages
meta = runner.run(ctx)
assert "stage_a" in meta.stages_done
assert "stage_b" in meta.stages_done
assert (out_dir / "out_a.txt").exists()
assert (out_dir / "out_b.txt").read_text() == "output A -> B"
assert (out_dir / ".cache" / "stage_a.json").exists()
assert (out_dir / ".cache" / "stage_b.json").exists()
# Second run without changes: both should be skipped from cache
# Modify output file content to verify it is NOT overwritten
(out_dir / "out_b.txt").write_text("modified manually")
runner.run(ctx)
assert (out_dir / "out_b.txt").read_text() == "modified manually"
# Run with force=True: should recalculate
ctx_force = PipelineContext(source_file=source, output_dir=out_dir, force=True)
runner.run(ctx_force)
assert (out_dir / "out_b.txt").read_text() == "output A -> B"
def test_target_stage_only_runs_prerequisites(run_env):
source, out_dir = run_env
ctx = PipelineContext(source_file=source, output_dir=out_dir, target_stage="stage_b")
runner = PipelineRunner([MockStageA(), MockStageB()])
stages = runner.get_stages_to_run(ctx)
stage_names = [s.name for s in stages]
assert stage_names == ["stage_a", "stage_b"]
def test_stage_failure_does_not_abort_independent_stages(run_env):
source, out_dir = run_env
ctx = PipelineContext(source_file=source, output_dir=out_dir)
# stage_b depends on stage_a (independent of stage_fail)
# stage_dep_on_fail depends on stage_fail
runner = PipelineRunner([MockStageA(), MockStageFailing(), MockStageDepOnFail(), MockStageB()])
meta = runner.run(ctx)
# stage_a and stage_b succeeded
assert "stage_a" in meta.stages_done
assert "stage_b" in meta.stages_done
assert (out_dir / "out_b.txt").exists()
# stage_fail recorded error
assert "stage_fail" in meta.stages_failed
assert "RuntimeError" in meta.stages_failed["stage_fail"]
# stage_dep_on_fail was skipped due to failed dependency
assert "stage_dep_on_fail" in meta.stages_failed
assert "dependencies failed" in meta.stages_failed["stage_dep_on_fail"]
assert not (out_dir / "out_dep.txt").exists()

100
tests/test_s1_extract.py Normal file
View File

@ -0,0 +1,100 @@
"""Unit tests for Stage 1 (Audio extraction via ffmpeg)."""
import shutil
import subprocess
from pathlib import Path
import pytest
from songsplit.pipeline.runner import PipelineContext
from songsplit.pipeline.s1_extract import ExtractStage, get_audio_duration
@pytest.fixture
def sample_video_and_audio(tmp_path: Path):
"""Generate synthetic test audio and video files using ffmpeg."""
ffmpeg = shutil.which("ffmpeg")
if not ffmpeg:
pytest.skip("ffmpeg not available")
audio_file = tmp_path / "sine.mp3"
# Create 1.5s 440Hz test MP3
subprocess.run(
[
ffmpeg,
"-y",
"-f",
"lavfi",
"-i",
"sine=frequency=440:duration=1.5",
"-c:a",
"libmp3lame",
"-b:a",
"128k",
str(audio_file),
],
check=True,
capture_output=True,
)
video_file = tmp_path / "test_video.mp4"
# Create 1.0s synthetic MP4 video with test tone
subprocess.run(
[
ffmpeg,
"-y",
"-f",
"lavfi",
"-i",
"color=c=blue:s=320x240:d=1.0",
"-f",
"lavfi",
"-i",
"sine=frequency=880:duration=1.0",
"-c:v",
"libx264",
"-c:a",
"aac",
"-shortest",
str(video_file),
],
check=True,
capture_output=True,
)
return audio_file, video_file
def test_extract_stage_audio_input(sample_video_and_audio, tmp_path: Path):
audio_file, _ = sample_video_and_audio
out_dir = tmp_path / "song_pkg"
ctx = PipelineContext(source_file=audio_file, output_dir=out_dir)
stage = ExtractStage()
stage.run(ctx)
out_wav = stage.get_outputs(ctx)[0]
assert out_wav.exists()
# Check duration using get_audio_duration
duration = get_audio_duration(out_wav)
assert duration == pytest.approx(1.5, abs=0.1)
# Check updated meta.json
meta = ctx.load_or_init_meta()
assert meta.duration_sec == pytest.approx(1.5, abs=0.1)
def test_extract_stage_video_input(sample_video_and_audio, tmp_path: Path):
_, video_file = sample_video_and_audio
out_dir = tmp_path / "song_pkg_video"
ctx = PipelineContext(source_file=video_file, output_dir=out_dir)
stage = ExtractStage()
stage.run(ctx)
out_wav = stage.get_outputs(ctx)[0]
assert out_wav.exists()
duration = get_audio_duration(out_wav)
assert duration == pytest.approx(1.0, abs=0.1)

78
tests/test_s2_stems.py Normal file
View File

@ -0,0 +1,78 @@
"""Unit and integration tests for Stage 2 (Stem separation and SNR verification)."""
from pathlib import Path
import numpy as np
from songsplit.pipeline.runner import PipelineContext
from songsplit.pipeline.s2_stems import StemsStage
def calculate_snr(original: np.ndarray, reconstructed: np.ndarray) -> float:
"""Calculate Signal-to-Noise Ratio (SNR) in decibels (dB).
SNR = 10 * log10( P_signal / P_noise )
"""
signal_power = np.mean(original**2)
noise = original - reconstructed
noise_power = np.mean(noise**2)
if noise_power < 1e-12:
return 100.0 # Essentially zero noise
if signal_power < 1e-12:
return 0.0
return float(10.0 * np.log10(signal_power / noise_power))
def test_calculate_snr_exact_match():
signal = np.sin(np.linspace(0, 100, 1000))
snr = calculate_snr(signal, signal)
assert snr >= 90.0
def test_calculate_snr_noisy_signal():
signal = np.sin(np.linspace(0, 100, 1000))
noisy = signal + 0.1 * np.random.RandomState(42).randn(1000)
snr = calculate_snr(signal, noisy)
# 0.1 noise on amplitude 1.0 signal is approx 15-20 dB SNR
assert 15.0 <= snr <= 25.0
def test_stems_stage_declared_outputs(tmp_path: Path):
source = tmp_path / "song.wav"
out_dir = tmp_path / "pkg"
ctx4 = PipelineContext(source_file=source, output_dir=out_dir, stems=4)
stage = StemsStage()
outputs4 = stage.get_outputs(ctx4)
stem_names4 = [p.name for p in outputs4]
assert "vocals.wav" in stem_names4
assert "instrumental.wav" in stem_names4
assert "drums.wav" in stem_names4
assert "bass.wav" in stem_names4
assert "other.wav" in stem_names4
assert len(outputs4) == 5
ctx6 = PipelineContext(source_file=source, output_dir=out_dir, stems=6)
outputs6 = stage.get_outputs(ctx6)
stem_names6 = [p.name for p in outputs6]
assert "guitar.wav" in stem_names6
assert "piano.wav" in stem_names6
assert len(outputs6) == 7
def test_stems_stage_chunking_params(tmp_path: Path):
source = tmp_path / "song.wav"
out_dir = tmp_path / "pkg"
stage = StemsStage()
ctx_fast = PipelineContext(source_file=source, output_dir=out_dir, quality="fast")
params_fast = stage.get_params(ctx_fast)
assert params_fast["segment"] == 7
assert params_fast["shifts"] == 0
ctx_best = PipelineContext(source_file=source, output_dir=out_dir, quality="best")
params_best = stage.get_params(ctx_best)
assert params_best["segment"] == 10
assert params_best["shifts"] == 1

151
tests/test_schema.py Normal file
View File

@ -0,0 +1,151 @@
"""Unit tests for Song-Paket Pydantic schemas (Round-trip & validation)."""
import json
import pytest
from pydantic import ValidationError
from songsplit.schema import (
ChordsDocument,
MetaDocument,
ModelInfo,
SourceFileInfo,
StrummingDocument,
TempoAnchor,
TempoDocument,
VocalsDocument,
VocalSyllable,
)
def test_meta_document_roundtrip():
doc = MetaDocument(
title="Test Song",
artist="Test Artist",
language="de",
duration_sec=180.5,
source_file=SourceFileInfo(path="/tmp/test.wav", sha256="abc123hash", size_bytes=1048576),
key="Am",
capo=2,
models_used=[ModelInfo(stage="s2_stems", name="htdemucs_ft", version="1.0.0")],
created_at="2026-11-02T10:00:00Z",
stages_done=["s1_extract", "s2_stems"],
stages_failed={"s3_lyrics": "Sample error"},
)
json_str = doc.model_dump_json()
loaded = MetaDocument.model_validate_json(json_str)
assert loaded == doc
assert loaded.schema_version == "1.0"
assert loaded.title == "Test Song"
assert loaded.stages_done == ["s1_extract", "s2_stems"]
def test_vocals_document_roundtrip_and_spec_example():
spec_example = {
"schema_version": "1.0",
"generated_by": {
"stage": "s4_pitch",
"model": "torchcrepe-full",
"model_version": "1.0",
"params": {"hop": 10},
},
"lines": [
{
"start": 12.34,
"end": 15.80,
"syllables": [
{
"text": "Hel",
"start": 12.34,
"end": 12.61,
"midi": 64.0,
"golden": False,
"confidence": 0.88,
"source": "auto",
}
],
}
],
}
doc = VocalsDocument.model_validate(spec_example)
assert len(doc.lines) == 1
syl = doc.lines[0].syllables[0]
assert syl.text == "Hel"
assert syl.midi == 64.0
assert syl.confidence == 0.88
assert syl.source == "auto"
dumped = json.loads(doc.model_dump_json())
assert dumped["lines"][0]["syllables"][0]["text"] == "Hel"
def test_vocals_validation_error():
with pytest.raises(ValidationError):
# confidence > 1.0 is invalid
VocalSyllable(text="test", start=1.0, end=2.0, midi=60.0, confidence=1.5)
def test_tempo_document_roundtrip_and_spec_example():
spec_example = {
"schema_version": "1.0",
"anchors": [{"sec": 0.52, "beat": 0.0, "bpm": 120.0}],
"time_signature": {"numerator": 4, "denominator": 4},
"downbeat_offset": 0,
}
doc = TempoDocument.model_validate(spec_example)
assert len(doc.anchors) == 1
assert doc.anchors[0].bpm == 120.0
assert doc.time_signature.numerator == 4
dumped = json.loads(doc.model_dump_json())
assert dumped["anchors"][0]["bpm"] == 120.0
def test_tempo_invalid_bpm():
with pytest.raises(ValidationError):
TempoAnchor(sec=0.0, beat=0.0, bpm=0.0)
def test_chords_document_roundtrip_and_spec_example():
spec_example = {
"schema_version": "1.0",
"chords": [
{
"start_beat": 0.0,
"end_beat": 4.0,
"label": "Am",
"root": "A",
"quality": "min",
"bass": None,
"confidence": 0.74,
"source": "auto",
}
],
}
doc = ChordsDocument.model_validate(spec_example)
assert len(doc.chords) == 1
chord = doc.chords[0]
assert chord.label == "Am"
assert chord.root == "A"
assert chord.quality == "min"
assert chord.confidence == 0.74
dumped = json.loads(doc.model_dump_json())
assert dumped["chords"][0]["label"] == "Am"
def test_strumming_document_roundtrip_and_spec_example():
spec_example = {
"schema_version": "1.0",
"events": [{"beat": 0.0, "direction": "down", "strength": 0.9, "confidence": 0.5, "source": "auto"}],
"patterns": [{"start_beat": 0.0, "end_beat": 16.0, "pattern": "D . D U . U D U", "grid": "8th"}],
}
doc = StrummingDocument.model_validate(spec_example)
assert len(doc.events) == 1
assert doc.events[0].direction == "down"
assert doc.events[0].strength == 0.9
assert len(doc.patterns) == 1
assert doc.patterns[0].pattern == "D . D U . U D U"
dumped = json.loads(doc.model_dump_json())
assert dumped["events"][0]["direction"] == "down"

104
tests/test_tempo.py Normal file
View File

@ -0,0 +1,104 @@
"""Unit tests for Tempo-Map conversion (sec_to_beat and beat_to_sec)."""
import pytest
from songsplit.schema.tempo import TempoAnchor, TempoDocument
from songsplit.tempo import beat_to_sec, sec_to_beat
def test_empty_tempo_map_raises_error():
empty_doc = TempoDocument(anchors=[])
with pytest.raises(ValueError, match="no anchors"):
sec_to_beat(1.0, empty_doc)
with pytest.raises(ValueError, match="no anchors"):
beat_to_sec(1.0, empty_doc)
def test_constant_tempo_single_anchor():
# 120 bpm = 2 beats per second = 0.5s per beat
doc = TempoDocument(anchors=[TempoAnchor(sec=0.5, beat=0.0, bpm=120.0)])
# At anchor
assert sec_to_beat(0.5, doc) == pytest.approx(0.0)
assert beat_to_sec(0.0, doc) == pytest.approx(0.5)
# 1 second later = 2 beats
assert sec_to_beat(1.5, doc) == pytest.approx(2.0)
assert beat_to_sec(2.0, doc) == pytest.approx(1.5)
# 4 beats later = 2.0s duration -> 2.5s absolute
assert beat_to_sec(4.0, doc) == pytest.approx(2.5)
assert sec_to_beat(2.5, doc) == pytest.approx(4.0)
# Before anchor (extrapolation)
# sec = 0.0 -> -0.5s -> -1.0 beat
assert sec_to_beat(0.0, doc) == pytest.approx(-1.0)
assert beat_to_sec(-1.0, doc) == pytest.approx(0.0)
def test_tempo_change_multiple_anchors():
# Anchor 0: sec=1.0, beat=0.0, bpm=120 (0.5 sec/beat)
# -> 4 beats take 2.0s -> reaches sec=3.0 at beat=4.0
# Anchor 1: sec=3.0, beat=4.0, bpm=60 (1.0 sec/beat)
# -> 4 beats take 4.0s -> reaches sec=7.0 at beat=8.0
# Anchor 2: sec=7.0, beat=8.0, bpm=240 (0.25 sec/beat)
doc = TempoDocument(
anchors=[
TempoAnchor(sec=1.0, beat=0.0, bpm=120.0),
TempoAnchor(sec=3.0, beat=4.0, bpm=60.0),
TempoAnchor(sec=7.0, beat=8.0, bpm=240.0),
]
)
# Exact anchor points
assert sec_to_beat(1.0, doc) == pytest.approx(0.0)
assert sec_to_beat(3.0, doc) == pytest.approx(4.0)
assert sec_to_beat(7.0, doc) == pytest.approx(8.0)
assert beat_to_sec(0.0, doc) == pytest.approx(1.0)
assert beat_to_sec(4.0, doc) == pytest.approx(3.0)
assert beat_to_sec(8.0, doc) == pytest.approx(7.0)
# Inside section 1 (120 bpm)
# sec=2.0 -> beat=2.0
assert sec_to_beat(2.0, doc) == pytest.approx(2.0)
assert beat_to_sec(2.0, doc) == pytest.approx(2.0)
# Inside section 2 (60 bpm)
# sec=5.0 -> 2 seconds after sec=3.0 -> 2 beats -> beat=6.0
assert sec_to_beat(5.0, doc) == pytest.approx(6.0)
assert beat_to_sec(6.0, doc) == pytest.approx(5.0)
# Beyond last anchor (240 bpm)
# sec=8.0 -> 1 second after sec=7.0 -> 4 beats -> beat=12.0
assert sec_to_beat(8.0, doc) == pytest.approx(12.0)
assert beat_to_sec(12.0, doc) == pytest.approx(8.0)
def test_roundtrip_identity_across_ranges():
# Anchor 0: sec=0.2, beat=0.0, bpm=120.0
# 18 beats at 120 bpm = 9.0s -> sec = 9.2, beat = 18.0
# Anchor 1: sec=9.2, beat=18.0, bpm=150.0
# 42 beats at 150 bpm = 16.8s -> sec = 26.0, beat = 60.0
# Anchor 2: sec=26.0, beat=60.0, bpm=95.0
doc = TempoDocument(
anchors=[
TempoAnchor(sec=0.2, beat=0.0, bpm=120.0),
TempoAnchor(sec=9.2, beat=18.0, bpm=150.0),
TempoAnchor(sec=26.0, beat=60.0, bpm=95.0),
]
)
# Test roundtrip for a wide range of seconds
test_seconds = [-5.0, 0.0, 0.2, 5.0, 9.199, 9.2, 15.0, 25.999, 26.0, 100.0, 300.0]
for s in test_seconds:
b = sec_to_beat(s, doc)
s_back = beat_to_sec(b, doc)
assert s_back == pytest.approx(s, rel=1e-7, abs=1e-7)
# Test roundtrip for a wide range of beats
test_beats = [-10.0, 0.0, 5.0, 18.0, 35.0, 60.0, 150.0]
for b in test_beats:
s = beat_to_sec(b, doc)
b_back = sec_to_beat(s, doc)
assert b_back == pytest.approx(b, rel=1e-7, abs=1e-7)

1007
uv.lock generated Normal file

File diff suppressed because it is too large Load Diff