feat(pipeline): implement stage runner, cache, cli, and doctor command
This commit is contained in:
3
src/songsplit/__init__.py
Normal file
3
src/songsplit/__init__.py
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
"""songsplit: Audio analysis pipeline for song package decomposition."""
|
||||||
|
|
||||||
|
__version__ = "0.1.0"
|
||||||
170
src/songsplit/cli.py
Normal file
170
src/songsplit/cli.py
Normal 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
43
src/songsplit/config.py
Normal 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()
|
||||||
6
src/songsplit/eval/__init__.py
Normal file
6
src/songsplit/eval/__init__.py
Normal 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"]
|
||||||
8
src/songsplit/eval/metrics.py
Normal file
8
src/songsplit/eval/metrics.py
Normal 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.")
|
||||||
8
src/songsplit/eval/run_eval.py
Normal file
8
src/songsplit/eval/run_eval.py
Normal 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.")
|
||||||
5
src/songsplit/export/__init__.py
Normal file
5
src/songsplit/export/__init__.py
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
"""Export modules."""
|
||||||
|
|
||||||
|
from songsplit.export.ultrastar import export_ultrastar
|
||||||
|
|
||||||
|
__all__ = ["export_ultrastar"]
|
||||||
8
src/songsplit/export/ultrastar.py
Normal file
8
src/songsplit/export/ultrastar.py
Normal 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.")
|
||||||
40
src/songsplit/pipeline/__init__.py
Normal file
40
src/songsplit/pipeline/__init__.py
Normal 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",
|
||||||
|
]
|
||||||
267
src/songsplit/pipeline/runner.py
Normal file
267
src/songsplit/pipeline/runner.py
Normal 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
|
||||||
27
src/songsplit/pipeline/s1_extract.py
Normal file
27
src/songsplit/pipeline/s1_extract.py
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
"""Stage 1: Extract audio to 44.1 kHz stereo WAV using ffmpeg."""
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from songsplit.pipeline.runner import PipelineContext, Stage
|
||||||
|
|
||||||
|
|
||||||
|
class ExtractStage(Stage):
|
||||||
|
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.output_dir / "extracted.wav"]
|
||||||
|
|
||||||
|
def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
|
||||||
|
return {"sample_rate": 44100, "channels": 2}
|
||||||
|
|
||||||
|
def run(self, ctx: PipelineContext) -> None:
|
||||||
|
# Implementation in M1
|
||||||
|
raise NotImplementedError("Stage s1_extract will be implemented in M1.")
|
||||||
30
src/songsplit/pipeline/s2_stems.py
Normal file
30
src/songsplit/pipeline/s2_stems.py
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
"""Stage 2: Stem separation using Demucs."""
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from songsplit.pipeline.runner import PipelineContext, Stage
|
||||||
|
|
||||||
|
|
||||||
|
class StemsStage(Stage):
|
||||||
|
name = "s2_stems"
|
||||||
|
version = "1.0.0"
|
||||||
|
model_name = "htdemucs_ft"
|
||||||
|
model_version = "1.0.0"
|
||||||
|
dependencies = ["s1_extract"]
|
||||||
|
|
||||||
|
def get_inputs(self, ctx: PipelineContext) -> list[Path]:
|
||||||
|
return [ctx.output_dir / "extracted.wav"]
|
||||||
|
|
||||||
|
def get_outputs(self, ctx: PipelineContext) -> list[Path]:
|
||||||
|
return [
|
||||||
|
ctx.stems_dir / "vocals.wav",
|
||||||
|
ctx.stems_dir / "instrumental.wav",
|
||||||
|
]
|
||||||
|
|
||||||
|
def get_params(self, ctx: PipelineContext) -> dict[str, Any]:
|
||||||
|
return {"stems": ctx.stems, "quality": ctx.quality}
|
||||||
|
|
||||||
|
def run(self, ctx: PipelineContext) -> None:
|
||||||
|
# Implementation in M1
|
||||||
|
raise NotImplementedError("Stage s2_stems will be implemented in M1.")
|
||||||
27
src/songsplit/pipeline/s3_lyrics.py
Normal file
27
src/songsplit/pipeline/s3_lyrics.py
Normal 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.")
|
||||||
30
src/songsplit/pipeline/s4_pitch.py
Normal file
30
src/songsplit/pipeline/s4_pitch.py
Normal 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.")
|
||||||
27
src/songsplit/pipeline/s5_tempo.py
Normal file
27
src/songsplit/pipeline/s5_tempo.py
Normal 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.")
|
||||||
30
src/songsplit/pipeline/s6_chords.py
Normal file
30
src/songsplit/pipeline/s6_chords.py
Normal 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.")
|
||||||
30
src/songsplit/pipeline/s7_strumming.py
Normal file
30
src/songsplit/pipeline/s7_strumming.py
Normal 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.")
|
||||||
Reference in New Issue
Block a user