Initial commit: Doctor-Patient clinical transcription and structured summary pipeline
This commit is contained in:
@@ -0,0 +1,220 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
# ── Optional Heavy ML Imports (GPU/ML packages) ────────────────────────────────
|
||||
# Pyannote, torch, speechbrain हे optional आहेत.
|
||||
# Install नसल्यास server crash होत नाही — gracefully LLM fallback वापरतो.
|
||||
try:
|
||||
import torch # type: ignore
|
||||
import torchaudio # type: ignore
|
||||
import numpy as np # type: ignore
|
||||
_TORCH_AVAILABLE = True
|
||||
except ImportError:
|
||||
_TORCH_AVAILABLE = False
|
||||
print("[diarization_pipeline] WARNING: torch/torchaudio not installed. Acoustic diarization disabled.")
|
||||
|
||||
try:
|
||||
from pyannote.audio import Pipeline as PyannotePipeline # type: ignore
|
||||
_PYANNOTE_AVAILABLE = True
|
||||
except ImportError:
|
||||
_PYANNOTE_AVAILABLE = False
|
||||
print("[diarization_pipeline] WARNING: pyannote.audio not installed. Acoustic diarization disabled.")
|
||||
|
||||
try:
|
||||
from speechbrain.pretrained import EncoderClassifier # type: ignore
|
||||
_SPEECHBRAIN_AVAILABLE = True
|
||||
except ImportError:
|
||||
_SPEECHBRAIN_AVAILABLE = False
|
||||
print("[diarization_pipeline] WARNING: speechbrain not installed. Speaker embeddings disabled.")
|
||||
|
||||
|
||||
class AcousticDiarizer:
|
||||
def __init__(self, hf_token: str = None):
|
||||
self.hf_token = hf_token or os.getenv("HF_TOKEN")
|
||||
if not self.hf_token:
|
||||
print("WARNING: HF_TOKEN not set. Pyannote may fail if models are not cached.")
|
||||
|
||||
# 1. Load Pyannote Diarization Pipeline
|
||||
self.diarization_pipeline = None
|
||||
if _PYANNOTE_AVAILABLE and _TORCH_AVAILABLE:
|
||||
try:
|
||||
self.diarization_pipeline = PyannotePipeline.from_pretrained(
|
||||
"pyannote/speaker-diarization-3.1",
|
||||
use_auth_token=self.hf_token
|
||||
)
|
||||
# Move to GPU if available
|
||||
if torch.cuda.is_available():
|
||||
self.diarization_pipeline.to(torch.device("cuda"))
|
||||
except Exception as e:
|
||||
print(f"Failed to load Pyannote Diarization: {e}")
|
||||
self.diarization_pipeline = None
|
||||
else:
|
||||
print("[AcousticDiarizer] Pyannote/torch unavailable — using LLM fallback.")
|
||||
|
||||
# 2. Load SpeechBrain ECAPA-TDNN for Speaker Embeddings (Role Assignment)
|
||||
self.embedding_model = None
|
||||
if _SPEECHBRAIN_AVAILABLE and _TORCH_AVAILABLE:
|
||||
try:
|
||||
self.embedding_model = EncoderClassifier.from_hparams(
|
||||
source="speechbrain/spkrec-ecapa-voxceleb",
|
||||
savedir="pretrained_models/spkrec-ecapa-voxceleb",
|
||||
run_opts={"device": "cuda" if torch.cuda.is_available() else "cpu"}
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"Failed to load SpeechBrain: {e}")
|
||||
self.embedding_model = None
|
||||
else:
|
||||
print("[AcousticDiarizer] SpeechBrain unavailable — speaker embeddings disabled.")
|
||||
|
||||
|
||||
def run_diarization(self, audio_path: str):
|
||||
"""Runs Pyannote diarization and returns list of segments."""
|
||||
if not self.diarization_pipeline:
|
||||
raise RuntimeError("Diarization pipeline is not initialized.")
|
||||
|
||||
# Pyannote expects 16kHz mono. It handles resampling internally, but best to ensure.
|
||||
diarization = self.diarization_pipeline(audio_path)
|
||||
|
||||
segments = []
|
||||
for turn, _, speaker in diarization.itertracks(yield_label=True):
|
||||
segments.append({
|
||||
"start": turn.start,
|
||||
"end": turn.end,
|
||||
"speaker_id": speaker
|
||||
})
|
||||
return segments
|
||||
|
||||
def extract_embedding(self, audio_path: str, start: float, end: float):
|
||||
"""Extracts speaker embedding for a specific segment."""
|
||||
if not self.embedding_model or not _TORCH_AVAILABLE:
|
||||
return None
|
||||
|
||||
signal, fs = torchaudio.load(audio_path)
|
||||
|
||||
# Resample to 16kHz if necessary
|
||||
if fs != 16000:
|
||||
resampler = torchaudio.transforms.Resample(fs, 16000)
|
||||
signal = resampler(signal)
|
||||
fs = 16000
|
||||
|
||||
# Ensure mono
|
||||
if signal.shape[0] > 1:
|
||||
signal = signal.mean(dim=0, keepdim=True)
|
||||
|
||||
start_sample = int(start * fs)
|
||||
end_sample = int(end * fs)
|
||||
segment = signal[:, start_sample:end_sample]
|
||||
|
||||
# BUG 15 FIX: Very short segments पण gracefully handle करा
|
||||
min_samples = int(fs * 0.5) # 0.5 seconds minimum
|
||||
if segment.shape[1] < min_samples:
|
||||
return None
|
||||
|
||||
with torch.no_grad():
|
||||
embeddings = self.embedding_model.encode_batch(segment)
|
||||
embeddings = embeddings.squeeze().cpu().numpy()
|
||||
|
||||
return embeddings
|
||||
|
||||
|
||||
def assign_roles_heuristically(self, segments: list) -> dict:
|
||||
"""
|
||||
Assigns 'Doctor' and 'Patient' roles based on conversational dynamics.
|
||||
Heuristics:
|
||||
1. Doctor usually initiates the conversation or speaks first.
|
||||
2. Doctor usually has more short turns (asking questions).
|
||||
3. Patient usually has longer narrative turns (describing symptoms).
|
||||
"""
|
||||
if not segments:
|
||||
return {}
|
||||
|
||||
speaker_stats = {}
|
||||
for seg in segments:
|
||||
spk = seg["speaker_id"]
|
||||
dur = seg["end"] - seg["start"]
|
||||
if spk not in speaker_stats:
|
||||
speaker_stats[spk] = {"count": 0, "total_duration": 0, "first_appearance": seg["start"]}
|
||||
speaker_stats[spk]["count"] += 1
|
||||
speaker_stats[spk]["total_duration"] += dur
|
||||
|
||||
if not speaker_stats:
|
||||
return {}
|
||||
|
||||
# If only one speaker detected
|
||||
if len(speaker_stats) == 1:
|
||||
spk = list(speaker_stats.keys())[0]
|
||||
return {spk: "Doctor"} # Fallback
|
||||
|
||||
# Sort speakers by first appearance
|
||||
speakers = sorted(speaker_stats.keys(), key=lambda x: speaker_stats[x]["first_appearance"])
|
||||
|
||||
# Sort speakers by number of turns
|
||||
speakers_by_turns = sorted(speaker_stats.keys(), key=lambda x: speaker_stats[x]["count"], reverse=True)
|
||||
|
||||
mapping = {}
|
||||
|
||||
# Primary Heuristic: The speaker with the most back-and-forth turns is usually the doctor
|
||||
# Secondary: Doctor usually speaks first.
|
||||
|
||||
doctor_candidate = speakers_by_turns[0]
|
||||
|
||||
mapping[doctor_candidate] = "Doctor"
|
||||
|
||||
# BUG 6 FIX: Comment म्हणतो 'Patient_{i}' पण code सगळ्यांना 'Patient' करतो
|
||||
# Multiple speakers असल्यास योग्य index द्या
|
||||
non_doctor_speakers = [s for s in speaker_stats.keys() if s != doctor_candidate]
|
||||
for i, spk in enumerate(non_doctor_speakers):
|
||||
if len(non_doctor_speakers) == 1:
|
||||
mapping[spk] = "Patient" # एकटाच Patient असल्यास plain "Patient"
|
||||
else:
|
||||
mapping[spk] = f"Patient_{i + 1}" # Patient_1, Patient_2, ... (Relative etc.)
|
||||
|
||||
return mapping
|
||||
|
||||
def align_stt_with_diarization(self, stt_words: list, diarization_segments: list, role_mapping: dict):
|
||||
"""
|
||||
Aligns STT word/segment timestamps with the acoustic diarization segments.
|
||||
stt_words: [{'text': 'hello', 'start': 0.5, 'end': 1.0}, ...]
|
||||
"""
|
||||
aligned_transcript = []
|
||||
|
||||
for stt in stt_words:
|
||||
midpoint = (stt["start"] + stt["end"]) / 2.0
|
||||
|
||||
# Find the diarization segment that covers this midpoint
|
||||
assigned_speaker = "Unknown"
|
||||
assigned_role = "Unknown"
|
||||
|
||||
for d_seg in diarization_segments:
|
||||
if d_seg["start"] <= midpoint <= d_seg["end"]:
|
||||
assigned_speaker = d_seg["speaker_id"]
|
||||
assigned_role = role_mapping.get(assigned_speaker, "Unknown")
|
||||
break
|
||||
|
||||
aligned_transcript.append({
|
||||
"text": stt["text"],
|
||||
"start": stt["start"],
|
||||
"end": stt["end"],
|
||||
"speaker": assigned_speaker,
|
||||
"role": assigned_role
|
||||
})
|
||||
|
||||
# Group contiguous words by role
|
||||
final_blocks = []
|
||||
current_role = None
|
||||
current_text = []
|
||||
|
||||
for item in aligned_transcript:
|
||||
if item["role"] != current_role:
|
||||
if current_text:
|
||||
final_blocks.append(f"{current_role}: {' '.join(current_text)}")
|
||||
current_role = item["role"]
|
||||
current_text = [item["text"]]
|
||||
else:
|
||||
current_text.append(item["text"])
|
||||
|
||||
if current_text:
|
||||
final_blocks.append(f"{current_role}: {' '.join(current_text)}")
|
||||
|
||||
return "\n\n".join(final_blocks)
|
||||
|
||||
Reference in New Issue
Block a user