tz-voice-chat 1.2.0 → 1.3.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.
@@ -18,8 +18,8 @@
18
18
  }
19
19
  }
20
20
  </script>
21
- <script type="module" crossorigin src="/assets/index-CFWv17S2.js"></script>
22
- <link rel="stylesheet" crossorigin href="/assets/index-BDMCgrF_.css">
21
+ <script type="module" crossorigin src="/assets/index-KxBxd4q9.js"></script>
22
+ <link rel="stylesheet" crossorigin href="/assets/index-Bcmhe9G_.css">
23
23
  </head>
24
24
  <body>
25
25
  <div id="root"></div>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tz-voice-chat",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "description": "Voice assistant: React hook + UI and a ready-to-run server/CLI. VAD → Whisper STT → LLM → Kokoro/OpenAI/WebSpeech TTS, configurable from a Settings page.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
package/server/index.js CHANGED
@@ -30,6 +30,7 @@ import { createSettingsStore } from './settings.js';
30
30
  import { streamOpenAI, streamAnthropic, streamOpenAICompatible } from './chat.js';
31
31
  import { transcribeElevenLabs, synthesizeElevenLabs } from './elevenlabs.js';
32
32
  import { transcribeOpenAI } from './openai-stt.js';
33
+ import { synthesizeOpenAICompatible, parseBaseUrl } from './openai-tts.js';
33
34
 
34
35
  /**
35
36
  * @param {object} [options]
@@ -93,6 +94,8 @@ export function createVoiceAssistantRouter({ settingsFile, defaults = {} } = {})
93
94
  kokoroVoice: o.kokoroVoice,
94
95
  openaiTtsModel: o.openaiTtsModel,
95
96
  openaiTtsVoice: o.openaiTtsVoice,
97
+ ttsCompatModel: o.ttsCompatModel,
98
+ ttsCompatVoice: o.ttsCompatVoice,
96
99
  webSpeechVoice: o.webSpeechVoice,
97
100
  webSpeechRate: o.webSpeechRate,
98
101
  webSpeechPitch: o.webSpeechPitch,
@@ -274,6 +277,28 @@ export function createVoiceAssistantRouter({ settingsFile, defaults = {} } = {})
274
277
  return res.end();
275
278
  }
276
279
 
280
+ if (o.ttsProvider === 'openai-compatible') {
281
+ const base = parseBaseUrl(o.ttsCompatBaseUrl);
282
+ if (!base) return res.status(400).send('The OpenAI-compatible TTS server URL is missing or invalid — fix it in Settings');
283
+ let out;
284
+ try {
285
+ out = await synthesizeOpenAICompatible({
286
+ baseUrl: base.href,
287
+ apiKey: o.ttsCompatApiKey,
288
+ model: o.ttsCompatModel || 'tts-1',
289
+ voice: voice || o.ttsCompatVoice || 'alloy',
290
+ format: o.ttsCompatFormat,
291
+ text,
292
+ });
293
+ } catch (err) {
294
+ return res.status(502).send(`Could not reach the OpenAI-compatible TTS server at ${base.origin}: ${err.cause?.code || err.message}`);
295
+ }
296
+ if (!out.ok) return res.status(out.status).send(out.body);
297
+ res.setHeader('Content-Type', out.contentType);
298
+ res.setHeader('Content-Length', String(out.audio.length));
299
+ return res.end(out.audio);
300
+ }
301
+
277
302
  if (o.ttsProvider === 'elevenlabs') {
278
303
  if (!o.elevenlabsApiKey) return res.status(500).send('ElevenLabs API key is missing — set it in Settings');
279
304
  const out = await synthesizeElevenLabs({
@@ -0,0 +1,39 @@
1
+ /**
2
+ * OpenAI-compatible text-to-speech: POST <baseUrl>/audio/speech with { model, input, voice, response_format }.
3
+ * Works with OpenAI itself and with any server that speaks the same protocol (LocalAI, openedai-speech,
4
+ * Kokoro-FastAPI, Speaches, an on-premise gateway…), e.g. to run Piper voices behind it.
5
+ */
6
+
7
+ const MIME = { mp3: 'audio/mpeg', wav: 'audio/wav', opus: 'audio/ogg', aac: 'audio/aac', flac: 'audio/flac' };
8
+
9
+ /** @returns {URL | null} the parsed http(s) base URL, or null when it is not usable */
10
+ export function parseBaseUrl(value) {
11
+ try {
12
+ const url = new URL(value);
13
+ return /^https?:$/.test(url.protocol) ? url : null;
14
+ } catch (_) {
15
+ return null;
16
+ }
17
+ }
18
+
19
+ /**
20
+ * @returns {Promise<{ok: true, audio: Buffer, contentType: string} | {ok: false, status: number, body: string}>}
21
+ */
22
+ export async function synthesizeOpenAICompatible({ baseUrl, apiKey, model, voice, format, text }) {
23
+ const body = { model, input: text, voice };
24
+ if (format) body.response_format = format;
25
+ const headers = { 'Content-Type': 'application/json' };
26
+ if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
27
+
28
+ const res = await fetch(`${baseUrl.replace(/\/$/, '')}/audio/speech`, {
29
+ method: 'POST',
30
+ headers,
31
+ body: JSON.stringify(body),
32
+ });
33
+ if (!res.ok) return { ok: false, status: res.status, body: await res.text() };
34
+ const audio = Buffer.from(await res.arrayBuffer());
35
+ // Trust the server's Content-Type unless it is generic; otherwise derive it from the requested format.
36
+ const upstream = res.headers.get('content-type') || '';
37
+ const contentType = /^audio\//.test(upstream) ? upstream : MIME[format] || 'audio/mpeg';
38
+ return { ok: true, audio, contentType };
39
+ }
package/server/run.js CHANGED
@@ -5,6 +5,8 @@
5
5
  import express from 'express';
6
6
  import fs from 'node:fs';
7
7
  import path from 'node:path';
8
+ import https from 'node:https';
9
+ import os from 'node:os';
8
10
  import { fileURLToPath } from 'node:url';
9
11
  import { createVoiceAssistantRouter } from './index.js';
10
12
  import { createVendorRouter } from './vendor.js';
@@ -18,9 +20,11 @@ const appDir = path.resolve(here, '../dist-app');
18
20
  * @param {string} [opts.host='127.0.0.1'] Loopback by default: the Settings endpoints can read and
19
21
  * write API keys, so only expose them on a network you trust.
20
22
  * @param {string} [opts.settingsFile]
23
+ * @param {string} [opts.cert] PEM certificate file — with `key`, serves HTTPS (needed for the microphone on phones)
24
+ * @param {string} [opts.key] PEM private key file
21
25
  * @returns {Promise<{ url: string, server: import('node:http').Server, settings: object }>}
22
26
  */
23
- export async function startServer({ port = 3000, host = '127.0.0.1', settingsFile } = {}) {
27
+ export async function startServer({ port = 3000, host = '127.0.0.1', settingsFile, cert, key } = {}) {
24
28
  if (!fs.existsSync(path.join(appDir, 'index.html'))) {
25
29
  throw new Error(`Client app not found at ${appDir}. Run "npm run build" in the tz-voice-chat package first.`);
26
30
  }
@@ -33,10 +37,20 @@ export async function startServer({ port = 3000, host = '127.0.0.1', settingsFil
33
37
  app.get('*', (req, res) => res.sendFile(path.join(appDir, 'index.html')));
34
38
 
35
39
  await ready();
40
+ const secure = Boolean(cert && key);
36
41
  const server = await new Promise((resolve, reject) => {
37
- const s = app.listen(port, host, () => resolve(s));
42
+ const s = secure
43
+ ? https.createServer({ cert: fs.readFileSync(cert), key: fs.readFileSync(key) }, app).listen(port, host, () => resolve(s))
44
+ : app.listen(port, host, () => resolve(s));
38
45
  s.on('error', reject);
39
46
  });
47
+ const scheme = secure ? 'https' : 'http';
48
+ const actualPort = server.address().port;
40
49
  const shown = host === '0.0.0.0' || host === '::' ? 'localhost' : host;
41
- return { url: `http://${shown}:${server.address().port}`, server, settings, host };
50
+ // When listening on every interface, also list the addresses other devices can use.
51
+ const network = host === '0.0.0.0' || host === '::'
52
+ ? Object.values(os.networkInterfaces()).flat().filter(a => a && a.family === 'IPv4' && !a.internal)
53
+ .map(a => `${scheme}://${a.address}:${actualPort}`)
54
+ : [];
55
+ return { url: `${scheme}://${shown}:${actualPort}`, network, secure, server, settings, host };
42
56
  }
@@ -105,6 +105,7 @@ export const SETTINGS_SCHEMA = [
105
105
  ['kokoro', 'Kokoro in the browser', LOCAL],
106
106
  ['server-kokoro', 'Kokoro on the server (needs: npm install kokoro-js)', LOCAL],
107
107
  ['webspeech', 'Browser Web Speech API (built-in voices)', LOCAL],
108
+ ['openai-compatible', 'OpenAI-compatible server (Piper, LocalAI, Kokoro-FastAPI… any /audio/speech)', LOCAL],
108
109
  ['openai', 'OpenAI TTS', CLOUD],
109
110
  ['elevenlabs', 'ElevenLabs', CLOUD],
110
111
  ],
@@ -124,6 +125,17 @@ export const SETTINGS_SCHEMA = [
124
125
  showWhen: { ttsProvider: 'openai' }, suggestions: ['tts-1', 'tts-1-hd', 'gpt-4o-mini-tts'] },
125
126
  { key: 'openaiTtsVoice', label: 'OpenAI voice', type: 'text', env: 'OPENAI_TTS_VOICE', default: 'alloy',
126
127
  showWhen: { ttsProvider: 'openai' }, suggestions: ['alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer'] },
128
+ { key: 'ttsCompatBaseUrl', label: 'TTS server base URL', type: 'text', env: 'TTS_COMPAT_BASE_URL', default: 'http://localhost:8000/v1',
129
+ showWhen: { ttsProvider: 'openai-compatible' }, suggestions: ['http://localhost:8000/v1', 'http://localhost:8080/v1', 'http://localhost:8880/v1'],
130
+ hint: 'Must serve POST /audio/speech (the OpenAI text-to-speech protocol). From inside Docker use host.docker.internal instead of localhost.' },
131
+ { key: 'ttsCompatModel', label: 'TTS model name', type: 'text', env: 'TTS_COMPAT_MODEL', default: 'tts-1',
132
+ showWhen: { ttsProvider: 'openai-compatible' }, hint: 'Exactly as the server names it — e.g. tts-1, or a Piper voice such as en_US-lessac-medium' },
133
+ { key: 'ttsCompatVoice', label: 'TTS voice', type: 'text', env: 'TTS_COMPAT_VOICE', default: 'alloy',
134
+ showWhen: { ttsProvider: 'openai-compatible' }, hint: 'Voice name the server understands (alloy, af_bella, a Piper voice…)' },
135
+ { key: 'ttsCompatFormat', label: 'Audio format', type: 'select', env: 'TTS_COMPAT_FORMAT', default: '',
136
+ showWhen: { ttsProvider: 'openai-compatible' }, options: [['', 'Server default'], ['mp3', 'mp3'], ['wav', 'wav (no encoding delay)']] },
137
+ { key: 'ttsCompatApiKey', label: 'TTS API key (optional)', type: 'password', secret: true, env: 'TTS_COMPAT_API_KEY',
138
+ showWhen: { ttsProvider: 'openai-compatible' }, hint: 'Leave empty if the server needs no key (most local servers).' },
127
139
  { key: 'elevenlabsVoiceId', label: 'ElevenLabs voice ID', type: 'text', env: 'ELEVENLABS_VOICE_ID', default: '21m00Tcm4TlvDq8ikWAM',
128
140
  showWhen: { ttsProvider: 'elevenlabs' }, hint: 'Default is the premade "Rachel" voice. Copy another voice\'s ID from your ElevenLabs voice library.' },
129
141
  { key: 'elevenlabsTtsModel', label: 'ElevenLabs model', type: 'text', env: 'ELEVENLABS_TTS_MODEL', default: 'eleven_flash_v2_5',
@@ -185,6 +197,10 @@ export function computeMissing(values, secretsSet = {}) {
185
197
  if (!values.compatModel) missing.push({ key: 'compatModel', message: 'The model name for the OpenAI-compatible server is missing.', scope: 'chat' });
186
198
  }
187
199
 
200
+ if (values.ttsProvider === 'openai-compatible' && !values.ttsCompatBaseUrl) {
201
+ missing.push({ key: 'ttsCompatBaseUrl', message: 'The OpenAI-compatible text-to-speech server URL is missing.', scope: 'tts' });
202
+ }
203
+
188
204
  const needs = [
189
205
  { key: 'openrouterApiKey', name: 'OpenRouter API key', uses: [p === 'openrouter' && ['chat', 'chat']] },
190
206
  { key: 'anthropicApiKey', name: 'Anthropic API key', uses: [p === 'anthropic' && ['chat', 'chat']] },
@@ -1 +0,0 @@
1
- (function(){"use strict";let t=null,r=null;self.onmessage=async l=>{var n,p;const{type:o,messages:i,modelProxyUrl:g}=l.data;if(o==="init"){try{const{pipeline:e,TextStreamer:a,env:s}=await import("/vendor/transformers/transformers.min.js");s.remoteHost=g||"/api/models/",(p=(n=s==null?void 0:s.backends)==null?void 0:n.onnx)!=null&&p.wasm&&(s.backends.onnx.wasm.wasmPaths="/vendor/transformers/"),r=a,t=await e("text-generation","HuggingFaceTB/SmolLM2-360M-Instruct",{dtype:"q4",progress_callback:({status:c,progress:m}={})=>{self.postMessage({type:"progress",status:c,progress:(m??0)/100})}}),self.postMessage({type:"ready"})}catch(e){self.postMessage({type:"error",message:String((e==null?void 0:e.message)??e)})}return}if(o==="generate"){if(!t||!r){self.postMessage({type:"done"});return}try{const e=new r(t.tokenizer,{skip_prompt:!0,skip_special_tokens:!0,callback_function:a=>{self.postMessage({type:"token",text:a})}});await t(i,{max_new_tokens:150,do_sample:!1,streamer:e}),self.postMessage({type:"done"})}catch(e){console.error("[LLM worker] generate error:",e),self.postMessage({type:"done"})}}}})();
@@ -1 +0,0 @@
1
- (function(){"use strict";let i=null,c=Promise.resolve();self.onmessage=async t=>{var m,d;const{type:l,audio:a}=t.data;if(l==="init"){const n=t.data.model||"onnx-community/whisper-tiny.en",e=t.data.device||"wasm",p=e==="cpu"?"wasm":e,g=t.data.modelProxyUrl||"/api/models/";let r=t.data.dtype||"q8";p==="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=g,(d=(m=o==null?void 0:o.backends)==null?void 0:m.onnx)!=null&&d.wasm&&(o.backends.onnx.wasm.wasmPaths="/vendor/transformers/"),i=await s("automatic-speech-recognition",n,{dtype:r,device:p,progress_callback:({status:y,progress:w}={})=>{self.postMessage({type:"progress",status:y,progress:(w??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:",a==null?void 0:a.length),c=c.then(async()=>{var n;try{if(!i){console.warn("[Whisper worker] pipeline not ready, dropping segment"),self.postMessage({type:"transcript",text:""});return}const e=await i(a),p=(e==null?void 0:e.text)??((n=e==null?void 0:e[0])==null?void 0:n.text)??"";self.postMessage({type:"transcript",text:p})}catch(e){console.error("[Whisper worker] transcription error:",e),self.postMessage({type:"transcript",text:""})}}))}})();