tz-voice-chat 1.0.1 → 1.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +31 -0
- package/dist/assets/llmWorker-CVEGn6yI.js +1 -0
- package/dist/index.cjs +2 -1
- package/dist/index.js +809 -437
- package/dist/style.css +1 -1
- package/package.json +18 -4
- package/server/index.js +263 -0
- package/server/tts.js +116 -0
package/README.md
CHANGED
|
@@ -178,3 +178,34 @@ TZVoiceChat hook
|
|
|
178
178
|
AIAssistantButton component
|
|
179
179
|
└── 5-state animated button with waveform visualiser and mic selector
|
|
180
180
|
```
|
|
181
|
+
|
|
182
|
+
---
|
|
183
|
+
|
|
184
|
+
## Full assistant in two files (UI + server)
|
|
185
|
+
|
|
186
|
+
Besides the `TZVoiceChat` hook, the package ships a ready-made UI and the matching Express backend.
|
|
187
|
+
|
|
188
|
+
**Client**
|
|
189
|
+
|
|
190
|
+
```jsx
|
|
191
|
+
import { VoiceAssistant } from 'tz-voice-chat';
|
|
192
|
+
import 'tz-voice-chat/style.css';
|
|
193
|
+
|
|
194
|
+
export default () => <VoiceAssistant />; // props: apiBase='/api', title, showInfo, systemPrompt, className
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
`VoiceAssistant` (built on the `useVoiceAssistant` hook) renders the status header, an info card (STT / TTS / chat model / memory), the mic button, a typed-message box, and a transcript with per-message timings (`transcribe`, `think`, `tts`). Esc stops listening. It uses the server chat proxy when the server has an API key, otherwise an in-browser SmolLM2 model.
|
|
198
|
+
|
|
199
|
+
**Server** (`express` and, for `TTS_PROVIDER=server-kokoro`, `kokoro-js` are peer dependencies)
|
|
200
|
+
|
|
201
|
+
```js
|
|
202
|
+
import express from 'express';
|
|
203
|
+
import { createVoiceAssistantRouter } from 'tz-voice-chat/server';
|
|
204
|
+
|
|
205
|
+
const app = express();
|
|
206
|
+
const { router, ready } = createVoiceAssistantRouter(); // options default to env vars
|
|
207
|
+
app.use('/api', router); // /config /stats /chat /tts /models/*
|
|
208
|
+
ready().then(() => app.listen(3000));
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
Environment variables: `OPENAI_PROVIDER`, `OPENROUTER_API_KEY`, `OPENROUTER_MODEL`, `HUGGINGFACE_API_KEY`, `TTS_PROVIDER`, `KOKORO_VOICE`, `KOKORO_DTYPE`, `KOKORO_DEVICE`, `KOKORO_SPEED`, `KOKORO_BROWSER_DEVICE`, `OPENAI_API_KEY`, `OPENAI_TTS_MODEL`, `OPENAI_TTS_VOICE`, `WHISPER_MODEL`, `WHISPER_DTYPE`, `WHISPER_DEVICE`, `WEBSPEECH_VOICE`, `WEBSPEECH_RATE`, `WEBSPEECH_PITCH`. Any of them can be overridden with the matching camelCase option.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
(function(){"use strict";let t=null,r=null;self.onmessage=async l=>{var n,p;const{type:o,messages:i,modelProxyUrl:g}=l.data;if(o==="init"){try{const{pipeline:e,TextStreamer:a,env:s}=await import("/vendor/transformers/transformers.min.js");s.remoteHost=g||"/api/models/",(p=(n=s==null?void 0:s.backends)==null?void 0:n.onnx)!=null&&p.wasm&&(s.backends.onnx.wasm.wasmPaths="/vendor/transformers/"),r=a,t=await e("text-generation","HuggingFaceTB/SmolLM2-360M-Instruct",{dtype:"q4",progress_callback:({status:c,progress:m}={})=>{self.postMessage({type:"progress",status:c,progress:(m??0)/100})}}),self.postMessage({type:"ready"})}catch(e){self.postMessage({type:"error",message:String((e==null?void 0:e.message)??e)})}return}if(o==="generate"){if(!t||!r){self.postMessage({type:"done"});return}try{const e=new r(t.tokenizer,{skip_prompt:!0,skip_special_tokens:!0,callback_function:a=>{self.postMessage({type:"token",text:a})}});await t(i,{max_new_tokens:150,do_sample:!1,streamer:e}),self.postMessage({type:"done"})}catch(e){console.error("[LLM worker] generate error:",e),self.postMessage({type:"done"})}}}})();
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
"use strict";var ve=Object.create;var fe=Object.defineProperty;var ke=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var xe=Object.getPrototypeOf,Ae=Object.prototype.hasOwnProperty;var Ie=(e,s,n,a)=>{if(s&&typeof s=="object"||typeof s=="function")for(let t of Te(s))!Ae.call(e,t)&&t!==n&&fe(e,t,{get:()=>s[t],enumerable:!(a=ke(s,t))||a.enumerable});return e};var de=(e,s,n)=>(n=e!=null?ve(xe(e)):{},Ie(s||!e||!e.__esModule?fe(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("react"),g=require("react/jsx-runtime");var ie=typeof document<"u"?document.currentScript:null;function he(){let e="";function s(){const n=[];for(;;){const a=/([.!?]{1,3})(\s|$)/.exec(e);if(a){const t=e.slice(0,a.index+a[0].length).trim();if(t.length>=10){n.push(t),e=e.slice(a.index+a[0].length);continue}}if(e.length>=25){const t=/[,;:—–](\s|$)/.exec(e);if(t){const o=e.slice(0,t.index+t[0].length).trim();if(o.length>=20){n.push(o),e=e.slice(t.index+t[0].length);continue}}}if(e.length>=45){const t=e.lastIndexOf(" ",44),o=t>10?t:45;n.push(e.slice(0,o).trim()),e=e.slice(o).trimStart();continue}break}return n}return{write(n){return e+=n,s()},flush(){const n=e.trim();return e="",n}}}async function Ne(e,{dtype:s="q8",device:n="cpu",modelProxyUrl:a="/api/models/"}={}){var u,v;const{env:t}=await import("/vendor/transformers/transformers.min.js");t.remoteHost=a,(v=(u=t==null?void 0:t.backends)==null?void 0:u.onnx)!=null&&v.wasm&&(t.backends.onnx.wasm.wasmPaths="/vendor/transformers/"),t!=null&&t.onnx&&(t.onnx.logSeverityLevel=3);const o=await import("/vendor/kokoro/kokoro.web.js"),{KokoroTTS:i}=o;let b=s;n==="webgpu"&&(s==="q4"||s==="q8")&&(console.warn(`[modelLoader] dtype "${s}" not supported on WebGPU — using "fp32".`),b="fp32");let r=0;const m=d=>{typeof(d==null?void 0:d.progress)=="number"&&(r=Math.max(r,d.progress/100),e==null||e("kokoro",Math.min(.99,r)))};async function w(d,_){return i.from_pretrained("onnx-community/Kokoro-82M-ONNX",{dtype:_,device:d,progress_callback:m})}let c;try{c=await w(n,b)}catch(d){if(n!=="wasm")console.warn(`[modelLoader] Kokoro on "${n}" failed (${d==null?void 0:d.message}) — falling back to WASM.`),r=0,c=await w("wasm",s);else throw d}return e==null||e("kokoro",1),{kokoro:c}}function Re(e,{voice:s="af_bella",onPlayStart:n}={}){const a=new AudioContext,t=[];let o=!1,i=null,b=!1;async function r(c){if(c instanceof AudioBuffer)return c;const u=(c==null?void 0:c.audio)??c;if(u instanceof ArrayBuffer)return await a.decodeAudioData(u.slice(0));if(u instanceof Float32Array){const v=(c==null?void 0:c.samplingRate)??24e3,d=a.createBuffer(1,u.length,v);return d.copyToChannel(u,0),d}throw new Error("Unsupported TTS payload")}async function m(c){await a.resume();const u=a.createBufferSource();return u.buffer=c,u.connect(a.destination),new Promise(v=>{u.onended=()=>{i===u&&(i=null),v()},i=u,u.start(),b||(b=!0,n==null||n())})}async function w(){if(!o){for(o=!0;t.length>0;){const c=t.shift();try{const u=await c;u&&await m(u)}catch(u){console.error("[TtsQueue]",u)}}o=!1}}return{enqueue(c){t.push(e.generate(c,{voice:s}).then(r)),w()},cancel(){if(t.length=0,i){try{i.stop()}catch{}i=null}},async finished(){for(;o||t.length>0;)await new Promise(c=>setTimeout(c,200))}}}function ze({voice:e="",onPlayStart:s,url:n="/api/tts"}={}){const a=new AudioContext,t=[];let o=!1,i=null,b=!1;async function r(c){const u={text:c};e&&(u.voice=e);const v=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!v.ok)throw new Error(`TTS ${v.status}: ${await v.text()}`);return a.decodeAudioData(await v.arrayBuffer())}async function m(c){await a.resume();const u=a.createBufferSource();return u.buffer=c,u.connect(a.destination),new Promise(v=>{u.onended=()=>{i===u&&(i=null),v()},i=u,u.start(),b||(b=!0,s==null||s())})}async function w(){if(!o){for(o=!0;t.length>0;){const c=t.shift();try{await m(await c)}catch(u){console.error("[ServerTTS]",u)}}o=!1}}return{enqueue(c){c!=null&&c.trim()&&(t.push(r(c)),w())},cancel(){if(t.length=0,i){try{i.stop()}catch{}i=null}b=!1},async finished(){for(;o||t.length>0;)await new Promise(c=>setTimeout(c,100))}}}function Ee({voice:e="",rate:s=1,pitch:n=1,onPlayStart:a}={}){const t=[];let o=!1,i=!1;function b(){return e?speechSynthesis.getVoices().find(w=>w.name===e||w.voiceURI===e)??null:null}function r(){if(o||t.length===0)return;o=!0;const m=t.shift(),w=new SpeechSynthesisUtterance(m),c=b();c&&(w.voice=c),w.rate=s,w.pitch=n,w.onstart=()=>{i||(i=!0,a==null||a())},w.onend=()=>{o=!1,r()},w.onerror=u=>{console.error("[WebSpeech TTS] error",u.error),o=!1,r()},speechSynthesis.speak(w)}return{enqueue(m){m!=null&&m.trim()&&(t.push(m),r())},cancel(){t.length=0,speechSynthesis.cancel(),o=!1,i=!1},async finished(){for(;o||t.length>0;)await new Promise(m=>setTimeout(m,100))}}}async function _e({onSpeechStart:e,onSpeechEnd:s,onError:n,deviceId:a}){try{const{MicVAD:t}=window.vad;return await t.new({model:"legacy",baseAssetPath:"/vendor/vad/",onnxWASMBasePath:"/vendor/ort/",additionalAudioConstraints:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!1,...a?{deviceId:{exact:a}}:{}},onSpeechStart:()=>e==null?void 0:e(),onSpeechEnd:i=>{console.log("[VAD] onSpeechEnd — samples:",i==null?void 0:i.length),s==null||s(i)},onVADMisfire:()=>{},negativeSpeechThreshold:.25,positiveSpeechThreshold:.5,redemptionFrames:4,minSpeechFrames:3,preSpeechPadFrames:1})}catch(t){throw n==null||n("VAD initialization failed. Falling back to manual microphone capture."),t}}const S={IDLE:"idle",LISTENING:"listening",TRANSCRIBING:"transcribing",THINKING:"thinking",SPEAKING:"speaking"},Me="You are a friendly assistant for quick voice interactions. Provide answers only in the form of a single concise sentence, without any introductory phrases. Don't use any formatting, markdown, emoji, or code blocks — just plain text. The answers will be spoken aloud, so keep them short and natural.";function je({processInput:e,systemPrompt:s=Me,ttsProvider:n="server-kokoro",ttsVoice:a="af_bella",ttsServerUrl:t="/api/tts",ttsSpeechRate:o=1,ttsSpeechPitch:i=1,whisperModel:b="onnx-community/whisper-tiny.en",whisperDtype:r="q8",whisperDevice:m="cpu",kokoroDtype:w="q8",kokoroBrowserDevice:c="wasm",modelProxyUrl:u="/api/models/"}={}){const[v,d]=h.useState(S.IDLE),[_,A]=h.useState(!0),[j,N]=h.useState({whisper:0,kokoro:0}),[L,z]=h.useState(null),[J,P]=h.useState([]),[$,G]=h.useState(null),[y,R]=h.useState(!1),[M,Y]=h.useState(""),[X,ee]=h.useState([]),[te,C]=h.useState(null),D=h.useRef(S.IDLE),B=h.useRef(!1),x=h.useRef(null),V=h.useRef(null),K=h.useRef(null),U=h.useRef(null),ne=h.useRef(null),se=h.useRef(null),Q=h.useRef([{role:"system",content:s}]),ae=h.useRef(e);h.useEffect(()=>{D.current=v},[v]),h.useEffect(()=>{B.current=y},[y]),h.useEffect(()=>{ae.current=e},[e]),h.useEffect(()=>{async function p(){try{const k=await navigator.mediaDevices.enumerateDevices();ee(k.filter(l=>l.kind==="audioinput"))}catch{}}return p(),navigator.mediaDevices.addEventListener("devicechange",p),()=>navigator.mediaDevices.removeEventListener("devicechange",p)},[y]),h.useEffect(()=>{let p=!1;async function k(){try{const l=()=>{var f;n==="webspeech"&&((f=V.current)==null||f.pause())};if(n==="webspeech")x.current=Ee({voice:a,rate:o,pitch:i,onPlayStart:l}),N(f=>({...f,kokoro:1}));else if(n==="kokoro"){const{kokoro:f}=await Ne((T,q)=>N(F=>({...F,[T]:q})),{dtype:w,device:c,modelProxyUrl:u});if(p)return;x.current=Re(f,{voice:a,onPlayStart:l})}else x.current=ze({voice:a,onPlayStart:l,url:t}),N(f=>({...f,kokoro:1}));if(p)return;U.current=new Worker(new URL("./assets/whisperWorker-BJuP9cl9.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:ie&&ie.tagName.toUpperCase()==="SCRIPT"&&ie.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),U.current.onmessage=f=>{f.data.type==="transcript"?pe(f.data.text):f.data.type==="progress"?N(T=>({...T,whisper:f.data.progress})):f.data.type==="ready"?(N(T=>({...T,whisper:1})),A(!1)):f.data.type==="error"&&(z(`Whisper: ${f.data.message}`),A(!1))},U.current.onerror=()=>{z("Model load failed. Check WebGPU/WASM browser support."),A(!1)},U.current.postMessage({type:"init",model:b,dtype:r,device:m,modelProxyUrl:u})}catch(l){p||(z("Initialisation failed: "+((l==null?void 0:l.message)??String(l))),A(!1))}}return k(),()=>{var l;p=!0,(l=U.current)==null||l.terminate()}},[n,b,r,m,w,c]);function ce(p,k){P(l=>[...l,{role:p,content:k,time:new Date().toISOString()}])}async function pe(p){if(!(p!=null&&p.trim())){d(B.current?S.LISTENING:S.IDLE);return}d(S.THINKING),ce("user",p);const k=[...Q.current,{role:"user",content:p}];Q.current=k,await ge(p,k)}async function ge(p,k){var l,f,T,q,F;(l=K.current)==null||l.abort(),K.current=new AbortController,(f=x.current)==null||f.cancel();try{if(!ae.current)throw new Error("processInput is not provided");const W=he();let H="",re=!1;G("");for await(const ue of ae.current(p,k,K.current.signal))H+=ue,G(H),W.write(ue).forEach(Se=>{var le;re||(re=!0,d(S.SPEAKING)),(le=x.current)==null||le.enqueue(Se)});const oe=W.flush();oe&&(re||d(S.SPEAKING),(T=x.current)==null||T.enqueue(oe)),ce("assistant",H),G(null),Q.current=[...Q.current,{role:"assistant",content:H}],await((q=x.current)==null?void 0:q.finished()),n==="webspeech"&&((F=V.current)==null||F.start())}catch(W){G(null),W.name!=="AbortError"&&z(W.message||"Processing failed.")}finally{d(B.current?S.LISTENING:S.IDLE)}}async function we(){var p,k;z(null),D.current===S.SPEAKING&&((p=x.current)==null||p.cancel(),(k=K.current)==null||k.abort());try{d(S.LISTENING),R(!0);try{const l=await navigator.mediaDevices.getUserMedia({audio:M?{deviceId:{exact:M}}:!0,video:!1});se.current=l;const f=new AudioContext;ne.current=f;const T=f.createAnalyser();T.fftSize=256,f.createMediaStreamSource(l).connect(T),C(T)}catch(l){console.warn("[TZVoiceChat] waveform analyser unavailable:",l)}V.current=await _e({onSpeechStart:()=>{var l,f;n==="webspeech"&&D.current===S.SPEAKING||(D.current===S.SPEAKING&&((l=x.current)==null||l.cancel(),(f=K.current)==null||f.abort()),d(S.LISTENING))},onSpeechEnd:l=>{var f;n==="webspeech"&&D.current===S.SPEAKING||(d(S.TRANSCRIBING),(f=U.current)==null||f.postMessage({type:"transcribe",audio:l},[l.buffer]))},onError:l=>{z(l),d(S.IDLE)},deviceId:M||void 0})}catch(l){console.error("[TZVoiceChat] startListening failed:",l),z("Microphone access failed. Allow audio permissions and refresh."),d(S.IDLE),R(!1)}}function be(){var p,k,l,f,T;R(!1),(p=V.current)==null||p.destroy(),V.current=null,(k=se.current)==null||k.getTracks().forEach(q=>q.stop()),se.current=null,(l=ne.current)==null||l.close(),ne.current=null,C(null),(f=x.current)==null||f.cancel(),(T=K.current)==null||T.abort(),d(S.IDLE)}function ye(p){var T;if(!(p!=null&&p.trim()))return;d(S.SPEAKING);const k=he(),l=k.write(p),f=k.flush();[...l,...f?[f]:[]].forEach(q=>{var F;return(F=x.current)==null?void 0:F.enqueue(q)}),(T=x.current)==null||T.finished().then(()=>{d(B.current?S.LISTENING:S.IDLE)})}return{status:v,loading:_,progress:j,error:L,transcript:J,streamingMessage:$,micEnabled:y,startListening:we,stopListening:be,speak:ye,liveAnalyser:te,devices:X,selectedMicId:M,setSelectedMicId:Y}}function me(e){const s=e.replace("#",""),n=s.length===3?s.split("").map(a=>a+a).join(""):s;return[parseInt(n.slice(0,2),16),parseInt(n.slice(2,4),16),parseInt(n.slice(4,6),16)]}function Le(e,s,n){e/=255,s/=255,n/=255;const a=Math.max(e,s,n),t=Math.min(e,s,n),o=(a+t)/2;if(a===t)return[0,0,o*100];const i=a-t,b=o>.5?i/(2-a-t):i/(a+t);let r;switch(a){case e:r=((s-n)/i+(s<n?6:0))/6;break;case s:r=((n-e)/i+2)/6;break;default:r=((e-s)/i+4)/6}return[r*360,b*100,o*100]}function $e(e,s,n){s/=100,n/=100;const a=i=>(i+e/30)%12,t=s*Math.min(n,1-n),o=i=>n-t*Math.max(-1,Math.min(a(i)-3,Math.min(9-a(i),1)));return[Math.round(o(0)*255),Math.round(o(8)*255),Math.round(o(4)*255)]}function E(e,s){const[n,a,t]=me(e),[o,i,b]=Le(n,a,t),[r,m,w]=$e(o,i,Math.max(0,Math.min(100,b+s)));return`rgb(${r}, ${m}, ${w})`}function I(e,s){const[n,a,t]=me(e);return`rgba(${n}, ${a}, ${t}, ${s})`}function O(e,s){return e.replace("rgb(","rgba(").replace(")",`, ${s})`)}const Z=10;function De({analyser:e}){const s=h.useRef(null),n=h.useRef(null);return h.useEffect(()=>{if(cancelAnimationFrame(n.current),!e)return;const a=s.current;if(!a)return;const t=a.getContext("2d"),o=e.frequencyBinCount,i=new Uint8Array(o),b=Math.max(1,Math.floor(o/Z)),r=getComputedStyle(a),m=+r.getPropertyValue("--bar-hue"),w=+r.getPropertyValue("--bar-hue-range"),c=+r.getPropertyValue("--bar-sat"),u=+r.getPropertyValue("--bar-lit"),v=+r.getPropertyValue("--bar-lit-range"),d=()=>{n.current=requestAnimationFrame(d),e.getByteFrequencyData(i);const _=a.width,A=a.height;t.clearRect(0,0,_,A);const j=(_-(Z-1)*2)/Z;for(let N=0;N<Z;N++){const L=i[N*b]/255,z=Math.max(3,L*A*.88);t.fillStyle=`hsl(${m+L*w}, ${c}%, ${u+L*v}%)`,t.beginPath(),t.roundRect(N*(j+2),(A-z)/2,j,z,[2]),t.fill()}};return d(),()=>cancelAnimationFrame(n.current)},[e]),g.jsx("canvas",{ref:s,width:55,height:35,className:"ai-btn__canvas"})}function qe({status:e="idle",active:s=!1,loading:n=!1,analyser:a=null,onToggle:t,devices:o=[],selectedMicId:i="",onDeviceChange:b,accentColor:r="#f97316",uiColor:m="#64748b",size:w=70,barHue:c=25,barHueRange:u=20,barSat:v=88,barLit:d=65,barLitRange:_=20}){var G;const[A,j]=h.useState(!1),N=h.useRef(null);h.useEffect(()=>{if(!A)return;function y(R){var M;(M=N.current)!=null&&M.contains(R.target)||j(!1)}return document.addEventListener("pointerdown",y),()=>document.removeEventListener("pointerdown",y)},[A]);function L(y){b==null||b(y),j(!1)}const z=h.useMemo(()=>{const y=E(r,-8),R=E(r,-15),M=E(r,-22),Y=E(r,-30),X=E(r,-42),ee=E(r,8),te=E(r,20),C=E(r,30),D=E(m,-22),B=E(m,-30),x=E(m,18),V=E(m,37);return{"--tz-size":`${w}px`,"--tz-a":r,"--tz-a-d8":y,"--tz-a-d15":R,"--tz-a-d22":M,"--tz-a-d30":Y,"--tz-a-d42":X,"--tz-a-l8":ee,"--tz-a-l20":te,"--tz-a-l30":C,"--tz-a-25":I(r,.25),"--tz-a-28":I(r,.28),"--tz-a-30":I(r,.3),"--tz-a-32":I(r,.32),"--tz-a-34":I(r,.34),"--tz-a-35":I(r,.35),"--tz-a-38":I(r,.38),"--tz-a-45":I(r,.45),"--tz-a-50":I(r,.5),"--tz-a-55":I(r,.55),"--tz-a-60":I(r,.6),"--tz-a-65":I(r,.65),"--tz-a-68":I(r,.68),"--tz-u":m,"--tz-u-d22":D,"--tz-u-d30":B,"--tz-u-l18":x,"--tz-u-l37":V,"--tz-u-30":I(m,.3),"--tz-u-55":I(m,.55),"--tz-u-d30-a85":O(B,.85),"--tz-u-l18-a18":O(x,.18),"--tz-u-l18-a20":O(x,.2),"--tz-u-l18-a32":O(x,.32),"--tz-u-d22-a90":O(D,.9),"--bar-hue":c,"--bar-hue-range":u,"--bar-sat":v,"--bar-lit":d,"--bar-lit-range":_}},[r,m,w,c,u,v,d,_]),J=((G=o.find(y=>y.deviceId===i))==null?void 0:G.label)||(i?`Mic ${i.slice(0,6)}…`:"Default mic"),P=s?e:"off";let $;return!s||e==="idle"?$=g.jsx("svg",{className:"ai-btn__mic",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:g.jsx("path",{d:"M12 1a4 4 0 0 1 4 4v6a4 4 0 0 1-8 0V5a4 4 0 0 1 4-4zm6 10a1 1 0 0 1 2 0 8 8 0 0 1-7 7.94V21h2a1 1 0 0 1 0 2H9a1 1 0 0 1 0-2h2v-2.06A8 8 0 0 1 4 11a1 1 0 0 1 2 0 6 6 0 0 0 12 0z"})}):e==="listening"?$=g.jsx(De,{analyser:a}):e==="transcribing"?$=g.jsx("div",{className:"ai-btn__bars ai-btn__bars--transcribing",children:Array.from({length:7},(y,R)=>g.jsx("span",{style:{animationDelay:`${R*.1}s`}},R))}):e==="thinking"?$=g.jsxs("div",{className:"ai-btn__dots",children:[g.jsx("span",{}),g.jsx("span",{style:{animationDelay:"0.18s"}}),g.jsx("span",{style:{animationDelay:"0.36s"}})]}):e==="speaking"&&($=g.jsx("div",{className:"ai-btn__bars ai-btn__bars--speaking",children:Array.from({length:7},(y,R)=>g.jsx("span",{style:{animationDelay:`${R*.11}s`}},R))})),g.jsxs("div",{className:"ai-btn-root",style:z,children:[g.jsxs("div",{className:`ai-btn-rings ai-btn-rings--${P}`,"aria-hidden":"true",children:[g.jsx("span",{className:"ai-ring ai-ring--1"}),g.jsx("span",{className:"ai-ring ai-ring--2"})]}),g.jsxs("button",{className:`ai-btn ai-btn--${P}`,disabled:n,onClick:t,"aria-label":s?"Stop assistant":"Start assistant","aria-pressed":s,children:[$,s&&g.jsx("span",{className:"ai-btn__hover-stop","aria-hidden":"true",children:"■"})]}),g.jsxs("div",{className:`ai-mic-sel${A?" open":""}`,ref:N,children:[g.jsxs("button",{className:"ai-mic-sel__trigger",onClick:()=>j(y=>!y),title:"Change microphone","aria-label":"Change microphone","aria-expanded":A,children:[g.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[g.jsx("path",{d:"M12 1a4 4 0 0 1 4 4v6a4 4 0 0 1-8 0V5a4 4 0 0 1 4-4z"}),g.jsx("path",{d:"M5 11a1 1 0 0 0-2 0 9 9 0 0 0 8 8.94V22H9a1 1 0 0 0 0 2h6a1 1 0 0 0 0-2h-2v-2.06A9 9 0 0 0 21 11a1 1 0 0 0-2 0 7 7 0 0 1-14 0z"})]}),g.jsx("span",{className:"ai-mic-sel__label",children:J}),g.jsx("svg",{className:`ai-mic-sel__caret${A?" open":""}`,width:"9",height:"9",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:g.jsx("path",{d:"M12 16L4 8h16l-8 8z"})})]}),A&&g.jsxs("ul",{className:"ai-mic-sel__menu",role:"listbox","aria-label":"Select microphone",children:[g.jsx("li",{role:"option",className:`ai-mic-sel__option${i===""?" selected":""}`,onClick:()=>L(""),"aria-selected":i==="",children:"Default microphone"}),o.map(y=>g.jsx("li",{role:"option",className:`ai-mic-sel__option${i===y.deviceId?" selected":""}`,onClick:()=>L(y.deviceId),"aria-selected":i===y.deviceId,children:y.label||`Microphone ${y.deviceId.slice(0,8)}`},y.deviceId))]})]})]})}exports.AIAssistantButton=qe;exports.STATES=S;exports.TZVoiceChat=je;
|
|
1
|
+
"use strict";var Pe=Object.create;var xe=Object.defineProperty;var Oe=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var Ke=Object.getPrototypeOf,Ge=Object.prototype.hasOwnProperty;var Be=(e,s,r,i)=>{if(s&&typeof s=="object"||typeof s=="function")for(let t of Ue(s))!Ge.call(e,t)&&t!==r&&xe(e,t,{get:()=>s[t],enumerable:!(i=Oe(s,t))||i.enumerable});return e};var Se=(e,s,r)=>(r=e!=null?Pe(Ke(e)):{},Be(s||!e||!e.__esModule?xe(r,"default",{value:e,enumerable:!0}):r,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("react"),a=require("react/jsx-runtime");var Z=typeof document<"u"?document.currentScript:null;const he=60,ne=200;function _e(){let e="",s=!0;function r(t,o,n){t.push(o),e=n,s=!1}function i(){const t=[];for(;;){const o=/([.!?]{1,3})(\s|$)/.exec(e);if(o){const n=e.slice(0,o.index+o[0].length).trim();if(n.length>=10){r(t,n,e.slice(o.index+o[0].length));continue}}if(s){if(e.length>=25){const n=/[,;:—–](\s|$)/.exec(e);if(n){const u=e.slice(0,n.index+n[0].length).trim();if(u.length>=20){r(t,u,e.slice(n.index+n[0].length));continue}}}if(e.length>=he){const n=e.lastIndexOf(" ",he-1),u=n>10?n:he;r(t,e.slice(0,u).trim(),e.slice(u).trimStart());continue}}else if(e.length>=ne){const n=e.slice(0,ne),u=Math.max(n.lastIndexOf(", "),n.lastIndexOf("; "),n.lastIndexOf(": ")),c=u>ne/2?u+1:n.lastIndexOf(" ")>10?n.lastIndexOf(" "):ne;r(t,e.slice(0,c).trim(),e.slice(c).trimStart());continue}break}return t}return{write(t){return e+=t,i()},flush(){const t=e.trim();return e="",t}}}async function Fe(e,{dtype:s="q8",device:r="cpu",modelProxyUrl:i="/api/models/"}={}){var d,f;const{env:t}=await import("/vendor/transformers/transformers.min.js");t.remoteHost=i,(f=(d=t==null?void 0:t.backends)==null?void 0:d.onnx)!=null&&f.wasm&&(t.backends.onnx.wasm.wasmPaths="/vendor/transformers/"),t!=null&&t.onnx&&(t.onnx.logSeverityLevel=3);const o=await import("/vendor/kokoro/kokoro.web.js"),{KokoroTTS:n}=o;let u=s;r==="webgpu"&&(s==="q4"||s==="q8")&&(console.warn(`[modelLoader] dtype "${s}" not supported on WebGPU — using "fp32".`),u="fp32");let c=0;const h=w=>{typeof(w==null?void 0:w.progress)=="number"&&(c=Math.max(c,w.progress/100),e==null||e("kokoro",Math.min(.99,c)))};async function l(w,g){return n.from_pretrained("onnx-community/Kokoro-82M-ONNX",{dtype:g,device:w,progress_callback:h})}let v;try{v=await l(r,u)}catch(w){if(r!=="wasm")console.warn(`[modelLoader] Kokoro on "${r}" failed (${w==null?void 0:w.message}) — falling back to WASM.`),c=0,v=await l("wasm",s);else throw w}return e==null||e("kokoro",1),{kokoro:v}}function re(e,s,{threshold:r=.01,padMs:i=25}={}){const{numberOfChannels:t,length:o,sampleRate:n}=s;let u=o,c=-1;for(let f=0;f<t;f++){const w=s.getChannelData(f);for(let g=0;g<o;g++)if(Math.abs(w[g])>r){g<u&&(u=g);break}for(let g=o-1;g>=0;g--)if(Math.abs(w[g])>r){g>c&&(c=g);break}}if(c<u)return s;const h=Math.round(i/1e3*n),l=Math.max(0,u-h),v=Math.min(o,c+1+h);if(l===0&&v===o)return s;const d=e.createBuffer(t,v-l,n);for(let f=0;f<t;f++)d.copyToChannel(s.getChannelData(f).subarray(l,v),f);return d}function We(e,{voice:s="af_bella",speed:r=1,onPlayStart:i}={}){const t=new AudioContext,o=[];let n=!1,u=null,c=!1;async function h(d){if(d instanceof AudioBuffer)return re(t,d);const f=(d==null?void 0:d.audio)??d;if(f instanceof ArrayBuffer)return re(t,await t.decodeAudioData(f.slice(0)));if(f instanceof Float32Array){const w=(d==null?void 0:d.samplingRate)??24e3,g=t.createBuffer(1,f.length,w);return g.copyToChannel(f,0),re(t,g)}throw new Error("Unsupported TTS payload")}async function l(d){await t.resume();const f=t.createBufferSource();return f.buffer=d,f.connect(t.destination),new Promise(w=>{f.onended=()=>{u===f&&(u=null),w()},u=f,f.start(),c||(c=!0,i==null||i())})}async function v(){if(!n){for(n=!0;o.length>0;){const d=o.shift();try{const f=await d;f&&await l(f)}catch(f){console.error("[TtsQueue]",f)}}n=!1}}return{enqueue(d){o.push(e.generate(d,{voice:s,speed:r}).then(h)),v()},cancel(){if(o.length=0,c=!1,u){try{u.stop()}catch{}u=null}},async finished(){for(;n||o.length>0;)await new Promise(d=>setTimeout(d,200))}}}function He({voice:e="",speed:s=1,onPlayStart:r,url:i="/api/tts"}={}){const t=new AudioContext,o=[];let n=!1,u=null,c=!1;async function h(d){const f={text:d};e&&(f.voice=e),s!==1&&(f.speed=s);const w=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)});if(!w.ok)throw new Error(`TTS ${w.status}: ${await w.text()}`);return re(t,await t.decodeAudioData(await w.arrayBuffer()))}async function l(d){await t.resume();const f=t.createBufferSource();return f.buffer=d,f.connect(t.destination),new Promise(w=>{f.onended=()=>{u===f&&(u=null),w()},u=f,f.start(),c||(c=!0,r==null||r())})}async function v(){if(!n){for(n=!0;o.length>0;){const d=o.shift();try{await l(await d)}catch(f){console.error("[ServerTTS]",f)}}n=!1}}return{enqueue(d){d!=null&&d.trim()&&(o.push(h(d)),v())},cancel(){if(o.length=0,u){try{u.stop()}catch{}u=null}c=!1},async finished(){for(;n||o.length>0;)await new Promise(d=>setTimeout(d,100))}}}function Qe({voice:e="",rate:s=1,pitch:r=1,onPlayStart:i}={}){const t=[];let o=!1,n=!1;function u(){return e?speechSynthesis.getVoices().find(l=>l.name===e||l.voiceURI===e)??null:null}function c(){if(o||t.length===0)return;o=!0;const h=t.shift(),l=new SpeechSynthesisUtterance(h),v=u();v&&(l.voice=v),l.rate=s,l.pitch=r,l.onstart=()=>{n||(n=!0,i==null||i())},l.onend=()=>{o=!1,c()},l.onerror=d=>{console.error("[WebSpeech TTS] error",d.error),o=!1,c()},speechSynthesis.speak(l)}return{enqueue(h){h!=null&&h.trim()&&(t.push(h),c())},cancel(){t.length=0,speechSynthesis.cancel(),o=!1,n=!1},async finished(){for(;o||t.length>0;)await new Promise(h=>setTimeout(h,100))}}}async function Ze({onSpeechStart:e,onSpeechEnd:s,onError:r,deviceId:i}){try{const{MicVAD:t}=window.vad;return await t.new({model:"legacy",baseAssetPath:"/vendor/vad/",onnxWASMBasePath:"/vendor/ort/",additionalAudioConstraints:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!1,...i?{deviceId:{exact:i}}:{}},onSpeechStart:()=>e==null?void 0:e(),onSpeechEnd:n=>{console.log("[VAD] onSpeechEnd — samples:",n==null?void 0:n.length),s==null||s(n)},onVADMisfire:()=>{},negativeSpeechThreshold:.25,positiveSpeechThreshold:.5,redemptionFrames:4,minSpeechFrames:3,preSpeechPadFrames:1})}catch(t){throw r==null||r("VAD initialization failed. Falling back to manual microphone capture."),t}}const j={IDLE:"idle",LISTENING:"listening",TRANSCRIBING:"transcribing",THINKING:"thinking",SPEAKING:"speaking"},Je="You are a friendly assistant for quick voice interactions. Provide answers only in the form of a single concise sentence, without any introductory phrases. Don't use any formatting, markdown, emoji, or code blocks — just plain text. The answers will be spoken aloud, so keep them short and natural.";function Me({processInput:e,systemPrompt:s=Je,ttsProvider:r="server-kokoro",ttsVoice:i="af_bella",ttsSpeed:t=1,ttsServerUrl:o="/api/tts",ttsSpeechRate:n=1,ttsSpeechPitch:u=1,whisperModel:c="onnx-community/whisper-tiny.en",whisperDtype:h="q8",whisperDevice:l="cpu",kokoroDtype:v="q8",kokoroBrowserDevice:d="wasm",modelProxyUrl:f="/api/models/"}={}){const[w,g]=p.useState(j.IDLE),[N,R]=p.useState(!0),[I,x]=p.useState({whisper:0,kokoro:0}),[z,T]=p.useState(null),[q,$]=p.useState([]),[S,E]=p.useState(null),[L,P]=p.useState(!1),[k,b]=p.useState(""),[K,ae]=p.useState([]),[ie,Y]=p.useState(null),W=p.useRef(j.IDLE),H=p.useRef(!1),V=p.useRef(null),G=p.useRef(null),O=p.useRef(null),B=p.useRef(null),oe=p.useRef(null),ce=p.useRef(null),X=p.useRef([{role:"system",content:s}]),le=p.useRef(e),me=p.useRef(0),we=p.useRef({id:null,enqueuedAt:null,ttsMs:null}),Re=p.useRef(1);p.useEffect(()=>{W.current=w},[w]),p.useEffect(()=>{H.current=L},[L]),p.useEffect(()=>{le.current=e},[e]),p.useEffect(()=>{async function _(){try{const A=await navigator.mediaDevices.enumerateDevices();ae(A.filter(y=>y.kind==="audioinput"))}catch{}}return _(),navigator.mediaDevices.addEventListener("devicechange",_),()=>navigator.mediaDevices.removeEventListener("devicechange",_)},[L]),p.useEffect(()=>{let _=!1;async function A(){try{const y=()=>{var M;const m=we.current;m.enqueuedAt!=null&&m.ttsMs==null&&(m.ttsMs=Math.round(performance.now()-m.enqueuedAt),m.id!=null&&ze(m.id,{timings:{ttsMs:m.ttsMs}})),r==="webspeech"&&((M=G.current)==null||M.pause())};if(r==="webspeech")V.current=Qe({voice:i,rate:n,pitch:u,onPlayStart:y}),x(m=>({...m,kokoro:1}));else if(r==="kokoro"){const{kokoro:m}=await Fe((M,F)=>x(U=>({...U,[M]:F})),{dtype:v,device:d,modelProxyUrl:f});if(_)return;V.current=We(m,{voice:i,speed:t,onPlayStart:y})}else V.current=He({voice:i,speed:t,onPlayStart:y,url:o}),x(m=>({...m,kokoro:1}));if(_)return;B.current=new Worker(new URL("./assets/whisperWorker-BJuP9cl9.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:Z&&Z.tagName.toUpperCase()==="SCRIPT"&&Z.src||new URL("index.cjs",document.baseURI).href),{type:"module"}),B.current.onmessage=m=>{m.data.type==="transcript"?ye(m.data.text,{transcribeMs:Math.round(performance.now()-me.current)}):m.data.type==="progress"?x(M=>({...M,whisper:m.data.progress})):m.data.type==="ready"?(x(M=>({...M,whisper:1})),R(!1)):m.data.type==="error"&&(T(`Whisper: ${m.data.message}`),R(!1))},B.current.onerror=()=>{T("Model load failed. Check WebGPU/WASM browser support."),R(!1)},B.current.postMessage({type:"init",model:c,dtype:h,device:l,modelProxyUrl:f})}catch(y){_||(T("Initialisation failed: "+((y==null?void 0:y.message)??String(y))),R(!1))}}return A(),()=>{var y;_=!0,(y=B.current)==null||y.terminate()}},[r,c,h,l,v,d]);function ge(_,A,y){const m=Re.current++;return $(M=>[...M,{id:m,role:_,content:A,timings:y,time:new Date().toISOString()}]),m}function ze(_,{timings:A}){$(y=>y.map(m=>m.id===_?{...m,timings:{...m.timings,...A}}:m))}async function ye(_,{transcribeMs:A}={}){if(!(_!=null&&_.trim())){g(H.current?j.LISTENING:j.IDLE);return}g(j.THINKING),ge("user",_,A!=null?{transcribeMs:A}:void 0);const y=[...X.current,{role:"user",content:_}];X.current=y,await $e(_,y)}async function $e(_,A){var y,m,M,F;(y=O.current)==null||y.abort(),O.current=new AbortController,(m=V.current)==null||m.cancel();try{if(!le.current)throw new Error("processInput is not provided");const U=_e();let ee="",ue=!1,fe=null;const Ve=performance.now(),Q={id:null,enqueuedAt:null,ttsMs:null};we.current=Q;const ve=te=>{var de;Q.enqueuedAt==null&&(Q.enqueuedAt=performance.now()),(de=V.current)==null||de.enqueue(te)};E("");for await(const te of le.current(_,A,O.current.signal))fe==null&&(fe=Math.round(performance.now()-Ve)),ee+=te,E(ee),U.write(te).forEach(Ce=>{ue||(ue=!0,g(j.SPEAKING)),ve(Ce)});const be=U.flush();be&&(ue||g(j.SPEAKING),ve(be)),Q.id=ge("assistant",ee,{thinkMs:fe,...Q.ttsMs!=null?{ttsMs:Q.ttsMs}:{}}),E(null),X.current=[...X.current,{role:"assistant",content:ee}],await((M=V.current)==null?void 0:M.finished()),r==="webspeech"&&((F=G.current)==null||F.start())}catch(U){E(null),U.name!=="AbortError"&&T(U.message||"Processing failed.")}finally{g(H.current?j.LISTENING:j.IDLE)}}async function Ee(){var _,A;T(null),W.current===j.SPEAKING&&((_=V.current)==null||_.cancel(),(A=O.current)==null||A.abort());try{g(j.LISTENING),P(!0);try{const y=await navigator.mediaDevices.getUserMedia({audio:k?{deviceId:{exact:k}}:!0,video:!1});ce.current=y;const m=new AudioContext;oe.current=m;const M=m.createAnalyser();M.fftSize=256,m.createMediaStreamSource(y).connect(M),Y(M)}catch(y){console.warn("[TZVoiceChat] waveform analyser unavailable:",y)}G.current=await Ze({onSpeechStart:()=>{var y,m;r==="webspeech"&&W.current===j.SPEAKING||(W.current===j.SPEAKING&&((y=V.current)==null||y.cancel(),(m=O.current)==null||m.abort()),g(j.LISTENING))},onSpeechEnd:y=>{var m;r==="webspeech"&&W.current===j.SPEAKING||(g(j.TRANSCRIBING),me.current=performance.now(),(m=B.current)==null||m.postMessage({type:"transcribe",audio:y},[y.buffer]))},onError:y=>{T(y),g(j.IDLE)},deviceId:k||void 0})}catch(y){console.error("[TZVoiceChat] startListening failed:",y),T("Microphone access failed. Allow audio permissions and refresh."),g(j.IDLE),P(!1)}}function De(){var _,A,y,m,M;P(!1),(_=G.current)==null||_.destroy(),G.current=null,(A=ce.current)==null||A.getTracks().forEach(F=>F.stop()),ce.current=null,(y=oe.current)==null||y.close(),oe.current=null,Y(null),(m=V.current)==null||m.cancel(),(M=O.current)==null||M.abort(),g(j.IDLE)}function qe(_){var M;if(!(_!=null&&_.trim()))return;g(j.SPEAKING);const A=_e(),y=A.write(_),m=A.flush();[...y,...m?[m]:[]].forEach(F=>{var U;return(U=V.current)==null?void 0:U.enqueue(F)}),(M=V.current)==null||M.finished().then(()=>{g(H.current?j.LISTENING:j.IDLE)})}return{status:w,loading:N,progress:I,error:z,transcript:q,streamingMessage:S,micEnabled:L,startListening:Ee,stopListening:De,speak:qe,submitText:ye,liveAnalyser:ie,devices:K,selectedMicId:k,setSelectedMicId:b}}function je(e){const s=e.replace("#",""),r=s.length===3?s.split("").map(i=>i+i).join(""):s;return[parseInt(r.slice(0,2),16),parseInt(r.slice(2,4),16),parseInt(r.slice(4,6),16)]}function Ye(e,s,r){e/=255,s/=255,r/=255;const i=Math.max(e,s,r),t=Math.min(e,s,r),o=(i+t)/2;if(i===t)return[0,0,o*100];const n=i-t,u=o>.5?n/(2-i-t):n/(i+t);let c;switch(i){case e:c=((s-r)/n+(s<r?6:0))/6;break;case s:c=((r-e)/n+2)/6;break;default:c=((e-s)/n+4)/6}return[c*360,u*100,o*100]}function Xe(e,s,r){s/=100,r/=100;const i=n=>(n+e/30)%12,t=s*Math.min(r,1-r),o=n=>r-t*Math.max(-1,Math.min(i(n)-3,Math.min(9-i(n),1)));return[Math.round(o(0)*255),Math.round(o(8)*255),Math.round(o(4)*255)]}function C(e,s){const[r,i,t]=je(e),[o,n,u]=Ye(r,i,t),[c,h,l]=Xe(o,n,Math.max(0,Math.min(100,u+s)));return`rgb(${c}, ${h}, ${l})`}function D(e,s){const[r,i,t]=je(e);return`rgba(${r}, ${i}, ${t}, ${s})`}function J(e,s){return e.replace("rgb(","rgba(").replace(")",`, ${s})`)}const se=10;function et({analyser:e}){const s=p.useRef(null),r=p.useRef(null);return p.useEffect(()=>{if(cancelAnimationFrame(r.current),!e)return;const i=s.current;if(!i)return;const t=i.getContext("2d"),o=e.frequencyBinCount,n=new Uint8Array(o),u=Math.max(1,Math.floor(o/se)),c=getComputedStyle(i),h=+c.getPropertyValue("--bar-hue"),l=+c.getPropertyValue("--bar-hue-range"),v=+c.getPropertyValue("--bar-sat"),d=+c.getPropertyValue("--bar-lit"),f=+c.getPropertyValue("--bar-lit-range"),w=()=>{r.current=requestAnimationFrame(w),e.getByteFrequencyData(n);const g=i.width,N=i.height;t.clearRect(0,0,g,N);const R=(g-(se-1)*2)/se;for(let I=0;I<se;I++){const x=n[I*u]/255,z=Math.max(3,x*N*.88);t.fillStyle=`hsl(${h+x*l}, ${v}%, ${d+x*f}%)`,t.beginPath(),t.roundRect(I*(R+2),(N-z)/2,R,z,[2]),t.fill()}};return w(),()=>cancelAnimationFrame(r.current)},[e]),a.jsx("canvas",{ref:s,width:55,height:35,className:"ai-btn__canvas"})}function Te({status:e="idle",active:s=!1,loading:r=!1,analyser:i=null,onToggle:t,devices:o=[],selectedMicId:n="",onDeviceChange:u,inputData:c="",sendData:h,accentColor:l="#f97316",uiColor:v="#64748b",size:d=70,barHue:f=25,barHueRange:w=20,barSat:g=88,barLit:N=65,barLitRange:R=20}){var P;const[I,x]=p.useState(!1),z=p.useRef(null);p.useEffect(()=>{if(!I)return;function k(b){var K;(K=z.current)!=null&&K.contains(b.target)||x(!1)}return document.addEventListener("pointerdown",k),()=>document.removeEventListener("pointerdown",k)},[I]);function T(k){u==null||u(k),x(!1)}const q=p.useMemo(()=>{const k=C(l,-8),b=C(l,-15),K=C(l,-22),ae=C(l,-30),ie=C(l,-42),Y=C(l,8),W=C(l,20),H=C(l,30),V=C(v,-22),G=C(v,-30),O=C(v,18),B=C(v,37);return{"--tz-size":`${d}px`,"--tz-a":l,"--tz-a-d8":k,"--tz-a-d15":b,"--tz-a-d22":K,"--tz-a-d30":ae,"--tz-a-d42":ie,"--tz-a-l8":Y,"--tz-a-l20":W,"--tz-a-l30":H,"--tz-a-25":D(l,.25),"--tz-a-28":D(l,.28),"--tz-a-30":D(l,.3),"--tz-a-32":D(l,.32),"--tz-a-34":D(l,.34),"--tz-a-35":D(l,.35),"--tz-a-38":D(l,.38),"--tz-a-45":D(l,.45),"--tz-a-50":D(l,.5),"--tz-a-55":D(l,.55),"--tz-a-60":D(l,.6),"--tz-a-65":D(l,.65),"--tz-a-68":D(l,.68),"--tz-u":v,"--tz-u-d22":V,"--tz-u-d30":G,"--tz-u-l18":O,"--tz-u-l37":B,"--tz-u-30":D(v,.3),"--tz-u-55":D(v,.55),"--tz-u-d30-a85":J(G,.85),"--tz-u-l18-a18":J(O,.18),"--tz-u-l18-a20":J(O,.2),"--tz-u-l18-a32":J(O,.32),"--tz-u-d22-a90":J(V,.9),"--bar-hue":f,"--bar-hue-range":w,"--bar-sat":g,"--bar-lit":N,"--bar-lit-range":R}},[l,v,d,f,w,g,N,R]),$=((P=o.find(k=>k.deviceId===n))==null?void 0:P.label)||(n?`Mic ${n.slice(0,6)}…`:"Default mic"),S=c.trim().length>0,E=S?"ready":s?e:"off";let L;return S?L=a.jsx("svg",{className:"ai-btn__mic",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:a.jsx("path",{d:"M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"})}):!s||e==="idle"?L=a.jsxs("svg",{className:"ai-btn__mic",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[a.jsx("path",{fillOpacity:"0.52",d:"M12 1a4 4 0 0 1 4 4v6a4 4 0 0 1-8 0V5a4 4 0 0 1 4-4zm6 10a1 1 0 0 1 2 0 8 8 0 0 1-7 7.94V21h2a1 1 0 0 1 0 2H9a1 1 0 0 1 0-2h2v-2.06A8 8 0 0 1 4 11a1 1 0 0 1 2 0 6 6 0 0 0 12 0z"}),a.jsx("path",{fill:"white",fillOpacity:"0.98",d:"M14.5 0L15.65 3.45L19.1 4.6L15.65 5.75L14.5 9.2L13.35 5.75L9.9 4.6L13.35 3.45Z"}),a.jsx("path",{fill:"white",fillOpacity:"0.88",d:"M19 8.62L19.75 10.75L21.88 11.5L19.75 12.25L19 14.38L18.25 12.25L16.12 11.5L18.25 10.75Z"})]}):e==="listening"?L=a.jsx(et,{analyser:i}):e==="transcribing"?L=a.jsx("div",{className:"ai-btn__bars ai-btn__bars--transcribing",children:Array.from({length:7},(k,b)=>a.jsx("span",{style:{animationDelay:`${b*.1}s`}},b))}):e==="thinking"?L=a.jsxs("div",{className:"ai-btn__dots",children:[a.jsx("span",{}),a.jsx("span",{style:{animationDelay:"0.18s"}}),a.jsx("span",{style:{animationDelay:"0.36s"}})]}):e==="speaking"&&(L=a.jsx("div",{className:"ai-btn__bars ai-btn__bars--speaking",children:Array.from({length:7},(k,b)=>a.jsx("span",{style:{animationDelay:`${b*.11}s`}},b))})),a.jsxs("div",{className:"ai-btn-root",style:q,children:[a.jsxs("div",{className:`ai-btn-rings ai-btn-rings--${E}`,"aria-hidden":"true",children:[a.jsx("span",{className:"ai-ring ai-ring--1"}),a.jsx("span",{className:"ai-ring ai-ring--2"})]}),a.jsxs("button",{className:`ai-btn ai-btn--${E}`,disabled:r,onClick:S?()=>h==null?void 0:h(c):t,"aria-label":S?"Send message":s?"Stop assistant":"Start assistant","aria-pressed":S?void 0:s,children:[L,s&&!S&&a.jsx("span",{className:"ai-btn__hover-stop","aria-hidden":"true",children:"■"})]}),a.jsxs("div",{className:`ai-mic-sel${I?" open":""}`,ref:z,children:[a.jsxs("button",{className:"ai-mic-sel__trigger",onClick:()=>x(k=>!k),title:"Change microphone","aria-label":"Change microphone","aria-expanded":I,children:[a.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[a.jsx("path",{d:"M12 1a4 4 0 0 1 4 4v6a4 4 0 0 1-8 0V5a4 4 0 0 1 4-4z"}),a.jsx("path",{d:"M5 11a1 1 0 0 0-2 0 9 9 0 0 0 8 8.94V22H9a1 1 0 0 0 0 2h6a1 1 0 0 0 0-2h-2v-2.06A9 9 0 0 0 21 11a1 1 0 0 0-2 0 7 7 0 0 1-14 0z"})]}),a.jsx("span",{className:"ai-mic-sel__label",children:$}),a.jsx("svg",{className:`ai-mic-sel__caret${I?" open":""}`,width:"9",height:"9",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:a.jsx("path",{d:"M12 16L4 8h16l-8 8z"})})]}),I&&a.jsxs("ul",{className:"ai-mic-sel__menu",role:"listbox","aria-label":"Select microphone",children:[a.jsx("li",{role:"option",className:`ai-mic-sel__option${n===""?" selected":""}`,onClick:()=>T(""),"aria-selected":n==="",children:"Default microphone"}),o.map(k=>a.jsx("li",{role:"option",className:`ai-mic-sel__option${n===k.deviceId?" selected":""}`,onClick:()=>T(k.deviceId),"aria-selected":n===k.deviceId,children:k.label||`Microphone ${k.deviceId.slice(0,8)}`},k.deviceId))]})]})]})}async function Ae(e,s,r="/api/chat"){var u;const i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},signal:s,body:JSON.stringify({messages:e})});if(!i.ok){const c=await i.text();throw new Error(`Server error: ${i.status} ${c}`)}const t=(u=i.body)==null?void 0:u.getReader();if(!t){const c=await i.json();return{stream:async function*(){yield c.text}}}const o=new TextDecoder;let n="";return{stream:async function*(){var h,l,v;let c="";for(;;){const{value:d,done:f}=await t.read();if(f)break;n+=o.decode(d,{stream:!0});const w=n.split(`
|
|
2
|
+
`);n=w.pop();for(const g of w){const N=g.trim();if(!N.startsWith("data:"))continue;const R=N.slice(5).trimStart();if(R==="[DONE]")return;try{const x=(v=(l=(h=JSON.parse(R).choices)==null?void 0:h[0])==null?void 0:l.delta)==null?void 0:v.content;x&&(c&&/\w/.test(c)&&/\w/.test(x[0])&&(yield" "),c=x[x.length-1],yield x)}catch{}}}}}}function Ne(e,s,r){return{stream:async function*(){const i=[];let t=null,o=!1,n="";const u=({data:h})=>{h.type==="token"?(i.push(h.text),t==null||t(),t=null):h.type==="done"&&(o=!0,t==null||t(),t=null)},c=()=>{o=!0,t==null||t(),t=null};e.addEventListener("message",u),r==null||r.addEventListener("abort",c),e.postMessage({type:"generate",messages:s});try{for(;!o||i.length>0;)if(i.length>0){const h=i.shift();n&&/\w/.test(n)&&/\w/.test(h[0])&&(yield" "),n=h[h.length-1],yield h}else await new Promise(h=>{t=h})}finally{e.removeEventListener("message",u),r==null||r.removeEventListener("abort",c)}}}}function Ie({apiBase:e="/api",systemPrompt:s}={}){const[r,i]=p.useState(!0),[t,o]=p.useState(0),[n,u]=p.useState(""),[c,h]=p.useState({}),[l,v]=p.useState(null),[d,f]=p.useState({}),w=p.useRef(null),g=p.useRef(null);p.useEffect(()=>{let x=!1;async function z(){let T=!0,q={};try{const S=await(await fetch(`${e}/config`)).json();T=S.hasApiKey,v(S),q={ttsProvider:S.ttsProvider||"server-kokoro",ttsVoice:S.ttsProvider==="openai"?S.openaiTtsVoice||"alloy":S.kokoroVoice||"af_bella",ttsServerUrl:`${e}/tts`,ttsSpeed:S.kokoroSpeed??1,ttsSpeechRate:S.webSpeechRate??1,ttsSpeechPitch:S.webSpeechPitch??1,whisperModel:S.whisperModel||"onnx-community/whisper-tiny.en",whisperDtype:S.whisperDtype||"q8",whisperDevice:S.whisperDevice||"cpu",kokoroDtype:S.kokoroDtype||"q8",kokoroBrowserDevice:S.kokoroBrowserDevice||"wasm",modelProxyUrl:`${e}/models/`}}catch{q={ttsProvider:"server-kokoro",ttsServerUrl:`${e}/tts`,modelProxyUrl:`${e}/models/`}}if(!x)if(T)w.current=async function*($,S,E){const{stream:L}=await Ae(S,E,`${e}/chat`);yield*L()},h(q),i(!1);else{u("No API key — using SmolLM2-360M-Instruct locally in your browser.");const $=new Worker(new URL("./assets/llmWorker-CVEGn6yI.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:Z&&Z.tagName.toUpperCase()==="SCRIPT"&&Z.src||new URL("index.cjs",document.baseURI).href),{type:"module"});g.current=$,$.onmessage=S=>{S.data.type==="progress"?o(S.data.progress??0):S.data.type==="ready"?(o(1),w.current=async function*(E,L,P){const{stream:k}=Ne($,L,P);yield*k()},h(q),i(!1)):S.data.type==="error"&&i(!1)},$.onerror=()=>i(!1),$.postMessage({type:"init",modelProxyUrl:`${e}/models/`})}}return z(),()=>{var T;x=!0,(T=g.current)==null||T.terminate()}},[e]);const N=Me({processInput:async function*(x,z,T){w.current&&(yield*w.current(x,z,T))},...s?{systemPrompt:s}:{},...c});p.useEffect(()=>{let x=!1;async function z(){const q={};typeof performance<"u"&&performance.memory&&(q.browser=performance.memory.usedJSHeapSize);try{const $=await fetch(`${e}/stats`);$.ok&&(q.server=(await $.json()).rss)}catch{}x||f(q)}z();const T=setInterval(z,3e3);return()=>{x=!0,clearInterval(T)}},[e]);const{micEnabled:R,stopListening:I}=N;return p.useEffect(()=>{if(!R)return;const x=z=>{z.key==="Escape"&&I()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[R,I]),{chat:N,info:l,config:c,memory:d,llmProgress:t,note:n,loading:N.loading||r}}const Le=(e,s)=>e==="webgpu"&&(s==="q4"||s==="q8")?"fp32":s,pe=e=>e>=1e3?`${(e/1e3).toFixed(1)} s`:`${e} ms`,ke=e=>`${(e/1048576).toFixed(0)} MB`;function tt(e){switch(e.ttsProvider){case"openai":return`OpenAI · ${e.openaiTtsModel} · ${e.ttsVoice}`;case"webspeech":return`Web Speech API · rate ${e.ttsSpeechRate} · pitch ${e.ttsSpeechPitch}`;case"server-kokoro":return`Kokoro (server) · ${e.ttsVoice} · ${e.kokoroDtype}/${e.kokoroDevice}`;default:return`Kokoro (browser) · ${e.ttsVoice} · ${Le(e.kokoroBrowserDevice,e.kokoroDtype)}/${e.kokoroBrowserDevice}`}}const nt=e=>e.replace(/\b\w/g,s=>s.toUpperCase());function st({apiBase:e="/api",title:s="Voice Assistant",showInfo:r=!0,systemPrompt:i,className:t=""}={}){const{chat:o,info:n,config:u,memory:c,llmProgress:h,note:l,loading:v}=Ie({apiBase:e,systemPrompt:i}),{status:d,progress:f,error:w,transcript:g,streamingMessage:N,micEnabled:R,startListening:I,stopListening:x,submitText:z,liveAnalyser:T,devices:q,selectedMicId:$,setSelectedMicId:S}=o,[E,L]=p.useState(""),P=p.useRef(null);p.useEffect(()=>{var b;(b=P.current)==null||b.scrollIntoView({behavior:N!==null?"auto":"smooth"})},[g,N]);const k=n&&u.whisperDevice&&[["STT",`Whisper · ${(u.whisperModel||n.whisperModel).split("/").pop()} · ${Le(u.whisperDevice,u.whisperDtype)}/${u.whisperDevice}`],["TTS",tt({...n,...u})],["Chat",n.hasApiKey?`${n.chatProvider} · ${n.chatModel}`:"SmolLM2-360M-Instruct (in-browser)"],["Memory",[c.browser!=null?`browser heap ${ke(c.browser)}`:"browser heap n/a",c.server!=null?`server ${ke(c.server)}`:null].filter(Boolean).join(" · ")]];return a.jsxs("div",{className:`tz-va ${t}`.trim(),children:[a.jsxs("section",{className:"tz-va__card tz-va__header",children:[a.jsx("h1",{children:s}),a.jsx("span",{className:`tz-va__chip tz-va__chip--${d}`,children:nt(d)})]}),r&&k&&a.jsx("section",{className:"tz-va__card tz-va__info",children:k.map(([b,K])=>a.jsxs("div",{className:"tz-va__info-row",children:[a.jsx("span",{className:"tz-va__info-label",children:b}),a.jsx("span",{className:"tz-va__info-value",children:K})]},b))}),a.jsxs("section",{className:"tz-va__card",children:[v&&a.jsxs("div",{className:"tz-va__progress",children:[a.jsxs("label",{children:["Whisper STT",a.jsx("div",{className:"tz-va__bar",children:a.jsx("span",{style:{width:`${f.whisper*100}%`}})})]}),a.jsxs("label",{children:["Kokoro TTS",a.jsx("div",{className:"tz-va__bar",children:a.jsx("span",{style:{width:`${f.kokoro*100}%`}})})]}),h>0&&a.jsxs("label",{children:["Local LLM",a.jsx("div",{className:"tz-va__bar",children:a.jsx("span",{style:{width:`${h*100}%`}})})]})]}),a.jsx("div",{className:"tz-va__button",children:a.jsx(Te,{status:d,active:R,loading:v,analyser:T,onToggle:R?x:I,devices:q,selectedMicId:$,onDeviceChange:S,inputData:E,sendData:b=>{L(""),z(b)}})}),a.jsx("div",{className:"tz-va__input-row",children:a.jsx("input",{type:"text",className:"tz-va__input",value:E,onChange:b=>L(b.target.value),onKeyDown:b=>{b.key==="Enter"&&E.trim()&&(L(""),z(E))},placeholder:"Type a message…",disabled:v})}),a.jsx("p",{className:"tz-va__note",children:v?f.kokoro<1?"Loading Kokoro TTS…":f.whisper<1?"Loading Whisper STT…":h>0&&h<1?"Loading local LLM (SmolLM2-360M, ~200 MB)…":"Finishing up…":"Ready."}),l&&a.jsx("p",{className:"tz-va__note",children:l})]}),a.jsxs("section",{className:"tz-va__card tz-va__transcript",children:[g.map(b=>a.jsxs("div",{className:`tz-va__message tz-va__message--${b.role}`,children:[a.jsx("small",{children:b.role==="user"?"You":"Assistant"}),a.jsx("p",{children:b.content}),b.timings&&a.jsxs("div",{className:"tz-va__timings",children:[b.timings.transcribeMs!=null&&a.jsxs("span",{children:["transcribe ",pe(b.timings.transcribeMs)]}),b.timings.thinkMs!=null&&a.jsxs("span",{children:["think ",pe(b.timings.thinkMs)]}),b.timings.ttsMs!=null&&a.jsxs("span",{children:["tts ",pe(b.timings.ttsMs)]})]})]},b.id)),N!==null&&a.jsxs("div",{className:"tz-va__message tz-va__message--assistant tz-va__message--streaming",children:[a.jsx("small",{children:"Assistant"}),a.jsxs("p",{children:[N,a.jsx("span",{className:"tz-va__cursor"})]})]}),a.jsx("div",{ref:P})]}),w?a.jsxs("section",{className:"tz-va__card",children:[a.jsx("strong",{children:"Error:"}),a.jsx("p",{children:w})]}):null]})}exports.AIAssistantButton=Te;exports.STATES=j;exports.TZVoiceChat=Me;exports.VoiceAssistant=st;exports.createLocalChatStream=Ne;exports.sendChatRequest=Ae;exports.useVoiceAssistant=Ie;
|