Update asr_diarization/pipeline.py
Browse files16 unmodified lines17181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911925 unmodified lines1981992003120120220320420537 unmodified lines24324424524624724824925025125225325425525625715 unmodified lines27327427596276277278279100 unmodified lines380381382203383384385386332 unmodified lines7197207215427227237247258 unmodified lines73473573673773873974074174274374474574674774810 unmodified lines75976076157376276376476515 unmodified lines7817827837847857867877887897907918 unmodified lines80080180280380480580677 unmodified lines88488588669288716 unmodified linesfrom pyannote.metrics.diarization import DiarizationErrorRatefrom jiwer import wer, Compose, ToLowerCase, RemovePunctuation, RemoveMultipleSpaces, Strip
# Add YAMNet importstry: import tensorflow as tf import tensorflow_hub as hub import librosa YAMNET_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 = None self.yamnet_class_names = None self._load_yamnet() def _load_yamnet(self): """Load YAMNet model""" if not YAMNET_AVAILABLE: print("[YAMNet] TensorFlow/Librosa not available") return try: 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 = None def 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.48
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) 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 label merged = [raw[0]] for ev in raw[1:]: cur = merged[-1] # Merge if same label and within merge_gap 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)
# Step 2: Filter by min_duration filtered = [ev for ev in merged if ev["end"] - ev["start"] >= min_duration]
# Step 3: Keep only desired labels final_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 threshold thresh = np.mean(rms) + 2 * np.std(rms)
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.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.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
class ASR_Diarization: def __init__(self, HF_TOKEN,5 unmodified lines min_segment_duration=0.5, snr_threshold=15.0, min_whisper_duration=0.3, embedding_threshold=0.5): embedding_threshold=0.5, enable_nse=True): # ADD enable_nse parameter self.HF_TOKEN = HF_TOKEN self.device = "cuda" if torch.cuda.is_available() else "cpu"37 unmodified lines print("WebRTC VAD not available") self.use_vad = False
# Initialize YAMNet NSE detector self.enable_nse = enable_nse if self.enable_nse: self.nse_detector = YAMNetNSEDetector() print("[NSE] YAMNet-based NSE detector initialized") else: self.nse_detector = None print("[NSE] NSE detection disabled")
# Load ASR model if model_path and os.path.exists(model_path): print(f"Loading custom ASR model from: {model_path}")15 unmodified lines return_timestamps=True )
# ========== SPEAKER EMBEDDING METHODS (From Second Pipeline) ========== # ========== SPEAKER EMBEDDING METHODS ========== def load_unknown_speakers(self, unknown_speakers_path): """Load unknown speakers from JSON file"""100 unmodified lines
return cluster_embeddings
# ========== EXISTING METHODS (Enhanced) ========== # ========== EXISTING METHODS ========== def clean_transcription_text(self, text): """Clean ASR text for better TTS performance"""332 unmodified lines def 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""" """Enhanced pipeline with YAMNet NSE detection""" # Validate input audio file if not os.path.exists(audio_path): raise FileNotFoundError(f"Audio file not found: {audio_path}")8 unmodified lines
print(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 transcription diar_json = self.run_diarization(audio_path)10 unmodified lines if not self.embedding_model: merged_segments, speakers = self.map_speaker_labels(merged_segments)
# Combine ASR segments with NSE events if provided # Combine ASR segments with NSE events if nse_events: print(f"Combining {len(merged_segments)} ASR segments with {len(nse_events)} NSE events") all_segments = merged_segments + nse_events15 unmodified lines f"{seg['speaker']} <NA> <NA>\n" )
# Save NSE events separately nse_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 lines return { "speakers": speakers, "segments": all_segments, # Return combined segments "nse_events": nse_events, # Return NSE events separately too "evaluation": eval_results }
77 unmodified lines finally: # Always clean up temporary file if tmp_path and os.path.exists(tmp_path): os.unlink(tmp_path) os.unlink(tmp_path)asr_diarization/pipeline.py+201-6