tz-voice-chat 1.0.0 → 1.0.1
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/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
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 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;
|
package/dist/index.js
CHANGED
package/package.json
CHANGED