""" 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(' bytes: dl = len(pcm); h = bytearray(44) h[0:4]=b'RIFF'; struct.pack_into(' 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=["*"] )], )