Spaces:
Sleeping
Sleeping
Upload article_template.html
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{{ headline }} - TRON Voice News</title> <script src="https://cdn.tailwindcss.com"></script> <link href="https://fonts.googleapis.com/css2?family=Playfair+Display:ital,wght@0,700;1,400&family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet"> <style> body { font-family: 'Inter', sans-serif; background-color: #f8fafc; } .toi-header { font-family: 'Playfair Display', serif; letter-spacing: 0.05em; } .toi-body { font-family: Georgia, serif; line-height: 1.8; color: #1f2937; } /* Custom scrollbar for transcripts */ .custom-scrollbar::-webkit-scrollbar { width: 5px; } .custom-scrollbar::-webkit-scrollbar-track { background: #020617; } .custom-scrollbar::-webkit-scrollbar-thumb { background: #1e293b; border-radius: 4px; } .custom-scrollbar::-webkit-scrollbar-thumb:hover { background: #334155; } </style></head><body class="min-h-screen text-slate-800 flex flex-col justify-between"> <!-- Configuration Injectors --> <script> // Global variables for backend connectivity and assistant configuration const BACKEND_URL = "{{ backend_url }}"; const TRON_CONFIG = {{ tron_config | tojson }}; </script>
<!-- Header bar --> <header class="border-b border-slate-200 bg-white sticky top-0 z-30 shadow-sm"> <div class="max-w-4xl mx-auto px-6 py-4 flex items-center justify-between"> <div class="flex items-center space-x-3"> <div class="w-8 h-8 rounded-lg bg-neutral-900 flex items-center justify-center"> <span class="text-lg font-bold text-white toi-header">T</span> </div> <div> <h1 class="text-sm font-bold text-neutral-900">TRON</h1> <p class="text-[10px] text-neutral-500 font-semibold tracking-wider uppercase">Voice-Activated Article</p> </div> </div> <a href="/" class="text-xs font-semibold text-indigo-600 hover:text-indigo-800 transition-colors flex items-center space-x-1"> <span>← Back to Dashboard</span> </a> </div> </header>
<!-- Article layout --> <main class="flex-1 max-w-4xl w-full mx-auto px-6 py-12"> <article class="bg-white rounded-3xl p-8 md:p-12 border border-slate-200 shadow-xl space-y-8"> <!-- TOI Masthead Replica --> <div class="text-center border-b-4 border-double border-neutral-900 pb-4"> <div class="text-xs uppercase tracking-widest font-serif font-bold text-neutral-500 flex justify-between px-1"> <span>Established 1838</span> <span>The Times of India</span> <span>Daily Edition</span> </div> <h1 class="text-4xl md:text-5xl font-serif font-black tracking-normal toi-header my-3 text-neutral-950">THE TIMES OF INDIA</h1> <div class="text-xs border-t border-neutral-900 pt-2 flex justify-between font-serif italic text-neutral-700"> <span>Reg. No. Delhi-0912</span> <span>{{ date }}</span> <span>Price: ₹ 5.00</span> </div> </div>
<!-- Headline --> <div class="space-y-4"> <h1 class="text-2xl md:text-3.5xl font-bold font-serif leading-tight text-neutral-950 tracking-tight">{{ headline }}</h1> <!-- Metadata line --> <div class="text-xs text-neutral-600 border-b border-neutral-200 pb-3 font-serif flex items-center justify-between"> <span>By <strong class="text-neutral-900">{{ author }}</strong></span> <span>{{ date }}</span> </div> </div>
<!-- Columns layout --> <div class="toi-body text-base md:text-md text-justify space-y-4 columns-1 md:columns-2 gap-8"> {% for para in body.split('\n') %} {% if para.strip() %} <p class="mb-4 indent-4">{{ para.strip() }}</p> {% endif %} {% endfor %} </div>
<!-- CTA Talk to Tron Button --> <div class="border-t border-neutral-200 pt-8 flex flex-col sm:flex-row items-center justify-between gap-4"> <div class="text-xs text-neutral-500 font-serif italic"> * This investigative report includes a voice-activated assistant grounded in local research. </div> <button id="btn-talk-to-tron" class="w-full sm:w-auto px-6 py-3.5 rounded-xl bg-gradient-to-r from-neutral-900 to-slate-800 hover:from-neutral-800 hover:to-slate-700 text-white font-semibold text-sm flex items-center justify-center space-x-3 transition-all shadow-lg shadow-neutral-900/10 active:scale-95"> <svg class="w-5 h-5 text-cyan-400 animate-pulse" fill="currentColor" viewBox="0 0 24 24"><path d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3z"/><path d="M17 11c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z"/></svg> <span>Talk to Tron</span> </button> </div> </article> </main>
<!-- Side Drawer Popup overlay --> <div id="side-drawer" class="fixed inset-y-0 right-0 w-full sm:w-[420px] bg-slate-950 border-l border-slate-800 z-50 transform translate-x-full transition-transform duration-300 ease-out shadow-2xl flex flex-col justify-between text-slate-100 hidden"> <!-- Drawer Header --> <div class="p-6 border-b border-slate-900 flex items-center justify-between bg-slate-950/80 backdrop-blur-md"> <div class="flex items-center space-x-3"> <span class="relative flex h-3 w-3"> <span id="status-pulse" class="animate-ping absolute inline-flex h-full w-full rounded-full bg-cyan-400 opacity-75"></span> <span id="status-dot" class="relative inline-flex rounded-full h-3 w-3 bg-cyan-500"></span> </span> <div> <h3 class="font-bold text-sm tracking-wide">TRON ASSISTANT</h3> <p id="connection-status" class="text-[10px] text-slate-400 font-semibold uppercase">Connecting...</p> </div> </div> <button id="btn-close-drawer" class="text-slate-500 hover:text-white transition-colors p-1.5 rounded-lg hover:bg-slate-900"> <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg> </button> </div>
<!-- Drawer Content --> <div class="flex-1 overflow-y-auto p-6 space-y-6 flex flex-col justify-between custom-scrollbar"> <!-- Visualizer Container --> <div class="flex flex-col items-center justify-center py-6 bg-slate-900/30 border border-slate-900 rounded-2xl relative overflow-hidden"> <canvas id="visualizer-canvas" class="w-full h-44"></canvas> <div id="orb-label" class="absolute bottom-4 text-[10px] text-slate-500 font-bold tracking-widest uppercase">Voice Orb Activator</div> </div>
<!-- Notes Section (Dynamic) --> <div id="note-container" class="hidden animate-bounce mt-2"> <a id="btn-download-note" href="#" target="_blank" class="w-full py-3.5 px-4 rounded-xl bg-gradient-to-r from-emerald-500 to-teal-600 hover:from-emerald-600 hover:to-teal-700 text-white font-bold text-xs uppercase tracking-wider flex items-center justify-center space-x-2 transition-all shadow-lg shadow-emerald-500/20 active:scale-95"> <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg> <span id="note-btn-label">Download Requested Note</span> </a> </div>
<!-- Text Input Option --> <div class="space-y-2 mt-4"> <label class="text-[10px] text-slate-500 font-bold uppercase tracking-wider">Type Your Question</label> <div class="flex gap-2"> <input id="input-chat" type="text" placeholder="Type a question or correction..." class="flex-1 bg-slate-900 border border-slate-800 rounded-xl px-4 py-2.5 text-xs text-slate-100 placeholder-slate-500 focus:outline-none focus:border-cyan-500 transition-colors" /> <button id="btn-send-chat" class="px-4 py-2.5 rounded-xl bg-cyan-600 hover:bg-cyan-700 text-white font-bold text-xs transition-all active:scale-95 flex items-center justify-center"> <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"/></svg> </button> </div> </div>
<!-- Transcripts area --> <div class="space-y-2 flex-1 flex flex-col justify-end mt-4"> <label class="text-[10px] text-slate-500 font-bold uppercase tracking-wider">Live Logs / Transcripts</label> <div id="transcript-box" class="h-48 overflow-y-auto bg-slate-950 border border-slate-900 rounded-xl p-4 text-xs font-mono text-slate-300 space-y-3 custom-scrollbar flex flex-col justify-start"> <div class="text-slate-600 italic">No dialogue yet. Click Activate to talk.</div> </div> </div>
<!-- Dispute email notification banner --> <div id="dispute-banner" class="hidden bg-red-950/40 border border-red-900/60 rounded-xl p-3 text-[11px] text-red-300 flex items-start space-x-2"> <svg class="w-4 h-4 text-red-400 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/></svg> <div> <span class="font-bold">Editorial Dispute Sent:</span> Alerts containing reader suggested corrections have been dispatched to the editorial desk. </div> </div> </div>
<!-- Drawer Footer Controls --> <div class="p-6 border-t border-slate-900 bg-slate-950/80 backdrop-blur-md flex items-center justify-between gap-4"> <!-- Mute/Unmute microphone button --> <button id="btn-toggle-mic" class="flex-1 py-3 px-4 rounded-xl bg-slate-900 border border-slate-800 text-slate-300 hover:text-white font-semibold text-xs flex items-center justify-center space-x-2 transition-all active:scale-95"> <svg id="mic-icon-on" class="w-4 h-4 text-cyan-400" fill="currentColor" viewBox="0 0 24 24"><path d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3z"/><path d="M17 11c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z"/></svg> <svg id="mic-icon-off" class="w-4 h-4 text-red-500 hidden" fill="currentColor" viewBox="0 0 24 24"><path d="M19 11h-1.7c0 .74-.16 1.43-.43 2.05l1.23 1.23c.56-.98.9-2.09.9-3.28zm-4.02.17l-1.98-1.98V5c0-1.66-1.34-3-3-3S7 3.34 7 5v.18L8.82 7h-.02v4c0 .32.07.62.17.9l-1.98-1.98c.56-.98.9-2.09.9-3.28zm-5.98 5.75c1.39.81 3.03 1.08 4.67.75l1.45 1.45c-2.31.75-4.83.43-6.92-.9L7 16.92zm11.97 3.05L5.12 5.12 3.88 6.38l4.47 4.47v.15c0 2.76 2.24 5 5 5 .59 0 1.15-.12 1.67-.31l3.52 3.52 1.24-1.24zM12 18c-3.31 0-6-2.69-6-6h2c0 2.21 1.79 4 4 4 .43 0 .83-.09 1.21-.24l1.52 1.52C13.88 17.76 13 18 12 18z"/></svg> <span id="mic-label">Listening</span> </button>
<!-- Disconnect session --> <button id="btn-disconnect" class="py-3 px-5 rounded-xl bg-red-950/40 hover:bg-red-900 border border-red-900 text-red-300 hover:text-white font-semibold text-xs transition-all active:scale-95"> Stop </button> </div> </div>
<!-- Backdrop overlay --> <div id="drawer-backdrop" class="fixed inset-0 bg-slate-950/50 backdrop-blur-sm z-40 hidden"></div>
<!-- Footer --> <footer class="border-t border-slate-200 py-6 text-center text-xs text-neutral-500 bg-white"> <p>© 2026 TRON News Assistant Prototype. Powered by Gemini Multimodal Live API.</p> </footer>
<!-- Interactive script for voice capture & WebSocket streaming --> <script> const btnTalkToTron = document.getElementById('btn-talk-to-tron'); const sideDrawer = document.getElementById('side-drawer'); const btnCloseDrawer = document.getElementById('btn-close-drawer'); const btnDisconnect = document.getElementById('btn-disconnect'); const drawerBackdrop = document.getElementById('drawer-backdrop'); const connectionStatus = document.getElementById('connection-status'); const statusPulse = document.getElementById('status-pulse'); const statusDot = document.getElementById('status-dot'); const transcriptBox = document.getElementById('transcript-box'); const btnToggleMic = document.getElementById('btn-toggle-mic'); const micIconOn = document.getElementById('mic-icon-on'); const micIconOff = document.getElementById('mic-icon-off'); const micLabel = document.getElementById('mic-label'); const noteContainer = document.getElementById('note-container'); const btnDownloadNote = document.getElementById('btn-download-note'); const noteBtnLabel = document.getElementById('note-btn-label'); const disputeBanner = document.getElementById('dispute-banner'); const inputChat = document.getElementById('input-chat'); const btnSendChat = document.getElementById('btn-send-chat');
const canvas = document.getElementById('visualizer-canvas'); const ctx = canvas.getContext('2d');
let socket = null; let isListening = false; let mediaStream = null; let audioContext = null; let scriptProcessor = null; let animationFrameId = null; let nextPlayTime = 0; let activeSources = []; let averageVolume = 0; // shared variable for orb visualizer let isModelSpeaking = true; let analyser = null; let playbackAnalyser = null; let liveCaptionEl = null;
// Resample Float32 array to 16000Hz and convert to Int16 PCM ArrayBuffer function resampleAndConvertToInt16(buffer, inputSampleRate) { const targetSampleRate = 16000; let resultBuffer = buffer; if (inputSampleRate !== targetSampleRate) { const ratio = inputSampleRate / targetSampleRate; const newLength = Math.round(buffer.length / ratio); const resampled = new Float32Array(newLength); for (let i = 0; i < newLength; i++) { const index = Math.round(i * ratio); resampled[i] = index < buffer.length ? buffer[index] : 0; } resultBuffer = resampled; } let l = resultBuffer.length; let buf = new Int16Array(l); while (l--) { // Apply a 4.0x software gain multiplier to boost quiet microphone inputs let s = Math.max(-1, Math.min(1, resultBuffer[l] * 4.0)); buf[l] = Math.round(s < 0 ? s * 0x8000 : s * 0x7FFF); } return buf.buffer; }
// Open drawer UI btnTalkToTron.addEventListener('click', () => { sideDrawer.classList.remove('hidden'); drawerBackdrop.classList.remove('hidden'); setTimeout(() => { sideDrawer.classList.remove('translate-x-full'); }, 10); initSession(); visualizeOrb(); });
// Close drawer UI function closeDrawer() { sideDrawer.classList.add('translate-x-full'); drawerBackdrop.classList.add('hidden'); setTimeout(() => { sideDrawer.classList.add('hidden'); }, 300); disconnectSession(); if (animationFrameId) { cancelAnimationFrame(animationFrameId); animationFrameId = null; } ctx.clearRect(0, 0, canvas.width, canvas.height); }
btnCloseDrawer.addEventListener('click', closeDrawer); btnDisconnect.addEventListener('click', closeDrawer); drawerBackdrop.addEventListener('click', closeDrawer);
// Mute/Unmute mic toggle btnToggleMic.addEventListener('click', () => { isListening = !isListening; if (isListening) { micIconOn.classList.remove('hidden'); micIconOff.classList.add('hidden'); micLabel.textContent = "Listening"; btnToggleMic.className = "flex-1 py-3 px-4 rounded-xl bg-slate-900 border border-slate-800 text-slate-300 hover:text-white font-semibold text-xs flex items-center justify-center space-x-2 transition-all active:scale-95"; setStatus("Listening...", "cyan"); } else { micIconOn.classList.add('hidden'); micIconOff.classList.remove('hidden'); micLabel.textContent = "Muted"; btnToggleMic.className = "flex-1 py-3 px-4 rounded-xl bg-red-950/40 border border-red-950 text-red-400 hover:text-white font-semibold text-xs flex items-center justify-center space-x-2 transition-all active:scale-95"; setStatus("Muted", "red"); } });
// Send text query message async function sendChatMessage() { const text = inputChat.value.trim(); if (!text) return; if (socket && socket.readyState === WebSocket.OPEN) { // Immediately commit text to transcripts visually updateLiveCaption('user', text, true); // Send text packet via WebSocket socket.send(JSON.stringify({ type: 'input_text', text: text })); inputChat.value = ''; } else { appendLog("Cannot send message: Not connected to TRON server.", true); } }
btnSendChat.addEventListener('click', sendChatMessage); inputChat.addEventListener('keydown', (e) => { if (e.key === 'Enter') { sendChatMessage(); } });
function setStatus(text, color) { connectionStatus.textContent = text; if (color === 'cyan') { statusPulse.className = "animate-ping absolute inline-flex h-full w-full rounded-full bg-cyan-400 opacity-75"; statusDot.className = "relative inline-flex rounded-full h-3 w-3 bg-cyan-500"; } else if (color === 'indigo') { statusPulse.className = "animate-ping absolute inline-flex h-full w-full rounded-full bg-indigo-400 opacity-75"; statusDot.className = "relative inline-flex rounded-full h-3 w-3 bg-indigo-500"; } else if (color === 'red') { statusPulse.className = "hidden"; statusDot.className = "relative inline-flex rounded-full h-3 w-3 bg-red-500"; } }
function appendLog(text, isModel = false) { // Remove empty placeholder if (transcriptBox.innerHTML.includes('No dialogue yet')) { transcriptBox.innerHTML = ''; } const wrapper = document.createElement('div'); wrapper.className = isModel ? "text-cyan-400 font-semibold" : "text-slate-400"; wrapper.innerHTML = `<span class="text-slate-600">[${isModel ? 'TRON' : 'YOU'}]</span> ${text}`; transcriptBox.appendChild(wrapper); transcriptBox.scrollTop = transcriptBox.scrollHeight; }
function updateLiveCaption(role, text, isFinal) { if (transcriptBox.innerHTML.includes('No dialogue yet') || transcriptBox.innerHTML.includes('Tron is ready')) { transcriptBox.innerHTML = ''; }
if (!liveCaptionEl) { liveCaptionEl = document.createElement('div'); liveCaptionEl.id = 'live-caption'; transcriptBox.appendChild(liveCaptionEl); }
const roleColor = role === 'user' ? 'text-cyan-400' : 'text-indigo-400'; const roleName = role === 'user' ? 'You' : 'Tron'; liveCaptionEl.className = `${roleColor} font-medium border-l-2 border-current pl-2 py-0.5 my-1 animate-pulse`; liveCaptionEl.innerHTML = `<span class="opacity-60 text-[10px] uppercase font-bold tracking-wider mr-1.5">${roleName}:</span> ${text}`; transcriptBox.scrollTop = transcriptBox.scrollHeight;
if (isFinal) { liveCaptionEl.id = ''; liveCaptionEl.className = 'text-slate-300 py-1 border-b border-slate-900/50'; liveCaptionEl.innerHTML = `<span class="${role === 'user' ? 'text-cyan-500' : 'text-indigo-500'} font-semibold mr-1">${roleName}:</span> ${text}`; liveCaptionEl = null; } }
// Initialize Session async function initSession() { setStatus("Connecting...", "cyan"); transcriptBox.innerHTML = '<div class="text-slate-600 italic">Establishing connection to TRON server...</div>'; noteContainer.classList.add('hidden'); disputeBanner.classList.add('hidden'); isListening = true; isModelSpeaking = true; micIconOn.classList.remove('hidden'); micIconOff.classList.add('hidden'); micLabel.textContent = "Listening"; btnToggleMic.className = "flex-1 py-3 px-4 rounded-xl bg-slate-900 border border-slate-800 text-slate-300 hover:text-white font-semibold text-xs flex items-center justify-center space-x-2 transition-all active:scale-95";
// Initialize/Resume AudioContexts inside the direct user-gesture handler to prevent browser suspension try { if (!audioContext) { audioContext = new (window.AudioContext || window.webkitAudioContext)(); } if (audioContext.state === 'suspended') { await audioContext.resume(); } if (!audioCtxPlayback) { audioCtxPlayback = new (window.AudioContext || window.webkitAudioContext)({ sampleRate: 24000 }); nextPlayTime = audioCtxPlayback.currentTime; } if (audioCtxPlayback.state === 'suspended') { await audioCtxPlayback.resume(); } } catch (ae) { console.warn("Could not pre-initialize AudioContexts:", ae); }
try { // Setup WebSocket connection socket = new WebSocket(BACKEND_URL); socket.binaryType = 'arraybuffer';
socket.onopen = () => { setStatus("Sending config...", "indigo"); // Send Setup configurations immediately socket.send(JSON.stringify({ type: 'setup', voice: TRON_CONFIG.voice, system_instruction: TRON_CONFIG.system_instruction, greeting: TRON_CONFIG.greeting, document_context: TRON_CONFIG.document_context, silence_duration_ms: TRON_CONFIG.silence_duration_ms || 1000 })); };
socket.onmessage = async (event) => { if (event.data instanceof ArrayBuffer) { // Incoming 24kHz audio bytes from model const int16Array = new Int16Array(event.data); const float32Array = new Float32Array(int16Array.length); for (let i = 0; i < int16Array.length; i++) { float32Array[i] = int16Array[i] / 32768.0; } playAudioChunk(float32Array); setStatus("Speaking...", "indigo"); } else { // JSON text control messages try { const msg = JSON.parse(event.data); if (msg.type === 'transcript') { appendLog(msg.text, true); } else if (msg.type === 'interim_input_transcription') { updateLiveCaption('user', msg.text, false); } else if (msg.type === 'input_transcription') { updateLiveCaption('user', msg.text, true); } else if (msg.type === 'output_transcription') { updateLiveCaption('model', msg.text, msg.finished); } else if (msg.type === 'interrupted') { stopAllAudio(); appendLog("<em class='text-red-400'>[Interrupted]</em>", true); setStatus("Listening...", "cyan"); } else if (msg.type === 'document_ready') { noteBtnLabel.textContent = `Download: ${msg.subject}`; btnDownloadNote.href = msg.download_url; noteContainer.classList.remove('hidden'); const isSandbox = window.self !== window.top; let msgHtml = `<span class='text-emerald-400 font-bold'>✓ Word Document Generated!</span> Auto-downloading...`; if (isSandbox) { const directUrl = window.location.origin; msgHtml += `<br/><span class='text-amber-400 text-[11px] font-medium'>⚠️ Note: Embedded sandboxed web frames block automatic downloads. Please open the direct page to download: <a href="${directUrl}" target="_blank" class="underline font-bold text-cyan-300">${directUrl}</a></span>`; } else { msgHtml += ` (Or click download inside drawer).`; } appendLog(msgHtml, true); // Automatically trigger download in browser try { const a = document.createElement('a'); a.href = msg.download_url; a.download = msg.subject || 'document.docx'; document.body.appendChild(a); a.click(); document.body.removeChild(a); } catch (downloadErr) { console.error("Auto-download failed:", downloadErr); } } else if (msg.type === 'dispute_triggered') { disputeBanner.classList.remove('hidden'); appendLog(`<span class='text-red-400 font-bold'>⚠️ dispute filed:</span> "${msg.suggested_correction}" (over "${msg.original_fact}"). Alert dispatched.`, true); } else if (msg.type === 'model_speaking') { if (msg.speaking) { isModelSpeaking = true; setStatus("Speaking...", "indigo"); } else { // Add a 500ms delay before unmuting microphone to avoid capturing self-echo setTimeout(() => { isModelSpeaking = false; if (isListening) { setStatus("Listening...", "cyan"); } }, 500); } } else if (msg.type === 'ready') { setStatus("Listening...", "cyan"); transcriptBox.innerHTML = '<div class="text-slate-500 italic">Tron is ready. Speak now.</div>'; startMicrophone(); } } catch (err) { console.error("Failed to parse JSON text WebSocket message:", err); } } };
socket.onclose = () => { setStatus("Offline", "red"); appendLog("Connection to server closed."); stopMicrophone(); stopAllAudio(); };
socket.onerror = (err) => { console.error("WebSocket Error:", err); setStatus("Error", "red"); appendLog("A WebSocket connection error occurred."); };
} catch (err) { console.error("Microphone or WebSocket initialization failed:", err); setStatus("Error", "red"); appendLog("Error: " + err.message); } }
// Disconnect Session function disconnectSession() { if (socket) { socket.close(); socket = null; } stopMicrophone(); stopAllAudio(); if (audioContext) { audioContext.close().catch(()=>{}); audioContext = null; } playbackAnalyser = null; liveCaptionEl = null; }
// Audio Capturing async function startMicrophone() { try { mediaStream = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true } }); if (!audioContext) { audioContext = new (window.AudioContext || window.webkitAudioContext)(); } if (audioContext.state === 'suspended') { await audioContext.resume(); } const source = audioContext.createMediaStreamSource(mediaStream); // Analyser node for local orb visualization analyser = audioContext.createAnalyser(); analyser.fftSize = 256; source.connect(analyser); scriptProcessor = audioContext.createScriptProcessor(2048, 1, 1); source.connect(scriptProcessor); scriptProcessor.connect(audioContext.destination); scriptProcessor.onaudioprocess = (e) => { if (socket && socket.readyState === WebSocket.OPEN && isListening && !isModelSpeaking) { const inputData = e.inputBuffer.getChannelData(0); const pcmBuffer = resampleAndConvertToInt16(inputData, audioContext.sampleRate); socket.send(pcmBuffer); } }; } catch (err) { console.error("Failed to capture mic:", err); appendLog("Microphone Access Blocked or Not Found."); } } function stopMicrophone() { if (scriptProcessor) { scriptProcessor.disconnect(); scriptProcessor = null; } if (mediaStream) { mediaStream.getTracks().forEach(track => track.stop()); mediaStream = null; } analyser = null; };
// Playback incoming audio chunks function playAudioChunk(float32Array) { if (!audioContext) { audioContext = new (window.AudioContext || window.webkitAudioContext)(); nextPlayTime = audioContext.currentTime; }
if (audioContext.state === 'suspended') { audioContext.resume(); }
if (!playbackAnalyser) { playbackAnalyser = audioContext.createAnalyser(); playbackAnalyser.fftSize = 256; playbackAnalyser.connect(audioContext.destination); }
const buffer = audioContext.createBuffer(1, float32Array.length, 24000); buffer.copyToChannel(float32Array, 0);
const source = audioContext.createBufferSource(); source.buffer = buffer; source.connect(playbackAnalyser);
activeSources.push(source); source.onended = () => { activeSources = activeSources.filter(s => s !== source); if (activeSources.length === 0 && isListening) { setStatus("Listening...", "cyan"); } };
const currentTime = audioContext.currentTime; if (nextPlayTime < currentTime) { nextPlayTime = currentTime; } source.start(nextPlayTime); nextPlayTime += buffer.duration; }
function stopAllAudio() { activeSources.forEach(source => { try { source.stop(); } catch (e) {} }); activeSources = []; if (audioContext) { nextPlayTime = audioContext.currentTime; } }
// Pulse Orb Visualizer logic function visualizeOrb() { const bufferLength = 128; const dataArray = new Uint8Array(bufferLength);
function draw() { animationFrameId = requestAnimationFrame(draw);
let activeAnalyser = null; if (activeSources.length > 0 && playbackAnalyser) { activeAnalyser = playbackAnalyser; } else if (isListening && !isModelSpeaking && analyser) { activeAnalyser = analyser; }
if (activeAnalyser) { activeAnalyser.getByteFrequencyData(dataArray); let sum = 0; for (let i = 0; i < bufferLength; i++) { sum += dataArray[i]; } const average = sum / bufferLength; // 0 to 255 averageVolume = averageVolume * 0.8 + average * 0.2; } else { averageVolume = averageVolume * 0.95; }
const width = canvas.width = canvas.clientWidth; const height = canvas.height = canvas.clientHeight; const centerX = width / 2; const centerY = height / 2;
ctx.clearRect(0, 0, width, height);
// Pulse factor let pulse = averageVolume * 0.55; if (pulse < 0.5) { // Gentle breathing effect when quiet pulse = (Math.sin(Date.now() / 400) + 1.0) * 1.5; } const baseRadius = 40 + pulse;
// Outer neon aura glow const gradient = ctx.createRadialGradient( centerX, centerY, baseRadius * 0.2, centerX, centerY, baseRadius * 1.5 ); if (isListening && activeSources.length === 0) { // CYAN listening state gradient.addColorStop(0, 'rgba(6, 182, 212, 0.9)'); gradient.addColorStop(0.3, 'rgba(6, 182, 212, 0.4)'); gradient.addColorStop(0.8, 'rgba(16, 185, 129, 0.1)'); gradient.addColorStop(1, 'rgba(0,0,0,0)'); } else if (activeSources.length > 0) { // INDIGO speaking state gradient.addColorStop(0, 'rgba(99, 102, 241, 0.9)'); gradient.addColorStop(0.3, 'rgba(168, 85, 247, 0.4)'); gradient.addColorStop(0.8, 'rgba(236, 72, 153, 0.1)'); gradient.addColorStop(1, 'rgba(0,0,0,0)'); } else { // RED muted state gradient.addColorStop(0, 'rgba(239, 68, 68, 0.7)'); gradient.addColorStop(0.4, 'rgba(239, 68, 68, 0.2)'); gradient.addColorStop(1, 'rgba(0,0,0,0)'); }
ctx.fillStyle = gradient; ctx.beginPath(); ctx.arc(centerX, centerY, baseRadius * 1.5, 0, 2 * Math.PI); ctx.fill();
// Inner core orb ctx.shadowBlur = 25; if (isListening && activeSources.length === 0) { ctx.shadowColor = '#22d3ee'; // cyan-400 ctx.fillStyle = '#ffffff'; } else if (activeSources.length > 0) { ctx.shadowColor = '#a855f7'; // purple-500 ctx.fillStyle = '#f8fafc'; } else { ctx.shadowColor = '#ef4444'; // red-500 ctx.fillStyle = '#fca5a5'; }
ctx.beginPath(); ctx.arc(centerX, centerY, baseRadius, 0, 2 * Math.PI); ctx.fill(); ctx.shadowBlur = 0; // reset }
draw(); } </script></body></html>article_template.htmlAdded+762