File size: 3,676 Bytes
de01f6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
"""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}"