k9cli's picture
Flatten package contents to repo root
de01f6a verified
Raw
History Blame Contribute Delete
3.94 kB
"""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())