tz-voice-chat 1.0.2 → 1.2.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 +616 -127
- package/bin/tz-voice-chat.js +46 -0
- package/dist/assets/llmWorker-CVEGn6yI.js +1 -0
- package/dist/assets/whisperWorker-D69IwlqW.js +1 -0
- package/dist/index.cjs +2 -1
- package/dist/index.js +1429 -437
- package/dist/style.css +1 -1
- package/dist-app/assets/index-BDMCgrF_.css +1 -0
- package/dist-app/assets/index-CFWv17S2.js +41 -0
- package/dist-app/assets/llmWorker-CVEGn6yI.js +1 -0
- package/dist-app/assets/whisperWorker-D69IwlqW.js +1 -0
- package/dist-app/index.html +27 -0
- package/package.json +58 -10
- package/server/chat.js +91 -0
- package/server/elevenlabs.js +40 -0
- package/server/index.js +344 -0
- package/server/openai-stt.js +21 -0
- package/server/run.js +42 -0
- package/server/settings.js +102 -0
- package/server/tts.js +139 -0
- package/server/vendor.js +57 -0
- package/shared/settingsSchema.js +212 -0
- package/vendor/kokoro/kokoro.web.js +1 -0
- package/vendor/ort/ort-wasm-simd-threaded.jsep.mjs +125 -0
- package/vendor/ort/ort-wasm-simd-threaded.jsep.wasm +0 -0
- package/vendor/ort/ort-wasm-simd-threaded.mjs +70 -0
- package/vendor/ort/ort-wasm-simd-threaded.wasm +0 -0
- package/vendor/ort/ort.wasm.min.js +8 -0
- package/vendor/transformers/ort-wasm-simd-threaded.jsep.mjs +125 -0
- package/vendor/transformers/ort-wasm-simd-threaded.jsep.wasm +0 -0
- package/vendor/transformers/transformers.min.js +2 -0
- package/vendor/transformers/transformers.node.min.mjs +2 -0
- package/vendor/transformers/transformers.node.mjs +36472 -0
- package/vendor/vad/bundle.min.js +2 -0
- package/vendor/vad/silero_vad_legacy.onnx +0 -0
- package/vendor/vad/vad.worklet.bundle.min.js +1 -0
- package/dist/assets/whisperWorker-BJuP9cl9.js +0 -1
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tz-voice-chat",
|
|
3
|
-
"version": "1.0
|
|
4
|
-
"description": "React hook
|
|
3
|
+
"version": "1.2.0",
|
|
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",
|
|
7
7
|
"module": "./dist/index.js",
|
|
@@ -10,25 +10,73 @@
|
|
|
10
10
|
"import": "./dist/index.js",
|
|
11
11
|
"require": "./dist/index.cjs"
|
|
12
12
|
},
|
|
13
|
-
"./style.css": "./dist/style.css"
|
|
13
|
+
"./style.css": "./dist/style.css",
|
|
14
|
+
"./server": "./server/index.js"
|
|
14
15
|
},
|
|
15
16
|
"files": [
|
|
16
17
|
"dist",
|
|
18
|
+
"dist-app",
|
|
19
|
+
"vendor",
|
|
20
|
+
"server",
|
|
21
|
+
"shared",
|
|
22
|
+
"bin",
|
|
17
23
|
"README.md"
|
|
18
24
|
],
|
|
19
25
|
"scripts": {
|
|
20
|
-
"build": "vite build",
|
|
21
|
-
"
|
|
26
|
+
"build": "node scripts/bundle-vendor.mjs && vite build && vite build --config vite.app.config.js",
|
|
27
|
+
"start": "node bin/tz-voice-chat.js",
|
|
28
|
+
"prepack": "npm run build"
|
|
22
29
|
},
|
|
23
|
-
"keywords": [
|
|
30
|
+
"keywords": [
|
|
31
|
+
"ai",
|
|
32
|
+
"chat",
|
|
33
|
+
"cli",
|
|
34
|
+
"hook",
|
|
35
|
+
"kokoro",
|
|
36
|
+
"react",
|
|
37
|
+
"server",
|
|
38
|
+
"speech",
|
|
39
|
+
"stt",
|
|
40
|
+
"tts",
|
|
41
|
+
"vad",
|
|
42
|
+
"voice",
|
|
43
|
+
"voice-assistant",
|
|
44
|
+
"whisper"
|
|
45
|
+
],
|
|
24
46
|
"license": "MIT",
|
|
47
|
+
"repository": {
|
|
48
|
+
"type": "git",
|
|
49
|
+
"url": "git+https://github.com/yuriyo/tz-voice-chat.git",
|
|
50
|
+
"directory": "packages/tz-voice-chat"
|
|
51
|
+
},
|
|
52
|
+
"homepage": "https://github.com/yuriyo/tz-voice-chat#readme",
|
|
53
|
+
"bugs": "https://github.com/yuriyo/tz-voice-chat/issues",
|
|
54
|
+
"publishConfig": {
|
|
55
|
+
"access": "public"
|
|
56
|
+
},
|
|
25
57
|
"peerDependencies": {
|
|
26
58
|
"react": ">=18",
|
|
27
|
-
"
|
|
28
|
-
"
|
|
29
|
-
|
|
59
|
+
"react-dom": ">=18",
|
|
60
|
+
"kokoro-js": "^1.2.1"
|
|
61
|
+
},
|
|
62
|
+
"bin": {
|
|
63
|
+
"tz-voice-chat": "bin/tz-voice-chat.js"
|
|
64
|
+
},
|
|
65
|
+
"dependencies": {
|
|
66
|
+
"express": "^4.18.2"
|
|
67
|
+
},
|
|
68
|
+
"engines": {
|
|
69
|
+
"node": ">=18"
|
|
70
|
+
},
|
|
71
|
+
"devDependencies": {
|
|
72
|
+
"@huggingface/transformers": "3.5.1",
|
|
73
|
+
"@ricky0123/vad-web": "0.0.29",
|
|
74
|
+
"kokoro-js": "1.2.1",
|
|
75
|
+
"onnxruntime-web": "1.22.0"
|
|
30
76
|
},
|
|
31
77
|
"peerDependenciesMeta": {
|
|
32
|
-
"kokoro-js": {
|
|
78
|
+
"kokoro-js": {
|
|
79
|
+
"optional": true
|
|
80
|
+
}
|
|
33
81
|
}
|
|
34
82
|
}
|
package/server/chat.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Chat provider adapters. Every provider is exposed to the browser as the same
|
|
3
|
+
* OpenAI-style SSE stream ("data: {choices:[{delta:{content}}]}" … "data: [DONE]"),
|
|
4
|
+
* so the client has a single parser.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
const OPENAI_BASE = () => (process.env.OPENAI_BASE_URL || 'https://api.openai.com/v1').replace(/\/$/, '');
|
|
8
|
+
const ANTHROPIC_BASE = () => (process.env.ANTHROPIC_BASE_URL || 'https://api.anthropic.com').replace(/\/$/, '');
|
|
9
|
+
|
|
10
|
+
/** Forward an upstream error response to the client unchanged. Returns true if it was an error. */
|
|
11
|
+
async function forwardError(upstream, res) {
|
|
12
|
+
if (upstream.ok) return false;
|
|
13
|
+
res.status(upstream.status).send(await upstream.text());
|
|
14
|
+
return true;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Providers that already speak OpenAI-style streaming: pass the bytes straight through. */
|
|
18
|
+
export async function streamOpenAICompatible(res, { url, apiKey, body }) {
|
|
19
|
+
const upstream = await fetch(url, {
|
|
20
|
+
method: 'POST',
|
|
21
|
+
// The key is optional: most local / on-premise servers need none.
|
|
22
|
+
headers: { ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}), 'Content-Type': 'application/json' },
|
|
23
|
+
body: JSON.stringify({ ...body, stream: true }),
|
|
24
|
+
});
|
|
25
|
+
if (await forwardError(upstream, res)) return;
|
|
26
|
+
res.setHeader('Content-Type', 'text/plain;charset=UTF-8');
|
|
27
|
+
const reader = upstream.body.getReader();
|
|
28
|
+
const decoder = new TextDecoder();
|
|
29
|
+
while (true) {
|
|
30
|
+
const { done, value } = await reader.read();
|
|
31
|
+
if (done) break;
|
|
32
|
+
res.write(decoder.decode(value, { stream: true }));
|
|
33
|
+
}
|
|
34
|
+
res.end();
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export const streamOpenAI = (res, { apiKey, model, messages }) =>
|
|
38
|
+
streamOpenAICompatible(res, {
|
|
39
|
+
url: `${OPENAI_BASE()}/chat/completions`,
|
|
40
|
+
apiKey,
|
|
41
|
+
body: { model, messages, max_tokens: 1250, temperature: 0.7 },
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Anthropic Messages API → OpenAI-style SSE. System messages go in the top-level
|
|
46
|
+
* `system` field; text deltas are re-emitted as OpenAI chunks.
|
|
47
|
+
*/
|
|
48
|
+
export async function streamAnthropic(res, { apiKey, model, messages }) {
|
|
49
|
+
const system = messages.filter(m => m.role === 'system').map(m => m.content).join('\n\n');
|
|
50
|
+
const chat = messages.filter(m => m.role !== 'system');
|
|
51
|
+
const upstream = await fetch(`${ANTHROPIC_BASE()}/v1/messages`, {
|
|
52
|
+
method: 'POST',
|
|
53
|
+
headers: {
|
|
54
|
+
'x-api-key': apiKey,
|
|
55
|
+
'anthropic-version': '2023-06-01',
|
|
56
|
+
'Content-Type': 'application/json',
|
|
57
|
+
},
|
|
58
|
+
body: JSON.stringify({
|
|
59
|
+
model,
|
|
60
|
+
max_tokens: 1250,
|
|
61
|
+
...(system ? { system } : {}),
|
|
62
|
+
messages: chat,
|
|
63
|
+
stream: true,
|
|
64
|
+
}),
|
|
65
|
+
});
|
|
66
|
+
if (await forwardError(upstream, res)) return;
|
|
67
|
+
|
|
68
|
+
res.setHeader('Content-Type', 'text/plain;charset=UTF-8');
|
|
69
|
+
const reader = upstream.body.getReader();
|
|
70
|
+
const decoder = new TextDecoder();
|
|
71
|
+
const emit = (text) => res.write(`data: ${JSON.stringify({ choices: [{ delta: { content: text } }] })}\n\n`);
|
|
72
|
+
let buffer = '';
|
|
73
|
+
while (true) {
|
|
74
|
+
const { done, value } = await reader.read();
|
|
75
|
+
if (done) break;
|
|
76
|
+
buffer += decoder.decode(value, { stream: true });
|
|
77
|
+
const lines = buffer.split('\n');
|
|
78
|
+
buffer = lines.pop();
|
|
79
|
+
for (const line of lines) {
|
|
80
|
+
const t = line.trim();
|
|
81
|
+
if (!t.startsWith('data:')) continue;
|
|
82
|
+
try {
|
|
83
|
+
const evt = JSON.parse(t.slice(5).trim());
|
|
84
|
+
if (evt.type === 'content_block_delta' && evt.delta?.type === 'text_delta' && evt.delta.text) emit(evt.delta.text);
|
|
85
|
+
else if (evt.type === 'error') console.error('[anthropic]', evt.error?.message ?? evt);
|
|
86
|
+
} catch (_) {}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
res.write('data: [DONE]\n\n');
|
|
90
|
+
res.end();
|
|
91
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/** ElevenLabs adapters (speech-to-text and text-to-speech). The browser never sees the API key. */
|
|
2
|
+
|
|
3
|
+
const BASE = () => (process.env.ELEVENLABS_BASE_URL || 'https://api.elevenlabs.io').replace(/\/$/, '');
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Scribe speech-to-text: POST /v1/speech-to-text (multipart: model_id, file).
|
|
7
|
+
* @returns {Promise<{ok: true, text: string} | {ok: false, status: number, body: string}>}
|
|
8
|
+
*/
|
|
9
|
+
export async function transcribeElevenLabs({ apiKey, model, language, audio, contentType = 'audio/wav' }) {
|
|
10
|
+
const form = new FormData();
|
|
11
|
+
form.append('model_id', model);
|
|
12
|
+
if (language) form.append('language_code', language);
|
|
13
|
+
form.append('tag_audio_events', 'false'); // no "(laughter)" style tags in a voice chat
|
|
14
|
+
form.append('file', new Blob([audio], { type: contentType }), 'speech.wav');
|
|
15
|
+
|
|
16
|
+
const res = await fetch(`${BASE()}/v1/speech-to-text`, {
|
|
17
|
+
method: 'POST',
|
|
18
|
+
headers: { 'xi-api-key': apiKey },
|
|
19
|
+
body: form,
|
|
20
|
+
});
|
|
21
|
+
if (!res.ok) return { ok: false, status: res.status, body: await res.text() };
|
|
22
|
+
const json = await res.json();
|
|
23
|
+
const text = json.text ?? (json.transcripts || []).map(t => t.text).join(' ') ?? '';
|
|
24
|
+
return { ok: true, text: String(text).trim() };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Text-to-speech: POST /v1/text-to-speech/{voice_id} -> MP3 bytes.
|
|
29
|
+
* @returns {Promise<{ok: true, audio: Buffer, contentType: string} | {ok: false, status: number, body: string}>}
|
|
30
|
+
*/
|
|
31
|
+
export async function synthesizeElevenLabs({ apiKey, voiceId, model, text }) {
|
|
32
|
+
if (!/^[\w-]+$/.test(voiceId || '')) return { ok: false, status: 400, body: 'Invalid ElevenLabs voice id' };
|
|
33
|
+
const res = await fetch(`${BASE()}/v1/text-to-speech/${voiceId}?output_format=mp3_44100_128`, {
|
|
34
|
+
method: 'POST',
|
|
35
|
+
headers: { 'xi-api-key': apiKey, 'Content-Type': 'application/json', Accept: 'audio/mpeg' },
|
|
36
|
+
body: JSON.stringify({ text, model_id: model }),
|
|
37
|
+
});
|
|
38
|
+
if (!res.ok) return { ok: false, status: res.status, body: await res.text() };
|
|
39
|
+
return { ok: true, audio: Buffer.from(await res.arrayBuffer()), contentType: res.headers.get('content-type') || 'audio/mpeg' };
|
|
40
|
+
}
|
package/server/index.js
ADDED
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* tz-voice-chat/server — Express router that backs the voice-assistant client.
|
|
3
|
+
*
|
|
4
|
+
* import express from 'express';
|
|
5
|
+
* import { createVoiceAssistantRouter } from 'tz-voice-chat/server';
|
|
6
|
+
*
|
|
7
|
+
* const app = express();
|
|
8
|
+
* const { router, ready } = createVoiceAssistantRouter();
|
|
9
|
+
* app.use('/api', router);
|
|
10
|
+
* await ready(); // pre-load server-side Kokoro, if selected
|
|
11
|
+
*
|
|
12
|
+
* Routes (relative to the mount point):
|
|
13
|
+
* GET /config public configuration + which required settings are missing
|
|
14
|
+
* GET /settings editable settings (secrets are never returned, only whether they are set)
|
|
15
|
+
* PUT /settings save a partial update (persisted to the settings file, applied immediately)
|
|
16
|
+
* GET /settings/export full settings INCLUDING secrets, as a downloadable JSON file
|
|
17
|
+
* GET /stats server process memory
|
|
18
|
+
* POST /chat POST /stt POST /tts GET /models/* (Hugging Face model proxy)
|
|
19
|
+
*
|
|
20
|
+
* Configuration precedence: defaults < environment variables (see shared/settingsSchema.js)
|
|
21
|
+
* < `options` < the saved settings file (written by the Settings page).
|
|
22
|
+
* Nothing is required up front: with no chat provider configured the app starts, uses the
|
|
23
|
+
* pre-configured speech models, and asks the user to finish setup in Settings.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import express from 'express';
|
|
27
|
+
import { Readable } from 'node:stream';
|
|
28
|
+
import { configureKokoro, loadKokoro, generateWav, resetKokoro } from './tts.js';
|
|
29
|
+
import { createSettingsStore } from './settings.js';
|
|
30
|
+
import { streamOpenAI, streamAnthropic, streamOpenAICompatible } from './chat.js';
|
|
31
|
+
import { transcribeElevenLabs, synthesizeElevenLabs } from './elevenlabs.js';
|
|
32
|
+
import { transcribeOpenAI } from './openai-stt.js';
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* @param {object} [options]
|
|
36
|
+
* @param {string} [options.settingsFile] Where saved settings live. Default: $TZ_VOICE_CHAT_SETTINGS or ~/.tz-voice-chat/settings.json
|
|
37
|
+
* @param {object} [options.defaults] Initial values for any setting (keys from shared/settingsSchema.js);
|
|
38
|
+
* the saved settings file takes precedence over these.
|
|
39
|
+
* @returns {{ router: import('express').Router, ready: () => Promise<void>, settings: object }}
|
|
40
|
+
*/
|
|
41
|
+
export function createVoiceAssistantRouter({ settingsFile, defaults = {} } = {}) {
|
|
42
|
+
const settings = createSettingsStore({ file: settingsFile, options: defaults });
|
|
43
|
+
|
|
44
|
+
const applyKokoro = (o) => configureKokoro({ dtype: o.kokoroDtype, device: o.kokoroDevice, voice: o.kokoroVoice });
|
|
45
|
+
applyKokoro(settings.get());
|
|
46
|
+
|
|
47
|
+
// Server-side Kokoro must be reloaded when its parameters (or the provider) change.
|
|
48
|
+
settings.onChange((now, before) => {
|
|
49
|
+
const changed = ['kokoroDtype', 'kokoroDevice', 'kokoroVoice', 'ttsProvider'].some(k => now[k] !== before[k]);
|
|
50
|
+
if (!changed) return;
|
|
51
|
+
applyKokoro(now);
|
|
52
|
+
resetKokoro();
|
|
53
|
+
if (now.ttsProvider === 'server-kokoro') loadKokoro().catch(err => console.error('[Kokoro]', err.message));
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
const router = express.Router();
|
|
57
|
+
router.use(express.json());
|
|
58
|
+
|
|
59
|
+
const chatModel = (o) => ({
|
|
60
|
+
huggingface: 'gpt2',
|
|
61
|
+
openrouter: o.openrouterModel,
|
|
62
|
+
openai: o.openaiChatModel,
|
|
63
|
+
'openai-compatible': o.compatModel,
|
|
64
|
+
anthropic: o.anthropicModel,
|
|
65
|
+
local: 'SmolLM2-360M-Instruct',
|
|
66
|
+
}[o.chatProvider] ?? '');
|
|
67
|
+
|
|
68
|
+
// Public configuration: tells the client how to wire STT/TTS/LLM, and what is still missing.
|
|
69
|
+
router.get('/config', (req, res) => {
|
|
70
|
+
const o = settings.get();
|
|
71
|
+
const { missing } = settings.getPublic();
|
|
72
|
+
const chatReady = !missing.some(m => m.scope === 'chat');
|
|
73
|
+
res.json({
|
|
74
|
+
chatProvider: o.chatProvider,
|
|
75
|
+
chatModel: chatModel(o),
|
|
76
|
+
chatReady,
|
|
77
|
+
hasApiKey: chatReady && o.chatProvider !== 'local', // true = chat goes through the server proxy
|
|
78
|
+
missing,
|
|
79
|
+
systemPrompt: o.systemPrompt,
|
|
80
|
+
sttProvider: o.sttProvider,
|
|
81
|
+
openaiSttModel: o.openaiSttModel,
|
|
82
|
+
elevenlabsSttModel: o.elevenlabsSttModel,
|
|
83
|
+
elevenlabsVoiceId: o.elevenlabsVoiceId,
|
|
84
|
+
elevenlabsTtsModel: o.elevenlabsTtsModel,
|
|
85
|
+
kokoroDevice: o.kokoroDevice,
|
|
86
|
+
kokoroSpeed: o.kokoroSpeed,
|
|
87
|
+
kokoroDtype: o.kokoroDtype,
|
|
88
|
+
kokoroBrowserDevice: o.kokoroBrowserDevice,
|
|
89
|
+
whisperModel: o.whisperModel,
|
|
90
|
+
whisperDtype: o.whisperDtype,
|
|
91
|
+
whisperDevice: o.whisperDevice,
|
|
92
|
+
ttsProvider: o.ttsProvider,
|
|
93
|
+
kokoroVoice: o.kokoroVoice,
|
|
94
|
+
openaiTtsModel: o.openaiTtsModel,
|
|
95
|
+
openaiTtsVoice: o.openaiTtsVoice,
|
|
96
|
+
webSpeechVoice: o.webSpeechVoice,
|
|
97
|
+
webSpeechRate: o.webSpeechRate,
|
|
98
|
+
webSpeechPitch: o.webSpeechPitch,
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
// ── Settings ────────────────────────────────────────────────────────────────
|
|
103
|
+
router.get('/settings', (req, res) => {
|
|
104
|
+
res.json({ ...settings.getPublic(), file: settings.file });
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
router.put('/settings', (req, res) => {
|
|
108
|
+
// Accept either a bare object or the export format ({ settings: {...} }).
|
|
109
|
+
const body = req.body && typeof req.body === 'object' ? req.body : {};
|
|
110
|
+
const patch = body.settings && typeof body.settings === 'object' ? body.settings : body;
|
|
111
|
+
try {
|
|
112
|
+
const { ignored } = settings.update(patch);
|
|
113
|
+
res.json({ ...settings.getPublic(), file: settings.file, ignored });
|
|
114
|
+
} catch (err) {
|
|
115
|
+
console.error('[/settings]', err);
|
|
116
|
+
res.status(500).send(`Could not save settings: ${err.message}`);
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
router.get('/settings/export', (req, res) => {
|
|
121
|
+
res.setHeader('Content-Disposition', 'attachment; filename="tz-voice-chat-settings.json"');
|
|
122
|
+
res.json({ format: 'tz-voice-chat-settings', version: 1, settings: settings.exportAll() });
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
// Server process memory, shown in the client's info card.
|
|
126
|
+
router.get('/stats', (req, res) => {
|
|
127
|
+
const { rss, heapUsed } = process.memoryUsage();
|
|
128
|
+
res.json({ rss, heapUsed });
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
router.post('/chat', async (req, res) => {
|
|
132
|
+
const o = settings.get();
|
|
133
|
+
const { messages } = req.body;
|
|
134
|
+
if (!messages || !Array.isArray(messages)) {
|
|
135
|
+
return res.status(400).send('Invalid request payload');
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
try {
|
|
139
|
+
if (o.chatProvider === 'huggingface') {
|
|
140
|
+
if (!o.huggingfaceApiKey) {
|
|
141
|
+
return res.status(500).send('Hugging Face token is missing — set it in Settings');
|
|
142
|
+
}
|
|
143
|
+
const prompt = messages.map(m => `${m.role}: ${m.content}`).join('\n') + '\nassistant:';
|
|
144
|
+
const response = await fetch('https://api-inference.huggingface.co/models/gpt2', {
|
|
145
|
+
method: 'POST',
|
|
146
|
+
headers: {
|
|
147
|
+
Authorization: `Bearer ${o.huggingfaceApiKey}`,
|
|
148
|
+
'Content-Type': 'application/json',
|
|
149
|
+
},
|
|
150
|
+
body: JSON.stringify({ inputs: prompt, parameters: { max_new_tokens: 200, return_full_text: false } }),
|
|
151
|
+
});
|
|
152
|
+
const data = await response.json();
|
|
153
|
+
if (data.error) return res.status(500).send(data.error);
|
|
154
|
+
const text = Array.isArray(data) ? data[0]?.generated_text || '' : data.generated_text || '';
|
|
155
|
+
res.setHeader('Content-Type', 'text/plain;charset=UTF-8');
|
|
156
|
+
res.write(text);
|
|
157
|
+
res.end();
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
if (o.chatProvider === 'openai') {
|
|
162
|
+
if (!o.openaiApiKey) return res.status(500).send('OpenAI API key is missing — set it in Settings');
|
|
163
|
+
return await streamOpenAI(res, { apiKey: o.openaiApiKey, model: o.openaiChatModel, messages });
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
if (o.chatProvider === 'openai-compatible') {
|
|
167
|
+
let base;
|
|
168
|
+
try {
|
|
169
|
+
base = new URL(o.compatBaseUrl);
|
|
170
|
+
if (!/^https?:$/.test(base.protocol)) throw new Error('not http(s)');
|
|
171
|
+
} catch (_) {
|
|
172
|
+
return res.status(400).send('The OpenAI-compatible server URL is invalid — fix it in Settings');
|
|
173
|
+
}
|
|
174
|
+
if (!o.compatModel) return res.status(400).send('The OpenAI-compatible model name is missing — set it in Settings');
|
|
175
|
+
try {
|
|
176
|
+
return await streamOpenAICompatible(res, {
|
|
177
|
+
url: `${base.href.replace(/\/$/, '')}/chat/completions`,
|
|
178
|
+
apiKey: o.compatApiKey,
|
|
179
|
+
body: { model: o.compatModel, messages, max_tokens: 1250, temperature: 0.7 },
|
|
180
|
+
});
|
|
181
|
+
} catch (err) {
|
|
182
|
+
return res.status(502).send(`Could not reach the OpenAI-compatible server at ${base.origin}: ${err.cause?.code || err.message}`);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
if (o.chatProvider === 'anthropic') {
|
|
187
|
+
if (!o.anthropicApiKey) return res.status(500).send('Anthropic API key is missing — set it in Settings');
|
|
188
|
+
return await streamAnthropic(res, { apiKey: o.anthropicApiKey, model: o.anthropicModel, messages });
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
if (o.chatProvider !== 'openrouter') {
|
|
192
|
+
return res.status(400).send('No server-side chat provider is configured — choose one in Settings');
|
|
193
|
+
}
|
|
194
|
+
if (!o.openrouterApiKey) {
|
|
195
|
+
return res.status(500).send('OpenRouter API key is missing — set it in Settings');
|
|
196
|
+
}
|
|
197
|
+
await streamOpenAICompatible(res, {
|
|
198
|
+
url: 'https://openrouter.ai/api/v1/chat/completions',
|
|
199
|
+
apiKey: o.openrouterApiKey,
|
|
200
|
+
body: { model: o.openrouterModel, messages, max_tokens: 1250, temperature: 0.7 },
|
|
201
|
+
});
|
|
202
|
+
} catch (err) {
|
|
203
|
+
console.error(err);
|
|
204
|
+
res.status(500).send(err.message || 'Unexpected proxy error');
|
|
205
|
+
}
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
// Speech-to-text for providers that run on the server (OpenAI, ElevenLabs). Body: a WAV file.
|
|
209
|
+
router.post('/stt', express.raw({ type: ['audio/*', 'application/octet-stream'], limit: '25mb' }), async (req, res) => {
|
|
210
|
+
const o = settings.get();
|
|
211
|
+
const providers = {
|
|
212
|
+
elevenlabs: { name: 'ElevenLabs', key: o.elevenlabsApiKey, run: transcribeElevenLabs, model: o.elevenlabsSttModel, language: o.elevenlabsLanguage },
|
|
213
|
+
openai: { name: 'OpenAI', key: o.openaiApiKey, run: transcribeOpenAI, model: o.openaiSttModel, language: o.openaiSttLanguage },
|
|
214
|
+
};
|
|
215
|
+
const sp = providers[o.sttProvider];
|
|
216
|
+
if (!sp) {
|
|
217
|
+
return res.status(400).send('Server-side speech-to-text is not enabled — choose a provider in Settings');
|
|
218
|
+
}
|
|
219
|
+
if (!sp.key) return res.status(500).send(`${sp.name} API key is missing — set it in Settings`);
|
|
220
|
+
if (!Buffer.isBuffer(req.body) || !req.body.length) return res.status(400).send('Send the audio as the request body (audio/wav)');
|
|
221
|
+
try {
|
|
222
|
+
const out = await sp.run({
|
|
223
|
+
apiKey: sp.key,
|
|
224
|
+
model: sp.model,
|
|
225
|
+
language: sp.language,
|
|
226
|
+
audio: req.body,
|
|
227
|
+
contentType: req.headers['content-type'] || 'audio/wav',
|
|
228
|
+
});
|
|
229
|
+
if (!out.ok) return res.status(out.status).send(out.body);
|
|
230
|
+
res.json({ text: out.text });
|
|
231
|
+
} catch (err) {
|
|
232
|
+
console.error('[/stt]', err);
|
|
233
|
+
res.status(500).send(err.message || 'STT error');
|
|
234
|
+
}
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
router.post('/tts', async (req, res) => {
|
|
238
|
+
const o = settings.get();
|
|
239
|
+
const { text, voice, model, speed } = req.body;
|
|
240
|
+
if (!text) return res.status(400).send('text is required');
|
|
241
|
+
|
|
242
|
+
try {
|
|
243
|
+
if (o.ttsProvider === 'server-kokoro') {
|
|
244
|
+
const wavBuf = await generateWav(text, voice || o.kokoroVoice, Number(speed) > 0 ? Number(speed) : o.kokoroSpeed || 1);
|
|
245
|
+
res.setHeader('Content-Type', 'audio/wav');
|
|
246
|
+
res.setHeader('Content-Length', String(wavBuf.length));
|
|
247
|
+
return res.end(wavBuf);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
if (o.ttsProvider === 'openai') {
|
|
251
|
+
if (!o.openaiApiKey) return res.status(500).send('OpenAI API key is missing — set it in Settings');
|
|
252
|
+
const response = await fetch('https://api.openai.com/v1/audio/speech', {
|
|
253
|
+
method: 'POST',
|
|
254
|
+
headers: {
|
|
255
|
+
Authorization: `Bearer ${o.openaiApiKey}`,
|
|
256
|
+
'Content-Type': 'application/json',
|
|
257
|
+
},
|
|
258
|
+
body: JSON.stringify({
|
|
259
|
+
model: model || o.openaiTtsModel,
|
|
260
|
+
voice: voice || o.openaiTtsVoice,
|
|
261
|
+
input: text,
|
|
262
|
+
}),
|
|
263
|
+
});
|
|
264
|
+
if (!response.ok) {
|
|
265
|
+
return res.status(response.status).send(await response.text());
|
|
266
|
+
}
|
|
267
|
+
res.setHeader('Content-Type', 'audio/mpeg');
|
|
268
|
+
const reader = response.body.getReader();
|
|
269
|
+
while (true) {
|
|
270
|
+
const { done, value } = await reader.read();
|
|
271
|
+
if (done) break;
|
|
272
|
+
res.write(value);
|
|
273
|
+
}
|
|
274
|
+
return res.end();
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
if (o.ttsProvider === 'elevenlabs') {
|
|
278
|
+
if (!o.elevenlabsApiKey) return res.status(500).send('ElevenLabs API key is missing — set it in Settings');
|
|
279
|
+
const out = await synthesizeElevenLabs({
|
|
280
|
+
apiKey: o.elevenlabsApiKey,
|
|
281
|
+
voiceId: voice || o.elevenlabsVoiceId,
|
|
282
|
+
model: model || o.elevenlabsTtsModel,
|
|
283
|
+
text,
|
|
284
|
+
});
|
|
285
|
+
if (!out.ok) return res.status(out.status).send(out.body);
|
|
286
|
+
res.setHeader('Content-Type', out.contentType);
|
|
287
|
+
res.setHeader('Content-Length', String(out.audio.length));
|
|
288
|
+
return res.end(out.audio);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// 'kokoro' (browser) / 'webspeech' — the client synthesises audio itself.
|
|
292
|
+
return res.status(400).send(`TTS provider "${o.ttsProvider}" does not use a server-side audio endpoint`);
|
|
293
|
+
} catch (err) {
|
|
294
|
+
console.error('[/tts]', err);
|
|
295
|
+
res.status(500).send(err.message || 'TTS error');
|
|
296
|
+
}
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
// HuggingFace model proxy. Keeps all model traffic on our own origin: the browser
|
|
300
|
+
// (transformers.js with env.remoteHost = '<mount>/models/') requests
|
|
301
|
+
// GET /models/org/repo/resolve/revision/path/to/file
|
|
302
|
+
// which we proxy to https://huggingface.co/org/repo/resolve/revision/path/to/file.
|
|
303
|
+
// LFS redirects are followed server-side and the body is streamed, never buffered.
|
|
304
|
+
router.get('/models/*', async (req, res) => {
|
|
305
|
+
const hfPath = req.params[0];
|
|
306
|
+
|
|
307
|
+
// Allow only safe path characters — prevent open-redirect / SSRF abuse.
|
|
308
|
+
if (!/^[\w][\w.\-/]*$/.test(hfPath)) {
|
|
309
|
+
return res.status(400).json({ error: 'Invalid model path' });
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
try {
|
|
313
|
+
const upstream = await fetch(`https://huggingface.co/${hfPath}`, {
|
|
314
|
+
headers: {
|
|
315
|
+
'User-Agent': 'tz-voice-chat/1.0',
|
|
316
|
+
...(req.headers.range ? { Range: req.headers.range } : {}),
|
|
317
|
+
},
|
|
318
|
+
redirect: 'follow',
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
res.status(upstream.status);
|
|
322
|
+
for (const h of ['content-type', 'content-length', 'content-range', 'accept-ranges', 'cache-control', 'etag']) {
|
|
323
|
+
const v = upstream.headers.get(h);
|
|
324
|
+
if (v) res.setHeader(h, v);
|
|
325
|
+
}
|
|
326
|
+
Readable.fromWeb(upstream.body).pipe(res);
|
|
327
|
+
} catch (err) {
|
|
328
|
+
console.error('[/models proxy]', err.message);
|
|
329
|
+
if (!res.headersSent) res.status(502).json({ error: 'Model proxy failed' });
|
|
330
|
+
}
|
|
331
|
+
});
|
|
332
|
+
|
|
333
|
+
// Load server-side Kokoro eagerly so the first TTS request has no cold start.
|
|
334
|
+
async function ready() {
|
|
335
|
+
if (settings.get().ttsProvider === 'server-kokoro') {
|
|
336
|
+
try { await loadKokoro(); } catch (err) { console.warn('[tz-voice-chat]', err.message); }
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
return { router, ready, settings };
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
export { createVendorRouter } from './vendor.js';
|
|
344
|
+
export { loadKokoro, generateWav };
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** OpenAI speech-to-text: POST /v1/audio/transcriptions (multipart: file, model). */
|
|
2
|
+
|
|
3
|
+
const BASE = () => (process.env.OPENAI_BASE_URL || 'https://api.openai.com/v1').replace(/\/$/, '');
|
|
4
|
+
|
|
5
|
+
/** @returns {Promise<{ok: true, text: string} | {ok: false, status: number, body: string}>} */
|
|
6
|
+
export async function transcribeOpenAI({ apiKey, model, language, audio, contentType = 'audio/wav' }) {
|
|
7
|
+
const form = new FormData();
|
|
8
|
+
form.append('model', model);
|
|
9
|
+
form.append('response_format', 'json');
|
|
10
|
+
if (language) form.append('language', language);
|
|
11
|
+
form.append('file', new Blob([audio], { type: contentType }), 'speech.wav');
|
|
12
|
+
|
|
13
|
+
const res = await fetch(`${BASE()}/audio/transcriptions`, {
|
|
14
|
+
method: 'POST',
|
|
15
|
+
headers: { Authorization: `Bearer ${apiKey}` },
|
|
16
|
+
body: form,
|
|
17
|
+
});
|
|
18
|
+
if (!res.ok) return { ok: false, status: res.status, body: await res.text() };
|
|
19
|
+
const json = await res.json();
|
|
20
|
+
return { ok: true, text: String(json.text ?? '').trim() };
|
|
21
|
+
}
|
package/server/run.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Starts a complete, self-contained voice-assistant server: the API router, the vendored
|
|
3
|
+
* browser runtime assets, and the prebuilt client page. Used by the `tz-voice-chat` CLI.
|
|
4
|
+
*/
|
|
5
|
+
import express from 'express';
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import { createVoiceAssistantRouter } from './index.js';
|
|
10
|
+
import { createVendorRouter } from './vendor.js';
|
|
11
|
+
|
|
12
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
13
|
+
const appDir = path.resolve(here, '../dist-app');
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @param {object} [opts]
|
|
17
|
+
* @param {number} [opts.port=3000]
|
|
18
|
+
* @param {string} [opts.host='127.0.0.1'] Loopback by default: the Settings endpoints can read and
|
|
19
|
+
* write API keys, so only expose them on a network you trust.
|
|
20
|
+
* @param {string} [opts.settingsFile]
|
|
21
|
+
* @returns {Promise<{ url: string, server: import('node:http').Server, settings: object }>}
|
|
22
|
+
*/
|
|
23
|
+
export async function startServer({ port = 3000, host = '127.0.0.1', settingsFile } = {}) {
|
|
24
|
+
if (!fs.existsSync(path.join(appDir, 'index.html'))) {
|
|
25
|
+
throw new Error(`Client app not found at ${appDir}. Run "npm run build" in the tz-voice-chat package first.`);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const app = express();
|
|
29
|
+
const { router, ready, settings } = createVoiceAssistantRouter({ settingsFile });
|
|
30
|
+
app.use('/api', router);
|
|
31
|
+
app.use('/vendor', createVendorRouter());
|
|
32
|
+
app.use(express.static(appDir));
|
|
33
|
+
app.get('*', (req, res) => res.sendFile(path.join(appDir, 'index.html')));
|
|
34
|
+
|
|
35
|
+
await ready();
|
|
36
|
+
const server = await new Promise((resolve, reject) => {
|
|
37
|
+
const s = app.listen(port, host, () => resolve(s));
|
|
38
|
+
s.on('error', reject);
|
|
39
|
+
});
|
|
40
|
+
const shown = host === '0.0.0.0' || host === '::' ? 'localhost' : host;
|
|
41
|
+
return { url: `http://${shown}:${server.address().port}`, server, settings, host };
|
|
42
|
+
}
|