# -*- coding: utf-8 -*- """FunASR-style realtime speaker chunking and clustering.""" from __future__ import annotations import logging from typing import Any, Dict, List, Optional, Tuple import numpy as np import scipy.linalg import sklearn.metrics.pairwise from sklearn.cluster._kmeans import k_means from app.core.config import settings from app.core.executor import run_sync from app.services.speaker_registry import get_speaker_registry_service logger = logging.getLogger(__name__) class RealtimeSpeakerClusterer: """Sentence-level speaker attribution using chunk embeddings and session clustering.""" FUNASR_SMOOTH_MINDUR_SEC = 0.7 FUNASR_MAX_HISTORY_CHUNKS = 128 FUNASR_CENTER_MATCH_THRESHOLD = 0.6 _REGISTRY_MATCH_MIN_SEC = 2.4 def _normalize_embedding(self, embedding: np.ndarray) -> np.ndarray: emb = np.asarray(embedding, dtype=np.float32).reshape(-1) norm = max(float(np.linalg.norm(emb)), 1e-12) return (emb / norm).astype(np.float32) def _correct_labels(self, labels: np.ndarray) -> np.ndarray: labels_id = 0 id2id: dict[int, int] = {} new_labels: list[int] = [] for label in labels.tolist(): label = int(label) if label not in id2id: id2id[label] = labels_id labels_id += 1 new_labels.append(id2id[label]) return np.asarray(new_labels, dtype=np.int32) def _spectral_cluster(self, X: np.ndarray, oracle_num: Optional[int] = None) -> np.ndarray: sim_mat = sklearn.metrics.pairwise.cosine_similarity(X, X) A = sim_mat.copy() pval = 0.022 if A.shape[0] * pval < 6: pval = 6.0 / A.shape[0] n_elems = int((1 - pval) * A.shape[0]) for i in range(A.shape[0]): low_indexes = np.argsort(A[i, :])[:n_elems] A[i, low_indexes] = 0 A = 0.5 * (A + A.T) A[np.diag_indices(A.shape[0])] = 0 D = np.diag(np.sum(np.abs(A), axis=1)) L = D - A lambdas, eig_vecs = scipy.linalg.eigh(L) if oracle_num is not None: num_spk = max(int(oracle_num), 1) else: min_num_spks = 1 max_num_spks = min(15, max(1, X.shape[0] - 1)) eig_slice = lambdas[min_num_spks - 1 : max_num_spks + 1] gap_list = [float(eig_slice[i + 1]) - float(eig_slice[i]) for i in range(len(eig_slice) - 1)] num_spk = int(np.argmax(gap_list)) + min_num_spks if gap_list else 1 emb = eig_vecs[:, : max(num_spk, 1)] _, labels, _ = k_means(emb, max(num_spk, 1)) return np.asarray(labels, dtype=np.int32) def _merge_by_cos(self, labels: np.ndarray, embs: np.ndarray, cos_thr: float) -> np.ndarray: labels = np.asarray(labels, dtype=np.int32).copy() while True: spk_num = int(labels.max()) + 1 if spk_num <= 1: break centers = [] for i in range(spk_num): spk_emb = embs[labels == i].mean(0) centers.append(spk_emb) centers = np.stack(centers, axis=0) norm_centers = centers / np.linalg.norm(centers, axis=1, keepdims=True) affinity = np.matmul(norm_centers, norm_centers.T) affinity = np.triu(affinity, 1) spks = np.unravel_index(np.argmax(affinity), affinity.shape) if float(affinity[spks]) < cos_thr: break for i in range(len(labels)): if labels[i] == spks[1]: labels[i] = spks[0] elif labels[i] > spks[1]: labels[i] -= 1 return self._correct_labels(labels) def _cluster_embeddings(self, X: np.ndarray, oracle_num: Optional[int] = None) -> np.ndarray: if X.shape[0] < 20: labels = np.zeros(X.shape[0], dtype=np.int32) else: labels = self._spectral_cluster(X, oracle_num=oracle_num) return self._merge_by_cos(labels, X, cos_thr=0.78 if oracle_num is None else 1.0) def _map_cluster_centers( self, cluster_centers: np.ndarray, speaker_centers: List[np.ndarray], speaker_center_updates: List[int], *, update_centers: bool, ) -> List[int]: """Map each window's temporary cluster label to a persistent speaker ID. FunASR's ClusterBackend labels are local to each clustering pass. Its realtime tracker maps those labels through cosine-matched centroids so speakers keep the same identity as the 128-chunk window moves. """ centers = np.stack( [self._normalize_embedding(center) for center in np.asarray(cluster_centers)], axis=0, ) stable_ids: List[int] = [] used_ids: set[int] = set() for center in centers: best_id: Optional[int] = None best_score = -1.0 for candidate, known_center in enumerate(speaker_centers): if candidate in used_ids: continue score = float(np.dot(center, self._normalize_embedding(known_center))) if score > best_score: best_id, best_score = candidate, score matched = best_id is not None and best_score >= self.FUNASR_CENTER_MATCH_THRESHOLD created = False if not matched and update_centers and len(speaker_centers) < 15: best_id = len(speaker_centers) speaker_centers.append(center.copy()) speaker_center_updates.append(1) matched = True created = True elif best_id is None: # Match FunASR's max-speaker fallback when all old IDs were used. if not speaker_centers: best_id = 0 else: scores = [float(np.dot(center, self._normalize_embedding(item))) for item in speaker_centers] best_id = int(np.argmax(scores)) if update_centers and matched and not created: assert best_id is not None count = speaker_center_updates[best_id] weight = 1.0 / min(count + 1, 20) updated = (1.0 - weight) * speaker_centers[best_id] + weight * center speaker_centers[best_id] = self._normalize_embedding(updated) speaker_center_updates[best_id] = count + 1 assert best_id is not None stable_ids.append(best_id) used_ids.add(best_id) return stable_ids def cluster_chunk_history( self, chunks: List[Dict[str, Any]], speaker_centers: List[np.ndarray], speaker_center_updates: List[int], *, update_centers: bool, ) -> Tuple[List[Dict[str, Any]], List[int]]: """Cluster a fixed-size rolling window of timestamped speaker chunks.""" valid_chunks = [item for item in chunks if item.get("embedding") is not None] valid_chunks = valid_chunks[-self.FUNASR_MAX_HISTORY_CHUNKS:] if not valid_chunks: return [], [] embeddings = np.stack( [self._normalize_embedding(np.asarray(item["embedding"], dtype=np.float32)) for item in valid_chunks], axis=0, ) labels = self._cluster_embeddings(embeddings, oracle_num=None) temporary_ids = sorted({int(value) for value in labels.tolist()}) centers = np.stack( [self._normalize_embedding(embeddings[labels == label].mean(axis=0)) for label in temporary_ids], axis=0, ) stable_ids = self._map_cluster_centers( centers, speaker_centers, speaker_center_updates, update_centers=update_centers, ) temp_to_stable = dict(zip(temporary_ids, stable_ids)) timeline = self._postprocess_timeline(valid_chunks, labels, embeddings) for item in timeline: item["cluster_index"] = int(temp_to_stable[int(item["cluster_index"])]) return timeline, stable_ids def flatten_chunk_history(self, records: List[Dict[str, Any]]) -> List[Dict[str, Any]]: """Return the most recent FunASR-sized history from segment records.""" chunks: List[Dict[str, Any]] = [] for record in records: entries = record.get("chunks") or [] if entries: chunks.extend(entries) continue embeddings = record.get("embeddings") or [] if not embeddings and record.get("embedding") is not None: embeddings = [record["embedding"]] for embedding in embeddings: chunks.append({ "start_ms": int(record.get("start_ms", 0)), "end_ms": int(record.get("end_ms", record.get("start_ms", 0))), "embedding": embedding, }) return chunks[-self.FUNASR_MAX_HISTORY_CHUNKS:] @staticmethod def pick_timeline_speaker( timeline: List[Dict[str, Any]], *, start_ms: int, end_ms: int, ) -> Optional[int]: """Assign a sentence to its dominant overlapping speaker, as FunASR does.""" sentence_speaker = 0 max_overlap = 0 for item in timeline: overlap = min(end_ms, int(item["end_ms"])) - max(start_ms, int(item["start_ms"])) if overlap > 0: speaker = int(item["cluster_index"]) if overlap > max_overlap: max_overlap = overlap sentence_speaker = speaker if sentence_speaker == speaker: max_overlap += overlap if max_overlap <= 0: return None return sentence_speaker def build_sv_chunks( self, audio: np.ndarray, *, segment_start_ms: int = 0, ) -> List[Dict[str, Any]]: audio = np.asarray(audio, dtype=np.float32).flatten() if audio.size == 0: return [] sample_rate = 16000 chunk_len = int(1.5 * sample_rate) chunk_shift = int(0.75 * sample_rate) chunks: List[Dict[str, Any]] = [] last_chunk_end = 0 for chunk_start in range(0, audio.shape[0], chunk_shift): chunk_end = min(chunk_start + chunk_len, audio.shape[0]) if chunk_end <= last_chunk_end: break actual_start = max(0, chunk_end - chunk_len) actual_end = chunk_end last_chunk_end = actual_end chunk_audio = np.asarray(audio[actual_start:actual_end], dtype=np.float32) if chunk_audio.shape[0] < chunk_len: chunk_audio = np.pad(chunk_audio, (0, chunk_len - chunk_audio.shape[0]), "constant") chunks.append( { "start_ms": int(segment_start_ms + actual_start / 16.0), "end_ms": int(segment_start_ms + actual_end / 16.0), "audio": chunk_audio, } ) return chunks async def extract_chunk_embeddings( self, audio: np.ndarray, *, segment_start_ms: int = 0, ) -> List[Dict[str, Any]]: chunk_items = self.build_sv_chunks(audio, segment_start_ms=segment_start_ms) if not chunk_items: chunk_items = [ { "start_ms": int(segment_start_ms), "end_ms": int(segment_start_ms + np.asarray(audio, dtype=np.float32).size / 16.0), "audio": np.asarray(audio, dtype=np.float32), } ] registry = get_speaker_registry_service() results: List[Dict[str, Any]] = [] for item in chunk_items: embedding = await run_sync( registry.extract_embedding_from_audio, item["audio"], 16000, model_id=settings.REALTIME_SV_MODEL, model_revision=settings.REALTIME_SV_MODEL_REVISION or None, ) results.append( { "start_ms": int(item["start_ms"]), "end_ms": int(item["end_ms"]), "embedding": self._normalize_embedding(np.asarray(embedding, dtype=np.float32)), } ) return results async def extract_registry_embedding(self, audio: np.ndarray) -> Optional[np.ndarray]: audio_array = np.asarray(audio, dtype=np.float32).flatten() if audio_array.size == 0: return None try: registry = get_speaker_registry_service() embedding = await run_sync( registry.extract_embedding_from_audio, audio_array, 16000, ) return self._normalize_embedding(np.asarray(embedding, dtype=np.float32)) except Exception as exc: logger.warning("Realtime registry speaker embedding failed: %s", exc) return None def _merge_seque(self, distribute_res: List[List[float]]) -> List[List[float]]: if not distribute_res: return [] res = [distribute_res[0][:]] for item in distribute_res[1:]: if item[2] != res[-1][2] or item[0] > res[-1][1]: res.append(item[:]) else: res[-1][1] = item[1] return res def _smooth_timeline( self, res: List[List[float]], mindur: float = FUNASR_SMOOTH_MINDUR_SEC, ) -> List[List[float]]: if len(res) < 2: return res for item in res: item[0] = round(float(item[0]), 2) item[1] = round(float(item[1]), 2) for idx in range(len(res)): if res[idx][1] - res[idx][0] < mindur: if idx == 0: res[idx][2] = res[idx + 1][2] elif idx == len(res) - 1: res[idx][2] = res[idx - 1][2] elif res[idx][0] - res[idx - 1][1] <= res[idx + 1][0] - res[idx][1]: res[idx][2] = res[idx - 1][2] else: res[idx][2] = res[idx + 1][2] return self._merge_seque(res) def _postprocess_timeline( self, flat_chunks: List[Dict[str, Any]], labels: np.ndarray, embeddings: np.ndarray, ) -> List[Dict[str, Any]]: assert len(flat_chunks) == len(labels) labels = self._correct_labels(labels) distribute_res = [ [ float(chunk["start_ms"]) / 1000.0, float(chunk["end_ms"]) / 1000.0, int(labels[idx]), ] for idx, chunk in enumerate(flat_chunks) ] distribute_res = self._merge_seque(distribute_res) def is_overlapped(t1: float, t2: float) -> bool: return t1 > t2 + 1e-4 for idx in range(1, len(distribute_res)): if is_overlapped(distribute_res[idx - 1][1], distribute_res[idx][0]): pivot = (distribute_res[idx][0] + distribute_res[idx - 1][1]) / 2.0 distribute_res[idx][0] = pivot distribute_res[idx - 1][1] = pivot distribute_res = self._smooth_timeline(distribute_res) return [ { "start_ms": int(round(item[0] * 1000.0)), "end_ms": int(round(item[1] * 1000.0)), "cluster_index": int(item[2]), } for item in distribute_res ] def cluster_records_with_ranges( self, records: List[Dict[str, Any]], ) -> Tuple[List[Dict[str, Any]], List[int], List[Dict[str, Any]]]: # Preserve the existing helper API while routing it through the same # 128-chunk policy used by live sessions. return self.cluster_records_with_stable_history(records, [], [], update_centers=True) def cluster_records_with_stable_history( self, records: List[Dict[str, Any]], speaker_centers: List[np.ndarray], speaker_center_updates: List[int], *, update_centers: bool, ) -> Tuple[List[Dict[str, Any]], List[int], List[Dict[str, Any]]]: """Cluster only the last 128 chunks and return persistent speaker IDs.""" chunks = self.flatten_chunk_history(records) timeline, _ = self.cluster_chunk_history( chunks, speaker_centers, speaker_center_updates, update_centers=update_centers, ) assignments = [ self.pick_timeline_speaker( timeline, start_ms=int(record.get("start_ms", 0)), end_ms=int(record.get("end_ms", record.get("start_ms", 0))), ) for record in records ] cluster_ids = sorted({int(item["cluster_index"]) for item in timeline}) clusters: List[Dict[str, Any]] = [] for cluster_id in cluster_ids: refs = [ record for record, assigned_id in zip(records, assignments) if assigned_id == cluster_id ] if cluster_id < len(speaker_centers): center = speaker_centers[cluster_id] else: matching_embeddings = [ item["embedding"] for item in chunks if self.pick_timeline_speaker( timeline, start_ms=int(item["start_ms"]), end_ms=int(item["end_ms"]), ) == cluster_id ] center = np.mean(matching_embeddings or [chunks[0]["embedding"]], axis=0) clusters.append({ "cluster_index": cluster_id, "centroid": self._normalize_embedding(np.asarray(center, dtype=np.float32)), "count": sum(1 for item in timeline if int(item["cluster_index"]) == cluster_id), "record_refs": refs, }) return clusters, [-1 if value is None else int(value) for value in assignments], timeline def cluster_records( self, records: List[Dict[str, Any]], ) -> Tuple[List[Dict[str, Any]], List[int]]: clusters, record_assignments, _ = self.cluster_records_with_ranges(records) return clusters, record_assignments async def resolve_segment_speaker( self, speaker_records: List[Dict[str, Any]], audio: np.ndarray, *, segment_start_ms: int, segment_end_ms: int, enable_registry_match: bool, speaker_threshold: Optional[float], speaker_centers: List[np.ndarray], speaker_center_updates: List[int], ) -> Optional[Dict[str, Any]]: duration_sec = float(len(audio)) / 16000.0 current_chunks = await self.extract_chunk_embeddings( np.asarray(audio, dtype=np.float32), segment_start_ms=segment_start_ms, ) if not current_chunks: return None mean_embedding = self._normalize_embedding( np.mean(np.stack([chunk["embedding"] for chunk in current_chunks], axis=0), axis=0) ) # Re-cluster the same fixed number of recent chunks as FunASR. Chunk # labels are temporary, so the session-owned centers keep IDs stable. history_chunks = self.flatten_chunk_history(speaker_records) timeline, _ = self.cluster_chunk_history( history_chunks + current_chunks, speaker_centers, speaker_center_updates, update_centers=True, ) cluster_index = self.pick_timeline_speaker( timeline, start_ms=segment_start_ms, end_ms=segment_end_ms, ) if cluster_index is None: cluster_index = max(len(speaker_centers) - 1, 0) speaker_id = f"Speaker{cluster_index + 1:02d}" speaker_name = speaker_id user_id = None registry_speaker_id = None confidence = 1.0 strategy = "chunk_cluster" if ( enable_registry_match and duration_sec >= self._REGISTRY_MATCH_MIN_SEC ): # Realtime clustering can use a dedicated fast model, while the # registry stores embeddings from the registration model. Match the # registry in its own embedding space instead of comparing vectors # extracted by a different model. registry_embedding = await self.extract_registry_embedding(audio) if registry_embedding is not None: matched = await get_speaker_registry_service().identify_embedding( registry_embedding, threshold=speaker_threshold, ) if matched.get("name"): speaker_id = matched.get("speaker_id") or speaker_id speaker_name = matched.get("name") or speaker_name user_id = matched.get("user_id") registry_speaker_id = matched.get("speaker_id") strategy = "registry_match" return { "speaker_id": speaker_id, "speaker_name": speaker_name, "user_id": user_id, "registry_speaker_id": registry_speaker_id, "speaker_confidence": round(confidence, 4), "speaker_strategy": strategy, "_cluster_index": int(cluster_index), "_embedding": mean_embedding, "_chunk_embeddings": [np.asarray(chunk["embedding"], dtype=np.float32) for chunk in current_chunks], "_chunks": current_chunks, "_matched_existing": True, "_speaker_timeline": timeline, } _realtime_speaker_clusterer: Optional[RealtimeSpeakerClusterer] = None def get_realtime_speaker_clusterer() -> RealtimeSpeakerClusterer: global _realtime_speaker_clusterer if _realtime_speaker_clusterer is None: _realtime_speaker_clusterer = RealtimeSpeakerClusterer() return _realtime_speaker_clusterer