/** * AI Clinical Assistant — Doctor-Patient Conversation * Real-time Speech-to-Text, Audio Synchronization, and Clinical LLM Pipeline */ (function () { 'use strict'; // ── DOM References ──────────────────────────────────────────────────────── const startBtn = document.getElementById('startBtn'); const stopBtn = document.getElementById('stopBtn'); const uploadAudioBtn = document.getElementById('uploadAudioBtn'); const audioFileInput = document.getElementById('audioFileInput'); const demoBtn = document.getElementById('demoBtn'); const timerEl = document.getElementById('timer'); const recSubStatus = document.getElementById('recSubStatus'); const recStatusText = document.getElementById('recStatusText'); const recError = document.getElementById('recError'); const recordingCard = document.querySelector('.recording-card'); // Transcript Elements const transcriptBody = document.getElementById('transcriptBody'); const copyTranscriptBtn = document.getElementById('copyTranscriptBtn'); const clearTranscriptBtn = document.getElementById('clearTranscriptBtn'); const transcriptSearch = document.getElementById('transcriptSearch'); const liveRealtimeBadge = document.getElementById('liveRealtimeBadge'); const filterPills = document.querySelectorAll('.filter-pill'); // Audio Player Sync Elements const audioPlaybackBar = document.getElementById('audioPlaybackBar'); const playAudioBtn = document.getElementById('playAudioBtn'); const playIcon = document.getElementById('playIcon'); const audioScrubber = document.getElementById('audioScrubber'); const audioCurrentTime = document.getElementById('audioCurrentTime'); const audioTotalDuration = document.getElementById('audioTotalDuration'); // Summary Elements const summaryBody = document.getElementById('summaryBody'); const sumChiefComplaint = document.getElementById('sumChiefComplaint'); const sumSymptoms = document.getElementById('sumSymptoms'); const sumAssessment = document.getElementById('sumAssessment'); const sumHistory = document.getElementById('sumHistory'); const sumPlan = document.getElementById('sumPlan'); const copySummaryBtn = document.getElementById('copySummaryBtn'); const printSummaryBtn = document.getElementById('printSummaryBtn'); const exportJsonBtn = document.getElementById('exportJsonBtn'); // Form Inputs const langSelect = document.getElementById('langSelect'); const patientInput = document.getElementById('patientName'); const patientIdInput = document.getElementById('patientId'); const doctorSelect = document.getElementById('doctorName'); const dateInput = document.getElementById('consultationDate'); // Canvas & Toast const waveformCanvas = document.getElementById('waveformCanvas'); const canvasCtx = waveformCanvas ? waveformCanvas.getContext('2d') : null; const toastBox = document.getElementById('toastBox'); // Navigation & Modals const navItems = document.querySelectorAll('.sidebar-nav .nav-item'); const tabViews = document.querySelectorAll('.tab-view'); const pageHeading = document.getElementById('pageHeading'); const menuToggle = document.getElementById('menuToggle'); const sidebar = document.getElementById('sidebar'); const patientModal = document.getElementById('patientModal'); const openAddPatientBtn = document.getElementById('openAddPatientBtn'); const btnAddNewPatientTab = document.getElementById('btnAddNewPatientTab'); const closePatientModal = document.getElementById('closePatientModal'); const cancelPatientModal = document.getElementById('cancelPatientModal'); const savePatientBtn = document.getElementById('savePatientBtn'); const newPatientName = document.getElementById('newPatientName'); // ── Audio Constants & Pipeline State ────────────────────────────────────── const SAMPLE_RATE = 16000; const BUFFER_SIZE = 4096; let audioCtx = null; let sourceNode = null; let processorNode = null; let analyserNode = null; let mediaStream = null; let animationId = null; let recording = false; let timerInterval = null; let secondsElapsed = 0; let pcmChunks = []; // Real-time Recognition & Sync State let speechRecognizer = null; let liveUtterances = []; // Array of { id, speaker, role, text, startSec, endSec } let currentTranscript = ''; let currentSummaryData = null; // Audio Playback Player State let audioPlayerAudio = null; // HTMLAudioElement or Synthesized Audio let playerInterval = null; let activeFilter = 'all'; // Initialize Today's Date if (dateInput) { const today = new Date(); const dd = String(today.getDate()).padStart(2, '0'); const mm = String(today.getMonth() + 1).padStart(2, '0'); const yyyy = today.getFullYear(); dateInput.value = `${dd}-${mm}-${yyyy}`; } // ── Helper Utilities ────────────────────────────────────────────────────── function showToast(msg) { if (!toastBox) return; toastBox.textContent = msg; toastBox.classList.add('show'); setTimeout(() => { toastBox.classList.remove('show'); }, 3000); } function showError(msg) { if (!recError) return; recError.textContent = msg; recError.style.display = 'block'; } function clearError() { if (!recError) return; recError.textContent = ''; recError.style.display = 'none'; } function fmtTime(s) { const secNum = Math.max(0, Math.floor(s || 0)); const m = Math.floor(secNum / 60).toString().padStart(2, '0'); const sec = (secNum % 60).toString().padStart(2, '0'); return `${m}:${sec}`; } function escapeHtml(str) { const d = document.createElement('div'); d.innerText = str || ''; return d.innerHTML; } // ── Audio Waveform Visualizer ───────────────────────────────────────────── function drawVisualizer() { if (!canvasCtx || !analyserNode) return; const bufferLength = analyserNode.frequencyBinCount; const dataArray = new Uint8Array(bufferLength); function renderFrame() { if (!recording) { canvasCtx.clearRect(0, 0, waveformCanvas.width, waveformCanvas.height); canvasCtx.strokeStyle = '#cbd5e1'; canvasCtx.lineWidth = 2; canvasCtx.beginPath(); canvasCtx.moveTo(0, waveformCanvas.height / 2); canvasCtx.lineTo(waveformCanvas.width, waveformCanvas.height / 2); canvasCtx.stroke(); return; } animationId = requestAnimationFrame(renderFrame); analyserNode.getByteFrequencyData(dataArray); canvasCtx.clearRect(0, 0, waveformCanvas.width, waveformCanvas.height); const barWidth = (waveformCanvas.width / 32) - 3; let x = 2; for (let i = 0; i < 32; i++) { const value = dataArray[i * 2] || 0; const percent = value / 255; const barHeight = Math.max(4, percent * waveformCanvas.height); const y = (waveformCanvas.height - barHeight) / 2; const gradient = canvasCtx.createLinearGradient(0, y, 0, y + barHeight); gradient.addColorStop(0, '#2563eb'); gradient.addColorStop(1, '#10b981'); canvasCtx.fillStyle = gradient; canvasCtx.beginPath(); canvasCtx.roundRect(x, y, barWidth, barHeight, 3); canvasCtx.fill(); x += barWidth + 3; } } renderFrame(); } // ── WAV Builder & Downsampler (16kHz PCM linear16 mono) ──────────────────── async function downsampleNative(audioBuffer, targetSampleRate) { // Native, instantaneous resampling using OfflineAudioContext const length = Math.ceil(audioBuffer.duration * targetSampleRate); const offlineCtx = new (window.OfflineAudioContext || window.webkitOfflineAudioContext)( 1, length, targetSampleRate ); const source = offlineCtx.createBufferSource(); source.buffer = audioBuffer; source.connect(offlineCtx.destination); source.start(0); const renderedBuffer = await offlineCtx.startRendering(); return renderedBuffer.getChannelData(0); } function downsample(input, inputRate, outputRate) { if (inputRate === outputRate) return input; const ratio = inputRate / outputRate; const newLength = Math.round(input.length / ratio); const result = new Float32Array(newLength); for (let i = 0; i < newLength; i++) { const start = Math.round(i * ratio); const end = Math.round((i + 1) * ratio); let sum = 0, cnt = 0; for (let j = start; j < end && j < input.length; j++) { sum += input[j]; cnt++; } result[i] = cnt > 0 ? sum / cnt : 0; } return result; } function buildWav(float32Chunks, sampleRate) { const totalLen = float32Chunks.reduce((s, c) => s + c.length, 0); const merged = new Float32Array(totalLen); let offset = 0; for (const chunk of float32Chunks) { merged.set(chunk, offset); offset += chunk.length; } const pcm16 = new Int16Array(merged.length); for (let i = 0; i < merged.length; i++) { const s = Math.max(-1, Math.min(1, merged[i])); pcm16[i] = s < 0 ? s * 0x8000 : s * 0x7FFF; } const dataBytes = pcm16.length * 2; const buffer = new ArrayBuffer(44 + dataBytes); const view = new DataView(buffer); const numCh = 1; const bps = 16; const byteRate = sampleRate * numCh * bps / 8; const blockAlign = numCh * bps / 8; function writeStr(off, str) { for (let i = 0; i < str.length; i++) view.setUint8(off + i, str.charCodeAt(i)); } writeStr(0, 'RIFF'); view.setUint32(4, 36 + dataBytes, true); writeStr(8, 'WAVE'); writeStr(12, 'fmt '); view.setUint32(16, 16, true); view.setUint16(20, 1, true); view.setUint16(22, numCh, true); view.setUint32(24, sampleRate, true); view.setUint32(28, byteRate, true); view.setUint16(32, blockAlign, true); view.setUint16(34, bps, true); writeStr(36, 'data'); view.setUint32(40, dataBytes, true); const pcmBytes = new Uint8Array(buffer, 44); const pcmView = new Uint8Array(pcm16.buffer); pcmBytes.set(pcmView); return buffer; } function bufferToBase64(ab) { const bytes = new Uint8Array(ab); let bin = ''; const CHUNK = 0x8000; for (let i = 0; i < bytes.length; i += CHUNK) { bin += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK)); } return btoa(bin); } // ── Sarvam WebSocket Live Streaming STT ────────────────────────────────── // Replaces Web Speech API — streams raw PCM16 audio to our FastAPI // WebSocket proxy, which forwards it to Sarvam realtime STT. // Partial results show instantly; final results are added as utterances. let sarvamWs = null; // WebSocket to backend proxy let wsAudioCtx = null; // Separate AudioContext for WS streaming let wsProcessor = null; let wsSource = null; let partialBubbleId = 'partial-bubble-live'; function floatTo16BitPCM(float32) { const buf = new ArrayBuffer(float32.length * 2); const view = new DataView(buf); for (let i = 0; i < float32.length; i++) { const s = Math.max(-1, Math.min(1, float32[i])); view.setInt16(i * 2, s < 0 ? s * 0x8000 : s * 0x7FFF, true); } return buf; } function startSarvamLiveStream(stream) { const lang = (langSelect && langSelect.value && langSelect.value !== 'auto') ? langSelect.value : 'auto'; const proto = location.protocol === 'https:' ? 'wss' : 'ws'; const wsPort = location.port || (location.protocol === 'https:' ? 443 : 3000); const wsUrl = `${proto}://${location.hostname}:${wsPort}/ws/transcribe?language_code=${lang}`; sarvamWs = new WebSocket(wsUrl); sarvamWs.binaryType = 'arraybuffer'; sarvamWs.onopen = () => { liveRealtimeBadge.style.display = 'inline-flex'; console.log('[WS] Connected to Sarvam realtime proxy'); // Start sending PCM chunks over WebSocket wsAudioCtx = new (window.AudioContext || window.webkitAudioContext)(); wsSource = wsAudioCtx.createMediaStreamSource(stream); wsProcessor = wsAudioCtx.createScriptProcessor(2048, 1, 1); wsProcessor.onaudioprocess = (e) => { if (!recording || !sarvamWs || sarvamWs.readyState !== WebSocket.OPEN) return; const raw = e.inputBuffer.getChannelData(0); const resampled = downsample(raw, wsAudioCtx.sampleRate, SAMPLE_RATE); const pcm16 = floatTo16BitPCM(resampled); // Sarvam realtime expects: {"event": "audio_input", "audio": ""} const bytes = new Uint8Array(pcm16); let bin = ''; for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]); const b64 = btoa(bin); sarvamWs.send(JSON.stringify({ event: 'audio_input', audio: b64 })); }; wsSource.connect(wsProcessor); wsProcessor.connect(wsAudioCtx.destination); }; sarvamWs.onmessage = (evt) => { let msg; try { msg = JSON.parse(evt.data); } catch { return; } if (msg.event === 'transcript.partial' && msg.text) { renderLiveInterimBubble(msg.text); } else if (msg.event === 'transcript.final' && msg.text && msg.text.trim()) { // Remove partial bubble and add final utterance removePartialBubble(); addLiveUtterance(msg.text.trim(), secondsElapsed); } else if (msg.event === 'error') { console.warn('[WS] Sarvam error:', msg.message); } }; sarvamWs.onerror = (e) => { console.warn('[WS] WebSocket error:', e); }; sarvamWs.onclose = () => { liveRealtimeBadge.style.display = 'none'; stopWsAudioPipeline(); }; } function stopWsAudioPipeline() { if (wsProcessor) { try { wsProcessor.disconnect(); } catch(e){} wsProcessor = null; } if (wsSource) { try { wsSource.disconnect(); } catch(e){} wsSource = null; } if (wsAudioCtx) { try { wsAudioCtx.close(); } catch(e){} wsAudioCtx = null; } } function stopSarvamLiveStream() { liveRealtimeBadge.style.display = 'none'; stopWsAudioPipeline(); if (sarvamWs) { if (sarvamWs.readyState === WebSocket.OPEN) { try { sarvamWs.send(JSON.stringify({ event: 'end' })); } catch(e) {} setTimeout(() => { try { sarvamWs.close(); } catch(e){} }, 400); } sarvamWs = null; } removePartialBubble(); } function removePartialBubble() { const el = document.getElementById(partialBubbleId); if (el) el.remove(); } // Keep old names so rest of code compiles function startLiveSpeechRecognizer() {} // replaced by startSarvamLiveStream function stopLiveSpeechRecognizer() { stopSarvamLiveStream(); } function addLiveUtterance(text, timestampSec) { if (!text) return; const role = 'unknown'; const speaker = 'Live Speaker'; const startSec = Math.max(0, timestampSec - 3); const endSec = timestampSec; const uttId = 'utt-' + Date.now() + '-' + Math.random().toString(36).substr(2, 4); liveUtterances.push({ id: uttId, role: role, speaker: speaker, text: text, startSec: startSec, endSec: endSec }); renderAllUtterances(); // Background diarization — real speaker detect करतो fetch('/api/diarize', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ transcript: text }) }).then(async resp => { // BUG 5 FRONTEND FIX: 402 quota error handle करा if (resp.status === 402) { console.warn('[Live Diarize] Sarvam quota exhausted'); return; } if (resp.ok) { const data = await resp.json(); const diarizedText = data.transcript || ''; const isPatient = /(पेशंट|patient|रुग्ण)\s*[::\-]/i.test(diarizedText); const isDoc = /(डॉक्टर|doctor)\s*[::\-]/i.test(diarizedText); if (isDoc || isPatient) { const utt = liveUtterances.find(u => u.id === uttId); if (utt) { utt.role = isDoc ? 'doctor' : 'patient'; // BUG: doctorSelect हा DOM ID नाही — 'doctorName' हा actual ID आहे const doctorEl = document.getElementById('doctorName'); const patientEl = document.getElementById('patientName'); utt.speaker = isDoc ? 'Doctor (डॉक्टर)' : 'Patient (रुग्ण / पेशंट)'; renderAllUtterances(); } } } }).catch(e => console.error("Live diarize error:", e)); } function renderLiveInterimBubble(interimText) { const existingInterim = document.getElementById('interimBubble'); const speaker = 'Live Speaker'; const icon = '🗣️'; const roleCls = 'unknown'; const html = `
${icon}
${escapeHtml(speaker)} [${fmtTime(secondsElapsed)}] ● Listening Live…
${escapeHtml(interimText)}…
`; if (existingInterim) { existingInterim.outerHTML = html; } else { transcriptBody.insertAdjacentHTML('beforeend', html); } transcriptBody.scrollTop = transcriptBody.scrollHeight; } // ── Recording Actions ───────────────────────────────────────────────────── async function startRecording() { clearError(); pcmChunks = []; liveUtterances = []; try { mediaStream = await navigator.mediaDevices.getUserMedia({ audio: { channelCount: 1, echoCancellation: true } }); } catch (e) { showError('Microphone access denied. Please allow microphone permissions in your browser.'); return; } audioCtx = new (window.AudioContext || window.webkitAudioContext)(); sourceNode = audioCtx.createMediaStreamSource(mediaStream); analyserNode = audioCtx.createAnalyser(); analyserNode.fftSize = 64; processorNode = audioCtx.createScriptProcessor(BUFFER_SIZE, 1, 1); processorNode.onaudioprocess = (e) => { if (!recording) return; const raw = e.inputBuffer.getChannelData(0); const resampled = downsample(raw, audioCtx.sampleRate, SAMPLE_RATE); pcmChunks.push(new Float32Array(resampled)); }; sourceNode.connect(analyserNode); sourceNode.connect(processorNode); processorNode.connect(audioCtx.destination); recording = true; secondsElapsed = 0; timerEl.textContent = '00:00:00'; recStatusText.textContent = 'Live recording consultation...'; recordingCard.classList.add('is-recording'); timerInterval = setInterval(() => { secondsElapsed++; timerEl.textContent = fmtTime(secondsElapsed); }, 1000); startBtn.disabled = true; stopBtn.disabled = false; audioPlaybackBar.style.display = 'none'; drawVisualizer(); transcriptBody.innerHTML = `
🎙️

Live consultation recording started…

Speak clearly into the microphone. Words will appear in real time.
`; 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; stopLiveSpeechRecognizer(); if (timerInterval) { clearInterval(timerInterval); timerInterval = null; } if (animationId) cancelAnimationFrame(animationId); if (processorNode) { processorNode.disconnect(); processorNode = null; } if (sourceNode) { sourceNode.disconnect(); sourceNode = null; } if (audioCtx) { audioCtx.close(); audioCtx = null; } if (mediaStream) { mediaStream.getTracks().forEach(t => t.stop()); mediaStream = null; } recordingCard.classList.remove('is-recording'); startBtn.disabled = true; stopBtn.disabled = true; recStatusText.textContent = 'Processing full transcript & audio sync with Sarvam AI…'; if (pcmChunks.length === 0) { showError('No audio recorded.'); resetButtons(); return; } try { 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); const resp = await fetch('/api/transcribe', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ audio_b64, language_code: lang, num_speakers }) }); const data = await resp.json(); if (!resp.ok) throw new Error(data.error || 'Server error ' + resp.status); currentTranscript = data.transcript || ''; parseAndSetFullTranscript(currentTranscript, secondsElapsed, data.entries); recStatusText.textContent = `Completed in ${fmtTime(secondsElapsed)} • Generating clinical summary…`; showToast('Full transcript synchronized! Generating summary…'); if (currentTranscript.trim()) { await generateSummary(currentTranscript); } } catch (e) { const msg = e.message === 'Failed to fetch' ? 'Connection lost to server (http://localhost:3000). Server may have restarted or timed out. Please try again.' : e.message; showError('Transcription: ' + msg); recStatusText.textContent = 'Error during transcription'; } resetButtons(); } function resetButtons() { startBtn.disabled = false; stopBtn.disabled = true; } // ── Parse Full Transcript & Assign Real-time Audio Timestamps ───────────── function parseAndSetFullTranscript(text, totalDurationSec, entries) { if (!text || !text.trim()) { transcriptBody.innerHTML = '

No speech detected in audio.

'; return; } const patientName = patientInput.value.trim() || 'Patient'; const doctorName = (doctorSelect.value || 'Dr. Sharma').split('(')[0].trim(); const duration = Math.max(10, totalDurationSec || 60); liveUtterances = []; // Case 1: Use true acoustic timestamps returned directly by Sarvam Diarization if (entries && Array.isArray(entries) && entries.length > 0) { // 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(); let speaker = 'Doctor (डॉक्टर)'; if (role === 'patient') { speaker = 'Patient (रुग्ण / पेशंट)'; } else if (role === 'relative') { speaker = 'Relative (नातेवाईक)'; } else if (role === 'nurse') { speaker = 'Nurse (परिचारिका)'; } const startSec = typeof entry.startSec === 'number' ? entry.startSec : (parseFloat(entry.startSec) || 0); const endSec = typeof entry.endSec === 'number' ? entry.endSec : (parseFloat(entry.endSec) || (startSec + 2)); return { id: 'utt-' + idx, role: role, speaker: speaker, text: entry.text || entry.textContent || '', startSec: startSec, endSec: endSec }; }); renderAllUtterances(); return; } // Case 2: Fallback text parsing if no structured timestamps provided const plainText = text.replace(/\*/g, '').trim(); // Check if text has Doctor/Patient/Relative/Nurse markers OR the new [Speaker_X | Role] format const hasMarkers = /(?:\[Speaker_\d+\s*\|\s*(?:Doctor|Patient|Relative|Nurse)\])|(?:(?:डॉक्टर|पेशंट|doctor|patient|रुग्ण|relative|नातेवाईक|nurse|परिचारिका|नर्स)\s*[::\-])/i.test(plainText); if (hasMarkers) { // Split the text before each speaker label const segments = plainText.split(/(?=\[Speaker_\d+\s*\|\s*(?:Doctor|Patient|Relative|Nurse)\]|(?:डॉक्टर|पेशंट|Doctor|Patient|रुग्ण|Relative|नातेवाईक|Nurse|परिचारिका|नर्स)\s*[::\-])/i).map(s => s.trim()).filter(s => s.length > 0); const wordCounts = segments.map(s => { const cleaned = s.replace(/^(?:\[Speaker_\d+\s*\|\s*(?:Doctor|Patient|Relative|Nurse)\]\s*)|^(?:(?:डॉक्टर|पेशंट|doctor|patient|रुग्ण|relative|नातेवाईक|nurse|परिचारिका|नर्स)\s*[::\-]\s*)/i, '').trim(); return Math.max(1, cleaned.split(/\s+/).length); }); const totalWords = wordCounts.reduce((a, b) => a + b, 0); // Allocate 85% of total audio to speech, 15% to pauses between turns const pausePerTurn = segments.length > 1 ? (duration * 0.15) / (segments.length - 1) : 0; const speechDurationBudget = duration - (pausePerTurn * Math.max(0, segments.length - 1)); let currentOffset = 0; segments.forEach((segment, idx) => { const isPatient = /^(?:\[Speaker_\d+\s*\|\s*Patient\])|(?:(?:पेशंट|patient|रुग्ण)\s*[::\-])/i.test(segment); const isRelative = /^(?:\[Speaker_\d+\s*\|\s*Relative\])|(?:(?:relative|नातेवाईक)\s*[::\-])/i.test(segment); const isNurse = /^(?:\[Speaker_\d+\s*\|\s*Nurse\])|(?:(?:nurse|परिचारिका|नर्स)\s*[::\-])/i.test(segment); let role = 'doctor'; let speaker = 'Doctor (डॉक्टर)'; if (isPatient) { role = 'patient'; speaker = 'Patient (रुग्ण / पेशंट)'; } else if (isRelative) { role = 'relative'; speaker = 'Relative (नातेवाईक)'; } else if (isNurse) { role = 'nurse'; speaker = 'Nurse (परिचारिका)'; } const cleanedText = segment.replace(/^(?:\[Speaker_\d+\s*\|\s*(?:Doctor|Patient|Relative|Nurse)\]\s*)|^(?:(?:डॉक्टर|पेशंट|doctor|patient|रुग्ण|relative|नातेवाईक|nurse|परिचारिका|नर्स)\s*[::\-]\s*)/i, '').trim(); const proportion = wordCounts[idx] / totalWords; const segmentDuration = Math.max(1.5, proportion * speechDurationBudget); liveUtterances.push({ id: 'utt-' + idx, role: role, speaker: speaker, text: cleanedText || segment, startSec: currentOffset, endSec: currentOffset + segmentDuration }); currentOffset += segmentDuration + pausePerTurn; }); } else { // Fallback if AI didn't format it properly liveUtterances.push({ id: 'utt-0', role: 'patient', speaker: 'Transcript (Unlabeled)', text: plainText, startSec: 0, endSec: duration }); } renderAllUtterances(); } // ── Render All Utterances (Full Transcript with Synchronized Audio) ───────── function renderAllUtterances() { if (liveUtterances.length === 0) return; const searchTerm = (transcriptSearch.value || '').toLowerCase().trim(); let html = ''; liveUtterances.forEach((utt) => { // Filter by speaker (All, Doctor, Patient, Relative, Nurse) if (activeFilter !== 'all' && utt.role !== activeFilter) return; // Filter by search if (searchTerm && !utt.text.toLowerCase().includes(searchTerm) && !utt.speaker.toLowerCase().includes(searchTerm)) { return; } let icon = '🧑'; let colorCls = 'patient-color'; if (utt.role === 'doctor') { icon = '🧑‍⚕️'; colorCls = 'doctor-color'; } else if (utt.role === 'relative') { icon = '👨‍👩‍👧'; colorCls = 'relative-color'; } else if (utt.role === 'nurse') { icon = '👩‍⚕️'; colorCls = 'nurse-color'; } html += `
${icon}
${escapeHtml(utt.speaker)} [${fmtTime(utt.startSec)} - ${fmtTime(utt.endSec)}] English
${escapeHtml(utt.text)}
`; }); if (!html && searchTerm) { transcriptBody.innerHTML = `

No dialogue matching "${escapeHtml(searchTerm)}"

`; return; } transcriptBody.innerHTML = html; } // ── Audio Player & Real-time Karaoke Highlighting ───────────────────────── function setupAudioPlayer(wavBuffer, durationSec) { if (audioPlayerAudio) { audioPlayerAudio.pause(); audioPlayerAudio = null; } clearInterval(playerInterval); const blob = new Blob([wavBuffer], { type: 'audio/wav' }); const audioUrl = URL.createObjectURL(blob); audioPlayerAudio = new Audio(audioUrl); audioPlaybackBar.style.display = 'flex'; audioScrubber.max = durationSec || 10; audioScrubber.value = 0; audioCurrentTime.textContent = '00:00'; audioTotalDuration.textContent = fmtTime(durationSec); playIcon.textContent = '▶'; audioPlayerAudio.ontimeupdate = () => { const cur = audioPlayerAudio.currentTime; audioScrubber.value = cur; audioCurrentTime.textContent = fmtTime(cur); syncHighlightUtterance(cur); }; audioPlayerAudio.onended = () => { playIcon.textContent = '▶'; removePlayingHighlights(); }; } function setupDemoAudioPlayer(durationSec) { audioPlaybackBar.style.display = 'flex'; audioScrubber.max = durationSec; audioScrubber.value = 0; audioCurrentTime.textContent = '00:00'; audioTotalDuration.textContent = fmtTime(durationSec); playIcon.textContent = '▶'; } function togglePlayPause() { if (audioPlayerAudio) { if (audioPlayerAudio.paused) { audioPlayerAudio.play(); playIcon.textContent = '⏸'; } else { audioPlayerAudio.pause(); playIcon.textContent = '▶'; } return; } // Simulated playback for demo if no audio file if (playerInterval) { clearInterval(playerInterval); playerInterval = null; playIcon.textContent = '▶'; } else { playIcon.textContent = '⏸'; const maxTime = parseFloat(audioScrubber.max) || 60; playerInterval = setInterval(() => { let cur = parseFloat(audioScrubber.value) + 0.5; if (cur > maxTime) { cur = 0; clearInterval(playerInterval); playerInterval = null; playIcon.textContent = '▶'; removePlayingHighlights(); } audioScrubber.value = cur; audioCurrentTime.textContent = fmtTime(cur); syncHighlightUtterance(cur); }, 500); } } function syncHighlightUtterance(currentSec) { const items = document.querySelectorAll('.utterance-item'); let matchedItem = null; items.forEach((item) => { const start = parseFloat(item.getAttribute('data-start') || 0); const end = parseFloat(item.getAttribute('data-end') || 0); if (currentSec >= start && currentSec <= end) { matchedItem = item; } }); if (matchedItem) { if (!matchedItem.classList.contains('active-playing')) { items.forEach(i => i.classList.remove('active-playing')); matchedItem.classList.add('active-playing'); matchedItem.scrollIntoView({ behavior: 'smooth', block: 'nearest' }); } } else { // Audio is currently in silence / pause: remove active highlight so it remains still items.forEach(i => i.classList.remove('active-playing')); } } function removePlayingHighlights() { document.querySelectorAll('.utterance-item').forEach(i => i.classList.remove('active-playing')); } // ── Generate AI Clinical Summary ────────────────────────────────────────── async function generateSummary(transcriptText) { if (!transcriptText || !transcriptText.trim()) return; sumChiefComplaint.innerHTML = '

Generating with AI (Groq LLM)…

'; sumSymptoms.innerHTML = '

Detecting symptoms…

'; sumAssessment.innerHTML = '

Evaluating assessment…

'; sumHistory.innerHTML = '

Extracting medical history…

'; sumPlan.innerHTML = '

Structuring prescription & plan…

'; try { const resp = await fetch('/api/summary', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ transcript: transcriptText }) }); const data = await resp.json(); if (!resp.ok) throw new Error(data.error || 'Summary error ' + resp.status); currentSummaryData = data.summary; renderSummaryCards(currentSummaryData); recStatusText.textContent = '✅ Clinical Consultation Summarized Successfully'; showToast('AI Clinical Summary generated!'); } catch (e) { sumChiefComplaint.innerHTML = `

${escapeHtml(e.message)}

`; sumSymptoms.innerHTML = '

—

'; sumAssessment.innerHTML = '

—

'; sumHistory.innerHTML = '

—

'; sumPlan.innerHTML = '

—

'; } } function renderSummaryCards(s) { if (!s) return; // 1. Chief Complaint sumChiefComplaint.innerHTML = `

${escapeHtml(s.chief_complaint || 'Not mentioned')}

`; // 2. Symptoms Discussed (Pill Badges) if (Array.isArray(s.symptoms) && s.symptoms.length > 0) { sumSymptoms.innerHTML = `
${s.symptoms.map(sym => `⚠️ ${escapeHtml(String(sym))}`).join('')}
`; } else { sumSymptoms.innerHTML = `

${escapeHtml(s.symptoms || 'None recorded')}

`; } // 3. Assessment / Recommendation sumAssessment.innerHTML = `

${escapeHtml(s.assessment || 'Under clinical evaluation')}

`; // 4. History sumHistory.innerHTML = `

${escapeHtml(s.history || 'No prior medical history noted')}

`; // 5. Prescription & Plan (Rx) if (Array.isArray(s.plan) && s.plan.length > 0) { sumPlan.innerHTML = ` `; } else { sumPlan.innerHTML = `

${escapeHtml(s.plan || 'Follow standard clinical protocol')}

`; } } let currentCaseIdx = 0; const availableCases = ['case-cardiology', 'case-diabetes', 'case-ent']; // ── Demo Conversation Loader ────────────────────────────────────────────── async function loadDemoConversation(caseId) { let selectedCase = caseId; if (!selectedCase || typeof selectedCase !== 'string') { selectedCase = availableCases[currentCaseIdx % availableCases.length]; currentCaseIdx++; } recStatusText.textContent = `Loading consultation…`; try { const resp = await fetch(`/api/demo?case=${encodeURIComponent(selectedCase)}`); const demo = await resp.json(); patientInput.value = demo.patientName; patientIdInput.value = demo.patientId; dateInput.value = demo.date; if (doctorSelect) doctorSelect.value = demo.doctorName || 'Dr. Sharma'; if (langSelect) langSelect.value = demo.language || 'mr-IN'; const dur = demo.durationSec || 200; timerEl.textContent = fmtTime(dur); currentTranscript = demo.transcript; currentSummaryData = demo.summary; parseAndSetFullTranscript(currentTranscript, dur); setupDemoAudioPlayer(dur); renderSummaryCards(currentSummaryData); recStatusText.textContent = `⚡ Loaded "${demo.title || demo.patientName}" with Full Real-time Sync`; showToast(`Loaded ${demo.patientName} (${demo.language}) consultation!`); } catch (e) { showError('Failed to load demo: ' + e.message); } } // ── Populate Past Recordings & Archives on startup ──────────────────────── async function loadArchiveLists() { try { const resp = await fetch('/api/demos'); const data = await resp.json(); const cases = data.cases || []; // Populate Recordings List in Past Recordings tab const recordingsList = document.getElementById('recordingsList'); if (recordingsList && cases.length > 0) { recordingsList.innerHTML = cases.map(c => `
📁
${escapeHtml(c.patientName)} (${c.patientId}) ⏱️ ${fmtTime(c.durationSec)} ${c.language}
${escapeHtml(c.title)} — ${escapeHtml(c.summary?.chief_complaint || '')}
`).join(''); } // Populate Patients Grid in Patients tab const patientsGrid = document.getElementById('patientsGrid'); if (patientsGrid && cases.length > 0) { patientsGrid.innerHTML = cases.map(c => `
👤

${escapeHtml(c.patientName)}

${c.patientId} • ${c.date}

Recent Diagnosis: ${escapeHtml(c.summary?.assessment || 'Routine Checkup')}

`).join(''); } } catch (e) { console.warn('Could not populate archive lists:', e); } } loadArchiveLists(); // ── Upload Audio Handler (Real-Time Chunk Streaming) ────────────────────── uploadAudioBtn.addEventListener('click', () => { audioFileInput.click(); }); audioFileInput.addEventListener('change', async (e) => { const file = e.target.files[0]; if (!file) return; clearError(); recStatusText.textContent = `Decoding audio: ${file.name}…`; showToast(`Loading audio file: ${file.name}`); try { const arrayBuffer = await file.arrayBuffer(); const tempAudioCtx = new (window.AudioContext || window.webkitAudioContext)(); const audioBuffer = await tempAudioCtx.decodeAudioData(arrayBuffer); // Fast native resampling instead of slow JS loop const resampled = await downsampleNative(audioBuffer, SAMPLE_RATE); const fullWavBuffer = buildWav([resampled], SAMPLE_RATE); tempAudioCtx.close(); const totalDurationSec = audioBuffer.duration; timerEl.textContent = fmtTime(totalDurationSec); setupAudioPlayer(fullWavBuffer, totalDurationSec); // 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 }) }).then(async resp => { const data = await resp.json(); if (!resp.ok) throw new Error(data.error || 'Server error'); return data; }); const transcribeData = await transcribePromise; currentTranscript = transcribeData.transcript || ''; parseAndSetFullTranscript(currentTranscript, totalDurationSec, transcribeData.entries); recStatusText.textContent = `✅ Transcribed ${file.name} successfully! Generating Summary...`; showToast('Audio transcribed & diarized! Generating AI Summary...'); if (currentTranscript.trim()) { await generateSummary(currentTranscript); recStatusText.textContent = `✅ Consultation Processed Successfully!`; } } catch (err) { const msg = err.message === 'Failed to fetch' ? 'Connection lost to server (http://localhost:3000). Server may have restarted or timed out. Please try again.' : err.message; showError('Failed to process uploaded audio: ' + msg); recStatusText.textContent = 'Error processing uploaded audio file'; } audioFileInput.value = ''; }); // ── Scrubber, Filter & Search Handlers ───────────────────────────────────── if (playAudioBtn) playAudioBtn.addEventListener('click', togglePlayPause); if (audioScrubber) { audioScrubber.addEventListener('input', (e) => { const targetSec = parseFloat(e.target.value); if (audioPlayerAudio) { audioPlayerAudio.currentTime = targetSec; } audioCurrentTime.textContent = fmtTime(targetSec); syncHighlightUtterance(targetSec); }); } if (transcriptSearch) { transcriptSearch.addEventListener('input', renderAllUtterances); } filterPills.forEach(pill => { pill.addEventListener('click', () => { filterPills.forEach(p => p.classList.remove('active')); pill.classList.add('active'); activeFilter = pill.getAttribute('data-filter'); renderAllUtterances(); }); }); // ── Copy, Print, & Export Handlers ──────────────────────────────────────── copyTranscriptBtn.addEventListener('click', () => { if (!currentTranscript) { showToast('No transcript to copy!'); return; } navigator.clipboard.writeText(currentTranscript).then(() => { showToast('📋 Full transcript copied to clipboard!'); }); }); clearTranscriptBtn.addEventListener('click', () => { currentTranscript = ''; currentSummaryData = null; liveUtterances = []; if (audioPlayerAudio) { audioPlayerAudio.pause(); audioPlayerAudio = null; } clearInterval(playerInterval); audioPlaybackBar.style.display = 'none'; transcriptBody.innerHTML = `
🎙️

Recording in progress… Transcript will appear here in real time.

Speak into the microphone or click DEMO to see full real-time audio synchronization.
`; sumChiefComplaint.innerHTML = '

—

'; sumSymptoms.innerHTML = '

—

'; sumAssessment.innerHTML = '

—

'; sumHistory.innerHTML = '

—

'; sumPlan.innerHTML = '

—

'; timerEl.textContent = '00:00:00'; recStatusText.textContent = 'Ready to record consultation...'; clearError(); showToast('Reset consultation workspace.'); }); copySummaryBtn.addEventListener('click', () => { if (!currentSummaryData) { showToast('No summary generated yet!'); return; } const textToCopy = `AI CLINICAL SUMMARY Patient: ${patientInput.value} (ID: ${patientIdInput.value}) Doctor: ${doctorSelect.value} Date: ${dateInput.value} CHIEF COMPLAINT: ${currentSummaryData.chief_complaint || ''} SYMPTOMS: ${Array.isArray(currentSummaryData.symptoms) ? currentSummaryData.symptoms.join(', ') : currentSummaryData.symptoms || ''} ASSESSMENT / DIAGNOSIS: ${currentSummaryData.assessment || ''} HISTORY: ${currentSummaryData.history || ''} PLAN & PRESCRIPTION: ${Array.isArray(currentSummaryData.plan) ? currentSummaryData.plan.join('\n- ') : currentSummaryData.plan || ''} `; navigator.clipboard.writeText(textToCopy).then(() => { showToast('📋 Summary copied to clipboard!'); }); }); printSummaryBtn.addEventListener('click', () => { window.print(); }); exportJsonBtn.addEventListener('click', () => { if (!currentSummaryData) { showToast('No summary data to export!'); return; } const exportData = { patientName: patientInput.value, patientId: patientIdInput.value, doctor: doctorSelect.value, date: dateInput.value, transcript: currentTranscript, summary: currentSummaryData }; const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `Consultation_${patientIdInput.value}_${dateInput.value}.json`; a.click(); URL.revokeObjectURL(url); showToast('📥 Consultation exported as JSON!'); }); // ── Sidebar Tabs Navigation ─────────────────────────────────────────────── navItems.forEach(item => { item.addEventListener('click', (e) => { e.preventDefault(); const tabId = item.getAttribute('data-tab'); navItems.forEach(i => i.classList.remove('active')); item.classList.add('active'); tabViews.forEach(v => v.classList.remove('active')); const activeView = document.getElementById(`view-${tabId}`); if (activeView) activeView.classList.add('active'); const label = item.querySelector('.nav-label'); if (label && pageHeading) { pageHeading.textContent = label.textContent; } if (window.innerWidth < 768 && sidebar) { sidebar.classList.remove('open'); } }); }); if (menuToggle && sidebar) { menuToggle.addEventListener('click', () => { sidebar.classList.toggle('open'); }); } // ── Patient Modal ───────────────────────────────────────────────────────── function openModal() { patientModal.classList.add('open'); newPatientName.focus(); } function closeModal() { patientModal.classList.remove('open'); } if (openAddPatientBtn) openAddPatientBtn.addEventListener('click', openModal); if (btnAddNewPatientTab) btnAddNewPatientTab.addEventListener('click', openModal); if (closePatientModal) closePatientModal.addEventListener('click', closeModal); if (cancelPatientModal) cancelPatientModal.addEventListener('click', closeModal); if (savePatientBtn) { savePatientBtn.addEventListener('click', () => { const name = newPatientName.value.trim(); if (!name) { alert('Please enter patient name'); return; } patientInput.value = name; patientIdInput.value = 'PT-2026-' + String(Math.floor(10000 + Math.random() * 90000)); closeModal(); showToast(`Selected patient: ${name} (${patientIdInput.value})`); newPatientName.value = ''; }); } // ── Event Listeners ─────────────────────────────────────────────────────── startBtn.addEventListener('click', startRecording); stopBtn.addEventListener('click', stopAndSummarize); demoBtn.addEventListener('click', loadDemoConversation); // Global window helpers window.app = { seekToTime: function(seconds) { if (audioPlayerAudio) { audioPlayerAudio.currentTime = seconds; audioPlayerAudio.play(); playIcon.textContent = '⏸'; } else { audioScrubber.value = seconds; audioCurrentTime.textContent = fmtTime(seconds); syncHighlightUtterance(seconds); } }, loadSpecificCase: function(caseId) { const tab = document.querySelector('[data-tab="new-consultation"]'); if (tab) tab.click(); if (demoCaseSelect) demoCaseSelect.value = caseId; loadDemoConversation(caseId); }, loadDemoRecord: function(type) { const caseMap = { ramesh: 'case-cardiology', sunita: 'case-diabetes', amit: 'case-ent' }; const caseId = caseMap[type] || 'case-cardiology'; this.loadSpecificCase(caseId); } }; })(); // End of application logic.