"""Core data models and IO helpers shared across the pipeline.""" from __future__ import annotations import json from dataclasses import dataclass, field, asdict from pathlib import Path from typing import Any, Iterable, Iterator, Optional VIDEO_EXTENSIONS: frozenset[str] = frozenset( {".mp4", ".mkv", ".avi", ".mov", ".webm"} ) @dataclass(slots=True) class Segment: """A single transcribed time span. Serializes to the spec's shape: ``{"start": .., "end": .., "text": ..}``. """ start: float end: float text: str @property def duration(self) -> float: return max(0.0, self.end - self.start) def to_dict(self) -> dict[str, Any]: return {"start": round(self.start, 3), "end": round(self.end, 3), "text": self.text} @classmethod def from_dict(cls, data: dict[str, Any]) -> "Segment": return cls( start=float(data["start"]), end=float(data["end"]), text=str(data["text"]).strip(), ) @dataclass(slots=True) class DatasetEntry: """A finalized dataset row pointing at a clipped audio file.""" audio: str # relative path, e.g. "audio/000001.wav" text: str duration: float speaker: Optional[str] = None language: Optional[str] = None source_video: Optional[str] = None def to_jsonl_dict(self) -> dict[str, Any]: """Match the spec: audio/text/duration (extra keys retained if present).""" row: dict[str, Any] = { "audio": self.audio, "text": self.text, "duration": round(self.duration, 3), } if self.speaker is not None: row["speaker"] = self.speaker if self.language is not None: row["language"] = self.language return row @classmethod def from_dict(cls, data: dict[str, Any]) -> "DatasetEntry": return cls( audio=str(data["audio"]), text=str(data["text"]), duration=float(data["duration"]), speaker=data.get("speaker"), language=data.get("language"), source_video=data.get("source_video"), ) def ensure_dir(path: str | Path) -> Path: """Create ``path`` (and parents) if needed and return it as ``Path``.""" p = Path(path) p.mkdir(parents=True, exist_ok=True) return p def iter_video_files(root: str | Path) -> Iterator[Path]: """Recursively yield supported video files under ``root`` (sorted, stable).""" root_path = Path(root) if not root_path.exists(): raise FileNotFoundError(f"Video directory not found: {root_path}") for path in sorted(root_path.rglob("*")): if path.is_file() and path.suffix.lower() in VIDEO_EXTENSIONS: yield path def write_jsonl(path: str | Path, rows: Iterable[dict[str, Any]]) -> int: """Stream ``rows`` to a JSONL file. Returns the number of rows written.""" ensure_dir(Path(path).parent) count = 0 with Path(path).open("w", encoding="utf-8") as fh: for row in rows: fh.write(json.dumps(row, ensure_ascii=False)) fh.write("\n") count += 1 return count def read_jsonl(path: str | Path) -> Iterator[dict[str, Any]]: """Lazily read a JSONL file, yielding one dict per non-empty line.""" with Path(path).open("r", encoding="utf-8") as fh: for line in fh: line = line.strip() if line: yield json.loads(line) def clip_index_name(index: int, *, width: int = 6, ext: str = "wav") -> str: """Return a zero-padded clip filename, e.g. ``000001.wav``.""" return f"{index:0{width}d}.{ext}"