Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7d008ed738 | ||
|
|
3c79b91fb1 | ||
|
|
7b4a4052a6 |
+145
-14
@@ -433,9 +433,7 @@
|
|||||||
// BUG: doctorSelect हा DOM ID नाही — 'doctorName' हा actual ID आहे
|
// BUG: doctorSelect हा DOM ID नाही — 'doctorName' हा actual ID आहे
|
||||||
const doctorEl = document.getElementById('doctorName');
|
const doctorEl = document.getElementById('doctorName');
|
||||||
const patientEl = document.getElementById('patientName');
|
const patientEl = document.getElementById('patientName');
|
||||||
utt.speaker = isDoc
|
utt.speaker = isDoc ? 'Doctor (डॉक्टर)' : 'Patient (रुग्ण / पेशंट)';
|
||||||
? (doctorEl ? doctorEl.value || 'Dr. Sharma' : 'Dr. Sharma').split('(')[0].trim()
|
|
||||||
: (patientEl ? patientEl.value.trim() || 'Patient' : 'Patient');
|
|
||||||
renderAllUtterances();
|
renderAllUtterances();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -526,6 +524,15 @@
|
|||||||
startSarvamLiveStream(mediaStream);
|
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() {
|
async function stopAndSummarize() {
|
||||||
if (!recording) return;
|
if (!recording) return;
|
||||||
recording = false;
|
recording = false;
|
||||||
@@ -553,6 +560,7 @@
|
|||||||
const wavBuffer = buildWav(pcmChunks, SAMPLE_RATE);
|
const wavBuffer = buildWav(pcmChunks, SAMPLE_RATE);
|
||||||
const audio_b64 = bufferToBase64(wavBuffer);
|
const audio_b64 = bufferToBase64(wavBuffer);
|
||||||
const lang = langSelect.value;
|
const lang = langSelect.value;
|
||||||
|
const num_speakers = getSelectedSpeakerCount();
|
||||||
|
|
||||||
// Setup playable audio blob for synchronized playback
|
// Setup playable audio blob for synchronized playback
|
||||||
setupAudioPlayer(wavBuffer, secondsElapsed);
|
setupAudioPlayer(wavBuffer, secondsElapsed);
|
||||||
@@ -560,7 +568,7 @@
|
|||||||
const resp = await fetch('/api/transcribe', {
|
const resp = await fetch('/api/transcribe', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
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();
|
const data = await resp.json();
|
||||||
@@ -606,11 +614,21 @@
|
|||||||
|
|
||||||
// Case 1: Use true acoustic timestamps returned directly by Sarvam Diarization
|
// Case 1: Use true acoustic timestamps returned directly by Sarvam Diarization
|
||||||
if (entries && Array.isArray(entries) && entries.length > 0) {
|
if (entries && Array.isArray(entries) && entries.length > 0) {
|
||||||
liveUtterances = entries.map((entry, idx) => {
|
// Defensive sort: Ensure strictly chronological sequence by spoken start time
|
||||||
|
const sortedEntries = [...entries].sort((a, b) => {
|
||||||
|
const aStart = typeof a.startSec === 'number' ? a.startSec : (parseFloat(a.startSec) || 0);
|
||||||
|
const bStart = typeof b.startSec === 'number' ? b.startSec : (parseFloat(b.startSec) || 0);
|
||||||
|
if (aStart !== bStart) return aStart - bStart;
|
||||||
|
const aEnd = typeof a.endSec === 'number' ? a.endSec : (parseFloat(a.endSec) || 0);
|
||||||
|
const bEnd = typeof b.endSec === 'number' ? b.endSec : (parseFloat(b.endSec) || 0);
|
||||||
|
return aEnd - bEnd;
|
||||||
|
});
|
||||||
|
|
||||||
|
liveUtterances = sortedEntries.map((entry, idx) => {
|
||||||
const role = (entry.role || 'patient').toLowerCase();
|
const role = (entry.role || 'patient').toLowerCase();
|
||||||
let speaker = doctorName;
|
let speaker = 'Doctor (डॉक्टर)';
|
||||||
if (role === 'patient') {
|
if (role === 'patient') {
|
||||||
speaker = patientName;
|
speaker = 'Patient (रुग्ण / पेशंट)';
|
||||||
} else if (role === 'relative') {
|
} else if (role === 'relative') {
|
||||||
speaker = 'Relative (नातेवाईक)';
|
speaker = 'Relative (नातेवाईक)';
|
||||||
} else if (role === 'nurse') {
|
} else if (role === 'nurse') {
|
||||||
@@ -661,11 +679,11 @@
|
|||||||
const isNurse = /^(?:\[Speaker_\d+\s*\|\s*Nurse\])|(?:(?:nurse|परिचारिका|नर्स)\s*[::\-])/i.test(segment);
|
const isNurse = /^(?:\[Speaker_\d+\s*\|\s*Nurse\])|(?:(?:nurse|परिचारिका|नर्स)\s*[::\-])/i.test(segment);
|
||||||
|
|
||||||
let role = 'doctor';
|
let role = 'doctor';
|
||||||
let speaker = doctorName;
|
let speaker = 'Doctor (डॉक्टर)';
|
||||||
|
|
||||||
if (isPatient) {
|
if (isPatient) {
|
||||||
role = 'patient';
|
role = 'patient';
|
||||||
speaker = patientName;
|
speaker = 'Patient (रुग्ण / पेशंट)';
|
||||||
} else if (isRelative) {
|
} else if (isRelative) {
|
||||||
role = 'relative';
|
role = 'relative';
|
||||||
speaker = 'Relative (नातेवाईक)';
|
speaker = 'Relative (नातेवाईक)';
|
||||||
@@ -712,9 +730,8 @@
|
|||||||
let html = '';
|
let html = '';
|
||||||
|
|
||||||
liveUtterances.forEach((utt) => {
|
liveUtterances.forEach((utt) => {
|
||||||
// Filter by speaker
|
// Filter by speaker (All, Doctor, Patient, Relative, Nurse)
|
||||||
if (activeFilter === 'doctor' && utt.role !== 'doctor') return;
|
if (activeFilter !== 'all' && utt.role !== activeFilter) return;
|
||||||
if (activeFilter === 'patient' && utt.role !== 'patient') return;
|
|
||||||
|
|
||||||
// Filter by search
|
// Filter by search
|
||||||
if (searchTerm && !utt.text.toLowerCase().includes(searchTerm) && !utt.speaker.toLowerCase().includes(searchTerm)) {
|
if (searchTerm && !utt.text.toLowerCase().includes(searchTerm) && !utt.speaker.toLowerCase().includes(searchTerm)) {
|
||||||
@@ -740,7 +757,10 @@
|
|||||||
<div class="utterance-avatar">${icon}</div>
|
<div class="utterance-avatar">${icon}</div>
|
||||||
<div class="utterance-content">
|
<div class="utterance-content">
|
||||||
<div class="utterance-meta">
|
<div class="utterance-meta">
|
||||||
<span class="utterance-speaker ${colorCls}">${escapeHtml(utt.speaker)}</span>
|
<button type="button" class="speaker-role-btn ${colorCls}" onclick="event.stopPropagation(); window.app.openRolePicker('${utt.id}', this, event)" title="Click to choose speaker role">
|
||||||
|
<span class="speaker-role-text">${escapeHtml(utt.speaker)}</span>
|
||||||
|
<span class="role-switch-icon" aria-hidden="true">▾</span>
|
||||||
|
</button>
|
||||||
<span class="utterance-time">[${fmtTime(utt.startSec)} - ${fmtTime(utt.endSec)}]</span>
|
<span class="utterance-time">[${fmtTime(utt.startSec)} - ${fmtTime(utt.endSec)}]</span>
|
||||||
<span class="utterance-lang-badge">English</span>
|
<span class="utterance-lang-badge">English</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -1050,11 +1070,12 @@
|
|||||||
// Call /api/transcribe which runs STT + NVIDIA NeMo Diarization on the server
|
// Call /api/transcribe which runs STT + NVIDIA NeMo Diarization on the server
|
||||||
const audio_b64 = bufferToBase64(fullWavBuffer);
|
const audio_b64 = bufferToBase64(fullWavBuffer);
|
||||||
const lang = langSelect.value;
|
const lang = langSelect.value;
|
||||||
|
const num_speakers = getSelectedSpeakerCount();
|
||||||
|
|
||||||
const transcribePromise = fetch('/api/transcribe', {
|
const transcribePromise = fetch('/api/transcribe', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
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 => {
|
}).then(async resp => {
|
||||||
const data = await resp.json();
|
const data = await resp.json();
|
||||||
if (!resp.ok) throw new Error(data.error || 'Server error');
|
if (!resp.ok) throw new Error(data.error || 'Server error');
|
||||||
@@ -1293,9 +1314,119 @@ ${Array.isArray(currentSummaryData.plan) ? currentSummaryData.plan.join('\n- ')
|
|||||||
};
|
};
|
||||||
const caseId = caseMap[type] || 'case-cardiology';
|
const caseId = caseMap[type] || 'case-cardiology';
|
||||||
this.loadSpecificCase(caseId);
|
this.loadSpecificCase(caseId);
|
||||||
|
},
|
||||||
|
cycleRole: function(uttId) {
|
||||||
|
const utt = liveUtterances.find(u => u.id === uttId);
|
||||||
|
if (!utt) return;
|
||||||
|
|
||||||
|
const roleOrder = ['doctor', 'patient', 'relative', 'nurse'];
|
||||||
|
const currentIdx = roleOrder.indexOf((utt.role || 'patient').toLowerCase());
|
||||||
|
const nextIdx = (currentIdx + 1) % roleOrder.length;
|
||||||
|
this.setRole(uttId, roleOrder[nextIdx]);
|
||||||
|
},
|
||||||
|
openRolePicker: function(uttId, btnEl, event) {
|
||||||
|
if (event) event.stopPropagation();
|
||||||
|
|
||||||
|
if (window._activeRolePicker && window._activeRolePicker._btnEl === btnEl) {
|
||||||
|
window.app.closeRolePicker();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
window.app.closeRolePicker();
|
||||||
|
|
||||||
|
const utt = liveUtterances.find(u => u.id === uttId);
|
||||||
|
if (!utt) return;
|
||||||
|
|
||||||
|
const roles = [
|
||||||
|
{ key: 'doctor', label: 'Doctor (डॉक्टर)', icon: '🩺', cls: 'opt-doctor' },
|
||||||
|
{ key: 'patient', label: 'Patient (रुग्ण / पेशंट)', icon: '🧑', cls: 'opt-patient' },
|
||||||
|
{ key: 'relative', label: 'Relative (नातेवाईक)', icon: '👨👩👧', cls: 'opt-relative' },
|
||||||
|
{ key: 'nurse', label: 'Nurse (परिचारिका)', icon: '👩⚕️', cls: 'opt-nurse' }
|
||||||
|
];
|
||||||
|
|
||||||
|
const popover = document.createElement('div');
|
||||||
|
popover.className = 'role-picker-popover';
|
||||||
|
popover._btnEl = btnEl;
|
||||||
|
|
||||||
|
const currentRole = (utt.role || 'patient').toLowerCase();
|
||||||
|
|
||||||
|
popover.innerHTML = `
|
||||||
|
<div class="role-picker-header">Assign Speaker</div>
|
||||||
|
${roles.map(r => `
|
||||||
|
<button type="button" class="role-picker-option ${r.cls} ${currentRole === r.key ? 'active' : ''}" data-role="${r.key}">
|
||||||
|
<span class="opt-icon">${r.icon}</span>
|
||||||
|
<span class="opt-label">${r.label}</span>
|
||||||
|
<span class="opt-check">${currentRole === r.key ? '✓' : ''}</span>
|
||||||
|
</button>
|
||||||
|
`).join('')}
|
||||||
|
`;
|
||||||
|
|
||||||
|
popover.querySelectorAll('.role-picker-option').forEach(opt => {
|
||||||
|
opt.addEventListener('click', (e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
const selectedRole = opt.getAttribute('data-role');
|
||||||
|
window.app.setRole(uttId, selectedRole);
|
||||||
|
window.app.closeRolePicker();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
document.body.appendChild(popover);
|
||||||
|
window._activeRolePicker = popover;
|
||||||
|
|
||||||
|
const rect = btnEl.getBoundingClientRect();
|
||||||
|
const popoverHeight = 185;
|
||||||
|
let top = rect.bottom + window.scrollY + 5;
|
||||||
|
let left = rect.left + window.scrollX;
|
||||||
|
|
||||||
|
if (left + 210 > window.innerWidth) {
|
||||||
|
left = Math.max(10, window.innerWidth - 220);
|
||||||
|
}
|
||||||
|
if (rect.bottom + popoverHeight > window.innerHeight && rect.top > popoverHeight) {
|
||||||
|
top = rect.top + window.scrollY - popoverHeight - 5;
|
||||||
|
}
|
||||||
|
|
||||||
|
popover.style.top = `${top}px`;
|
||||||
|
popover.style.left = `${left}px`;
|
||||||
|
},
|
||||||
|
closeRolePicker: function() {
|
||||||
|
if (window._activeRolePicker) {
|
||||||
|
window._activeRolePicker.remove();
|
||||||
|
window._activeRolePicker = null;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
setRole: function(uttId, newRole) {
|
||||||
|
const utt = liveUtterances.find(u => u.id === uttId);
|
||||||
|
if (!utt) return;
|
||||||
|
|
||||||
|
utt.role = newRole;
|
||||||
|
if (newRole === 'doctor') {
|
||||||
|
utt.speaker = 'Doctor (डॉक्टर)';
|
||||||
|
} else if (newRole === 'patient') {
|
||||||
|
utt.speaker = 'Patient (रुग्ण / पेशंट)';
|
||||||
|
} else if (newRole === 'relative') {
|
||||||
|
utt.speaker = 'Relative (नातेवाईक)';
|
||||||
|
} else if (newRole === 'nurse') {
|
||||||
|
utt.speaker = 'Nurse (परिचारिका)';
|
||||||
|
}
|
||||||
|
|
||||||
|
currentTranscript = liveUtterances.map(u => `[${u.speaker}] ${u.text}`).join('\n\n');
|
||||||
|
renderAllUtterances();
|
||||||
|
showToast(`Speaker assigned: ${utt.speaker}`);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Close role picker popover on outside click or Esc
|
||||||
|
document.addEventListener('click', (e) => {
|
||||||
|
if (window._activeRolePicker && !window._activeRolePicker.contains(e.target)) {
|
||||||
|
window.app.closeRolePicker();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
document.addEventListener('keydown', (e) => {
|
||||||
|
if (e.key === 'Escape') {
|
||||||
|
window.app.closeRolePicker();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
})();
|
})();
|
||||||
|
|
||||||
// End of application logic.
|
// End of application logic.
|
||||||
|
|||||||
@@ -196,6 +196,21 @@
|
|||||||
<input type="text" id="consultationDate" value="09-09-2026">
|
<input type="text" id="consultationDate" value="09-09-2026">
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Speaker Diarization Mode -->
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="speakerModeSelect" class="form-label">Speakers / Diarization</label>
|
||||||
|
<div class="input-icon-box select-box">
|
||||||
|
<span class="input-icon">👥</span>
|
||||||
|
<select id="speakerModeSelect">
|
||||||
|
<option value="auto" selected>Auto-Detect (2+ Speakers)</option>
|
||||||
|
<option value="2">2 Speakers (Doctor & Patient)</option>
|
||||||
|
<option value="3">3 Speakers (Doctor, Patient, Relative)</option>
|
||||||
|
<option value="4">4 Speakers (Doctor, Patient, Relative, Nurse)</option>
|
||||||
|
</select>
|
||||||
|
<span class="select-chevron">▾</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -288,6 +303,8 @@
|
|||||||
<button class="filter-pill active" data-filter="all">All Dialogue</button>
|
<button class="filter-pill active" data-filter="all">All Dialogue</button>
|
||||||
<button class="filter-pill" data-filter="doctor">🧑⚕️ Doctor</button>
|
<button class="filter-pill" data-filter="doctor">🧑⚕️ Doctor</button>
|
||||||
<button class="filter-pill" data-filter="patient">🧑 Patient</button>
|
<button class="filter-pill" data-filter="patient">🧑 Patient</button>
|
||||||
|
<button class="filter-pill" data-filter="relative">👨👩👧 Relative</button>
|
||||||
|
<button class="filter-pill" data-filter="nurse">👩⚕️ Nurse</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Full Transcript Scroll Viewport -->
|
<!-- Full Transcript Scroll Viewport -->
|
||||||
|
|||||||
+132
-8
@@ -525,7 +525,7 @@ html, body {
|
|||||||
══════════════════════════════════════════════════════════════════ */
|
══════════════════════════════════════════════════════════════════ */
|
||||||
.details-form-grid {
|
.details-form-grid {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: repeat(4, 1fr);
|
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
||||||
gap: 16px;
|
gap: 16px;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -946,11 +946,16 @@ html, body {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.filter-pill.active {
|
.filter-pill.active {
|
||||||
background: #2563eb;
|
background: #0f172a;
|
||||||
color: #ffffff;
|
color: #ffffff;
|
||||||
border-color: #2563eb;
|
border-color: #0f172a;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.filter-pill[data-filter="doctor"].active { background: #0284c7; border-color: #0284c7; }
|
||||||
|
.filter-pill[data-filter="patient"].active { background: #059669; border-color: #059669; }
|
||||||
|
.filter-pill[data-filter="relative"].active { background: #e11d48; border-color: #e11d48; }
|
||||||
|
.filter-pill[data-filter="nurse"].active { background: #d97706; border-color: #d97706; }
|
||||||
|
|
||||||
/* Transcript Scroll Viewport */
|
/* Transcript Scroll Viewport */
|
||||||
.transcript-viewport {
|
.transcript-viewport {
|
||||||
min-height: 180px;
|
min-height: 180px;
|
||||||
@@ -1015,7 +1020,7 @@ html, body {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.utterance-item.doctor {
|
.utterance-item.doctor {
|
||||||
border-left: 4px solid #2563eb;
|
border-left: 4px solid #0284c7;
|
||||||
}
|
}
|
||||||
|
|
||||||
.utterance-item.patient {
|
.utterance-item.patient {
|
||||||
@@ -1023,11 +1028,11 @@ html, body {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.utterance-item.relative {
|
.utterance-item.relative {
|
||||||
border-left: 4px solid #8b5cf6;
|
border-left: 4px solid #e11d48;
|
||||||
}
|
}
|
||||||
|
|
||||||
.utterance-item.nurse {
|
.utterance-item.nurse {
|
||||||
border-left: 4px solid #f59e0b;
|
border-left: 4px solid #d97706;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Active Playing Karaoke Glow */
|
/* Active Playing Karaoke Glow */
|
||||||
@@ -1060,11 +1065,130 @@ html, body {
|
|||||||
color: #0f172a;
|
color: #0f172a;
|
||||||
}
|
}
|
||||||
|
|
||||||
.utterance-speaker.doctor-color { color: #2563eb; }
|
.utterance-speaker.doctor-color { color: #0284c7; }
|
||||||
.utterance-speaker.patient-color { color: #059669; }
|
.utterance-speaker.patient-color { color: #059669; }
|
||||||
.utterance-speaker.relative-color { color: #7c3aed; }
|
.utterance-speaker.relative-color { color: #e11d48; }
|
||||||
.utterance-speaker.nurse-color { color: #d97706; }
|
.utterance-speaker.nurse-color { color: #d97706; }
|
||||||
|
|
||||||
|
/* 1-Click Interactive Speaker Role Toggle Badge */
|
||||||
|
.speaker-role-btn {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
background: #f8fafc;
|
||||||
|
border: 1px solid #e2e8f0;
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 3px 8px;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 700;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.18s ease;
|
||||||
|
user-select: none;
|
||||||
|
font-family: inherit;
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
.speaker-role-btn:hover {
|
||||||
|
background: #ffffff;
|
||||||
|
border-color: #cbd5e1;
|
||||||
|
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
|
||||||
|
transform: translateY(-1px);
|
||||||
|
}
|
||||||
|
.speaker-role-btn.doctor-color { color: #0284c7; border-color: #bae6fd; background: #f0f9ff; }
|
||||||
|
.speaker-role-btn.patient-color { color: #059669; border-color: #a7f3d0; background: #ecfdf5; }
|
||||||
|
.speaker-role-btn.relative-color { color: #e11d48; border-color: #fecdd3; background: #fff1f2; }
|
||||||
|
.speaker-role-btn.nurse-color { color: #d97706; border-color: #fde68a; background: #fffbeb; }
|
||||||
|
|
||||||
|
.speaker-role-btn .role-switch-icon {
|
||||||
|
font-size: 11px;
|
||||||
|
opacity: 0.65;
|
||||||
|
transition: transform 0.2s ease, opacity 0.2s ease;
|
||||||
|
}
|
||||||
|
.speaker-role-btn:hover .role-switch-icon {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 1-Click Floating Role Picker Menu */
|
||||||
|
.role-picker-popover {
|
||||||
|
position: absolute;
|
||||||
|
z-index: 1000;
|
||||||
|
background: #ffffff;
|
||||||
|
border: 1px solid #e2e8f0;
|
||||||
|
border-radius: 10px;
|
||||||
|
box-shadow: 0 12px 28px -4px rgba(15, 23, 42, 0.2), 0 6px 12px -4px rgba(15, 23, 42, 0.1);
|
||||||
|
padding: 6px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 3px;
|
||||||
|
min-width: 195px;
|
||||||
|
animation: popoverFadeIn 0.15s cubic-bezier(0.16, 1, 0.3, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes popoverFadeIn {
|
||||||
|
from { opacity: 0; transform: translateY(-5px) scale(0.97); }
|
||||||
|
to { opacity: 1; transform: translateY(0) scale(1); }
|
||||||
|
}
|
||||||
|
|
||||||
|
.role-picker-header {
|
||||||
|
font-size: 10.5px;
|
||||||
|
font-weight: 700;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.5px;
|
||||||
|
color: #94a3b8;
|
||||||
|
padding: 4px 8px 3px 8px;
|
||||||
|
border-bottom: 1px solid #f1f5f9;
|
||||||
|
margin-bottom: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.role-picker-option {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
width: 100%;
|
||||||
|
padding: 7px 10px;
|
||||||
|
border-radius: 6px;
|
||||||
|
background: transparent;
|
||||||
|
border: none;
|
||||||
|
font-size: 12.5px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: #1e293b;
|
||||||
|
cursor: pointer;
|
||||||
|
text-align: left;
|
||||||
|
transition: all 0.14s ease;
|
||||||
|
font-family: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
.role-picker-option:hover {
|
||||||
|
background: #f1f5f9;
|
||||||
|
}
|
||||||
|
|
||||||
|
.role-picker-option.active {
|
||||||
|
background: #f8fafc;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
.role-picker-option.opt-doctor:hover { background: #f0f9ff; color: #0284c7; }
|
||||||
|
.role-picker-option.opt-patient:hover { background: #ecfdf5; color: #059669; }
|
||||||
|
.role-picker-option.opt-relative:hover { background: #fff1f2; color: #e11d48; }
|
||||||
|
.role-picker-option.opt-nurse:hover { background: #fffbeb; color: #d97706; }
|
||||||
|
|
||||||
|
.role-picker-option .opt-icon {
|
||||||
|
font-size: 15px;
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.role-picker-option .opt-label {
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.role-picker-option .opt-check {
|
||||||
|
font-size: 13px;
|
||||||
|
color: #059669;
|
||||||
|
opacity: 0;
|
||||||
|
}
|
||||||
|
.role-picker-option.active .opt-check {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
|
||||||
.utterance-time {
|
.utterance-time {
|
||||||
font-size: 11px;
|
font-size: 11px;
|
||||||
font-family: var(--font-mono);
|
font-family: var(--font-mono);
|
||||||
|
|||||||
@@ -615,9 +615,446 @@ ${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 & 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
|
// 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) => {
|
app.post('/api/transcribe', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
@@ -629,14 +1066,24 @@ app.post('/api/transcribe', async (req, res) => {
|
|||||||
let { dataOffset, dataLength, sampleRate, numChannels, bitsPerSample } = parseWavHeader(wavBuffer);
|
let { dataOffset, dataLength, sampleRate, numChannels, bitsPerSample } = parseWavHeader(wavBuffer);
|
||||||
const bytesPerSec = sampleRate * numChannels * (bitsPerSample / 8);
|
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 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)
|
? 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', {
|
const initRes = await fetch('https://api.sarvam.ai/speech-to-text/job/v1', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
@@ -644,14 +1091,7 @@ app.post('/api/transcribe', async (req, res) => {
|
|||||||
'Content-Type': 'application/json'
|
'Content-Type': 'application/json'
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
job_parameters: {
|
job_parameters: jobParams
|
||||||
model: "saaras:v4",
|
|
||||||
mode: "translate",
|
|
||||||
with_diarization: true,
|
|
||||||
with_timestamps: true,
|
|
||||||
language_code: lang,
|
|
||||||
num_speakers: targetSpeakers
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
const initData = await initRes.json();
|
const initData = await initRes.json();
|
||||||
@@ -760,61 +1200,40 @@ app.post('/api/transcribe', async (req, res) => {
|
|||||||
};
|
};
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const plainConversation = normalizedEntries.map(entry => `${entry.speakerId}: ${entry.textContent}`).join('\n');
|
// Strict Chronological Sort: Order utterances strictly by spoken timeline
|
||||||
const firstSpeakerId = normalizedEntries[0].speakerId;
|
normalizedEntries.sort((a, b) => {
|
||||||
|
if (a.startSec !== b.startSec) return a.startSec - b.startSec;
|
||||||
|
return a.endSec - b.endSec;
|
||||||
|
});
|
||||||
|
|
||||||
// Step 2: Role Classifier using LLM
|
// Step 2: Role Classifier using Multi-Provider LLM Context Analysis + Clinical Rule Guardrail
|
||||||
console.log("8. Running NLP Role Classifier (LLM Context Analysis)...");
|
console.log("8. Running Multi-Speaker Diarization Role Classifier & Integrity Guardrails...");
|
||||||
let roleMap = {};
|
const uniqueSpeakerIds = Array.from(new Set(normalizedEntries.map(e => e.speakerId)));
|
||||||
const classifierPrompt = `You are a medical NLP Role Classifier.
|
const roleMap = await classifyConversationRoles(normalizedEntries, uniqueSpeakerIds);
|
||||||
TASK: Analyze this transcript and classify each unique speaker as 'Doctor', 'Patient', 'Relative', or 'Nurse'.
|
console.log("Final Speaker Role Mapping:", roleMap);
|
||||||
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:
|
// Step 3: Apply Intent-Based Turn Alignment (resolves acoustic cluster bleed & natural speech misattribution)
|
||||||
${plainConversation.slice(0, 3000)}`;
|
console.log("9. Refining Turn Roles using Conversational Intent Analysis...");
|
||||||
|
const turnRoles = await refineTurnsWithIntent(normalizedEntries, roleMap);
|
||||||
|
|
||||||
try {
|
structuredEntries = normalizedEntries.map((entry, idx) => {
|
||||||
const llmRes = await fetch('https://api.sarvam.ai/v1/chat/completions', {
|
const finalRole = turnRoles[idx] || roleMap[entry.speakerId] || 'Patient';
|
||||||
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
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
speakerId: entry.speakerId,
|
speakerId: entry.speakerId,
|
||||||
role: role,
|
role: finalRole,
|
||||||
text: entry.textContent,
|
text: entry.textContent,
|
||||||
startSec: entry.startSec,
|
startSec: entry.startSec,
|
||||||
endSec: entry.endSec
|
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 => {
|
finalTranscript = structuredEntries.map(entry => {
|
||||||
return `[${entry.speakerId} | ${entry.role}] ${entry.text}`;
|
return `[${entry.speakerId} | ${entry.role}] ${entry.text}`;
|
||||||
}).join('\n\n');
|
}).join('\n\n');
|
||||||
@@ -950,18 +1369,27 @@ function buildWav(pcmData, sampleRate, numChannels, bitsPerSample) {
|
|||||||
return buf;
|
return buf;
|
||||||
}
|
}
|
||||||
|
|
||||||
const server = app.listen(PORT, () => {
|
module.exports = {
|
||||||
console.log(`✅ Server चालू आहे: http://localhost:${PORT}`);
|
app,
|
||||||
});
|
classifyConversationRoles,
|
||||||
server.setTimeout(300000);
|
classifyRolesWithRules,
|
||||||
server.keepAliveTimeout = 300000;
|
refineTurnRole,
|
||||||
server.headersTimeout = 310000;
|
refineTurnsWithIntent
|
||||||
|
};
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
let server;
|
||||||
// WebSocket Proxy: Browser <-> Sarvam Realtime STT (Mode: Translate)
|
if (require.main === module) {
|
||||||
// Streams 16kHz mono PCM to Sarvam and relays English partial/final transcripts
|
server = app.listen(PORT, () => {
|
||||||
// ---------------------------------------------------------------------------
|
console.log(`✅ Server चालू आहे: http://localhost:${PORT}`);
|
||||||
const wss = new WebSocketServer({ server, path: '/ws/transcribe' });
|
});
|
||||||
|
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) => {
|
wss.on('connection', (clientWs, req) => {
|
||||||
if (!SARVAM_API_KEY) {
|
if (!SARVAM_API_KEY) {
|
||||||
@@ -1041,3 +1469,4 @@ wss.on('connection', (clientWs, req) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user