require('dotenv').config(); const express = require('express'); const path = require('path'); const http = require('http'); const fs = require('fs'); const os = require('os'); const WebSocket = require('ws'); const { WebSocketServer } = WebSocket; const app = express(); app.use(express.json({ limit: '100mb' })); app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization'); if (req.method === 'OPTIONS') return res.sendStatus(200); next(); }); app.use(express.static(path.join(__dirname, 'public'))); const SARVAM_API_KEY = process.env.SARVAM_API_KEY; const SARVAM_CHAT_MODEL = process.env.SARVAM_CHAT_MODEL || 'sarvam-105b-conversations'; const GROQ_API_KEY = process.env.GROQ_API_KEY; const GROQ_PRIMARY_MODEL = 'openai/gpt-oss-120b'; const GROQ_FALLBACK_MODEL = 'minimaxai/minimax-m2.7'; const PORT = process.env.PORT || 3000; if (!SARVAM_API_KEY) { console.warn('WARNING: .env मध्ये SARVAM_API_KEY सेट केलेली नाही.'); } if (!GROQ_API_KEY) { console.warn('WARNING: .env मध्ये GROQ_API_KEY सेट केलेली नाही. Summary local fallback वापरेल.'); } const SUMMARY_SYSTEM_PROMPT = `You are an expert AI Clinical Documentation Assistant. Analyze the doctor-patient consultation transcript (which may be in Marathi, Hindi, English, or mixed Indic language). Generate a structured medical summary in clean JSON format matching this schema: { "chief_complaint": "Primary reason for visit and duration", "symptoms": ["Symptom 1", "Symptom 2"], "history": "History of present illness, past medical/surgical history, allergy history", "assessment": "Doctor diagnosis or clinical impression", "plan": ["Treatment step 1", "Medication Rx with dosage", "Follow-up/Diet instructions"] } If a section is not mentioned in the transcript, write "Not mentioned". Respond with pure JSON only, no markdown markers or extra conversational text.`; // --------------------------------------------------------------------------- // Sarvam AI Text Translation Safeguard (Always English Pipeline) // Uses Sarvam Translate API (mayura:v1) to translate any residual Indic text // --------------------------------------------------------------------------- async function ensureEnglishText(text) { if (!text || typeof text !== 'string' || !text.trim()) return text; // Check if text contains Devanagari/Indic characters (Marathi/Hindi) if (!/[\u0900-\u097F]/.test(text)) return text; if (!SARVAM_API_KEY) return text; // Handle multi-line strings with speaker markers const lines = text.split('\n'); if (lines.length > 1) { const translated = await Promise.all(lines.map(async line => { if (!line.trim() || !/[\u0900-\u097F]/.test(line)) return line; const speakerPrefixMatch = line.match(/^(\s*(?:\[[^\]]+\]|(?:Doctor|Patient|Relative|Nurse|डॉक्टर|पेशंट|रुग्ण)\s*[::\-])\s*)(.*)$/i); if (speakerPrefixMatch) { const prefix = speakerPrefixMatch[1]; const content = speakerPrefixMatch[2]; const trans = await ensureEnglishText(content); return prefix + trans; } return await ensureEnglishText(line); })); return translated.join('\n'); } try { const resp = await fetch('https://api.sarvam.ai/translate', { method: 'POST', headers: { 'api-subscription-key': SARVAM_API_KEY, 'Content-Type': 'application/json' }, body: JSON.stringify({ input: text, source_language_code: 'auto', target_language_code: 'en-IN', mode: 'formal', model: 'mayura:v1' }) }); if (resp.ok) { const data = await resp.json(); if (data.translated_text && data.translated_text.trim()) { return data.translated_text.trim(); } } } catch (err) { console.warn('[ensureEnglishText] Sarvam translation fallback error:', err.message); } return text; } // --------------------------------------------------------------------------- // REST: संभाषणाच्या transcript वरून क्लिनिकल समरी — LOCAL extraction (No LLM API) // Sarvam API फक्त transcript + diarization साठी वापरली जाते, summary साठी नाही. // --------------------------------------------------------------------------- /** * extractLocalSummary — Transcript मधून keyword/pattern-based NLP extraction * Marathi, Hindi, English mixed transcripts support करतो. */ function extractLocalSummary(transcript) { const lines = transcript.split(/\n+/).map(l => l.trim()).filter(l => l.length > 0); // ── Keyword dictionaries ── const symptomKeywords = [ // English primary patterns { pattern: /chest\s*pain/i, label: 'Chest pain' }, { pattern: /numbness|tingling/i, label: 'Numbness / Tingling' }, { pattern: /shortness\s*of\s*breath|breathless/i, label: 'Shortness of breath' }, { pattern: /fatigue|tired|exhaust/i, label: 'Fatigue / Weakness' }, { pattern: /insomnia|trouble\s*sleep|cannot\s*sleep|can't\s*sleep/i, label: 'Insomnia' }, { pattern: /fever|high\s*temperature/i, label: 'Fever' }, { pattern: /body\s*ache/i, label: 'Body ache' }, { pattern: /chills|rigors?/i, label: 'Chills' }, { pattern: /cough/i, label: 'Cough' }, { pattern: /sore\s*throat|throat\s*pain/i, label: 'Sore throat' }, { pattern: /difficulty\s*swallowing|trouble\s*swallowing|dysphagia/i, label: 'Difficulty swallowing (Dysphagia)' }, { pattern: /hoarseness|voice\s*heavy|lost\s*voice/i, label: 'Hoarseness of voice' }, { pattern: /headache/i, label: 'Headache' }, { pattern: /vomit|nausea/i, label: 'Nausea / Vomiting' }, { pattern: /diarrhea|loose\s*motion/i, label: 'Diarrhea' }, { pattern: /swelling|swollen/i, label: 'Swelling' }, { pattern: /burning.*urinat|urinat.*burning|dysuria/i, label: 'Burning urination (Dysuria)' }, { pattern: /thirst|polydipsia/i, label: 'Excessive thirst (Polydipsia)' }, { pattern: /pain/i, label: 'Pain' }, // Marathi & Hindi fallback patterns { pattern: /छातीत\s*(दुख|वेद|दाब)/i, label: 'Chest pain' }, { pattern: /मुंग्या/i, label: 'Numbness / Tingling' }, { pattern: /धाप\s*लाग/i, label: 'Shortness of breath' }, { pattern: /थकवा/i, label: 'Fatigue' }, { pattern: /झोप\s*(नाही|येत\s*नाही|लागत\s*नाही)/i, label: 'Insomnia' }, { pattern: /ताप/i, label: 'Fever' }, { pattern: /अंगदुखी/i, label: 'Body ache' }, { pattern: /तहान/i, label: 'Excessive thirst (Polydipsia)' }, { pattern: /लघवी.*जळजळ|जळजळ.*लघवी/i, label: 'Burning urination (Dysuria)' }, { pattern: /हुडहुडी/i, label: 'Chills' }, { pattern: /खोकला|खांसी|कफ/i, label: 'Cough' }, { pattern: /गळ.*दुख|गले.*दर्द|throat.*pain/i, label: 'Sore throat' }, { pattern: /निगल|गिलने/i, label: 'Difficulty swallowing (Dysphagia)' }, { pattern: /आवाज.*बैठ|आवाज.*भारी/i, label: 'Hoarseness of voice' }, { pattern: /डोके\s*दुख/i, label: 'Headache' }, { pattern: /उलटी|वांती/i, label: 'Vomiting' }, { pattern: /जुलाब/i, label: 'Diarrhea' }, { pattern: /सूज/i, label: 'Swelling' }, { pattern: /बुखार|बुख़ार/i, label: 'Fever' }, { pattern: /सीने.*दर्द/i, label: 'Chest pain' }, { pattern: /सांस.*तकलीफ/i, label: 'Shortness of breath' } ]; const historyKeywords = [ /(?:history|previously|since|duration|past|years?|months?)\s*.{5,80}/gi, /(?:blood\s*pressure|hypertension|diabetes|sugar|BP|asthma)\s*.{0,80}/gi, /(?:medicine|tablet|medication|dose|prescription)\s*.{0,60}/gi, /(?:type\s*\d)/gi, /(?:पूर्वी|आधी|पासून|वर्ष|साल)\s*.{5,80}/gi, /(?:ब्लड\s*प्रेशर|डायबिटीस|मधुमेह|दमा)\s*.{0,80}/gi, ]; const assessmentKeywords = [ /(?:diagnosis|assessment|impression|diagnosed)[\s::\-]*.{5,120}/gi, /(?:hypertension|diabetes|UTI|tonsillitis|pharyngitis|angina|ischemic|infection)\s*.{0,80}/gi, /(?:BP|blood\s*pressure|बीपी)\s*\d{2,3}\s*[\/\\]\s*\d{2,3}/gi, /(?:tonsil|infection|संसर्ग)\s*.{0,60}/gi, ]; const planKeywords = [ /(?:ECG|echo|MRI|CT|X-?ray|CBC|Urine|blood\s*test|test|investigation|ईसीजी|इको)\s*.{0,80}/gi, /(?:Tab(?:let)?|Syr(?:up)?|Cap(?:sule)?|medicine|antibiotic|paracetamol|cefixime|telmisartan|amlodipine|गोळी|औषध)\s*.{0,100}/gi, /(?:diet|salt|exercise|rest|water|warm\s*water|gargle|पथ्य|आहार|व्यायाम)\s*.{0,80}/gi, /(?:follow[\s-]*up|visit|see\s*me\s*again|come\s*back|days|फॉलो[\s-]*अप)\s*.{0,80}/gi, ]; // ── Extract ── const fullText = lines.join(' '); // Patient lines (first few patient utterances usually describe chief complaint) const patientLines = lines.filter(l => /^(?:\[.*Patient\]|पेशंट|patient|रुग्ण)/i.test(l)); const doctorLines = lines.filter(l => /^(?:\[.*Doctor\]|डॉक्टर|doctor)/i.test(l)); // Chief Complaint — first patient utterance let chiefComplaint = 'Not mentioned'; if (patientLines.length > 0) { const firstPatient = patientLines[0].replace(/^(?:\[.*?\]|(?:पेशंट|patient|रुग्ण)\s*[::\-])\s*/i, '').trim(); chiefComplaint = firstPatient.slice(0, 200) || 'Not mentioned'; } // Symptoms const symptomsFound = new Set(); symptomKeywords.forEach(kw => { if (kw.pattern.test(fullText)) { symptomsFound.add(kw.label); } }); const symptoms = symptomsFound.size > 0 ? [...symptomsFound] : ['No specific symptoms detected in transcript']; // History const historyMatches = new Set(); historyKeywords.forEach(re => { const matches = fullText.match(re); if (matches) matches.forEach(m => historyMatches.add(m.trim())); }); const history = historyMatches.size > 0 ? [...historyMatches].join('; ') : 'No prior medical history mentioned in transcript.'; // Assessment — from doctor lines const assessmentMatches = new Set(); const doctorText = doctorLines.join(' '); assessmentKeywords.forEach(re => { const matches = (doctorText || fullText).match(re); if (matches) matches.forEach(m => assessmentMatches.add(m.trim())); }); const assessment = assessmentMatches.size > 0 ? [...assessmentMatches].join('; ') : 'Clinical assessment — refer to transcript for details.'; // Plan const planMatches = new Set(); planKeywords.forEach(re => { const matches = (doctorText || fullText).match(re); if (matches) matches.forEach(m => planMatches.add(m.trim())); }); const plan = planMatches.size > 0 ? [...planMatches] : ['Refer to transcript for treatment plan details.']; return { chief_complaint: chiefComplaint, symptoms, history, assessment, plan, extraction_method: 'local_nlp' }; } /** * callGroqSummary — Groq API ला call करून LLM summary generate करतो * @param {string} transcript - consultation transcript * @param {string} model - Groq model ID * @returns {object|null} parsed summary or null on failure */ async function callGroqSummary(transcript, model) { const resp = await fetch('https://api.groq.com/openai/v1/chat/completions', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${GROQ_API_KEY}` }, body: JSON.stringify({ model: model, temperature: 0.2, messages: [ { role: 'system', content: SUMMARY_SYSTEM_PROMPT }, { role: 'user', content: `Consultation Transcript:\n${transcript}` } ] }) }); if (!resp.ok) { const errText = await resp.text(); console.error(`Groq model ${model} error (${resp.status}):`, errText.slice(0, 300)); return null; } const data = await resp.json(); const content = data?.choices?.[0]?.message?.content; if (!content) { console.error(`Groq model ${model}: empty response`); return null; } try { const cleaned = content.trim().replace(/^```json/i, '').replace(/^```/, '').replace(/```$/, '').trim(); return JSON.parse(cleaned); } catch (e) { console.error(`Groq model ${model}: JSON parse failed, returning raw`); return { chief_complaint: 'Extracted from conversation', symptoms: ['See detailed notes below'], history: 'Refer to raw transcript', assessment: 'Consultation reviewed', plan: [content], raw_text: content }; } } app.post('/api/summary', async (req, res) => { try { const { transcript } = req.body || {}; if (!transcript || !transcript.trim()) { return res.status(400).json({ error: 'Transcript is empty' }); } // Strategy: Groq LLM (primary model → fallback model) → Local NLP extraction if (GROQ_API_KEY) { // Try primary model: openai/gpt-oss-120b console.log(`1️⃣ Trying Groq LLM: ${GROQ_PRIMARY_MODEL}...`); let summary = await callGroqSummary(transcript, GROQ_PRIMARY_MODEL); if (summary) { summary.model_used = GROQ_PRIMARY_MODEL; console.log(`✅ Summary generated via ${GROQ_PRIMARY_MODEL}`); return res.json({ summary, notice: `Generated via Groq ${GROQ_PRIMARY_MODEL}` }); } // Try fallback model: minimaxai/minimax-m2.7 console.log(`2️⃣ Primary failed. Trying fallback: ${GROQ_FALLBACK_MODEL}...`); summary = await callGroqSummary(transcript, GROQ_FALLBACK_MODEL); if (summary) { summary.model_used = GROQ_FALLBACK_MODEL; console.log(`✅ Summary generated via ${GROQ_FALLBACK_MODEL}`); return res.json({ summary, notice: `Generated via Groq ${GROQ_FALLBACK_MODEL}` }); } console.warn('⚠️ Both Groq models failed. Falling back to local NLP extraction...'); } else { console.log('No GROQ_API_KEY configured. Using local NLP extraction...'); } // Final fallback: Local keyword-based extraction console.log('3️⃣ Using local keyword-based NLP extraction...'); const summary = extractLocalSummary(transcript); console.log('✅ Local summary extraction complete.'); res.json({ summary, notice: 'Extracted locally (Groq API unavailable or failed)' }); } catch (err) { console.error('summary error:', err); // Even if everything crashes, try local extraction try { const fallback = extractLocalSummary(req.body?.transcript || ''); return res.json({ summary: fallback, notice: 'Emergency local fallback' }); } catch (e2) { res.status(500).json({ error: err.message || 'Unexpected error' }); } } }); app.get('/api/health', (req, res) => { res.json({ ok: true, sarvamKeyConfigured: Boolean(SARVAM_API_KEY), model: SARVAM_CHAT_MODEL, sttModel: 'saaras:v4' }); }); // --------------------------------------------------------------------------- // REST: Multiple Clinical Cases & Demo Sample Conversations // --------------------------------------------------------------------------- const CLINICAL_CASES = [ { id: 'case-cardiology', title: 'Cardiology — Chest Pain & High BP', patientName: 'Ramesh Patil', patientId: 'PT-2026-00124', doctorName: 'Dr. Sharma (Cardiology)', doctorSpecialty: 'Cardiologist', language: 'en-IN', durationSec: 222, date: new Date().toLocaleDateString('en-GB'), transcript: `Doctor: Hello Rameshji, please have a seat. What trouble are you experiencing? Patient: Hello Doctor. For the past three days, I have had chest pain and numbness in my left arm. Doctor: Okay, do you experience more shortness of breath while walking or climbing stairs? Patient: Yes Doctor, even a little walking causes breathlessness and severe fatigue. I cannot sleep well at night. Doctor: Do you have any prior history of high blood pressure or diabetes? Patient: Yes Doctor, I have had high blood pressure for five years, but I was not taking medicine regularly. Doctor: Alright, let me check your BP. It is 160/100, which is high. We need to do an immediate ECG and 2D Echo test. In the meantime, I will prescribe medication to lower your blood pressure. Patient: Sure Doctor, I will get the tests done today. Any dietary restrictions to follow? Doctor: Yes, reduce salt intake in your diet, avoid oily and fatty foods, do light exercise, and avoid stress. Come back to see me this evening once the test reports arrive.`, summary: { chief_complaint: "Chest pain radiating to the left arm and numbness for the past 3 days", symptoms: [ "Chest pain", "Numbness in left arm", "Shortness of breath on exertion", "Severe fatigue and insomnia" ], history: "5-year history of hypertension, with irregular medication adherence.", assessment: "Uncontrolled Hypertension (BP: 160/100 mmHg), Suspected Angina / Ischemic Heart Disease. Immediate cardiac evaluation required.", plan: [ "Immediate ECG and 2D Echocardiography tests", "Start anti-hypertensive medication (Telmisartan 40mg + Amlodipine 5mg) immediately", "Reduce dietary salt intake and avoid oily/fatty foods", "Avoid physical and emotional stress; follow-up consultation this evening with reports" ] } }, { id: 'case-diabetes', title: 'General Medicine — Diabetes & Fever', patientName: 'Sunita Deshmukh', patientId: 'PT-2026-00123', doctorName: 'Dr. Kulkarni (General Physician)', doctorSpecialty: 'General Medicine', language: 'en-IN', durationSec: 195, date: new Date().toLocaleDateString('en-GB'), transcript: `Doctor: Welcome Sunitatai, what problem are you having? Patient: Doctor, I have had a high fever and body ache for two days. I feel thirsty frequently and have a burning sensation while urinating. Doctor: Alright, did you measure the fever at home? Patient: Yes, last night it was 102 degrees with severe chills. Doctor: Do you have diabetes? Have you checked your sugar levels recently? Patient: Yes, I have Type 2 Diabetes. Last week my fasting blood sugar was 180. Doctor: The fever could be due to a urinary tract infection (UTI) and uncontrolled blood sugar. I am prescribing an antibiotic and paracetamol. We will also do a CBC, urine routine, and fasting blood sugar test. Patient: Okay Doctor, should I drink plenty of water? Doctor: Yes, drink plenty of water and lemon water. Completely stop sugary foods. Come back with reports in 3 days.`, summary: { chief_complaint: "High fever with chills, body ache, and dysuria for 2 days", symptoms: [ "High fever (102°F)", "Body ache and chills", "Burning urination (Dysuria)", "Excessive thirst (Polydipsia)" ], history: "Type 2 Diabetes Mellitus - recent Fasting Blood Sugar: 180 mg/dL.", assessment: "Urinary Tract Infection (UTI) with Uncontrolled Diabetes Mellitus & Acute Febrile Illness.", plan: [ "Tab Paracetamol 650mg post-meals when fever occurs", "Tab Cefixime 200mg twice daily for 5 days", "CBC, Urine Routine & Microscopy, and Fasting Blood Sugar tests", "Drink 3-4 liters of water daily and maintain strict glycemic control" ] } }, { id: 'case-ent', title: 'ENT — Sore Throat & Severe Cough', patientName: 'Amit Verma', patientId: 'PT-2026-00122', doctorName: 'Dr. Joshi (ENT Specialist)', doctorSpecialty: 'Otolaryngology', language: 'en-IN', durationSec: 160, date: new Date().toLocaleDateString('en-GB'), transcript: `Doctor: Hello Amitji, please tell me what trouble you are having. Patient: Doctor, I have severe pain in my throat and a lot of difficulty swallowing food. I also have a dry cough. Doctor: How long has this issue been going on? Does your voice feel heavy or hoarse? Patient: It has been four days, Doctor. My voice has become hoarse and I cannot sleep at night due to coughing. Doctor: Open your mouth, let me examine your tonsils. The tonsils are quite red and swollen. Patient: Is it a serious infection, Doctor? Doctor: It is acute tonsillitis and pharyngitis. Gargle with warm salt water 3 times a day, and strictly avoid cold water and ice cream. I am prescribing an antibiotic and a cough syrup. Patient: Thank you Doctor, how many days until I feel relief? Doctor: You will see significant improvement in three days, but be sure to complete the full 5-day course.`, summary: { chief_complaint: "Severe throat pain, difficulty swallowing, and dry cough for 4 days", symptoms: [ "Severe throat pain", "Difficulty swallowing (Dysphagia)", "Hoarseness of voice", "Nocturnal dry cough" ], history: "No significant prior medical illness; symptoms started after intake of cold beverages.", assessment: "Acute Tonsillitis with Pharyngitis (Upper Respiratory Tract Infection).", plan: [ "Tab Amoxicillin + Clavulanate 625mg twice daily for 5 days", "Syr Cough Relief 10ml at night before sleeping", "Warm saline gargles 3 times a day", "Strictly avoid cold foods, sour items, and oily food" ] } } ]; app.get('/api/demos', (req, res) => { res.json({ cases: CLINICAL_CASES }); }); app.get('/api/demo', (req, res) => { const caseId = req.query.case || 'case-cardiology'; const selectedCase = CLINICAL_CASES.find(c => c.id === caseId) || CLINICAL_CASES[0]; res.json(selectedCase); }); // --------------------------------------------------------------------------- // REST: Single Chunk Streaming STT // --------------------------------------------------------------------------- app.post('/api/transcribe-chunk', async (req, res) => { try { const { audio_chunk_b64, chunk_index, total_chunks, start_time_sec, language_code } = req.body || {}; if (!audio_chunk_b64) return res.status(400).json({ error: 'audio_chunk_b64 missing' }); if (!SARVAM_API_KEY) return res.status(500).json({ error: 'SARVAM_API_KEY not configured on server.' }); const wavBuffer = Buffer.from(audio_chunk_b64, 'base64'); const lang = (language_code && language_code !== 'auto') ? language_code : 'unknown'; const formData = new FormData(); const blob = new Blob([wavBuffer], { type: 'audio/wav' }); formData.append('file', blob, `chunk_${chunk_index || 0}.wav`); formData.append('model', 'saaras:v4'); formData.append('mode', 'translate'); formData.append('language_code', lang); const resp = await fetch('https://api.sarvam.ai/speech-to-text', { method: 'POST', headers: { 'api-subscription-key': SARVAM_API_KEY }, body: formData }); if (!resp.ok) { const errText = await resp.text(); console.error(`Sarvam STT chunk ${chunk_index} error:`, errText); // BUG 5 FIX: Quota error पण proper 402 status code पाठवा (200 नाही) if (errText.includes('insufficient_quota') || errText.includes('No credits available') || resp.status === 402) { return res.status(402).json({ transcript: '', isQuotaError: true, error: 'Sarvam API credits exhausted. Please recharge your Sarvam account.' }); } return res.status(resp.status).json({ error: `Sarvam STT error: ${errText.slice(0, 400)}` }); } const data = await resp.json(); let transcriptText = data.transcript || ''; transcriptText = await ensureEnglishText(transcriptText); console.log(`✅ Chunk ${chunk_index + 1}/${total_chunks} transcribed (English): "${transcriptText.slice(0, 60)}..."`); res.json({ chunk_index: chunk_index || 0, total_chunks: total_chunks || 1, transcript: transcriptText, language_code: 'en-IN' }); } catch (err) { console.error('transcribe-chunk error:', err); res.status(500).json({ error: err.message || 'Chunk transcription error' }); } }); // --------------------------------------------------------------------------- // REST: Hybrid Diarization Endpoint (Production Approach) // Uses Sarvam STT + Nvidia NeMo via hybrid_diarization.py // --------------------------------------------------------------------------- const { exec } = require('child_process'); const crypto = require('crypto'); app.post('/api/hybrid-transcribe', async (req, res) => { try { const { audio_b64 } = req.body || {}; if (!audio_b64) return res.status(400).json({ error: 'audio_b64 missing' }); let wavBuffer = Buffer.from(audio_b64, 'base64'); // Save to temp file const tempFileName = `temp_audio/hybrid_${crypto.randomBytes(6).toString('hex')}.wav`; if (!fs.existsSync('temp_audio')) fs.mkdirSync('temp_audio'); fs.writeFileSync(tempFileName, wavBuffer); console.log(`[Hybrid] Running hybrid_diarization.py on ${tempFileName}...`); // Execute python script // Ensure you have python environment with NeMo set up! exec(`python hybrid_diarization.py ${tempFileName}`, { maxBuffer: 1024 * 1024 * 10 }, async (error, stdout, stderr) => { // Clean up temp file if (fs.existsSync(tempFileName)) fs.unlinkSync(tempFileName); if (error) { console.error(`[Hybrid] Error running python: ${error.message}`); console.error(`[Hybrid] stderr: ${stderr}`); return res.status(500).json({ error: 'Hybrid Diarization failed' }); } // Extract the dialogue part from stdout let finalTranscript = ""; const splitToken = "--- FINAL HYBRID DIALOGUE ---"; if (stdout.includes(splitToken)) { finalTranscript = stdout.split(splitToken)[1].trim(); } else { finalTranscript = stdout; } // Step 2: Use LLM to correct Context / Roles and ensure English output console.log(`[Hybrid] Running LLM Context Correction (English)...`); const correctionPrompt = `You are a medical NLP assistant. Below is a transcript diarized by an AI model. The speaker tags might have slight errors. Based on context (Doctor asks questions/prescribes, Patient describes symptoms), fix any obvious speaker tag errors. Format the output as a clean dialogue. Ensure the spoken dialogue is always in clear, fluent English, translating from Marathi or Hindi if any non-English text is present, while strictly preserving medical meaning and intent. Transcript: ${finalTranscript.slice(0, 4000)}`; try { const llmRes = await fetch('https://api.sarvam.ai/v1/chat/completions', { method: 'POST', headers: { 'Content-Type': 'application/json', 'api-subscription-key': SARVAM_API_KEY }, body: JSON.stringify({ model: SARVAM_CHAT_MODEL, temperature: 0.1, max_tokens: 2000, messages: [{ role: 'system', content: 'You are a helpful assistant.' }, { role: 'user', content: correctionPrompt }] }) }); const llmData = await llmRes.json(); const content = llmData?.choices?.[0]?.message?.content; if (content && content.trim()) { finalTranscript = content.trim(); } } catch (err) { console.error("[Hybrid] LLM Correction failed, using raw hybrid output:", err.message); } finalTranscript = await ensureEnglishText(finalTranscript); console.log(`[Hybrid] Success!`); res.json({ transcript: finalTranscript }); }); } catch (err) { console.error('hybrid-transcribe error:', err); res.status(500).json({ error: err.message || 'Unexpected error' }); } }); // --------------------------------------------------------------------------- // Clinical Diarization Role Classifier & Multi-Speaker Guardrails // Multi-Speaker Support: Doctor, Patient, Relative, Nurse // Fixes Doctor <-> Patient Inversion, Short-Turn Bleed & Multi-Party Conversations // --------------------------------------------------------------------------- function classifyRolesWithRules(normalizedEntries, uniqueSpeakerIds) { const scores = {}; uniqueSpeakerIds.forEach(id => { scores[id] = { doctor: 0, patient: 0, relative: 0, nurse: 0 }; }); const doctorKeywords = [ 'tablet', 'tablets', 'capsule', 'medicine', 'medicines', 'syrup', 'dosage', 'dose', 'mg', 'twice a day', 'once a day', 'three times', 'after food', 'before food', 'after meals', 'before meals', 'let me examine', 'let me check', 'open your mouth', 'deep breath', 'take a breath', 'blood test', 'cbc', 'x-ray', 'ecg', 'sonography', 'ultrasound', 'mri', 'ct scan', 'urine test', 'come back', 'follow up', 'avoid oily', 'reduce salt', 'drink water', 'don\'t worry', 'diagnosis', 'infection', 'hypertension', 'blood pressure', 'fever is', 'prescribe', 'prescribing' ]; const patientKeywords = [ 'i have', 'i feel', 'i am having', 'i suffer', 'since yesterday', 'since 2 days', 'since 3 days', 'severe pain', 'chest pain', 'stomach ache', 'headache', 'throat pain', 'back pain', 'nausea', 'vomiting', 'loose motion', 'cough', 'cold', 'fever', 'shivering', 'weakness', 'dizziness', 'cannot sleep', 'hurts', 'burning sensation', 'yes doctor', 'okay doctor', 'thank you doctor', 'sure doctor', 'will i be okay', 'how many days', 'should i take' ]; const relativeKeywords = [ 'my mother', 'my father', 'my son', 'my daughter', 'my husband', 'my wife', 'my brother', 'my sister', 'my child', 'my baby', 'he has', 'she has', 'he is having', 'she is having', 'he cannot', 'she cannot', 'his fever', 'her fever', 'his pain', 'her pain', 'he didn\'t eat', 'she didn\'t eat', 'they are' ]; const nurseKeywords = [ 'spo2', 'pulse rate', 'blood pressure reading', 'temperature reading', 'vital signs', 'chart', 'next patient' ]; normalizedEntries.forEach(entry => { const text = (entry.textContent || '').toLowerCase(); const id = entry.speakerId; if (!scores[id]) return; doctorKeywords.forEach(kw => { if (text.includes(kw)) scores[id].doctor += 2; }); patientKeywords.forEach(kw => { if (text.includes(kw)) scores[id].patient += 1.5; }); relativeKeywords.forEach(kw => { if (text.includes(kw)) scores[id].relative += 3; }); nurseKeywords.forEach(kw => { if (text.includes(kw)) scores[id].nurse += 3; }); }); const roleMap = {}; // Find speaker with highest doctor score let maxDocScore = -1; let doctorSpeakerId = null; uniqueSpeakerIds.forEach(id => { if (scores[id].doctor > maxDocScore) { maxDocScore = scores[id].doctor; doctorSpeakerId = id; } }); if (doctorSpeakerId) { roleMap[doctorSpeakerId] = 'Doctor'; } // Assign remaining speakers uniqueSpeakerIds.forEach(id => { if (id === doctorSpeakerId) return; const sc = scores[id]; if (sc.relative >= 3 && sc.relative > sc.patient) { roleMap[id] = 'Relative'; } else if (sc.nurse >= 3 && sc.nurse > sc.patient) { roleMap[id] = 'Nurse'; } else { roleMap[id] = 'Patient'; } }); // Safety fallback if no doctor was identified if (!Object.values(roleMap).includes('Doctor')) { roleMap[uniqueSpeakerIds[0]] = 'Doctor'; if (uniqueSpeakerIds.length > 1) { roleMap[uniqueSpeakerIds[1]] = 'Patient'; } } return roleMap; } function refineTurnRole(assignedRole, textContent) { if (!textContent || typeof textContent !== 'string') return assignedRole; const lower = textContent.toLowerCase().trim(); // 1. Patient Inquiries and Medication Questions (takes priority over prescription keywords) const patientInquiryPatterns = [ /\b(?:what (?:will|should|all will|do) i do with (?:the )?(?:rest of the )?(?:pills|tablets|medicine|medicines))\b/i, /\b(?:how many (?:times|days|pills|tablets) (?:should|do) i take)\b/i, /\b(?:should i take|can i take|do i need to take|should i continue)\b/i, /\b(?:what about (?:the|my) (?:pills|diet|food|reports))\b/i, /\b(?:how long (?:will|should) i take)\b/i ]; if (patientInquiryPatterns.some(rx => rx.test(lower))) { return 'Patient'; } // 2. Definite Patient Symptoms & Self-Reporting (e.g. fever in stomach, no pain now) const patientSymptomPatterns = [ /\b(?:i had|i have|i feel|i am having|i suffered|i was having|i took|i vomited)\b/i, /\b(?:fever in my|pain in my|my stomach|my chest|my throat|my head|my back|my leg|my arm)\b/i, /\b(?:now it's all gone|now there is no pain|no pain now|getting better)\b/i, /\b(?:since yesterday|for \d+ days|since \d+ days|since last night)\b/i, /\b(?:doctor,?\s+(?:i have|i had|i feel|can i|should i))\b/i ]; if (patientSymptomPatterns.some(rx => rx.test(lower))) { if (!lower.startsWith('so you had') && !lower.startsWith('do you have') && !lower.startsWith('did you have') && !lower.startsWith('you had')) { return 'Patient'; } } // 3. Definite Relative speech patterns (3rd person) const relativePatterns = [ /\b(?:my\s+(?:father|mother|husband|wife|son|daughter|brother|sister|grandfather|grandmother|child|baby|dad|mom))\b/i, /\b(?:he has had|she has had|he cannot|she cannot|he is not|she is not|he feels|she feels)\b/i, /\b(?:his fever|her fever|his pain|her pain|his stomach|her stomach)\b/i ]; if (relativePatterns.some(rx => rx.test(lower))) { return 'Relative'; } // 4. Definite Doctor speech patterns (Prescriptions, Clinical Advice, Examination) const doctorPatterns = [ /\b(?:take (?:the|these|this|one|two) (?:pills|tablets|capsule|syrup|medicine))\b/i, /\b\d+\s*mg\b/i, /\b(?:twice|thrice|once)\s+(?:a|daily|every)\s*day\b/i, /\b(?:after|before)\s+(?:meals|food|eating|breakfast|dinner|lunch)\b/i, /\b(?:open your mouth|let me check|take a deep breath|show me your|lie down on the bed)\b/i, /\b(?:get an? (?:ecg|x-ray|blood test|cbc|ultrasound|ct scan|mri))\b/i, /\b(?:come back|follow up|visit again)\s+(?:after|in)\s+\d+\s*(?:days|weeks)\b/i, /\b(?:reduce salt|avoid oily|drink plenty of water|working fine for now|are working fine)\b/i ]; if (doctorPatterns.some(rx => rx.test(lower))) { return 'Doctor'; } return assignedRole; } async function classifyConversationRoles(normalizedEntries, uniqueSpeakerIds) { let roleMap = {}; const speakerListStr = uniqueSpeakerIds.join(', '); const exampleMapping = Object.fromEntries( uniqueSpeakerIds.map((id, idx) => [id, idx === 0 ? 'Doctor' : (idx === 1 ? 'Patient' : 'Relative')]) ); const plainConversation = normalizedEntries.map(entry => `${entry.speakerId}: ${entry.textContent}`).join('\n'); const classifierPrompt = `You are an expert Clinical Consultation Role Classifier. TASK: Analyze this consultation transcript and assign each unique speaker to EXACTLY ONE role from: 'Doctor', 'Patient', 'Relative', 'Nurse'. SPEAKERS DETECTED IN TRANSCRIPT: [${speakerListStr}] MANDATORY CLINICAL RULES: 1. Every consultation transcript MUST contain at least one 'Patient' and one 'Doctor'. NEVER omit 'Patient' or 'Doctor'. 2. If 2 speakers are detected: One MUST be 'Doctor' and the other MUST be 'Patient'. 3. If 3 or more speakers are detected: Assign 'Doctor' (the medical professional) and 'Patient' (the person being treated) first. Only assign 'Relative' if a speaker speaks on behalf of the patient in third person ('my mother has fever', 'he didn't eat'). Only assign 'Nurse' if taking vitals or assisting. ROLE CRITERIA & CONTEXTUAL BOUNDARIES: - 'Doctor': Asks diagnostic questions, conducts clinical examination, explains medical conditions, prescribes medicines/tests/dosages, gives medical advice. - 'Patient': Describes their own symptoms ("I had fever", "now there is no pain"), answers doctor questions about pain/duration, asks about treatment/diet for themselves ("What will I do with the rest of the pills?"). - 'Relative': Accompanying family member (spouse, parent, child). Speaks about the patient's personal home life, sleep, eating habits, or home-observed symptoms ("my mother has fever", "he cannot sleep", "he is not eating"). - 'Nurse': Clinic/hospital staff handling operational tasks, patient navigation, room instructions ("come inside", "are you with them", "sit here", "go inside now", "next patient / next song"), taking vitals (BP, SpO2, pulse, temperature), or checking medical files. CRITICAL DISTINCTION (NURSE vs RELATIVE): - Procedural, logistical, clinic-room, or patient flow instructions ("are you with them", "go inside", "look", "next patient", "take chart") = 'Nurse'. - Family health, home care, home symptoms, or diet discussions = 'Relative'. CRITICAL INSTRUCTION: Return ONLY a valid JSON object where keys are the EXACT speaker IDs listed above and values are the roles. Example format: ${JSON.stringify(exampleMapping, null, 2)} TRANSCRIPT: ${plainConversation.slice(0, 4000)}`; // 1. Try Groq Primary Model (openai/gpt-oss-120b) if (GROQ_API_KEY) { try { console.log(`[RoleClassifier] Attempting Groq primary (${GROQ_PRIMARY_MODEL})...`); const gRes = await fetch('https://api.groq.com/openai/v1/chat/completions', { method: 'POST', headers: { 'Authorization': `Bearer ${GROQ_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ model: GROQ_PRIMARY_MODEL, temperature: 0.1, messages: [ { role: 'system', content: 'You are a strict clinical JSON role classifier. Output valid JSON only, no markdown or reasoning.' }, { role: 'user', content: classifierPrompt } ] }) }); if (gRes.ok) { const gData = await gRes.json(); const content = gData?.choices?.[0]?.message?.content || ''; const match = content.match(/\{[\s\S]*\}/); if (match) { roleMap = JSON.parse(match[0]); console.log(`✅ [RoleClassifier] Groq primary succeeded:`, roleMap); } } else { console.warn(`[RoleClassifier] Groq primary failed with status ${gRes.status}`); } } catch (err) { console.warn(`[RoleClassifier] Groq primary error:`, err.message); } // 1b. Try Groq Fallback Model (openai/gpt-oss-20b) if primary didn't succeed if (Object.keys(roleMap).length === 0) { try { console.log(`[RoleClassifier] Attempting Groq fallback (openai/gpt-oss-20b)...`); const gRes = await fetch('https://api.groq.com/openai/v1/chat/completions', { method: 'POST', headers: { 'Authorization': `Bearer ${GROQ_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ model: 'openai/gpt-oss-20b', temperature: 0.1, messages: [ { role: 'system', content: 'You are a strict clinical JSON role classifier. Output valid JSON only, no markdown or reasoning.' }, { role: 'user', content: classifierPrompt } ] }) }); if (gRes.ok) { const gData = await gRes.json(); const content = gData?.choices?.[0]?.message?.content || ''; const match = content.match(/\{[\s\S]*\}/); if (match) { roleMap = JSON.parse(match[0]); console.log(`✅ [RoleClassifier] Groq fallback succeeded:`, roleMap); } } } catch (err) { console.warn(`[RoleClassifier] Groq fallback error:`, err.message); } } } // 2. Try Sarvam Chat Model if Groq was not available or failed if (Object.keys(roleMap).length === 0 && SARVAM_API_KEY) { try { console.log(`[RoleClassifier] Attempting Sarvam Chat (${SARVAM_CHAT_MODEL})...`); const sRes = await fetch('https://api.sarvam.ai/v1/chat/completions', { method: 'POST', headers: { 'Content-Type': 'application/json', 'api-subscription-key': SARVAM_API_KEY }, body: JSON.stringify({ model: SARVAM_CHAT_MODEL, temperature: 0.1, max_tokens: 300, messages: [ { role: 'system', content: 'Output JSON only.' }, { role: 'user', content: classifierPrompt } ] }) }); if (sRes.ok) { const sData = await sRes.json(); const content = sData?.choices?.[0]?.message?.content || ''; const match = content.match(/\{[\s\S]*\}/); if (match) { roleMap = JSON.parse(match[0]); console.log(`✅ [RoleClassifier] Sarvam Chat succeeded:`, roleMap); } } } catch (err) { console.warn(`[RoleClassifier] Sarvam Chat error:`, err.message); } } // 3. Fallback: Deterministic Clinical Rule-Based Classifier if (Object.keys(roleMap).length === 0) { console.log(`[RoleClassifier] Using clinical rule-based NLP classifier fallback...`); roleMap = classifyRolesWithRules(normalizedEntries, uniqueSpeakerIds); console.log(`✅ [RoleClassifier] Rule-based classifier result:`, roleMap); } // Ensure all detected uniqueSpeakerIds have a valid normalized role uniqueSpeakerIds.forEach(id => { if (!roleMap[id]) { roleMap[id] = id === uniqueSpeakerIds[0] ? 'Doctor' : 'Patient'; } const r = roleMap[id].toString().toLowerCase(); if (r.includes('doc')) roleMap[id] = 'Doctor'; else if (r.includes('relat') || r.includes('fam') || r.includes('attend')) roleMap[id] = 'Relative'; else if (r.includes('nurse')) roleMap[id] = 'Nurse'; else roleMap[id] = 'Patient'; }); // MANDATORY CLINICAL RULE: Every consultation MUST contain at least one Patient and one Doctor! const hasPatient = Object.values(roleMap).includes('Patient'); const hasDoctor = Object.values(roleMap).includes('Doctor'); if (!hasPatient) { console.warn("⚠️ [RoleClassifier] No 'Patient' assigned in roleMap! Enforcing Patient role..."); const nonDoctorIds = uniqueSpeakerIds.filter(id => roleMap[id] !== 'Doctor'); if (nonDoctorIds.length > 0) { roleMap[nonDoctorIds[0]] = 'Patient'; } else if (uniqueSpeakerIds.length > 1) { roleMap[uniqueSpeakerIds[1]] = 'Patient'; } } if (!hasDoctor) { console.warn("⚠️ [RoleClassifier] No 'Doctor' assigned in roleMap! Enforcing Doctor role..."); const nonPatientIds = uniqueSpeakerIds.filter(id => roleMap[id] !== 'Patient'); if (nonPatientIds.length > 0) { roleMap[nonPatientIds[0]] = 'Doctor'; } else { roleMap[uniqueSpeakerIds[0]] = 'Doctor'; } } return roleMap; } // --------------------------------------------------------------------------- // Intent-Based Conversational Dialogue Turn Refinement // Resolves acoustic cluster collapse, mono mic bleed, and Marathi pro-drop // by analyzing human conversational intent rather than brittle keyword matching // --------------------------------------------------------------------------- async function refineTurnsWithIntent(normalizedEntries, roleMap) { if (!normalizedEntries || normalizedEntries.length === 0) return []; // Default baseline mapping using roleMap and rule-based heuristic const fallbackRoles = normalizedEntries.map(entry => { const base = roleMap[entry.speakerId] || 'Patient'; return refineTurnRole(base, entry.textContent); }); if (!GROQ_API_KEY && !SARVAM_API_KEY) { return fallbackRoles; } const turnsText = normalizedEntries.map((t, idx) => { const base = roleMap[t.speakerId] || 'Speaker'; return `[Turn ${idx}] (${t.speakerId} | Baseline: ${base}): "${(t.textContent || '').replace(/"/g, "'")}"`; }).join('\n'); const intentPrompt = `You are an expert Clinical Consultation Dialogue Analyzer. Below is a transcribed clinical consultation. Because acoustic diarization can bleed or miscluster across noisy microphones, some utterances spoken by the patient, relative, or nurse may have been grouped under the Doctor's track (or vice versa). ROLES & CONTEXTUAL BOUNDARIES: - 'Doctor': Medical professional examining, inquiring, reassuring, explaining medical condition, prescribing medicines/dosages, giving medical advice. - 'Patient': Person receiving medical care, describing personal bodily sensations/symptoms/fever/pain, answering questions about their physical health, or asking about their medication/diet/what they should do. - 'Relative': Accompanying family member (spouse, parent, child). Speaks about the patient's personal home life, sleep, eating habits, or home-observed symptoms ('my husband has pain', 'she hasn't eaten since yesterday'). - 'Nurse': Clinic or hospital staff handling operational tasks, patient navigation, room instructions ("come inside", "are you with them, go inside", "look", "sit on bed", "next patient / next song"), taking vitals (BP, SpO2, pulse, temperature), or checking medical charts. CRUCIAL DISTINCTION (NURSE vs RELATIVE): - If the speaker gives logistical, clinic-room, or procedural instructions ("are you with them, go inside", "look", "wait outside", "next patient", "give file"), classify as 'Nurse'. - If the speaker discusses family health, personal care, home lifestyle, or expresses emotional concern for the patient, classify as 'Relative'. CONVERSATION TURNS: ${turnsText.slice(0, 5000)} TASK: Classify each turn index based on the TRUE CONVERSATIONAL INTENT. - If an utterance is reporting personal symptoms, sensations, or asking what to do with treatment, classify as 'Patient'. - If an utterance is medical reassurance, diagnosis, or prescription instructions, classify as 'Doctor'. - If an utterance is clinic navigation/room coordination ("are you with them", "go inside", "look"), classify as 'Nurse'. - If an utterance is home/family health history, classify as 'Relative'. OUTPUT FORMAT: Output ONLY a valid JSON array of strings containing the exact role for each turn index from 0 to ${normalizedEntries.length - 1}. Example: ["Doctor", "Patient", "Patient", "Nurse", "Doctor"]`; // Try Groq Primary (openai/gpt-oss-120b) if (GROQ_API_KEY) { try { console.log(`[IntentClassifier] Refining ${normalizedEntries.length} turns with Groq (${GROQ_PRIMARY_MODEL})...`); const gRes = await fetch('https://api.groq.com/openai/v1/chat/completions', { method: 'POST', headers: { 'Authorization': `Bearer ${GROQ_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ model: GROQ_PRIMARY_MODEL, temperature: 0.1, messages: [ { role: 'system', content: 'You are a strict clinical dialogue role analyzer. Output JSON array only.' }, { role: 'user', content: intentPrompt } ] }) }); if (gRes.ok) { const gData = await gRes.json(); const content = gData?.choices?.[0]?.message?.content || ''; const match = content.match(/\[[\s\S]*\]/); if (match) { const parsed = JSON.parse(match[0]); if (Array.isArray(parsed) && parsed.length === normalizedEntries.length) { console.log(`✅ [IntentClassifier] Successfully refined ${parsed.length} turns via Groq.`); return parsed.map((r, i) => { const val = (r || '').toString().toLowerCase(); if (val.includes('doc')) return 'Doctor'; if (val.includes('relat') || val.includes('fam')) return 'Relative'; if (val.includes('nurse')) return 'Nurse'; return 'Patient'; }); } } } } catch (err) { console.warn(`[IntentClassifier] Groq intent error:`, err.message); } } // Fallback to heuristic roles console.log(`[IntentClassifier] Using heuristic turn role fallback.`); return fallbackRoles; } // --------------------------------------------------------------------------- // REST: Full audio (base64 WAV) → Sarvam STT → transcript // --------------------------------------------------------------------------- app.post('/api/transcribe', async (req, res) => { try { const { audio_b64, language_code, num_speakers } = req.body || {}; if (!audio_b64) return res.status(400).json({ error: 'audio_b64 missing' }); if (!SARVAM_API_KEY) return res.status(500).json({ error: 'SARVAM_API_KEY not configured on server.' }); let wavBuffer = Buffer.from(audio_b64, 'base64'); let { dataOffset, dataLength, sampleRate, numChannels, bitsPerSample } = parseWavHeader(wavBuffer); const bytesPerSec = sampleRate * numChannels * (bitsPerSample / 8); const lang = (language_code && language_code !== 'auto') ? language_code : 'unknown'; const parsedSpeakers = (num_speakers && parseInt(num_speakers, 10) > 0) ? parseInt(num_speakers, 10) : null; console.log(`1. Initializing Sarvam Batch Job (Transcript + Diarization, Mode: Translate, Num Speakers: ${parsedSpeakers || 'Auto-Detect'})...`); const jobParams = { model: "saaras:v4", mode: "translate", with_diarization: true, with_timestamps: true, language_code: lang }; if (parsedSpeakers !== null) { jobParams.num_speakers = parsedSpeakers; } const initRes = await fetch('https://api.sarvam.ai/speech-to-text/job/v1', { method: 'POST', headers: { 'api-subscription-key': SARVAM_API_KEY, 'Content-Type': 'application/json' }, body: JSON.stringify({ job_parameters: jobParams }) }); const initData = await initRes.json(); if (!initData.job_id) throw new Error("Failed to initialize job: " + JSON.stringify(initData)); const jobId = initData.job_id; console.log("2. Getting Upload URL..."); const uploadRes = await fetch('https://api.sarvam.ai/speech-to-text/job/v1/upload-files', { method: 'POST', headers: { 'api-subscription-key': SARVAM_API_KEY, 'Content-Type': 'application/json' }, body: JSON.stringify({ job_id: jobId, files: ["audio.wav"] }) }); const uploadData = await uploadRes.json(); const uploadUrl = uploadData.upload_urls["audio.wav"].file_url; console.log("3. Uploading Audio..."); const putRes = await fetch(uploadUrl, { method: 'PUT', headers: { 'x-ms-blob-type': 'BlockBlob', 'Content-Type': 'audio/wav' }, body: wavBuffer }); if (!putRes.ok) throw new Error("Failed to upload audio to blob."); console.log("4. Starting Job..."); await fetch(`https://api.sarvam.ai/speech-to-text/job/v1/${jobId}/start`, { method: 'POST', headers: { 'api-subscription-key': SARVAM_API_KEY, 'Content-Type': 'application/json' } }); console.log("5. Polling Status..."); let statusData; for (let i = 0; i < 60; i++) { const statusRes = await fetch(`https://api.sarvam.ai/speech-to-text/job/v1/${jobId}/status`, { method: 'GET', headers: { 'api-subscription-key': SARVAM_API_KEY } }); statusData = await statusRes.json(); console.log(`Poll ${i}:`, statusData.job_state); if (statusData.job_state === "Completed" || statusData.job_state === "Failed") break; await new Promise(r => setTimeout(r, 5000)); } if (statusData.job_state !== "Completed") { throw new Error("Job failed or timed out: " + JSON.stringify(statusData)); } const outFile = statusData.job_details[0].outputs[0].file_name; console.log("6. Getting Download URL..."); const dlRes = await fetch('https://api.sarvam.ai/speech-to-text/job/v1/download-files', { method: 'POST', headers: { 'api-subscription-key': SARVAM_API_KEY, 'Content-Type': 'application/json' }, body: JSON.stringify({ job_id: jobId, files: [outFile] }) }); const dlData = await dlRes.json(); const dlUrl = dlData.download_urls[outFile].file_url; console.log("7. Downloading Result..."); const resultRes = await fetch(dlUrl); const resultData = await resultRes.json(); let finalTranscript = ''; let structuredEntries = []; // Parse Diarized Transcript natively returned by Sarvam if (resultData.diarized_transcript && resultData.diarized_transcript.entries && resultData.diarized_transcript.entries.length > 0) { console.log("Sample Diarization Entry from Sarvam:", resultData.diarized_transcript.entries[0]); // Step 1: Normalize Speaker IDs, timestamps, and extract plain conversation for NLP const normalizedEntries = await Promise.all(resultData.diarized_transcript.entries.map(async entry => { const rawId = (entry.speaker || entry.speaker_id || entry.speaker_label || '0').toString(); const speakerId = rawId.toUpperCase().startsWith('SPEAKER') ? rawId : `Speaker_${rawId}`; let textContent = entry.text || entry.transcript || entry.words || ''; textContent = await ensureEnglishText(textContent); const startSec = typeof entry.start_time_seconds === 'number' ? entry.start_time_seconds : (parseFloat(entry.start_time_seconds || entry.start_time || entry.start || 0) || 0); const endSec = typeof entry.end_time_seconds === 'number' ? entry.end_time_seconds : (parseFloat(entry.end_time_seconds || entry.end_time || entry.end || 0) || (startSec + 2.0)); return { speakerId, textContent, startSec: Number(startSec.toFixed(2)), endSec: Number(endSec.toFixed(2)) }; })); // Strict Chronological Sort: Order utterances strictly by spoken timeline normalizedEntries.sort((a, b) => { if (a.startSec !== b.startSec) return a.startSec - b.startSec; return a.endSec - b.endSec; }); // Step 2: Role Classifier using Multi-Provider LLM Context Analysis + Clinical Rule Guardrail console.log("8. Running Multi-Speaker Diarization Role Classifier & Integrity Guardrails..."); const uniqueSpeakerIds = Array.from(new Set(normalizedEntries.map(e => e.speakerId))); const roleMap = await classifyConversationRoles(normalizedEntries, uniqueSpeakerIds); console.log("Final Speaker Role Mapping:", roleMap); // Step 3: Apply Intent-Based Turn Alignment (resolves acoustic cluster bleed & natural speech misattribution) console.log("9. Refining Turn Roles using Conversational Intent Analysis..."); const turnRoles = await refineTurnsWithIntent(normalizedEntries, roleMap); structuredEntries = normalizedEntries.map((entry, idx) => { const finalRole = turnRoles[idx] || roleMap[entry.speakerId] || 'Patient'; return { speakerId: entry.speakerId, role: finalRole, text: entry.textContent, startSec: entry.startSec, endSec: entry.endSec }; }); // Strict Chronological Sort for Structured UI Entries & Final Transcript structuredEntries.sort((a, b) => { if (a.startSec !== b.startSec) return a.startSec - b.startSec; return a.endSec - b.endSec; }); finalTranscript = structuredEntries.map(entry => { return `[${entry.speakerId} | ${entry.role}] ${entry.text}`; }).join('\n\n'); console.log("Sarvam Native Diarization + Role Classification complete!"); } else { finalTranscript = await ensureEnglishText(resultData.transcript || "No transcript found."); } res.json({ transcript: finalTranscript, entries: structuredEntries, chunks: 1, language: lang, processedSeconds: dataLength / bytesPerSec }); } catch (err) { console.error('transcribe error:', err); res.status(500).json({ error: err.message || 'Unexpected error' }); } }); // --------------------------------------------------------------------------- // REST: Standalone Diarization Endpoint // --------------------------------------------------------------------------- app.post('/api/diarize', async (req, res) => { try { const { transcript } = req.body || {}; if (!transcript) return res.status(400).json({ error: 'transcript missing' }); if (!SARVAM_API_KEY) return res.status(500).json({ error: 'SARVAM_API_KEY not configured.' }); let finalTranscript = transcript; const DIARIZE_PROMPT = `You are an expert medical conversation diarizer. TASK: Identify WHO said WHAT in this doctor-patient conversation. STRICT RULES: 1. Output ONLY a valid JSON array. No markdown, no explanations, no reasoning. 2. Each object must have "speaker" (either "Doctor" or "Patient") and "text" (the spoken words in English). 3. "Doctor" = asks questions, examines, prescribes. "Patient" = describes symptoms. 4. The "text" field must ALWAYS be in English. If any input conversation is in Marathi, Hindi, or mixed Indic language, translate it faithfully into English while strictly preserving the original meaning, context, and clinical intent without losing or hallucinating information. Example Output: [ {"speaker": "Doctor", "text": "What trouble are you experiencing?"}, {"speaker": "Patient", "text": "I have had a headache for two days."} ] NOW DIARIZE THIS: ${transcript}`; const diarizeResp = await fetch('https://api.sarvam.ai/v1/chat/completions', { method: 'POST', headers: { 'Content-Type': 'application/json', 'api-subscription-key': SARVAM_API_KEY }, body: JSON.stringify({ model: SARVAM_CHAT_MODEL, temperature: 0.1, max_tokens: 2500, messages: [ { role: 'system', content: 'You are a helpful JSON API returning only valid JSON.' }, { role: 'user', content: DIARIZE_PROMPT } ] }) }); if (diarizeResp.ok) { const diarizeData = await diarizeResp.json(); let content = diarizeData?.choices?.[0]?.message?.content; if (content && content.trim()) { try { const cleaned = content.trim().replace(/^```(?:json)?/i, '').replace(/```$/, '').trim(); const parsed = JSON.parse(cleaned); finalTranscript = parsed.map(item => `${item.speaker}: ${item.text}`).join('\n\n'); } catch (err) { console.error("Failed to parse Diarize JSON:", err); } } } else { const errText = await diarizeResp.text(); console.error('Sarvam Diarization failed:', errText); if (errText.includes('insufficient_quota') || errText.includes('No credits available')) { return res.status(402).json({ error: 'Sarvam API quota exhausted for LLM.' }); } return res.status(500).json({ error: 'Diarization API failed.' }); } finalTranscript = await ensureEnglishText(finalTranscript); res.json({ transcript: finalTranscript }); } catch (err) { console.error('diarize error:', err); res.status(500).json({ error: err.message || 'Unexpected error' }); } }); // ── WAV helpers ────────────────────────────────────────────────────────────── function parseWavHeader(buf) { let offset = 12; let sampleRate = 16000, numChannels = 1, bitsPerSample = 16; let dataOffset = 44, dataLength = buf.length - 44; while (offset + 8 <= buf.length) { const chunkId = buf.toString('ascii', offset, offset + 4); const chunkSize = buf.readUInt32LE(offset + 4); if (chunkId === 'fmt ') { numChannels = buf.readUInt16LE(offset + 10); sampleRate = buf.readUInt32LE(offset + 12); bitsPerSample = buf.readUInt16LE(offset + 22); } else if (chunkId === 'data') { dataOffset = offset + 8; dataLength = chunkSize; break; } offset += 8 + chunkSize; } return { dataOffset, dataLength, sampleRate, numChannels, bitsPerSample }; } function buildWav(pcmData, sampleRate, numChannels, bitsPerSample) { const dataLen = pcmData.length; const headerLen = 44; const buf = Buffer.alloc(headerLen + dataLen); buf.write('RIFF', 0); buf.writeUInt32LE(36 + dataLen, 4); buf.write('WAVE', 8); buf.write('fmt ', 12); buf.writeUInt32LE(16, 16); buf.writeUInt16LE(1, 20); buf.writeUInt16LE(numChannels, 22); buf.writeUInt32LE(sampleRate, 24); buf.writeUInt32LE(sampleRate * numChannels * bitsPerSample / 8, 28); buf.writeUInt16LE(numChannels * bitsPerSample / 8, 32); buf.writeUInt16LE(bitsPerSample, 34); buf.write('data', 36); buf.writeUInt32LE(dataLen, 40); pcmData.copy(buf, headerLen); return buf; } module.exports = { app, classifyConversationRoles, classifyRolesWithRules, refineTurnRole, refineTurnsWithIntent }; let server; if (require.main === module) { server = app.listen(PORT, () => { console.log(`✅ Server चालू आहे: http://localhost:${PORT}`); }); server.setTimeout(300000); server.keepAliveTimeout = 300000; server.headersTimeout = 310000; // --------------------------------------------------------------------------- // WebSocket Proxy: Browser <-> Sarvam Realtime STT (Mode: Translate) // Streams 16kHz mono PCM to Sarvam and relays English partial/final transcripts // --------------------------------------------------------------------------- const wss = new WebSocketServer({ server, path: '/ws/transcribe' }); wss.on('connection', (clientWs, req) => { if (!SARVAM_API_KEY) { clientWs.send(JSON.stringify({ event: 'error', message: 'SARVAM_API_KEY not configured.' })); clientWs.close(); return; } const urlObj = new URL(req.url, 'http://localhost'); let lang = urlObj.searchParams.get('language_code') || 'auto'; if (lang === 'unknown') lang = 'auto'; const sarvamWsUrl = `wss://api.sarvam.ai/speech-to-text-realtime/ws?language_code=${encodeURIComponent(lang)}&model=saaras:v3-realtime&encoding=linear16&sample_rate=16000&stream_type=balanced&mode=translate`; let sarvamWs = null; try { sarvamWs = new WebSocket(sarvamWsUrl, { headers: { 'api-subscription-key': SARVAM_API_KEY } }); } catch (e) { console.error('[WS Proxy] Error connecting to Sarvam WS:', e.message); clientWs.send(JSON.stringify({ event: 'error', message: e.message })); clientWs.close(); return; } sarvamWs.on('open', () => { console.log(`[WS Proxy] Connected to Sarvam Realtime STT (mode=translate, language=${lang})`); }); sarvamWs.on('message', async (data) => { if (clientWs.readyState === 1 /* OPEN */) { try { const parsed = JSON.parse(data.toString()); if ((parsed.event === 'transcript.final' || parsed.event === 'transcript.partial') && parsed.text) { parsed.text = await ensureEnglishText(parsed.text); } clientWs.send(JSON.stringify(parsed)); } catch { clientWs.send(data.toString()); } } }); sarvamWs.on('error', (err) => { console.error('[WS Proxy] Sarvam WS error:', err.message); if (clientWs.readyState === 1 /* OPEN */) { clientWs.send(JSON.stringify({ event: 'error', message: err.message })); } }); sarvamWs.on('close', (code, reason) => { if (clientWs.readyState === 1 /* OPEN */) { clientWs.close(code, reason); } }); clientWs.on('message', (msg) => { if (sarvamWs && sarvamWs.readyState === 1 /* OPEN */) { try { const d = JSON.parse(msg.toString()); if (d.event === 'end' || d.event === 'stop') { sarvamWs.send(JSON.stringify({ event: 'end' })); } else { sarvamWs.send(msg.toString()); } } catch { sarvamWs.send(msg); } } }); clientWs.on('close', () => { if (sarvamWs) { try { sarvamWs.send(JSON.stringify({ event: 'end' })); } catch (e) {} setTimeout(() => { try { sarvamWs.close(); } catch (e) {} }, 300); } }); }); }