tz-voice-chat 1.0.0
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 +180 -0
- package/dist/assets/whisperWorker-BJuP9cl9.js +1 -0
- package/dist/index.cjs +1 -0
- package/dist/index.js +686 -0
- package/dist/style.css +1 -0
- package/package.json +34 -0
package/README.md
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
# tz-voice-chat
|
|
2
|
+
|
|
3
|
+
A self-contained React hook and UI component that wire together a full voice-chat pipeline:
|
|
4
|
+
|
|
5
|
+
```
|
|
6
|
+
Microphone → VAD → Whisper STT → your AI function → Kokoro / OpenAI / WebSpeech TTS
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
You provide the AI logic. The hook handles everything else.
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm install tz-voice-chat
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Peer dependencies (install separately):
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
npm install react @huggingface/transformers @ricky0123/vad-web
|
|
23
|
+
# Optional — only for ttsProvider: 'kokoro' (browser-side synthesis):
|
|
24
|
+
npm install kokoro-js
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## Quick start
|
|
30
|
+
|
|
31
|
+
```jsx
|
|
32
|
+
import { TZVoiceChat, AIAssistantButton } from 'tz-voice-chat';
|
|
33
|
+
import 'tz-voice-chat/style.css';
|
|
34
|
+
|
|
35
|
+
function MyApp() {
|
|
36
|
+
const {
|
|
37
|
+
status, // 'idle' | 'listening' | 'transcribing' | 'thinking' | 'speaking'
|
|
38
|
+
loading, // true while Whisper + TTS models are loading
|
|
39
|
+
progress, // { whisper: 0–1, kokoro: 0–1 }
|
|
40
|
+
error,
|
|
41
|
+
transcript, // [{ role, content, time }]
|
|
42
|
+
streamingMessage,// partial assistant response, or null
|
|
43
|
+
micEnabled,
|
|
44
|
+
startListening,
|
|
45
|
+
stopListening,
|
|
46
|
+
speak, // speak(text) — directly synthesise any text
|
|
47
|
+
liveAnalyser, // AnalyserNode for waveform UI, or null
|
|
48
|
+
devices, // MediaDeviceInfo[] — audio inputs
|
|
49
|
+
selectedMicId,
|
|
50
|
+
setSelectedMicId,
|
|
51
|
+
} = TZVoiceChat({
|
|
52
|
+
// ── Required ─────────────────────────────────────────────────────────
|
|
53
|
+
// Async generator that receives the user utterance, full conversation
|
|
54
|
+
// history, and an AbortSignal. Yield response tokens/chunks.
|
|
55
|
+
processInput: async function* (text, history, signal) {
|
|
56
|
+
const res = await fetch('/api/chat', {
|
|
57
|
+
method: 'POST',
|
|
58
|
+
headers: { 'Content-Type': 'application/json' },
|
|
59
|
+
body: JSON.stringify({ messages: history }),
|
|
60
|
+
signal,
|
|
61
|
+
});
|
|
62
|
+
const reader = res.body.getReader();
|
|
63
|
+
const dec = new TextDecoder();
|
|
64
|
+
let buf = '';
|
|
65
|
+
while (true) {
|
|
66
|
+
const { value, done } = await reader.read();
|
|
67
|
+
if (done) break;
|
|
68
|
+
buf += dec.decode(value, { stream: true });
|
|
69
|
+
const lines = buf.split('\n');
|
|
70
|
+
buf = lines.pop();
|
|
71
|
+
for (const line of lines) {
|
|
72
|
+
const data = line.replace(/^data:\s*/, '');
|
|
73
|
+
if (data === '[DONE]') return;
|
|
74
|
+
try { const token = JSON.parse(data).choices?.[0]?.delta?.content; if (token) yield token; }
|
|
75
|
+
catch (_) {}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
},
|
|
79
|
+
|
|
80
|
+
// ── Optional ─────────────────────────────────────────────────────────
|
|
81
|
+
ttsProvider: 'server-kokoro', // 'server-kokoro' | 'kokoro' | 'openai' | 'webspeech'
|
|
82
|
+
ttsVoice: 'af_bella',
|
|
83
|
+
ttsServerUrl: '/api/tts', // POST endpoint for server-side TTS
|
|
84
|
+
whisperModel: 'onnx-community/whisper-tiny.en',
|
|
85
|
+
whisperDtype: 'q8',
|
|
86
|
+
whisperDevice: 'cpu', // 'cpu' | 'webgpu'
|
|
87
|
+
modelProxyUrl: '/api/models/', // proxies HuggingFace model downloads
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
return (
|
|
91
|
+
<div>
|
|
92
|
+
<p>Status: {status}</p>
|
|
93
|
+
<button onClick={micEnabled ? stopListening : startListening} disabled={loading}>
|
|
94
|
+
{micEnabled ? 'Stop' : 'Start'}
|
|
95
|
+
</button>
|
|
96
|
+
<button onClick={() => speak('Hello! How can I help you?')}>Say hello</button>
|
|
97
|
+
{transcript.map((msg, i) => (
|
|
98
|
+
<p key={i}><b>{msg.role}</b>: {msg.content}</p>
|
|
99
|
+
))}
|
|
100
|
+
</div>
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
---
|
|
106
|
+
|
|
107
|
+
## API
|
|
108
|
+
|
|
109
|
+
### `TZVoiceChat(options)`
|
|
110
|
+
|
|
111
|
+
#### Required option
|
|
112
|
+
|
|
113
|
+
| Option | Type | Description |
|
|
114
|
+
|---|---|---|
|
|
115
|
+
| `processInput` | `async function*(text, history, signal)` | Your AI processor. Called after each user utterance. `history` is the full `[{role,content}]` array. Yield response tokens. |
|
|
116
|
+
|
|
117
|
+
#### Optional options
|
|
118
|
+
|
|
119
|
+
| Option | Default | Description |
|
|
120
|
+
|---|---|---|
|
|
121
|
+
| `systemPrompt` | friendly voice assistant prompt | System message prepended to all conversations |
|
|
122
|
+
| `ttsProvider` | `'server-kokoro'` | `'server-kokoro'` \| `'kokoro'` \| `'openai'` \| `'webspeech'` |
|
|
123
|
+
| `ttsVoice` | `'af_bella'` | Voice name for Kokoro / OpenAI TTS |
|
|
124
|
+
| `ttsServerUrl` | `'/api/tts'` | POST endpoint for server-side TTS (receives `{text, voice}`, returns audio) |
|
|
125
|
+
| `ttsSpeechRate` | `1` | WebSpeech rate |
|
|
126
|
+
| `ttsSpeechPitch` | `1` | WebSpeech pitch |
|
|
127
|
+
| `whisperModel` | `'onnx-community/whisper-tiny.en'` | HuggingFace model ID |
|
|
128
|
+
| `whisperDtype` | `'q8'` | `'q4'` \| `'q8'` \| `'fp32'` |
|
|
129
|
+
| `whisperDevice` | `'cpu'` | `'cpu'` \| `'webgpu'` |
|
|
130
|
+
| `kokoroDtype` | `'q8'` | Browser Kokoro dtype (when `ttsProvider: 'kokoro'`) |
|
|
131
|
+
| `kokoroBrowserDevice` | `'wasm'` | `'wasm'` \| `'webgpu'` |
|
|
132
|
+
| `modelProxyUrl` | `'/api/models/'` | Base URL for model downloads (proxies HuggingFace) |
|
|
133
|
+
|
|
134
|
+
#### Return value
|
|
135
|
+
|
|
136
|
+
| Field | Type | Description |
|
|
137
|
+
|---|---|---|
|
|
138
|
+
| `status` | `string` | `'idle'` \| `'listening'` \| `'transcribing'` \| `'thinking'` \| `'speaking'` |
|
|
139
|
+
| `loading` | `boolean` | `true` while Whisper + TTS are loading |
|
|
140
|
+
| `progress` | `{whisper:number, kokoro:number}` | Per-model load progress (0–1) |
|
|
141
|
+
| `error` | `string\|null` | Last error message |
|
|
142
|
+
| `transcript` | `{role,content,time}[]` | Completed conversation turns |
|
|
143
|
+
| `streamingMessage` | `string\|null` | Partial assistant response being streamed |
|
|
144
|
+
| `micEnabled` | `boolean` | Whether microphone is open |
|
|
145
|
+
| `startListening()` | `() => Promise<void>` | Open microphone and start pipeline |
|
|
146
|
+
| `stopListening()` | `() => void` | Close microphone and cancel in-progress pipeline |
|
|
147
|
+
| `speak(text)` | `(text:string) => void` | Synthesise and play text immediately |
|
|
148
|
+
| `liveAnalyser` | `AnalyserNode\|null` | Real-time frequency data for waveform UI |
|
|
149
|
+
| `devices` | `MediaDeviceInfo[]` | Available audio input devices |
|
|
150
|
+
| `selectedMicId` | `string` | Selected device ID (`''` = system default) |
|
|
151
|
+
| `setSelectedMicId` | `(id:string) => void` | Select an audio input device |
|
|
152
|
+
|
|
153
|
+
---
|
|
154
|
+
|
|
155
|
+
## Server requirements
|
|
156
|
+
|
|
157
|
+
For `ttsProvider: 'server-kokoro'` or `'openai'`:
|
|
158
|
+
|
|
159
|
+
- `POST /api/tts` — accepts `{ text: string, voice?: string }`, returns audio (`audio/wav` or `audio/mpeg`)
|
|
160
|
+
|
|
161
|
+
For model downloads (Whisper STT, browser Kokoro TTS):
|
|
162
|
+
|
|
163
|
+
- `GET /api/models/*` — proxies HuggingFace Hub downloads (or set `modelProxyUrl` to a direct URL)
|
|
164
|
+
|
|
165
|
+
The included example app ([`src/App.jsx`](../../src/App.jsx)) demonstrates a complete Express server setup for all of the above.
|
|
166
|
+
|
|
167
|
+
---
|
|
168
|
+
|
|
169
|
+
## Infrastructure diagram
|
|
170
|
+
|
|
171
|
+
```
|
|
172
|
+
TZVoiceChat hook
|
|
173
|
+
├── VAD (@ricky0123/vad-web, IIFE — loaded via <script> in index.html)
|
|
174
|
+
├── Whisper Worker (Web Worker — @huggingface/transformers, auto-speech-recognition)
|
|
175
|
+
├── TTS Queue (server-kokoro | kokoro | openai | webspeech)
|
|
176
|
+
└── processInput ← YOU provide this (async generator)
|
|
177
|
+
|
|
178
|
+
AIAssistantButton component
|
|
179
|
+
└── 5-state animated button with waveform visualiser and mic selector
|
|
180
|
+
```
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
(function(){"use strict";let p=null,c=Promise.resolve();self.onmessage=async t=>{var g,d;const{type:l,audio:n}=t.data;if(l==="init"){const a=t.data.model||"onnx-community/whisper-tiny.en",e=t.data.device||"cpu",i=t.data.modelProxyUrl||"/api/models/";let r=t.data.dtype||"q8";e==="webgpu"&&(r==="q4"||r==="q8")&&(console.warn(`[Whisper worker] dtype "${r}" not supported on WebGPU — using "fp32".`),r="fp32");try{const{pipeline:s,env:o}=await import("/vendor/transformers/transformers.min.js");o.remoteHost=i,(d=(g=o==null?void 0:o.backends)==null?void 0:g.onnx)!=null&&d.wasm&&(o.backends.onnx.wasm.wasmPaths="/vendor/transformers/"),p=await s("automatic-speech-recognition",a,{dtype:r,device:e,progress_callback:({status:m,progress:y}={})=>{self.postMessage({type:"progress",status:m,progress:(y??0)/100})}}),self.postMessage({type:"ready"})}catch(s){self.postMessage({type:"error",message:String((s==null?void 0:s.message)??s)})}return}l==="transcribe"&&(console.log("[Whisper worker] transcribe — samples:",n==null?void 0:n.length),c=c.then(async()=>{var a;try{if(!p){console.warn("[Whisper worker] pipeline not ready, dropping segment"),self.postMessage({type:"transcript",text:""});return}const e=await p(n),i=(e==null?void 0:e.text)??((a=e==null?void 0:e[0])==null?void 0:a.text)??"";self.postMessage({type:"transcript",text:i})}catch(e){console.error("[Whisper worker] transcription error:",e),self.postMessage({type:"transcript",text:""})}}))}})();
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +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;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,686 @@
|
|
|
1
|
+
import { useState as L, useRef as _, useEffect as U, useMemo as ke } from "react";
|
|
2
|
+
import { jsx as v, jsxs as V } from "react/jsx-runtime";
|
|
3
|
+
function he() {
|
|
4
|
+
let e = "";
|
|
5
|
+
function s() {
|
|
6
|
+
const t = [];
|
|
7
|
+
for (; ; ) {
|
|
8
|
+
const r = /([.!?]{1,3})(\s|$)/.exec(e);
|
|
9
|
+
if (r) {
|
|
10
|
+
const n = e.slice(0, r.index + r[0].length).trim();
|
|
11
|
+
if (n.length >= 10) {
|
|
12
|
+
t.push(n), e = e.slice(r.index + r[0].length);
|
|
13
|
+
continue;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
if (e.length >= 25) {
|
|
17
|
+
const n = /[,;:—–](\s|$)/.exec(e);
|
|
18
|
+
if (n) {
|
|
19
|
+
const o = e.slice(0, n.index + n[0].length).trim();
|
|
20
|
+
if (o.length >= 20) {
|
|
21
|
+
t.push(o), e = e.slice(n.index + n[0].length);
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
if (e.length >= 45) {
|
|
27
|
+
const n = e.lastIndexOf(" ", 44), o = n > 10 ? n : 45;
|
|
28
|
+
t.push(e.slice(0, o).trim()), e = e.slice(o).trimStart();
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
break;
|
|
32
|
+
}
|
|
33
|
+
return t;
|
|
34
|
+
}
|
|
35
|
+
return {
|
|
36
|
+
write(t) {
|
|
37
|
+
return e += t, s();
|
|
38
|
+
},
|
|
39
|
+
flush() {
|
|
40
|
+
const t = e.trim();
|
|
41
|
+
return e = "", t;
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
async function Se(e, {
|
|
46
|
+
dtype: s = "q8",
|
|
47
|
+
device: t = "cpu",
|
|
48
|
+
modelProxyUrl: r = "/api/models/"
|
|
49
|
+
} = {}) {
|
|
50
|
+
var l, b;
|
|
51
|
+
const { env: n } = await import(
|
|
52
|
+
/* @vite-ignore */
|
|
53
|
+
"/vendor/transformers/transformers.min.js"
|
|
54
|
+
);
|
|
55
|
+
n.remoteHost = r, (b = (l = n == null ? void 0 : n.backends) == null ? void 0 : l.onnx) != null && b.wasm && (n.backends.onnx.wasm.wasmPaths = "/vendor/transformers/"), n != null && n.onnx && (n.onnx.logSeverityLevel = 3);
|
|
56
|
+
const o = await import(
|
|
57
|
+
/* @vite-ignore */
|
|
58
|
+
"/vendor/kokoro/kokoro.web.js"
|
|
59
|
+
), { KokoroTTS: i } = o;
|
|
60
|
+
let g = s;
|
|
61
|
+
t === "webgpu" && (s === "q4" || s === "q8") && (console.warn(`[modelLoader] dtype "${s}" not supported on WebGPU — using "fp32".`), g = "fp32");
|
|
62
|
+
let a = 0;
|
|
63
|
+
const h = (d) => {
|
|
64
|
+
typeof (d == null ? void 0 : d.progress) == "number" && (a = Math.max(a, d.progress / 100), e == null || e("kokoro", Math.min(0.99, a)));
|
|
65
|
+
};
|
|
66
|
+
async function p(d, R) {
|
|
67
|
+
return i.from_pretrained("onnx-community/Kokoro-82M-ONNX", {
|
|
68
|
+
dtype: R,
|
|
69
|
+
device: d,
|
|
70
|
+
progress_callback: h
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
let c;
|
|
74
|
+
try {
|
|
75
|
+
c = await p(t, g);
|
|
76
|
+
} catch (d) {
|
|
77
|
+
if (t !== "wasm")
|
|
78
|
+
console.warn(`[modelLoader] Kokoro on "${t}" failed (${d == null ? void 0 : d.message}) — falling back to WASM.`), a = 0, c = await p("wasm", s);
|
|
79
|
+
else
|
|
80
|
+
throw d;
|
|
81
|
+
}
|
|
82
|
+
return e == null || e("kokoro", 1), { kokoro: c };
|
|
83
|
+
}
|
|
84
|
+
function Ae(e, { voice: s = "af_bella", onPlayStart: t } = {}) {
|
|
85
|
+
const r = new AudioContext(), n = [];
|
|
86
|
+
let o = !1, i = null, g = !1;
|
|
87
|
+
async function a(c) {
|
|
88
|
+
if (c instanceof AudioBuffer) return c;
|
|
89
|
+
const l = (c == null ? void 0 : c.audio) ?? c;
|
|
90
|
+
if (l instanceof ArrayBuffer) return await r.decodeAudioData(l.slice(0));
|
|
91
|
+
if (l instanceof Float32Array) {
|
|
92
|
+
const b = (c == null ? void 0 : c.samplingRate) ?? 24e3, d = r.createBuffer(1, l.length, b);
|
|
93
|
+
return d.copyToChannel(l, 0), d;
|
|
94
|
+
}
|
|
95
|
+
throw new Error("Unsupported TTS payload");
|
|
96
|
+
}
|
|
97
|
+
async function h(c) {
|
|
98
|
+
await r.resume();
|
|
99
|
+
const l = r.createBufferSource();
|
|
100
|
+
return l.buffer = c, l.connect(r.destination), new Promise((b) => {
|
|
101
|
+
l.onended = () => {
|
|
102
|
+
i === l && (i = null), b();
|
|
103
|
+
}, i = l, l.start(), g || (g = !0, t == null || t());
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
async function p() {
|
|
107
|
+
if (!o) {
|
|
108
|
+
for (o = !0; n.length > 0; ) {
|
|
109
|
+
const c = n.shift();
|
|
110
|
+
try {
|
|
111
|
+
const l = await c;
|
|
112
|
+
l && await h(l);
|
|
113
|
+
} catch (l) {
|
|
114
|
+
console.error("[TtsQueue]", l);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
o = !1;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return {
|
|
121
|
+
enqueue(c) {
|
|
122
|
+
n.push(e.generate(c, { voice: s }).then(a)), p();
|
|
123
|
+
},
|
|
124
|
+
cancel() {
|
|
125
|
+
if (n.length = 0, i) {
|
|
126
|
+
try {
|
|
127
|
+
i.stop();
|
|
128
|
+
} catch {
|
|
129
|
+
}
|
|
130
|
+
i = null;
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
async finished() {
|
|
134
|
+
for (; o || n.length > 0; ) await new Promise((c) => setTimeout(c, 200));
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
function Ie({ voice: e = "", onPlayStart: s, url: t = "/api/tts" } = {}) {
|
|
139
|
+
const r = new AudioContext(), n = [];
|
|
140
|
+
let o = !1, i = null, g = !1;
|
|
141
|
+
async function a(c) {
|
|
142
|
+
const l = { text: c };
|
|
143
|
+
e && (l.voice = e);
|
|
144
|
+
const b = await fetch(t, {
|
|
145
|
+
method: "POST",
|
|
146
|
+
headers: { "Content-Type": "application/json" },
|
|
147
|
+
body: JSON.stringify(l)
|
|
148
|
+
});
|
|
149
|
+
if (!b.ok) throw new Error(`TTS ${b.status}: ${await b.text()}`);
|
|
150
|
+
return r.decodeAudioData(await b.arrayBuffer());
|
|
151
|
+
}
|
|
152
|
+
async function h(c) {
|
|
153
|
+
await r.resume();
|
|
154
|
+
const l = r.createBufferSource();
|
|
155
|
+
return l.buffer = c, l.connect(r.destination), new Promise((b) => {
|
|
156
|
+
l.onended = () => {
|
|
157
|
+
i === l && (i = null), b();
|
|
158
|
+
}, i = l, l.start(), g || (g = !0, s == null || s());
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
async function p() {
|
|
162
|
+
if (!o) {
|
|
163
|
+
for (o = !0; n.length > 0; ) {
|
|
164
|
+
const c = n.shift();
|
|
165
|
+
try {
|
|
166
|
+
await h(await c);
|
|
167
|
+
} catch (l) {
|
|
168
|
+
console.error("[ServerTTS]", l);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
o = !1;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return {
|
|
175
|
+
enqueue(c) {
|
|
176
|
+
c != null && c.trim() && (n.push(a(c)), p());
|
|
177
|
+
},
|
|
178
|
+
cancel() {
|
|
179
|
+
if (n.length = 0, i) {
|
|
180
|
+
try {
|
|
181
|
+
i.stop();
|
|
182
|
+
} catch {
|
|
183
|
+
}
|
|
184
|
+
i = null;
|
|
185
|
+
}
|
|
186
|
+
g = !1;
|
|
187
|
+
},
|
|
188
|
+
async finished() {
|
|
189
|
+
for (; o || n.length > 0; ) await new Promise((c) => setTimeout(c, 100));
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
function Ne({ voice: e = "", rate: s = 1, pitch: t = 1, onPlayStart: r } = {}) {
|
|
194
|
+
const n = [];
|
|
195
|
+
let o = !1, i = !1;
|
|
196
|
+
function g() {
|
|
197
|
+
return e ? speechSynthesis.getVoices().find((p) => p.name === e || p.voiceURI === e) ?? null : null;
|
|
198
|
+
}
|
|
199
|
+
function a() {
|
|
200
|
+
if (o || n.length === 0) return;
|
|
201
|
+
o = !0;
|
|
202
|
+
const h = n.shift(), p = new SpeechSynthesisUtterance(h), c = g();
|
|
203
|
+
c && (p.voice = c), p.rate = s, p.pitch = t, p.onstart = () => {
|
|
204
|
+
i || (i = !0, r == null || r());
|
|
205
|
+
}, p.onend = () => {
|
|
206
|
+
o = !1, a();
|
|
207
|
+
}, p.onerror = (l) => {
|
|
208
|
+
console.error("[WebSpeech TTS] error", l.error), o = !1, a();
|
|
209
|
+
}, speechSynthesis.speak(p);
|
|
210
|
+
}
|
|
211
|
+
return {
|
|
212
|
+
enqueue(h) {
|
|
213
|
+
h != null && h.trim() && (n.push(h), a());
|
|
214
|
+
},
|
|
215
|
+
cancel() {
|
|
216
|
+
n.length = 0, speechSynthesis.cancel(), o = !1, i = !1;
|
|
217
|
+
},
|
|
218
|
+
async finished() {
|
|
219
|
+
for (; o || n.length > 0; ) await new Promise((h) => setTimeout(h, 100));
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
async function Te({ onSpeechStart: e, onSpeechEnd: s, onError: t, deviceId: r }) {
|
|
224
|
+
try {
|
|
225
|
+
const { MicVAD: n } = window.vad;
|
|
226
|
+
return await n.new({
|
|
227
|
+
model: "legacy",
|
|
228
|
+
baseAssetPath: "/vendor/vad/",
|
|
229
|
+
onnxWASMBasePath: "/vendor/ort/",
|
|
230
|
+
additionalAudioConstraints: {
|
|
231
|
+
echoCancellation: !0,
|
|
232
|
+
noiseSuppression: !0,
|
|
233
|
+
autoGainControl: !1,
|
|
234
|
+
...r ? { deviceId: { exact: r } } : {}
|
|
235
|
+
},
|
|
236
|
+
onSpeechStart: () => e == null ? void 0 : e(),
|
|
237
|
+
onSpeechEnd: (i) => {
|
|
238
|
+
console.log("[VAD] onSpeechEnd — samples:", i == null ? void 0 : i.length), s == null || s(i);
|
|
239
|
+
},
|
|
240
|
+
onVADMisfire: () => {
|
|
241
|
+
},
|
|
242
|
+
negativeSpeechThreshold: 0.25,
|
|
243
|
+
positiveSpeechThreshold: 0.5,
|
|
244
|
+
redemptionFrames: 4,
|
|
245
|
+
minSpeechFrames: 3,
|
|
246
|
+
preSpeechPadFrames: 1
|
|
247
|
+
});
|
|
248
|
+
} catch (n) {
|
|
249
|
+
throw t == null || t("VAD initialization failed. Falling back to manual microphone capture."), n;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
const y = {
|
|
253
|
+
IDLE: "idle",
|
|
254
|
+
LISTENING: "listening",
|
|
255
|
+
TRANSCRIBING: "transcribing",
|
|
256
|
+
THINKING: "thinking",
|
|
257
|
+
SPEAKING: "speaking"
|
|
258
|
+
}, ze = "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.";
|
|
259
|
+
function xe({
|
|
260
|
+
processInput: e,
|
|
261
|
+
systemPrompt: s = ze,
|
|
262
|
+
ttsProvider: t = "server-kokoro",
|
|
263
|
+
ttsVoice: r = "af_bella",
|
|
264
|
+
ttsServerUrl: n = "/api/tts",
|
|
265
|
+
ttsSpeechRate: o = 1,
|
|
266
|
+
ttsSpeechPitch: i = 1,
|
|
267
|
+
whisperModel: g = "onnx-community/whisper-tiny.en",
|
|
268
|
+
whisperDtype: a = "q8",
|
|
269
|
+
whisperDevice: h = "cpu",
|
|
270
|
+
kokoroDtype: p = "q8",
|
|
271
|
+
kokoroBrowserDevice: c = "wasm",
|
|
272
|
+
modelProxyUrl: l = "/api/models/"
|
|
273
|
+
} = {}) {
|
|
274
|
+
const [b, d] = L(y.IDLE), [R, I] = L(!0), [x, T] = L({ whisper: 0, kokoro: 0 }), [D, M] = L(null), [ee, Z] = L([]), [G, F] = L(null), [w, z] = L(!1), [$, ne] = L(""), [te, re] = L([]), [ae, C] = L(null), q = _(y.IDLE), K = _(!1), A = _(null), W = _(null), j = _(null), Q = _(null), se = _(null), ie = _(null), J = _([{ role: "system", content: s }]), ce = _(e);
|
|
275
|
+
U(() => {
|
|
276
|
+
q.current = b;
|
|
277
|
+
}, [b]), U(() => {
|
|
278
|
+
K.current = w;
|
|
279
|
+
}, [w]), U(() => {
|
|
280
|
+
ce.current = e;
|
|
281
|
+
}, [e]), U(() => {
|
|
282
|
+
async function m() {
|
|
283
|
+
try {
|
|
284
|
+
const k = await navigator.mediaDevices.enumerateDevices();
|
|
285
|
+
re(k.filter((u) => u.kind === "audioinput"));
|
|
286
|
+
} catch {
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
return m(), navigator.mediaDevices.addEventListener("devicechange", m), () => navigator.mediaDevices.removeEventListener("devicechange", m);
|
|
290
|
+
}, [w]), U(() => {
|
|
291
|
+
let m = !1;
|
|
292
|
+
async function k() {
|
|
293
|
+
try {
|
|
294
|
+
const u = () => {
|
|
295
|
+
var f;
|
|
296
|
+
t === "webspeech" && ((f = W.current) == null || f.pause());
|
|
297
|
+
};
|
|
298
|
+
if (t === "webspeech")
|
|
299
|
+
A.current = Ne({
|
|
300
|
+
voice: r,
|
|
301
|
+
rate: o,
|
|
302
|
+
pitch: i,
|
|
303
|
+
onPlayStart: u
|
|
304
|
+
}), T((f) => ({ ...f, kokoro: 1 }));
|
|
305
|
+
else if (t === "kokoro") {
|
|
306
|
+
const { kokoro: f } = await Se(
|
|
307
|
+
(S, B) => T((O) => ({ ...O, [S]: B })),
|
|
308
|
+
{ dtype: p, device: c, modelProxyUrl: l }
|
|
309
|
+
);
|
|
310
|
+
if (m) return;
|
|
311
|
+
A.current = Ae(f, { voice: r, onPlayStart: u });
|
|
312
|
+
} else
|
|
313
|
+
A.current = Ie({ voice: r, onPlayStart: u, url: n }), T((f) => ({ ...f, kokoro: 1 }));
|
|
314
|
+
if (m) return;
|
|
315
|
+
Q.current = new Worker(
|
|
316
|
+
new URL(
|
|
317
|
+
/* @vite-ignore */
|
|
318
|
+
"/assets/whisperWorker-BJuP9cl9.js",
|
|
319
|
+
import.meta.url
|
|
320
|
+
),
|
|
321
|
+
{ type: "module" }
|
|
322
|
+
), Q.current.onmessage = (f) => {
|
|
323
|
+
f.data.type === "transcript" ? pe(f.data.text) : f.data.type === "progress" ? T((S) => ({ ...S, whisper: f.data.progress })) : f.data.type === "ready" ? (T((S) => ({ ...S, whisper: 1 })), I(!1)) : f.data.type === "error" && (M(`Whisper: ${f.data.message}`), I(!1));
|
|
324
|
+
}, Q.current.onerror = () => {
|
|
325
|
+
M("Model load failed. Check WebGPU/WASM browser support."), I(!1);
|
|
326
|
+
}, Q.current.postMessage({
|
|
327
|
+
type: "init",
|
|
328
|
+
model: g,
|
|
329
|
+
dtype: a,
|
|
330
|
+
device: h,
|
|
331
|
+
modelProxyUrl: l
|
|
332
|
+
});
|
|
333
|
+
} catch (u) {
|
|
334
|
+
m || (M("Initialisation failed: " + ((u == null ? void 0 : u.message) ?? String(u))), I(!1));
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
return k(), () => {
|
|
338
|
+
var u;
|
|
339
|
+
m = !0, (u = Q.current) == null || u.terminate();
|
|
340
|
+
};
|
|
341
|
+
}, [t, g, a, h, p, c]);
|
|
342
|
+
function le(m, k) {
|
|
343
|
+
Z((u) => [...u, { role: m, content: k, time: (/* @__PURE__ */ new Date()).toISOString() }]);
|
|
344
|
+
}
|
|
345
|
+
async function pe(m) {
|
|
346
|
+
if (!(m != null && m.trim())) {
|
|
347
|
+
d(K.current ? y.LISTENING : y.IDLE);
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
d(y.THINKING), le("user", m);
|
|
351
|
+
const k = [...J.current, { role: "user", content: m }];
|
|
352
|
+
J.current = k, await ge(m, k);
|
|
353
|
+
}
|
|
354
|
+
async function ge(m, k) {
|
|
355
|
+
var u, f, S, B, O;
|
|
356
|
+
(u = j.current) == null || u.abort(), j.current = new AbortController(), (f = A.current) == null || f.cancel();
|
|
357
|
+
try {
|
|
358
|
+
if (!ce.current) throw new Error("processInput is not provided");
|
|
359
|
+
const P = he();
|
|
360
|
+
let Y = "", oe = !1;
|
|
361
|
+
F("");
|
|
362
|
+
for await (const fe of ce.current(m, k, j.current.signal))
|
|
363
|
+
Y += fe, F(Y), P.write(fe).forEach((ve) => {
|
|
364
|
+
var de;
|
|
365
|
+
oe || (oe = !0, d(y.SPEAKING)), (de = A.current) == null || de.enqueue(ve);
|
|
366
|
+
});
|
|
367
|
+
const ue = P.flush();
|
|
368
|
+
ue && (oe || d(y.SPEAKING), (S = A.current) == null || S.enqueue(ue)), le("assistant", Y), F(null), J.current = [...J.current, { role: "assistant", content: Y }], await ((B = A.current) == null ? void 0 : B.finished()), t === "webspeech" && ((O = W.current) == null || O.start());
|
|
369
|
+
} catch (P) {
|
|
370
|
+
F(null), P.name !== "AbortError" && M(P.message || "Processing failed.");
|
|
371
|
+
} finally {
|
|
372
|
+
d(K.current ? y.LISTENING : y.IDLE);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
async function we() {
|
|
376
|
+
var m, k;
|
|
377
|
+
M(null), q.current === y.SPEAKING && ((m = A.current) == null || m.cancel(), (k = j.current) == null || k.abort());
|
|
378
|
+
try {
|
|
379
|
+
d(y.LISTENING), z(!0);
|
|
380
|
+
try {
|
|
381
|
+
const u = await navigator.mediaDevices.getUserMedia({
|
|
382
|
+
audio: $ ? { deviceId: { exact: $ } } : !0,
|
|
383
|
+
video: !1
|
|
384
|
+
});
|
|
385
|
+
ie.current = u;
|
|
386
|
+
const f = new AudioContext();
|
|
387
|
+
se.current = f;
|
|
388
|
+
const S = f.createAnalyser();
|
|
389
|
+
S.fftSize = 256, f.createMediaStreamSource(u).connect(S), C(S);
|
|
390
|
+
} catch (u) {
|
|
391
|
+
console.warn("[TZVoiceChat] waveform analyser unavailable:", u);
|
|
392
|
+
}
|
|
393
|
+
W.current = await Te({
|
|
394
|
+
onSpeechStart: () => {
|
|
395
|
+
var u, f;
|
|
396
|
+
t === "webspeech" && q.current === y.SPEAKING || (q.current === y.SPEAKING && ((u = A.current) == null || u.cancel(), (f = j.current) == null || f.abort()), d(y.LISTENING));
|
|
397
|
+
},
|
|
398
|
+
onSpeechEnd: (u) => {
|
|
399
|
+
var f;
|
|
400
|
+
t === "webspeech" && q.current === y.SPEAKING || (d(y.TRANSCRIBING), (f = Q.current) == null || f.postMessage({ type: "transcribe", audio: u }, [u.buffer]));
|
|
401
|
+
},
|
|
402
|
+
onError: (u) => {
|
|
403
|
+
M(u), d(y.IDLE);
|
|
404
|
+
},
|
|
405
|
+
deviceId: $ || void 0
|
|
406
|
+
});
|
|
407
|
+
} catch (u) {
|
|
408
|
+
console.error("[TZVoiceChat] startListening failed:", u), M("Microphone access failed. Allow audio permissions and refresh."), d(y.IDLE), z(!1);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
function be() {
|
|
412
|
+
var m, k, u, f, S;
|
|
413
|
+
z(!1), (m = W.current) == null || m.destroy(), W.current = null, (k = ie.current) == null || k.getTracks().forEach((B) => B.stop()), ie.current = null, (u = se.current) == null || u.close(), se.current = null, C(null), (f = A.current) == null || f.cancel(), (S = j.current) == null || S.abort(), d(y.IDLE);
|
|
414
|
+
}
|
|
415
|
+
function ye(m) {
|
|
416
|
+
var S;
|
|
417
|
+
if (!(m != null && m.trim())) return;
|
|
418
|
+
d(y.SPEAKING);
|
|
419
|
+
const k = he(), u = k.write(m), f = k.flush();
|
|
420
|
+
[...u, ...f ? [f] : []].forEach((B) => {
|
|
421
|
+
var O;
|
|
422
|
+
return (O = A.current) == null ? void 0 : O.enqueue(B);
|
|
423
|
+
}), (S = A.current) == null || S.finished().then(() => {
|
|
424
|
+
d(K.current ? y.LISTENING : y.IDLE);
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
return {
|
|
428
|
+
/** Current pipeline state: 'idle' | 'listening' | 'transcribing' | 'thinking' | 'speaking' */
|
|
429
|
+
status: b,
|
|
430
|
+
/** True while models (Whisper + TTS) are still loading. */
|
|
431
|
+
loading: R,
|
|
432
|
+
/** Per-model load progress: { whisper: 0–1, kokoro: 0–1 } */
|
|
433
|
+
progress: x,
|
|
434
|
+
/** Last error string, or null. Cleared on startListening(). */
|
|
435
|
+
error: D,
|
|
436
|
+
/** Completed conversation turns: [{ role, content, time }] */
|
|
437
|
+
transcript: ee,
|
|
438
|
+
/** Partial assistant response being streamed, or null. */
|
|
439
|
+
streamingMessage: G,
|
|
440
|
+
/** Whether the microphone is currently open. */
|
|
441
|
+
micEnabled: w,
|
|
442
|
+
/** Open the microphone and start the VAD → STT → AI → TTS pipeline. */
|
|
443
|
+
startListening: we,
|
|
444
|
+
/** Close the microphone and cancel any in-progress pipeline. */
|
|
445
|
+
stopListening: be,
|
|
446
|
+
/** Directly synthesise and play text via the configured TTS provider. */
|
|
447
|
+
speak: ye,
|
|
448
|
+
/** AnalyserNode for real-time waveform rendering, or null when mic is off. */
|
|
449
|
+
liveAnalyser: ae,
|
|
450
|
+
/** Available audio input devices (updated on permission grant). */
|
|
451
|
+
devices: te,
|
|
452
|
+
/** Currently selected device ID ('': system default). */
|
|
453
|
+
selectedMicId: $,
|
|
454
|
+
/** Select an audio input device by its deviceId. */
|
|
455
|
+
setSelectedMicId: ne
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
function me(e) {
|
|
459
|
+
const s = e.replace("#", ""), t = s.length === 3 ? s.split("").map((r) => r + r).join("") : s;
|
|
460
|
+
return [
|
|
461
|
+
parseInt(t.slice(0, 2), 16),
|
|
462
|
+
parseInt(t.slice(2, 4), 16),
|
|
463
|
+
parseInt(t.slice(4, 6), 16)
|
|
464
|
+
];
|
|
465
|
+
}
|
|
466
|
+
function _e(e, s, t) {
|
|
467
|
+
e /= 255, s /= 255, t /= 255;
|
|
468
|
+
const r = Math.max(e, s, t), n = Math.min(e, s, t), o = (r + n) / 2;
|
|
469
|
+
if (r === n) return [0, 0, o * 100];
|
|
470
|
+
const i = r - n, g = o > 0.5 ? i / (2 - r - n) : i / (r + n);
|
|
471
|
+
let a;
|
|
472
|
+
switch (r) {
|
|
473
|
+
case e:
|
|
474
|
+
a = ((s - t) / i + (s < t ? 6 : 0)) / 6;
|
|
475
|
+
break;
|
|
476
|
+
case s:
|
|
477
|
+
a = ((t - e) / i + 2) / 6;
|
|
478
|
+
break;
|
|
479
|
+
default:
|
|
480
|
+
a = ((e - s) / i + 4) / 6;
|
|
481
|
+
}
|
|
482
|
+
return [a * 360, g * 100, o * 100];
|
|
483
|
+
}
|
|
484
|
+
function Me(e, s, t) {
|
|
485
|
+
s /= 100, t /= 100;
|
|
486
|
+
const r = (i) => (i + e / 30) % 12, n = s * Math.min(t, 1 - t), o = (i) => t - n * Math.max(-1, Math.min(r(i) - 3, Math.min(9 - r(i), 1)));
|
|
487
|
+
return [Math.round(o(0) * 255), Math.round(o(8) * 255), Math.round(o(4) * 255)];
|
|
488
|
+
}
|
|
489
|
+
function E(e, s) {
|
|
490
|
+
const [t, r, n] = me(e), [o, i, g] = _e(t, r, n), [a, h, p] = Me(o, i, Math.max(0, Math.min(100, g + s)));
|
|
491
|
+
return `rgb(${a}, ${h}, ${p})`;
|
|
492
|
+
}
|
|
493
|
+
function N(e, s) {
|
|
494
|
+
const [t, r, n] = me(e);
|
|
495
|
+
return `rgba(${t}, ${r}, ${n}, ${s})`;
|
|
496
|
+
}
|
|
497
|
+
function H(e, s) {
|
|
498
|
+
return e.replace("rgb(", "rgba(").replace(")", `, ${s})`);
|
|
499
|
+
}
|
|
500
|
+
const X = 10;
|
|
501
|
+
function Ee({ analyser: e }) {
|
|
502
|
+
const s = _(null), t = _(null);
|
|
503
|
+
return U(() => {
|
|
504
|
+
if (cancelAnimationFrame(t.current), !e) return;
|
|
505
|
+
const r = s.current;
|
|
506
|
+
if (!r) return;
|
|
507
|
+
const n = r.getContext("2d"), o = e.frequencyBinCount, i = new Uint8Array(o), g = Math.max(1, Math.floor(o / X)), a = getComputedStyle(r), h = +a.getPropertyValue("--bar-hue"), p = +a.getPropertyValue("--bar-hue-range"), c = +a.getPropertyValue("--bar-sat"), l = +a.getPropertyValue("--bar-lit"), b = +a.getPropertyValue("--bar-lit-range"), d = () => {
|
|
508
|
+
t.current = requestAnimationFrame(d), e.getByteFrequencyData(i);
|
|
509
|
+
const R = r.width, I = r.height;
|
|
510
|
+
n.clearRect(0, 0, R, I);
|
|
511
|
+
const x = (R - (X - 1) * 2) / X;
|
|
512
|
+
for (let T = 0; T < X; T++) {
|
|
513
|
+
const D = i[T * g] / 255, M = Math.max(3, D * I * 0.88);
|
|
514
|
+
n.fillStyle = `hsl(${h + D * p}, ${c}%, ${l + D * b}%)`, n.beginPath(), n.roundRect(T * (x + 2), (I - M) / 2, x, M, [2]), n.fill();
|
|
515
|
+
}
|
|
516
|
+
};
|
|
517
|
+
return d(), () => cancelAnimationFrame(t.current);
|
|
518
|
+
}, [e]), /* @__PURE__ */ v("canvas", { ref: s, width: 55, height: 35, className: "ai-btn__canvas" });
|
|
519
|
+
}
|
|
520
|
+
function De({
|
|
521
|
+
status: e = "idle",
|
|
522
|
+
active: s = !1,
|
|
523
|
+
loading: t = !1,
|
|
524
|
+
analyser: r = null,
|
|
525
|
+
onToggle: n,
|
|
526
|
+
devices: o = [],
|
|
527
|
+
selectedMicId: i = "",
|
|
528
|
+
onDeviceChange: g,
|
|
529
|
+
// ── Theming ────────────────────────────────────────────────
|
|
530
|
+
accentColor: a = "#f97316",
|
|
531
|
+
uiColor: h = "#64748b",
|
|
532
|
+
size: p = 70,
|
|
533
|
+
barHue: c = 25,
|
|
534
|
+
barHueRange: l = 20,
|
|
535
|
+
barSat: b = 88,
|
|
536
|
+
barLit: d = 65,
|
|
537
|
+
barLitRange: R = 20
|
|
538
|
+
}) {
|
|
539
|
+
var F;
|
|
540
|
+
const [I, x] = L(!1), T = _(null);
|
|
541
|
+
U(() => {
|
|
542
|
+
if (!I) return;
|
|
543
|
+
function w(z) {
|
|
544
|
+
var $;
|
|
545
|
+
($ = T.current) != null && $.contains(z.target) || x(!1);
|
|
546
|
+
}
|
|
547
|
+
return document.addEventListener("pointerdown", w), () => document.removeEventListener("pointerdown", w);
|
|
548
|
+
}, [I]);
|
|
549
|
+
function D(w) {
|
|
550
|
+
g == null || g(w), x(!1);
|
|
551
|
+
}
|
|
552
|
+
const M = ke(() => {
|
|
553
|
+
const w = E(a, -8), z = E(a, -15), $ = E(a, -22), ne = E(a, -30), te = E(a, -42), re = E(a, 8), ae = E(a, 20), C = E(a, 30), q = E(h, -22), K = E(h, -30), A = E(h, 18), W = E(h, 37);
|
|
554
|
+
return {
|
|
555
|
+
"--tz-size": `${p}px`,
|
|
556
|
+
// Accent shades
|
|
557
|
+
"--tz-a": a,
|
|
558
|
+
"--tz-a-d8": w,
|
|
559
|
+
"--tz-a-d15": z,
|
|
560
|
+
"--tz-a-d22": $,
|
|
561
|
+
"--tz-a-d30": ne,
|
|
562
|
+
"--tz-a-d42": te,
|
|
563
|
+
"--tz-a-l8": re,
|
|
564
|
+
"--tz-a-l20": ae,
|
|
565
|
+
"--tz-a-l30": C,
|
|
566
|
+
// Accent + alpha
|
|
567
|
+
"--tz-a-25": N(a, 0.25),
|
|
568
|
+
"--tz-a-28": N(a, 0.28),
|
|
569
|
+
"--tz-a-30": N(a, 0.3),
|
|
570
|
+
"--tz-a-32": N(a, 0.32),
|
|
571
|
+
"--tz-a-34": N(a, 0.34),
|
|
572
|
+
"--tz-a-35": N(a, 0.35),
|
|
573
|
+
"--tz-a-38": N(a, 0.38),
|
|
574
|
+
"--tz-a-45": N(a, 0.45),
|
|
575
|
+
"--tz-a-50": N(a, 0.5),
|
|
576
|
+
"--tz-a-55": N(a, 0.55),
|
|
577
|
+
"--tz-a-60": N(a, 0.6),
|
|
578
|
+
"--tz-a-65": N(a, 0.65),
|
|
579
|
+
"--tz-a-68": N(a, 0.68),
|
|
580
|
+
// UI shades
|
|
581
|
+
"--tz-u": h,
|
|
582
|
+
"--tz-u-d22": q,
|
|
583
|
+
"--tz-u-d30": K,
|
|
584
|
+
"--tz-u-l18": A,
|
|
585
|
+
"--tz-u-l37": W,
|
|
586
|
+
// UI + alpha
|
|
587
|
+
"--tz-u-30": N(h, 0.3),
|
|
588
|
+
"--tz-u-55": N(h, 0.55),
|
|
589
|
+
"--tz-u-d30-a85": H(K, 0.85),
|
|
590
|
+
"--tz-u-l18-a18": H(A, 0.18),
|
|
591
|
+
"--tz-u-l18-a20": H(A, 0.2),
|
|
592
|
+
"--tz-u-l18-a32": H(A, 0.32),
|
|
593
|
+
"--tz-u-d22-a90": H(q, 0.9),
|
|
594
|
+
// Waveform bar colors (cascade to canvas via getComputedStyle)
|
|
595
|
+
"--bar-hue": c,
|
|
596
|
+
"--bar-hue-range": l,
|
|
597
|
+
"--bar-sat": b,
|
|
598
|
+
"--bar-lit": d,
|
|
599
|
+
"--bar-lit-range": R
|
|
600
|
+
};
|
|
601
|
+
}, [a, h, p, c, l, b, d, R]), ee = ((F = o.find((w) => w.deviceId === i)) == null ? void 0 : F.label) || (i ? `Mic ${i.slice(0, 6)}…` : "Default mic"), Z = s ? e : "off";
|
|
602
|
+
let G;
|
|
603
|
+
return !s || e === "idle" ? G = /* @__PURE__ */ v("svg", { className: "ai-btn__mic", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", children: /* @__PURE__ */ v("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 = /* @__PURE__ */ v(Ee, { analyser: r }) : e === "transcribing" ? G = /* @__PURE__ */ v("div", { className: "ai-btn__bars ai-btn__bars--transcribing", children: Array.from({ length: 7 }, (w, z) => /* @__PURE__ */ v("span", { style: { animationDelay: `${z * 0.1}s` } }, z)) }) : e === "thinking" ? G = /* @__PURE__ */ V("div", { className: "ai-btn__dots", children: [
|
|
604
|
+
/* @__PURE__ */ v("span", {}),
|
|
605
|
+
/* @__PURE__ */ v("span", { style: { animationDelay: "0.18s" } }),
|
|
606
|
+
/* @__PURE__ */ v("span", { style: { animationDelay: "0.36s" } })
|
|
607
|
+
] }) : e === "speaking" && (G = /* @__PURE__ */ v("div", { className: "ai-btn__bars ai-btn__bars--speaking", children: Array.from({ length: 7 }, (w, z) => /* @__PURE__ */ v("span", { style: { animationDelay: `${z * 0.11}s` } }, z)) })), /* @__PURE__ */ V("div", { className: "ai-btn-root", style: M, children: [
|
|
608
|
+
/* @__PURE__ */ V("div", { className: `ai-btn-rings ai-btn-rings--${Z}`, "aria-hidden": "true", children: [
|
|
609
|
+
/* @__PURE__ */ v("span", { className: "ai-ring ai-ring--1" }),
|
|
610
|
+
/* @__PURE__ */ v("span", { className: "ai-ring ai-ring--2" })
|
|
611
|
+
] }),
|
|
612
|
+
/* @__PURE__ */ V(
|
|
613
|
+
"button",
|
|
614
|
+
{
|
|
615
|
+
className: `ai-btn ai-btn--${Z}`,
|
|
616
|
+
disabled: t,
|
|
617
|
+
onClick: n,
|
|
618
|
+
"aria-label": s ? "Stop assistant" : "Start assistant",
|
|
619
|
+
"aria-pressed": s,
|
|
620
|
+
children: [
|
|
621
|
+
G,
|
|
622
|
+
s && /* @__PURE__ */ v("span", { className: "ai-btn__hover-stop", "aria-hidden": "true", children: "■" })
|
|
623
|
+
]
|
|
624
|
+
}
|
|
625
|
+
),
|
|
626
|
+
/* @__PURE__ */ V("div", { className: `ai-mic-sel${I ? " open" : ""}`, ref: T, children: [
|
|
627
|
+
/* @__PURE__ */ V(
|
|
628
|
+
"button",
|
|
629
|
+
{
|
|
630
|
+
className: "ai-mic-sel__trigger",
|
|
631
|
+
onClick: () => x((w) => !w),
|
|
632
|
+
title: "Change microphone",
|
|
633
|
+
"aria-label": "Change microphone",
|
|
634
|
+
"aria-expanded": I,
|
|
635
|
+
children: [
|
|
636
|
+
/* @__PURE__ */ V("svg", { width: "11", height: "11", viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true", children: [
|
|
637
|
+
/* @__PURE__ */ v("path", { d: "M12 1a4 4 0 0 1 4 4v6a4 4 0 0 1-8 0V5a4 4 0 0 1 4-4z" }),
|
|
638
|
+
/* @__PURE__ */ v("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" })
|
|
639
|
+
] }),
|
|
640
|
+
/* @__PURE__ */ v("span", { className: "ai-mic-sel__label", children: ee }),
|
|
641
|
+
/* @__PURE__ */ v(
|
|
642
|
+
"svg",
|
|
643
|
+
{
|
|
644
|
+
className: `ai-mic-sel__caret${I ? " open" : ""}`,
|
|
645
|
+
width: "9",
|
|
646
|
+
height: "9",
|
|
647
|
+
viewBox: "0 0 24 24",
|
|
648
|
+
fill: "currentColor",
|
|
649
|
+
"aria-hidden": "true",
|
|
650
|
+
children: /* @__PURE__ */ v("path", { d: "M12 16L4 8h16l-8 8z" })
|
|
651
|
+
}
|
|
652
|
+
)
|
|
653
|
+
]
|
|
654
|
+
}
|
|
655
|
+
),
|
|
656
|
+
I && /* @__PURE__ */ V("ul", { className: "ai-mic-sel__menu", role: "listbox", "aria-label": "Select microphone", children: [
|
|
657
|
+
/* @__PURE__ */ v(
|
|
658
|
+
"li",
|
|
659
|
+
{
|
|
660
|
+
role: "option",
|
|
661
|
+
className: `ai-mic-sel__option${i === "" ? " selected" : ""}`,
|
|
662
|
+
onClick: () => D(""),
|
|
663
|
+
"aria-selected": i === "",
|
|
664
|
+
children: "Default microphone"
|
|
665
|
+
}
|
|
666
|
+
),
|
|
667
|
+
o.map((w) => /* @__PURE__ */ v(
|
|
668
|
+
"li",
|
|
669
|
+
{
|
|
670
|
+
role: "option",
|
|
671
|
+
className: `ai-mic-sel__option${i === w.deviceId ? " selected" : ""}`,
|
|
672
|
+
onClick: () => D(w.deviceId),
|
|
673
|
+
"aria-selected": i === w.deviceId,
|
|
674
|
+
children: w.label || `Microphone ${w.deviceId.slice(0, 8)}`
|
|
675
|
+
},
|
|
676
|
+
w.deviceId
|
|
677
|
+
))
|
|
678
|
+
] })
|
|
679
|
+
] })
|
|
680
|
+
] });
|
|
681
|
+
}
|
|
682
|
+
export {
|
|
683
|
+
De as AIAssistantButton,
|
|
684
|
+
y as STATES,
|
|
685
|
+
xe as TZVoiceChat
|
|
686
|
+
};
|
package/dist/style.css
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
@charset "UTF-8";.ai-btn-root{display:inline-flex;flex-direction:column;align-items:center;gap:6px;position:relative;-webkit-user-select:none;user-select:none;padding-bottom:5px}.ai-btn-rings{position:absolute;top:0;left:50%;transform:translate(-50%);width:var(--tz-size);height:var(--tz-size);pointer-events:none;z-index:0}.ai-ring{position:absolute;top:0;right:0;bottom:0;left:0;border-radius:50%;border:1px solid transparent}@keyframes ai-ring-expand{0%{transform:scale(1);opacity:1}to{transform:scale(1.65);opacity:0}}.ai-btn-rings--idle .ai-ring--1{border-color:var(--tz-a-28);animation:ai-ring-expand 2.8s ease-out infinite}.ai-btn-rings--idle .ai-ring--2{display:none}.ai-btn-rings--listening .ai-ring--1{border-color:var(--tz-a-60);animation:ai-ring-expand 1.8s ease-out infinite}.ai-btn-rings--listening .ai-ring--2{border-color:var(--tz-a-32);animation:ai-ring-expand 1.8s ease-out .55s infinite}.ai-btn-rings--transcribing .ai-ring--1{border-color:var(--tz-a-50);animation:ai-ring-expand 1.4s ease-out infinite}.ai-btn-rings--transcribing .ai-ring--2{display:none}.ai-btn-rings--thinking .ai-ring--1{border-color:var(--tz-a-34);animation:ai-ring-expand 2s ease-out infinite}.ai-btn-rings--thinking .ai-ring--2{display:none}.ai-btn-rings--speaking .ai-ring--1{border-color:var(--tz-a-68);animation:ai-ring-expand 1.1s ease-out infinite}.ai-btn-rings--speaking .ai-ring--2{border-color:var(--tz-a-38);animation:ai-ring-expand 1.1s ease-out .35s infinite}.ai-btn{position:relative;z-index:1;width:var(--tz-size);height:var(--tz-size);border-radius:50%;border:2px solid transparent;overflow:hidden;display:flex;align-items:center;justify-content:center;cursor:pointer;transition:background .3s ease,border-color .3s ease,box-shadow .3s ease,transform .15s ease;-webkit-tap-highlight-color:transparent}.ai-btn:hover:not(:disabled){transform:scale(1.045)}.ai-btn:active:not(:disabled){transform:scale(.97)}.ai-btn:disabled{cursor:not-allowed;opacity:.5}.ai-btn__hover-stop{position:absolute;top:0;right:0;bottom:0;left:0;display:flex;align-items:center;justify-content:center;font-size:12px;color:#fffc;opacity:0;background:#00000061;transition:opacity .2s;border-radius:50%;pointer-events:none}.ai-btn:hover:not(:disabled) .ai-btn__hover-stop{opacity:1}.ai-btn--off{background:var(--tz-u-d30);border-color:var(--tz-u-30);box-shadow:0 4px 18px #00000073;color:var(--tz-u)}.ai-btn--off:hover:not(:disabled){border-color:var(--tz-u-55);color:var(--tz-u-l18)}.ai-btn--idle{background:radial-gradient(circle at 42% 38%,var(--tz-a-d42),var(--tz-a-d42));border-color:var(--tz-a-30);box-shadow:0 0 22px var(--tz-a-25),0 4px 18px #0006;color:var(--tz-a-l20)}.ai-btn--listening{background:radial-gradient(circle at 42% 38%,var(--tz-a-d22),var(--tz-a-d30));border-color:var(--tz-a-50);box-shadow:0 0 28px var(--tz-a-50),0 4px 18px #0006;color:var(--tz-a-l30)}.ai-btn--transcribing{background:radial-gradient(circle at 42% 38%,var(--tz-a-d15),var(--tz-a-d22));border-color:var(--tz-a-45);box-shadow:0 0 30px var(--tz-a-55),0 4px 18px #0006;color:var(--tz-a-l8)}.ai-btn--thinking{background:radial-gradient(circle at 42% 38%,var(--tz-a-d30),var(--tz-a-d42));border-color:var(--tz-a-35);box-shadow:0 0 26px var(--tz-a-50),0 4px 18px #0006;color:var(--tz-a-l20)}.ai-btn--speaking{background:radial-gradient(circle at 42% 38%,var(--tz-a-d8),var(--tz-a-d15));border-color:var(--tz-a-55);box-shadow:0 0 32px var(--tz-a-65),0 4px 18px #0006;color:var(--tz-a-l30)}.ai-btn__mic{width:23px;height:23px;opacity:.9;flex-shrink:0}.ai-btn__canvas{display:block;max-width:58px}.ai-btn__bars{display:flex;align-items:center;gap:3px}.ai-btn__bars span{display:block;width:4px;border-radius:2px;transform-origin:center}.ai-btn__bars--transcribing{height:37px}.ai-btn__bars--transcribing span{height:31px;background:linear-gradient(180deg,var(--tz-a-l20),var(--tz-a-d8));animation:ai-bar-transcribe .85s ease-in-out infinite}.ai-btn__bars--speaking{height:37px}.ai-btn__bars--speaking span{height:31px;background:linear-gradient(180deg,var(--tz-a-l30),var(--tz-a));animation:ai-bar-speak .55s ease-in-out infinite}.ai-btn__dots{display:flex;align-items:center;gap:6px}.ai-btn__dots span{display:block;width:8px;height:8px;border-radius:50%;background:var(--tz-a-l20);animation:ai-dot-think 1.1s ease-in-out infinite}@keyframes ai-bar-transcribe{0%,to{transform:scaleY(.1);opacity:.35}50%{transform:scaleY(1);opacity:1}}@keyframes ai-bar-speak{0%,to{transform:scaleY(.18)}50%{transform:scaleY(1)}}@keyframes ai-dot-think{0%,60%,to{transform:translateY(0);opacity:.4}30%{transform:translateY(-10px);opacity:1}}.ai-mic-sel{position:relative;opacity:0;visibility:hidden;transform:translateY(4px);transition:opacity .18s,visibility .18s,transform .18s}.ai-btn-root:hover .ai-mic-sel,.ai-mic-sel.open{opacity:1;visibility:visible;transform:translateY(0)}.ai-mic-sel__trigger{display:inline-flex;align-items:center;gap:5px;padding:5px 11px;border-radius:999px;background:var(--tz-u-d30-a85);border:1px solid var(--tz-u-l18-a18);color:var(--tz-u-l18);font-size:.73rem;cursor:pointer;transition:background .18s,border-color .18s,color .18s;white-space:nowrap;max-width:200px}.ai-mic-sel__trigger:hover{background:var(--tz-u-d22-a90);border-color:var(--tz-u-l18-a32);color:var(--tz-u-l37)}.ai-mic-sel__label{max-width:130px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.ai-mic-sel__caret{transition:transform .2s;flex-shrink:0;opacity:.7}.ai-mic-sel__caret.open{transform:rotate(180deg)}.ai-mic-sel__menu{position:absolute;bottom:calc(100% + 7px);left:50%;transform:translate(-50%);min-width:220px;background:var(--tz-u-d30);border:1px solid var(--tz-u-l18-a20);border-radius:10px;box-shadow:0 8px 30px #0000008c;overflow:hidden;z-index:200;list-style:none;margin:0;padding:4px}.ai-mic-sel__option{display:block;width:100%;padding:8px 12px;text-align:left;font-size:.8rem;color:var(--tz-u-l37);border-radius:7px;background:none;border:none;cursor:pointer;transition:background .15s;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.ai-mic-sel__option:hover{background:#3b82f624;color:#e2e8f0}.ai-mic-sel__option.selected{background:#3b82f633;color:#93c5fd}.ai-mic-sel__option.selected:before{content:"✓ "}
|
package/package.json
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "tz-voice-chat",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "React hook for a full voice-chat pipeline: VAD → Whisper STT → custom AI processor → Kokoro/OpenAI/WebSpeech TTS.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.cjs",
|
|
7
|
+
"module": "./dist/index.js",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"import": "./dist/index.js",
|
|
11
|
+
"require": "./dist/index.cjs"
|
|
12
|
+
},
|
|
13
|
+
"./style.css": "./dist/style.css"
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist",
|
|
17
|
+
"README.md"
|
|
18
|
+
],
|
|
19
|
+
"scripts": {
|
|
20
|
+
"build": "vite build",
|
|
21
|
+
"prepublishOnly": "npm run build"
|
|
22
|
+
},
|
|
23
|
+
"keywords": ["react", "hook", "voice", "chat", "speech", "stt", "tts", "whisper", "kokoro", "vad", "ai"],
|
|
24
|
+
"license": "MIT",
|
|
25
|
+
"peerDependencies": {
|
|
26
|
+
"react": ">=18",
|
|
27
|
+
"@huggingface/transformers": ">=3",
|
|
28
|
+
"@ricky0123/vad-web": ">=0.0.29",
|
|
29
|
+
"kokoro-js": "*"
|
|
30
|
+
},
|
|
31
|
+
"peerDependenciesMeta": {
|
|
32
|
+
"kokoro-js": { "optional": true }
|
|
33
|
+
}
|
|
34
|
+
}
|