Spaces:
Sleeping
Sleeping
Download article_template.html from SimblyPaul/Tron: direct link, hf CLI and curl.
- Browser
- Download file 46.1 kB
-
https://huggingface.co/spaces/SimblyPaul/Tron/resolve/main/article_template.html
- Command line
-
hf download hf://spaces/SimblyPaul/Tron/article_template.html
-
curl -L -o article_template.html https://huggingface.co/spaces/SimblyPaul/Tron/resolve/main/article_template.html
46.1 kB
| <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> | |
| // Resolve backend URL dynamically to allow seamless localhost & remote access | |
| let rawBackendUrl = "{{ backend_url }}"; | |
| if (window.location.protocol === 'http:' || window.location.protocol === 'https:') { | |
| const currentHost = window.location.host; | |
| const wsScheme = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; | |
| // Replace baked host with browser's current host if accessing through localhost/HF | |
| rawBackendUrl = `${wsScheme}//${currentHost}/ws/live`; | |
| } | |
| const BACKEND_URL = rawBackendUrl; | |
| 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"> | |
| <!-- Security Notice for file:/// users --> | |
| <div id="file-protocol-warning" class="hidden bg-amber-500/10 border-b border-amber-500/20 px-4 py-2 text-[11px] text-amber-300 flex items-center justify-between"> | |
| <span class="flex items-center gap-1.5"> | |
| <svg class="w-4 h-4 text-amber-400 shrink-0" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/></svg> | |
| <span>For microphone access, open via <a id="link-direct-http" href="#" class="underline font-bold text-amber-200">http://localhost:49999</a></span> | |
| </span> | |
| </div> | |
| <!-- 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> | |
| <!-- Real-time Mic Activity Indicator --> | |
| <div id="mic-meter-container" class="absolute top-3 left-4 right-4 flex items-center justify-between text-[10px] font-mono"> | |
| <span id="voice-indicator-status" class="text-slate-400 flex items-center gap-1.5"> | |
| <span class="w-2 h-2 rounded-full bg-slate-600 inline-block" id="voice-dot"></span> | |
| <span id="voice-text">Mic ready</span> | |
| </span> | |
| <div class="w-24 h-1.5 bg-slate-800 rounded-full overflow-hidden border border-slate-700/50"> | |
| <div id="voice-level-bar" class="h-full bg-cyan-400 transition-all duration-75" style="width: 0%;"></div> | |
| </div> | |
| </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'); | |
| const voiceLevelBar = document.getElementById('voice-level-bar'); | |
| const voiceText = document.getElementById('voice-text'); | |
| const voiceDot = document.getElementById('voice-dot'); | |
| 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 = false; | |
| let analyser = null; | |
| let playbackAnalyser = null; | |
| let liveCaptionEl = null; | |
| // Hybrid VAD silence tracker | |
| let lastUserVoiceTime = 0; | |
| let hasSpokenInCurrentTurn = false; | |
| let vadCheckInterval = null; | |
| // Check if running directly via file:/// protocol and display warning | |
| if (window.location.protocol === 'file:') { | |
| const warningEl = document.getElementById('file-protocol-warning'); | |
| const linkDirect = document.getElementById('link-direct-http'); | |
| if (warningEl && linkDirect) { | |
| warningEl.classList.remove('hidden'); | |
| linkDirect.href = "http://127.0.0.1:49999/"; | |
| } | |
| } | |
| // 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--) { | |
| // Natural gain without 4.0x over-amplification | |
| let s = Math.max(-1, Math.min(1, resultBuffer[l])); | |
| buf[l] = Math.round(s < 0 ? s * 0x8000 : s * 0x7FFF); | |
| } | |
| return buf.buffer; | |
| } | |
| // Open drawer UI | |
| btnTalkToTron.addEventListener('click', async () => { | |
| sideDrawer.classList.remove('hidden'); | |
| drawerBackdrop.classList.remove('hidden'); | |
| setTimeout(() => { | |
| sideDrawer.classList.remove('translate-x-full'); | |
| }, 10); | |
| // Warm up and start audio immediately on user click gesture | |
| await initAudioContext(); | |
| await startMicrophone(); | |
| 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; | |
| } | |
| } | |
| // Pre-initialize and resume AudioContexts inside direct user interaction | |
| async function initAudioContext() { | |
| try { | |
| if (!audioContext) { | |
| audioContext = new (window.AudioContext || window.webkitAudioContext)({ sampleRate: 16000 }); | |
| } | |
| if (audioContext.state === 'suspended') { | |
| await audioContext.resume(); | |
| } | |
| nextPlayTime = audioContext.currentTime; | |
| } catch (ae) { | |
| console.warn("AudioContext init warning:", ae); | |
| } | |
| } | |
| // 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 = false; | |
| 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"; | |
| await initAudioContext(); | |
| try { | |
| // Generate a session ID if not already cached/existing | |
| if (!TRON_CONFIG.session_id) { | |
| TRON_CONFIG.session_id = 'session_' + Math.random().toString(36).substring(2, 15); | |
| } | |
| // Setup WebSocket connection with session tracking query parameters | |
| const queryParams = `?article_id=${encodeURIComponent(TRON_CONFIG.article_id || 'general')}&session_id=${encodeURIComponent(TRON_CONFIG.session_id)}`; | |
| const wsConnUrl = BACKEND_URL + queryParams; | |
| socket = new WebSocket(wsConnUrl); | |
| 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 | |
| isModelSpeaking = true; // Instantly block client microphone input to prevent feedback/interruption echo | |
| 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') { | |
| isModelSpeaking = msg.speaking; | |
| if (msg.speaking) { | |
| setStatus("Speaking...", "indigo"); | |
| } else { | |
| if (isListening) { | |
| setStatus("Listening...", "cyan"); | |
| } | |
| } | |
| } else if (msg.type === 'ready') { | |
| setStatus("Listening...", "cyan"); | |
| transcriptBox.innerHTML = '<div class="text-slate-500 italic">Tron is ready. You can speak now.</div>'; | |
| } | |
| } 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() { | |
| if (scriptProcessor || mediaStream) return; | |
| try { | |
| mediaStream = await navigator.mediaDevices.getUserMedia({ | |
| audio: { | |
| echoCancellation: true, | |
| noiseSuppression: true, | |
| autoGainControl: true | |
| } | |
| }); | |
| if (!audioContext) { | |
| audioContext = new (window.AudioContext || window.webkitAudioContext)({ sampleRate: 16000 }); | |
| } | |
| if (audioContext.state === 'suspended') { | |
| await audioContext.resume(); | |
| } | |
| const source = audioContext.createMediaStreamSource(mediaStream); | |
| // Analyser node for local orb & meter visualization | |
| analyser = audioContext.createAnalyser(); | |
| analyser.fftSize = 256; | |
| source.connect(analyser); | |
| // Audio processor: stream 16kHz PCM audio | |
| scriptProcessor = audioContext.createScriptProcessor(2048, 1, 1); | |
| source.connect(scriptProcessor); | |
| // Connect through silent gain to prevent audio loopback | |
| const silentGain = audioContext.createGain(); | |
| silentGain.gain.value = 0; | |
| scriptProcessor.connect(silentGain); | |
| silentGain.connect(audioContext.destination); | |
| // Hybrid VAD timer: Send audio_stream_end after 800ms of user silence | |
| if (!vadCheckInterval) { | |
| vadCheckInterval = setInterval(() => { | |
| if (socket && socket.readyState === WebSocket.OPEN && hasSpokenInCurrentTurn) { | |
| const timeSinceSpeech = Date.now() - lastUserVoiceTime; | |
| if (timeSinceSpeech > 850) { | |
| hasSpokenInCurrentTurn = false; | |
| try { | |
| socket.send(JSON.stringify({ type: 'audio_stream_end' })); | |
| if (voiceIndicatorStatus) { | |
| voiceIndicatorStatus.textContent = "Listening..."; | |
| } | |
| } catch (e) {} | |
| } | |
| } | |
| }, 200); | |
| } | |
| scriptProcessor.onaudioprocess = (e) => { | |
| if (socket && socket.readyState === WebSocket.OPEN && isListening) { | |
| const inputData = e.inputBuffer.getChannelData(0); | |
| // Calculate instant amplitude to track user voice activity | |
| let sumSquares = 0; | |
| for (let i = 0; i < inputData.length; i++) { | |
| sumSquares += inputData[i] * inputData[i]; | |
| } | |
| const rms = Math.sqrt(sumSquares / inputData.length); | |
| // Update voice meter | |
| const meterPercent = Math.min(100, Math.round(rms * 400)); | |
| if (voiceLevelBar) { | |
| voiceLevelBar.style.width = `${meterPercent}%`; | |
| } | |
| // Check if speaking above room threshold | |
| if (rms > 0.02) { | |
| lastUserVoiceTime = Date.now(); | |
| hasSpokenInCurrentTurn = true; | |
| if (voiceText) voiceText.textContent = "Hearing you..."; | |
| if (voiceDot) voiceDot.className = "w-2 h-2 rounded-full bg-emerald-400 animate-ping inline-block"; | |
| // If user speaks while TRON is talking, automatically interrupt TRON playback | |
| if (activeSources.length > 0) { | |
| stopAllAudio(); | |
| } | |
| } else { | |
| if (voiceText && Date.now() - lastUserVoiceTime > 600) { | |
| voiceText.textContent = activeSources.length > 0 ? "Tron speaking" : "Mic listening"; | |
| if (voiceDot) voiceDot.className = activeSources.length > 0 ? "w-2 h-2 rounded-full bg-indigo-400 inline-block" : "w-2 h-2 rounded-full bg-cyan-400 inline-block"; | |
| } | |
| } | |
| 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. Please ensure you are viewing via http://localhost:49999."); | |
| } | |
| } | |
| function stopMicrophone() { | |
| if (vadCheckInterval) { | |
| clearInterval(vadCheckInterval); | |
| vadCheckInterval = null; | |
| } | |
| if (scriptProcessor) { | |
| scriptProcessor.disconnect(); | |
| scriptProcessor = null; | |
| } | |
| if (mediaStream) { | |
| mediaStream.getTracks().forEach(track => track.stop()); | |
| mediaStream = null; | |
| } | |
| analyser = null; | |
| if (voiceLevelBar) voiceLevelBar.style.width = '0%'; | |
| }; | |
| // Playback incoming audio chunks | |
| function playAudioChunk(float32Array) { | |
| if (!audioContext) { | |
| audioContext = new (window.AudioContext || window.webkitAudioContext)({ sampleRate: 16000 }); | |
| 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; | |
| // Add a 150ms jitter buffer delay if starting a new playback stream or if the queue ran dry | |
| if (activeSources.length === 1 || nextPlayTime < currentTime) { | |
| nextPlayTime = currentTime + 0.15; | |
| } | |
| 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> | |