Consulawtech commited on
Commit
172f7f2
·
1 Parent(s): 2f73c0e

Auto-detect Yoruba/Hausa probe; one-speaker handling; source revision e98e60e

Browse files
src/diarization/engine.py CHANGED
@@ -105,11 +105,9 @@ class DiarizationEngine:
105
  kwargs = {}
106
  if num_speakers is not None:
107
  kwargs["num_speakers"] = num_speakers
108
- else:
109
- # Without a hint pyannote tends to under-cluster, merging distinct
110
- # speakers into one. min_speakers=2 prevents collapsing all speech
111
- # to a single speaker in multi-speaker recordings.
112
- kwargs["min_speakers"] = 2
113
 
114
  device = getattr(self.pipeline, "device", "unknown")
115
  logger.info(f"Running diarization on {audio_path} (num_speakers={num_speakers}, device={device})…")
@@ -247,6 +245,9 @@ VOICE_THRESHOLD = 0.45 # cosine distance at which two voices stay apart
247
  VOICE_MIN_SHARE = 0.02 # a "voice" with less speech than this...
248
  VOICE_MIN_TOTAL_SEC = 3.0 # ...or this joins its nearest real voice
249
  VOICE_SWITCH_MARGIN = 0.10 # voice grouping must beat pyannote's by this much
 
 
 
250
 
251
 
252
  def _silhouette(V: np.ndarray, labels: List) -> float:
@@ -300,15 +301,26 @@ def refine_with_voices(segments: List[Dict], fingerprints: List[Optional[np.ndar
300
  V /= np.linalg.norm(V, axis=1, keepdims=True) + 1e-9
301
  dur = np.array([segments[i]["end"] - segments[i]["start"] for i in idx])
302
  voice = group_voices(V, dur, num_speakers)
 
 
 
 
 
 
 
 
 
 
 
 
 
303
  if len(set(voice)) < 2:
304
  return segments
305
- current = [segments[i].get("speaker") or "none" for i in idx]
306
  if not num_speakers and len(set(voice)) < len(set(current)):
307
  # The fix is for voices pyannote merged; never use it to merge people
308
  # pyannote kept apart (no reference shows that would be right).
309
  return segments
310
- s_voice, s_current = _silhouette(V, list(voice)), _silhouette(V, current)
311
- if s_voice < s_current + VOICE_SWITCH_MARGIN:
312
  logger.info(f"Voice check kept pyannote's speakers (silhouette {s_current:.2f} vs {s_voice:.2f}).")
313
  return segments
314
  # Name voices SPEAKER_00, 01... in order of first appearance.
 
105
  kwargs = {}
106
  if num_speakers is not None:
107
  kwargs["num_speakers"] = num_speakers
108
+ # No minimum otherwise: forcing two speakers split one-person
109
+ # recordings in two. Voices pyannote merges are separated afterwards
110
+ # by the per-sentence voice check (refine_with_voices).
 
 
111
 
112
  device = getattr(self.pipeline, "device", "unknown")
113
  logger.info(f"Running diarization on {audio_path} (num_speakers={num_speakers}, device={device})…")
 
245
  VOICE_MIN_SHARE = 0.02 # a "voice" with less speech than this...
246
  VOICE_MIN_TOTAL_SEC = 3.0 # ...or this joins its nearest real voice
247
  VOICE_SWITCH_MARGIN = 0.10 # voice grouping must beat pyannote's by this much
248
+ VOICE_ONE_SPEAKER_SILHOUETTE = 0.15 # below this pyannote's split doesn't follow the voices
249
+ VOICE_SPLIT_MIN = 0.30 # voice groups must be at least this distinct to add speakers
250
+ # (two-person dialogues scored 0.49-0.56; one-person tracks 0.10-0.15)
251
 
252
 
253
  def _silhouette(V: np.ndarray, labels: List) -> float:
 
301
  V /= np.linalg.norm(V, axis=1, keepdims=True) + 1e-9
302
  dur = np.array([segments[i]["end"] - segments[i]["start"] for i in idx])
303
  voice = group_voices(V, dur, num_speakers)
304
+ current = [segments[i].get("speaker") or "none" for i in idx]
305
+ s_current = _silhouette(V, current)
306
+ s_voice = _silhouette(V, list(voice)) if len(set(voice)) > 1 else -1.0
307
+ if not num_speakers and s_current < VOICE_ONE_SPEAKER_SILHOUETTE and s_voice < VOICE_SPLIT_MIN:
308
+ # Neither pyannote's split nor the voices show distinct people:
309
+ # one speaker (a single-voice lesson was coming out as 2-3 speakers).
310
+ if len(set(current)) > 1:
311
+ logger.info(f"Voice check: one speaker (pyannote had {len(set(current))}).")
312
+ out = [dict(s) for s in segments]
313
+ for seg in out:
314
+ seg["speaker"] = "SPEAKER_00"
315
+ return out
316
+ return segments
317
  if len(set(voice)) < 2:
318
  return segments
 
319
  if not num_speakers and len(set(voice)) < len(set(current)):
320
  # The fix is for voices pyannote merged; never use it to merge people
321
  # pyannote kept apart (no reference shows that would be right).
322
  return segments
323
+ if s_voice < max(s_current + VOICE_SWITCH_MARGIN, VOICE_SPLIT_MIN if not num_speakers else -1.0):
 
324
  logger.info(f"Voice check kept pyannote's speakers (silhouette {s_current:.2f} vs {s_voice:.2f}).")
325
  return segments
326
  # Name voices SPEAKER_00, 01... in order of first appearance.
src/transcription/engine.py CHANGED
@@ -60,6 +60,12 @@ ENGLISH_WORD_SHARE = 0.5 # ...at least half its words must be English wo
60
  # to be ahead: on Nigerian-accented English the Yoruba model is about as sure
61
  # as Whisper ("Nigeria records 122 new COVID-19 infections": -0.40 vs -0.47),
62
  # and invented English only ever showed up on 1-4 word pieces.
 
 
 
 
 
 
63
  ENGLISH_SENTENCE_WORDS = 5
64
  ENGLISH_SENTENCE_SHARE = 0.6
65
  # ...and it must say something: fillers and spelled letters ("Oh, yeah",
@@ -162,12 +168,18 @@ class TranscriptionEngine:
162
  self._turn_cuts = turn_cuts(speaker_turns) if speaker_turns else []
163
 
164
  try:
165
- native_choice = (len(requested) == 1 and requested[0] in NATIVE_MODELS and native_asr_enabled()
166
- and mixed_language_enabled() and actual_duration >= 3
167
- and NATIVE_MODELS[requested[0]] in self.registry.list_available_models())
168
- plan = None if native_choice else self._language_plan(audio, sr, requested, actual_duration)
169
- if native_choice:
170
- result = self._transcribe_native_with_english(audio, sr, requested[0], job_model, kwargs, progress_callback)
 
 
 
 
 
 
171
  result.audio_duration = metadata.duration
172
  result.processing_time = time.time() - started
173
  elif plan and len({r.language for r in plan}) > 1:
@@ -399,6 +411,40 @@ class TranscriptionEngine:
399
  return True
400
  return False
401
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
402
  def _transcribe_native_with_english(self, audio, sr, lang: str, job_model: str, kwargs,
403
  progress_callback) -> TranscriptionResult:
404
  """A chosen Yoruba/Igbo/Hausa recording, piece by piece, with English
 
60
  # to be ahead: on Nigerian-accented English the Yoruba model is about as sure
61
  # as Whisper ("Nigeria records 122 new COVID-19 infections": -0.40 vs -0.47),
62
  # and invented English only ever showed up on 1-4 word pieces.
63
+ # Auto-detect: Whisper's language guess calls Yoruba names and words English,
64
+ # so a sample of pieces is read by the Yoruba/Hausa model and by Whisper; when
65
+ # the dedicated model is the surer reader of at least half, the recording is
66
+ # treated as that language (its English parts are still kept in English).
67
+ PROBE_PIECES = 8
68
+ PROBE_NATIVE_SHARE = 0.5
69
  ENGLISH_SENTENCE_WORDS = 5
70
  ENGLISH_SENTENCE_SHARE = 0.6
71
  # ...and it must say something: fillers and spelled letters ("Oh, yeah",
 
168
  self._turn_cuts = turn_cuts(speaker_turns) if speaker_turns else []
169
 
170
  try:
171
+ # One Nigerian language chosen, alone or with English: that model
172
+ # reads it and English is kept where it really is English.
173
+ natives = [l for l in requested if l in NATIVE_MODELS]
174
+ native_choice = (len(natives) == 1 and all(l in NATIVE_MODELS or l == "en" for l in requested)
175
+ and native_asr_enabled() and mixed_language_enabled() and actual_duration >= 3
176
+ and NATIVE_MODELS[natives[0]] in self.registry.list_available_models())
177
+ native_lang = natives[0] if native_choice else None
178
+ if not requested and native_asr_enabled() and mixed_language_enabled() and actual_duration >= 3:
179
+ native_lang = self._probe_native_language(audio, sr, job_model)
180
+ plan = None if native_lang else self._language_plan(audio, sr, requested, actual_duration)
181
+ if native_lang:
182
+ result = self._transcribe_native_with_english(audio, sr, native_lang, job_model, kwargs, progress_callback)
183
  result.audio_duration = metadata.duration
184
  result.processing_time = time.time() - started
185
  elif plan and len({r.language for r in plan}) > 1:
 
411
  return True
412
  return False
413
 
414
+ def _probe_native_language(self, audio, sr, job_model: str) -> Optional[str]:
415
+ """Auto-detect: is this mostly Yoruba or Hausa? Returns the language,
416
+ or None to carry on with the usual language plan."""
417
+ available = self.registry.list_available_models()
418
+ if DETECTOR_MODEL not in available:
419
+ return None
420
+ total_sec = len(audio) / sr
421
+ spans = pieces(speech_windows(audio, sr), 0.0, total_sec) or []
422
+ spans = [sp for sp in spans if sp[1] - sp[0] >= 0.4] # alphabet drills are single letters
423
+ if len(spans) < 3:
424
+ return None
425
+ step = max(1, len(spans) // PROBE_PIECES)
426
+ sample = spans[::step][:PROBE_PIECES]
427
+ clips = [audio[int(a * sr): int(b * sr)] for a, b in sample]
428
+ try:
429
+ detector = self._use_model(DETECTOR_MODEL)
430
+ # Which dedicated language is closest (Igbo has no Whisper token).
431
+ totals: Dict[str, float] = {}
432
+ for sc in detector.language_scores(clips, ["yo", "ha"], sr):
433
+ for c, v in (sc or {}).items():
434
+ totals[c] = totals.get(c, 0.0) + v
435
+ lang = max(totals, key=totals.get) if totals else "yo"
436
+ if NATIVE_MODELS.get(lang) not in available:
437
+ return None
438
+ whisper_read = detector.decode_with_confidence(clips, None, sr)
439
+ native_read = self._use_model(NATIVE_MODELS[lang]).decode_with_confidence(clips, None, sr)
440
+ except Exception as e:
441
+ logger.warning(f"Language probe skipped: {type(e).__name__}")
442
+ return None
443
+ wins = sum(1 for (wt, ws), (nt, ns) in zip(whisper_read, native_read)
444
+ if nt and ns is not None and (ws is None or ns > ws))
445
+ logger.info(f"Language probe: {lang} model surer on {wins}/{len(sample)} sample pieces")
446
+ return lang if wins >= PROBE_NATIVE_SHARE * len(sample) else None
447
+
448
  def _transcribe_native_with_english(self, audio, sr, lang: str, job_model: str, kwargs,
449
  progress_callback) -> TranscriptionResult:
450
  """A chosen Yoruba/Igbo/Hausa recording, piece by piece, with English