Initial commit: Doctor-Patient clinical transcription and structured summary pipeline
This commit is contained in:
@@ -0,0 +1,192 @@
|
||||
import sys
|
||||
import json
|
||||
import warnings
|
||||
import urllib.request
|
||||
import io
|
||||
import os
|
||||
import wave
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
import shutil
|
||||
original_rmtree = shutil.rmtree
|
||||
def safe_rmtree(path, ignore_errors=False, onerror=None, onexc=None, **kwargs):
|
||||
try:
|
||||
if sys.version_info >= (3, 12):
|
||||
original_rmtree(path, ignore_errors=True, onexc=onexc, **kwargs)
|
||||
else:
|
||||
original_rmtree(path, ignore_errors=True, onerror=onerror, **kwargs)
|
||||
except Exception:
|
||||
pass
|
||||
shutil.rmtree = safe_rmtree
|
||||
|
||||
def get_sarvam_transcript(audio_path):
|
||||
api_key = None
|
||||
if os.path.exists('.env'):
|
||||
with open('.env', encoding='utf-8') as f:
|
||||
for line in f:
|
||||
if line.startswith('SARVAM_API_KEY='):
|
||||
api_key = line.strip().split('=', 1)[1].strip('"\' ')
|
||||
|
||||
if not api_key:
|
||||
raise ValueError("SARVAM_API_KEY not found in .env")
|
||||
|
||||
with open(audio_path, 'rb') as f:
|
||||
wav_bytes = f.read()
|
||||
|
||||
boundary = '----WebKitFormBoundary7MA4YWxkTrZu0gW'
|
||||
filename = os.path.basename(audio_path)
|
||||
body = (
|
||||
f'--{boundary}\r\n'
|
||||
f'Content-Disposition: form-data; name="file"; filename="{filename}"\r\n'
|
||||
f'Content-Type: audio/wav\r\n\r\n'
|
||||
).encode('utf-8') + wav_bytes + (
|
||||
f'\r\n--{boundary}\r\n'
|
||||
f'Content-Disposition: form-data; name="model"\r\n\r\n'
|
||||
f'saaras:v4\r\n'
|
||||
f'--{boundary}\r\n'
|
||||
f'Content-Disposition: form-data; name="mode"\r\n\r\n'
|
||||
f'translate\r\n'
|
||||
f'--{boundary}\r\n'
|
||||
f'Content-Disposition: form-data; name="with_timestamps"\r\n\r\n'
|
||||
f'true\r\n'
|
||||
f'--{boundary}--\r\n'
|
||||
).encode('utf-8')
|
||||
|
||||
req = urllib.request.Request(
|
||||
'https://api.sarvam.ai/speech-to-text',
|
||||
data=body,
|
||||
headers={
|
||||
'api-subscription-key': api_key,
|
||||
'Content-Type': f'multipart/form-data; boundary={boundary}'
|
||||
}
|
||||
)
|
||||
|
||||
with urllib.request.urlopen(req) as resp:
|
||||
return json.loads(resp.read().decode('utf-8'))
|
||||
|
||||
def get_nemo_segments(audio_path):
|
||||
try:
|
||||
from nemo.collections.asr.models import SortformerEncLabelModel
|
||||
except ImportError:
|
||||
raise RuntimeError("NeMo not installed")
|
||||
|
||||
diar_model = SortformerEncLabelModel.from_pretrained("nvidia/diar_sortformer_4spk-v1").eval()
|
||||
|
||||
from omegaconf import OmegaConf
|
||||
OmegaConf.set_struct(diar_model.cfg, False)
|
||||
if hasattr(diar_model.cfg, 'num_workers'):
|
||||
diar_model.cfg.num_workers = 0
|
||||
if 'validation_ds' in diar_model.cfg and hasattr(diar_model.cfg.validation_ds, 'num_workers'):
|
||||
diar_model.cfg.validation_ds.num_workers = 0
|
||||
if 'test_ds' in diar_model.cfg and hasattr(diar_model.cfg.test_ds, 'num_workers'):
|
||||
diar_model.cfg.test_ds.num_workers = 0
|
||||
|
||||
predicted_segments = diar_model.diarize(audio=[audio_path], batch_size=1, num_workers=0)
|
||||
if isinstance(predicted_segments, tuple):
|
||||
predicted_segments = predicted_segments[0]
|
||||
|
||||
segments = predicted_segments[0] if len(predicted_segments) > 0 else []
|
||||
|
||||
out_segments = []
|
||||
for seg in segments:
|
||||
try:
|
||||
start = float(seg[0])
|
||||
end = float(seg[1])
|
||||
spk = int(seg[2])
|
||||
out_segments.append([start, end, spk])
|
||||
except:
|
||||
pass
|
||||
|
||||
return out_segments
|
||||
|
||||
def align_words_to_segments(sarvam_res, nemo_segments):
|
||||
if "timestamps" not in sarvam_res:
|
||||
return []
|
||||
|
||||
ts = sarvam_res["timestamps"]
|
||||
words = ts.get("words", [])
|
||||
starts = ts.get("start_time_seconds", [])
|
||||
ends = ts.get("end_time_seconds", [])
|
||||
|
||||
aligned_dialogue = []
|
||||
current_spk = None
|
||||
current_sentence = []
|
||||
|
||||
for i in range(len(words)):
|
||||
word = words[i]
|
||||
w_start = starts[i]
|
||||
w_end = ends[i]
|
||||
w_mid = (w_start + w_end) / 2.0
|
||||
|
||||
# Find which segment contains the word's midpoint
|
||||
assigned_spk = None
|
||||
for seg in nemo_segments:
|
||||
seg_start, seg_end, spk_id = seg
|
||||
if seg_start <= w_mid <= seg_end:
|
||||
assigned_spk = spk_id
|
||||
break
|
||||
|
||||
# If midpoint doesn't fall strictly into any segment, find the closest one
|
||||
if assigned_spk is None and nemo_segments:
|
||||
closest_spk = None
|
||||
min_dist = float('inf')
|
||||
for seg in nemo_segments:
|
||||
seg_start, seg_end, spk_id = seg
|
||||
# distance to segment
|
||||
if w_mid < seg_start:
|
||||
dist = seg_start - w_mid
|
||||
elif w_mid > seg_end:
|
||||
dist = w_mid - seg_end
|
||||
else:
|
||||
dist = 0
|
||||
if dist < min_dist:
|
||||
min_dist = dist
|
||||
closest_spk = spk_id
|
||||
assigned_spk = closest_spk
|
||||
|
||||
if assigned_spk is None:
|
||||
assigned_spk = "Unknown"
|
||||
else:
|
||||
assigned_spk = f"Speaker {assigned_spk}"
|
||||
|
||||
if current_spk is None:
|
||||
current_spk = assigned_spk
|
||||
|
||||
if assigned_spk != current_spk:
|
||||
aligned_dialogue.append((current_spk, " ".join(current_sentence)))
|
||||
current_spk = assigned_spk
|
||||
current_sentence = [word]
|
||||
else:
|
||||
current_sentence.append(word)
|
||||
|
||||
if current_sentence:
|
||||
aligned_dialogue.append((current_spk, " ".join(current_sentence)))
|
||||
|
||||
return aligned_dialogue
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
print("Usage: python hybrid_diarization.py <audio_file.wav>")
|
||||
sys.exit(1)
|
||||
|
||||
audio_path = sys.argv[1]
|
||||
|
||||
print(f"[*] Calling Sarvam STT API for transcription... (with_timestamps=true)")
|
||||
sarvam_res = get_sarvam_transcript(audio_path)
|
||||
print("[+] Sarvam STT finished.")
|
||||
|
||||
print(f"[*] Running local Nvidia Sortformer model for diarization...")
|
||||
nemo_segments = get_nemo_segments(audio_path)
|
||||
print(f"[+] Nvidia Diarization finished. Found {len(nemo_segments)} segments.")
|
||||
|
||||
print(f"[*] Aligning Sarvam transcript words with Nvidia speaker segments...")
|
||||
dialogue = align_words_to_segments(sarvam_res, nemo_segments)
|
||||
|
||||
print("\n--- FINAL HYBRID DIALOGUE ---\n")
|
||||
for spk, text in dialogue:
|
||||
print(f"**{spk}:** {text}")
|
||||
print()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user