"""A stand-in for sherpa_onnx, for scripts/diarize-sherpa.test.mjs. Same surface as the calls scripts/diarize-sherpa.py makes, none of the models: a "voice" is a pure tone, so a test can say who is speaking when by writing a wav. Segmentation labels each voiced 0.25 s frame by its dominant frequency; an embedding is a smooth bump on a 192-bin frequency axis, so two tones of one pitch embed alike and two pitches embed apart; clustering is greedy cosine. The real engine is tested by the same file when DIARIZE_PYTHON / DIARIZE_SEG_MODEL / DIARIZE_EMB_MODEL name it. """ import numpy as np __version__ = "stub-1" SR = 16000 FRAME = 0.25 class _Cfg: def __init__(self, **kw): self.__dict__.update(kw) def validate(self): return True OfflineSpeakerDiarizationConfig = _Cfg OfflineSpeakerSegmentationModelConfig = _Cfg OfflineSpeakerSegmentationPyannoteModelConfig = _Cfg SpeakerEmbeddingExtractorConfig = _Cfg FastClusteringConfig = _Cfg def _pitch(x): if x.size == 0: return 0.0 spec = np.abs(np.fft.rfft(x * np.hanning(x.size))) return float(np.argmax(spec)) * SR / x.size class _Seg: def __init__(self, start, end, speaker): self.start, self.end, self.speaker = start, end, speaker class _Result(list): def sort_by_start_time(self): return _Result(sorted(self, key=lambda s: s.start)) class OfflineSpeakerDiarization: sample_rate = SR def __init__(self, cfg): self.cfg = cfg def process(self, samples): n = int(FRAME * SR) labels = {} segs = [] cur = None for i in range(0, samples.size - n + 1, n): x = samples[i:i + n] if float(np.sqrt(np.mean(x * x))) < 0.01: cur = None continue # Pitch to the nearest 100 Hz is the "speaker". key = int(round(_pitch(x) / 100.0)) spk = labels.setdefault(key, len(labels)) t = i / SR if cur is not None and cur.speaker == spk and abs(cur.end - t) < 1e-6: cur.end = t + FRAME else: cur = _Seg(t, t + FRAME, spk) segs.append(cur) return _Result(segs) class _Stream: def __init__(self): self.x = np.zeros(0, dtype=np.float32) def accept_waveform(self, sr, x): self.x = np.concatenate([self.x, np.asarray(x, dtype=np.float32)]) def input_finished(self): pass class SpeakerEmbeddingExtractor: dim = 192 def __init__(self, cfg): self.cfg = cfg def create_stream(self): return _Stream() def is_ready(self, stream): # STUB_NOT_READY: an embedder that never has enough (audio that decodes, # and still no fingerprint). import os if os.environ.get("STUB_NOT_READY"): return False return stream.x.size >= int(0.5 * SR) def compute(self, stream): f = _pitch(stream.x) axis = np.arange(self.dim, dtype=np.float64) centre = min(self.dim - 1, f / 20.0) v = np.exp(-((axis - centre) ** 2) / 18.0) + 0.01 return list(v) class FastClustering: def __init__(self, cfg): self.cfg = cfg def __call__(self, arr): cents = [] out = [] for v in np.asarray(arr, dtype=np.float64): v = v / np.linalg.norm(v) best = -1 for k, c in enumerate(cents): if float(np.dot(v, c)) > 0.5: best = k break if best < 0: cents.append(v) best = len(cents) - 1 out.append(best) return out