File size: 3,938 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
120
121
"""Cut normalized audio into clips according to transcript timestamps."""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
from typing import Iterable, Optional

import numpy as np

from video_vec2wav2_tokenizer.audio.extractor import load_wav
from video_vec2wav2_tokenizer.utils.io import Segment, ensure_dir
from video_vec2wav2_tokenizer.utils.logging import get_logger

logger = get_logger(__name__)


def normalize_segments(
    segments: Iterable[Segment],
    *,
    min_length: float = 1.0,
    max_length: float = 20.0,
    padding: float = 0.0,
    total_duration: Optional[float] = None,
) -> list[Segment]:
    """Filter and split segments to respect length constraints.

    - Drops segments shorter than ``min_length``.
    - Splits segments longer than ``max_length`` into equal sub-spans (text is
      kept on the first sub-span to avoid duplicating words).
    - Applies symmetric ``padding`` clamped to ``[0, total_duration]``.
    """
    out: list[Segment] = []
    for seg in segments:
        start = max(0.0, seg.start - padding)
        end = seg.end + padding
        if total_duration is not None:
            end = min(end, total_duration)
        if end <= start:
            continue

        length = end - start
        if length < min_length:
            continue

        if length <= max_length:
            out.append(Segment(start=start, end=end, text=seg.text))
            continue

        # Split overly long spans into chunks of <= max_length.
        n_chunks = int(np.ceil(length / max_length))
        chunk = length / n_chunks
        for i in range(n_chunks):
            c_start = start + i * chunk
            c_end = min(end, c_start + chunk)
            text = seg.text if i == 0 else ""
            out.append(Segment(start=c_start, end=c_end, text=text))
    return out


@dataclass(slots=True)
class Segmenter:
    """Slice a WAV file into per-segment clips."""

    sample_rate: int = 16000

    def segment_file(
        self,
        audio_path: str | Path,
        segments: list[Segment],
        output_dir: str | Path,
        *,
        start_index: int = 1,
        index_width: int = 6,
    ) -> list[tuple[Path, Segment]]:
        """Write one WAV clip per segment.

        Returns ``(clip_path, segment)`` pairs. Filenames are zero-padded
        sequential numbers continuing from ``start_index``.
        """
        output_dir = ensure_dir(output_dir)
        samples, sr = load_wav(audio_path, sample_rate=self.sample_rate)
        results: list[tuple[Path, Segment]] = []

        for offset, seg in enumerate(segments):
            idx = start_index + offset
            i0 = int(round(seg.start * sr))
            i1 = int(round(seg.end * sr))
            i0 = max(0, min(i0, samples.shape[0]))
            i1 = max(i0, min(i1, samples.shape[0]))
            clip = samples[i0:i1]
            if clip.size == 0:
                logger.warning("Empty clip for segment %s, skipping", idx)
                continue

            name = f"{idx:0{index_width}d}.wav"
            clip_path = output_dir / name
            _write_wav(clip_path, clip, sr)
            results.append((clip_path, seg))

        logger.info("Wrote %d clips from %s", len(results), Path(audio_path).name)
        return results


def _write_wav(path: Path, samples: np.ndarray, sample_rate: int) -> None:
    """Write float32 samples as 16-bit PCM WAV (soundfile or stdlib fallback)."""
    samples = np.clip(samples, -1.0, 1.0)
    try:
        import soundfile as sf  # type: ignore

        sf.write(str(path), samples, sample_rate, subtype="PCM_16")
    except ImportError:
        import wave

        ints = (samples * 32767.0).astype(np.int16)
        with wave.open(str(path), "wb") as wf:
            wf.setnchannels(1)
            wf.setsampwidth(2)
            wf.setframerate(sample_rate)
            wf.writeframes(ints.tobytes())