Aichatbot12321 commited on
Commit
10f410b
·
verified ·
1 Parent(s): 7104aa0

Upload 3 files

Browse files
Files changed (3) hide show
  1. gemini-live.js +159 -0
  2. live.html +404 -0
  3. server (79).js +0 -0
gemini-live.js ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Gemini Live voice + camera bridge for server.js
3
+ *
4
+ * Browser <--ws /live-ws--> this module <--wss--> Gemini Live API
5
+ *
6
+ * Keys: GEMINI_API_KEY_1 ... GEMINI_API_KEY_5 (or GEMINI_API_KEY). Tried in order if one fails.
7
+ * Env: GEMINI_LIVE_MODEL (default gemini-3.8-live), GEMINI_LIVE_VOICE (default Puck),
8
+ * GEMINI_LIVE_API_VERSION (default v1beta)
9
+ * Needs: npm i ws
10
+ */
11
+ const fs = require('fs');
12
+ const path = require('path');
13
+ const { WebSocketServer, WebSocket } = require('ws');
14
+
15
+ const MODEL = process.env.GEMINI_LIVE_MODEL || 'gemini-3.8-live';
16
+ const VOICE = process.env.GEMINI_LIVE_VOICE || 'Puck'; // Puck, Kore, Charon, Aoede, Fenrir...
17
+ const API_VERSION = process.env.GEMINI_LIVE_API_VERSION || 'v1beta';
18
+ const WS_PATH = '/live-ws';
19
+ const upstreamUrl = key => (process.env.GEMINI_LIVE_URL ||
20
+ `wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.${API_VERSION}.GenerativeService.BidiGenerateContent`) +
21
+ `?key=${key}`;
22
+
23
+ function apiKeys() {
24
+ const list = [1, 2, 3, 4, 5].map(i => process.env['GEMINI_API_KEY_' + i]).concat(process.env.GEMINI_API_KEY);
25
+ return [...new Set(list.filter(Boolean))];
26
+ }
27
+
28
+ const instruction = lang =>
29
+ (lang === 'hi'
30
+ ? 'You are a warm, friendly voice assistant. ALWAYS speak and reply in Hindi (हिन्दी) by default, in natural conversational Hindi; ' +
31
+ 'write any text in Devanagari. Only switch language if the user clearly speaks or asks in another language. '
32
+ : 'You are a warm, quick-witted voice assistant. Reply in English unless the user speaks another language. ') +
33
+ 'Keep answers short and natural. When the user\'s camera is on you receive live video frames: ' +
34
+ 'look at them and describe or reason about what you see whenever it is relevant.';
35
+
36
+ const greeting = lang => lang === 'hi'
37
+ ? 'कृपया हिंदी में एक छोटे से वाक्य में मुझे नमस्ते कहिए और पूछिए कि आप मेरी कैसे मदद कर सकते हैं।'
38
+ : 'Greet me with one short friendly sentence and invite me to speak.';
39
+
40
+ function setupMessage(compress, lang) {
41
+ const setup = {
42
+ model: MODEL.startsWith('models/') ? MODEL : 'models/' + MODEL,
43
+ generationConfig: {
44
+ responseModalities: ['AUDIO'],
45
+ speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: VOICE } } }
46
+ },
47
+ systemInstruction: { parts: [{ text: instruction(lang) }] },
48
+ inputAudioTranscription: {},
49
+ outputAudioTranscription: {}
50
+ };
51
+ if (compress) setup.contextWindowCompression = { slidingWindow: {} }; // lets camera sessions run longer than 2 minutes
52
+ return { setup };
53
+ }
54
+
55
+ function handleClient(ws, lang) {
56
+ const keys = apiKeys();
57
+ // every key with context compression, then one last try without it (same fallback as the old Python app)
58
+ const attempts = keys.map(key => ({ key, compress: true }));
59
+ if (keys.length) attempts.push({ key: keys[0], compress: false });
60
+
61
+ let up = null, ready = false, closed = false, next = 0, lastError = '';
62
+ let micSeen = false, camSeen = false, audioSeen = false;
63
+ const toBrowser = obj => { if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(obj)); };
64
+ const toGemini = obj => { if (up && up.readyState === WebSocket.OPEN) up.send(JSON.stringify(obj)); };
65
+ const realtime = input => toGemini({ realtimeInput: input });
66
+
67
+ const ping = setInterval(() => { if (ws.readyState === WebSocket.OPEN) ws.ping(); }, 25000); // keeps proxies from dropping idle sockets
68
+
69
+ function connect() {
70
+ if (closed) return;
71
+ const attempt = attempts[next++];
72
+ if (!attempt) {
73
+ toBrowser({ t: 'error', text: keys.length ? ('Could not connect to Gemini Live. ' + lastError).trim() : 'No Gemini API key found. Set GEMINI_API_KEY_1.' });
74
+ return ws.close();
75
+ }
76
+ const g = new WebSocket(upstreamUrl(attempt.key));
77
+ up = g;
78
+ g.on('open', () => g.send(JSON.stringify(setupMessage(attempt.compress, lang))));
79
+ g.on('message', raw => {
80
+ let m; try { m = JSON.parse(raw.toString()); } catch { return; }
81
+ onGemini(g, m);
82
+ });
83
+ g.on('error', e => failed(g, e.message));
84
+ g.on('close', (code, reason) => failed(g, `closed (${code}) ${reason}`.trim()));
85
+ }
86
+
87
+ function failed(g, why) {
88
+ if (g !== up || closed) return; // stale socket from an earlier attempt
89
+ lastError = why;
90
+ up = null;
91
+ try { g.terminate(); } catch { }
92
+ if (!ready) { console.log('Live: attempt failed, trying next:', why); return connect(); }
93
+ toBrowser({ t: 'error', text: 'Gemini disconnected. ' + why });
94
+ ws.close();
95
+ }
96
+
97
+ function onGemini(g, m) {
98
+ if (g !== up) return;
99
+ if (m.setupComplete) {
100
+ ready = true;
101
+ toBrowser({ t: 'ready', model: MODEL });
102
+ realtime({ text: greeting(lang) }); // instant proof the voice works
103
+ return;
104
+ }
105
+ const sc = m.serverContent;
106
+ if (!sc) return;
107
+ if (sc.inputTranscription && sc.inputTranscription.text) {
108
+ console.log('you :', sc.inputTranscription.text);
109
+ toBrowser({ t: 'user', text: sc.inputTranscription.text });
110
+ }
111
+ if (sc.outputTranscription && sc.outputTranscription.text) toBrowser({ t: 'bot', text: sc.outputTranscription.text });
112
+ for (const p of (sc.modelTurn && sc.modelTurn.parts) || []) {
113
+ if (p.inlineData && p.inlineData.data && ws.readyState === WebSocket.OPEN) { // 24 kHz PCM16
114
+ if (!audioSeen) { audioSeen = true; console.log('Live: Gemini is sending audio'); }
115
+ ws.send(Buffer.from(p.inlineData.data, 'base64'));
116
+ }
117
+ }
118
+ if (sc.interrupted) toBrowser({ t: 'interrupted' });
119
+ if (sc.turnComplete) toBrowser({ t: 'done' });
120
+ }
121
+
122
+ ws.on('message', (data, isBinary) => {
123
+ if (!ready) return;
124
+ if (isBinary) { // 16 kHz PCM16 mic audio (native mode)
125
+ if (!micSeen) { micSeen = true; console.log('Live: mic audio is arriving'); }
126
+ return realtime({ audio: { data: data.toString('base64'), mimeType: 'audio/pcm;rate=16000' } });
127
+ }
128
+ let d; try { d = JSON.parse(data.toString()); } catch { return; }
129
+ if (d.t === 'text' && d.text) { console.log('you (text):', d.text); realtime({ text: String(d.text) }); }
130
+ else if (d.t === 'video' && d.data) {
131
+ if (!camSeen) { camSeen = true; console.log('Live: camera frames are arriving'); }
132
+ realtime({ video: { data: d.data, mimeType: 'image/jpeg' } });
133
+ } else if (d.t === 'end') realtime({ audioStreamEnd: true });
134
+ });
135
+ ws.on('close', () => { closed = true; clearInterval(ping); if (up) try { up.terminate(); } catch { } });
136
+ ws.on('error', () => { });
137
+ connect();
138
+ }
139
+
140
+ /** Call once with the http.Server. Handles WebSocket upgrades on /live-ws. */
141
+ function attach(server) {
142
+ const wss = new WebSocketServer({ noServer: true, maxPayload: 16 * 1024 * 1024 });
143
+ server.on('upgrade', (req, socket, head) => {
144
+ const u = new URL(req.url, `http://${req.headers.host}`);
145
+ if (u.pathname !== WS_PATH) return socket.destroy();
146
+ wss.handleUpgrade(req, socket, head, ws => handleClient(ws, u.searchParams.get('lang') === 'en' ? 'en' : 'hi'));
147
+ });
148
+ }
149
+
150
+ /** GET /live -> the voice app page */
151
+ function servePage(req, res) {
152
+ fs.readFile(path.join(__dirname, 'live.html'), 'utf8', (err, html) => {
153
+ if (err) { res.writeHead(404); return res.end('live.html not found next to server.js'); }
154
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-cache' });
155
+ res.end(html);
156
+ });
157
+ }
158
+
159
+ module.exports = { attach, servePage };
live.html ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
6
+ <title>Gemini Live</title>
7
+ <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Devanagari:wght@300;400;500&family=Sora:wght@300;500&display=swap" rel="stylesheet">
8
+ <style>
9
+ :root{--c1:#5ef2d6;--c2:#8b7bff;--ink:#eef1ff;--dim:#8d96c4;--lv:0}
10
+ *{box-sizing:border-box;margin:0;-webkit-tap-highlight-color:transparent}
11
+ html,body{height:100%;background:#000;color:var(--ink);font-family:Sora,'Noto Sans Devanagari',system-ui,sans-serif;overflow:hidden}
12
+ body::before{content:"";position:fixed;inset:0;z-index:0;background:linear-gradient(180deg,#000 0%,#000 36%,#0a1030 70%,#16206b 100%)}
13
+ button{font:inherit;color:inherit;border:0;background:none;cursor:pointer}
14
+ button:focus-visible,input:focus-visible,select:focus-visible{outline:2px solid var(--c1);outline-offset:2px}
15
+ svg.i{width:24px;height:24px;stroke:currentColor;fill:none;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}
16
+ #fx{position:fixed;inset:0;width:100%;height:100%;z-index:1;pointer-events:none}
17
+ #app{position:relative;z-index:2;max-width:520px;height:100dvh;margin:0 auto;display:grid;grid-template-rows:auto 1fr auto;padding:env(safe-area-inset-top) 0 env(safe-area-inset-bottom);transition:opacity .45s,transform .45s}
18
+ body.camopen #app{opacity:0;pointer-events:none;transform:scale(.95)}
19
+ header{display:flex;justify-content:space-between;align-items:center;padding:16px 18px}
20
+ .ib{width:44px;height:44px;border-radius:50%;display:grid;place-items:center;transition:background .3s,transform .2s}
21
+ .ib:hover{background:#ffffff14}.ib:active{transform:scale(.9)}
22
+ #chip{display:flex;gap:8px;align-items:center;font-size:12px;color:var(--dim);padding:8px 14px;border-radius:20px;background:#ffffff0d;border:1px solid #ffffff12}
23
+ #dot{width:8px;height:8px;border-radius:50%;background:#555b7a;transition:.4s}
24
+ body.live #dot{background:var(--c1);box-shadow:0 0 12px var(--c1)}
25
+ #stage{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:22px;padding:0 24px;text-align:center;min-height:0}
26
+ #ucap,#camucap{font-size:15px;color:var(--dim);min-height:1.3em;max-width:92%}
27
+ #cap,#camcap{font-size:clamp(26px,7vw,38px);font-weight:300;line-height:1.38;max-height:46vh;overflow-y:auto;scrollbar-width:none;color:#e9ecfb}
28
+ body:not(.live) #cap{background:linear-gradient(90deg,#8d96c4,#fff,#8d96c4);background-size:220% 100%;-webkit-background-clip:text;background-clip:text;color:transparent;animation:shim 4.5s linear infinite}
29
+ @keyframes shim{to{background-position:-220% 0}}
30
+ #cap.status,#camcap.status{animation:breathe 2.4s ease-in-out infinite}
31
+ body.live #cap.status{color:#c9cff0}
32
+ @keyframes breathe{50%{opacity:.55}}
33
+ .w{display:inline-block;white-space:pre;animation:in .6s cubic-bezier(.2,.8,.2,1) both,glow 1.6s ease-out both}
34
+ @keyframes in{from{opacity:0;transform:translateY(10px);filter:blur(7px)}to{opacity:1;transform:none;filter:none}}
35
+ @keyframes glow{from{text-shadow:0 0 22px var(--c1)}to{text-shadow:none}}
36
+ #bar{display:flex;align-items:center;gap:10px;padding:12px 14px 22px}
37
+ .rb{flex:none;border-radius:50%;display:grid;place-items:center;border:1px solid #ffffff14;background:rgba(28,32,56,.72);backdrop-filter:blur(12px);transition:transform .18s,background .3s,box-shadow .3s,opacity .3s}
38
+ .rb:hover{box-shadow:0 0 20px color-mix(in srgb,var(--c1) 45%,transparent)}.rb:active{transform:scale(.88)}
39
+ .rb.big{width:58px;height:58px}.rb.sm{width:46px;height:46px}
40
+ .mutebtn.muted{background:#ff4d6d30;color:#ff8fa3;border-color:#ff4d6d70;animation:pulsered 1.6s ease-in-out infinite}
41
+ @keyframes pulsered{50%{box-shadow:0 0 22px #ff4d6d77}}
42
+ .mutebtn .ic-off,.mutebtn.muted .ic-mic{display:none}.mutebtn.muted .ic-off{display:block}
43
+ #bend{opacity:.45}#bend.on{opacity:1;background:rgba(80,30,50,.8)}
44
+ #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);
45
+ background:radial-gradient(120% 150% at 50% 140%,color-mix(in srgb,var(--c2) 55%,#0a1a4a),#04060f 70%);
46
+ 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}
47
+ #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}
48
+ @keyframes sweep{60%,100%{transform:translateX(100%)}}
49
+ #bars{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;gap:5px;opacity:0;transition:opacity .4s}
50
+ #bars i{width:5px;height:6px;border-radius:5px;background:linear-gradient(var(--c1),var(--c2))}
51
+ #pl{position:relative;z-index:1;transition:opacity .3s}
52
+ body.live #bars{opacity:1}body.live #pl{opacity:0}
53
+ #camview{position:fixed;inset:0;z-index:50;background:#000;opacity:0;pointer-events:none;transform:scale(1.05);transition:opacity .45s,transform .45s}
54
+ #camview.on{opacity:1;pointer-events:auto;transform:none}
55
+ #camv{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}
56
+ #camglow{position:absolute;inset:0;pointer-events:none;box-shadow:inset 0 0 calc(30px + var(--lv)*100px) color-mix(in srgb,var(--c1) 60%,transparent)}
57
+ #camtop{position:absolute;top:0;left:0;right:0;padding:calc(16px + env(safe-area-inset-top)) 16px 40px;background:linear-gradient(#000a,transparent)}
58
+ #live{display:inline-flex;gap:8px;align-items:center;padding:7px 14px;border-radius:20px;font-size:12px;background:#0007;backdrop-filter:blur(8px)}
59
+ #live::before{content:"";width:8px;height:8px;border-radius:50%;background:#ff4d6d;animation:blink 1s steps(2) infinite}
60
+ @keyframes blink{50%{opacity:.2}}
61
+ #cambot{position:absolute;left:0;right:0;bottom:0;padding:70px 18px calc(22px + env(safe-area-inset-bottom));background:linear-gradient(transparent,#000d);text-align:center}
62
+ #camcap{font-size:clamp(20px,5.4vw,28px);max-height:24vh;margin-bottom:16px;text-shadow:0 2px 12px #000}
63
+ #camucap{margin-bottom:6px;color:#cdd3f5}
64
+ #camctl{display:flex;justify-content:center;align-items:center;gap:18px}
65
+ .cb{width:54px;height:54px;border-radius:50%;display:grid;place-items:center;background:#ffffff1f;backdrop-filter:blur(14px);border:1px solid #ffffff2a;transition:transform .2s,background .3s}
66
+ .cb:active{transform:scale(.88)}.cb.on{background:#ffd54a;color:#1a1400}
67
+ #coff{width:68px;height:68px;background:linear-gradient(135deg,#ff4d6d,#c2185b);border:0;box-shadow:0 0 26px #ff4d6d77}
68
+ #textview{position:fixed;inset:0;z-index:60;display:flex;flex-direction:column;background:linear-gradient(180deg,#02040c,#0b1238 82%,#16206b);transform:translateY(102%);transition:transform .5s cubic-bezier(.2,.8,.2,1)}
69
+ #textview.on{transform:none}
70
+ #thead{display:flex;align-items:center;padding:calc(14px + env(safe-area-inset-top)) 70px 8px 18px;width:min(680px,100%);margin:0 auto}
71
+ #thead b{font-weight:500;font-size:18px}
72
+ #chat{flex:1;overflow-y:auto;width:min(680px,100%);margin:0 auto;padding:6px 18px;scrollbar-width:none}
73
+ #chat:empty::before{content:attr(data-empty);display:block;text-align:center;color:var(--dim);margin-top:30vh;font-size:15px}
74
+ .msg{margin:12px 0;max-width:88%;animation:pop .5s cubic-bezier(.2,.8,.2,1) both}
75
+ @keyframes pop{from{opacity:0;transform:translateY(12px) scale(.96)}to{opacity:1;transform:none}}
76
+ .you{margin-left:auto;text-align:right}
77
+ .you .txt{display:inline-block;padding:10px 15px;border-radius:18px 18px 4px 18px;background:linear-gradient(135deg,#2b3a8f,#4b3ba8);font-size:16px;text-align:left}
78
+ .bot .txt{font-size:18px;line-height:1.6;font-weight:300}
79
+ .who{font-size:11px;color:var(--dim);margin-bottom:3px}
80
+ .cursor .txt::after{content:"";display:inline-block;width:2px;height:1em;background:var(--c1);margin-left:3px;vertical-align:-3px;animation:blink 1s steps(2) infinite}
81
+ .dots i{display:inline-block;width:9px;height:9px;margin:6px 4px;border-radius:50%;background:var(--c1);animation:bn 1s ease-in-out infinite}
82
+ .dots i:nth-child(2){animation-delay:.15s;background:var(--c2)}.dots i:nth-child(3){animation-delay:.3s}
83
+ @keyframes bn{0%,100%{transform:translateY(0);opacity:.4}50%{transform:translateY(-8px);opacity:1}}
84
+ #tbar{display:flex;gap:10px;width:min(680px,100%);margin:0 auto;padding:10px 14px calc(18px + env(safe-area-inset-bottom))}
85
+ #typed{flex:1;min-width:0;padding:14px 18px;border-radius:28px;border:1px solid #ffffff22;background:#ffffff0f;color:var(--ink);font:inherit;font-size:16px;transition:border-color .3s,box-shadow .3s}
86
+ #typed:focus{border-color:var(--c1);box-shadow:0 0 20px color-mix(in srgb,var(--c1) 30%,transparent)}
87
+ #tsend{width:52px;height:52px;border-radius:50%;display:grid;place-items:center;background:linear-gradient(135deg,var(--c1),var(--c2));color:#06101a;transition:transform .2s}
88
+ #tsend:active{transform:scale(.88)}
89
+ #tclose{position:absolute;top:calc(12px + env(safe-area-inset-top));right:14px}
90
+ #menu{position:fixed;top:68px;left:12px;z-index:70;width:min(330px,calc(100vw - 24px));padding:16px;border-radius:22px;background:rgba(12,16,38,.93);backdrop-filter:blur(18px);border:1px solid #ffffff1c;opacity:0;transform:translateY(-10px) scale(.96);pointer-events:none;transition:.28s}
91
+ #menu.on{opacity:1;transform:none;pointer-events:auto}
92
+ #menu h4{font-size:12px;font-weight:400;color:var(--dim);margin:12px 0 6px}#menu h4:first-child{margin-top:0}
93
+ .seg{display:flex;gap:6px}.seg button{flex:1;padding:9px;border-radius:12px;background:#ffffff0d;border:1px solid #ffffff14;font-size:14px;transition:.25s}
94
+ .seg button.on{background:linear-gradient(135deg,var(--c1),var(--c2));color:#06101a;border-color:transparent}
95
+ #mics{width:100%;padding:9px;border-radius:12px;background:#101733;color:var(--ink);border:1px solid #ffffff1a;font:inherit;font-size:13px}
96
+ #meter{height:4px;border-radius:4px;background:#ffffff14;overflow:hidden;margin-top:8px}
97
+ #meter i{display:block;height:100%;background:linear-gradient(90deg,var(--c1),var(--c2));transform-origin:left;transform:scaleX(0);transition:transform .07s}
98
+ #diag{font-size:11px;color:var(--dim);margin-top:6px}
99
+ #toast{position:fixed;bottom:112px;left:50%;transform:translate(-50%,20px);z-index:90;padding:11px 18px;border-radius:16px;background:#1b2147ee;border:1px solid #ffffff1c;font-size:14px;max-width:88vw;text-align:center;opacity:0;pointer-events:none;transition:.35s}
100
+ #toast.on{opacity:1;transform:translate(-50%,0)}
101
+ @media(prefers-reduced-motion:reduce){*{animation:none!important}}
102
+ </style>
103
+ </head>
104
+ <body data-st="idle">
105
+ <canvas id="fx"></canvas>
106
+
107
+ <div id="app">
108
+ <header>
109
+ <button class="ib" id="bmenu" aria-label="Settings"><svg class="i" viewBox="0 0 24 24"><path d="M4 9h16M4 15h10"/></svg></button>
110
+ <div id="chip"><span id="dot"></span><span id="st">offline</span></div>
111
+ </header>
112
+ <section id="stage">
113
+ <div id="ucap"></div>
114
+ <div id="cap" class="status"></div>
115
+ </section>
116
+ <nav id="bar">
117
+ <button class="rb big" id="bcam" aria-label="Open camera"><svg class="i" viewBox="0 0 24 24"><path d="m16 13 5.22 3.48a.5.5 0 0 0 .78-.42V7.94a.5.5 0 0 0-.78-.42L16 11"/><rect x="2" y="6" width="14" height="12" rx="2"/></svg></button>
118
+ <button class="rb sm" id="btext" aria-label="Type a message"><svg class="i" viewBox="0 0 24 24"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/><path d="M8 9h8M8 13h5"/></svg></button>
119
+ <button id="pill" aria-label="Start conversation"><span id="pl" data-t="tap"></span><span id="bars"><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i></span></button>
120
+ <button class="rb sm mutebtn" id="bmute" aria-label="Mute microphone"><svg class="i ic-mic" viewBox="0 0 24 24"><path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2M12 19v3"/></svg><svg class="i ic-off" viewBox="0 0 24 24"><path d="m2 2 20 20"/><path d="M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V5a3 3 0 0 0-5.9-.77"/><path d="M19 10v2a7 7 0 0 1-.78 3.22M5 10v2a7 7 0 0 0 11.12 5.66M12 19v3"/></svg></button>
121
+ <button class="rb big" id="bend" aria-label="End conversation"><svg class="i" viewBox="0 0 24 24"><path d="M18 6 6 18M6 6l12 12"/></svg></button>
122
+ </nav>
123
+ </div>
124
+
125
+ <div id="camview">
126
+ <video id="camv" muted playsinline autoplay></video><div id="camglow"></div>
127
+ <div id="camtop"><span id="live" data-t="live"></span></div>
128
+ <div id="cambot"><div id="camucap"></div><div id="camcap" class="status"></div>
129
+ <div id="camctl">
130
+ <button class="cb" id="cflash" aria-label="Flashlight"><svg class="i" viewBox="0 0 24 24"><path d="M18 6c0 2-2 2-2 4v10a2 2 0 0 1-2 2h-4a2 2 0 0 1-2-2V10c0-2-2-2-2-4V2h12z"/><path d="M6 6h12M12 12v2"/></svg></button>
131
+ <button class="cb" id="cflip" aria-label="Switch camera"><svg class="i" viewBox="0 0 24 24"><path d="M11 19H4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h5M13 5h7a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-5"/><circle cx="12" cy="12" r="3"/><path d="m18 22-3-3 3-3M6 2l3 3-3 3"/></svg></button>
132
+ <button class="cb" id="coff" aria-label="Turn camera off"><svg class="i" viewBox="0 0 24 24"><path d="M10.66 6H14a2 2 0 0 1 2 2v2.5l5.25-3.5a.5.5 0 0 1 .75.43v9.14M16 16a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h1"/><path d="m2 2 20 20"/></svg></button>
133
+ <button class="cb mutebtn" id="cmute" aria-label="Mute microphone"><svg class="i ic-mic" viewBox="0 0 24 24"><path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2M12 19v3"/></svg><svg class="i ic-off" viewBox="0 0 24 24"><path d="m2 2 20 20"/><path d="M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V5a3 3 0 0 0-5.9-.77"/><path d="M19 10v2a7 7 0 0 1-.78 3.22M5 10v2a7 7 0 0 0 11.12 5.66M12 19v3"/></svg></button>
134
+ </div>
135
+ </div>
136
+ </div>
137
+
138
+ <div id="textview">
139
+ <div id="thead"><b data-t="title"></b></div>
140
+ <button class="ib" id="tclose" aria-label="Close"><svg class="i" viewBox="0 0 24 24"><path d="M18 6 6 18M6 6l12 12"/></svg></button>
141
+ <div id="chat"></div>
142
+ <div id="tbar"><input id="typed" autocomplete="off" data-ph="ph"><button id="tsend" aria-label="Send"><svg class="i" viewBox="0 0 24 24"><path d="M22 2 11 13"/><path d="M22 2 15 22l-4-9-9-4z"/></svg></button></div>
143
+ </div>
144
+
145
+ <div id="menu">
146
+ <h4 data-t="lang"></h4><div class="seg" id="langseg"><button data-l="hi">Hindi</button><button data-l="en">English</button></div>
147
+ <h4 data-t="mode" id="modeh"></h4><div class="seg" id="modeseg"><button data-m="stt" data-t="brow"></button><button data-m="native" data-t="nat"></button></div>
148
+ <h4 data-t="mic"></h4><select id="mics"><option>Microphone</option></select><div id="meter"><i id="mi"></i></div><div id="diag"></div>
149
+ </div>
150
+ <div id="toast"></div>
151
+
152
+ <script>
153
+ const $=id=>document.getElementById(id);
154
+ const TXT={idle:'Start a conversation anytime',listening:'Listening…',thinking:'Thinking…',speaking:'Speaking…',muted:'Mic is muted',
155
+ tap:'Tap to start',ph:'Type your question…',live:'LIVE · Gemini can see you',title:'Conversation',empty:'Your conversation will appear here',
156
+ nofl:'This camera has no flashlight. Try the back camera.',nocam:'Could not start the camera. Check permission.',
157
+ nomic:'No sound from your mic. Pick the right one in Settings.',mutedT:'Mic muted',unmutedT:'Mic on',
158
+ lang:'AI speaks',mode:'Voice input',mic:'Microphone',brow:'Browser',nat:'Native',err:'Connecting… send again in a moment'};
159
+ let LANG='hi'; // language the AI speaks. Hindi by default; the interface is always English.
160
+ try{LANG=localStorage.getItem('ailang')||'hi'}catch{}
161
+ const T=k=>TXT[k]||'';
162
+ const SR=window.SpeechRecognition||window.webkitSpeechRecognition;
163
+ let MODE=SR?'stt':'native';
164
+ const STATES={idle:{c:['#5ef2d6','#8b7bff','#4285f4']},listening:{c:['#5ef2d6','#4aa8ff','#8b7bff']},thinking:{c:['#ffc46b','#ff7ab8','#8b7bff']},speaking:{c:['#8b7bff','#ff7ab8','#5ef2d6']}};
165
+ const rgb=h=>[1,3,5].map(i=>parseInt(h.substr(i,2),16));
166
+ const cur=STATES.idle.c.map(rgb);
167
+ let state='',ws,micCtx,outCtx,stream,node,analyser,micAn,active=false,starting=false,muted=false,chunks=0,heard=0,rst='-',maxLevel=0;
168
+ let micLevel=0,spokeAt=0,userSpeaking=false,floor=.003,nextT=0,sources=[],rec=null,liveUser=null,botEl=null,userEl=null,typing=null,botActive=false,userBuf='';
169
+
170
+ function toast(m){const e=$('toast');e.textContent=m;e.classList.add('on');clearTimeout(window.tt);window.tt=setTimeout(()=>e.classList.remove('on'),3500)}
171
+ function applyLang(){
172
+ document.querySelectorAll('[data-t]').forEach(e=>e.textContent=T(e.dataset.t));
173
+ document.querySelectorAll('[data-ph]').forEach(e=>e.placeholder=T(e.dataset.ph));
174
+ $('chat').dataset.empty=T('empty');
175
+ document.querySelectorAll('#langseg button').forEach(b=>b.classList.toggle('on',b.dataset.l===LANG));
176
+ document.querySelectorAll('#modeseg button').forEach(b=>b.classList.toggle('on',b.dataset.m===MODE));
177
+ $('modeh').style.display=$('modeseg').style.display=SR?'':'none';refreshStatus();
178
+ }
179
+ /* ---------- captions ---------- */
180
+ const caps=()=>[$('cap'),$('camcap')];
181
+ function statusText(){if(!active)return T('idle');if(muted&&(state==='listening'||state==='idle'))return T('muted');return T(state)||''}
182
+ function capSet(text,cls){caps().forEach(e=>{e.className=cls;e.textContent=text})}
183
+ function capAdd(text){caps().forEach(e=>{if(e.className!=='bot'){e.className='bot';e.textContent=''}
184
+ text.split(/(\s+)/).filter(Boolean).forEach(w=>{const s=document.createElement('span');s.className='w';s.textContent=w;e.appendChild(s)});e.scrollTop=1e9})}
185
+ function refreshStatus(){if(!botActive)capSet(statusText(),'status')}
186
+ function ucapSet(t){$('ucap').textContent=t;$('camucap').textContent=t}
187
+ function newUserTurn(){botActive=false;refreshStatus()}
188
+ function setState(s){
189
+ if(s===state)return;state=s;const r=document.documentElement.style,c=STATES[s].c;
190
+ r.setProperty('--c1',c[0]);r.setProperty('--c2',c[1]);document.body.dataset.st=s;
191
+ if(s==='thinking'&&active)showTyping();else hideTyping();
192
+ refreshStatus();
193
+ if(MODE==='stt'&&active){if(s==='speaking')stopRec();else if(s==='listening')startRec()}
194
+ }
195
+ /* ---------- written conversation ---------- */
196
+ const chat=$('chat');
197
+ function newLine(cls){const m=document.createElement('div');m.className='msg '+cls;
198
+ m.innerHTML='<div class="who">'+(cls==='you'?'You':'Gemini')+'</div><div class="txt"></div>';chat.appendChild(m);chat.scrollTop=1e9;return m}
199
+ function addWords(m,text){m.classList.remove('cursor');const box=m.lastChild;
200
+ text.split(/(\s+)/).filter(Boolean).forEach(w=>{const s=document.createElement('span');s.className='w';s.textContent=w;box.appendChild(s)});
201
+ m.classList.add('cursor');chat.scrollTop=1e9}
202
+ function showTyping(){if(typing||botEl)return;typing=newLine('bot');typing.lastChild.innerHTML='<span class="dots"><i></i><i></i><i></i></span>'}
203
+ function hideTyping(){if(typing){typing.remove();typing=null}}
204
+ function closeUserEl(){if(userEl){userEl.classList.remove('cursor');userEl=null}}
205
+ function endTurn(){if(botEl)botEl.classList.remove('cursor');botEl=null}
206
+ function addUser(text){hideTyping();endTurn();closeUserEl();const m=newLine('you');m.lastChild.textContent=text;userBuf='';ucapSet(text);newUserTurn()}
207
+ function onUserText(t){hideTyping();endTurn();if(!userEl)userEl=newLine('you');addWords(userEl,t);userBuf+=t;ucapSet(userBuf);newUserTurn()}
208
+ function onBotText(t){hideTyping();closeUserEl();userBuf='';if(state==='listening'||state==='idle')setState('thinking');hideTyping();
209
+ if(!botEl){botEl=newLine('bot');capSet('','bot')}addWords(botEl,t);botActive=true;capAdd(t)}
210
+ function sendText(text){if(ws&&ws.readyState===1){sendFrame();ws.send(JSON.stringify({t:'text',text}));setState('thinking')}}
211
+
212
+ /* ---------- browser speech recognition ---------- */
213
+ function startRec(){
214
+ if(MODE!=='stt'||!SR||!active||rec||muted)return;
215
+ const r=new SR();rec=r;r.lang=LANG==='hi'?'hi-IN':'en-IN';r.continuous=true;r.interimResults=true;
216
+ r.onresult=e=>{
217
+ let interim='',fin='';
218
+ for(let i=e.resultIndex;i<e.results.length;i++){const x=e.results[i];if(x.isFinal)fin+=x[0].transcript;else interim+=x[0].transcript}
219
+ const txt=(fin||interim).trim();if(!txt)return;rst='heard you';
220
+ if(state!=='speaking')setState('listening');
221
+ hideTyping();endTurn();if(!liveUser)liveUser=newLine('you');
222
+ liveUser.lastChild.textContent=txt;chat.scrollTop=1e9;ucapSet(txt);newUserTurn();
223
+ if(fin.trim()){liveUser=null;heard++;sendText(fin.trim())}
224
+ };
225
+ r.onstart=()=>{rst='recognizer on'};r.onsoundstart=()=>{rst='sound detected'};r.onspeechstart=()=>{rst='speech detected'};
226
+ r.onerror=e=>{rst='error: '+e.error;
227
+ if(['not-allowed','service-not-allowed','audio-capture','network'].includes(e.error))toast('Speech: '+e.error+' · you can type instead')};
228
+ r.onend=()=>{if(rec===r)rec=null;if(active&&MODE==='stt'&&state!=='speaking'&&!muted)setTimeout(startRec,150)};
229
+ try{r.start()}catch{rec=null}
230
+ }
231
+ function stopRec(){if(rec){const r=rec;rec=null;r.onend=null;try{r.abort()}catch{}}}
232
+
233
+ /* ---------- audio out ---------- */
234
+ function playPcm(buf){
235
+ if(!outCtx)return;
236
+ const i16=new Int16Array(buf),f=new Float32Array(i16.length);
237
+ for(let i=0;i<i16.length;i++)f[i]=i16[i]/32768;
238
+ const ab=outCtx.createBuffer(1,f.length,24000);ab.copyToChannel(f,0);
239
+ const src=outCtx.createBufferSource();src.buffer=ab;src.connect(analyser);
240
+ nextT=Math.max(nextT,outCtx.currentTime+.04);src.start(nextT);nextT+=ab.duration;
241
+ sources.push(src);src.onended=()=>{sources=sources.filter(s=>s!==src)};
242
+ chunks++;setState('speaking');
243
+ }
244
+ function stopPlayback(){sources.forEach(s=>{try{s.stop()}catch{}});sources=[];nextT=0}
245
+
246
+ /* ---------- microphone ---------- */
247
+ let micId='';try{micId=localStorage.getItem('micId')||''}catch{}
248
+ async function openMic(){
249
+ try{return await navigator.mediaDevices.getUserMedia({audio:micId?{deviceId:{exact:micId}}:true})}
250
+ catch(e){if(micId){micId='';return await navigator.mediaDevices.getUserMedia({audio:true})}throw e}
251
+ }
252
+ async function fillMics(){
253
+ try{const list=(await navigator.mediaDevices.enumerateDevices()).filter(d=>d.kind==='audioinput'),sel=$('mics');sel.innerHTML='';
254
+ list.forEach((d,i)=>{const o=document.createElement('option');o.value=d.deviceId;o.textContent=d.label||('Microphone '+(i+1));sel.appendChild(o)});
255
+ const c=stream&&stream.getAudioTracks()[0]&&stream.getAudioTracks()[0].getSettings().deviceId;if(c)sel.value=c}catch{}
256
+ }
257
+ $('mics').onchange=e=>{micId=e.target.value;try{localStorage.setItem('micId',micId)}catch{}restart()};
258
+
259
+ /* ---------- connection ---------- */
260
+ async function start(){
261
+ if(active||starting)return;starting=true;
262
+ try{stream=await openMic()}catch(e){starting=false;toast('Allow the microphone and try again');return}
263
+ stream.getAudioTracks().forEach(t=>t.enabled=!muted);
264
+ micCtx=new AudioContext();outCtx=new AudioContext();await micCtx.resume();await outCtx.resume();
265
+ analyser=outCtx.createAnalyser();analyser.fftSize=256;analyser.connect(outCtx.destination);
266
+ const code=`class P extends AudioWorkletProcessor{constructor(){super();this.r=sampleRate/16000;this.p=0;this.a=0;this.n=0;this.o=[]}
267
+ process(i){const c=i[0][0];if(!c)return true;let s=0;
268
+ for(let k=0;k<c.length;k++){const v=c[k];s+=v*v;this.a+=v;this.n++;this.p+=1;
269
+ if(this.p>=this.r){this.p-=this.r;this.o.push(Math.max(-1,Math.min(1,this.a/this.n))*32767);this.a=0;this.n=0}}
270
+ const rms=Math.sqrt(s/c.length);
271
+ if(this.o.length>=320){const x=Int16Array.from(this.o);this.o=[];this.port.postMessage({pcm:x.buffer,rms},[x.buffer])}
272
+ else this.port.postMessage({rms});return true}}registerProcessor('p',P)`;
273
+ await micCtx.audioWorklet.addModule(URL.createObjectURL(new Blob([code],{type:'application/javascript'})));
274
+ node=new AudioWorkletNode(micCtx,'p');const msrc=micCtx.createMediaStreamSource(stream);msrc.connect(node);
275
+ const mute=micCtx.createGain();mute.gain.value=0;node.connect(mute);mute.connect(micCtx.destination);
276
+ micAn=micCtx.createAnalyser();micAn.fftSize=128;msrc.connect(micAn);
277
+ maxLevel=0;fillMics();clearTimeout(window.silent);
278
+ window.silent=setTimeout(()=>{if(active&&!muted&&maxLevel<.004)toast(T('nomic'))},6000);
279
+ ws=new WebSocket(`${location.protocol==='https:'?'wss':'ws'}://${location.host}/live-ws?lang=${LANG}`);ws.binaryType='arraybuffer';
280
+ node.port.onmessage=e=>{
281
+ const d=e.data;micLevel=muted?0:d.rms;maxLevel=Math.max(maxLevel,micLevel);
282
+ if(MODE==='native'&&!muted&&d.pcm&&ws.readyState===1)ws.send(d.pcm);
283
+ const now=performance.now();floor+=(micLevel-floor)*(micLevel<floor?.2:.002);const thr=Math.max(.012,floor*3);
284
+ if(MODE==='native'&&!muted&&state!=='speaking'){
285
+ if(micLevel>thr){spokeAt=now;userSpeaking=true;if(state!=='listening'){setState('listening');newUserTurn()}}
286
+ else if(userSpeaking&&now-spokeAt>900){userSpeaking=false;setState('thinking');if(ws.readyState===1)ws.send(JSON.stringify({t:'end'}))}
287
+ }
288
+ };
289
+ ws.onmessage=e=>{
290
+ if(typeof e.data!=='string'){playPcm(e.data);return}
291
+ const d=JSON.parse(e.data);
292
+ if(d.t==='ready'){active=true;starting=false;document.body.classList.add('live');$('bend').classList.add('on');$('st').textContent=d.model;
293
+ state='';setState('thinking');chunks=0;heard=0;if(MODE==='stt')startRec();
294
+ clearInterval(window.dbg);window.dbg=setInterval(()=>{$('diag').textContent=(MODE==='stt'?'phrases '+heard+' · '+rst:'native')+' · audio '+chunks},600)}
295
+ else if(d.t==='user')onUserText(d.text);
296
+ else if(d.t==='bot')onBotText(d.text);
297
+ else if(d.t==='interrupted'){stopPlayback();setState('listening')}
298
+ else if(d.t==='done')endTurn();
299
+ else if(d.t==='error'){toast(d.text);stop()}
300
+ };
301
+ ws.onclose=()=>{if(active||starting)stop()};
302
+ }
303
+ function stop(){
304
+ active=false;starting=false;stopRec();closeCam();clearTimeout(window.silent);clearInterval(window.dbg);liveUser=null;micAn=null;
305
+ try{ws.close()}catch{}stream&&stream.getTracks().forEach(t=>t.stop());
306
+ micCtx&&micCtx.close();outCtx&&outCtx.close();stopPlayback();hideTyping();endTurn();
307
+ document.body.classList.remove('live');$('bend').classList.remove('on');$('st').textContent='offline';
308
+ botActive=false;ucapSet('');state='';setState('idle');
309
+ }
310
+ function restart(){if(active){stop();setTimeout(start,400)}}
311
+
312
+ /* ---------- mute ---------- */
313
+ function toggleMute(){
314
+ muted=!muted;if(stream)stream.getAudioTracks().forEach(t=>t.enabled=!muted);
315
+ document.querySelectorAll('.mutebtn').forEach(b=>b.classList.toggle('muted',muted));
316
+ if(muted){stopRec();userSpeaking=false}else if(active&&MODE==='stt'&&state!=='speaking')startRec();
317
+ refreshStatus();toast(T(muted?'mutedT':'unmutedT'));
318
+ }
319
+
320
+ /* ---------- camera ---------- */
321
+ let camStream=null,camTimer=null,facing='user',torchOn=false;const cc=document.createElement('canvas');
322
+ async function startCamStream(){
323
+ if(camStream)camStream.getTracks().forEach(t=>t.stop());
324
+ try{camStream=await navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:facing},width:{ideal:1280},height:{ideal:720}},audio:false})}
325
+ catch(e){camStream=null;toast(T('nocam'));return false}
326
+ const v=$('camv');v.srcObject=camStream;v.style.transform=facing==='user'?'scaleX(-1)':'none';try{await v.play()}catch{}
327
+ torchOn=false;$('cflash').classList.remove('on');clearInterval(camTimer);camTimer=setInterval(sendFrame,1000);return true;
328
+ }
329
+ async function openCam(){
330
+ if(!active)start();
331
+ if(await startCamStream())document.body.classList.add('camopen'),$('camview').classList.add('on');
332
+ }
333
+ function closeCam(){
334
+ clearInterval(camTimer);if(camStream)camStream.getTracks().forEach(t=>t.stop());camStream=null;
335
+ $('camview').classList.remove('on');document.body.classList.remove('camopen');
336
+ }
337
+ async function toggleTorch(){
338
+ const tr=camStream&&camStream.getVideoTracks()[0];if(!tr)return;
339
+ const caps=tr.getCapabilities?tr.getCapabilities():{};if(!caps.torch){toast(T('nofl'));return}
340
+ try{await tr.applyConstraints({advanced:[{torch:!torchOn}]});torchOn=!torchOn;$('cflash').classList.toggle('on',torchOn)}catch{toast(T('nofl'))}
341
+ }
342
+ function sendFrame(){
343
+ const v=$('camv');if(!camStream||!v.videoWidth||!ws||ws.readyState!==1)return;
344
+ const w=Math.min(640,v.videoWidth),h=Math.round(w*v.videoHeight/v.videoWidth);cc.width=w;cc.height=h;
345
+ cc.getContext('2d').drawImage(v,0,0,w,h);ws.send(JSON.stringify({t:'video',data:cc.toDataURL('image/jpeg',.6).split(',')[1]}));
346
+ }
347
+
348
+ /* ---------- wiring ---------- */
349
+ $('pill').onclick=()=>{if(!active)start();else if(state==='speaking'){stopPlayback();setState('listening')}};
350
+ $('bend').onclick=()=>{if(active)stop()};
351
+ $('bmute').onclick=$('cmute').onclick=toggleMute;
352
+ $('bcam').onclick=openCam;$('coff').onclick=closeCam;$('cflip').onclick=async()=>{facing=facing==='user'?'environment':'user';await startCamStream()};$('cflash').onclick=toggleTorch;
353
+ $('btext').onclick=()=>{$('textview').classList.add('on');if(!active)start();setTimeout(()=>$('typed').focus(),450)};
354
+ $('tclose').onclick=()=>$('textview').classList.remove('on');
355
+ function submitText(){const v=$('typed').value.trim();if(!v)return;if(!active){toast(T('err'));start();return}$('typed').value='';addUser(v);sendText(v)}
356
+ $('tsend').onclick=submitText;$('typed').addEventListener('keydown',e=>{if(e.key==='Enter')submitText()});
357
+ $('bmenu').onclick=e=>{e.stopPropagation();$('menu').classList.toggle('on')};
358
+ document.addEventListener('click',e=>{if(!$('menu').contains(e.target))$('menu').classList.remove('on')});
359
+ document.querySelectorAll('#langseg button').forEach(b=>b.onclick=()=>{LANG=b.dataset.l;try{localStorage.setItem('ailang',LANG)}catch{}applyLang();restart()});
360
+ document.querySelectorAll('#modeseg button').forEach(b=>b.onclick=()=>{MODE=b.dataset.m;applyLang();restart()});
361
+ applyLang();
362
+
363
+ /* ---------- background animation ---------- */
364
+ const fx=$('fx'),f=fx.getContext('2d'),BARS=[...document.querySelectorAll('#bars i')];
365
+ let FW,FH,t=0,smooth=0,ripples=[],lastState='';
366
+ const buf=new Uint8Array(128),micBuf=new Uint8Array(64),DPR=()=>devicePixelRatio||1,avg=a=>a.reduce((x,y)=>x+y,0)/a.length;
367
+ function fit(){const d=DPR();FW=fx.width=innerWidth*d;FH=fx.height=innerHeight*d}addEventListener('resize',fit);fit();
368
+ const PT=Array.from({length:70},()=>({x:Math.random(),y:Math.random(),s:.2+Math.random(),z:Math.random()}));
369
+ const rgba=(c,a)=>`rgba(${c.map(Math.round)},${a})`;
370
+ function frame(){
371
+ t+=.012;const d=DPR();
372
+ if(state==='speaking'&&outCtx&&!sources.length&&outCtx.currentTime>nextT+.3)setState('listening');
373
+ if(state!==lastState){ripples.push({r:0,a:.8});lastState=state}
374
+ let spec=null,lvl=0;
375
+ if(state==='speaking'&&analyser){analyser.getByteFrequencyData(buf);spec=buf;lvl=avg(buf)/80}
376
+ else if(state==='thinking')lvl=.3+.15*Math.sin(t*8);
377
+ else if(micAn&&active&&!muted){micAn.getByteFrequencyData(micBuf);spec=micBuf;lvl=Math.min(1,Math.max(micLevel*10,avg(micBuf)/70))}
378
+ if(!active)lvl=.06+.03*Math.sin(t*2);
379
+ lvl=Math.min(1,lvl);smooth+=(lvl-smooth)*.18;
380
+ if(smooth>.3&&Math.random()<.04+smooth*.06)ripples.push({r:0,a:.5*smooth});
381
+ const S=STATES[state||'idle'];
382
+ for(let j=0;j<3;j++){const tg=rgb(S.c[j]);for(let i=0;i<3;i++)cur[j][i]+=(tg[i]-cur[j][i])*.05}
383
+ document.body.style.setProperty('--lv',smooth.toFixed(3));
384
+ BARS.forEach((b,i)=>{const k=Math.abs(i-4),v=spec?Math.min(1,spec[2+k*4]/190):.5+.5*Math.sin(t*3+i);b.style.height=(6+v*(active?40:5))+'px'});
385
+ $('mi').style.transform='scaleX('+Math.min(1,micLevel*12)+')';
386
+ f.clearRect(0,0,FW,FH);f.globalCompositeOperation='lighter';
387
+ for(let j=0;j<3;j++){
388
+ const x=FW*(.15+.35*j+.08*Math.sin(t*.8+j*2)),y=FH*(1.02+.02*Math.sin(t+j)),r=FW*.75*(1+smooth*.35);
389
+ const g=f.createRadialGradient(x,y,0,x,y,Math.max(r,FH*.45));g.addColorStop(0,rgba(cur[j],.26+smooth*.28));g.addColorStop(1,rgba(cur[j],0));
390
+ f.fillStyle=g;f.fillRect(0,0,FW,FH);
391
+ }
392
+ PT.forEach((p,i)=>{p.y-=p.s*.0004*(1+smooth*4);if(p.y<0){p.y=1;p.x=Math.random()}
393
+ f.fillStyle=rgba(cur[i%3],.1+.45*p.z*(.3+smooth));f.beginPath();f.arc(p.x*FW+Math.sin(t+i)*12*d,p.y*FH,(1+p.z*2.2)*d,0,7);f.fill()});
394
+ if(!document.body.classList.contains('camopen')){ // ripples spread from the voice pill
395
+ const rc=$('pill').getBoundingClientRect(),ox=(rc.left+rc.width/2)*d,oy=(rc.top+rc.height/2)*d;
396
+ ripples.forEach(q=>{q.r+=.011;f.beginPath();f.arc(ox,oy,(40+q.r*260)*d,0,7);f.lineWidth=2*d;f.strokeStyle=rgba(cur[0],q.a*(1-q.r));f.stroke()});
397
+ }
398
+ ripples=ripples.filter(q=>q.r<1);
399
+ requestAnimationFrame(frame);
400
+ }
401
+ frame();
402
+ </script>
403
+ </body>
404
+ </html>
server (79).js ADDED
The diff for this file is too large to render. See raw diff