Update asr_diarization/pipeline.py
Browse files64 unmodified lines656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819964 unmodified linesself._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.3, min_duration=0.2, conf_thresh=0.1):"""Detect NSE events using YAMNet with improved sensitivity"""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.48 # YAMNet frame durationraw = []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)# Only keep events we care aboutif label in NSE_LABELS_KEEP:raw.append({"label": label,"start": i * frame_dur,"end": (i + 1) * frame_dur,"confidence": score})if not raw:print("[YAMNet] No NSE events detected above threshold")return self._detect_nse_fallback(audio_path)# Improved merging - be more aggressivemerged = [raw[0]]for ev in raw[1:]:cur = merged[-1]# Merge if same label and within merge_gap OR if confidence is highif (ev["label"] == cur["label"] and ev["start"] - cur["end"] <= merge_gap) or ev["confidence"] > 0.5:cur["end"] = ev["end"]cur["confidence"] = max(cur["confidence"], ev["confidence"])else:merged.append(ev)# Filter by min_durationfiltered = [ev for ev in merged if ev["end"] - ev["start"] >= min_duration]# Format final eventsfinal_events = []for ev in filtered: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),})print(f"[YAMNet] Final NSE events: {len(final_events)}")for event in final_events:print(f" - {event['event']}: {event['start']:.2f}-{event['end']:.2f}s (conf: {event['confidence']:.3f})")return final_eventsdef _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,64 unmodified lines656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725864 unmodified linesself._load_yamnet()def _load_yamnet(self):"""Load YAMNet model with better error handling"""if not YAMNET_AVAILABLE:print("[YAMNet] ❌ TensorFlow/Librosa not available")returntry:print("[YAMNet] Loading YAMNet model...")# Clear any existing TensorFlow sessionimport tensorflow as tftf.keras.backend.clear_session()self.yamnet_model = hub.load("https://tfhub.dev/google/yamnet/1")# Get class namesclass_map_path = self.yamnet_model.class_map_path().numpy().decode("utf-8")self.yamnet_class_names = []with open(class_map_path, "r", encoding="utf-8") as f:for line in f:line = line.strip()if line:self.yamnet_class_names.append(line)print(f"[YAMNet] ✅ YAMNet loaded successfully - {len(self.yamnet_class_names)} classes")print(f"[YAMNet] Available NSE classes: {list(NSE_LABELS_KEEP)}")except Exception as e:print(f"[YAMNet] ❌ Failed to load YAMNet: {e}")import tracebacktraceback.print_exc()self.yamnet_model = Nonedef detect_nse_events(self, audio_path, merge_gap=0.3, min_duration=0.2, conf_thresh=0.05):"""Enhanced NSE detection with better debugging"""if self.yamnet_model is None:print("[YAMNet] ❌ Model not available, using fallback")return self._detect_nse_fallback(audio_path)try:print(f"[YAMNet] Loading audio: {audio_path}")# Check if file exists and has contentif not os.path.exists(audio_path):print(f"[YAMNet] ❌ Audio file not found: {audio_path}")return []file_size = os.path.getsize(audio_path)if file_size == 0:print(f"[YAMNet] ❌ Audio file is empty: {audio_path}")return []print(f"[YAMNet] File size: {file_size} bytes")# Load audio with librosawav, sr = librosa.load(audio_path, sr=16000, mono=True)print(f"[YAMNet] Audio loaded: {len(wav)} samples, {sr} Hz, duration: {len(wav)/sr:.2f}s")# Check if audio has meaningful contentif np.max(np.abs(wav)) < 0.001:print("[YAMNet] ⚠️ Audio appears to be silent or very quiet")return []# Run YAMNet inferenceprint("[YAMNet] Running YAMNet inference...")scores, embeddings, spectrogram = self.yamnet_model(np.array(wav, dtype=np.float32))scores = scores.numpy()frame_dur = 0.48 # YAMNet frame duration (480ms)print(f"[YAMNet] Processed {len(scores)} frames")raw = []for i, sc in enumerate(scores):idx = int(np.argmax(sc))score = float(np.max(sc))# Lower threshold to catch more eventsif score < conf_thresh:continuelabel_raw = self.yamnet_class_names[idx].strip().lower()label = NSE_CANONICAL.get(label_raw, label_raw)# Only keep events we care aboutif label in NSE_LABELS_KEEP:raw.append({"label": label,"start": i * frame_dur,"end": (i + 1) * frame_dur,"confidence": score})print(f"[YAMNet] Found {len(raw)} raw NSE events above threshold {conf_thresh}")if not raw:print("[YAMNet] No NSE events detected, trying fallback")return self._detect_nse_fallback(audio_path)# Improved merging - be more aggressiveif raw:merged = [raw[0]]for ev in raw[1:]:cur = merged[-1]# Merge if same label and within merge_gap OR if confidence is highif (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)# Filter by min_durationfiltered = [ev for ev in merged if ev["end"] - ev["start"] >= min_duration]# Format final eventsfinal_events = []for ev in filtered: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),})print(f"[YAMNet] ✅ Final NSE events: {len(final_events)}")for event in final_events:print(f" - {event['event']}: {event['start']:.2f}-{event['end']:.2f}s (conf: {event['confidence']:.3f})")return final_eventselse:print("[YAMNet] No events after merging/filtering")return self._detect_nse_fallback(audio_path)except Exception as e:print(f"[YAMNet] ❌ Error during detection: {e}")import tracebacktraceback.print_exc()return self._detect_nse_fallback(audio_path)def _detect_nse_fallback(self, audio_path):"""Fallback NSE detection using energy-based approach"""try:print("[YAMNet] Using fallback energy-based detection")y, sr = librosa.load(audio_path, sr=16000, mono=True)# More sensitive energy detectionhop, win = int(0.01 * sr), int(0.05 * sr) # Shorter hop for better resolutionrms = 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)# More sensitive thresholdthresh = np.mean(rms) + 1.5 * np.std(rms) # Lower thresholdprint(f"[YAMNet Fallback] Energy threshold: {thresh:.6f}")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.3: # Shorter duration thresholdevs.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.3: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,})print(f"[YAMNet Fallback] Found {len(evs)} events")return evsexcept Exception as e:print(f"[YAMNet Fallback] Error: {e}")return []class ASR_Diarization:def __init__(self, HF_TOKEN,
asr_diarization/pipeline.py+156-97