1302 lines
50 KiB
JavaScript
1302 lines
50 KiB
JavaScript
/**
|
||
* 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": "<base64>"}
|
||
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
|
||
? (doctorEl ? doctorEl.value || 'Dr. Sharma' : 'Dr. Sharma').split('(')[0].trim()
|
||
: (patientEl ? patientEl.value.trim() || 'Patient' : '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 = `
|
||
<div class="utterance-item ${roleCls} live-streaming" id="interimBubble">
|
||
<div class="utterance-avatar">${icon}</div>
|
||
<div class="utterance-content">
|
||
<div class="utterance-meta">
|
||
<span class="utterance-speaker">${escapeHtml(speaker)}</span>
|
||
<span class="utterance-time">[${fmtTime(secondsElapsed)}]</span>
|
||
<span class="utterance-lang-badge" style="background:#fef3c7; color:#b45309;">● Listening Live…</span>
|
||
</div>
|
||
<div class="utterance-text" style="opacity:0.85;">${escapeHtml(interimText)}…</div>
|
||
</div>
|
||
</div>`;
|
||
|
||
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 = `
|
||
<div class="transcript-placeholder">
|
||
<div class="placeholder-icon">🎙️</div>
|
||
<p>Live consultation recording started…</p>
|
||
<span class="placeholder-sub">Speak clearly into the microphone. Words will appear in real time.</span>
|
||
</div>`;
|
||
|
||
startSarvamLiveStream(mediaStream);
|
||
}
|
||
|
||
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;
|
||
|
||
// 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: 2 })
|
||
});
|
||
|
||
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 = '<div class="transcript-placeholder"><p>No speech detected in audio.</p></div>';
|
||
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) {
|
||
liveUtterances = entries.map((entry, idx) => {
|
||
const role = (entry.role || 'patient').toLowerCase();
|
||
let speaker = doctorName;
|
||
if (role === 'patient') {
|
||
speaker = patientName;
|
||
} 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 = doctorName;
|
||
|
||
if (isPatient) {
|
||
role = 'patient';
|
||
speaker = patientName;
|
||
} 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
|
||
if (activeFilter === 'doctor' && utt.role !== 'doctor') return;
|
||
if (activeFilter === 'patient' && utt.role !== 'patient') 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 += `
|
||
<div class="utterance-item ${utt.role}" id="${utt.id}" data-start="${utt.startSec.toFixed(2)}" data-end="${utt.endSec.toFixed(2)}" onclick="window.app.seekToTime(${utt.startSec})">
|
||
<div class="utterance-avatar">${icon}</div>
|
||
<div class="utterance-content">
|
||
<div class="utterance-meta">
|
||
<span class="utterance-speaker ${colorCls}">${escapeHtml(utt.speaker)}</span>
|
||
<span class="utterance-time">[${fmtTime(utt.startSec)} - ${fmtTime(utt.endSec)}]</span>
|
||
<span class="utterance-lang-badge">English</span>
|
||
</div>
|
||
<div class="utterance-text">${escapeHtml(utt.text)}</div>
|
||
</div>
|
||
</div>`;
|
||
});
|
||
|
||
if (!html && searchTerm) {
|
||
transcriptBody.innerHTML = `<div class="transcript-placeholder"><p>No dialogue matching "${escapeHtml(searchTerm)}"</p></div>`;
|
||
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 = '<p class="empty-field">Generating with AI (Groq LLM)…</p>';
|
||
sumSymptoms.innerHTML = '<p class="empty-field">Detecting symptoms…</p>';
|
||
sumAssessment.innerHTML = '<p class="empty-field">Evaluating assessment…</p>';
|
||
sumHistory.innerHTML = '<p class="empty-field">Extracting medical history…</p>';
|
||
sumPlan.innerHTML = '<p class="empty-field">Structuring prescription & plan…</p>';
|
||
|
||
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 = `<p class="empty-field" style="color:#ef4444;">${escapeHtml(e.message)}</p>`;
|
||
sumSymptoms.innerHTML = '<p class="empty-field">—</p>';
|
||
sumAssessment.innerHTML = '<p class="empty-field">—</p>';
|
||
sumHistory.innerHTML = '<p class="empty-field">—</p>';
|
||
sumPlan.innerHTML = '<p class="empty-field">—</p>';
|
||
}
|
||
}
|
||
|
||
function renderSummaryCards(s) {
|
||
if (!s) return;
|
||
|
||
// 1. Chief Complaint
|
||
sumChiefComplaint.innerHTML = `<p><strong>${escapeHtml(s.chief_complaint || 'Not mentioned')}</strong></p>`;
|
||
|
||
// 2. Symptoms Discussed (Pill Badges)
|
||
if (Array.isArray(s.symptoms) && s.symptoms.length > 0) {
|
||
sumSymptoms.innerHTML = `
|
||
<div class="symptom-tag-list">
|
||
${s.symptoms.map(sym => `<span class="symptom-tag">⚠️ ${escapeHtml(String(sym))}</span>`).join('')}
|
||
</div>`;
|
||
} else {
|
||
sumSymptoms.innerHTML = `<p>${escapeHtml(s.symptoms || 'None recorded')}</p>`;
|
||
}
|
||
|
||
// 3. Assessment / Recommendation
|
||
sumAssessment.innerHTML = `<p>${escapeHtml(s.assessment || 'Under clinical evaluation')}</p>`;
|
||
|
||
// 4. History
|
||
sumHistory.innerHTML = `<p>${escapeHtml(s.history || 'No prior medical history noted')}</p>`;
|
||
|
||
// 5. Prescription & Plan (Rx)
|
||
if (Array.isArray(s.plan) && s.plan.length > 0) {
|
||
sumPlan.innerHTML = `
|
||
<ul class="plan-item-list">
|
||
${s.plan.map(p => `<li>${escapeHtml(String(p))}</li>`).join('')}
|
||
</ul>`;
|
||
} else {
|
||
sumPlan.innerHTML = `<p>${escapeHtml(s.plan || 'Follow standard clinical protocol')}</p>`;
|
||
}
|
||
}
|
||
|
||
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 => `
|
||
<div class="utterance-item doctor" style="cursor:pointer; margin-bottom:10px;" onclick="window.app.loadSpecificCase('${c.id}')">
|
||
<div class="utterance-avatar">📁</div>
|
||
<div class="utterance-content">
|
||
<div class="utterance-meta">
|
||
<span class="utterance-speaker doctor-color">${escapeHtml(c.patientName)} (${c.patientId})</span>
|
||
<span class="utterance-time">⏱️ ${fmtTime(c.durationSec)}</span>
|
||
<span class="utterance-lang-badge">${c.language}</span>
|
||
</div>
|
||
<div class="utterance-text"><strong>${escapeHtml(c.title)}</strong> — ${escapeHtml(c.summary?.chief_complaint || '')}</div>
|
||
</div>
|
||
<button class="table-btn" style="align-self:center;">Load in Workspace</button>
|
||
</div>
|
||
`).join('');
|
||
}
|
||
|
||
// Populate Patients Grid in Patients tab
|
||
const patientsGrid = document.getElementById('patientsGrid');
|
||
if (patientsGrid && cases.length > 0) {
|
||
patientsGrid.innerHTML = cases.map(c => `
|
||
<div class="card" style="margin-bottom:10px; background:#f8fafc;">
|
||
<div class="card-header-row">
|
||
<div class="card-title-group">
|
||
<span style="font-size:22px;">👤</span>
|
||
<div>
|
||
<h4 style="font-size:14px; color:#0f172a;">${escapeHtml(c.patientName)}</h4>
|
||
<span style="font-size:11px; color:#64748b;">${c.patientId} • ${c.date}</span>
|
||
</div>
|
||
</div>
|
||
<button class="table-btn" onclick="window.app.loadSpecificCase('${c.id}')">Select Patient</button>
|
||
</div>
|
||
<p style="font-size:12.5px; color:#334155; margin-top:4px;"><strong>Recent Diagnosis:</strong> ${escapeHtml(c.summary?.assessment || 'Routine Checkup')}</p>
|
||
</div>
|
||
`).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 transcribePromise = fetch('/api/transcribe', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ audio_b64, language_code: lang, num_speakers: 2 })
|
||
}).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 = `
|
||
<div class="transcript-placeholder">
|
||
<div class="placeholder-icon">🎙️</div>
|
||
<p>Recording in progress… Transcript will appear here in real time.</p>
|
||
<span class="placeholder-sub">Speak into the microphone or click DEMO to see full real-time audio synchronization.</span>
|
||
</div>`;
|
||
sumChiefComplaint.innerHTML = '<p class="empty-field">—</p>';
|
||
sumSymptoms.innerHTML = '<p class="empty-field">—</p>';
|
||
sumAssessment.innerHTML = '<p class="empty-field">—</p>';
|
||
sumHistory.innerHTML = '<p class="empty-field">—</p>';
|
||
sumPlan.innerHTML = '<p class="empty-field">—</p>';
|
||
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.
|