(() => { 'use strict'; // ── Config ───────────────────────────────────────────────────────────────── // Point this to wherever your FastAPI backend is running const BACKEND = 'http://127.0.0.1:8080'; // ── DOM refs (matching existing HTML IDs exactly) ────────────────────────── const startBtn = document.getElementById('startBtn'); const stopBtn = document.getElementById('stopBtn'); const timerEl = document.getElementById('timer'); const liveBadge = document.getElementById('liveBadge'); const serverStatus = document.getElementById('serverStatus'); const recError = document.getElementById('recError'); const transcriptBody = document.getElementById('transcriptBody'); const summaryBtn = document.getElementById('summaryBtn'); const clearBtn = document.getElementById('clearBtn'); const summaryCard = document.getElementById('summaryCard'); const summaryBody = document.getElementById('summaryBody'); // ── State ────────────────────────────────────────────────────────────────── let mediaRecorder = null; let recordedChunks = []; let timerInterval = null; let secondsElapsed = 0; let lastTranscript = ''; // ── Helpers ──────────────────────────────────────────────────────────────── function fmtTime(s) { const h = String(Math.floor(s / 3600)).padStart(2, '0'); const m = String(Math.floor((s % 3600) / 60)).padStart(2, '0'); const sec = String(s % 60).padStart(2, '0'); return `${h}:${m}:${sec}`; } function escHtml(str) { const d = document.createElement('div'); d.innerText = str; return d.innerHTML; } function showError(msg) { recError.textContent = msg; recError.style.display = 'block'; } function clearError() { recError.textContent = ''; recError.style.display = 'none'; } function setStatus(msg, type = '') { serverStatus.textContent = msg; serverStatus.className = 'status-text' + (type ? ` ${type}` : ''); } // ── Health check on load ─────────────────────────────────────────────────── async function checkHealth() { try { const res = await fetch(`${BACKEND}/api/health`); const data = await res.json(); if (data.sarvam_key_configured) { setStatus('✔ Backend ready — Sarvam API key configured', 'ok'); } else { setStatus('✘ Backend running but SARVAM_API_KEY is not set', 'bad'); startBtn.disabled = true; } } catch { setStatus('✘ Cannot reach backend at ' + BACKEND, 'bad'); startBtn.disabled = true; } } // ── Choose best supported MIME type ─────────────────────────────────────── function getSupportedMimeType() { const types = [ 'audio/webm;codecs=opus', 'audio/webm', 'audio/ogg;codecs=opus', 'audio/ogg', 'audio/mp4', ]; return types.find(t => MediaRecorder.isTypeSupported(t)) || ''; } // ── Start recording ──────────────────────────────────────────────────────── async function startRecording() { clearError(); recordedChunks = []; // Request microphone let stream; try { stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: false }); } catch (err) { if (err.name === 'NotAllowedError' || err.name === 'PermissionDeniedError') { showError('Microphone permission denied. Please allow microphone access in your browser settings.'); } else if (err.name === 'NotFoundError') { showError('No microphone found. Please connect a microphone and try again.'); } else { showError(`Microphone error: ${err.message}`); } return; } // Create MediaRecorder const mimeType = getSupportedMimeType(); try { mediaRecorder = new MediaRecorder(stream, mimeType ? { mimeType } : {}); } catch (err) { showError(`Could not start MediaRecorder: ${err.message}`); stream.getTracks().forEach(t => t.stop()); return; } mediaRecorder.ondataavailable = (e) => { if (e.data && e.data.size > 0) recordedChunks.push(e.data); }; mediaRecorder.onerror = (e) => { showError(`Recording error: ${e.error?.message || 'Unknown error'}`); }; mediaRecorder.start(250); // collect data every 250 ms // Update UI → recording state startBtn.disabled = true; stopBtn.disabled = false; liveBadge.classList.add('on'); summaryBtn.disabled = true; summaryCard.style.display = 'none'; lastTranscript = ''; transcriptBody.innerHTML = '
Recording in progress… press ⏹ Stop & Transcribe when done.
'; // Start timer secondsElapsed = 0; timerEl.textContent = '🔴 ' + fmtTime(0); timerInterval = setInterval(() => { secondsElapsed++; timerEl.textContent = '🔴 ' + fmtTime(secondsElapsed); }, 1000); setStatus('🎙️ Recording…'); } // ── Stop recording → send to backend ────────────────────────────────────── function stopRecording() { if (!mediaRecorder || mediaRecorder.state === 'inactive') return; // Stop timer clearInterval(timerInterval); timerInterval = null; // Stop all mic tracks mediaRecorder.stream.getTracks().forEach(t => t.stop()); // When recorder finishes flushing, send the audio mediaRecorder.onstop = async () => { await sendAudioToBackend(); }; mediaRecorder.stop(); // Update UI → processing state startBtn.disabled = true; stopBtn.disabled = true; liveBadge.classList.remove('on'); timerEl.textContent = '⏳ ' + fmtTime(secondsElapsed); setStatus('Processing transcript…'); transcriptBody.innerHTML = `Transcription failed. Please try again.
'; timerEl.textContent = '🔴 ' + fmtTime(secondsElapsed); setStatus('Transcription failed', 'bad'); } resetButtons(); } function resetButtons() { startBtn.disabled = false; stopBtn.disabled = true; } // ── Render transcript in existing #transcriptBody ───────────────────────── function renderTranscript(text, language) { if (!text) { transcriptBody.innerHTML = 'No speech detected in the recording.
'; return; } // Split on sentence boundaries and render each as an utterance block // (Doctor / Patient alternating — best-effort without diarization) const sentences = text.match(/[^.!?।\n]+[.!?।\n]*/g) || [text]; const langTag = language && language !== 'unknown' ? `[${escHtml(language)}]` : ''; let html = ''; sentences.forEach((sentence, i) => { sentence = sentence.trim(); if (!sentence) return; const isDoc = i % 2 === 0; const icon = isDoc ? '🧑⚕️' : '🧑'; const name = isDoc ? 'Doctor' : 'Patient'; const cls = isDoc ? '' : 'patient'; const ts = fmtTime(Math.round((i / sentences.length) * secondsElapsed)); html += `Transcript will appear here once recording starts…
'; summaryCard.style.display = 'none'; summaryBtn.disabled = true; timerEl.textContent = '🔴 00:00:00'; clearError(); setStatus(''); } // ── Generate AI Summary ──────────────────────────────────────────────────── async function generateSummary() { if (!lastTranscript.trim()) return; summaryCard.style.display = 'block'; summaryBody.innerHTML = `