Consulawtech Claude Opus 5.5 (1M context) commited on
Commit
eb4ae44
·
1 Parent(s): 2678e3b

Make 30-60 min recordings transcribe reliably and accurately

Browse files

- Long jobs no longer fail at the end over a 'repetition loop': loops are
removed segment by segment and sentence by sentence instead of rejecting
the whole transcript (real meetings repeat phrases like 'all in favour')
- Stop feeding the previous chunk's text as a prompt (Whisper echoed it)
- 5 min blocks decoded in batched 30 s windows on GPU; greedy decoding for
long audio. 25 min meeting: ~19 min -> ~3-5 min; 60 min: ~19 min on T4
- Join overlapping blocks by matching text, with a 35 s overlap; removed the
duplicated/dropped speech at every block boundary
- Per-job model selection under a lock, unload unused models, per-model
batch sizes (large-v3 previously OOM'd the T4)
- Diarization: clear error when the token lacks access, in-memory audio,
device/timing logs
- Report processing_time for long files

Tested: 25.6 min council meeting (6 speakers) and a 60.4 min two-speaker
recording with known script: 5.65% WER, full coverage, no gaps.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Dockerfile CHANGED
@@ -19,6 +19,7 @@ COPY . .
19
  RUN mkdir -p /app/temp /app/model_cache
20
 
21
  ENV MPLBACKEND=Agg
 
22
  ENV HF_HOME=/app/model_cache
23
  ENV GRADIO_ANALYTICS_ENABLED=false
24
  ENV PYTHONPATH=/app
 
19
  RUN mkdir -p /app/temp /app/model_cache
20
 
21
  ENV MPLBACKEND=Agg
22
+ ENV PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
23
  ENV HF_HOME=/app/model_cache
24
  ENV GRADIO_ANALYTICS_ENABLED=false
25
  ENV PYTHONPATH=/app
app.py CHANGED
@@ -10,6 +10,7 @@ import hmac
10
  import io
11
  import json
12
  import os
 
13
  import time
14
  import uuid
15
  import argparse
@@ -1011,24 +1012,99 @@ else:
1011
  return engine.transcribe_bytes(content, filename=filename, **kwargs)
1012
 
1013
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1014
  def _run_transcription_sync(
1015
  jid: str,
1016
  content: bytes,
1017
  filename: str,
1018
- original_model: Optional[str],
1019
  **kwargs,
1020
  ):
1021
  """Sync worker running in ThreadPoolExecutor — returns immediately so 202 is sent."""
1022
  try:
1023
- result = _transcribe_with_engine(content, filename, **kwargs)
 
 
 
 
1024
 
1025
- if _is_repetition_loop(result.text):
1026
- logger.warning(f"Repetition loop detected: {result.text[:80]!r}")
 
 
 
 
 
 
1027
  _upsert_job(
1028
  jid,
1029
  status="error",
1030
  detail=(
1031
- "Transcription failed: the model produced a repetition loop. "
1032
  "Try selecting the correct language manually or a larger model."
1033
  ),
1034
  )
@@ -1103,11 +1179,6 @@ def _run_transcription_sync(
1103
  _upsert_job(jid, status="error", detail=str(e))
1104
  finally:
1105
  _job_progress_cache.pop(jid, None)
1106
- if original_model:
1107
- try:
1108
- engine.set_model(original_model)
1109
- except Exception:
1110
- pass
1111
 
1112
 
1113
  @app.post("/transcribe")
@@ -1158,15 +1229,14 @@ async def transcribe(
1158
  effective_model = _UPGRADE_TARGET
1159
  else:
1160
  logger.info(f"Languages {lang_list} — CPU-only, staying with default model for speed")
1161
- effective_model = effective_model or engine.current_model_key
1162
 
1163
- original_model = None
1164
- if effective_model and effective_model != engine.current_model_key:
1165
- original_model = engine.current_model_key
1166
- try:
1167
- engine.set_model(effective_model)
1168
- except ValueError as e:
1169
- raise HTTPException(status_code=400, detail=str(e))
1170
 
1171
  jid = job_id or str(uuid.uuid4())
1172
  _JOB_SUBMIT_TIMES[jid] = time.time()
@@ -1207,7 +1277,7 @@ async def transcribe(
1207
  jid,
1208
  content,
1209
  file.filename or "audio",
1210
- original_model,
1211
  **transcription_kwargs,
1212
  )
1213
 
 
10
  import io
11
  import json
12
  import os
13
+ import threading
14
  import time
15
  import uuid
16
  import argparse
 
1012
  return engine.transcribe_bytes(content, filename=filename, **kwargs)
1013
 
1014
 
1015
+ # The engine holds one "current model" shared by every job. Switching it at
1016
+ # submit time (as this used to) let a second upload swap the model out from
1017
+ # under a job that was still running. Each job now selects its own model and
1018
+ # runs inside this lock, so concurrent uploads queue instead of colliding.
1019
+ _ENGINE_LOCK = threading.Lock()
1020
+
1021
+
1022
+ def _default_model_key() -> str:
1023
+ return engine.config.get("models", {}).get("default") or engine.current_model_key
1024
+
1025
+
1026
+ def _drop_repetition_segments(segments: list) -> list:
1027
+ """Remove hallucinated loops segment by segment instead of failing the job.
1028
+
1029
+ Long meetings legitimately repeat phrases ("all in favour", the agenda
1030
+ title), so judging the whole transcript at once rejected real 30-60 min
1031
+ recordings after all the work was done. Here only segments that are
1032
+ themselves loops, or the 4th+ consecutive copy of the same text, go.
1033
+ """
1034
+ cleaned = []
1035
+ run_text, run_len = None, 0
1036
+ for seg in segments:
1037
+ text = (seg.get("text") or "").strip()
1038
+ if not text:
1039
+ continue
1040
+ key = text.lower()
1041
+ run_len = run_len + 1 if key == run_text else 1
1042
+ run_text = key
1043
+ if run_len > 3 or _is_repetition_loop(text):
1044
+ logger.info(f"Dropped repeated/looping segment: {text[:60]!r}")
1045
+ continue
1046
+ cleaned.append(seg)
1047
+ return cleaned
1048
+
1049
+
1050
+ _SENTENCE_SPLIT = __import__("re").compile(r"(?<=[.!?])\s+")
1051
+
1052
+
1053
+ def _collapse_repeated_sentences(segments: list) -> list:
1054
+ """Drop a sentence that exactly repeats one of the 3 sentences before it.
1055
+
1056
+ Whisper sometimes loops inside a 30 s window ("X. Y. X. X.") without the
1057
+ whole segment looking like a loop. A person repeating a full 5+ word
1058
+ sentence verbatim within a few sentences is rare, so the copy is
1059
+ removed; short replies ("Yes. Yes.") are left alone.
1060
+ """
1061
+ import re
1062
+ norm = lambda t: " ".join(re.sub(r"[^a-z0-9' ]", " ", t.lower()).split())
1063
+ recent: list = []
1064
+ out = []
1065
+ for seg in segments:
1066
+ kept = []
1067
+ for sentence in _SENTENCE_SPLIT.split((seg.get("text") or "").strip()):
1068
+ key = norm(sentence)
1069
+ if key and key in recent and len(key.split()) >= 5:
1070
+ continue
1071
+ if key:
1072
+ recent = (recent + [key])[-3:]
1073
+ kept.append(sentence)
1074
+ text = " ".join(kept).strip()
1075
+ if text:
1076
+ out.append({**seg, "text": text})
1077
+ return out
1078
+
1079
+
1080
  def _run_transcription_sync(
1081
  jid: str,
1082
  content: bytes,
1083
  filename: str,
1084
+ model_key: Optional[str],
1085
  **kwargs,
1086
  ):
1087
  """Sync worker running in ThreadPoolExecutor — returns immediately so 202 is sent."""
1088
  try:
1089
+ with _ENGINE_LOCK:
1090
+ target_model = model_key or _default_model_key()
1091
+ if target_model != engine.current_model_key:
1092
+ engine.set_model(target_model)
1093
+ result = _transcribe_with_engine(content, filename, **kwargs)
1094
 
1095
+ if result.segments:
1096
+ result.segments = _collapse_repeated_sentences(
1097
+ _drop_repetition_segments(result.segments)
1098
+ )
1099
+ result.text = " ".join((seg.get("text") or "").strip() for seg in result.segments)
1100
+ loop_only = not result.segments and _is_repetition_loop(result.text or "")
1101
+ if loop_only or not (result.text or "").strip():
1102
+ logger.warning(f"No usable speech after loop cleanup: {(result.text or '')[:80]!r}")
1103
  _upsert_job(
1104
  jid,
1105
  status="error",
1106
  detail=(
1107
+ "Transcription failed: no clear speech was recognised. "
1108
  "Try selecting the correct language manually or a larger model."
1109
  ),
1110
  )
 
1179
  _upsert_job(jid, status="error", detail=str(e))
1180
  finally:
1181
  _job_progress_cache.pop(jid, None)
 
 
 
 
 
1182
 
1183
 
1184
  @app.post("/transcribe")
 
1229
  effective_model = _UPGRADE_TARGET
1230
  else:
1231
  logger.info(f"Languages {lang_list} — CPU-only, staying with default model for speed")
1232
+ effective_model = effective_model or _default_model_key()
1233
 
1234
+ # Validate only; the worker switches models under _ENGINE_LOCK.
1235
+ if effective_model and effective_model not in engine.registry.list_available_models():
1236
+ raise HTTPException(
1237
+ status_code=400,
1238
+ detail=f"Model '{effective_model}' not available. Options: {list(engine.registry.list_available_models().keys())}",
1239
+ )
 
1240
 
1241
  jid = job_id or str(uuid.uuid4())
1242
  _JOB_SUBMIT_TIMES[jid] = time.time()
 
1277
  jid,
1278
  content,
1279
  file.filename or "audio",
1280
+ effective_model,
1281
  **transcription_kwargs,
1282
  )
1283
 
config/settings.yaml CHANGED
@@ -11,8 +11,13 @@ audio:
11
  target_dbfs: -20
12
  # Disabled — noisereduce not in requirements; set true only if you add it
13
  noise_reduction: false
14
- chunk_duration_sec: 30
15
- chunk_overlap_sec: 4
 
 
 
 
 
16
 
17
  models:
18
  default: "whisper-large-v3"
@@ -45,3 +50,5 @@ transcription:
45
  task: "transcribe"
46
  return_timestamps: true
47
  beam_size: 5
 
 
 
11
  target_dbfs: -20
12
  # Disabled — noisereduce not in requirements; set true only if you add it
13
  noise_reduction: false
14
+ # 5-minute blocks: each is decoded by the HF pipeline in batched 30 s
15
+ # windows (fast on GPU) and reports progress per block. The overlap is a
16
+ # little over one Whisper window because a block's first window starts
17
+ # mid-sentence and often comes back garbled; the previous block covers it
18
+ # (see AudioChunker.merge_chunk_results).
19
+ chunk_duration_sec: 300
20
+ chunk_overlap_sec: 35
21
 
22
  models:
23
  default: "whisper-large-v3"
 
50
  task: "transcribe"
51
  return_timestamps: true
52
  beam_size: 5
53
+ # Used for recordings long enough to be chunked (> chunk_duration_sec).
54
+ long_audio_beam_size: 1
src/audio_processor/chunker.py CHANGED
@@ -8,6 +8,8 @@ import numpy as np
8
  import librosa
9
  from typing import List, Tuple
10
  import logging
 
 
11
  from dataclasses import dataclass
12
 
13
  logger = logging.getLogger(__name__)
@@ -85,64 +87,114 @@ class AudioChunker:
85
  return chunks
86
 
87
  def merge_chunk_results(self, chunk_results: List[Tuple[AudioChunk, dict]]) -> dict:
88
- """Merge transcription results from chunks"""
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  if not chunk_results:
90
  return {"text": "", "segments": [], "chunks": 0}
91
 
92
- merged_text = []
93
- merged_segments = []
94
-
95
  for i, (chunk, result) in enumerate(chunk_results):
96
- if i == 0:
97
- merged_text.append(result.get("text", ""))
98
- for seg in result.get("segments", []):
99
- seg_start = seg.get("start", 0)
100
- seg_end = seg.get("end", 0)
101
- if seg_end < seg_start:
102
- seg_end = seg_start + 0.5
103
- seg = {**seg, "start": seg_start, "end": seg_end}
104
- merged_segments.append(seg)
105
- else:
106
- # Use the nominal overlap boundary as the dedup cutoff.
107
- # Previously used the previous chunk's last segment .end, which
108
- # drifts when Whisper pushes a timestamp past the chunk boundary,
109
- # causing real speech just after the boundary to be dropped.
110
- cutoff = chunk.start_time + self.overlap_duration
111
 
112
- segments = result.get("segments", [])
113
- trimmed_segments = []
 
 
 
114
 
115
- for seg in segments:
116
- seg_start = seg.get("start", 0) + chunk.start_time
117
- seg_end = seg.get("end", 0) + chunk.start_time
 
 
 
 
 
 
118
 
119
- # Whisper can hallucinate end < start on difficult audio.
120
- # Clamp to minimum 0.5 s so merge/diarization don't break.
121
- if seg_end < seg_start:
122
- seg_end = seg_start + 0.5
123
 
124
- # Keep segment if it starts after the overlap zone (new content)
125
- # OR if it spans the cutoff — a segment that starts inside the
126
- # overlap zone but ends past it has post-cutoff content that
127
- # the previous chunk never saw. Dropping it entirely loses
128
- # everything from the cutoff to seg_end.
129
- if seg_start >= cutoff or seg_end > cutoff:
130
- adjusted_seg = seg.copy()
131
- adjusted_seg["start"] = seg_start
132
- adjusted_seg["end"] = seg_end
133
- trimmed_segments.append(adjusted_seg)
134
 
135
- if trimmed_segments:
136
- chunk_text = " ".join([seg.get("text", "") for seg in trimmed_segments])
137
- merged_text.append(chunk_text)
138
- merged_segments.extend(trimmed_segments)
 
 
 
 
139
 
140
- merged_segments.sort(key=lambda x: x.get("start", 0))
141
- for idx, seg in enumerate(merged_segments):
142
- seg["id"] = idx
 
 
 
 
 
 
 
143
 
144
- return {
145
- "text": " ".join(merged_text),
146
- "segments": merged_segments,
147
- "chunks": len(chunk_results)
148
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  import librosa
9
  from typing import List, Tuple
10
  import logging
11
+ import re
12
+ from difflib import SequenceMatcher
13
  from dataclasses import dataclass
14
 
15
  logger = logging.getLogger(__name__)
 
87
  return chunks
88
 
89
  def merge_chunk_results(self, chunk_results: List[Tuple[AudioChunk, dict]]) -> dict:
90
+ """Merge transcription results from overlapping chunks.
91
+
92
+ Neighbouring chunks share `overlap_duration` seconds of audio, so both
93
+ transcribe it. The join is found by TEXT, not time: the longest run of
94
+ words shared by the end of the merged transcript and the start of the
95
+ next chunk marks the same speech, so the earlier chunk keeps everything
96
+ up to the end of that run and the next chunk contributes only what
97
+ follows it. Timestamps alone were not reliable enough: near the start
98
+ of a chunk they drifted by ~15 s on long recordings, which both
99
+ duplicated sentences and dropped others (7.6% WER on a 60 min test,
100
+ mostly insertions). If no solid match exists (e.g. silence across the
101
+ boundary) it falls back to a time handover near the end of the overlap,
102
+ where the earlier chunk heard the audio in context.
103
+ """
104
  if not chunk_results:
105
  return {"text": "", "segments": [], "chunks": 0}
106
 
107
+ merged: List[dict] = []
 
 
108
  for i, (chunk, result) in enumerate(chunk_results):
109
+ segs = []
110
+ for seg in result.get("segments", []):
111
+ seg_start = seg.get("start", 0) + chunk.start_time
112
+ seg_end = seg.get("end", 0) + chunk.start_time
113
+ # Whisper can hallucinate end < start on difficult audio.
114
+ # Clamp to minimum 0.5 s so merge/diarization don't break.
115
+ if seg_end < seg_start:
116
+ seg_end = seg_start + 0.5
117
+ segs.append({**seg, "start": seg_start, "end": seg_end})
 
 
 
 
 
 
118
 
119
+ if i == 0 or not merged:
120
+ merged.extend(segs)
121
+ continue
122
+ merged, segs = self._join(merged, segs, chunk)
123
+ merged.extend(segs)
124
 
125
+ merged = [s for s in merged if (s.get("text") or "").strip()]
126
+ merged.sort(key=lambda x: x.get("start", 0))
127
+ for idx, seg in enumerate(merged):
128
+ seg["id"] = idx
129
+ return {
130
+ "text": " ".join(s["text"].strip() for s in merged),
131
+ "segments": merged,
132
+ "chunks": len(chunk_results)
133
+ }
134
 
135
+ # Minimum shared words to trust a text match. Stock phrases ("so carried",
136
+ # "thank you very much") are shorter than this; real overlap is ~30 s of
137
+ # speech, typically dozens of words.
138
+ _MIN_MATCH_WORDS = 6
139
 
140
+ @staticmethod
141
+ def _tokens(text: str) -> List[Tuple[str, str]]:
142
+ """(original token, normalised token) pairs; punctuation-only tokens
143
+ keep an empty normalised form so slicing stays aligned."""
144
+ out = []
145
+ for tok in (text or "").split():
146
+ out.append((tok, re.sub(r"[^a-z0-9']", "", tok.lower())))
147
+ return out
 
 
148
 
149
+ def _join(self, merged: List[dict], segs: List[dict], chunk: "AudioChunk"):
150
+ """Trim the end of `merged` and the start of `segs` so the overlap
151
+ appears once. Returns (merged, segs)."""
152
+ overlap_end = chunk.start_time + self.overlap_duration
153
+ # Earlier chunk's view of the overlap (plus a little slack for drift).
154
+ tail_ids = [k for k, s in enumerate(merged) if s["end"] > chunk.start_time - 5]
155
+ # Next chunk's view of it (slack for the late-timestamp drift).
156
+ head_ids = [j for j, s in enumerate(segs) if s["start"] < overlap_end + 20]
157
 
158
+ tail_words = [] # (merged index, token position, normalised word)
159
+ for k in tail_ids:
160
+ for p, (_, n) in enumerate(self._tokens(merged[k]["text"])):
161
+ if n:
162
+ tail_words.append((k, p, n))
163
+ head_words = []
164
+ for j in head_ids:
165
+ for p, (_, n) in enumerate(self._tokens(segs[j]["text"])):
166
+ if n:
167
+ head_words.append((j, p, n))
168
 
169
+ if tail_words and head_words:
170
+ m = SequenceMatcher(
171
+ None, [w for _, _, w in tail_words], [w for _, _, w in head_words], autojunk=False
172
+ ).find_longest_match(0, len(tail_words), 0, len(head_words))
173
+ if m.size >= self._MIN_MATCH_WORDS:
174
+ k_end, p_end, _ = tail_words[m.a + m.size - 1]
175
+ j_end, q_end, _ = head_words[m.b + m.size - 1]
176
+ # Earlier chunk: keep through the end of the matched run; its
177
+ # words after that are the cut-off edge of its audio.
178
+ kept_tail = self._tokens(merged[k_end]["text"])[: p_end + 1]
179
+ merged = merged[:k_end] + [{**merged[k_end], "text": " ".join(t for t, _ in kept_tail)}]
180
+ # Next chunk: drop everything up to and including the match.
181
+ rest = self._tokens(segs[j_end]["text"])[q_end + 1:]
182
+ new_segs = []
183
+ if rest:
184
+ new_segs.append({**segs[j_end], "text": " ".join(t for t, _ in rest)})
185
+ new_segs.extend(segs[j_end + 1:])
186
+ # Next-chunk timestamps can run late near its start; keep the
187
+ # timeline monotonic so ordering and diarization stay sane.
188
+ floor = merged[-1]["end"]
189
+ for s in new_segs:
190
+ if s["start"] < floor:
191
+ s["start"] = floor
192
+ s["end"] = max(s["end"], floor + 0.1)
193
+ floor = s["start"]
194
+ return merged, new_segs
195
+
196
+ # Fallback: hand over by time near the end of the overlap.
197
+ handover = chunk.start_time + max(self.overlap_duration - 2, self.overlap_duration / 2)
198
+ merged = [s for s in merged if s["start"] < handover]
199
+ segs = [s for s in segs if s["start"] >= handover]
200
+ return merged, segs
src/diarization/engine.py CHANGED
@@ -5,6 +5,7 @@ License: MIT
5
  """
6
 
7
  import os
 
8
  import logging
9
  from typing import List, Dict, Optional
10
 
@@ -64,6 +65,15 @@ class DiarizationEngine:
64
  use_auth_token=self.hf_token,
65
  )
66
 
 
 
 
 
 
 
 
 
 
67
  # Explicitly move to GPU — pyannote does not always auto-detect CUDA
68
  # when loaded inside a thread executor (the default device stays CPU).
69
  if _TORCH_AVAILABLE and _torch.cuda.is_available():
@@ -99,8 +109,21 @@ class DiarizationEngine:
99
  # to a single speaker in multi-speaker recordings.
100
  kwargs["min_speakers"] = 2
101
 
102
- logger.info(f"Running diarization on {audio_path} (num_speakers={num_speakers})…")
103
- diarization = self.pipeline(audio_path, **kwargs)
 
 
 
 
 
 
 
 
 
 
 
 
 
104
 
105
  turns = []
106
  speaker_map: Dict[str, str] = {}
 
5
  """
6
 
7
  import os
8
+ import time
9
  import logging
10
  from typing import List, Dict, Optional
11
 
 
65
  use_auth_token=self.hf_token,
66
  )
67
 
68
+ # pyannote returns None (rather than raising) when the token cannot
69
+ # access the gated model, which surfaced as "'NoneType' object has no
70
+ # attribute 'to'". Fail with the actual cause instead.
71
+ if self.pipeline is None:
72
+ raise RuntimeError(
73
+ "Could not load pyannote/speaker-diarization-3.1: HF_TOKEN lacks access "
74
+ "to the gated model (accept its terms on huggingface.co with the token's account)."
75
+ )
76
+
77
  # Explicitly move to GPU — pyannote does not always auto-detect CUDA
78
  # when loaded inside a thread executor (the default device stays CPU).
79
  if _TORCH_AVAILABLE and _torch.cuda.is_available():
 
109
  # to a single speaker in multi-speaker recordings.
110
  kwargs["min_speakers"] = 2
111
 
112
+ device = getattr(self.pipeline, "device", "unknown")
113
+ logger.info(f"Running diarization on {audio_path} (num_speakers={num_speakers}, device={device})…")
114
+ started = time.time()
115
+ # Hand pyannote the waveform already in memory: given a path it
116
+ # re-reads a crop from disk for every sliding window, which is a large
117
+ # share of the runtime on hour-long recordings.
118
+ try:
119
+ import soundfile as _sf
120
+ data, sr = _sf.read(audio_path, dtype="float32", always_2d=True)
121
+ audio_input = {"waveform": _torch.from_numpy(data.T.copy()), "sample_rate": sr}
122
+ except Exception as e:
123
+ logger.warning(f"Could not preload audio for diarization ({e}); passing path.")
124
+ audio_input = audio_path
125
+ diarization = self.pipeline(audio_input, **kwargs)
126
+ logger.info(f"Diarization took {time.time() - started:.1f}s on {device}.")
127
 
128
  turns = []
129
  speaker_map: Dict[str, str] = {}
src/models/asr_pipeline.py CHANGED
@@ -5,6 +5,7 @@ License: MIT
5
  """
6
 
7
  import io
 
8
  import time
9
  import numpy as np
10
  import soundfile as sf
@@ -57,6 +58,24 @@ class ASRPipeline:
57
  if self.pipeline is None:
58
  self.pipeline = self.registry.create_pipeline(self.model_key)
59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  def transcribe(self, audio: Union[str, np.ndarray, bytes], **kwargs) -> "TranscriptionResult":
61
  start_time = time.time()
62
  self._initialize_pipeline()
@@ -79,7 +98,14 @@ class ASRPipeline:
79
  }
80
  generate_kwargs = {k: v for k, v in generate_kwargs.items() if v is not None}
81
 
82
- num_beams = self.config.get("beam_size", 1)
 
 
 
 
 
 
 
83
  if num_beams and num_beams > 1:
84
  generate_kwargs["num_beams"] = num_beams
85
 
@@ -109,6 +135,10 @@ class ASRPipeline:
109
  audio,
110
  return_timestamps=return_timestamps,
111
  generate_kwargs=generate_kwargs,
 
 
 
 
112
  )
113
  elif isinstance(audio, bytes):
114
  audio_array, _ = sf.read(io.BytesIO(audio))
 
5
  """
6
 
7
  import io
8
+ import os
9
  import time
10
  import numpy as np
11
  import soundfile as sf
 
58
  if self.pipeline is None:
59
  self.pipeline = self.registry.create_pipeline(self.model_key)
60
 
61
+ def _batch_size(self, num_beams: int) -> int:
62
+ """30 s windows decoded at once. Each window runs `num_beams` beams
63
+ whose cross-attention cache grows with model size: large-v3 at
64
+ batch 8 x 5 beams needed ~10 GB of cache alone and OOM'd a 16 GB T4.
65
+ Budget is expressed in sequences (batch x beams)."""
66
+ if not torch.cuda.is_available():
67
+ return 1
68
+ override = os.getenv("ASR_BATCH_SIZE")
69
+ if override:
70
+ return int(override)
71
+ if "large" in self.model_key:
72
+ sequences = 10
73
+ elif "medium" in self.model_key:
74
+ sequences = 20
75
+ else:
76
+ sequences = 40
77
+ return max(1, min(8, sequences // max(1, num_beams)))
78
+
79
  def transcribe(self, audio: Union[str, np.ndarray, bytes], **kwargs) -> "TranscriptionResult":
80
  start_time = time.time()
81
  self._initialize_pipeline()
 
98
  }
99
  generate_kwargs = {k: v for k, v in generate_kwargs.items() if v is not None}
100
 
101
+ # Beam search is ~5x the decode cost. For long recordings (the engine
102
+ # passes long_form=True) greedy decoding with the temperature fallback
103
+ # above keeps accuracy close while making a 60 min file practical on
104
+ # a T4: with 5 beams large-v3 needed ~3.5 min per 5 min of audio.
105
+ if kwargs.get("long_form"):
106
+ num_beams = self.config.get("long_audio_beam_size", 1)
107
+ else:
108
+ num_beams = self.config.get("beam_size", 1)
109
  if num_beams and num_beams > 1:
110
  generate_kwargs["num_beams"] = num_beams
111
 
 
135
  audio,
136
  return_timestamps=return_timestamps,
137
  generate_kwargs=generate_kwargs,
138
+ # The engine hands over multi-minute blocks; the pipeline
139
+ # splits them into 30 s windows and decodes several at
140
+ # once on GPU instead of one window per call.
141
+ batch_size=self._batch_size(num_beams or 1),
142
  )
143
  elif isinstance(audio, bytes):
144
  audio_array, _ = sf.read(io.BytesIO(audio))
src/models/registry.py CHANGED
@@ -107,9 +107,28 @@ class ModelRegistry:
107
  logger.error(f"Failed to load model {model_key}: {e}")
108
  raise
109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  def create_pipeline(self, model_key: str, **kwargs) -> Any:
111
  if model_key in self.pipelines and not kwargs.get("force_reload", False):
112
  return self.pipelines[model_key]
 
113
 
114
  model, processor = self.load_model(model_key)
115
 
 
107
  logger.error(f"Failed to load model {model_key}: {e}")
108
  raise
109
 
110
+ def unload_all_except(self, keep_key: str) -> None:
111
+ """Free every cached Whisper model/pipeline except `keep_key`.
112
+
113
+ Models used to stay cached forever, so switching small -> large-v3
114
+ kept both on the GPU and a long large-v3 job ran a 16 GB T4 out of
115
+ memory.
116
+ """
117
+ dropped = [k for k in list(self.models) if k != keep_key]
118
+ for key in dropped:
119
+ self.models.pop(key, None)
120
+ self.processors.pop(key, None)
121
+ self.pipelines.pop(key, None)
122
+ if dropped:
123
+ gc.collect()
124
+ if torch.cuda.is_available():
125
+ torch.cuda.empty_cache()
126
+ logger.info(f"Unloaded models {dropped} to free memory for {keep_key}")
127
+
128
  def create_pipeline(self, model_key: str, **kwargs) -> Any:
129
  if model_key in self.pipelines and not kwargs.get("force_reload", False):
130
  return self.pipelines[model_key]
131
+ self.unload_all_except(model_key)
132
 
133
  model, processor = self.load_model(model_key)
134
 
src/transcription/engine.py CHANGED
@@ -7,6 +7,7 @@ License: MIT
7
  from pathlib import Path
8
  from typing import Optional, Dict
9
  import logging
 
10
  import uuid
11
  import yaml
12
  import soundfile as sf
@@ -83,6 +84,7 @@ class TranscriptionEngine:
83
  num_speakers = kwargs.pop("num_speakers", None)
84
  progress_callback = kwargs.pop("progress_callback", None)
85
  job_token = uuid.uuid4().hex[:8]
 
86
 
87
  is_valid, metadata, error = self.validator.is_valid_audio(file_path)
88
  if not is_valid:
@@ -108,20 +110,14 @@ class TranscriptionEngine:
108
  # Announce total upfront so client can show the bar immediately
109
  progress_callback(0, total_chunks)
110
 
111
- prev_text = ""
112
  for chunk in chunks:
113
  chunk_path = self.temp_dir / f"chunk_{job_token}_{chunk.index}.wav"
114
  sf.write(chunk_path, chunk.audio, sr)
115
 
116
- chunk_kwargs = dict(kwargs)
117
- # Feed the last ~200 chars of the previous chunk as context so
118
- # Whisper maintains language, style, and speaker continuity
119
- # across chunk boundaries instead of starting cold each time.
120
- if prev_text:
121
- chunk_kwargs["initial_prompt"] = prev_text[-200:]
122
-
123
- chunk_result = self._get_pipeline().transcribe(str(chunk_path), **chunk_kwargs)
124
- prev_text = chunk_result.text or ""
125
  chunk_results.append((chunk, chunk_result.to_merge_dict()))
126
  chunk_path.unlink(missing_ok=True)
127
  if progress_callback:
@@ -135,6 +131,7 @@ class TranscriptionEngine:
135
  audio_duration=metadata.duration,
136
  model_used=self.current_model_key,
137
  )
 
138
  else:
139
  result = self._get_pipeline().transcribe(processed_path, **kwargs)
140
  result.audio_duration = metadata.duration
 
7
  from pathlib import Path
8
  from typing import Optional, Dict
9
  import logging
10
+ import time
11
  import uuid
12
  import yaml
13
  import soundfile as sf
 
84
  num_speakers = kwargs.pop("num_speakers", None)
85
  progress_callback = kwargs.pop("progress_callback", None)
86
  job_token = uuid.uuid4().hex[:8]
87
+ started = time.time()
88
 
89
  is_valid, metadata, error = self.validator.is_valid_audio(file_path)
90
  if not is_valid:
 
110
  # Announce total upfront so client can show the bar immediately
111
  progress_callback(0, total_chunks)
112
 
 
113
  for chunk in chunks:
114
  chunk_path = self.temp_dir / f"chunk_{job_token}_{chunk.index}.wav"
115
  sf.write(chunk_path, chunk.audio, sr)
116
 
117
+ # No initial_prompt from the previous chunk: Whisper (HF
118
+ # implementation) echoes prompt text back when unsure, which
119
+ # duplicated sentences across chunks of long recordings.
120
+ chunk_result = self._get_pipeline().transcribe(str(chunk_path), long_form=True, **kwargs)
 
 
 
 
 
121
  chunk_results.append((chunk, chunk_result.to_merge_dict()))
122
  chunk_path.unlink(missing_ok=True)
123
  if progress_callback:
 
131
  audio_duration=metadata.duration,
132
  model_used=self.current_model_key,
133
  )
134
+ result.processing_time = time.time() - started
135
  else:
136
  result = self._get_pipeline().transcribe(processed_path, **kwargs)
137
  result.audio_duration = metadata.duration