From 3c79b91fb15d82178fc9249aa1f1866d3f9d7d6d Mon Sep 17 00:00:00 2001
From: Ayush <155418492+Ayushshah1109@users.noreply.github.com>
Date: Tue, 17 Nov 2026 20:31:57 +0530
Subject: [PATCH] feat(diarization): Sub-Phase 3B - multi-speaker
auto-detection and clinical role guardrails
---
public/app.js | 15 +-
public/index.html | 15 ++
public/style.css | 2 +-
server.js | 451 +++++++++++++++++++++++++++++++++++++++-------
4 files changed, 411 insertions(+), 72 deletions(-)
diff --git a/public/app.js b/public/app.js
index 8f096dc..d5f742b 100644
--- a/public/app.js
+++ b/public/app.js
@@ -524,6 +524,15 @@
startSarvamLiveStream(mediaStream);
}
+ function getSelectedSpeakerCount() {
+ const select = document.getElementById('speakerModeSelect');
+ if (!select) return null;
+ const val = select.value;
+ if (!val || val === 'auto') return null;
+ const num = parseInt(val, 10);
+ return isNaN(num) || num < 2 ? null : num;
+ }
+
async function stopAndSummarize() {
if (!recording) return;
recording = false;
@@ -551,6 +560,7 @@
const wavBuffer = buildWav(pcmChunks, SAMPLE_RATE);
const audio_b64 = bufferToBase64(wavBuffer);
const lang = langSelect.value;
+ const num_speakers = getSelectedSpeakerCount();
// Setup playable audio blob for synchronized playback
setupAudioPlayer(wavBuffer, secondsElapsed);
@@ -558,7 +568,7 @@
const resp = await fetch('/api/transcribe', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ audio_b64, language_code: lang, num_speakers: 2 })
+ body: JSON.stringify({ audio_b64, language_code: lang, num_speakers })
});
const data = await resp.json();
@@ -1057,11 +1067,12 @@
// Call /api/transcribe which runs STT + NVIDIA NeMo Diarization on the server
const audio_b64 = bufferToBase64(fullWavBuffer);
const lang = langSelect.value;
+ const num_speakers = getSelectedSpeakerCount();
const transcribePromise = fetch('/api/transcribe', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ audio_b64, language_code: lang, num_speakers: 2 })
+ body: JSON.stringify({ audio_b64, language_code: lang, num_speakers })
}).then(async resp => {
const data = await resp.json();
if (!resp.ok) throw new Error(data.error || 'Server error');
diff --git a/public/index.html b/public/index.html
index 5273547..2f3c246 100644
--- a/public/index.html
+++ b/public/index.html
@@ -196,6 +196,21 @@
+
+
+
diff --git a/public/style.css b/public/style.css
index 9b9e9a2..1c9d9ad 100644
--- a/public/style.css
+++ b/public/style.css
@@ -525,7 +525,7 @@ html, body {
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ */
.details-form-grid {
display: grid;
- grid-template-columns: repeat(4, 1fr);
+ grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
gap: 16px;
}
diff --git a/server.js b/server.js
index f757f12..af8d1c0 100644
--- a/server.js
+++ b/server.js
@@ -615,9 +615,344 @@ ${finalTranscript.slice(0, 4000)}`;
}
});
+// ---------------------------------------------------------------------------
+// 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:
+- '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': Speaks on behalf of the patient (e.g., 'my father has fever', 'she cannot sleep', 'he is not eating'), accompanies the patient, or asks caretaking questions.
+- 'Nurse': Reports vital signs (BP, pulse, SPO2, temperature), assists doctor or coordinates patient logistics.
+
+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;
+}
+
// ---------------------------------------------------------------------------
// 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 {
@@ -629,14 +964,24 @@ app.post('/api/transcribe', async (req, res) => {
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';
- const targetSpeakers = (num_speakers && parseInt(num_speakers, 10) > 0)
+ const parsedSpeakers = (num_speakers && parseInt(num_speakers, 10) > 0)
? parseInt(num_speakers, 10)
- : 2;
+ : 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;
+ }
- console.log(`1. Initializing Sarvam Batch Job (Transcript + Diarization, Mode: Translate, Num Speakers: ${targetSpeakers})...`);
const initRes = await fetch('https://api.sarvam.ai/speech-to-text/job/v1', {
method: 'POST',
headers: {
@@ -644,14 +989,7 @@ app.post('/api/transcribe', async (req, res) => {
'Content-Type': 'application/json'
},
body: JSON.stringify({
- job_parameters: {
- model: "saaras:v4",
- mode: "translate",
- with_diarization: true,
- with_timestamps: true,
- language_code: lang,
- num_speakers: targetSpeakers
- }
+ job_parameters: jobParams
})
});
const initData = await initRes.json();
@@ -766,55 +1104,21 @@ app.post('/api/transcribe', async (req, res) => {
return a.endSec - b.endSec;
});
- const plainConversation = normalizedEntries.map(entry => `${entry.speakerId}: ${entry.textContent}`).join('\n');
- const firstSpeakerId = normalizedEntries[0]?.speakerId || 'Speaker_0';
+ // 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 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 & Structured Entries
+ // Step 3: Apply Classifications for UI Output & Structured Entries with Turn-Level Semantic Refinement
structuredEntries = normalizedEntries.map(entry => {
- let role = roleMap[entry.speakerId] || 'Patient';
- if (Object.keys(roleMap).length === 0 && entry.speakerId === firstSpeakerId) {
- role = 'Doctor'; // hardcoded fallback if LLM completely fails
- }
+ const baseRole = roleMap[entry.speakerId] || 'Patient';
+ // Apply turn-level semantic guardrail to catch symptom/medication bleed
+ const finalRole = refineTurnRole(baseRole, entry.textContent);
return {
speakerId: entry.speakerId,
- role: role,
+ role: finalRole,
text: entry.textContent,
startSec: entry.startSec,
endSec: entry.endSec
@@ -962,18 +1266,26 @@ function buildWav(pcmData, sampleRate, numChannels, bitsPerSample) {
return buf;
}
-const server = app.listen(PORT, () => {
- console.log(`โ
Server เคเคพเคฒเฅ เคเคนเฅ: http://localhost:${PORT}`);
-});
-server.setTimeout(300000);
-server.keepAliveTimeout = 300000;
-server.headersTimeout = 310000;
+module.exports = {
+ app,
+ classifyConversationRoles,
+ classifyRolesWithRules,
+ refineTurnRole
+};
-// ---------------------------------------------------------------------------
-// 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' });
+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) {
@@ -1053,3 +1365,4 @@ wss.on('connection', (clientWs, req) => {
}
});
});
+}