Files

1015 lines
43 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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' });
}
});
// ---------------------------------------------------------------------------
// REST: Full audio (base64 WAV) → Sarvam STT → transcript
// Splits into 25-second chunks to stay within 30s API limit.
// ---------------------------------------------------------------------------
app.post('/api/transcribe', async (req, res) => {
try {
const { audio_b64, language_code } = 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);
// Audio crop logic removed to process FULL audio
const lang = (language_code && language_code !== 'auto') ? language_code : 'unknown';
console.log("1. Initializing Sarvam Batch Job (Transcript + Diarization, Mode: Translate)...");
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: {
model: "saaras:v4",
mode: "translate",
with_diarization: true,
with_timestamps: true,
language_code: lang
}
})
});
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 = '';
// 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 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);
return { speakerId, textContent };
}));
const plainConversation = normalizedEntries.map(entry => `${entry.speakerId}: ${entry.textContent}`).join('\n');
const firstSpeakerId = normalizedEntries[0].speakerId;
// Step 2: Role Classifier using LLM
console.log("8. Running NLP Role Classifier (LLM Context Analysis)...");
let roleMap = {};
const classifierPrompt = `You are a medical NLP Role Classifier.
TASK: Analyze this transcript and classify each unique speaker as 'Doctor', 'Patient', 'Relative', or 'Nurse'.
METHOD: Use Keywords (e.g., medicine, checkup = Doctor), Context, and conversational patterns.
OUTPUT: Output ONLY a valid JSON object mapping exact speaker IDs to roles. Example: {"Speaker_1": "Doctor", "Speaker_2": "Patient"}.
TRANSCRIPT:
${plainConversation.slice(0, 3000)}`;
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: 300,
messages: [{ role: 'system', content: 'Output JSON only.' }, { role: 'user', content: classifierPrompt }]
})
});
const llmData = await llmRes.json();
const content = llmData?.choices?.[0]?.message?.content || "";
const match = content.match(/\{[\s\S]*\}/);
if (match) {
roleMap = JSON.parse(match[0]);
console.log("Role Classification Output:", roleMap);
}
} catch (err) {
console.error("Role Classifier failed, falling back to defaults:", err.message);
}
// Step 3: Apply Classifications for UI Output
finalTranscript = normalizedEntries.map(entry => {
// Use the LLM's classification or fallback to Patient
let role = roleMap[entry.speakerId] || 'Patient';
if (Object.keys(roleMap).length === 0 && entry.speakerId === firstSpeakerId) {
role = 'Doctor'; // hardcoded fallback if LLM completely fails
}
return `[${entry.speakerId} | ${role}] ${entry.textContent}`;
}).join('\n\n');
console.log("Sarvam Native Diarization + Role Classification complete!");
} else {
finalTranscript = await ensureEnglishText(resultData.transcript || "No transcript found.");
}
res.json({
transcript: finalTranscript,
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;
}
const 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);
}
});
});