Initial commit: Doctor-Patient clinical transcription and structured summary pipeline

This commit is contained in:
Ayush
2026-11-16 19:22:04 +05:30
commit f451738732
60 changed files with 11321 additions and 0 deletions
+15
View File
@@ -0,0 +1,15 @@
# ====================================================================
# Backend Python API - Environment Configuration
# ====================================================================
# Sarvam AI API Key (Required)
# Get your key from: https://dashboard.sarvam.ai
SARVAM_API_KEY=your_sarvam_api_key_here
# Sarvam Chat Model (Default: sarvam-105b)
SARVAM_CHAT_MODEL=sarvam-105b
# Optional: Groq LLM API Key (Fallback for fast summary)
# Get your key from: https://console.groq.com
GROQ_API_KEY=your_groq_api_key_here
GROQ_MODEL=llama-3.3-70b-versatile
+220
View File
@@ -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)
+334
View File
@@ -0,0 +1,334 @@
"""
AI Medical Assistant — FastAPI backend
Uses starlette directly to avoid pydantic_core binary incompatibility on Python 3.14
"""
import os, sys, json, re, struct, asyncio, base64
from pathlib import Path
# ── Patch sys.path (optional local vendored packages) ────────────────────────
_root = Path(__file__).resolve().parent.parent
_pkgs = str(_root / "pkgs")
_src = str(_root / "sarvamai_src")
if os.path.isdir(_pkgs) and _pkgs not in sys.path:
sys.path.insert(0, _pkgs)
if os.path.isdir(_src) and _src not in sys.path:
sys.path.append(_src)
# ── Imports ───────────────────────────────────────────────────────────────────
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware
from starlette.routing import Route, WebSocketRoute, Mount
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.staticfiles import StaticFiles
from starlette.websockets import WebSocket, WebSocketDisconnect, WebSocketState
import httpx
import websockets as ws_lib
from dotenv import load_dotenv
load_dotenv()
SARVAM_API_KEY = os.getenv("SARVAM_API_KEY", "")
SARVAM_CHAT_MODEL = os.getenv("SARVAM_CHAT_MODEL", "sarvam-105b")
GROQ_API_KEY = os.getenv("GROQ_API_KEY", "")
GROQ_MODEL = os.getenv("GROQ_MODEL", "llama-3.3-70b-versatile")
TEMP_DIR = Path("temp_audio")
TEMP_DIR.mkdir(exist_ok=True)
# ── Helpers ───────────────────────────────────────────────────────────────────
def parse_wav(buf: bytes):
offset, sr, nc, bps = 12, 16000, 1, 16
do, dl = 44, len(buf) - 44
while offset + 8 <= len(buf):
cid = buf[offset:offset+4]
sz = struct.unpack('<I', buf[offset+4:offset+8])[0]
if cid == b'fmt ':
nc = struct.unpack('<H', buf[offset+10:offset+12])[0]
sr = struct.unpack('<I', buf[offset+12:offset+16])[0]
bps = struct.unpack('<H', buf[offset+22:offset+24])[0]
elif cid == b'data':
do, dl = offset + 8, sz; break
offset += 8 + sz
return do, dl, sr, nc, bps
def make_wav(pcm: bytes, sr, nc, bps) -> bytes:
dl = len(pcm); h = bytearray(44)
h[0:4]=b'RIFF'; struct.pack_into('<I',h,4,36+dl)
h[8:12]=b'WAVE'; h[12:16]=b'fmt '
struct.pack_into('<I',h,16,16); struct.pack_into('<H',h,20,1)
struct.pack_into('<H',h,22,nc); struct.pack_into('<I',h,24,sr)
struct.pack_into('<I',h,28,sr*nc*bps//8); struct.pack_into('<H',h,32,nc*bps//8)
struct.pack_into('<H',h,34,bps); h[36:40]=b'data'; struct.pack_into('<I',h,40,dl)
return bytes(h) + pcm
def chunk_wav(wav: bytes, chunk_sec=24):
do, dl, sr, nc, bps = parse_wav(wav)
bps_rate = sr * nc * (bps // 8)
cb = bps_rate * chunk_sec
if dl <= cb or bps_rate == 0: return [wav]
pcm = wav[do:do+dl]
return [make_wav(pcm[i:i+cb], sr, nc, bps) for i in range(0, len(pcm), cb)]
def clean_text(text: str) -> str:
if not text: return text
text = re.sub(r'\b(\w+)(\s+\1)+\b', r'\1', text, flags=re.IGNORECASE|re.UNICODE)
for n in range(8, 1, -1):
text = re.sub(r'((?:\S+\s+){'+str(n-1)+r'}\S+)(\s+\1)+',
r'\1', text, flags=re.IGNORECASE|re.UNICODE)
sents = re.split(r'(?<=[.!?।])\s+', text.strip())
seen, seen_n = [], []
for s in sents:
s = s.strip()
if not s: continue
n = re.sub(r'\s+',' ', s.lower().strip())
dup = any(n==p or (len(min(n,p,key=len))>10 and
min(n,p,key=len) in max(n,p,key=len)) for p in seen_n)
if not dup: seen.append(s); seen_n.append(n)
return ' '.join(seen)
async def ensure_english_text(client: httpx.AsyncClient, text: str) -> str:
if not text or not re.search(r'[\u0900-\u097F]', text):
return text
if not SARVAM_API_KEY:
return text
try:
resp = await client.post(
"https://api.sarvam.ai/translate",
headers={"api-subscription-key": SARVAM_API_KEY, "Content-Type": "application/json"},
json={
"input": text,
"source_language_code": "auto",
"target_language_code": "en-IN",
"mode": "formal",
"model": "mayura:v1"
},
timeout=15.0
)
if resp.is_success:
t = resp.json().get("translated_text", "")
if t and t.strip():
return t.strip()
except Exception as e:
print(f"[ensure_english_text] {e}")
return text
# ── Route Handlers ────────────────────────────────────────────────────────────
async def health(request: Request):
return JSONResponse({"ok": True, "ready": bool(SARVAM_API_KEY),
"sarvamKeyConfigured": bool(SARVAM_API_KEY)})
async def transcribe(request: Request):
if not SARVAM_API_KEY:
return JSONResponse({"error": "SARVAM_API_KEY not configured."}, status_code=500)
audio_bytes = b""; lang = "unknown"
ct = request.headers.get("content-type", "")
if "multipart" in ct:
form = await request.form()
f = form.get("file")
if f: audio_bytes = await f.read()
lang = form.get("language_code", "unknown") or "unknown"
else:
try:
body = await request.json()
if body.get("audio_b64"):
audio_bytes = base64.b64decode(body["audio_b64"])
lang = body.get("language_code") or "unknown"
except: pass
if not audio_bytes:
return JSONResponse({"error": "No audio provided."}, status_code=400)
if lang == "auto": lang = "unknown"
chunks = chunk_wav(audio_bytes)
parts, detected = [], lang
headers = {"api-subscription-key": SARVAM_API_KEY}
async with httpx.AsyncClient(timeout=90) as client:
for i, chunk in enumerate(chunks):
resp = await client.post(
"https://api.sarvam.ai/speech-to-text",
headers=headers,
files={"file": (f"chunk_{i}.wav", chunk, "audio/wav")},
data={"model":"saaras:v4","mode":"translate",
"language_code":lang,"with_timestamps":"false"},
)
if not resp.is_success:
return JSONResponse({"error": f"Sarvam STT error: {resp.text[:300]}"},
status_code=resp.status_code)
d = resp.json()
t = (d.get("transcript") or "").strip()
if t: parts.append(t)
if d.get("language_code") and detected == "unknown":
detected = d["language_code"]
raw_transcript = clean_text(" ".join(parts).strip())
transcript = await ensure_english_text(client, raw_transcript)
return JSONResponse({"success": True, "transcript": transcript, "language": "en-IN"})
async def summary(request: Request):
if not SARVAM_API_KEY:
return JSONResponse({"error": "SARVAM_API_KEY not configured in .env"}, status_code=500)
body = await request.json()
transcript = (body.get("transcript") or "").strip()
if not transcript:
return JSONResponse({"error": "transcript is empty"}, status_code=400)
PROMPT = (
"You are a clinical documentation assistant for Indian hospitals. "
"Read the doctor-patient conversation below (may be Marathi, Hindi, English, or code-mixed). "
"Extract clinical information and return ONLY a valid JSON object with exactly these keys:\n"
"- chief_complaint: main reason for visit (string)\n"
"- symptoms: list of symptoms mentioned (array of strings)\n"
"- history: relevant past medical history (string)\n"
"- assessment: doctor's diagnosis or assessment (string)\n"
"- plan: prescription, tests, or treatment steps (array of strings)\n\n"
"Rules:\n"
"1. Output ONLY raw JSON — no markdown, no explanation, no extra text.\n"
"2. Write 'Not mentioned' for any field not found in the conversation.\n"
"3. Keep the original language of the content (do not translate).\n"
"4. Do NOT give medical advice — only extract what was said."
)
async with httpx.AsyncClient(timeout=60) as client:
resp = await client.post(
"https://api.sarvam.ai/v2/chat/completions",
headers={
"Content-Type": "application/json",
"api-subscription-key": SARVAM_API_KEY,
},
json={
"model": "sarvam-105b",
"temperature": 0.1,
"max_tokens": 1000,
"response_format": {"type": "json_object"},
"messages": [
{"role": "system", "content": PROMPT},
{"role": "user", "content": transcript},
],
},
)
if not resp.is_success:
return JSONResponse(
{"error": f"Sarvam API error: {resp.text[:400]}"},
status_code=resp.status_code
)
content = resp.json().get("choices",[{}])[0].get("message",{}).get("content","")
try:
cleaned = re.sub(r'^```json|^```|```$','',content.strip(),flags=re.MULTILINE).strip()
parsed = json.loads(cleaned)
except:
parsed = {"raw_text": content}
return JSONResponse({"summary": parsed})
async def ws_transcribe(websocket: WebSocket):
await websocket.accept()
if not SARVAM_API_KEY:
await websocket.send_json({"event":"error","message":"SARVAM_API_KEY not configured."})
await websocket.close(); return
lang = websocket.query_params.get("language_code","auto")
if lang == "unknown":
lang = "auto"
sarvam_url = (
"wss://api.sarvam.ai/speech-to-text-realtime/ws"
f"?language_code={lang}"
"&model=saaras:v3-realtime"
"&encoding=linear16&sample_rate=16000"
"&stream_type=balanced&mode=translate"
)
try:
async with ws_lib.connect(
sarvam_url,
additional_headers={"api-subscription-key": SARVAM_API_KEY},
ping_interval=20, ping_timeout=20,
) as sarvam_ws:
async def b2s():
try:
while True:
msg = await websocket.receive()
if msg["type"] == "websocket.disconnect": break
if "text" in msg and msg["text"]:
d = json.loads(msg["text"])
if d.get("event") in ("end","stop"):
await sarvam_ws.send(json.dumps({"event":"end"})); break
elif d.get("event") == "audio_input":
await sarvam_ws.send(json.dumps(d))
except Exception as e: print(f"[b2s] {e}")
finally:
try: await sarvam_ws.send(json.dumps({"event":"end"}))
except: pass
async def s2b():
try:
async with httpx.AsyncClient(timeout=10.0) as http_client:
async for raw in sarvam_ws:
if websocket.client_state != WebSocketState.CONNECTED: break
if isinstance(raw,(bytes,bytearray)): continue
try: p = json.loads(raw)
except: continue
evt = p.get("event","")
if evt in ("transcript.partial","transcript.final"):
text_val = p.get("text","")
if evt == "transcript.final" and text_val:
text_val = await ensure_english_text(http_client, text_val)
await websocket.send_json({
"event": evt,
"text": text_val,
"language": "en-IN",
})
elif evt == "error":
await websocket.send_json({
"event":"error",
"message":p.get("message",""),
"code":p.get("code",""),
})
except Exception as e: print(f"[s2b] {e}")
finally:
try: await websocket.send_json({"event":"done"})
except: pass
await asyncio.gather(b2s(), s2b())
except Exception as e:
try: await websocket.send_json({"event":"error","message":str(e)})
except: pass
finally:
try: await websocket.close()
except: pass
# ── App ───────────────────────────────────────────────────────────────────────
static_dir = _root / "public"
routes = [
Route("/api/health", health, methods=["GET"]),
Route("/health", health, methods=["GET"]),
Route("/api/transcribe", transcribe, methods=["POST"]),
Route("/transcribe", transcribe, methods=["POST"]),
Route("/api/summary", summary, methods=["POST"]),
WebSocketRoute("/ws/transcribe", ws_transcribe),
]
if static_dir.exists():
routes.append(Mount("/", app=StaticFiles(directory=str(static_dir), html=True), name="static"))
app = Starlette(
routes=routes,
middleware=[Middleware(CORSMiddleware,
allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]
)],
)
+12
View File
@@ -0,0 +1,12 @@
fastapi==0.111.0
uvicorn==0.30.1
python-multipart==0.0.9
httpx==0.27.0
python-dotenv==1.0.1
pydantic==2.7.4
pyannote.audio==3.1.1
speechbrain==0.5.16
torchaudio>=2.0.0
torch>=2.0.0
scipy
numpy
BIN
View File
Binary file not shown.
+29
View File
@@ -0,0 +1,29 @@
import asyncio
import httpx
import os
import base64
from dotenv import load_dotenv
load_dotenv()
SARVAM_API_KEY = os.getenv("SARVAM_API_KEY", "")
async def test():
with open("test.wav", "rb") as f:
audio_data = f.read()
async with httpx.AsyncClient(timeout=60) as client:
submit_resp = await client.post(
"https://api.sarvam.ai/speech-to-text",
headers={"api-subscription-key": SARVAM_API_KEY},
files={"file": ("test.wav", audio_data, "audio/wav")},
data={
"model": "saaras:v4",
"mode": "codemix",
"with_timestamps": "true",
"with_diarization": "true",
}
)
print(submit_resp.status_code)
print(submit_resp.json())
asyncio.run(test())