"""Typed configuration loading for video_vec2wav2_tokenizer. The configuration is a plain dataclass so it is easy to construct in tests and serialize. ``load_config`` merges, in order of increasing priority: 1. the packaged ``configs/default.yaml`` 2. an optional user supplied YAML file 3. explicit keyword overrides (typically parsed from CLI flags) """ from __future__ import annotations import dataclasses from dataclasses import dataclass, field, fields from pathlib import Path from typing import Any, Optional import yaml _PACKAGE_DEFAULT = Path(__file__).resolve().parent.parent / "configs" / "default.yaml" @dataclass(slots=True) class Config: """Strongly-typed pipeline configuration.""" # Models model_name: str = "facebook/wav2vec2-base-960h" whisper_model: str = "large-v3" # Transcription language: Optional[str] = None device: str = "auto" compute_type: str = "auto" beam_size: int = 5 vad_filter: bool = True # Audio sample_rate: int = 16000 channels: int = 1 audio_format: str = "wav" # Segmentation min_segment_length: float = 1.0 max_segment_length: float = 20.0 segment_padding: float = 0.0 # Speakers default_speaker: str = "speaker_001" speaker_mode: str = "fixed" # fixed | per_video | per_file # Output input_dir: str = "input/videos" output_dir: str = "dataset" features_dir: str = "features" # Performance num_workers: int = 4 batch_size: int = 16 log_level: str = "INFO" # ---- derived path helpers ------------------------------------------------- @property def audio_dir(self) -> Path: """Directory holding the segmented audio clips.""" return Path(self.output_dir) / "audio" @property def metadata_csv(self) -> Path: return Path(self.output_dir) / "metadata.csv" @property def dataset_jsonl(self) -> Path: return Path(self.output_dir) / "dataset.jsonl" @property def tts_metadata_csv(self) -> Path: return Path(self.output_dir) / "tts_metadata.csv" @property def report_json(self) -> Path: return Path(self.output_dir) / "report.json" def to_dict(self) -> dict[str, Any]: return dataclasses.asdict(self) def validate(self) -> None: """Raise ``ValueError`` if the configuration is internally inconsistent.""" if self.sample_rate <= 0: raise ValueError("sample_rate must be positive") if self.channels not in (1, 2): raise ValueError("channels must be 1 or 2") if self.min_segment_length < 0: raise ValueError("min_segment_length must be >= 0") if self.max_segment_length <= self.min_segment_length: raise ValueError("max_segment_length must exceed min_segment_length") if self.device not in ("auto", "cpu", "cuda"): raise ValueError("device must be one of auto|cpu|cuda") if self.speaker_mode not in ("fixed", "per_video", "per_file"): raise ValueError("speaker_mode must be one of fixed|per_video|per_file") if self.num_workers < 1: raise ValueError("num_workers must be >= 1") def _read_yaml(path: Path) -> dict[str, Any]: with path.open("r", encoding="utf-8") as fh: data = yaml.safe_load(fh) or {} if not isinstance(data, dict): raise ValueError(f"Config file {path} must contain a mapping at the top level") return data def _filter_known(data: dict[str, Any]) -> dict[str, Any]: known = {f.name for f in fields(Config)} unknown = set(data) - known if unknown: # Be permissive but informative: ignore unknown keys instead of failing. import warnings warnings.warn(f"Ignoring unknown config keys: {sorted(unknown)}", stacklevel=2) return {k: v for k, v in data.items() if k in known} def load_config( path: Optional[str | Path] = None, *, overrides: Optional[dict[str, Any]] = None, ) -> Config: """Load configuration merging defaults, an optional file, and overrides. Args: path: Optional path to a user YAML config. overrides: Mapping of explicit overrides (``None`` values are ignored so unset CLI flags do not clobber file values). """ merged: dict[str, Any] = {} if _PACKAGE_DEFAULT.exists(): merged.update(_filter_known(_read_yaml(_PACKAGE_DEFAULT))) if path is not None: p = Path(path) if not p.exists(): raise FileNotFoundError(f"Config file not found: {p}") merged.update(_filter_known(_read_yaml(p))) if overrides: merged.update(_filter_known({k: v for k, v in overrides.items() if v is not None})) cfg = Config(**merged) cfg.validate() return cfg