268 lines
9.6 KiB
Python
268 lines
9.6 KiB
Python
"""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
|