mazesmazes commited on
Commit
3edc078
·
verified ·
1 Parent(s): eece501

Update custom model files, README, and requirements

Browse files
Files changed (3) hide show
  1. README.md +4 -3
  2. asr_pipeline.py +100 -19
  3. diarization.py +142 -38
README.md CHANGED
@@ -127,7 +127,8 @@ for word in result["words"]:
127
 
128
  Pass `return_speakers=True` to label every word with who said it. It also turns on word timestamps.
129
  It works on recordings of any length, keeps speaker labels consistent across hour-long meetings, and
130
- handles overlapping speech and up to 8 speakers.
 
131
 
132
  Diarization needs transformers installed from `main` until the next release:
133
 
@@ -154,8 +155,8 @@ for w in result["words"]:
154
  ```
155
 
156
  Speakers are numbered by when they first speak. The number of speakers is detected automatically. If
157
- you know it, pass `num_speakers` (exact) or `max_speakers` (an upper bound); any extra voices' words
158
- go to the closest kept speaker:
159
 
160
  ```python
161
  result = pipe("call.wav", return_speakers=True, num_speakers=2)
 
127
 
128
  Pass `return_speakers=True` to label every word with who said it. It also turns on word timestamps.
129
  It works on recordings of any length, keeps speaker labels consistent across hour-long meetings, and
130
+ handles up to 8 speakers. Each speaker is transcribed separately on audio where everyone else is
131
+ silenced, so overlapping speech is only partly handled.
132
 
133
  Diarization needs transformers installed from `main` until the next release:
134
 
 
155
  ```
156
 
157
  Speakers are numbered by when they first speak. The number of speakers is detected automatically. If
158
+ you know it, pass `num_speakers` (exact) or `max_speakers` (an upper bound); voices beyond the cap
159
+ are not transcribed:
160
 
161
  ```python
162
  result = pipe("call.wav", return_speakers=True, num_speakers=2)
asr_pipeline.py CHANGED
@@ -18,18 +18,18 @@ if TYPE_CHECKING:
18
  from .alignment import QwenForcedAligner
19
  from .asr_modeling import ASRModel
20
  from .asr_processing import prepend_lead_in
21
- from .diarization import NemotronDiarizer
22
  else:
23
  try:
24
  from .alignment import QwenForcedAligner
25
  from .asr_modeling import ASRModel
26
  from .asr_processing import prepend_lead_in
27
- from .diarization import NemotronDiarizer
28
  except ImportError: # flat layout on the Hub: sibling modules, no package
29
  from alignment import QwenForcedAligner
30
  from asr_modeling import ASRModel
31
  from asr_processing import prepend_lead_in
32
- from diarization import NemotronDiarizer
33
 
34
  # Re-export for backwards compatibility
35
  __all__ = [
@@ -67,6 +67,19 @@ def chunk_bounds(
67
  return bounds
68
 
69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  # Below this RMS (-100 dBFS) a chunk is digital silence: exact zeros, as in
71
  # edited or remixed recordings. Given one, the model answers with a memorized
72
  # training sentence ("The film was directed by the same director who directed
@@ -172,7 +185,9 @@ class ASRPipeline(transformers.AutomaticSpeechRecognitionPipeline):
172
  Args:
173
  inputs: Audio input (file path, dict with array/sampling_rate, etc.)
174
  return_timestamps: If True, return word-level timestamps (Qwen3-ForcedAligner)
175
- return_speakers: If True, label every word with a speaker (Nemotron-3-Diarization)
 
 
176
  user_prompt: Custom transcription prompt (default: "Transcribe: ")
177
  num_speakers: Exact number of speakers, if known
178
  max_speakers: Upper bound on the number of speakers
@@ -283,14 +298,13 @@ class ASRPipeline(transformers.AutomaticSpeechRecognitionPipeline):
283
  diarization_params: _DiarizationParams,
284
  **kwargs: Any,
285
  ) -> dict[str, Any]:
286
- """Transcribe in chunks, time every word, and label speakers if requested.
287
 
288
  Chunks of 8-18 s cut at quiet points are transcribed one by one and each
289
  is aligned against its own transcript (batched), then offset onto the
290
  recording's timeline -- so audio of any length gets every word timed,
291
- and the model never sees a clip longer than it trained on. Speakers come
292
- from ONE Nemotron pass over the whole recording, so labels are
293
- recording-level: chunking never touches speaker identity.
294
  """
295
  audio = self._extract_audio(inputs)
296
  if audio is None:
@@ -298,7 +312,14 @@ class ASRPipeline(transformers.AutomaticSpeechRecognitionPipeline):
298
  raise ValueError(msg)
299
  array = np.asarray(audio["array"], dtype=np.float32)
300
  sr = audio.get("sampling_rate", 16000)
 
 
 
301
 
 
 
 
 
302
  bounds = chunk_bounds(array, sr)
303
  texts: list[str] = [
304
  self._transcribe_chunk(array[s:e], sr, **kwargs)["text"] for s, e in bounds
@@ -318,21 +339,81 @@ class ASRPipeline(transformers.AutomaticSpeechRecognitionPipeline):
318
  except Exception as e:
319
  result["words"] = []
320
  result["timestamp_error"] = str(e)
 
321
 
322
- if return_speakers:
323
- try:
324
- activity = NemotronDiarizer.activity(array, sample_rate=sr)
325
- keep = NemotronDiarizer.top_speakers(activity, **diarization_params)
326
- result["speaker_segments"] = NemotronDiarizer.segments(activity, keep)
327
- result["words"] = NemotronDiarizer.assign_speakers_to_words(
328
- result["words"], activity, keep
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
329
  )
330
- except Exception as e:
331
- result["speaker_segments"] = []
332
- result["diarization_error"] = str(e)
333
-
 
 
334
  return result
335
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
336
  def _extract_audio(self, inputs: object) -> _RawAudio | None:
337
  """Extract audio array from various input formats using HF utilities."""
338
  if isinstance(inputs, dict):
 
18
  from .alignment import QwenForcedAligner
19
  from .asr_modeling import ASRModel
20
  from .asr_processing import prepend_lead_in
21
+ from .diarization import NemotronDiarizer, StreamChunk, masked_audio, pack_spans
22
  else:
23
  try:
24
  from .alignment import QwenForcedAligner
25
  from .asr_modeling import ASRModel
26
  from .asr_processing import prepend_lead_in
27
+ from .diarization import NemotronDiarizer, StreamChunk, masked_audio, pack_spans
28
  except ImportError: # flat layout on the Hub: sibling modules, no package
29
  from alignment import QwenForcedAligner
30
  from asr_modeling import ASRModel
31
  from asr_processing import prepend_lead_in
32
+ from diarization import NemotronDiarizer, StreamChunk, masked_audio, pack_spans
33
 
34
  # Re-export for backwards compatibility
35
  __all__ = [
 
67
  return bounds
68
 
69
 
70
+ def stream_chunks(
71
+ audio: npt.NDArray[np.float32],
72
+ spans: list[tuple[int, int]],
73
+ sample_rate: int,
74
+ max_s: float = CHUNK_MAX_S,
75
+ ) -> list[tuple[int, int]]:
76
+ """Ranges of at most `max_s` over one speaker's `spans`; long turns cut by `chunk_bounds`."""
77
+ pieces: list[tuple[int, int]] = []
78
+ for s, e in spans:
79
+ pieces.extend((s + a, s + b) for a, b in chunk_bounds(audio[s:e], sample_rate, max_s))
80
+ return pack_spans(pieces, int(max_s * sample_rate))
81
+
82
+
83
  # Below this RMS (-100 dBFS) a chunk is digital silence: exact zeros, as in
84
  # edited or remixed recordings. Given one, the model answers with a memorized
85
  # training sentence ("The film was directed by the same director who directed
 
185
  Args:
186
  inputs: Audio input (file path, dict with array/sampling_rate, etc.)
187
  return_timestamps: If True, return word-level timestamps (Qwen3-ForcedAligner)
188
+ return_speakers: If True, transcribe each Nemotron-3-Diarization speaker on
189
+ audio with the others silenced and label words by speaker (see
190
+ `_transcribe_streams`). Implies return_timestamps.
191
  user_prompt: Custom transcription prompt (default: "Transcribe: ")
192
  num_speakers: Exact number of speakers, if known
193
  max_speakers: Upper bound on the number of speakers
 
298
  diarization_params: _DiarizationParams,
299
  **kwargs: Any,
300
  ) -> dict[str, Any]:
301
+ """Transcribe in chunks and time every word; per-speaker streams if requested.
302
 
303
  Chunks of 8-18 s cut at quiet points are transcribed one by one and each
304
  is aligned against its own transcript (batched), then offset onto the
305
  recording's timeline -- so audio of any length gets every word timed,
306
+ and the model never sees a clip longer than it trained on. Speakers
307
+ come from `_transcribe_streams`.
 
308
  """
309
  audio = self._extract_audio(inputs)
310
  if audio is None:
 
312
  raise ValueError(msg)
313
  array = np.asarray(audio["array"], dtype=np.float32)
314
  sr = audio.get("sampling_rate", 16000)
315
+ if return_speakers:
316
+ return self._transcribe_streams(array, sr, diarization_params, **kwargs)
317
+ return self._transcribe_aligned(array, sr, **kwargs)
318
 
319
+ def _transcribe_aligned(
320
+ self, array: npt.NDArray[np.float32], sr: int, **kwargs: Any
321
+ ) -> dict[str, Any]:
322
+ """`{"text", "words"}` for the whole recording: chunk, transcribe, align, offset."""
323
  bounds = chunk_bounds(array, sr)
324
  texts: list[str] = [
325
  self._transcribe_chunk(array[s:e], sr, **kwargs)["text"] for s, e in bounds
 
339
  except Exception as e:
340
  result["words"] = []
341
  result["timestamp_error"] = str(e)
342
+ return result
343
 
344
+ def _transcribe_streams(
345
+ self,
346
+ array: npt.NDArray[np.float32],
347
+ sr: int,
348
+ diarization_params: _DiarizationParams,
349
+ **kwargs: Any,
350
+ ) -> dict[str, Any]:
351
+ """Per-speaker masked ASR, a zero-shot port of NeMo's `masked_asr`.
352
+
353
+ Nemotron runs first, one pass over the whole recording, so speaker ids
354
+ are recording-level. Each speaker is transcribed only where they talk
355
+ (`stream_chunks`), with everyone else zeroed (`masked_audio`); words take
356
+ their stream's speaker, and a word two streams both heard at once is
357
+ kept once (`dedupe_words`). Crosstalk under a speaker's mask is heard.
358
+ With at most one speaker active nothing is masked (today's exact text);
359
+ if diarization fails, the unmasked transcript gets `diarization_error`.
360
+ """
361
+ try:
362
+ activity = NemotronDiarizer.activity(array, sample_rate=sr)
363
+ keep = NemotronDiarizer.top_speakers(activity, **diarization_params)
364
+ except Exception as e:
365
+ result = self._transcribe_aligned(array, sr, **kwargs)
366
+ result["speaker_segments"] = []
367
+ result["diarization_error"] = str(e)
368
+ return result
369
+
370
+ masks = {c: activity[:, c] > NemotronDiarizer.SEGMENT_THRESHOLD for c in keep}
371
+ talking = [c for c in keep if masks[c].any()]
372
+ if len(talking) <= 1:
373
+ result = self._transcribe_aligned(array, sr, **kwargs)
374
+ name = f"SPEAKER_{keep.index(talking[0]) if talking else 0}"
375
+ result["words"] = [{**w, "speaker": name} for w in result["words"]]
376
+ else:
377
+ chunks: list[StreamChunk] = []
378
+ for c in talking:
379
+ spans = NemotronDiarizer.sample_spans(masks[c], sr, len(array))
380
+ chunks.extend(
381
+ {"col": c, "start": s, "audio": masked_audio(array, spans, s, e)}
382
+ for s, e in stream_chunks(array, spans, sr)
383
  )
384
+ texts = [self._transcribe_chunk(ch["audio"], sr, **kwargs)["text"] for ch in chunks]
385
+ result = self._align_streams(chunks, texts, sr, masks, keep)
386
+ if result["words"]:
387
+ result["words"] = NemotronDiarizer.dedupe_words(result["words"], activity, keep)
388
+ result["text"] = " ".join(w["word"] for w in result["words"])
389
+ result["speaker_segments"] = NemotronDiarizer.segments(activity, keep)
390
  return result
391
 
392
+ @staticmethod
393
+ def _align_streams(
394
+ chunks: list[StreamChunk],
395
+ texts: list[str],
396
+ sr: int,
397
+ masks: dict[int, npt.NDArray[np.bool_]],
398
+ keep: list[int],
399
+ ) -> dict[str, Any]:
400
+ """Align every stream chunk in one batch; `{"text", "words"}` merged by time.
401
+
402
+ If alignment fails the text is the chunk transcripts by start time and
403
+ `timestamp_error` is set.
404
+ """
405
+ try:
406
+ aligned = QwenForcedAligner.align_chunks(
407
+ [(ch["audio"], text) for ch, text in zip(chunks, texts, strict=True)],
408
+ sample_rate=sr,
409
+ )
410
+ except Exception as e:
411
+ order = sorted(range(len(chunks)), key=lambda k: chunks[k]["start"])
412
+ text = " ".join(texts[k] for k in order if texts[k])
413
+ return {"text": text, "words": [], "timestamp_error": str(e)}
414
+ words = NemotronDiarizer.stream_words(chunks, aligned, sr, masks, keep)
415
+ return {"text": " ".join(w["word"] for w in words), "words": words}
416
+
417
  def _extract_audio(self, inputs: object) -> _RawAudio | None:
418
  """Extract audio array from various input formats using HF utilities."""
419
  if isinstance(inputs, dict):
diarization.py CHANGED
@@ -1,6 +1,7 @@
1
  """Speaker diarization with NVIDIA Nemotron-3-Diarization."""
2
 
3
  import importlib.util
 
4
  from typing import TYPE_CHECKING, Any, TypedDict
5
 
6
  import numpy as np
@@ -17,6 +18,8 @@ if TYPE_CHECKING:
17
  Nemotron3DiarizationProcessor,
18
  )
19
 
 
 
20
 
21
  class SpeakerSegment(TypedDict):
22
  """One speaker turn, in seconds."""
@@ -52,6 +55,55 @@ def _label_runs(labels: npt.NDArray[np.generic]) -> list[tuple[int, int, int]]:
52
  return [(labels[s].item(), int(s), int(e)) for s, e in zip(starts, ends, strict=True)]
53
 
54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  class NemotronDiarizer:
56
  """Speaker activity from NVIDIA Nemotron-3-Diarization, per 10 ms frame.
57
 
@@ -68,13 +120,16 @@ class NemotronDiarizer:
68
  >>> activity = NemotronDiarizer.activity(audio) # (frames, 8) probabilities
69
  >>> keep = NemotronDiarizer.top_speakers(activity, max_speakers=2)
70
  >>> segments = NemotronDiarizer.segments(activity, keep)
71
- >>> words = NemotronDiarizer.assign_speakers_to_words(words, activity, keep)
 
 
 
 
72
  """
73
 
74
  MODEL_ID = "nvidia/Nemotron-3-Diarization"
75
  FRAME_S = 0.01
76
  SEGMENT_THRESHOLD = 0.5 # a speaker's segment = frames above this
77
- MIN_WORD_ACTIVITY = 0.1 # below this nobody is heard: the word inherits its neighbour
78
  _model: "Nemotron3DiarizationForAudioFrameClassification | None" = None
79
  _processor: "Nemotron3DiarizationProcessor | None" = None
80
 
@@ -130,8 +185,7 @@ class NemotronDiarizer:
130
 
131
  Every column that is ever above SEGMENT_THRESHOLD, capped by
132
  `num_speakers` (exact, when known) or `max_speakers` to the columns
133
- with the most speech. Capping is how a known count is applied:
134
- a dropped column's words go to the most active remaining speaker.
135
  """
136
  active = [
137
  c for c in range(activity.shape[1]) if (activity[:, c] > cls.SEGMENT_THRESHOLD).any()
@@ -156,45 +210,95 @@ class NemotronDiarizer:
156
  return sorted(out, key=lambda seg: (seg["start"], seg["end"]))
157
 
158
  @classmethod
159
- def speaker_columns(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
  cls,
161
- spans: list[tuple[float | None, float | None]],
162
- activity: npt.NDArray[np.float32],
 
 
163
  keep: list[int],
164
- ) -> list[int]:
165
- """The kept activity column that said each `(start_s, end_s)` word.
166
 
167
- The kept speaker most active over the word's span. A word with no
168
- time, or where no kept speaker reaches MIN_WORD_ACTIVITY (it sits in
169
- a pause), takes the previous word's speaker -- the next word's at the
170
- start of the recording.
171
  """
172
- cols = np.asarray(keep)
173
- picked: list[int | None] = []
174
- for start, end in spans:
175
- if start is None or end is None:
176
- picked.append(None)
177
- continue
178
- lo = min(int(start / cls.FRAME_S), len(activity) - 1)
179
- hi = max(lo + 1, min(int(np.ceil(end / cls.FRAME_S)), len(activity)))
180
- mean = activity[lo:hi, cols].mean(axis=0)
181
- best = int(mean.argmax())
182
- picked.append(int(cols[best]) if mean[best] >= cls.MIN_WORD_ACTIVITY else None)
183
- known = [p for p in picked if p is not None]
184
- last = known[0] if known else keep[0]
185
- out: list[int] = []
186
- for p in picked:
187
- last = p if p is not None else last
188
- out.append(last)
189
- return out
190
 
191
  @classmethod
192
- def assign_speakers_to_words(
193
  cls, words: list[dict[str, Any]], activity: npt.NDArray[np.float32], keep: list[int]
194
  ) -> list[dict[str, Any]]:
195
- """Label each `{"start", "end"}` word `SPEAKER_i` by `speaker_columns`."""
196
- names = {c: f"SPEAKER_{i}" for i, c in enumerate(keep)}
197
- spans = [(w["start"], w["end"]) for w in words]
198
- for word, col in zip(words, cls.speaker_columns(spans, activity, keep), strict=True):
199
- word["speaker"] = names[col]
200
- return words
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  """Speaker diarization with NVIDIA Nemotron-3-Diarization."""
2
 
3
  import importlib.util
4
+ import re
5
  from typing import TYPE_CHECKING, Any, TypedDict
6
 
7
  import numpy as np
 
18
  Nemotron3DiarizationProcessor,
19
  )
20
 
21
+ from .alignment import AlignedWord
22
+
23
 
24
  class SpeakerSegment(TypedDict):
25
  """One speaker turn, in seconds."""
 
55
  return [(labels[s].item(), int(s), int(e)) for s, e in zip(starts, ends, strict=True)]
56
 
57
 
58
+ def masked_audio(
59
+ audio: npt.NDArray[np.float32], spans: list[tuple[int, int]], start: int, end: int
60
+ ) -> npt.NDArray[np.float32]:
61
+ """`audio[start:end]` with every sample outside `spans` set to 0.0.
62
+
63
+ `spans` are absolute `(start, end)` sample ranges, end exclusive. Only the
64
+ slice is copied, so a speaker stream of a long recording never holds a
65
+ full-length masked copy. Zeros are digital silence: the encoder sees its
66
+ silence floor there, and `is_silent` skips a chunk that is nothing else.
67
+ """
68
+ out = np.zeros(end - start, dtype=np.float32)
69
+ for s, e in spans:
70
+ lo, hi = max(s, start), min(e, end)
71
+ if lo < hi:
72
+ out[lo - start : hi - start] = audio[lo:hi]
73
+ return out
74
+
75
+
76
+ def pack_spans(spans: list[tuple[int, int]], limit: int) -> list[tuple[int, int]]:
77
+ """Merge consecutive sorted `(start, end)` spans into ranges at most `limit` long.
78
+
79
+ Each range starts and ends on a span, so a speaker's chunk never begins or
80
+ ends in audio where they are silent. A span already over `limit` stays alone.
81
+ """
82
+ ranges: list[tuple[int, int]] = []
83
+ for s, e in spans:
84
+ if ranges and e - ranges[-1][0] <= limit:
85
+ ranges[-1] = (ranges[-1][0], e)
86
+ else:
87
+ ranges.append((s, e))
88
+ return ranges
89
+
90
+
91
+ class StreamChunk(TypedDict):
92
+ """One stretch of one speaker's masked audio: kept column, absolute start, samples."""
93
+
94
+ col: int
95
+ start: int
96
+ audio: npt.NDArray[np.float32]
97
+
98
+
99
+ _NON_WORD_RE = re.compile(r"[^\w']+")
100
+
101
+
102
+ def _norm_word(word: str) -> str:
103
+ """Lowercase `word` without punctuation, for matching one word heard in two streams."""
104
+ return _NON_WORD_RE.sub("", word.lower())
105
+
106
+
107
  class NemotronDiarizer:
108
  """Speaker activity from NVIDIA Nemotron-3-Diarization, per 10 ms frame.
109
 
 
120
  >>> activity = NemotronDiarizer.activity(audio) # (frames, 8) probabilities
121
  >>> keep = NemotronDiarizer.top_speakers(activity, max_speakers=2)
122
  >>> segments = NemotronDiarizer.segments(activity, keep)
123
+
124
+ `ASRPipeline(..., return_speakers=True)` turns this into speaker streams:
125
+ `sample_spans` gives each kept speaker a mask, the ASR runs once per
126
+ speaker on audio with everyone else silenced, and `span_is_active` /
127
+ `dedupe_words` clean up the merge.
128
  """
129
 
130
  MODEL_ID = "nvidia/Nemotron-3-Diarization"
131
  FRAME_S = 0.01
132
  SEGMENT_THRESHOLD = 0.5 # a speaker's segment = frames above this
 
133
  _model: "Nemotron3DiarizationForAudioFrameClassification | None" = None
134
  _processor: "Nemotron3DiarizationProcessor | None" = None
135
 
 
185
 
186
  Every column that is ever above SEGMENT_THRESHOLD, capped by
187
  `num_speakers` (exact, when known) or `max_speakers` to the columns
188
+ with the most speech. A dropped column gets no stream of its own.
 
189
  """
190
  active = [
191
  c for c in range(activity.shape[1]) if (activity[:, c] > cls.SEGMENT_THRESHOLD).any()
 
210
  return sorted(out, key=lambda seg: (seg["start"], seg["end"]))
211
 
212
  @classmethod
213
+ def _frame_range(cls, start: float, end: float, n_frames: int) -> tuple[int, int]:
214
+ """Frames `[lo, hi)` under the span `start..end` s: at least one, clamped to the array."""
215
+ lo = min(int(start / cls.FRAME_S), n_frames - 1)
216
+ hi = max(lo + 1, min(int(np.ceil(end / cls.FRAME_S)), n_frames))
217
+ return lo, hi
218
+
219
+ @classmethod
220
+ def sample_spans(
221
+ cls, frames: npt.NDArray[np.bool_], sample_rate: int, n_samples: int
222
+ ) -> list[tuple[int, int]]:
223
+ """The active runs of a frame mask as `(start, end)` sample ranges, end exclusive.
224
+
225
+ One frame covers `FRAME_S * sample_rate` samples. A run that reaches the
226
+ last frame runs to `n_samples`: the model's frame count can fall a few
227
+ samples short of the audio, and that tail belongs to the run.
228
+ """
229
+ hop = cls.FRAME_S * sample_rate
230
+ spans: list[tuple[int, int]] = []
231
+ for on, s, e in _label_runs(frames):
232
+ start = min(round(s * hop), n_samples)
233
+ end = n_samples if e == len(frames) else min(round(e * hop), n_samples)
234
+ if on and start < end:
235
+ spans.append((start, end))
236
+ return spans
237
+
238
+ @classmethod
239
+ def span_is_active(cls, frames: npt.NDArray[np.bool_], start: float, end: float) -> bool:
240
+ """True if any frame of the span `start..end` s is in the mask `frames`."""
241
+ if len(frames) == 0:
242
+ return False
243
+ lo, hi = cls._frame_range(start, end, len(frames))
244
+ return bool(frames[lo:hi].any())
245
+
246
+ @classmethod
247
+ def stream_words(
248
  cls,
249
+ chunks: list[StreamChunk],
250
+ aligned: "list[list[AlignedWord]]",
251
+ sample_rate: int,
252
+ masks: dict[int, npt.NDArray[np.bool_]],
253
  keep: list[int],
254
+ ) -> list[dict[str, Any]]:
255
+ """Every stream's aligned words on the recording timeline, labelled, by start.
256
 
257
+ A word placed wholly in its own speaker's silenced audio (`masks`) is a
258
+ hallucination on silence and is dropped.
 
 
259
  """
260
+ names = {c: f"SPEAKER_{i}" for i, c in enumerate(keep)}
261
+ words: list[dict[str, Any]] = []
262
+ for ch, chunk_words in zip(chunks, aligned, strict=True):
263
+ offset = ch["start"] / sample_rate
264
+ for w in chunk_words:
265
+ start, end = w["start"] + offset, w["end"] + offset
266
+ if cls.span_is_active(masks[ch["col"]], start, end):
267
+ words.append({**w, "start": start, "end": end, "speaker": names[ch["col"]]})
268
+ return sorted(words, key=lambda w: (w["start"], w["end"]))
269
+
270
+ @classmethod
271
+ def _span_activity(
272
+ cls, activity: npt.NDArray[np.float32], col: int, start: float, end: float
273
+ ) -> float:
274
+ """Mean activity of column `col` over the span `start..end` s."""
275
+ lo, hi = cls._frame_range(start, end, len(activity))
276
+ return float(activity[lo:hi, col].mean())
 
277
 
278
  @classmethod
279
+ def dedupe_words(
280
  cls, words: list[dict[str, Any]], activity: npt.NDArray[np.float32], keep: list[int]
281
  ) -> list[dict[str, Any]]:
282
+ """Drop one copy of a word two speaker streams both heard.
283
+
284
+ `words` are sorted by start and labelled `SPEAKER_i` (position in
285
+ `keep`). Two words from different speakers with the same text (case
286
+ and punctuation ignored) and overlapping spans are one word that
287
+ leaked into both masks: the copy whose speaker is more active over its
288
+ span stays, the earlier word on a tie.
289
+ """
290
+ cols = {f"SPEAKER_{i}": c for i, c in enumerate(keep)}
291
+ dropped: set[int] = set()
292
+ for i, a in enumerate(words):
293
+ for j in range(i + 1, len(words)):
294
+ b = words[j]
295
+ if b["start"] >= a["end"]:
296
+ break
297
+ if i in dropped or j in dropped or a["speaker"] == b["speaker"]:
298
+ continue
299
+ if not _norm_word(a["word"]) or _norm_word(a["word"]) != _norm_word(b["word"]):
300
+ continue
301
+ score_a = cls._span_activity(activity, cols[a["speaker"]], a["start"], a["end"])
302
+ score_b = cls._span_activity(activity, cols[b["speaker"]], b["start"], b["end"])
303
+ dropped.add(j if score_a >= score_b else i)
304
+ return [w for k, w in enumerate(words) if k not in dropped]