pnnbao-ump commited on
Commit
0efb691
·
1 Parent(s): 1b8a8f6

feat: optimize SDK core and add high-performance CPU streaming demo

Browse files
README.md CHANGED
@@ -105,6 +105,19 @@ The fastest way to experience VieNeu-TTS is through the Web interface (Gradio).
105
  ```
106
  Access the UI at `http://127.0.0.1:7860`.
107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  ### 🚀 GGUF GPU Acceleration (Optional) <a name="gguf-gpu"></a>
109
  If you want to use GGUF models with GPU acceleration (llama-cpp-python), follow these steps:
110
 
 
105
  ```
106
  Access the UI at `http://127.0.0.1:7860`.
107
 
108
+ ### ⚡ Real-time Streaming (CPU Optimized)
109
+ VieNeu-TTS supports **ultra-low latency streaming**, allowing audio playback to start before the entire sentence is finished. This is specifically optimized for **CPU-only** devices using the GGUF backend.
110
+
111
+ * **Latency:** <300ms for the first chunk on modern i3/i5 CPUs.
112
+ * **Efficiency:** Uses Q4/Q8 quantization and ONNX-based lightweight codecs.
113
+ * **Usage:** Perfect for real-time interactive AI assistants.
114
+
115
+ **Start the dedicated CPU streaming demo:**
116
+ ```bash
117
+ uv run web_stream_gguf.py
118
+ ```
119
+ Then open `http://localhost:8001` in your browser.
120
+
121
  ### 🚀 GGUF GPU Acceleration (Optional) <a name="gguf-gpu"></a>
122
  If you want to use GGUF models with GPU acceleration (llama-cpp-python), follow these steps:
123
 
client/client.html ADDED
@@ -0,0 +1,767 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+
4
+ <head>
5
+ <meta charset="UTF-8" />
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
+ <title>VieNeu SDK Stream</title>
8
+ <link rel="icon"
9
+ href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🦜</text></svg>">
10
+
11
+ <!-- Tailwind CSS -->
12
+ <script src="https://cdn.tailwindcss.com"></script>
13
+ <script>
14
+ tailwind.config = {
15
+ theme: {
16
+ extend: {
17
+ colors: {
18
+ slate: {
19
+ 850: '#151e2e',
20
+ 900: '#0f172a',
21
+ 950: '#020617',
22
+ },
23
+ primary: {
24
+ 400: '#38bdf8',
25
+ 500: '#0ea5e9',
26
+ 600: '#0284c7',
27
+ },
28
+ violet: {
29
+ 500: '#8b5cf6',
30
+ }
31
+ },
32
+ animation: {
33
+ 'pulse-slow': 'pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite',
34
+ }
35
+ }
36
+ }
37
+ }
38
+ </script>
39
+
40
+ <!-- Custom Scrollbar Styles -->
41
+ <style>
42
+ body {
43
+ background-color: #020617;
44
+ color: #f8fafc;
45
+ }
46
+
47
+ ::-webkit-scrollbar {
48
+ width: 8px;
49
+ height: 8px;
50
+ }
51
+
52
+ ::-webkit-scrollbar-track {
53
+ background: #0f172a;
54
+ }
55
+
56
+ ::-webkit-scrollbar-thumb {
57
+ background: #334155;
58
+ border-radius: 4px;
59
+ }
60
+
61
+ ::-webkit-scrollbar-thumb:hover {
62
+ background: #475569;
63
+ }
64
+ </style>
65
+
66
+ <!-- Import Map for React -->
67
+ <script type="importmap">
68
+ {
69
+ "imports": {
70
+ "react": "https://esm.sh/react@18.2.0",
71
+ "react-dom/client": "https://esm.sh/react-dom@18.2.0/client",
72
+ "react-dom/": "https://esm.sh/react-dom@^19.2.3/",
73
+ "react/": "https://esm.sh/react@^19.2.3/"
74
+ }
75
+ }
76
+ </script>
77
+
78
+ <!-- Babel Standalone for in-browser JSX compilation -->
79
+ <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
80
+ </head>
81
+
82
+ <body>
83
+ <div id="root"></div>
84
+
85
+ <!-- MAIN APPLICATION SCRIPT -->
86
+ <script type="text/babel" data-type="module">
87
+ import React, { useState, useRef, useEffect } from 'react';
88
+ import ReactDOM from 'react-dom/client';
89
+
90
+ // ==========================================
91
+ // CONSTANTS (Replaces TS Enums)
92
+ // ==========================================
93
+ const StreamStatus = {
94
+ IDLE: 'IDLE',
95
+ CONNECTING: 'CONNECTING',
96
+ PLAYING: 'PLAYING',
97
+ COMPLETED: 'COMPLETED',
98
+ ERROR: 'ERROR'
99
+ };
100
+
101
+ // ==========================================
102
+ // ICONS
103
+ // ==========================================
104
+ const Mic2 = ({ className }) => (
105
+ <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
106
+ <path d="m12 8-9.04 9.06a2.82 2.82 0 1 0 3.98 3.98L16 12" />
107
+ <circle cx="17" cy="7" r="5" />
108
+ </svg>
109
+ );
110
+
111
+ const Play = ({ className }) => (
112
+ <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
113
+ <polygon points="5 3 19 12 5 21 5 3" />
114
+ </svg>
115
+ );
116
+
117
+ const StopCircle = ({ className }) => (
118
+ <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
119
+ <circle cx="12" cy="12" r="10" />
120
+ <rect width="6" height="6" x="9" y="9" />
121
+ </svg>
122
+ );
123
+
124
+ const Loader2 = ({ className }) => (
125
+ <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
126
+ <path d="M21 12a9 9 0 1 1-6.219-8.56" />
127
+ </svg>
128
+ );
129
+
130
+ const Zap = ({ className }) => (
131
+ <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
132
+ <polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2" />
133
+ </svg>
134
+ );
135
+
136
+ const Activity = ({ className }) => (
137
+ <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
138
+ <path d="M22 12h-4l-3 9L9 3l-3 9H2" />
139
+ </svg>
140
+ );
141
+
142
+ // ==========================================
143
+ // VISUALIZER COMPONENT
144
+ // ==========================================
145
+ const Visualizer = ({ audioElementRef, isPlaying, externalContext, externalSource }) => {
146
+ const canvasRef = useRef(null);
147
+ const audioContextRef = useRef(null);
148
+ const analyserRef = useRef(null);
149
+ const animationFrameRef = useRef(0);
150
+
151
+ useEffect(() => {
152
+ if (isPlaying) {
153
+ // MODE A: External Web Audio API (Ultra Low Latency)
154
+ if (externalContext && externalContext.state !== 'closed') {
155
+ try {
156
+ // Reuse existing context
157
+ audioContextRef.current = externalContext;
158
+
159
+ if (!analyserRef.current) {
160
+ const analyser = externalContext.createAnalyser();
161
+ analyser.fftSize = 256;
162
+ analyserRef.current = analyser;
163
+
164
+ // HACK: To visualize, we need to connect the SOURCE to this analyser.
165
+ // But the source (buffers) are created dynamically in the loop.
166
+ // So we rely on the parent to connect the destination to a global analyser node if possible,
167
+ // OR we create a "tap" node.
168
+ // BETTER APPROACH: The parent creates the Analyser and passes it down.
169
+ }
170
+ } catch (e) { console.error(e); }
171
+ }
172
+ // MODE B: Standard Audio Element
173
+ else if (!audioContextRef.current && audioElementRef.current) {
174
+ try {
175
+ const AudioContextClass = window.AudioContext || window.webkitAudioContext;
176
+ const ctx = new AudioContextClass();
177
+ const analyser = ctx.createAnalyser();
178
+ analyser.fftSize = 256;
179
+
180
+ const source = ctx.createMediaElementSource(audioElementRef.current);
181
+ source.connect(analyser);
182
+ analyser.connect(ctx.destination);
183
+
184
+ audioContextRef.current = ctx;
185
+ analyserRef.current = analyser;
186
+ } catch (e) {
187
+ console.error("Audio Context initialization failed", e);
188
+ }
189
+ }
190
+
191
+ if (audioContextRef.current?.state === 'suspended') {
192
+ audioContextRef.current.resume();
193
+ }
194
+ }
195
+ }, [isPlaying, audioElementRef, externalContext]);
196
+
197
+ // Re-render logic is mostly same, just needs 'analyserRef' to be populated
198
+ useEffect(() => {
199
+ const renderFrame = () => {
200
+ const canvas = canvasRef.current;
201
+ // If parent provided an analyser directly (Mode A variant), use it
202
+ const analyser = externalSource || analyserRef.current;
203
+
204
+ if (!canvas || !analyser) {
205
+ // Simulate if no analyser but playing
206
+ if (isPlaying && canvas) {
207
+ // ... simulation code ...
208
+ }
209
+ return;
210
+ }
211
+
212
+ const ctx = canvas.getContext('2d');
213
+ if (!ctx) return;
214
+
215
+ const bufferLength = analyser.frequencyBinCount;
216
+ const dataArray = new Uint8Array(bufferLength);
217
+ analyser.getByteFrequencyData(dataArray);
218
+
219
+ const width = canvas.width;
220
+ const height = canvas.height;
221
+
222
+ ctx.clearRect(0, 0, width, height);
223
+
224
+ const barWidth = (width / bufferLength) * 2.5;
225
+ let barHeight;
226
+ let x = 0;
227
+
228
+ for (let i = 0; i < bufferLength; i++) {
229
+ barHeight = (dataArray[i] / 255) * height;
230
+
231
+ const gradient = ctx.createLinearGradient(0, height, 0, height - barHeight);
232
+ gradient.addColorStop(0, '#3b82f6');
233
+ gradient.addColorStop(1, '#a855f7');
234
+
235
+ ctx.fillStyle = gradient;
236
+ ctx.beginPath();
237
+ ctx.roundRect(x, height - barHeight, barWidth, barHeight, 4);
238
+ ctx.fill();
239
+
240
+ x += barWidth + 2;
241
+ }
242
+
243
+ animationFrameRef.current = requestAnimationFrame(renderFrame);
244
+ };
245
+
246
+ if (isPlaying) {
247
+ renderFrame();
248
+ } else {
249
+ cancelAnimationFrame(animationFrameRef.current);
250
+ const canvas = canvasRef.current;
251
+ if (canvas) {
252
+ const ctx = canvas.getContext('2d');
253
+ ctx?.clearRect(0, 0, canvas.width, canvas.height);
254
+ }
255
+ }
256
+ return () => cancelAnimationFrame(animationFrameRef.current);
257
+ }, [isPlaying, externalSource]); // Depend on externalSource (analyser)
258
+
259
+ return (
260
+ <div className="w-full h-24 bg-slate-900/50 rounded-lg border border-slate-800 backdrop-blur-sm overflow-hidden flex items-end justify-center px-4 py-2 relative">
261
+ <div className="absolute top-2 left-2 text-[10px] text-slate-500 font-mono tracking-widest uppercase">
262
+ Frequency Visualizer
263
+ </div>
264
+ <canvas
265
+ ref={canvasRef}
266
+ width={600}
267
+ height={100}
268
+ className="w-full h-full"
269
+ />
270
+ </div>
271
+ );
272
+ };
273
+
274
+ // ==========================================
275
+ // MAIN TTS INTERFACE
276
+ // ==========================================
277
+ const API_URL = '';
278
+
279
+ const TtsInterface = () => {
280
+ const [text, setText] = useState(`Sức Mạnh Của Sự Thích Nghi Trong Kỷ Nguyên Số
281
+ Chúng ta đang sống trong một thời đại mà sự thay đổi không còn tính bằng thập kỷ, mà bằng từng ngày, thậm chí từng giờ. Cuộc cách mạng công nghiệp lần thứ tư đã xóa nhòa ranh giới giữa thế giới thực và thế giới ảo, đặt con người trước những cơ hội khổng lồ nhưng cũng không ít thách thức nghiệt ngã. Trong bối cảnh đó, kỹ năng quan trọng nhất để một cá nhân có thể tồn tại và phát triển không phải là kiến thức chuyên môn thuần túy, mà chính là khả năng thích nghi.
282
+
283
+ Thích nghi không có nghĩa là đánh mất bản sắc hay buông xuôi theo dòng chảy của số phận. Ngược lại, đó là một quá trình chủ động học hỏi, điều chỉnh tư duy và hành động để phù hợp với hoàn cảnh mới. Hãy nhìn vào cách chúng ta giao tiếp: từ những lá thư tay mất hàng tuần để chuyển đi, giờ đây chỉ cần một cú chạm nhẹ trên màn hình điện thoại, thông tin đã có thể đi vòng quanh thế giới. Nếu một doanh nghiệp vẫn khăng khăng giữ phương thức quản lý truyền thống, từ chối chuyển đổi số, họ sẽ sớm bị đào thải. Tương tự, nếu một cá nhân ngừng cập nhật kỹ năng công nghệ, họ sẽ tự thấy mình trở nên lạc hậu trong chính môi trường làm việc của mình.
284
+
285
+ Tuy nhiên, sự thích nghi thực sự nằm ở tư duy mở (growth mindset). Thay vì sợ hãi trước những trí tuệ nhân tạo hay robot hóa, người có khả năng thích nghi cao sẽ nhìn thấy ở đó những công cụ để giải phóng sức lao động và kích thích sự sáng tạo. Họ coi những khó khăn, biến động là những bài kiểm tra cho bản lĩnh của mình. Lịch sử nhân loại đã chứng minh rằng, giống loài tồn tại mạnh mẽ nhất không phải là giống loài khỏe nhất hay thông minh nhất, mà là giống loài có khả năng thích ứng tốt nhất với sự thay đổi của môi trường.
286
+
287
+ Bên cạnh đó, trong thế giới số đầy biến động, việc giữ vững những giá trị cốt lõi như đạo đức và sự tử tế cũng là một phần của sự thích nghi thông minh. Công nghệ có thể thay đổi, nhưng nhu cầu về sự kết nối thực sự giữa người với người thì luôn hiện hữu. Chúng ta thích nghi với công cụ mới nhưng không được để mình trở thành nô lệ của chúng. Sự cân bằng giữa trí tuệ nhân tạo và trí tuệ cảm xúc chính là chìa khóa để con người không bị hòa tan trong dòng chảy cơ khí hóa.
288
+
289
+ Tóm lại, thế giới ngày mai thuộc về những người sẵn sàng bước ra khỏi vùng an toàn. Đừng sợ hãi sự thay đổi, hãy chào đón nó như một phần tất yếu của cuộc sống. Khi chúng ta giữ cho mình một tâm thế sẵn sàng học lại từ đầu (re-learn), chúng ta sẽ thấy rằng mọi sự chuyển dịch đều mang trong mình những hạt mầm của sự tiến bộ. Hãy nhớ rằng, cánh cửa của tương lai chỉ mở ra cho những ai biết linh hoạt xoay chuyển theo nhịp đập của thời đại.`);
290
+ const [status, setStatus] = useState(StreamStatus.IDLE);
291
+ const [metrics, setMetrics] = useState({ latencyMs: null, startTime: null });
292
+ const [voices, setVoices] = useState([]);
293
+ const [selectedVoice, setSelectedVoice] = useState("");
294
+
295
+ const [models, setModels] = useState([]);
296
+ const [currentModel, setCurrentModel] = useState(null);
297
+ const [isModelLoading, setIsModelLoading] = useState(false);
298
+
299
+ const [audioBlob, setAudioBlob] = useState(null);
300
+
301
+ const audioRef = useRef(null);
302
+
303
+ // Web Audio API Refs
304
+ const ctxRef = useRef(null);
305
+ const isPlayingRef = useRef(false);
306
+ const globalAnalyserRef = useRef(null);
307
+ const abortControllerRef = useRef(null);
308
+
309
+ // Audio Recording Refs
310
+ const recordedChunksRef = useRef([]);
311
+
312
+ const fetchVoices = async () => {
313
+ try {
314
+ const res = await fetch(`${API_URL}/voices`);
315
+ const data = await res.json();
316
+ setVoices(data);
317
+ if (data.length > 0) {
318
+ // Keep current selection if still available, otherwise first one
319
+ if (!data.find(v => v.id === selectedVoice)) {
320
+ setSelectedVoice(data[0].id);
321
+ }
322
+ }
323
+ } catch (e) {
324
+ console.warn("Failed to load voices", e);
325
+ }
326
+ };
327
+
328
+ // Load data on mount
329
+ useEffect(() => {
330
+ // Models
331
+ fetch(`${API_URL}/models`)
332
+ .then(r => r.json())
333
+ .then(data => {
334
+ setModels(data);
335
+ const active = data.find(m => m.active);
336
+ if (active) setCurrentModel(active.key);
337
+ })
338
+ .catch(e => console.warn("Models API not found"));
339
+
340
+ fetchVoices();
341
+ }, []);
342
+
343
+ const handleModelChange = async (key) => {
344
+ if (key === currentModel) return;
345
+ setIsModelLoading(true);
346
+ try {
347
+ const res = await fetch(`${API_URL}/set_model`, {
348
+ method: "POST",
349
+ headers: { "Content-Type": "application/json" },
350
+ body: JSON.stringify({ model_key: key })
351
+ });
352
+ const data = await res.json();
353
+ if (data.status === "ok") {
354
+ setCurrentModel(key);
355
+ // Refresh voices for new model
356
+ await fetchVoices();
357
+ } else {
358
+ alert("Error switching model: " + data.message);
359
+ }
360
+ } catch (e) {
361
+ alert("Network error switching model");
362
+ } finally {
363
+ setIsModelLoading(false);
364
+ }
365
+ };
366
+
367
+ const handleGenerate = async () => {
368
+ if (!text.trim()) return;
369
+
370
+ handleStop(); // Ensure clean state
371
+
372
+ setStatus(StreamStatus.CONNECTING);
373
+ const sessionStartTime = Date.now();
374
+ setMetrics({ startTime: sessionStartTime, latencyMs: null });
375
+ setAudioBlob(null); // Clear previous recording
376
+ recordedChunksRef.current = []; // Reset recorder buffer
377
+
378
+ isPlayingRef.current = true;
379
+
380
+ // Init AbortController
381
+ abortControllerRef.current = new AbortController();
382
+ const signal = abortControllerRef.current.signal;
383
+
384
+ // 1. Init Web Audio
385
+ const AudioContextClass = window.AudioContext || window.webkitAudioContext;
386
+ const ctx = new AudioContextClass({ sampleRate: 24000 });
387
+ ctxRef.current = ctx;
388
+
389
+ const analyser = ctx.createAnalyser();
390
+ analyser.fftSize = 256;
391
+ globalAnalyserRef.current = analyser;
392
+ analyser.connect(ctx.destination);
393
+
394
+ try {
395
+ const encodedText = encodeURIComponent(text);
396
+ const voiceParam = selectedVoice ? `&voice_id=${selectedVoice}` : "";
397
+
398
+ const response = await fetch(`${API_URL}/stream?text=${encodedText}${voiceParam}`, { signal });
399
+
400
+ if (!response.body) return;
401
+ const reader = response.body.getReader();
402
+
403
+ let nextTime = ctx.currentTime + 0.1;
404
+ let headerSkipped = false;
405
+ let firstChunkPlayed = false;
406
+
407
+ const processStream = async () => {
408
+ try {
409
+ while (isPlayingRef.current) {
410
+ const { done, value } = await reader.read();
411
+ if (done) break;
412
+
413
+ let audioData = value;
414
+
415
+ // Helper to create WAV later: Save raw PCM data
416
+ // Note: We save ALL data including header for simplicity or skip header?
417
+ // If we want clean WAV later, better to collect raw PCM and prepend own header.
418
+ // We will strip header from first chunk for saving too to have clean PCM stream.
419
+
420
+ let pcmData = audioData;
421
+
422
+ if (!headerSkipped) {
423
+ if (audioData.length > 44) {
424
+ audioData = audioData.slice(44);
425
+ pcmData = audioData; // Only save PCM part
426
+ headerSkipped = true;
427
+ } else {
428
+ // Chunk too small (just header?), skip it entirely
429
+ continue;
430
+ }
431
+ }
432
+
433
+ // Save for download
434
+ recordedChunksRef.current.push(pcmData);
435
+
436
+ const int16 = new Int16Array(audioData.buffer, audioData.byteOffset, audioData.byteLength / 2);
437
+ const float32 = new Float32Array(int16.length);
438
+ for (let i = 0; i < int16.length; i++) {
439
+ float32[i] = int16[i] / 32768.0;
440
+ }
441
+
442
+ const buffer = ctx.createBuffer(1, float32.length, 24000);
443
+ buffer.getChannelData(0).set(float32);
444
+
445
+ const source = ctx.createBufferSource();
446
+ source.buffer = buffer;
447
+ source.connect(analyser);
448
+
449
+ if (nextTime < ctx.currentTime) nextTime = ctx.currentTime;
450
+ source.start(nextTime);
451
+
452
+ nextTime += buffer.duration;
453
+
454
+ if (!firstChunkPlayed) {
455
+ const latency = Date.now() - sessionStartTime;
456
+ setMetrics(prev => ({ ...prev, latencyMs: latency }));
457
+ setStatus(StreamStatus.PLAYING);
458
+ firstChunkPlayed = true;
459
+ }
460
+ }
461
+ } catch (err) {
462
+ if (err.name === 'AbortError') {
463
+ console.log('Stream aborted by user');
464
+ } else {
465
+ throw err;
466
+ }
467
+ }
468
+
469
+ if (isPlayingRef.current) {
470
+ // Wait logic
471
+ const remainingTime = nextTime - ctx.currentTime;
472
+ if (remainingTime > 0) {
473
+ await new Promise(r => setTimeout(r, remainingTime * 1000));
474
+ }
475
+
476
+ if (isPlayingRef.current) {
477
+ setStatus(StreamStatus.COMPLETED);
478
+ finalizeRecording(); // Create download link
479
+ setTimeout(() => setStatus(StreamStatus.IDLE), 2000);
480
+ }
481
+ }
482
+ };
483
+
484
+ processStream();
485
+
486
+ } catch (e) {
487
+ if (e.name !== 'AbortError') {
488
+ console.error("Stream Error", e);
489
+ setStatus(StreamStatus.ERROR);
490
+ }
491
+ }
492
+ };
493
+
494
+ const handleStop = () => {
495
+ isPlayingRef.current = false;
496
+
497
+ // 1. Abort Fetch
498
+ if (abortControllerRef.current) {
499
+ abortControllerRef.current.abort();
500
+ abortControllerRef.current = null;
501
+ }
502
+
503
+ // 2. Close Audio Context
504
+ if (ctxRef.current) {
505
+ ctxRef.current.close();
506
+ ctxRef.current = null;
507
+ }
508
+ globalAnalyserRef.current = null;
509
+ setStatus(StreamStatus.IDLE);
510
+ };
511
+
512
+ const finalizeRecording = () => {
513
+ if (recordedChunksRef.current.length === 0) return;
514
+
515
+ // 1. Calculate total length
516
+ let totalLength = 0;
517
+ for (const chunk of recordedChunksRef.current) {
518
+ totalLength += chunk.length;
519
+ }
520
+
521
+ // 2. Create WAV Header
522
+ const buffer = new ArrayBuffer(44 + totalLength);
523
+ const view = new DataView(buffer);
524
+
525
+ // RIFF chunk descriptor
526
+ writeString(view, 0, 'RIFF');
527
+ view.setUint32(4, 36 + totalLength, true);
528
+ writeString(view, 8, 'WAVE');
529
+ // fmt sub-chunk
530
+ writeString(view, 12, 'fmt ');
531
+ view.setUint32(16, 16, true);
532
+ view.setUint16(20, 1, true); // PCM
533
+ view.setUint16(22, 1, true); // Mono
534
+ view.setUint32(24, 24000, true); // 24kHz
535
+ view.setUint32(28, 24000 * 2, true); // ByteRate
536
+ view.setUint16(32, 2, true); // BlockAlign
537
+ view.setUint16(34, 16, true); // BitsPerSample
538
+ // data sub-chunk
539
+ writeString(view, 36, 'data');
540
+ view.setUint32(40, totalLength, true);
541
+
542
+ // 3. Write PCM data
543
+ let offset = 44;
544
+ const bytes = new Uint8Array(buffer);
545
+ for (const chunk of recordedChunksRef.current) {
546
+ bytes.set(chunk, offset);
547
+ offset += chunk.length;
548
+ }
549
+
550
+ const blob = new Blob([buffer], { type: 'audio/wav' });
551
+ setAudioBlob(blob);
552
+ };
553
+
554
+ const writeString = (view, offset, string) => {
555
+ for (let i = 0; i < string.length; i++) {
556
+ view.setUint8(offset + i, string.charCodeAt(i));
557
+ }
558
+ };
559
+
560
+ const handleDownload = () => {
561
+ if (!audioBlob) return;
562
+ const url = URL.createObjectURL(audioBlob);
563
+ const a = document.createElement('a');
564
+ a.href = url;
565
+ a.download = `vienau_tts_${Date.now()}.wav`;
566
+ document.body.appendChild(a);
567
+ a.click();
568
+ document.body.removeChild(a);
569
+ URL.revokeObjectURL(url);
570
+ };
571
+
572
+ // Remove unused audio element handlers
573
+ const onPlay = () => { };
574
+ const onEnded = () => { };
575
+ const onError = () => { };
576
+
577
+ return (
578
+ <div className="w-full">
579
+ {/* Header Section */}
580
+ <div className="text-center mb-8 space-y-2">
581
+ <h1 className="text-4xl font-bold tracking-tight text-white">
582
+ <span className="text-transparent bg-clip-text bg-gradient-to-r from-blue-400 to-violet-400">🦜 VieNeu</span> Stream
583
+ </h1>
584
+ <p className="text-slate-400 max-w-sm mx-auto text-sm font-medium">
585
+ High-fidelity neural text-to-speech with ultra-low latency streaming capability.
586
+ </p>
587
+ </div>
588
+
589
+ <div className="bg-slate-800/50 backdrop-blur-xl rounded-3xl p-6 shadow-2xl shadow-black/50 border border-slate-700/50 relative overflow-hidden">
590
+
591
+ {isModelLoading && (
592
+ <div className="absolute inset-0 bg-slate-900/80 z-50 flex flex-col items-center justify-center space-y-3 backdrop-blur-sm">
593
+ <svg className="animate-spin h-10 w-10 text-blue-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
594
+ <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
595
+ <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
596
+ </svg>
597
+ <span className="text-blue-400 font-semibold animate-pulse">Switching Model...</span>
598
+ </div>
599
+ )}
600
+
601
+ <div className="flex gap-4 mb-4 items-end">
602
+ {/* Model Selection */}
603
+ <div className="flex-[2] space-y-2">
604
+ <label className="block text-slate-400 text-xs font-semibold uppercase tracking-wider ml-1">
605
+ Model
606
+ <span className="text-[10px] text-yellow-500/80 normal-case ml-2 border border-yellow-500/30 px-1.5 py-0.5 rounded bg-yellow-900/10">
607
+ ⚡ Demo này tối ưu hóa tốc độ streaming trên CPU - Không sử dụng GPU
608
+ </span>
609
+ </label>
610
+ <div className="flex gap-2">
611
+ <select
612
+ className="flex-1 bg-slate-900/50 border border-slate-700 text-slate-200 text-sm rounded-xl focus:ring-blue-500 focus:border-blue-500 block p-3 appearance-none truncate"
613
+ value={currentModel || "q4"}
614
+ onChange={(e) => handleModelChange(e.target.value)}
615
+ disabled={status !== StreamStatus.IDLE && status !== StreamStatus.COMPLETED}
616
+ >
617
+ {models.map(m => (
618
+ <option key={m.key} value={m.key}>{m.name}</option>
619
+ ))}
620
+ </select>
621
+ </div>
622
+ </div>
623
+
624
+ {/* Voice Selection */}
625
+ <div className="flex-1 space-y-2">
626
+ <label className="block text-slate-400 text-xs font-semibold uppercase tracking-wider ml-1">Voice</label>
627
+ <select
628
+ className={`w-full text-sm rounded-xl border p-3 appearance-none ${voices.length > 0 && voices[0].id.startsWith('error')
629
+ ? 'bg-red-900/20 border-red-500/50 text-red-300'
630
+ : 'bg-slate-900/50 border-slate-700 text-slate-200 focus:ring-blue-500'
631
+ }`}
632
+ value={selectedVoice}
633
+ onChange={(e) => setSelectedVoice(e.target.value)}
634
+ disabled={
635
+ (status !== StreamStatus.IDLE && status !== StreamStatus.COMPLETED) ||
636
+ (voices.length > 0 && voices[0].id.startsWith('error'))
637
+ }
638
+ >
639
+ {voices.length === 0 && <option>Loading voices...</option>}
640
+ {voices.map(v => (
641
+ <option key={v.id} value={v.id}>{v.name}</option>
642
+ ))}
643
+ </select>
644
+ </div>
645
+ </div>
646
+
647
+ {/* Input Area */}
648
+ <div className="relative group mb-6">
649
+ <div className="absolute -inset-1 bg-gradient-to-r from-blue-600 to-violet-600 rounded-2xl blur opacity-20 group-hover:opacity-40 transition duration-500"></div>
650
+ <textarea
651
+ value={text}
652
+ onChange={(e) => setText(e.target.value)}
653
+ placeholder="Enter text to synthesize..."
654
+ className="relative w-full min-h-[300px] h-[500px] bg-slate-900/90 text-slate-100 p-8 rounded-xl border border-slate-700 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 outline-none resize-y transition-all placeholder:text-slate-600 font-medium leading-relaxed text-lg shadow-inner"
655
+ spellCheck="false"
656
+ />
657
+ </div>
658
+
659
+ {/* Controls & Status - Flex Row */}
660
+ <div className="flex items-center justify-between gap-4 mb-6">
661
+ <div className="flex items-center gap-3">
662
+ {status === StreamStatus.CONNECTING || status === StreamStatus.PLAYING ? (
663
+ <button
664
+ onClick={handleStop}
665
+ className="group relative inline-flex items-center justify-center px-6 py-3 font-semibold text-white transition-all duration-200 bg-red-500/10 border border-red-500/50 rounded-xl hover:bg-red-500 hover:border-red-500 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 focus:ring-offset-slate-900"
666
+ >
667
+ <span className="mr-2">⏹</span> Stop Stream
668
+ </button>
669
+ ) : (
670
+ <button
671
+ onClick={handleGenerate}
672
+ disabled={status !== StreamStatus.IDLE && status !== StreamStatus.COMPLETED}
673
+ className="group relative inline-flex items-center justify-center px-6 py-3 font-bold text-white transition-all duration-200 bg-blue-600 border border-transparent rounded-xl hover:bg-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-slate-900 disabled:opacity-50 disabled:cursor-not-allowed shadow-lg shadow-blue-900/20"
674
+ >
675
+ <span className="absolute inset-0 w-full h-full -mt-1 rounded-lg opacity-30 bg-gradient-to-b from-transparent via-transparent to-black"></span>
676
+ <span className="relative flex items-center">
677
+ {status === StreamStatus.CONNECTING ? (
678
+ <svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
679
+ <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
680
+ <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
681
+ </svg>
682
+ ) : (
683
+ <span className="mr-2">🦜</span>
684
+ )}
685
+ {status === StreamStatus.CONNECTING ? 'Connecting...' : 'Generate Stream'}
686
+ </span>
687
+ </button>
688
+ )}
689
+
690
+ {audioBlob && status !== StreamStatus.PLAYING && status !== StreamStatus.CONNECTING && (
691
+ <button
692
+ onClick={handleDownload}
693
+ className="inline-flex items-center justify-center px-4 py-3 font-semibold text-slate-300 transition-all duration-200 bg-slate-700/50 border border-slate-600 rounded-xl hover:bg-slate-700 hover:text-white"
694
+ title="Download Wav"
695
+ >
696
+ ⬇️
697
+ </button>
698
+ )}
699
+ </div>
700
+
701
+ {/* Metrics Badge */}
702
+ <div className="flex flex-col items-end">
703
+ <div className={`flex items-center space-x-2 px-3 py-1.5 rounded-lg border ${status === StreamStatus.ERROR ? 'bg-red-500/10 border-red-500/20 text-red-400' :
704
+ status === StreamStatus.PLAYING ? 'bg-emerald-500/10 border-emerald-500/20 text-emerald-400' :
705
+ 'bg-slate-800 border-slate-700 text-slate-400'
706
+ }`}>
707
+ <div className={`w-2 h-2 rounded-full ${status === StreamStatus.PLAYING ? 'bg-emerald-400 animate-pulse' :
708
+ status === StreamStatus.ERROR ? 'bg-red-400' : 'bg-slate-500'
709
+ }`}></div>
710
+ <span className="text-xs font-mono font-medium">
711
+ {status === StreamStatus.IDLE ? 'READY' :
712
+ status === StreamStatus.CONNECTING ? 'BUFFERING' :
713
+ status === StreamStatus.PLAYING ? 'STREAMING' :
714
+ status === StreamStatus.COMPLETED ? 'COMPLETED' : 'ERROR'}
715
+ </span>
716
+ </div>
717
+ {metrics.latencyMs && (
718
+ <span className="text-[10px] font-mono text-slate-500 mt-1">
719
+ Head Latency: <span className="text-blue-400">{metrics.latencyMs}ms</span>
720
+ </span>
721
+ )}
722
+ </div>
723
+ </div>
724
+ {/* Hidden Audio Element */}
725
+ <audio
726
+ ref={audioRef}
727
+ onPlay={onPlay}
728
+ onEnded={onEnded}
729
+ onError={onError}
730
+ className="hidden"
731
+ />
732
+ </div>
733
+ </div>
734
+ );
735
+ };
736
+
737
+ // ==========================================
738
+ // APP ENTRY
739
+ // ==========================================
740
+ const App = () => {
741
+ return (
742
+ <div className="min-h-screen w-full bg-[#020617] relative overflow-hidden flex items-center justify-center p-4">
743
+ {/* Ambient Background Effects */}
744
+ <div className="absolute top-[-10%] left-[-10%] w-[40%] h-[40%] bg-primary-500/10 rounded-full blur-[120px] pointer-events-none" />
745
+ <div className="absolute bottom-[-10%] right-[-10%] w-[40%] h-[40%] bg-violet-500/10 rounded-full blur-[120px] pointer-events-none" />
746
+
747
+ <div className="relative z-10 w-full max-w-4xl">
748
+ <TtsInterface />
749
+ </div>
750
+
751
+ <footer className="absolute bottom-4 text-slate-500 text-xs text-center w-full">
752
+ Powered by VieNeu SDK & React
753
+ </footer>
754
+ </div>
755
+ );
756
+ };
757
+
758
+ // Mount to Root
759
+ const rootElement = document.getElementById('root');
760
+ if (rootElement) {
761
+ const root = ReactDOM.createRoot(rootElement);
762
+ root.render(<App />);
763
+ }
764
+ </script>
765
+ </body>
766
+
767
+ </html>
docs/sdk/README.md DELETED
@@ -1,24 +0,0 @@
1
- # VieNeu-TTS SDK Examples
2
-
3
- Bộ sưu tập các ví dụ hướng dẫn tích hợp VieNeu-TTS vào ứng dụng của bạn.
4
-
5
- ## Danh sách ví dụ
6
-
7
- 1. **[Standard Mode](standard_mode.py)**: Chạy TTS trực tiếp trên máy (Local). Hỗ trợ GGUF (CPU) và PyTorch (GPU).
8
- 2. **[Remote Mode](remote_mode.py)**: Kết nối tới server LMDeploy. Phù hợp cho ứng dụng Web/SaaS để đạt tốc độ tối đa và không cần phần cứng tại client.
9
- 3. **[Voice Cloning](voice_cloning.py)**: Hướng dẫn Clone giọng nói bất kỳ từ một file âm thanh mẫu ngắn (Zero-shot).
10
-
11
- ## Cách chạy
12
-
13
- Cài đặt SDK và các phụ kiện:
14
-
15
- uv pip install -e .
16
- # Hoặc
17
- pip install -e .
18
- ```
19
-
20
-
21
- ## Yêu cầu
22
-
23
- * Python 3.10+
24
- * Server LMDeploy (cho ví dụ remote mode)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
docs/sdk/remote_mode.py DELETED
@@ -1,90 +0,0 @@
1
- """
2
- Demo VieNeuSDK v1.1.3 - Full Features Guide
3
- """
4
-
5
- import time
6
- import soundfile as sf
7
- from vieneu import Vieneu
8
- from pathlib import Path
9
-
10
- def main():
11
- print("🚀 Initializing VieNeu SDK (v1.1.3)...")
12
-
13
- # Initialize SDK
14
- # Default: "pnnbao-ump/VieNeu-TTS-0.3B-q4-gguf" (Speed & CPU Optimized)
15
- #
16
- # You can change 'backbone_repo' to balance Quality vs Speed:
17
- # 1. Better Quality (slower than q4): "pnnbao-ump/VieNeu-TTS-0.3B-q8-gguf"
18
- # 2. PyTorch 0.3B (Fast, uncompressed): "pnnbao-ump/VieNeu-TTS-0.3B"
19
- # 3. PyTorch 0.5B (Best Quality, heavy): "pnnbao-ump/VieNeu-TTS"
20
- # You can also use a GGUF version merged with your own LoRA adapter.
21
- # See finetuning guide: https://github.com/pnnbao97/VieNeu-TTS/tree/main/finetune
22
-
23
- # Mode selection:
24
- # - mode="standard" (Default): Runs locally using GGUF (CPU) or PyTorch
25
- # - mode="remote": Connects to the LMDeploy server setup above for max speed
26
-
27
- # API Configuration for Remote Mode
28
- # Replace with your own server URL (e.g. http://localhost:23333/v1)
29
- LMDEPLOY_API_URL = 'http://bore.pub:31631/v1'
30
-
31
- # Initialize: Choose 'standard' (local) or 'remote' (API)
32
- # tts = Vieneu(mode='standard')
33
- # Note: 'model_name' must match the model ID serving on LMDeploy
34
- tts = Vieneu(mode='remote', api_base=LMDEPLOY_API_URL, model_name="pnnbao-ump/VieNeu-TTS")
35
-
36
- # ---------------------------------------------------------
37
- # PART 1: PRESET VOICES
38
- # ---------------------------------------------------------
39
- available_voices = tts.list_preset_voices()
40
-
41
- # Display available voices
42
- if available_voices:
43
- print(f"📋 Found {len(available_voices)} available voices. First 3:")
44
- for desc, name in available_voices[:3]:
45
- print(f" - {desc} (ID: {name})")
46
-
47
- # 1. Use the default voice
48
- print("\n--- 2. Default Voice ---")
49
- default_voice_data = tts.get_preset_voice() # No arg = Default
50
- print(f"✅ Default voice text: {default_voice_data['text'][:50]}...")
51
-
52
- # ---------------------------------------------------------
53
- # PART 2: CUSTOM VOICES GUIDE
54
- # ---------------------------------------------------------
55
- print("\n--- 3. Custom Voice Guide ---")
56
- print("ℹ️ To use a custom voice:")
57
- print("1. Create voice preset: `uv run python finetune/create_voices_json.py ...`")
58
- print("2. Or use ad-hoc reference in code.")
59
-
60
- # ---------------------------------------------------------
61
- # PART 3: SYNTHESIS
62
- # ---------------------------------------------------------
63
- print("\n--- 3. Speech Synthesis ---")
64
-
65
- text_input = "Xin chào, tôi là VieNeu. Tôi có thể giúp bạn đọc sách, làm chatbot thời gian thực, hoặc thậm chí clone giọng nói của bạn."
66
-
67
- # Example: Select the first voice ID
68
- _, selected_voice_id = available_voices[0] if available_voices else (None, None)
69
- # voice_data = tts.get_preset_voice(selected_voice_id)
70
-
71
- print("🎧 Generating...")
72
- print(f" Using default voice mechanism...")
73
- audio = tts.infer(
74
- text=text_input,
75
- voice=None, # SDK will use default automatically.
76
- # To use specific voice: voice=tts.get_preset_voice("VoiceName")
77
- temperature=1.0,
78
- top_k=50
79
- )
80
- tts.save(audio, "output.wav")
81
- print("💾 Saved: output.wav")
82
-
83
- # ---------------------------------------------------------
84
- # CLEANUP
85
- # ---------------------------------------------------------
86
- tts.close()
87
- print("\n✅ Done!")
88
-
89
- if __name__ == "__main__":
90
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
docs/sdk/standard_mode.py DELETED
@@ -1,83 +0,0 @@
1
- """
2
- VieNeu-TTS SDK Example: Standard Mode (Local Inference)
3
-
4
- This example demonstrates how to run VieNeu-TTS locally on your machine.
5
- Ideal for offline apps, local development, or private deployments.
6
- """
7
-
8
- from vieneu import Vieneu
9
-
10
- def main():
11
- print("🚀 Initializing local VieNeu engine...")
12
-
13
- # Ensure output directory exists
14
- import os
15
- os.makedirs("outputs", exist_ok=True)
16
-
17
- # ---------------------------------------------------------
18
- # PART 1: INITIALIZATION
19
- # ---------------------------------------------------------
20
- # Mode="standard" runs locally.
21
- # By default, it uses "pnnbao-ump/VieNeu-TTS-0.3B-q4-gguf" (Backbone)
22
- # and "neuphonic/distill-neucodec" (Codec) for maximum speed.
23
- tts = Vieneu()
24
-
25
- # Optional: If you want to force use a specific PyTorch model:
26
- # tts = Vieneu(backbone_repo="pnnbao-ump/VieNeu-TTS-0.3B", codec_repo="neuphonic/distill-neucodec", backbone_device="cuda")
27
-
28
- # ---------------------------------------------------------
29
- # PART 2: LIST PRESET VOICES
30
- # ---------------------------------------------------------
31
- # The SDK returns (Description, ID) tuples
32
- available_voices = tts.list_preset_voices()
33
- print(f"📋 Found {len(available_voices)} preset voices.")
34
-
35
- if available_voices:
36
- print(" Showing all voices:")
37
- for desc, name in available_voices:
38
- print(f" - {desc} (ID: {name})")
39
-
40
- # ---------------------------------------------------------
41
- # PART 3: SPEECH SYNTHESIS
42
- # ---------------------------------------------------------
43
- text = "Xin chào, tôi là VieNeu. Tôi có thể giúp bạn đọc sách, làm chatbot thời gian thực, hoặc thậm chí clone giọng nói của bạn."
44
-
45
- print(f"\n🎧 Synthesizing speech...")
46
- # By default, it uses the model's 'default_voice'
47
- audio = tts.infer(text=text)
48
- tts.save(audio, "outputs/standard_output.wav")
49
- print(f"💾 Saved synthesized speech to: outputs/standard_output.wav")
50
-
51
- # To use a specific voice from the list:
52
- # _, my_voice_id = available_voices[0]
53
- # voice_data = tts.get_preset_voice(my_voice_id)
54
- # audio = tts.infer(text=text, voice=voice_data)
55
-
56
- # ---------------------------------------------------------
57
- # PART 4: ZERO-SHOT VOICE CLONING
58
- # ---------------------------------------------------------
59
- # You can clone any voice using a short audio sample (5-10s) and its transcript
60
- ref_audio = "examples/audio_ref/example_ngoc_huyen.wav"
61
- ref_text = "Tác phẩm dự thi bảo đảm tính khoa học, tính đảng, tính chiến đấu, tính định hướng."
62
-
63
- import os
64
- if os.path.exists(ref_audio):
65
- print("\n--- PART 4: Voice Cloning ---")
66
- print(f"🦜 Cloning voice from: {ref_audio}")
67
- cloned_audio = tts.infer(
68
- text="Đây là giọng nói đã được clone thành công từ file mẫu.",
69
- ref_audio=ref_audio,
70
- ref_text=ref_text
71
- )
72
- tts.save(cloned_audio, "outputs/cloned_output.wav")
73
- print("💾 Saved cloned voice to: outputs/cloned_output.wav")
74
-
75
- # ---------------------------------------------------------
76
- # PART 5: CLEANUP
77
- # ---------------------------------------------------------
78
- # Cleanup (Optional for standard mode, but good practice)
79
- tts.close()
80
- print("\n✅ All tasks completed!")
81
-
82
- if __name__ == "__main__":
83
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
main_remote.py CHANGED
@@ -17,7 +17,7 @@ def main():
17
 
18
  # Replace with your actual LMDeploy server URL
19
  # Example: 'http://localhost:23333/v1' or a public tunnel URL
20
- REMOTE_API_BASE = 'http://bore.pub:31631/v1' # Replace with your actual LMDeploy server URL
21
  REMOTE_MODEL_ID = "pnnbao-ump/VieNeu-TTS"
22
 
23
  # ---------------------------------------------------------
@@ -53,18 +53,21 @@ def main():
53
  # ---------------------------------------------------------
54
  if available_voices:
55
  print("\n--- PART 3: Using Specific Voice ID ---")
56
- # Select a voice by its ID (the second element in the tuple)
57
- _, my_voice_id = available_voices[1] if len(available_voices) > 1 else available_voices[0]
58
- print(f"👤 Selecting voice: {my_voice_id}")
 
 
59
 
60
  # Get reference data for this specific voice
61
- voice_data = tts.get_preset_voice(my_voice_id)
62
 
63
- test_text = f"Chào bạn, tôi đang nói bằng giọng của bác sĩ Tuyên."
64
  audio_spec = tts.infer(text=test_text, voice=voice_data)
65
 
66
- tts.save(audio_spec, f"outputs/remote_{my_voice_id}.wav")
67
- print(f"💾 Saved {my_voice_id} synthesis to: outputs/remote_{my_voice_id}.wav")
 
68
 
69
  # ---------------------------------------------------------
70
  # PART 4: REMOTE SPEECH SYNTHESIS (DEFAULT)
@@ -99,9 +102,59 @@ def main():
99
  print("💾 Saved remote cloned voice to: outputs/remote_cloned_output.wav")
100
 
101
  # ---------------------------------------------------------
102
- # PART 6: DONE
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  # ---------------------------------------------------------
104
- print("\n✅ Remote tasks completed!")
 
105
 
106
  if __name__ == "__main__":
107
  main()
 
17
 
18
  # Replace with your actual LMDeploy server URL
19
  # Example: 'http://localhost:23333/v1' or a public tunnel URL
20
+ REMOTE_API_BASE = 'http://bore.pub:34939/v1' # Replace with your actual LMDeploy server URL
21
  REMOTE_MODEL_ID = "pnnbao-ump/VieNeu-TTS"
22
 
23
  # ---------------------------------------------------------
 
53
  # ---------------------------------------------------------
54
  if available_voices:
55
  print("\n--- PART 3: Using Specific Voice ID ---")
56
+ # Select a demonstration voice (Index 1 preferred for variety)
57
+ voice_info = available_voices[1] if len(available_voices) > 1 else available_voices[0]
58
+ desc, voice_id = voice_info
59
+
60
+ print(f"👤 Synthesis voice: {desc} (ID: {voice_id})")
61
 
62
  # Get reference data for this specific voice
63
+ voice_data = tts.get_preset_voice(voice_id)
64
 
65
+ test_text = f"Chào bạn, tôi đang nói bằng giọng của {desc}."
66
  audio_spec = tts.infer(text=test_text, voice=voice_data)
67
 
68
+ save_path = f"outputs/remote_{voice_id}.wav"
69
+ tts.save(audio_spec, save_path)
70
+ print(f"💾 Saved synthesis to: {save_path}")
71
 
72
  # ---------------------------------------------------------
73
  # PART 4: REMOTE SPEECH SYNTHESIS (DEFAULT)
 
102
  print("💾 Saved remote cloned voice to: outputs/remote_cloned_output.wav")
103
 
104
  # ---------------------------------------------------------
105
+ # PART 6: NATIVE ASYNC INFERENCE (High Performance)
106
+ # ---------------------------------------------------------
107
+ print("\n📌 PART 6: Native Async Processing")
108
+ print("=" * 60)
109
+
110
+ # Define voice for async tasks (Using index 0 as default)
111
+ if available_voices:
112
+ _, batch_voice_id = available_voices[0]
113
+ voice_data_batch = tts.get_preset_voice(batch_voice_id)
114
+ else:
115
+ voice_data_batch = None
116
+
117
+ try:
118
+ import asyncio
119
+ import time
120
+
121
+ async def run_async_examples():
122
+ print("🚀 Testing Native Async API...")
123
+ async_batch_texts = [
124
+ "Sài Gòn trong mắt tôi là những buổi sáng sớm tinh mơ, khi nắng vừa lên và thành phố bắt đầu nhộn nhịp tiếng còi xe, tiếng rao hàng rong âm vang khắp các con hẻm nhỏ.",
125
+ "Nhắc đến Sài Gòn, người ta không thể quên được hương vị cà phê sữa đá lề đường hay bát hủ tiếu gõ thơm phức, những nét ẩm thực đã trở thành linh hồn của mảnh đất này.",
126
+ "Dù là một đô thị sầm uất với những tòa cao ốc chọc trời, Sài Gòn vẫn giữ cho mình những góc phố rêu phong, những mái chùa cổ kính thầm lặng chứng kiến dòng thời gian trôi.",
127
+ "Người Sài Gòn nổi tiếng bao dung và hiếu khách, sẵn sàng dang tay đón nhận những người con từ khắp mọi miền tổ quốc về đây để cùng nhau xây dựng ước mơ và tương lai."
128
+ ]
129
+
130
+ start_async = time.time()
131
+ # infer_batch_async maintains order and manages concurrency internally
132
+ batch_results = await tts.infer_batch_async(
133
+ async_batch_texts,
134
+ voice=voice_data_batch,
135
+ concurrency_limit=10
136
+ )
137
+
138
+ elapsed_async = time.time() - start_async
139
+ print(f"✅ Async Batch completed in {elapsed_async:.2f}s")
140
+
141
+ for i, wav in enumerate(batch_results):
142
+ tts.save(wav, f"outputs/remote_native_batch_async_{i}.wav")
143
+ print(f"💾 Saved {len(batch_results)} async batch files.")
144
+
145
+ # Run the async loop
146
+ asyncio.run(run_async_examples())
147
+
148
+ except ImportError:
149
+ print("⚠️ aiohttp not installed. Please run: pip install aiohttp")
150
+ except Exception as e:
151
+ print(f"⚠️ Async example error: {e}")
152
+
153
+ # ---------------------------------------------------------
154
+ # PART 7: DONE
155
  # ---------------------------------------------------------
156
+ print("\n✅ All remote tasks completed!")
157
+ print("📁 Check the 'outputs/' folder for generated files.")
158
 
159
  if __name__ == "__main__":
160
  main()
vieneu/core.py CHANGED
@@ -11,14 +11,16 @@ import re
11
  import gc
12
  import json
13
  import requests
 
14
  from huggingface_hub import hf_hub_download
 
15
 
16
  # ============================================================================
17
  # Shared Utilities
18
  # ============================================================================
19
 
20
  def _linear_overlap_add(frames: list[np.ndarray], stride: int) -> np.ndarray:
21
- """Linear overlap-add for smooth audio concatenation"""
22
  assert len(frames)
23
  dtype = frames[0].dtype
24
  shape = frames[0].shape[:-1]
@@ -108,8 +110,8 @@ class VieNeuTTS:
108
  self.hop_length = 480
109
  self.streaming_overlap_frames = 1
110
  self.streaming_frames_per_chunk = 25
111
- self.streaming_lookforward = 5
112
- self.streaming_lookback = 50
113
  self.streaming_stride_samples = self.streaming_frames_per_chunk * self.hop_length
114
 
115
  # Flags
@@ -719,6 +721,10 @@ class VieNeuTTS:
719
  )
720
  curr_codes = token_cache[tokens_start:tokens_end]
721
  recon = self._decode("".join(curr_codes))
 
 
 
 
722
  recon = recon[sample_start:sample_end]
723
  audio_cache.append(recon)
724
 
@@ -750,6 +756,10 @@ class VieNeuTTS:
750
  ) * self.hop_length
751
  curr_codes = token_cache[tokens_start:]
752
  recon = self._decode("".join(curr_codes))
 
 
 
 
753
  recon = recon[sample_start:]
754
  audio_cache.append(recon)
755
 
@@ -1447,14 +1457,17 @@ class RemoteVieNeuTTS(VieNeuTTS):
1447
  hf_token=hf_token
1448
  )
1449
 
1450
- # Auto-load voices from the remote model repo
1451
- # This allows client to use 'voice=...' with server's custom voices
 
 
 
1452
  self._load_voices_from_repo(model_name, hf_token)
1453
 
1454
  print(f"📡 RemoteVieNeuTTS ready! Using backend: {self.api_base}")
1455
 
1456
  def _load_backbone(self, backbone_repo, backbone_device):
1457
- pass # Explicitly skip
1458
 
1459
  def _format_prompt(self, ref_codes: list[int], ref_text: str, input_text: str) -> str:
1460
  """Format prompt for remote LMDeploy server"""
@@ -1557,6 +1570,260 @@ class RemoteVieNeuTTS(VieNeuTTS):
1557
 
1558
  return final_wav
1559
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1560
 
1561
  def Vieneu(mode="standard", **kwargs):
1562
  """
 
11
  import gc
12
  import json
13
  import requests
14
+ import asyncio
15
  from huggingface_hub import hf_hub_download
16
+ from concurrent.futures import ThreadPoolExecutor
17
 
18
  # ============================================================================
19
  # Shared Utilities
20
  # ============================================================================
21
 
22
  def _linear_overlap_add(frames: list[np.ndarray], stride: int) -> np.ndarray:
23
+ # original impl --> https://github.com/facebookresearch/encodec/blob/main/encodec/utils.py
24
  assert len(frames)
25
  dtype = frames[0].dtype
26
  shape = frames[0].shape[:-1]
 
110
  self.hop_length = 480
111
  self.streaming_overlap_frames = 1
112
  self.streaming_frames_per_chunk = 25
113
+ self.streaming_lookforward = 10
114
+ self.streaming_lookback = 100
115
  self.streaming_stride_samples = self.streaming_frames_per_chunk * self.hop_length
116
 
117
  # Flags
 
721
  )
722
  curr_codes = token_cache[tokens_start:tokens_end]
723
  recon = self._decode("".join(curr_codes))
724
+ # Apply watermark if available
725
+ if self.watermarker:
726
+ recon = self.watermarker.apply_watermark(recon, sample_rate=self.sample_rate)
727
+
728
  recon = recon[sample_start:sample_end]
729
  audio_cache.append(recon)
730
 
 
756
  ) * self.hop_length
757
  curr_codes = token_cache[tokens_start:]
758
  recon = self._decode("".join(curr_codes))
759
+ # Apply watermark if available
760
+ if self.watermarker:
761
+ recon = self.watermarker.apply_watermark(recon, sample_rate=self.sample_rate)
762
+
763
  recon = recon[sample_start:]
764
  audio_cache.append(recon)
765
 
 
1457
  hf_token=hf_token
1458
  )
1459
 
1460
+ self.streaming_frames_per_chunk = 10
1461
+ self.streaming_lookforward = 5
1462
+ self.streaming_lookback = 50
1463
+ self.streaming_stride_samples = self.streaming_frames_per_chunk * self.hop_length
1464
+
1465
  self._load_voices_from_repo(model_name, hf_token)
1466
 
1467
  print(f"📡 RemoteVieNeuTTS ready! Using backend: {self.api_base}")
1468
 
1469
  def _load_backbone(self, backbone_repo, backbone_device):
1470
+ pass
1471
 
1472
  def _format_prompt(self, ref_codes: list[int], ref_text: str, input_text: str) -> str:
1473
  """Format prompt for remote LMDeploy server"""
 
1570
 
1571
  return final_wav
1572
 
1573
+ def infer_stream(self, text: str, ref_audio: str | Path = None, ref_codes: np.ndarray | torch.Tensor = None, ref_text: str = None, max_chars: int = 256, voice: dict = None, temperature: float = 1.0, top_k: int = 50) -> Generator[np.ndarray, None, None]:
1574
+ """
1575
+ Stream output audio (generator).
1576
+ """
1577
+ if voice is not None:
1578
+ ref_codes = voice.get('codes', ref_codes)
1579
+ ref_text = voice.get('text', ref_text)
1580
+
1581
+ # Auto-encode ref_audio locally if provided
1582
+ if ref_audio is not None and ref_codes is None:
1583
+ ref_codes = self.encode_reference(ref_audio)
1584
+ elif self._default_voice and (ref_codes is None or ref_text is None):
1585
+ try:
1586
+ voice_data = self.get_preset_voice(None)
1587
+ ref_codes = voice_data['codes']
1588
+ ref_text = voice_data['text']
1589
+ except Exception:
1590
+ pass
1591
+
1592
+ if ref_codes is None or ref_text is None:
1593
+ raise ValueError("Must provide either 'voice' dict or both 'ref_codes' and 'ref_text'.")
1594
+
1595
+ chunks = split_text_into_chunks(text, max_chars=max_chars)
1596
+ for chunk in chunks:
1597
+ yield from self._infer_stream_chunk(chunk, ref_codes, ref_text, temperature, top_k)
1598
+
1599
+ def _infer_stream_chunk(self, chunk, ref_codes, ref_text, temperature, top_k):
1600
+ """Internal helper to stream a single text chunk"""
1601
+ if isinstance(ref_codes, torch.Tensor):
1602
+ ref_codes_list = ref_codes.cpu().numpy().flatten().tolist()
1603
+ elif isinstance(ref_codes, np.ndarray):
1604
+ ref_codes_list = ref_codes.flatten().tolist()
1605
+ else:
1606
+ ref_codes_list = ref_codes
1607
+
1608
+ prompt = self._format_prompt(ref_codes_list, ref_text, chunk)
1609
+
1610
+ payload = {
1611
+ "model": self.model_name,
1612
+ "messages": [{"role": "user", "content": prompt}],
1613
+ "max_tokens": 2048,
1614
+ "temperature": temperature,
1615
+ "top_k": top_k,
1616
+ "stop": ["<|SPEECH_GENERATION_END|>"],
1617
+ "stream": True # Enable streaming
1618
+ }
1619
+
1620
+ # Streaming window state
1621
+ audio_cache: list[np.ndarray] = []
1622
+ token_cache: list[str] = [f"<|speech_{idx}|>" for idx in ref_codes_list]
1623
+ n_decoded_samples: int = 0
1624
+ n_decoded_tokens: int = len(ref_codes_list)
1625
+
1626
+ try:
1627
+ with requests.post(f"{self.api_base}/chat/completions", json=payload, stream=True, timeout=60) as r:
1628
+ r.raise_for_status()
1629
+ # Iterate over SSE lines
1630
+ for line in r.iter_lines():
1631
+ if not line:
1632
+ continue
1633
+
1634
+ line_str = line.decode('utf-8')
1635
+ if not line_str.startswith('data: '):
1636
+ continue
1637
+
1638
+ data_str = line_str[6:] # Strip 'data: '
1639
+ if data_str == '[DONE]':
1640
+ break
1641
+
1642
+ try:
1643
+ content = json.loads(data_str)["choices"][0]["delta"].get("content", "")
1644
+ if content:
1645
+ token_cache.append(content)
1646
+
1647
+ # --- Windowed Decoding Logic (Shared) ---
1648
+ if len(token_cache[n_decoded_tokens:]) >= self.streaming_frames_per_chunk + self.streaming_lookforward:
1649
+ tokens_start = max(n_decoded_tokens - self.streaming_lookback - self.streaming_overlap_frames, 0)
1650
+ tokens_end = n_decoded_tokens + self.streaming_frames_per_chunk + self.streaming_lookforward + self.streaming_overlap_frames
1651
+
1652
+ sample_start = (n_decoded_tokens - tokens_start) * self.hop_length
1653
+ sample_end = sample_start + (self.streaming_frames_per_chunk + 2 * self.streaming_overlap_frames) * self.hop_length
1654
+
1655
+ curr_codes = token_cache[tokens_start:tokens_end]
1656
+ recon = self._decode("".join(curr_codes))
1657
+
1658
+ # Apply watermark if available
1659
+ if self.watermarker:
1660
+ recon = self.watermarker.apply_watermark(recon, sample_rate=self.sample_rate)
1661
+
1662
+ recon = recon[sample_start:sample_end]
1663
+ audio_cache.append(recon)
1664
+
1665
+ processed_recon = _linear_overlap_add(audio_cache, stride=self.streaming_stride_samples)
1666
+ new_samples_end = len(audio_cache) * self.streaming_stride_samples
1667
+ processed_recon = processed_recon[n_decoded_samples:new_samples_end]
1668
+ n_decoded_samples = new_samples_end
1669
+ n_decoded_tokens += self.streaming_frames_per_chunk
1670
+ yield processed_recon
1671
+
1672
+ except json.JSONDecodeError:
1673
+ continue
1674
+
1675
+ except Exception as e:
1676
+ print(f"Error streaming chunk: {e}")
1677
+ return
1678
+
1679
+ # Final decoding (Flush remaining tokens)
1680
+ remaining_tokens = len(token_cache) - n_decoded_tokens
1681
+ if remaining_tokens > 0:
1682
+ tokens_start = max(len(token_cache) - (self.streaming_lookback + self.streaming_overlap_frames + remaining_tokens), 0)
1683
+ sample_start = (len(token_cache) - tokens_start - remaining_tokens - self.streaming_overlap_frames) * self.hop_length
1684
+
1685
+ curr_codes = token_cache[tokens_start:]
1686
+ recon = self._decode("".join(curr_codes))
1687
+ recon = recon[sample_start:]
1688
+ audio_cache.append(recon)
1689
+
1690
+ processed_recon = _linear_overlap_add(audio_cache, stride=self.streaming_stride_samples)
1691
+ processed_recon = processed_recon[n_decoded_samples:]
1692
+ yield processed_recon
1693
+
1694
+ async def infer_async(self, text: str, ref_audio: str | Path = None, ref_codes: np.ndarray | torch.Tensor = None, ref_text: str = None, max_chars: int = 256, silence_p: float = 0.15, crossfade_p: float = 0.0, voice: dict = None, temperature: float = 1.0, top_k: int = 50, session=None) -> np.ndarray:
1695
+ """
1696
+ Asynchronous inference (Non-blocking I/O).
1697
+ """
1698
+ try:
1699
+ import aiohttp
1700
+ except ImportError:
1701
+ raise ImportError("Async requires 'aiohttp'. Install with: pip install aiohttp")
1702
+
1703
+ if voice is not None:
1704
+ ref_codes = voice.get('codes', ref_codes)
1705
+ ref_text = voice.get('text', ref_text)
1706
+
1707
+ # Auto-encode ref_audio locally if provided
1708
+ if ref_audio is not None and ref_codes is None:
1709
+ ref_codes = self.encode_reference(ref_audio)
1710
+ elif self._default_voice and (ref_codes is None or ref_text is None):
1711
+ try:
1712
+ voice_data = self.get_preset_voice(None)
1713
+ ref_codes = voice_data['codes']
1714
+ ref_text = voice_data['text']
1715
+ except Exception:
1716
+ pass
1717
+
1718
+ if ref_codes is None or ref_text is None:
1719
+ raise ValueError("Must provide either 'voice' dict or both 'ref_codes' and 'ref_text'.")
1720
+
1721
+ chunks = split_text_into_chunks(text, max_chars=max_chars)
1722
+ if not chunks:
1723
+ return np.array([], dtype=np.float32)
1724
+
1725
+ # Handle Session: Use provided or create new one
1726
+ should_close_session = False
1727
+ if session is None:
1728
+ session = aiohttp.ClientSession()
1729
+ should_close_session = True
1730
+
1731
+ try:
1732
+ tasks = []
1733
+ for chunk in chunks:
1734
+ tasks.append(self._infer_chunk_async(session, chunk, ref_codes, ref_text, temperature, top_k))
1735
+
1736
+ # Process chunks in parallel
1737
+ wavs = await asyncio.gather(*tasks)
1738
+
1739
+ # Join chunks
1740
+ final_wav = join_audio_chunks(wavs, self.sample_rate, silence_p, crossfade_p)
1741
+
1742
+ if self.watermarker:
1743
+ final_wav = self.watermarker.apply_watermark(final_wav, sample_rate=self.sample_rate)
1744
+
1745
+ return final_wav
1746
+
1747
+ finally:
1748
+ if should_close_session:
1749
+ await session.close()
1750
+
1751
+ async def _infer_chunk_async(self, session, chunk, ref_codes, ref_text, temperature, top_k):
1752
+ """Internal async helper for a single chunk"""
1753
+ if isinstance(ref_codes, torch.Tensor):
1754
+ ref_codes_list = ref_codes.cpu().numpy().flatten().tolist()
1755
+ elif isinstance(ref_codes, np.ndarray):
1756
+ ref_codes_list = ref_codes.flatten().tolist()
1757
+ else:
1758
+ ref_codes_list = ref_codes
1759
+
1760
+ prompt = self._format_prompt(ref_codes_list, ref_text, chunk)
1761
+
1762
+ payload = {
1763
+ "model": self.model_name,
1764
+ "messages": [{"role": "user", "content": prompt}],
1765
+ "max_tokens": 2048,
1766
+ "temperature": temperature,
1767
+ "top_k": top_k,
1768
+ "stop": ["<|SPEECH_GENERATION_END|>"],
1769
+ "stream": False
1770
+ }
1771
+
1772
+ try:
1773
+ async with session.post(f"{self.api_base}/chat/completions", json=payload, timeout=60) as resp:
1774
+ resp.raise_for_status()
1775
+ data = await resp.json()
1776
+ output_str = data["choices"][0]["message"]["content"]
1777
+ return self._decode(output_str)
1778
+ except Exception as e:
1779
+ print(f"Error in async chunk: {e}")
1780
+ return np.array([], dtype=np.float32)
1781
+
1782
+ async def infer_batch_async(self, texts: list[str], ref_audio: str | Path = None, ref_codes: np.ndarray | torch.Tensor = None, ref_text: str = None, max_chars: int = 256, silence_p: float = 0.15, crossfade_p: float = 0.0, voice: dict = None, temperature: float = 1.0, top_k: int = 50, concurrency_limit: int = 50) -> list[np.ndarray]:
1783
+ """
1784
+ High-performance Asynchronous Batch Inference.
1785
+ """
1786
+ try:
1787
+ import aiohttp
1788
+ except ImportError:
1789
+ raise ImportError("Async requires 'aiohttp'. Install with: pip install aiohttp")
1790
+
1791
+ # Pre-resolve voice refs once
1792
+ if voice is not None:
1793
+ ref_codes = voice.get('codes', ref_codes)
1794
+ ref_text = voice.get('text', ref_text)
1795
+
1796
+ if ref_audio is not None and ref_codes is None:
1797
+ ref_codes = self.encode_reference(ref_audio)
1798
+ elif self._default_voice and (ref_codes is None or ref_text is None):
1799
+ try:
1800
+ voice_data = self.get_preset_voice(None)
1801
+ ref_codes = voice_data['codes']
1802
+ ref_text = voice_data['text']
1803
+ except Exception:
1804
+ pass
1805
+
1806
+ if ref_codes is None or ref_text is None:
1807
+ raise ValueError("Must provide either 'voice' dict or both 'ref_codes' and 'ref_text'.")
1808
+
1809
+ # Use Semaphore to control concurrency
1810
+ sem = asyncio.Semaphore(concurrency_limit)
1811
+
1812
+ async with aiohttp.ClientSession() as session:
1813
+ async def bounded_infer(text):
1814
+ async with sem:
1815
+ return await self.infer_async(
1816
+ text, ref_codes=ref_codes, ref_text=ref_text,
1817
+ max_chars=max_chars, silence_p=silence_p, crossfade_p=crossfade_p,
1818
+ temperature=temperature, top_k=top_k,
1819
+ session=session # Reuse session
1820
+ )
1821
+
1822
+ tasks = [bounded_infer(text) for text in texts]
1823
+ results = await asyncio.gather(*tasks)
1824
+
1825
+ return results
1826
+
1827
 
1828
  def Vieneu(mode="standard", **kwargs):
1829
  """
web_stream_gguf.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ import time
4
+ import asyncio
5
+ import numpy as np
6
+ from fastapi import FastAPI
7
+ from fastapi.responses import HTMLResponse, StreamingResponse
8
+ import uvicorn
9
+ from vieneu import Vieneu
10
+ import io
11
+ import wave
12
+ from huggingface_hub import hf_hub_download
13
+
14
+ # ==========================================
15
+ # CONFIG GGUF MODELS
16
+ # ==========================================
17
+ AVAILABLE_MODELS = {
18
+ "q4": {
19
+ "id": "pnnbao-ump/VieNeu-TTS-0.3B-q4-gguf",
20
+ "name": "VieNeu 0.3B (Q4_0) - Fast/Light",
21
+ "desc": "Recommended for most CPUs (Speed > Quality)"
22
+ },
23
+ "q8": {
24
+ "id": "pnnbao-ump/VieNeu-TTS-0.3B-q8-gguf",
25
+ "name": "VieNeu 0.3B (Q8_0) - High Quality",
26
+ "desc": "Higher quality but slower (Requires strong CPU)"
27
+ },
28
+ "ngochuyen": {
29
+ "id": "pnnbao-ump/VieNeu-TTS-0.3B-ngoc-huyen-gguf-Q4_0",
30
+ "name": "VieNeu 0.3B (Q4_0) - Ngoc Huyen",
31
+ "desc": "Ngoc Huyen Voice"
32
+ }
33
+ }
34
+
35
+ DEFAULT_MODEL = "ngochuyen"
36
+ current_model_id = DEFAULT_MODEL
37
+ app = FastAPI()
38
+
39
+ # Global TTS Instance
40
+ tts = None
41
+
42
+ def load_model_instance(model_key):
43
+ global tts, current_model_id
44
+ print(f"⏳ Loading Model: {model_key}...")
45
+
46
+ repo_id = ""
47
+
48
+ # Check if this is a preset model key
49
+ if model_key in AVAILABLE_MODELS:
50
+ repo_id = AVAILABLE_MODELS[model_key]["id"]
51
+ else:
52
+ # Assume it's a custom Hugging Face Repo ID
53
+ # Validation: Must contain 'gguf' (case-insensitive)
54
+ if "gguf" not in model_key.lower():
55
+ raise ValueError("Custom Model ID must contain 'gguf' (e.g. user/model-gguf)")
56
+
57
+ repo_id = model_key.strip()
58
+ print(f"🔄 Custom Model Detected: {repo_id}")
59
+
60
+ # Reload TTS
61
+ try:
62
+ new_tts = Vieneu(
63
+ mode='standard',
64
+ backbone_repo=repo_id,
65
+ backbone_device="cpu",
66
+ codec_repo="neuphonic/neucodec-onnx-decoder-int8",
67
+ codec_device="cpu"
68
+ )
69
+ tts = new_tts
70
+ current_model_id = model_key
71
+ print(f"✅ Model Loaded Successfully: {repo_id}")
72
+ except Exception as e:
73
+ print(f"❌ Failed to load model {repo_id}: {e}")
74
+ raise e
75
+
76
+ # Initial Load
77
+ try:
78
+ load_model_instance(DEFAULT_MODEL)
79
+ except Exception:
80
+ print("⚠️ Initial model load failed. Server running but needs valid model.")
81
+
82
+
83
+ # ==========================================
84
+ # UI SERVING
85
+ # ==========================================
86
+ try:
87
+ with open("client/client.html", "r", encoding="utf-8") as f:
88
+ HTML_CONTENT = f.read()
89
+ HTML_CONTENT = HTML_CONTENT.replace("VieNeu Stream", "VieNeu GGUF (CPU)")
90
+ HTML_CONTENT = HTML_CONTENT.replace("Server: LMDeploy (Remote)", "Server: Local GGUF (CPU)")
91
+ except FileNotFoundError:
92
+ HTML_CONTENT = "<h1>Error: client.html missing</h1>"
93
+
94
+ @app.get("/")
95
+ async def get_ui():
96
+ return HTMLResponse(content=HTML_CONTENT)
97
+
98
+ @app.get("/models")
99
+ async def get_models():
100
+ """Return available models"""
101
+ return [
102
+ {"key": k, "name": v["name"], "desc": v["desc"], "active": k == current_model_id}
103
+ for k, v in AVAILABLE_MODELS.items()
104
+ ]
105
+
106
+ from pydantic import BaseModel
107
+ class ModelRequest(BaseModel):
108
+ model_key: str
109
+
110
+ @app.post("/set_model")
111
+ async def set_model(req: ModelRequest):
112
+ """Switch Model"""
113
+ try:
114
+ load_model_instance(req.model_key)
115
+ return {"status": "ok", "current_model": req.model_key}
116
+ except Exception as e:
117
+ return {"status": "error", "message": str(e)}
118
+
119
+ @app.get("/voices")
120
+ async def get_voices():
121
+ """Return list of available voices. If none/error, return instruction."""
122
+ try:
123
+ if tts is None:
124
+ return [{"id": "error", "name": "Model not loaded yet"}]
125
+
126
+ voices = tts.list_preset_voices()
127
+
128
+ if not voices:
129
+ # Voices.json missing or empty
130
+ return [{"id": "error_no_voices", "name": "⚠️ ERROR: No voices found! Please create voices.json in the model folder."}]
131
+
132
+ # Normalize to list of objects for easier JS handling
133
+ result = []
134
+ if isinstance(voices[0], tuple):
135
+ for desc, vid in voices:
136
+ result.append({"id": vid, "name": desc})
137
+ else:
138
+ # Fallback if list is just strings
139
+ for vid in voices:
140
+ result.append({"id": vid, "name": vid})
141
+ return result
142
+ except Exception as e:
143
+ print(f"Error listing voices: {e}")
144
+ return [{"id": "error_exception", "name": f"⚠️ Error loading voices: {str(e)}"}]
145
+
146
+ def float32_to_pcm16(audio_float):
147
+ """Convert float32 [-1, 1] to int16 bytes"""
148
+ audio_int16 = (audio_float * 32767).clip(-32768, 32767).astype(np.int16)
149
+ return audio_int16.tobytes()
150
+
151
+ @app.get("/stream")
152
+ async def stream_audio(text: str, voice_id: str = None):
153
+ """Streaming Endpoint with Voice Support"""
154
+
155
+ voice_data = None
156
+ if voice_id:
157
+ try:
158
+ voice_data = tts.get_preset_voice(voice_id)
159
+ except Exception:
160
+ print(f"Voice {voice_id} not found, using default.")
161
+
162
+ def audio_generator():
163
+ header = io.BytesIO()
164
+ with wave.open(header, 'wb') as wav_file:
165
+ wav_file.setnchannels(1)
166
+ wav_file.setsampwidth(2)
167
+ wav_file.setframerate(24000)
168
+ wav_file.setnframes(100_000_000)
169
+ yield header.getvalue()
170
+
171
+ start = time.time()
172
+ count = 0
173
+ try:
174
+ for chunk in tts.infer_stream(text, voice=voice_data):
175
+ if count == 0:
176
+ print(f"⚡ First sound in {time.time() - start:.3f}s")
177
+ count += 1
178
+ yield float32_to_pcm16(chunk)
179
+ time.sleep(0.001)
180
+
181
+ except Exception as e:
182
+ print(f"Error during inference: {e}")
183
+
184
+ return StreamingResponse(audio_generator(), media_type="audio/wav")
185
+
186
+ if __name__ == "__main__":
187
+ print("🌍 Open http://localhost:8001 to test GGUF Streaming")
188
+ uvicorn.run(app, host="0.0.0.0", port=8001)