Consulawtech's picture
Claude Opus 5.5 (1M context)
Port long-audio reliability fixes from the HF Space (see Space commit eb4ae44)
32c229b
Raw History Blame Contribute Delete
8.54 kB
"""
Long audio chunking module
Author: Maaldeens
License: MIT
"""
import numpy as np
import librosa
from typing import List, Tuple
import logging
import re
from difflib import SequenceMatcher
from dataclasses import dataclass
logger = logging.getLogger(__name__)
@dataclass
class AudioChunk:
"""Audio chunk with metadata"""
audio: np.ndarray
start_time: float
end_time: float
index: int
overlap_with_prev: bool = False
class AudioChunker:
"""
Splits long audio files into manageable chunks
Maintains context through overlap
"""
def __init__(self, chunk_duration: int = 30, overlap_duration: int = 2,
target_sr: int = 16000):
self.chunk_samples = chunk_duration * target_sr
self.overlap_samples = overlap_duration * target_sr
self.target_sr = target_sr
self.chunk_duration = chunk_duration
self.overlap_duration = overlap_duration
def should_chunk(self, duration: float) -> bool:
"""Determine if audio needs chunking"""
return duration > self.chunk_duration
def create_chunks(self, audio: np.ndarray, sample_rate: int) -> List[AudioChunk]:
"""Split audio into overlapping chunks"""
if sample_rate != self.target_sr:
audio = librosa.resample(audio, orig_sr=sample_rate, target_sr=self.target_sr)
total_samples = len(audio)
if total_samples <= self.chunk_samples:
return [
AudioChunk(
audio=audio,
start_time=0,
end_time=total_samples / self.target_sr,
index=0,
overlap_with_prev=False
)
]
chunks = []
step = self.chunk_samples - self.overlap_samples
num_chunks = (total_samples - self.overlap_samples) // step + 1
for i in range(num_chunks):
start = i * step
end = min(start + self.chunk_samples, total_samples)
chunk_audio = audio[start:end]
# Drop only truly empty slivers (< 1 second).
# Previously used chunk_samples//2 (15 s) which silently discarded
# up to 14 s of trailing audio for recordings between 30–43 s.
if len(chunk_audio) < self.target_sr:
break
chunk = AudioChunk(
audio=chunk_audio,
start_time=start / self.target_sr,
end_time=end / self.target_sr,
index=i,
overlap_with_prev=(i > 0)
)
chunks.append(chunk)
logger.info(f"Created chunk {i}: {chunk.start_time:.1f}s - {chunk.end_time:.1f}s")
return chunks
def merge_chunk_results(self, chunk_results: List[Tuple[AudioChunk, dict]]) -> dict:
"""Merge transcription results from overlapping chunks.
Neighbouring chunks share `overlap_duration` seconds of audio, so both
transcribe it. The join is found by TEXT, not time: the longest run of
words shared by the end of the merged transcript and the start of the
next chunk marks the same speech, so the earlier chunk keeps everything
up to the end of that run and the next chunk contributes only what
follows it. Timestamps alone were not reliable enough: near the start
of a chunk they drifted by ~15 s on long recordings, which both
duplicated sentences and dropped others (7.6% WER on a 60 min test,
mostly insertions). If no solid match exists (e.g. silence across the
boundary) it falls back to a time handover near the end of the overlap,
where the earlier chunk heard the audio in context.
"""
if not chunk_results:
return {"text": "", "segments": [], "chunks": 0}
merged: List[dict] = []
for i, (chunk, result) in enumerate(chunk_results):
segs = []
for seg in result.get("segments", []):
seg_start = seg.get("start", 0) + chunk.start_time
seg_end = seg.get("end", 0) + chunk.start_time
# Whisper can hallucinate end < start on difficult audio.
# Clamp to minimum 0.5 s so merge/diarization don't break.
if seg_end < seg_start:
seg_end = seg_start + 0.5
segs.append({**seg, "start": seg_start, "end": seg_end})
if i == 0 or not merged:
merged.extend(segs)
continue
merged, segs = self._join(merged, segs, chunk)
merged.extend(segs)
merged = [s for s in merged if (s.get("text") or "").strip()]
merged.sort(key=lambda x: x.get("start", 0))
for idx, seg in enumerate(merged):
seg["id"] = idx
return {
"text": " ".join(s["text"].strip() for s in merged),
"segments": merged,
"chunks": len(chunk_results)
}
# Minimum shared words to trust a text match. Stock phrases ("so carried",
# "thank you very much") are shorter than this; real overlap is ~30 s of
# speech, typically dozens of words.
_MIN_MATCH_WORDS = 6
@staticmethod
def _tokens(text: str) -> List[Tuple[str, str]]:
"""(original token, normalised token) pairs; punctuation-only tokens
keep an empty normalised form so slicing stays aligned."""
out = []
for tok in (text or "").split():
out.append((tok, re.sub(r"[^a-z0-9']", "", tok.lower())))
return out
def _join(self, merged: List[dict], segs: List[dict], chunk: "AudioChunk"):
"""Trim the end of `merged` and the start of `segs` so the overlap
appears once. Returns (merged, segs)."""
overlap_end = chunk.start_time + self.overlap_duration
# Earlier chunk's view of the overlap (plus a little slack for drift).
tail_ids = [k for k, s in enumerate(merged) if s["end"] > chunk.start_time - 5]
# Next chunk's view of it (slack for the late-timestamp drift).
head_ids = [j for j, s in enumerate(segs) if s["start"] < overlap_end + 20]
tail_words = [] # (merged index, token position, normalised word)
for k in tail_ids:
for p, (_, n) in enumerate(self._tokens(merged[k]["text"])):
if n:
tail_words.append((k, p, n))
head_words = []
for j in head_ids:
for p, (_, n) in enumerate(self._tokens(segs[j]["text"])):
if n:
head_words.append((j, p, n))
if tail_words and head_words:
m = SequenceMatcher(
None, [w for _, _, w in tail_words], [w for _, _, w in head_words], autojunk=False
).find_longest_match(0, len(tail_words), 0, len(head_words))
if m.size >= self._MIN_MATCH_WORDS:
k_end, p_end, _ = tail_words[m.a + m.size - 1]
j_end, q_end, _ = head_words[m.b + m.size - 1]
# Earlier chunk: keep through the end of the matched run; its
# words after that are the cut-off edge of its audio.
kept_tail = self._tokens(merged[k_end]["text"])[: p_end + 1]
merged = merged[:k_end] + [{**merged[k_end], "text": " ".join(t for t, _ in kept_tail)}]
# Next chunk: drop everything up to and including the match.
rest = self._tokens(segs[j_end]["text"])[q_end + 1:]
new_segs = []
if rest:
new_segs.append({**segs[j_end], "text": " ".join(t for t, _ in rest)})
new_segs.extend(segs[j_end + 1:])
# Next-chunk timestamps can run late near its start; keep the
# timeline monotonic so ordering and diarization stay sane.
floor = merged[-1]["end"]
for s in new_segs:
if s["start"] < floor:
s["start"] = floor
s["end"] = max(s["end"], floor + 0.1)
floor = s["start"]
return merged, new_segs
# Fallback: hand over by time near the end of the overlap.
handover = chunk.start_time + max(self.overlap_duration - 2, self.overlap_duration / 2)
merged = [s for s in merged if s["start"] < handover]
segs = [s for s in segs if s["start"] >= handover]
return merged, segs