Spaces:
Running
Running
Update live.html
Browse files4 unmodified lines56789101134 unmodified lines46474849505152106 unmodified lines15916016116216316416516616716816917017117217314 unmodified lines1881891901911921931941951961971981992002012022032042052062072082092102 unmodified lines2132142152162172182192202212226 unmodified lines22923023123223323423511 unmodified lines24724824925025125225312 unmodified lines2662672682692702712722732742752762 unmodified lines2792802812822832842858 unmodified lines29429529629729829930011 unmodified lines3123133143153163173189 unmodified lines32832933033133233333433533633733833923 unmodified lines3633643653663673683696 unmodified lines3763773783793803813826 unmodified lines38939039139239339439549 unmodified lines4454464474484494504511 unmodified line45345445545645745845921 unmodified lines4814824834844854864877 unmodified lines49549649749849950050133 unmodified lines5355365375385395405415425435445455464 unmodified lines<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"><title>Gemini Live</title><link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Devanagari:wght@300;400;500&family=Sora:wght@300;500&display=swap" rel="stylesheet"><!-- Added localForage for History Vault compatibility --><script src="https://cdnjs.cloudflare.com/ajax/libs/localforage/1.10.0/localforage.min.js"></script><style>:root{--c1:#5ef2d6;--c2:#8b7bff;--ink:#eef1ff;--dim:#8d96c4;--lv:0}34 unmodified lines#pill{flex:1;min-width:0;height:62px;border-radius:34px;position:relative;overflow:hidden;color:var(--dim);font-size:13px;border:1px solid color-mix(in srgb,var(--c1) 35%,#ffffff10);background:radial-gradient(120% 150% at 50% 140%,color-mix(in srgb,var(--c2) 55%,#0a1a4a),#04060f 70%);box-shadow:0 0 calc(10px + var(--lv)*52px) color-mix(in srgb,var(--c1) 50%,transparent),inset 0 -10px 24px color-mix(in srgb,var(--c2) 30%,transparent);transition:border-color .6s}#pill::after{content:"";position:absolute;inset:0;background:linear-gradient(110deg,transparent 30%,#ffffff20 50%,transparent 70%);transform:translateX(-100%);animation:sweep 3.6s ease-in-out infinite}@keyframes sweep{60%,100%{transform:translateX(100%)}}#bars{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;gap:5px;opacity:0;transition:opacity .4s}#bars i{width:5px;height:6px;border-radius:5px;background:linear-gradient(var(--c1),var(--c2))}106 unmodified linesnofl:'This camera has no flashlight. Try the back camera.',nocam:'Could not start the camera. Check permission.',nomic:'No sound from your mic. Pick the right one in Settings.',mutedT:'Mic muted',unmutedT:'Mic on',lang:'AI speaks',mode:'Voice input',mic:'Microphone',brow:'Browser',nat:'Native',err:'Connecting… send again in a moment'};let LANG='hi';try{LANG=localStorage.getItem('ailang')||'hi'}catch{}const T=k=>TXT[k]||'';const SR=window.SpeechRecognition||window.webkitSpeechRecognition;// 1. DEFAULT MIC INPUT IS NOW NATIVE (DEVICE)let MODE='native';// HISTORY TRACKING VARSlet liveSessionId = Date.now().toString();let currentInteractions = [];let interactionCount = 0;14 unmodified lines$('modeh').style.display=$('modeseg').style.display=SR?'':'none';refreshStatus();}// 2. SAVING HISTORY CORE LOGICasync function saveToHistory() {if (interactionCount < 2) return;try {let history = await localforage.getItem('aiHistory') || [];let existingIdx = history.findIndex(h => String(h.id) === String(liveSessionId));let title = "Live Conversation";if (currentInteractions.length > 0 && currentInteractions[0].question) {title = currentInteractions[0].question.substring(0, 50);}let sessionObj = {id: liveSessionId,type: 'live',title: title,interactions: currentInteractions,timestamp: Date.now()};if (existingIdx >= 0) {2 unmodified lineshistory.unshift(sessionObj);}await localforage.setItem('aiHistory', history);} catch (e) { console.error("History save error", e); }}/* ---------- captions ---------- */const caps=()=>[$('cap'),$('camcap')];function statusText(){if(!active)return T('idle');if(muted&&(state==='listening'||state==='idle'))return T('muted');return T(state)||''}function capSet(text,cls){caps().forEach(e=>{e.className=cls;e.textContent=text})}6 unmodified liness.textContent=w;e.appendChild(s);});// DOM OPTIMIZATION: Cap maximum visible words in the live caption to prevent lag over long periodswhile(e.childNodes.length > 60) {e.removeChild(e.firstChild);}11 unmodified linesif(MODE==='stt'&&active){if(s==='speaking')stopRec();else if(s==='listening')startRec()}}/* ---------- written conversation ---------- */const chat=$('chat');function newLine(cls){const m=document.createElement('div');m.className='msg '+cls;m.innerHTML='<div class="who">'+(cls==='you'?'You':'Gemini')+'</div><div class="txt"></div>';chat.appendChild(m);chat.scrollTop=1e9;return m}12 unmodified linesfunction showTyping(){if(typing||botEl)return;typing=newLine('bot');typing.lastChild.innerHTML='<span class="dots"><i></i><i></i><i></i></span>'}function hideTyping(){if(typing){typing.remove();typing=null}}// 3. DOM LEAK LAG FIX: Squash spans at turn endfunction endTurn(){if(botEl){botEl.classList.remove('cursor');// Converts thousands of heavy span elements into one single lightweight text nodeif(botEl.lastChild) botEl.lastChild.innerHTML = botEl.lastChild.textContent;}botEl=null;2 unmodified linesfunction closeUserEl(){if(userEl){userEl.classList.remove('cursor');// Squash user node spans tooif(userEl.lastChild) userEl.lastChild.innerHTML = userEl.lastChild.textContent;userEl=null;}8 unmodified linesuserBuf='';ucapSet(text);// Track History InteractioncurrentInteractions.push({ question: text, answer: '', timestamp: Date.now() });interactionCount++;11 unmodified linesuserBuf+=t;ucapSet(userBuf);// Update History Interactionif(currentInteractions.length > 0) currentInteractions[currentInteractions.length - 1].question += t;newUserTurn();9 unmodified linesbotActive=true;capAdd(t);// Update History Interactionif(currentInteractions.length > 0) currentInteractions[currentInteractions.length - 1].answer += t;}function sendText(text){if(ws&&ws.readyState===1){sendFrame();ws.send(JSON.stringify({t:'text',text}));setState('thinking')}}/* ---------- browser speech recognition ---------- */function startRec(){if(MODE!=='stt'||!SR||!active||rec||muted)return;const r=new SR();rec=r;r.lang=LANG==='hi'?'hi-IN':'en-IN';r.continuous=true;r.interimResults=true;23 unmodified lines}function stopRec(){if(rec){const r=rec;rec=null;r.onend=null;try{r.abort()}catch{}}}/* ---------- audio out ---------- */function playPcm(buf){if(!outCtx)return;const i16=new Int16Array(buf),f=new Float32Array(i16.length);6 unmodified lines}function stopPlayback(){sources.forEach(s=>{try{s.stop()}catch{}});sources=[];nextT=0}/* ---------- microphone ---------- */let micId='';try{micId=localStorage.getItem('micId')||''}catch{}async function openMic(){try{return await navigator.mediaDevices.getUserMedia({audio:micId?{deviceId:{exact:micId}}:true})}6 unmodified lines}$('mics').onchange=e=>{micId=e.target.value;try{localStorage.setItem('micId',micId)}catch{}restart()};/* ---------- connection ---------- */async function start(){if(active||starting)return;try{await startInner()}catch(e){console.error(e);toast('Start failed: '+(e&&e.message||e),10000);stop()}}async function startInner(){starting=true;49 unmodified lines}function restart(){if(active){stop();setTimeout(start,400)}}/* ---------- mute ---------- */function toggleMute(){muted=!muted;if(stream)stream.getAudioTracks().forEach(t=>t.enabled=!muted);document.querySelectorAll('.mutebtn').forEach(b=>b.classList.toggle('muted',muted));1 unmodified linerefreshStatus();toast(T(muted?'mutedT':'unmutedT'));}/* ---------- camera ---------- */let camStream=null,camTimer=null,facing='user',torchOn=false;const cc=document.createElement('canvas');async function startCamStream(){if(camStream)camStream.getTracks().forEach(t=>t.stop());21 unmodified linescc.getContext('2d').drawImage(v,0,0,w,h);ws.send(JSON.stringify({t:'video',data:cc.toDataURL('image/jpeg',.6).split(',')[1]}));}/* ---------- wiring ---------- */$('pill').onclick=()=>{if(!active)start();else if(state==='speaking'){stopPlayback();setState('listening')}};$('bend').onclick=()=>{if(active)stop()};$('bmute').onclick=$('cmute').onclick=toggleMute;$('bcam').onclick=openCam;$('coff').onclick=closeCam;$('cflip').onclick=async()=>{facing=facing==='user'?'environment':'user';await startCamStream()};$('cflash').onclick=toggleTorch;7 unmodified linesdocument.querySelectorAll('#modeseg button').forEach(b=>b.onclick=()=>{MODE=b.dataset.m;applyLang();restart()});applyLang();/* ---------- background animation ---------- */const fx=$('fx'),f=fx.getContext('2d'),BARS=[...document.querySelectorAll('#bars i')];let FW,FH,t=0,smooth=0,ripples=[],lastState='';const buf=new Uint8Array(128),micBuf=new Uint8Array(64),DPR=()=>devicePixelRatio||1,avg=a=>a.reduce((x,y)=>x+y,0)/a.length;33 unmodified lines}frame();// 4. RESTORE OFFLINE SESSION LOGICdocument.addEventListener("DOMContentLoaded", () => {const urlParams = new URLSearchParams(window.location.search);const restoreId = urlParams.get('restore');if (restoreId) {$('textview').classList.add('on');$('textview').dataset.restored = "true"; // Prevents auto-connect until manual actionlocalforage.getItem('aiHistory').then(history => {if (history) {4 unmodified lines567891034 unmodified lines45464748495051106 unmodified lines15815916016116216316416516616716816917017117217317414 unmodified lines1891901911921931941951961971981992002012022032042052062072082092102112122132142152 unmodified lines2182192202212222232242252262276 unmodified lines23423523623723823911 unmodified lines25125225325425525612 unmodified lines2692702712722732742752762772 unmodified lines2802812822832842858 unmodified lines29429529629729829911 unmodified lines3113123133143153169 unmodified lines32632732832933033133233333433523 unmodified lines3593603613623633646 unmodified lines3713723733743753766 unmodified lines38338438538638738849 unmodified lines4384394404414424431 unmodified line44544644744844945021 unmodified lines4724734744754764777 unmodified lines48548648748848949033 unmodified lines5245255265275285295305315325335344 unmodified lines<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"><title>Gemini Live</title><link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Devanagari:wght@300;400;500&family=Sora:wght@300;500&display=swap" rel="stylesheet"><script src="https://cdnjs.cloudflare.com/ajax/libs/localforage/1.10.0/localforage.min.js"></script><style>:root{--c1:#5ef2d6;--c2:#8b7bff;--ink:#eef1ff;--dim:#8d96c4;--lv:0}34 unmodified lines#pill{flex:1;min-width:0;height:62px;border-radius:34px;position:relative;overflow:hidden;color:var(--dim);font-size:13px;border:1px solid color-mix(in srgb,var(--c1) 35%,#ffffff10);background:radial-gradient(120% 150% at 50% 140%,color-mix(in srgb,var(--c2) 55%,#0a1a4a),#04060f 70%);box-shadow:0 0 calc(10px + var(--lv)*52px) color-mix(in srgb,var(--c1) 50%,transparent),inset 0 -10px 24px color-mix(in srgb,var(--c2) 30%,transparent);transition:border-color .6s}#pill::after{content:"absolute;inset:0;background:linear-gradient(110deg,transparent 30%,#ffffff20 50%,transparent 70%);transform:translateX(-100%);animation:sweep 3.6s ease-in-out infinite}@keyframes sweep{60%,100%{transform:translateX(100%)}}#bars{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;gap:5px;opacity:0;transition:opacity .4s}#bars i{width:5px;height:6px;border-radius:5px;background:linear-gradient(var(--c1),var(--c2))}106 unmodified linesnofl:'This camera has no flashlight. Try the back camera.',nocam:'Could not start the camera. Check permission.',nomic:'No sound from your mic. Pick the right one in Settings.',mutedT:'Mic muted',unmutedT:'Mic on',lang:'AI speaks',mode:'Voice input',mic:'Microphone',brow:'Browser',nat:'Native',err:'Connecting… send again in a moment'};// FORCE DATABASE TO MATCH THE REST OF THE SUITElocalforage.config({ name: 'AI_Pro_Suite', storeName: 'massive_chat_history' });let LANG='hi';try{LANG=localStorage.getItem('ailang')||'hi'}catch{}const T=k=>TXT[k]||'';const SR=window.SpeechRecognition||window.webkitSpeechRecognition;let MODE='native';let liveSessionId = Date.now().toString();let currentInteractions = [];let interactionCount = 0;14 unmodified lines$('modeh').style.display=$('modeseg').style.display=SR?'':'none';refreshStatus();}async function saveToHistory() {if (interactionCount < 2) return;try {let history = await localforage.getItem('aiHistory') || [];let lsHistory = [];try { lsHistory = JSON.parse(localStorage.getItem('aiHistory') || '[]'); } catch(e){}if (lsHistory.length > history.length) history = lsHistory;let existingIdx = history.findIndex(h => String(h.id) === String(liveSessionId));let title = "Live Voice Session";if (currentInteractions.length > 0 && currentInteractions[0].question) {title = "🎙️ " + currentInteractions[0].question.substring(0, 50);}let sessionObj = {id: liveSessionId,type: 'live',title: title,interactions: JSON.parse(JSON.stringify(currentInteractions)),timestamp: Date.now()};if (existingIdx >= 0) {2 unmodified lineshistory.unshift(sessionObj);}await localforage.setItem('aiHistory', history);try { localStorage.setItem('aiHistory', JSON.stringify(history)); } catch(e) {}} catch (e) { console.error("History save error", e); }}const caps=()=>[$('cap'),$('camcap')];function statusText(){if(!active)return T('idle');if(muted&&(state==='listening'||state==='idle'))return T('muted');return T(state)||''}function capSet(text,cls){caps().forEach(e=>{e.className=cls;e.textContent=text})}6 unmodified liness.textContent=w;e.appendChild(s);});while(e.childNodes.length > 60) {e.removeChild(e.firstChild);}11 unmodified linesif(MODE==='stt'&&active){if(s==='speaking')stopRec();else if(s==='listening')startRec()}}const chat=$('chat');function newLine(cls){const m=document.createElement('div');m.className='msg '+cls;m.innerHTML='<div class="who">'+(cls==='you'?'You':'Gemini')+'</div><div class="txt"></div>';chat.appendChild(m);chat.scrollTop=1e9;return m}12 unmodified linesfunction showTyping(){if(typing||botEl)return;typing=newLine('bot');typing.lastChild.innerHTML='<span class="dots"><i></i><i></i><i></i></span>'}function hideTyping(){if(typing){typing.remove();typing=null}}function endTurn(){if(botEl){botEl.classList.remove('cursor');if(botEl.lastChild) botEl.lastChild.innerHTML = botEl.lastChild.textContent;}botEl=null;2 unmodified linesfunction closeUserEl(){if(userEl){userEl.classList.remove('cursor');if(userEl.lastChild) userEl.lastChild.innerHTML = userEl.lastChild.textContent;userEl=null;}8 unmodified linesuserBuf='';ucapSet(text);currentInteractions.push({ question: text, answer: '', timestamp: Date.now() });interactionCount++;11 unmodified linesuserBuf+=t;ucapSet(userBuf);if(currentInteractions.length > 0) currentInteractions[currentInteractions.length - 1].question += t;newUserTurn();9 unmodified linesbotActive=true;capAdd(t);if(currentInteractions.length > 0) currentInteractions[currentInteractions.length - 1].answer += t;}function sendText(text){if(ws&&ws.readyState===1){sendFrame();ws.send(JSON.stringify({t:'text',text}));setState('thinking')}}function startRec(){if(MODE!=='stt'||!SR||!active||rec||muted)return;const r=new SR();rec=r;r.lang=LANG==='hi'?'hi-IN':'en-IN';r.continuous=true;r.interimResults=true;23 unmodified lines}function stopRec(){if(rec){const r=rec;rec=null;r.onend=null;try{r.abort()}catch{}}}function playPcm(buf){if(!outCtx)return;const i16=new Int16Array(buf),f=new Float32Array(i16.length);6 unmodified lines}function stopPlayback(){sources.forEach(s=>{try{s.stop()}catch{}});sources=[];nextT=0}let micId='';try{micId=localStorage.getItem('micId')||''}catch{}async function openMic(){try{return await navigator.mediaDevices.getUserMedia({audio:micId?{deviceId:{exact:micId}}:true})}6 unmodified lines}$('mics').onchange=e=>{micId=e.target.value;try{localStorage.setItem('micId',micId)}catch{}restart()};async function start(){if(active||starting)return;try{await startInner()}catch(e){console.error(e);toast('Start failed: '+(e&&e.message||e),10000);stop()}}async function startInner(){starting=true;49 unmodified lines}function restart(){if(active){stop();setTimeout(start,400)}}function toggleMute(){muted=!muted;if(stream)stream.getAudioTracks().forEach(t=>t.enabled=!muted);document.querySelectorAll('.mutebtn').forEach(b=>b.classList.toggle('muted',muted));1 unmodified linerefreshStatus();toast(T(muted?'mutedT':'unmutedT'));}let camStream=null,camTimer=null,facing='user',torchOn=false;const cc=document.createElement('canvas');async function startCamStream(){if(camStream)camStream.getTracks().forEach(t=>t.stop());21 unmodified linescc.getContext('2d').drawImage(v,0,0,w,h);ws.send(JSON.stringify({t:'video',data:cc.toDataURL('image/jpeg',.6).split(',')[1]}));}$('pill').onclick=()=>{if(!active)start();else if(state==='speaking'){stopPlayback();setState('listening')}};$('bend').onclick=()=>{if(active)stop()};$('bmute').onclick=$('cmute').onclick=toggleMute;$('bcam').onclick=openCam;$('coff').onclick=closeCam;$('cflip').onclick=async()=>{facing=facing==='user'?'environment':'user';await startCamStream()};$('cflash').onclick=toggleTorch;7 unmodified linesdocument.querySelectorAll('#modeseg button').forEach(b=>b.onclick=()=>{MODE=b.dataset.m;applyLang();restart()});applyLang();const fx=$('fx'),f=fx.getContext('2d'),BARS=[...document.querySelectorAll('#bars i')];let FW,FH,t=0,smooth=0,ripples=[],lastState='';const buf=new Uint8Array(128),micBuf=new Uint8Array(64),DPR=()=>devicePixelRatio||1,avg=a=>a.reduce((x,y)=>x+y,0)/a.length;33 unmodified lines}frame();document.addEventListener("DOMContentLoaded", () => {const urlParams = new URLSearchParams(window.location.search);const restoreId = urlParams.get('restore');if (restoreId) {$('textview').classList.add('on');$('textview').dataset.restored = "true";localforage.getItem('aiHistory').then(history => {if (history) {
live.html+15-27