Files
Doctor_Patient_Summary/test_line_diarize.py

98 lines
5.8 KiB
Python

import os
import json
import sys
import urllib.request
import urllib.error
# --- .env load ---
_env_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env')
if os.path.exists(_env_path):
with open(_env_path, encoding='utf-8') as f:
for line in f:
line = line.strip()
if '=' in line and not line.startswith('#'):
k, v = line.split('=', 1)
os.environ.setdefault(k.strip(), v.strip())
SARVAM_API_KEY = os.getenv("SARVAM_API_KEY", "")
if not SARVAM_API_KEY:
sys.exit("ERROR: SARVAM_API_KEY not found in .env")
sample_text = """आपण हे dissection accelerated हे केले ते. तुम्ही आधी इथं पहिल्यांदा सरांना दाखवले फक्त त्याच्या आधी हो इथं आधी पहिल्यापासून इथं treatment चालू पहिल्यापासून इथं treatment चालू. आता 1 फक्त आपल्या इथला 1 नवीन हे चालू आहे EMR की जे directly audio connect करून इथं notes करतात तर त्याचं experimentation चालू आहे. त्यासाठी फक्त जर तुमची परवानगी असेल तर आपलं जे conversation आहे ते record करतायेत चालेल तुम्हाला IT team-चं? पण आपण जे बोलतोय ना तेच फक्त record करणार जसं AI असतं ना AI घेऊन direct notes generate करतील असं त्यांचा प्रयोग चाललाय. अच्छा अच्छा. त्या intention-साठी आहे बाकी काही नाही. ठीक आहे. OK that's OK. आधी तुमची treatment 4 cycle chemo झालेले आहेत. हो. 2006-मध्ये त्याच्यानंतर त्याच्यानंतर 1 वर्षाने MRI, 5 वर्षाने MRI आणि बाकी mammography आणि sonography दर वर्षाला. म्हणजे 2007-पासून continuous follow-up आहे. आणि आता त्रास काय व्हायला लागला तुम्हाला? त्रास काहीच नव्हता, follow-up-ला आलो होतो मी."""
system_prompt = """You are an expert Marathi medical consultation diarization system.
You will receive a raw, unlabeled Marathi conversation between a Doctor and a Patient.
Your job: label EACH utterance as either "Doctor:" or "Patient:".
CONTEXT CUES:
- Doctor: explains treatment, asks questions, mentions chemo/MRI/surgery/medicines/reports, gives advice, uses medical terminology, refers to "तुमची treatment", "आपण करतो".
- Patient: answers questions, describes symptoms, says "हो", "नाही", "अच्छा", "ठीक आहे", "त्रास काहीच नव्हता", came for follow-up after 4 cycles of chemo since 2006.
- Consent/permission questions about recording → Doctor asking.
- Short confirmations like "हो", "अच्छा अच्छा", "ठीक आहे", "OK that's OK" → Patient responding.
OUTPUT FORMAT (strict, one utterance per line):
Doctor: <exact original Marathi text>
Patient: <exact original Marathi text>
Doctor: <exact original Marathi text>
...
RULES:
- Every single line MUST start with either "Doctor: " or "Patient: ".
- Do NOT add explanations, headings, summaries, or blank lines.
- Do NOT merge multiple turns into one line.
- Do NOT translate or paraphrase — preserve original Marathi/English text exactly.
- Split at natural turn boundaries (question → answer, statement → reaction).
"""
payload = json.dumps({
"model": "sarvam-105b-conversations",
"temperature": 0.1,
"max_tokens": 8192,
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": f"Conversation:\n{sample_text}"}
]
}).encode('utf-8')
req = urllib.request.Request(
'https://api.sarvam.ai/v1/chat/completions',
data=payload,
headers={
'Content-Type': 'application/json',
'api-subscription-key': SARVAM_API_KEY
}
)
try:
with urllib.request.urlopen(req, timeout=120) as resp:
data = json.loads(resp.read().decode('utf-8'))
choice = data.get('choices', [{}])[0]
finish_reason = choice.get('finish_reason', 'unknown')
msg = choice.get('message', {})
content = msg.get('content', None)
reasoning = msg.get('reasoning_content', None)
if not content:
# Model used all tokens for reasoning, no final answer generated
print(f"[WARNING] content=None, finish_reason={finish_reason}", file=sys.stderr)
if reasoning:
print("\n===== MODEL REASONING (no final output) =====\n", file=sys.stderr)
sys.stderr.buffer.write(reasoning[:2000].encode('utf-8'))
sys.stderr.buffer.write(b"\n")
sys.exit(f"ERROR: Model returned empty content. Try increasing max_tokens or simplifying the prompt.")
print("\n===== DIARIZED TRANSCRIPT =====\n")
sys.stdout.buffer.write(content.encode('utf-8'))
sys.stdout.buffer.write(b"\n")
print(f"\n[finish_reason: {finish_reason} | tokens used: {data.get('usage', {}).get('total_tokens', '?')}]")
except urllib.error.HTTPError as e:
body = e.read().decode('utf-8')
print(f"\nHTTP ERROR {e.code}: {body}", file=sys.stderr)
sys.exit(1)
except urllib.error.URLError as e:
print(f"\nCONNECTION ERROR: {e.reason}", file=sys.stderr)
sys.exit(1)
except (KeyError, IndexError) as e:
print(f"\nUNEXPECTED RESPONSE FORMAT: {e}", file=sys.stderr)
sys.exit(1)