Update asr_diarization/pipeline.py
Browse files16 unmodified lines1718192021225 unmodified lines2829303132333437 unmodified lines72737475767715 unmodified lines93949596979899100 unmodified lines200201202203204205206332 unmodified lines5395405415425435445458 unmodified lines55455555655755855910 unmodified lines57057157257357457557615 unmodified lines5925935945955965978 unmodified lines60660760860961061177 unmodified lines68969069169216 unmodified linesfrom pyannote.metrics.diarization import DiarizationErrorRatefrom jiwer import wer, Compose, ToLowerCase, RemovePunctuation, RemoveMultipleSpaces, Stripclass ASR_Diarization:def __init__(self, HF_TOKEN,5 unmodified linesmin_segment_duration=0.5,snr_threshold=15.0,min_whisper_duration=0.3,embedding_threshold=0.5):self.HF_TOKEN = HF_TOKENself.device = "cuda" if torch.cuda.is_available() else "cpu"37 unmodified linesprint("WebRTC VAD not available")self.use_vad = False# Load ASR modelif model_path and os.path.exists(model_path):print(f"Loading custom ASR model from: {model_path}")15 unmodified linesreturn_timestamps=True)# ========== SPEAKER EMBEDDING METHODS (From Second Pipeline) ==========def load_unknown_speakers(self, unknown_speakers_path):"""Load unknown speakers from JSON file"""100 unmodified linesreturn cluster_embeddings# ========== EXISTING METHODS (Enhanced) ==========def clean_transcription_text(self, text):"""Clean ASR text for better TTS performance"""332 unmodified linesdef run_pipeline(self, audio_path, output_dir=None, base_name=None,ref_rttm=None, ref_json=None, nse_events=None,enrolled_speakers=None, unknown_speakers_path=None):"""Enhanced pipeline with speaker embedding support"""# Validate input audio fileif not os.path.exists(audio_path):raise FileNotFoundError(f"Audio file not found: {audio_path}")8 unmodified linesprint(f"Processing with VAD: {'ON' if self.use_vad else 'OFF'}")print(f"Using speaker embeddings: {'YES' if self.embedding_model else 'NO'}")# Run diarization and transcriptiondiar_json = self.run_diarization(audio_path)10 unmodified linesif not self.embedding_model:merged_segments, speakers = self.map_speaker_labels(merged_segments)# Combine ASR segments with NSE events if providedif nse_events:print(f"Combining {len(merged_segments)} ASR segments with {len(nse_events)} NSE events")all_segments = merged_segments + nse_events15 unmodified linesf"{seg['speaker']} <NA> <NA>\n")# Save transcription (with NSE events if available)merged_path = os.path.join(output_dir, f"{base_name}_merged_transcription.json")with open(merged_path, "w") as f:8 unmodified linesreturn {"speakers": speakers,"segments": all_segments, # Return combined segments"evaluation": eval_results}77 unmodified linesfinally:# Always clean up temporary fileif tmp_path and os.path.exists(tmp_path):os.unlink(tmp_path)16 unmodified lines17181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911925 unmodified lines19819920020120220320420537 unmodified lines24324424524624724824925025125225325425525625715 unmodified lines273274275276277278279100 unmodified lines380381382383384385386332 unmodified lines7197207217227237247258 unmodified lines73473573673773873974074174274374474574674774810 unmodified lines75976076176276376476515 unmodified lines7817827837847857867877887897907918 unmodified lines80080180280380480580677 unmodified lines88488588688716 unmodified linesfrom pyannote.metrics.diarization import DiarizationErrorRatefrom jiwer import wer, Compose, ToLowerCase, RemovePunctuation, RemoveMultipleSpaces, Strip# Add YAMNet importstry:import tensorflow as tfimport tensorflow_hub as hubimport librosaYAMNET_AVAILABLE = Trueexcept Exception:YAMNET_AVAILABLE = False# NSE configuration constantsNSE_THRESHOLDS = {"human": 0.20, "environment": 0.40, "default": 0.30}NSE_HUMAN_CLASSES = {"Cough","Sneeze","Throat clearing","Sniff","Breathing","Sigh","Laughter","Giggle","Chuckle","Snicker"}NSE_ENVIRONMENT_CLASSES = {"Clapping","Finger snapping","Knock","Tap","Keyboard typing","Computer keyboard","Mouse click","Writing","Page turning","Paper rustling","Pen","Footsteps","Door","Door knock","Door slam","Chair","Furniture"}NSE_LABELS_KEEP = NSE_HUMAN_CLASSES.union(NSE_ENVIRONMENT_CLASSES)FALLBACK_NSE_LABEL = "non-speech-event"NSE_CANONICAL = {"cough": "Cough", "coughing": "Cough","sneeze": "Sneeze", "sneezing": "Sneeze","throat clearing": "Throat clearing","sniff": "Sniff", "sniffle": "Sniff","breath": "Breathing", "breathing": "Breathing","sigh": "Sigh","laughter": "Laughter", "laughing": "Laughter","giggle": "Laughter", "chuckle": "Laughter", "snicker": "Laughter","clapping": "Clapping", "applause": "Clapping","knock": "Knock", "door knock": "Knock","door slam": "Door", "chair": "Chair", "furniture": "Chair","page turning": "Page turning", "paper rustling": "Page turning","keyboard typing": "Keyboard typing", "computer keyboard": "Keyboard typing","mouse click": "Mouse click", "tap": "Tap", "writing": "Writing", "pen": "Writing","footsteps": "Footsteps",}class YAMNetNSEDetector:def __init__(self):self.yamnet_model = Noneself.yamnet_class_names = Noneself._load_yamnet()def _load_yamnet(self):"""Load YAMNet model"""if not YAMNET_AVAILABLE:print("[YAMNet] TensorFlow/Librosa not available")returntry:print("[YAMNet] Loading YAMNet model...")self.yamnet_model = hub.load("https://tfhub.dev/google/yamnet/1")class_map_path = self.yamnet_model.class_map_path().numpy().decode("utf-8")self.yamnet_class_names = [line.strip() for line in open(class_map_path, "r", encoding="utf-8").read().splitlines()]print("[YAMNet] ✅ YAMNet loaded successfully")except Exception as e:print(f"[YAMNet] ❌ Failed to load YAMNet: {e}")self.yamnet_model = Nonedef detect_nse_events(self, audio_path, merge_gap=0.5, min_duration=0.1, conf_thresh=0.05):"""Detect NSE events using YAMNet (same logic as old server)"""if self.yamnet_model is None:return self._detect_nse_fallback(audio_path)try:wav, sr = librosa.load(audio_path, sr=16000, mono=True)except Exception as e:print(f"[YAMNet] Failed to load audio: {e}")return self._detect_nse_fallback(audio_path)scores, _, _ = self.yamnet_model(np.array(wav, dtype=np.float32))scores = scores.numpy()frame_dur = 0.48raw = []for i, sc in enumerate(scores):idx = int(np.argmax(sc))score = float(np.max(sc))if score < conf_thresh:continuelabel_raw = self.yamnet_class_names[idx].strip().lower()label = NSE_CANONICAL.get(label_raw, label_raw)raw.append({"label": label,"start": i * frame_dur,"end": (i + 1) * frame_dur,"confidence": score})if not raw:return self._detect_nse_fallback(audio_path)# Step 1: Merge consecutive frames with same labelmerged = [raw[0]]for ev in raw[1:]:cur = merged[-1]# Merge if same label and within merge_gapif ev["label"] == cur["label"] and ev["start"] - cur["end"] <= merge_gap:cur["end"] = ev["end"]cur["confidence"] = max(cur["confidence"], ev["confidence"])else:merged.append(ev)# Step 2: Filter by min_durationfiltered = [ev for ev in merged if ev["end"] - ev["start"] >= min_duration]# Step 3: Keep only desired labelsfinal_events = []for ev in filtered:if ev["label"] in NSE_LABELS_KEEP:final_events.append({"speaker": "NSE","event": ev["label"],"text": f"[{ev['label']}]","start": round(ev["start"], 3),"end": round(ev["end"], 3),"confidence": round(ev["confidence"], 3),})return final_events if final_events else self._detect_nse_fallback(audio_path)def _detect_nse_fallback(self, audio_path):"""Fallback NSE detection using energy-based approach"""try:y, sr = librosa.load(audio_path, sr=16000, mono=True)except:return []hop, win = int(0.02 * sr), int(0.05 * sr)rms = librosa.feature.rms(y=y, frame_length=win, hop_length=hop)[0]times = librosa.frames_to_time(np.arange(len(rms)), sr=sr, hop_length=hop, n_fft=win)# Stricter thresholdthresh = np.mean(rms) + 2 * np.std(rms)evs, active, start_t = [], False, 0.0for t, r in zip(times, rms):if r > thresh and not active:active, start_t = True, tif r <= thresh and active:dur = t - start_tif dur >= 0.5: # Only count longer burstsevs.append({"speaker": "NSE","event": FALLBACK_NSE_LABEL,"text": f"[{FALLBACK_NSE_LABEL}]","start": round(start_t, 3),"end": round(t, 3),"confidence": float(min(1.0, r / (thresh + 1e-8))),})active = Falseif active:dur = times[-1] + 0.05 - start_tif dur >= 0.5:evs.append({"speaker": "NSE","event": FALLBACK_NSE_LABEL,"text": f"[{FALLBACK_NSE_LABEL}]","start": round(start_t, 3),"end": round(times[-1] + 0.05, 3),"confidence": 0.5,})return evsclass ASR_Diarization:def __init__(self, HF_TOKEN,5 unmodified linesmin_segment_duration=0.5,snr_threshold=15.0,min_whisper_duration=0.3,embedding_threshold=0.5,enable_nse=True): # ADD enable_nse parameterself.HF_TOKEN = HF_TOKENself.device = "cuda" if torch.cuda.is_available() else "cpu"37 unmodified linesprint("WebRTC VAD not available")self.use_vad = False# Initialize YAMNet NSE detectorself.enable_nse = enable_nseif self.enable_nse:self.nse_detector = YAMNetNSEDetector()print("[NSE] YAMNet-based NSE detector initialized")else:self.nse_detector = Noneprint("[NSE] NSE detection disabled")# Load ASR modelif model_path and os.path.exists(model_path):print(f"Loading custom ASR model from: {model_path}")15 unmodified linesreturn_timestamps=True)# ========== SPEAKER EMBEDDING METHODS ==========def load_unknown_speakers(self, unknown_speakers_path):"""Load unknown speakers from JSON file"""100 unmodified linesreturn cluster_embeddings# ========== EXISTING METHODS ==========def clean_transcription_text(self, text):"""Clean ASR text for better TTS performance"""332 unmodified linesdef run_pipeline(self, audio_path, output_dir=None, base_name=None,ref_rttm=None, ref_json=None, nse_events=None,enrolled_speakers=None, unknown_speakers_path=None):"""Enhanced pipeline with YAMNet NSE detection"""# Validate input audio fileif not os.path.exists(audio_path):raise FileNotFoundError(f"Audio file not found: {audio_path}")8 unmodified linesprint(f"Processing with VAD: {'ON' if self.use_vad else 'OFF'}")print(f"Using speaker embeddings: {'YES' if self.embedding_model else 'NO'}")print(f"Using YAMNet NSE detection: {'YES' if self.enable_nse else 'NO'}")# Run NSE detection using YAMNet (same as old server)if nse_events is None and self.enable_nse:print("[NSE] Detecting non-speech events with YAMNet...")nse_events = self.nse_detector.detect_nse_events(audio_path)print(f"[NSE] Detected {len(nse_events)} non-speech events")elif nse_events is None:nse_events = []# Run diarization and transcriptiondiar_json = self.run_diarization(audio_path)10 unmodified linesif not self.embedding_model:merged_segments, speakers = self.map_speaker_labels(merged_segments)# Combine ASR segments with NSE eventsif nse_events:print(f"Combining {len(merged_segments)} ASR segments with {len(nse_events)} NSE events")all_segments = merged_segments + nse_events15 unmodified linesf"{seg['speaker']} <NA> <NA>\n")# Save NSE events separatelynse_path = os.path.join(output_dir, f"{base_name}_nse_events.json")with open(nse_path, "w") as f:json.dump(nse_events, f, indent=2)# Save transcription (with NSE events if available)merged_path = os.path.join(output_dir, f"{base_name}_merged_transcription.json")with open(merged_path, "w") as f:8 unmodified linesreturn {"speakers": speakers,"segments": all_segments, # Return combined segments"nse_events": nse_events, # Return NSE events separately too"evaluation": eval_results}77 unmodified linesfinally:# Always clean up temporary fileif tmp_path and os.path.exists(tmp_path):os.unlink(tmp_path)
asr_diarization/pipeline.py+201-6