Spaces:
Paused
Paused
Commit ·
65a5dfa
1
Parent(s): 1e3b725
Voice check per sentence; short English phrases kept in English; source revision a8bd243
Browse filesFiles changed (3)
8 unmodified lines91011121314127 unmodified lines14214314414514614740 unmodified lines1881891908 unmodified linesimport loggingfrom typing import List, Dict, Optionaltry:import torch as _torch_TORCH_AVAILABLE = True127 unmodified lineslogger.info(f"Diarization complete: {len(turns)} turns, {next_idx} speakers.")return turns@staticmethoddef align_speakers(transcript_segments: List[Dict],40 unmodified linesaligned.append(dict(seg))return aligned8 unmodified lines910111213141516127 unmodified lines14414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019140 unmodified lines2322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313328 unmodified linesimport loggingfrom typing import List, Dict, Optionalimport numpy as nptry:import torch as _torch_TORCH_AVAILABLE = True127 unmodified lineslogger.info(f"Diarization complete: {len(turns)} turns, {next_idx} speakers.")return turnsdef refine_speakers(self, audio_path: str, segments: List[Dict],num_speakers: Optional[int] = None) -> List[Dict]:"""Second opinion on who said each sentence, from a voice fingerprintof the whole sentence (see refine_with_voices). Uses the embeddingmodel pyannote has already loaded. Never fails the job: any problemkeeps pyannote's labels."""try:self._load_pipeline()embed = getattr(self.pipeline, "_embedding", None)if embed is None:return segmentsimport soundfile as _sfdata, sr = _sf.read(audio_path, dtype="float32", always_2d=True)wave = _torch.from_numpy(data.mean(axis=1).copy())target = getattr(embed, "sample_rate", 16000)if sr != target:import torchaudiowave = torchaudio.functional.resample(wave, sr, target)sr = targetstarted = time.time()prints: List[Optional[np.ndarray]] = []for seg in segments:a, b = float(seg.get("start", 0)), float(seg.get("end", 0))if b - a < VOICE_MIN_SEC:prints.append(None)continueif b - a > VOICE_MAX_SEC:mid = (a + b) / 2a, b = mid - VOICE_MAX_SEC / 2, mid + VOICE_MAX_SEC / 2clip = wave[int(a * sr):int(b * sr)]if clip.numel() < int(VOICE_MIN_SEC * sr):prints.append(None)continuevec = np.asarray(embed(clip.reshape(1, 1, -1))).reshape(-1)prints.append(vec if np.all(np.isfinite(vec)) else None)out = refine_with_voices(segments, prints, num_speakers)logger.info(f"Voice check took {time.time() - started:.1f}s for {len(segments)} sentences.")return outexcept Exception as e:logger.warning(f"Voice check skipped: {type(e).__name__}")return segments@staticmethoddef align_speakers(transcript_segments: List[Dict],40 unmodified linesaligned.append(dict(seg))return aligned# ── Voice check per sentence ────────────────────────────────────────────────# pyannote decides who speaks in 10 s windows. Two similar voices taking short# turns (a dialogue between two men, say) can end up as one speaker, and an# English narrator then takes the second slot. A voice fingerprint of each# whole sentence separates them much better, so after alignment the sentences# are also grouped by voice, and that grouping replaces pyannote's when it# separates the voices clearly better (silhouette score).VOICE_MIN_SEC = 1.0 # shorter sentences give unreliable fingerprintsVOICE_MAX_SEC = 20.0 # long sentences: fingerprint the middle 20 sVOICE_THRESHOLD = 0.45 # cosine distance at which two voices stay apartVOICE_MIN_SHARE = 0.02 # a "voice" with less speech than this...VOICE_MIN_TOTAL_SEC = 3.0 # ...or this joins its nearest real voiceVOICE_SWITCH_MARGIN = 0.10 # voice grouping must beat pyannote's by this muchdef _silhouette(V: np.ndarray, labels: List) -> float:"""Mean cosine silhouette of a labelling (rows of V are unit vectors)."""labels = np.asarray(labels, dtype=object)groups = list(dict.fromkeys(labels.tolist()))if len(groups) < 2:return -1.0D = 1.0 - V @ V.Tscores = []for i in range(len(V)):own = labels == labels[i]n_own = own.sum() - 1if n_own == 0:scores.append(0.0)continuea = D[i, own].sum() / n_ownb = min(D[i, labels == g].mean() for g in groups if g != labels[i])scores.append((b - a) / max(a, b) if max(a, b) > 0 else 0.0)return float(np.mean(scores))def group_voices(V: np.ndarray, durations: np.ndarray, num_speakers: Optional[int] = None) -> np.ndarray:"""Cluster sentence fingerprints into voices (average linkage, cosine)."""from scipy.cluster.hierarchy import linkage, fclusterif len(V) < 2:return np.zeros(len(V), dtype=int)Z = linkage(V, method="average", metric="cosine")if num_speakers:lab = fcluster(Z, t=num_speakers, criterion="maxclust")else:lab = fcluster(Z, t=VOICE_THRESHOLD, criterion="distance")total = durations.sum()big = [c for c in set(lab) if durations[lab == c].sum() >= max(VOICE_MIN_TOTAL_SEC, VOICE_MIN_SHARE * total)]if big:cent = {c: V[lab == c].mean(0) for c in big}for k, c in enumerate(lab):if c not in big:lab[k] = max(big, key=lambda b: float(V[k] @ cent[b]) / float(np.linalg.norm(cent[b])))return labdef refine_with_voices(segments: List[Dict], fingerprints: List[Optional[np.ndarray]],num_speakers: Optional[int] = None) -> List[Dict]:"""Relabel speakers by voice when that separates them clearly better.`fingerprints[i]` is sentence i's embedding, or None when too short."""idx = [i for i, f in enumerate(fingerprints) if f is not None]if len(idx) < 4:return segmentsV = np.stack([fingerprints[i] for i in idx]).astype(np.float64)V /= np.linalg.norm(V, axis=1, keepdims=True) + 1e-9dur = np.array([segments[i]["end"] - segments[i]["start"] for i in idx])voice = group_voices(V, dur, num_speakers)if len(set(voice)) < 2:return segmentscurrent = [segments[i].get("speaker") or "none" for i in idx]if not num_speakers and len(set(voice)) < len(set(current)):# The fix is for voices pyannote merged; never use it to merge people# pyannote kept apart (no reference shows that would be right).return segmentss_voice, s_current = _silhouette(V, list(voice)), _silhouette(V, current)if s_voice < s_current + VOICE_SWITCH_MARGIN:logger.info(f"Voice check kept pyannote's speakers (silhouette {s_current:.2f} vs {s_voice:.2f}).")return segments# Name voices SPEAKER_00, 01... in order of first appearance.names: Dict[int, str] = {}for v in voice:names.setdefault(int(v), f"SPEAKER_{len(names):02d}")labelled = {i: names[int(v)] for i, v in zip(idx, voice)}out = [dict(s) for s in segments]for i, name in labelled.items():out[i]["speaker"] = name# Sentences too short to fingerprint take the nearest labelled sentence.for i, seg in enumerate(out):if i in labelled:continuenearest = min(labelled, key=lambda j: abs((segments[j]["start"] + segments[j]["end"]) / 2- (seg["start"] + seg["end"]) / 2))seg["speaker"] = labelled[nearest]logger.info(f"Voice check relabelled speakers: {len(set(current))} -> {len(names)} "f"(silhouette {s_current:.2f} -> {s_voice:.2f}).")return out
19 unmodified lines2021222324252627134 unmodified lines16216316416516616755 unmodified lines22322422522622722822920 unmodified lines25025125225325425525619 unmodified linesfrom ..models.asr_pipeline import ASRPipeline, TranscriptionResultfrom ..diarization.engine import DiarizationEnginefrom .language_runs import (MIN_LID_SEC, Run, build_runs, candidates_for, dominant_language, drop_repeats, label_windows,pieces, scoring_codes, speech_windows,)logger = logging.getLogger(__name__)134 unmodified linestry:speaker_turns = self.diarization.diarize(str(processed_path), num_speakers=num_speakers)result.segments = self.diarization.align_speakers(result.segments, speaker_turns)except Exception as e:logger.warning(f"Diarization failed: {e}. Returning transcript without speakers.")else:55 unmodified lineswindows = speech_windows(audio, sr)if not windows:return Nonejudged = [i for i, w in enumerate(windows) if w.end - w.start >= MIN_LID_SEC]if not judged:return Nonedetector_key = DETECTOR_MODEL if DETECTOR_MODEL in self.registry.list_available_models() else self.current_model_key20 unmodified linesbest = max(candidates, key=lambda c: sc.get(c, -1e9) + prior.get(c, 0.0))time_by_lang[best] = time_by_lang.get(best, 0.0) + (w.end - w.start)dominant = max(time_by_lang, key=time_by_lang.get)label_windows(windows, scores, candidates, dominant, prior, implied)self._plan_windows = windowsruns = build_runs(windows, dominant)if len(runs) > 1:19 unmodified lines2021222324252627134 unmodified lines16216316416516616716816955 unmodified lines22522622722822923023123223320 unmodified lines25425525625725825926026126226326419 unmodified linesfrom ..models.asr_pipeline import ASRPipeline, TranscriptionResultfrom ..diarization.engine import DiarizationEnginefrom .language_runs import (ISLAND_MIN_SEC, MIN_LID_SEC, Run, build_runs, candidates_for, dominant_language, drop_repeats,label_windows, mark_english_islands, pieces, scoring_codes, speech_windows,)logger = logging.getLogger(__name__)134 unmodified linestry:speaker_turns = self.diarization.diarize(str(processed_path), num_speakers=num_speakers)result.segments = self.diarization.align_speakers(result.segments, speaker_turns)result.segments = self.diarization.refine_speakers(str(processed_path), result.segments, num_speakers=num_speakers)except Exception as e:logger.warning(f"Diarization failed: {e}. Returning transcript without speakers.")else:55 unmodified lineswindows = speech_windows(audio, sr)if not windows:return None# Windows from ISLAND_MIN_SEC are scored so short English phrases can be# found; only those from MIN_LID_SEC vote in the language sequence.judged = [i for i, w in enumerate(windows) if w.end - w.start >= ISLAND_MIN_SEC]if not judged:return Nonedetector_key = DETECTOR_MODEL if DETECTOR_MODEL in self.registry.list_available_models() else self.current_model_key20 unmodified linesbest = max(candidates, key=lambda c: sc.get(c, -1e9) + prior.get(c, 0.0))time_by_lang[best] = time_by_lang.get(best, 0.0) + (w.end - w.start)dominant = max(time_by_lang, key=time_by_lang.get)voting = [sc if (w.end - w.start) >= MIN_LID_SEC else None for w, sc in zip(windows, scores)]label_windows(windows, voting, candidates, dominant, prior, implied)islands = mark_english_islands(windows, scores, candidates, dominant)if islands:logger.info(f"Short English phrases kept in English: {islands}")self._plan_windows = windowsruns = build_runs(windows, dominant)if len(runs) > 1:
21 unmodified lines222324252627114 unmodified lines14214314414514614714814915015115215315415515615715815916016116216316416521 unmodified linesstart: float # seconds, on the processed audioend: floatlanguage: Optional[str] = None@dataclass114 unmodified linesw.language = nxt_lang or dominantdef build_runs(windows: List[Window], dominant: str) -> List[Run]:"""Contiguous same-language runs; runs under MIN_RUN_SEC join a neighbour."""runs: List[Run] = []for w in windows:lang = w.language or dominantif runs and runs[-1].language == lang:runs[-1].end = w.endelse:runs.append(Run(lang, w.start, w.end))changed = Truewhile changed and len(runs) > 1:changed = Falsefor i, r in enumerate(runs):if r.end - r.start >= MIN_RUN_SEC:continue# Join the longer neighbour (ties go to the previous one).prev = runs[i - 1] if i > 0 else Nonenxt = runs[i + 1] if i + 1 < len(runs) else Nonetarget = prev if (prev and (not nxt or (prev.end - prev.start) >= (nxt.end - nxt.start))) else nxtif target is prev:prev.end = r.end21 unmodified lines22232425262728114 unmodified lines14314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520621 unmodified linesstart: float # seconds, on the processed audioend: floatlanguage: Optional[str] = Nonepinned: bool = False # a short English phrase Whisper is sure about (see mark_english_islands)@dataclass114 unmodified linesw.language = nxt_lang or dominant# A short English phrase inside another language (a lesson title, "okay, next# item") is too short to survive MIN_RUN_SEC and the switch penalty, so the# Yoruba/Igbo/Hausa model mangles it. Measured on Whisper large-v3 (Oct 2026):# English phrases of 1.3-2.3 s scored 6.4-8.8 nats above Yoruba; Yoruba windows# of 1.2 s or more never scored above +4.0 for English. Shorter windows give# false spikes (+6.4 on a 0.5 s Yoruba word), so they are never pinned.ISLAND_MIN_SEC = 1.2ISLAND_MARGIN = 6.0def mark_english_islands(windows: List[Window], scores: Sequence[Optional[Dict[str, float]]],candidates: Sequence[str], dominant: str) -> int:"""Pin windows that are clearly English when the main language is not."""if dominant == "en" or "en" not in candidates:return 0pinned = 0for w, sc in zip(windows, scores):if not sc or w.end - w.start < ISLAND_MIN_SEC or "en" not in sc:continueothers = [v for c, v in sc.items() if c != "en"]if others and sc["en"] - max(others) >= ISLAND_MARGIN:w.language, w.pinned = "en", Truepinned += 1return pinneddef build_runs(windows: List[Window], dominant: str) -> List[Run]:"""Contiguous same-language runs; runs under MIN_RUN_SEC join a neighbourunless they hold a pinned English phrase."""runs: List[Run] = []pinned_runs = set()prev_pinned = Nonefor w in windows:lang = w.language or dominant# Pinned phrases form their own runs, so a window that only borrowed# "English" from its neighbour is still judged on its own length.if runs and runs[-1].language == lang and w.pinned == prev_pinned:runs[-1].end = w.endelse:runs.append(Run(lang, w.start, w.end))if w.pinned:pinned_runs.add(id(runs[-1]))prev_pinned = w.pinnedchanged = Truewhile changed and len(runs) > 1:changed = Falsefor i, r in enumerate(runs):if r.end - r.start >= MIN_RUN_SEC or id(r) in pinned_runs:continue# Join the longer neighbour (ties go to the previous one).prev = runs[i - 1] if i > 0 else Nonenxt = runs[i + 1] if i + 1 < len(runs) else None# Never stretch a pinned English phrase over other speech when# the other neighbour can take it.if prev and nxt and id(prev) in pinned_runs and id(nxt) not in pinned_runs:prev = Noneelif prev and nxt and id(nxt) in pinned_runs and id(prev) not in pinned_runs:nxt = Nonetarget = prev if (prev and (not nxt or (prev.end - prev.start) >= (nxt.end - nxt.start))) else nxtif target is prev:prev.end = r.end
src/diarization/engine.py+142
src/transcription/engine.py+12-4
src/transcription/language_runs.py+44-3