Update asr_diarization/pipeline.py
Browse files64 unmodified lines6566676868697070717273747576777879808182777883848586878889909192939495969798838499100101102103104105106107108109110111112113114115116117118119120909192121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189949596190191192193194195196197198989910010110210310410510610710810911011111211311411511611719920020120220320412012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015120520620720820915615715815916016116216316421021121221321421521621721821922016616716816917017117222122222322422522622722822923023123223323423523623723823924024124224324424517817924624724818118218318418518618718818919019119219319419524925025125225325425525625725864 unmodified lines self._load_yamnet() def _load_yamnet(self): """Load YAMNet model""" """Load YAMNet model with better error handling""" if not YAMNET_AVAILABLE: print("[YAMNet] TensorFlow/Librosa not available") print("[YAMNet] ❌ TensorFlow/Librosa not available") return try: print("[YAMNet] Loading YAMNet model...") # Clear any existing TensorFlow session import tensorflow as tf tf.keras.backend.clear_session() self.yamnet_model = hub.load("https://tfhub.dev/google/yamnet/1") # Get class names 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") 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 traceback traceback.print_exc() self.yamnet_model = None def 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""" def 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 content if 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 librosa 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) print(f"[YAMNet] Audio loaded: {len(wav)} samples, {sr} Hz, duration: {len(wav)/sr:.2f}s") # Check if audio has meaningful content if np.max(np.abs(wav)) < 0.001: print("[YAMNet] ⚠️ Audio appears to be silent or very quiet") return [] # Run YAMNet inference print("[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 events if score < conf_thresh: continue label_raw = self.yamnet_class_names[idx].strip().lower() label = NSE_CANONICAL.get(label_raw, label_raw) # Only keep events we care about if 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 aggressive if raw: merged = [raw[0]] for ev in raw[1:]: cur = merged[-1] # Merge if same label and within merge_gap OR if confidence is high if (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_duration filtered = [ev for ev in merged if ev["end"] - ev["start"] >= min_duration]
# Format final events final_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), })
scores, _, _ = self.yamnet_model(np.array(wav, dtype=np.float32)) scores = scores.numpy() frame_dur = 0.48 # YAMNet frame duration 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_events else: print("[YAMNet] No events after merging/filtering") return self._detect_nse_fallback(audio_path)
raw = [] for i, sc in enumerate(scores): idx = int(np.argmax(sc)) score = float(np.max(sc)) if score < conf_thresh: continue label_raw = self.yamnet_class_names[idx].strip().lower() label = NSE_CANONICAL.get(label_raw, label_raw) # Only keep events we care about if 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") except Exception as e: print(f"[YAMNet] ❌ Error during detection: {e}") import traceback traceback.print_exc() return self._detect_nse_fallback(audio_path)
# Improved merging - be more aggressive merged = [raw[0]] for ev in raw[1:]: cur = merged[-1] # Merge if same label and within merge_gap OR if confidence is high if (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_duration filtered = [ev for ev in merged if ev["end"] - ev["start"] >= min_duration]
# Format final events final_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_events
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) 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 threshold thresh = np.mean(rms) + 2 * np.std(rms) # More sensitive energy detection hop, win = int(0.01 * sr), int(0.05 * sr) # Shorter hop for better resolution 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)
# More sensitive threshold thresh = np.mean(rms) + 1.5 * np.std(rms) # Lower threshold print(f"[YAMNet Fallback] Energy threshold: {thresh:.6f}")
evs, active, start_t = [], False, 0.0 for t, r in zip(times, rms): if r > thresh and not active: active, start_t = True, t if r <= thresh and active: dur = t - start_t if dur >= 0.5: # Only count longer bursts evs, active, start_t = [], False, 0.0 for t, r in zip(times, rms): if r > thresh and not active: active, start_t = True, t if r <= thresh and active: dur = t - start_t if dur >= 0.3: # Shorter duration threshold evs.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 = False
if active: dur = times[-1] + 0.05 - start_t if dur >= 0.3: evs.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))), "end": round(times[-1] + 0.05, 3), "confidence": 0.5, }) active = False
if active: dur = times[-1] + 0.05 - start_t if 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 evs
print(f"[YAMNet Fallback] Found {len(evs)} events") return evs except Exception as e: print(f"[YAMNet Fallback] Error: {e}") return []
class ASR_Diarization: def __init__(self, HF_TOKEN,asr_diarization/pipeline.py+156-97