Commit ·
0efb691
1
Parent(s): 1b8a8f6
feat: optimize SDK core and add high-performance CPU streaming demo
Browse filesFiles changed (8)
- README.md+13
- client/client.htmlAdded+767
- docs/sdk/README.mdDeleted-24
- docs/sdk/remote_mode.pyDeleted-90
- docs/sdk/standard_mode.pyDeleted-83
- main_remote.py+63-10
- vieneu/core.py+273-6
- web_stream_gguf.pyAdded+188
104 unmodified lines105106107108109110104 unmodified lines```Access the UI at `http://127.0.0.1:7860`.### 🚀 GGUF GPU Acceleration (Optional) <a name="gguf-gpu"></a>If you want to use GGUF models with GPU acceleration (llama-cpp-python), follow these steps:104 unmodified lines105106107108109110111112113114115116117118119120121122123104 unmodified lines```Access the UI at `http://127.0.0.1:7860`.### ⚡ Real-time Streaming (CPU Optimized)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.* **Latency:** <300ms for the first chunk on modern i3/i5 CPUs.* **Efficiency:** Uses Q4/Q8 quantization and ONNX-based lightweight codecs.* **Usage:** Perfect for real-time interactive AI assistants.**Start the dedicated CPU streaming demo:**```bashuv run web_stream_gguf.py```Then open `http://localhost:8001` in your browser.### 🚀 GGUF GPU Acceleration (Optional) <a name="gguf-gpu"></a>If you want to use GGUF models with GPU acceleration (llama-cpp-python), follow these steps:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767<!DOCTYPE html><html lang="en">
<head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>VieNeu SDK Stream</title> <link rel="icon" 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>">
<!-- Tailwind CSS --> <script src="https://cdn.tailwindcss.com"></script> <script> tailwind.config = { theme: { extend: { colors: { slate: { 850: '#151e2e', 900: '#0f172a', 950: '#020617', }, primary: { 400: '#38bdf8', 500: '#0ea5e9', 600: '#0284c7', }, violet: { 500: '#8b5cf6', } }, animation: { 'pulse-slow': 'pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite', } } } } </script>
<!-- Custom Scrollbar Styles --> <style> body { background-color: #020617; color: #f8fafc; }
::-webkit-scrollbar { width: 8px; height: 8px; }
::-webkit-scrollbar-track { background: #0f172a; }
::-webkit-scrollbar-thumb { background: #334155; border-radius: 4px; }
::-webkit-scrollbar-thumb:hover { background: #475569; } </style>
<!-- Import Map for React --> <script type="importmap">{ "imports": { "react": "https://esm.sh/react@18.2.0", "react-dom/client": "https://esm.sh/react-dom@18.2.0/client", "react-dom/": "https://esm.sh/react-dom@^19.2.3/", "react/": "https://esm.sh/react@^19.2.3/" }}</script>
<!-- Babel Standalone for in-browser JSX compilation --> <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script></head>
<body> <div id="root"></div>
<!-- MAIN APPLICATION SCRIPT --> <script type="text/babel" data-type="module"> import React, { useState, useRef, useEffect } from 'react'; import ReactDOM from 'react-dom/client';
// ========================================== // CONSTANTS (Replaces TS Enums) // ========================================== const StreamStatus = { IDLE: 'IDLE', CONNECTING: 'CONNECTING', PLAYING: 'PLAYING', COMPLETED: 'COMPLETED', ERROR: 'ERROR' };
// ========================================== // ICONS // ========================================== const Mic2 = ({ className }) => ( <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}> <path d="m12 8-9.04 9.06a2.82 2.82 0 1 0 3.98 3.98L16 12" /> <circle cx="17" cy="7" r="5" /> </svg> );
const Play = ({ className }) => ( <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}> <polygon points="5 3 19 12 5 21 5 3" /> </svg> );
const StopCircle = ({ className }) => ( <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}> <circle cx="12" cy="12" r="10" /> <rect width="6" height="6" x="9" y="9" /> </svg> );
const Loader2 = ({ className }) => ( <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}> <path d="M21 12a9 9 0 1 1-6.219-8.56" /> </svg> );
const Zap = ({ className }) => ( <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}> <polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2" /> </svg> );
const Activity = ({ className }) => ( <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}> <path d="M22 12h-4l-3 9L9 3l-3 9H2" /> </svg> );
// ========================================== // VISUALIZER COMPONENT // ========================================== const Visualizer = ({ audioElementRef, isPlaying, externalContext, externalSource }) => { const canvasRef = useRef(null); const audioContextRef = useRef(null); const analyserRef = useRef(null); const animationFrameRef = useRef(0);
useEffect(() => { if (isPlaying) { // MODE A: External Web Audio API (Ultra Low Latency) if (externalContext && externalContext.state !== 'closed') { try { // Reuse existing context audioContextRef.current = externalContext;
if (!analyserRef.current) { const analyser = externalContext.createAnalyser(); analyser.fftSize = 256; analyserRef.current = analyser;
// HACK: To visualize, we need to connect the SOURCE to this analyser. // But the source (buffers) are created dynamically in the loop. // So we rely on the parent to connect the destination to a global analyser node if possible, // OR we create a "tap" node. // BETTER APPROACH: The parent creates the Analyser and passes it down. } } catch (e) { console.error(e); } } // MODE B: Standard Audio Element else if (!audioContextRef.current && audioElementRef.current) { try { const AudioContextClass = window.AudioContext || window.webkitAudioContext; const ctx = new AudioContextClass(); const analyser = ctx.createAnalyser(); analyser.fftSize = 256;
const source = ctx.createMediaElementSource(audioElementRef.current); source.connect(analyser); analyser.connect(ctx.destination);
audioContextRef.current = ctx; analyserRef.current = analyser; } catch (e) { console.error("Audio Context initialization failed", e); } }
if (audioContextRef.current?.state === 'suspended') { audioContextRef.current.resume(); } } }, [isPlaying, audioElementRef, externalContext]);
// Re-render logic is mostly same, just needs 'analyserRef' to be populated useEffect(() => { const renderFrame = () => { const canvas = canvasRef.current; // If parent provided an analyser directly (Mode A variant), use it const analyser = externalSource || analyserRef.current;
if (!canvas || !analyser) { // Simulate if no analyser but playing if (isPlaying && canvas) { // ... simulation code ... } return; }
const ctx = canvas.getContext('2d'); if (!ctx) return;
const bufferLength = analyser.frequencyBinCount; const dataArray = new Uint8Array(bufferLength); analyser.getByteFrequencyData(dataArray);
const width = canvas.width; const height = canvas.height;
ctx.clearRect(0, 0, width, height);
const barWidth = (width / bufferLength) * 2.5; let barHeight; let x = 0;
for (let i = 0; i < bufferLength; i++) { barHeight = (dataArray[i] / 255) * height;
const gradient = ctx.createLinearGradient(0, height, 0, height - barHeight); gradient.addColorStop(0, '#3b82f6'); gradient.addColorStop(1, '#a855f7');
ctx.fillStyle = gradient; ctx.beginPath(); ctx.roundRect(x, height - barHeight, barWidth, barHeight, 4); ctx.fill();
x += barWidth + 2; }
animationFrameRef.current = requestAnimationFrame(renderFrame); };
if (isPlaying) { renderFrame(); } else { cancelAnimationFrame(animationFrameRef.current); const canvas = canvasRef.current; if (canvas) { const ctx = canvas.getContext('2d'); ctx?.clearRect(0, 0, canvas.width, canvas.height); } } return () => cancelAnimationFrame(animationFrameRef.current); }, [isPlaying, externalSource]); // Depend on externalSource (analyser)
return ( <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"> <div className="absolute top-2 left-2 text-[10px] text-slate-500 font-mono tracking-widest uppercase"> Frequency Visualizer </div> <canvas ref={canvasRef} width={600} height={100} className="w-full h-full" /> </div> ); };
// ========================================== // MAIN TTS INTERFACE // ========================================== const API_URL = '';
const TtsInterface = () => { const [text, setText] = useState(`Sức Mạnh Của Sự Thích Nghi Trong Kỷ Nguyên Số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.
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.
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.
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.
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.`); const [status, setStatus] = useState(StreamStatus.IDLE); const [metrics, setMetrics] = useState({ latencyMs: null, startTime: null }); const [voices, setVoices] = useState([]); const [selectedVoice, setSelectedVoice] = useState("");
const [models, setModels] = useState([]); const [currentModel, setCurrentModel] = useState(null); const [isModelLoading, setIsModelLoading] = useState(false);
const [audioBlob, setAudioBlob] = useState(null);
const audioRef = useRef(null);
// Web Audio API Refs const ctxRef = useRef(null); const isPlayingRef = useRef(false); const globalAnalyserRef = useRef(null); const abortControllerRef = useRef(null);
// Audio Recording Refs const recordedChunksRef = useRef([]);
const fetchVoices = async () => { try { const res = await fetch(`${API_URL}/voices`); const data = await res.json(); setVoices(data); if (data.length > 0) { // Keep current selection if still available, otherwise first one if (!data.find(v => v.id === selectedVoice)) { setSelectedVoice(data[0].id); } } } catch (e) { console.warn("Failed to load voices", e); } };
// Load data on mount useEffect(() => { // Models fetch(`${API_URL}/models`) .then(r => r.json()) .then(data => { setModels(data); const active = data.find(m => m.active); if (active) setCurrentModel(active.key); }) .catch(e => console.warn("Models API not found"));
fetchVoices(); }, []);
const handleModelChange = async (key) => { if (key === currentModel) return; setIsModelLoading(true); try { const res = await fetch(`${API_URL}/set_model`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ model_key: key }) }); const data = await res.json(); if (data.status === "ok") { setCurrentModel(key); // Refresh voices for new model await fetchVoices(); } else { alert("Error switching model: " + data.message); } } catch (e) { alert("Network error switching model"); } finally { setIsModelLoading(false); } };
const handleGenerate = async () => { if (!text.trim()) return;
handleStop(); // Ensure clean state
setStatus(StreamStatus.CONNECTING); const sessionStartTime = Date.now(); setMetrics({ startTime: sessionStartTime, latencyMs: null }); setAudioBlob(null); // Clear previous recording recordedChunksRef.current = []; // Reset recorder buffer
isPlayingRef.current = true;
// Init AbortController abortControllerRef.current = new AbortController(); const signal = abortControllerRef.current.signal;
// 1. Init Web Audio const AudioContextClass = window.AudioContext || window.webkitAudioContext; const ctx = new AudioContextClass({ sampleRate: 24000 }); ctxRef.current = ctx;
const analyser = ctx.createAnalyser(); analyser.fftSize = 256; globalAnalyserRef.current = analyser; analyser.connect(ctx.destination);
try { const encodedText = encodeURIComponent(text); const voiceParam = selectedVoice ? `&voice_id=${selectedVoice}` : "";
const response = await fetch(`${API_URL}/stream?text=${encodedText}${voiceParam}`, { signal });
if (!response.body) return; const reader = response.body.getReader();
let nextTime = ctx.currentTime + 0.1; let headerSkipped = false; let firstChunkPlayed = false;
const processStream = async () => { try { while (isPlayingRef.current) { const { done, value } = await reader.read(); if (done) break;
let audioData = value;
// Helper to create WAV later: Save raw PCM data // Note: We save ALL data including header for simplicity or skip header? // If we want clean WAV later, better to collect raw PCM and prepend own header. // We will strip header from first chunk for saving too to have clean PCM stream.
let pcmData = audioData;
if (!headerSkipped) { if (audioData.length > 44) { audioData = audioData.slice(44); pcmData = audioData; // Only save PCM part headerSkipped = true; } else { // Chunk too small (just header?), skip it entirely continue; } }
// Save for download recordedChunksRef.current.push(pcmData);
const int16 = new Int16Array(audioData.buffer, audioData.byteOffset, audioData.byteLength / 2); const float32 = new Float32Array(int16.length); for (let i = 0; i < int16.length; i++) { float32[i] = int16[i] / 32768.0; }
const buffer = ctx.createBuffer(1, float32.length, 24000); buffer.getChannelData(0).set(float32);
const source = ctx.createBufferSource(); source.buffer = buffer; source.connect(analyser);
if (nextTime < ctx.currentTime) nextTime = ctx.currentTime; source.start(nextTime);
nextTime += buffer.duration;
if (!firstChunkPlayed) { const latency = Date.now() - sessionStartTime; setMetrics(prev => ({ ...prev, latencyMs: latency })); setStatus(StreamStatus.PLAYING); firstChunkPlayed = true; } } } catch (err) { if (err.name === 'AbortError') { console.log('Stream aborted by user'); } else { throw err; } }
if (isPlayingRef.current) { // Wait logic const remainingTime = nextTime - ctx.currentTime; if (remainingTime > 0) { await new Promise(r => setTimeout(r, remainingTime * 1000)); }
if (isPlayingRef.current) { setStatus(StreamStatus.COMPLETED); finalizeRecording(); // Create download link setTimeout(() => setStatus(StreamStatus.IDLE), 2000); } } };
processStream();
} catch (e) { if (e.name !== 'AbortError') { console.error("Stream Error", e); setStatus(StreamStatus.ERROR); } } };
const handleStop = () => { isPlayingRef.current = false;
// 1. Abort Fetch if (abortControllerRef.current) { abortControllerRef.current.abort(); abortControllerRef.current = null; }
// 2. Close Audio Context if (ctxRef.current) { ctxRef.current.close(); ctxRef.current = null; } globalAnalyserRef.current = null; setStatus(StreamStatus.IDLE); };
const finalizeRecording = () => { if (recordedChunksRef.current.length === 0) return;
// 1. Calculate total length let totalLength = 0; for (const chunk of recordedChunksRef.current) { totalLength += chunk.length; }
// 2. Create WAV Header const buffer = new ArrayBuffer(44 + totalLength); const view = new DataView(buffer);
// RIFF chunk descriptor writeString(view, 0, 'RIFF'); view.setUint32(4, 36 + totalLength, true); writeString(view, 8, 'WAVE'); // fmt sub-chunk writeString(view, 12, 'fmt '); view.setUint32(16, 16, true); view.setUint16(20, 1, true); // PCM view.setUint16(22, 1, true); // Mono view.setUint32(24, 24000, true); // 24kHz view.setUint32(28, 24000 * 2, true); // ByteRate view.setUint16(32, 2, true); // BlockAlign view.setUint16(34, 16, true); // BitsPerSample // data sub-chunk writeString(view, 36, 'data'); view.setUint32(40, totalLength, true);
// 3. Write PCM data let offset = 44; const bytes = new Uint8Array(buffer); for (const chunk of recordedChunksRef.current) { bytes.set(chunk, offset); offset += chunk.length; }
const blob = new Blob([buffer], { type: 'audio/wav' }); setAudioBlob(blob); };
const writeString = (view, offset, string) => { for (let i = 0; i < string.length; i++) { view.setUint8(offset + i, string.charCodeAt(i)); } };
const handleDownload = () => { if (!audioBlob) return; const url = URL.createObjectURL(audioBlob); const a = document.createElement('a'); a.href = url; a.download = `vienau_tts_${Date.now()}.wav`; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); };
// Remove unused audio element handlers const onPlay = () => { }; const onEnded = () => { }; const onError = () => { };
return ( <div className="w-full"> {/* Header Section */} <div className="text-center mb-8 space-y-2"> <h1 className="text-4xl font-bold tracking-tight text-white"> <span className="text-transparent bg-clip-text bg-gradient-to-r from-blue-400 to-violet-400">🦜 VieNeu</span> Stream </h1> <p className="text-slate-400 max-w-sm mx-auto text-sm font-medium"> High-fidelity neural text-to-speech with ultra-low latency streaming capability. </p> </div>
<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">
{isModelLoading && ( <div className="absolute inset-0 bg-slate-900/80 z-50 flex flex-col items-center justify-center space-y-3 backdrop-blur-sm"> <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"> <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle> <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> </svg> <span className="text-blue-400 font-semibold animate-pulse">Switching Model...</span> </div> )}
<div className="flex gap-4 mb-4 items-end"> {/* Model Selection */} <div className="flex-[2] space-y-2"> <label className="block text-slate-400 text-xs font-semibold uppercase tracking-wider ml-1"> Model <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"> ⚡ Demo này tối ưu hóa tốc độ streaming trên CPU - Không sử dụng GPU </span> </label> <div className="flex gap-2"> <select 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" value={currentModel || "q4"} onChange={(e) => handleModelChange(e.target.value)} disabled={status !== StreamStatus.IDLE && status !== StreamStatus.COMPLETED} > {models.map(m => ( <option key={m.key} value={m.key}>{m.name}</option> ))} </select> </div> </div>
{/* Voice Selection */} <div className="flex-1 space-y-2"> <label className="block text-slate-400 text-xs font-semibold uppercase tracking-wider ml-1">Voice</label> <select className={`w-full text-sm rounded-xl border p-3 appearance-none ${voices.length > 0 && voices[0].id.startsWith('error') ? 'bg-red-900/20 border-red-500/50 text-red-300' : 'bg-slate-900/50 border-slate-700 text-slate-200 focus:ring-blue-500' }`} value={selectedVoice} onChange={(e) => setSelectedVoice(e.target.value)} disabled={ (status !== StreamStatus.IDLE && status !== StreamStatus.COMPLETED) || (voices.length > 0 && voices[0].id.startsWith('error')) } > {voices.length === 0 && <option>Loading voices...</option>} {voices.map(v => ( <option key={v.id} value={v.id}>{v.name}</option> ))} </select> </div> </div>
{/* Input Area */} <div className="relative group mb-6"> <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> <textarea value={text} onChange={(e) => setText(e.target.value)} placeholder="Enter text to synthesize..." 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" spellCheck="false" /> </div>
{/* Controls & Status - Flex Row */} <div className="flex items-center justify-between gap-4 mb-6"> <div className="flex items-center gap-3"> {status === StreamStatus.CONNECTING || status === StreamStatus.PLAYING ? ( <button onClick={handleStop} 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" > <span className="mr-2">⏹</span> Stop Stream </button> ) : ( <button onClick={handleGenerate} disabled={status !== StreamStatus.IDLE && status !== StreamStatus.COMPLETED} 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" > <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> <span className="relative flex items-center"> {status === StreamStatus.CONNECTING ? ( <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"> <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle> <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> </svg> ) : ( <span className="mr-2">🦜</span> )} {status === StreamStatus.CONNECTING ? 'Connecting...' : 'Generate Stream'} </span> </button> )}
{audioBlob && status !== StreamStatus.PLAYING && status !== StreamStatus.CONNECTING && ( <button onClick={handleDownload} 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" title="Download Wav" > ⬇️ </button> )} </div>
{/* Metrics Badge */} <div className="flex flex-col items-end"> <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' : status === StreamStatus.PLAYING ? 'bg-emerald-500/10 border-emerald-500/20 text-emerald-400' : 'bg-slate-800 border-slate-700 text-slate-400' }`}> <div className={`w-2 h-2 rounded-full ${status === StreamStatus.PLAYING ? 'bg-emerald-400 animate-pulse' : status === StreamStatus.ERROR ? 'bg-red-400' : 'bg-slate-500' }`}></div> <span className="text-xs font-mono font-medium"> {status === StreamStatus.IDLE ? 'READY' : status === StreamStatus.CONNECTING ? 'BUFFERING' : status === StreamStatus.PLAYING ? 'STREAMING' : status === StreamStatus.COMPLETED ? 'COMPLETED' : 'ERROR'} </span> </div> {metrics.latencyMs && ( <span className="text-[10px] font-mono text-slate-500 mt-1"> Head Latency: <span className="text-blue-400">{metrics.latencyMs}ms</span> </span> )} </div> </div> {/* Hidden Audio Element */} <audio ref={audioRef} onPlay={onPlay} onEnded={onEnded} onError={onError} className="hidden" /> </div> </div> ); };
// ========================================== // APP ENTRY // ========================================== const App = () => { return ( <div className="min-h-screen w-full bg-[#020617] relative overflow-hidden flex items-center justify-center p-4"> {/* Ambient Background Effects */} <div className="absolute top-[-10%] left-[-10%] w-[40%] h-[40%] bg-primary-500/10 rounded-full blur-[120px] pointer-events-none" /> <div className="absolute bottom-[-10%] right-[-10%] w-[40%] h-[40%] bg-violet-500/10 rounded-full blur-[120px] pointer-events-none" />
<div className="relative z-10 w-full max-w-4xl"> <TtsInterface /> </div>
<footer className="absolute bottom-4 text-slate-500 text-xs text-center w-full"> Powered by VieNeu SDK & React </footer> </div> ); };
// Mount to Root const rootElement = document.getElementById('root'); if (rootElement) { const root = ReactDOM.createRoot(rootElement); root.render(<App />); } </script></body>
</html>123456789101112131415161718192021222324# VieNeu-TTS SDK Examples
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.
## Danh sách ví dụ
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).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.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).
## Cách chạy
Cài đặt SDK và các phụ kiện:
uv pip install -e .# Hoặcpip install -e .```
## Yêu cầu
* Python 3.10+* Server LMDeploy (cho ví dụ remote mode)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990"""Demo VieNeuSDK v1.1.3 - Full Features Guide"""
import timeimport soundfile as sffrom vieneu import Vieneufrom pathlib import Path
def main(): print("🚀 Initializing VieNeu SDK (v1.1.3)...") # Initialize SDK # Default: "pnnbao-ump/VieNeu-TTS-0.3B-q4-gguf" (Speed & CPU Optimized) # # You can change 'backbone_repo' to balance Quality vs Speed: # 1. Better Quality (slower than q4): "pnnbao-ump/VieNeu-TTS-0.3B-q8-gguf" # 2. PyTorch 0.3B (Fast, uncompressed): "pnnbao-ump/VieNeu-TTS-0.3B" # 3. PyTorch 0.5B (Best Quality, heavy): "pnnbao-ump/VieNeu-TTS" # You can also use a GGUF version merged with your own LoRA adapter. # See finetuning guide: https://github.com/pnnbao97/VieNeu-TTS/tree/main/finetune # Mode selection: # - mode="standard" (Default): Runs locally using GGUF (CPU) or PyTorch # - mode="remote": Connects to the LMDeploy server setup above for max speed # API Configuration for Remote Mode # Replace with your own server URL (e.g. http://localhost:23333/v1) LMDEPLOY_API_URL = 'http://bore.pub:31631/v1' # Initialize: Choose 'standard' (local) or 'remote' (API) # tts = Vieneu(mode='standard') # Note: 'model_name' must match the model ID serving on LMDeploy tts = Vieneu(mode='remote', api_base=LMDEPLOY_API_URL, model_name="pnnbao-ump/VieNeu-TTS")
# --------------------------------------------------------- # PART 1: PRESET VOICES # --------------------------------------------------------- available_voices = tts.list_preset_voices() # Display available voices if available_voices: print(f"📋 Found {len(available_voices)} available voices. First 3:") for desc, name in available_voices[:3]: print(f" - {desc} (ID: {name})") # 1. Use the default voice print("\n--- 2. Default Voice ---") default_voice_data = tts.get_preset_voice() # No arg = Default print(f"✅ Default voice text: {default_voice_data['text'][:50]}...")
# --------------------------------------------------------- # PART 2: CUSTOM VOICES GUIDE # --------------------------------------------------------- print("\n--- 3. Custom Voice Guide ---") print("ℹ️ To use a custom voice:") print("1. Create voice preset: `uv run python finetune/create_voices_json.py ...`") print("2. Or use ad-hoc reference in code.")
# --------------------------------------------------------- # PART 3: SYNTHESIS # --------------------------------------------------------- print("\n--- 3. Speech Synthesis ---") 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." # Example: Select the first voice ID _, selected_voice_id = available_voices[0] if available_voices else (None, None) # voice_data = tts.get_preset_voice(selected_voice_id) print("🎧 Generating...") print(f" Using default voice mechanism...") audio = tts.infer( text=text_input, voice=None, # SDK will use default automatically. # To use specific voice: voice=tts.get_preset_voice("VoiceName") temperature=1.0, top_k=50 ) tts.save(audio, "output.wav") print("💾 Saved: output.wav")
# --------------------------------------------------------- # CLEANUP # --------------------------------------------------------- tts.close() print("\n✅ Done!")
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283"""VieNeu-TTS SDK Example: Standard Mode (Local Inference)
This example demonstrates how to run VieNeu-TTS locally on your machine.Ideal for offline apps, local development, or private deployments."""
from vieneu import Vieneu
def main(): print("🚀 Initializing local VieNeu engine...") # Ensure output directory exists import os os.makedirs("outputs", exist_ok=True) # --------------------------------------------------------- # PART 1: INITIALIZATION # --------------------------------------------------------- # Mode="standard" runs locally. # By default, it uses "pnnbao-ump/VieNeu-TTS-0.3B-q4-gguf" (Backbone) # and "neuphonic/distill-neucodec" (Codec) for maximum speed. tts = Vieneu() # Optional: If you want to force use a specific PyTorch model: # tts = Vieneu(backbone_repo="pnnbao-ump/VieNeu-TTS-0.3B", codec_repo="neuphonic/distill-neucodec", backbone_device="cuda")
# --------------------------------------------------------- # PART 2: LIST PRESET VOICES # --------------------------------------------------------- # The SDK returns (Description, ID) tuples available_voices = tts.list_preset_voices() print(f"📋 Found {len(available_voices)} preset voices.") if available_voices: print(" Showing all voices:") for desc, name in available_voices: print(f" - {desc} (ID: {name})")
# --------------------------------------------------------- # PART 3: SPEECH SYNTHESIS # --------------------------------------------------------- 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." print(f"\n🎧 Synthesizing speech...") # By default, it uses the model's 'default_voice' audio = tts.infer(text=text) tts.save(audio, "outputs/standard_output.wav") print(f"💾 Saved synthesized speech to: outputs/standard_output.wav") # To use a specific voice from the list: # _, my_voice_id = available_voices[0] # voice_data = tts.get_preset_voice(my_voice_id) # audio = tts.infer(text=text, voice=voice_data)
# --------------------------------------------------------- # PART 4: ZERO-SHOT VOICE CLONING # --------------------------------------------------------- # You can clone any voice using a short audio sample (5-10s) and its transcript ref_audio = "examples/audio_ref/example_ngoc_huyen.wav" 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." import os if os.path.exists(ref_audio): print("\n--- PART 4: Voice Cloning ---") print(f"🦜 Cloning voice from: {ref_audio}") cloned_audio = tts.infer( text="Đây là giọng nói đã được clone thành công từ file mẫu.", ref_audio=ref_audio, ref_text=ref_text ) tts.save(cloned_audio, "outputs/cloned_output.wav") print("💾 Saved cloned voice to: outputs/cloned_output.wav")
# --------------------------------------------------------- # PART 5: CLEANUP # --------------------------------------------------------- # Cleanup (Optional for standard mode, but good practice) tts.close() print("\n✅ All tasks completed!")
if __name__ == "__main__": main()16 unmodified lines1718192021222329 unmodified lines53545556575859606162636465666768697028 unmodified lines9910010110210310410510610716 unmodified lines# Replace with your actual LMDeploy server URL# Example: 'http://localhost:23333/v1' or a public tunnel URLREMOTE_API_BASE = 'http://bore.pub:31631/v1' # Replace with your actual LMDeploy server URLREMOTE_MODEL_ID = "pnnbao-ump/VieNeu-TTS"# ---------------------------------------------------------29 unmodified lines# ---------------------------------------------------------if available_voices:print("\n--- PART 3: Using Specific Voice ID ---")# Select a voice by its ID (the second element in the tuple)_, my_voice_id = available_voices[1] if len(available_voices) > 1 else available_voices[0]print(f"👤 Selecting voice: {my_voice_id}")# Get reference data for this specific voicevoice_data = tts.get_preset_voice(my_voice_id)test_text = f"Chào bạn, tôi đang nói bằng giọng của bác sĩ Tuyên."audio_spec = tts.infer(text=test_text, voice=voice_data)tts.save(audio_spec, f"outputs/remote_{my_voice_id}.wav")print(f"💾 Saved {my_voice_id} synthesis to: outputs/remote_{my_voice_id}.wav")# ---------------------------------------------------------# PART 4: REMOTE SPEECH SYNTHESIS (DEFAULT)28 unmodified linesprint("💾 Saved remote cloned voice to: outputs/remote_cloned_output.wav")# ---------------------------------------------------------# PART 6: DONE# ---------------------------------------------------------print("\n✅ Remote tasks completed!")if __name__ == "__main__":main()16 unmodified lines1718192021222329 unmodified lines53545556575859606162636465666768697071727328 unmodified lines10210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016 unmodified lines# Replace with your actual LMDeploy server URL# Example: 'http://localhost:23333/v1' or a public tunnel URLREMOTE_API_BASE = 'http://bore.pub:34939/v1' # Replace with your actual LMDeploy server URLREMOTE_MODEL_ID = "pnnbao-ump/VieNeu-TTS"# ---------------------------------------------------------29 unmodified lines# ---------------------------------------------------------if available_voices:print("\n--- PART 3: Using Specific Voice ID ---")# Select a demonstration voice (Index 1 preferred for variety)voice_info = available_voices[1] if len(available_voices) > 1 else available_voices[0]desc, voice_id = voice_infoprint(f"👤 Synthesis voice: {desc} (ID: {voice_id})")# Get reference data for this specific voicevoice_data = tts.get_preset_voice(voice_id)test_text = f"Chào bạn, tôi đang nói bằng giọng của {desc}."audio_spec = tts.infer(text=test_text, voice=voice_data)save_path = f"outputs/remote_{voice_id}.wav"tts.save(audio_spec, save_path)print(f"💾 Saved synthesis to: {save_path}")# ---------------------------------------------------------# PART 4: REMOTE SPEECH SYNTHESIS (DEFAULT)28 unmodified linesprint("💾 Saved remote cloned voice to: outputs/remote_cloned_output.wav")# ---------------------------------------------------------# PART 6: NATIVE ASYNC INFERENCE (High Performance)# ---------------------------------------------------------print("\n📌 PART 6: Native Async Processing")print("=" * 60)# Define voice for async tasks (Using index 0 as default)if available_voices:_, batch_voice_id = available_voices[0]voice_data_batch = tts.get_preset_voice(batch_voice_id)else:voice_data_batch = Nonetry:import asyncioimport timeasync def run_async_examples():print("🚀 Testing Native Async API...")async_batch_texts = ["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ỏ.","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.","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.","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."]start_async = time.time()# infer_batch_async maintains order and manages concurrency internallybatch_results = await tts.infer_batch_async(async_batch_texts,voice=voice_data_batch,concurrency_limit=10)elapsed_async = time.time() - start_asyncprint(f"✅ Async Batch completed in {elapsed_async:.2f}s")for i, wav in enumerate(batch_results):tts.save(wav, f"outputs/remote_native_batch_async_{i}.wav")print(f"💾 Saved {len(batch_results)} async batch files.")# Run the async loopasyncio.run(run_async_examples())except ImportError:print("⚠️ aiohttp not installed. Please run: pip install aiohttp")except Exception as e:print(f"⚠️ Async example error: {e}")# ---------------------------------------------------------# PART 7: DONE# ---------------------------------------------------------print("\n✅ All remote tasks completed!")print("📁 Check the 'outputs/' folder for generated files.")if __name__ == "__main__":main()
10 unmodified lines111213141516171819202122232483 unmodified lines108109110111112113114115603 unmodified lines71972072172272372425 unmodified lines750751752753754755691 unmodified lines1447144814491450145114521453145414551456145714581459146096 unmodified lines15571558155915601561156210 unmodified linesimport gcimport jsonimport requestsfrom huggingface_hub import hf_hub_download# ============================================================================# Shared Utilities# ============================================================================def _linear_overlap_add(frames: list[np.ndarray], stride: int) -> np.ndarray:"""Linear overlap-add for smooth audio concatenation"""assert len(frames)dtype = frames[0].dtypeshape = frames[0].shape[:-1]83 unmodified linesself.hop_length = 480self.streaming_overlap_frames = 1self.streaming_frames_per_chunk = 25self.streaming_lookforward = 5self.streaming_lookback = 50self.streaming_stride_samples = self.streaming_frames_per_chunk * self.hop_length# Flags603 unmodified lines)curr_codes = token_cache[tokens_start:tokens_end]recon = self._decode("".join(curr_codes))recon = recon[sample_start:sample_end]audio_cache.append(recon)25 unmodified lines) * self.hop_lengthcurr_codes = token_cache[tokens_start:]recon = self._decode("".join(curr_codes))recon = recon[sample_start:]audio_cache.append(recon)691 unmodified lineshf_token=hf_token)# Auto-load voices from the remote model repo# This allows client to use 'voice=...' with server's custom voicesself._load_voices_from_repo(model_name, hf_token)print(f"📡 RemoteVieNeuTTS ready! Using backend: {self.api_base}")def _load_backbone(self, backbone_repo, backbone_device):pass # Explicitly skipdef _format_prompt(self, ref_codes: list[int], ref_text: str, input_text: str) -> str:"""Format prompt for remote LMDeploy server"""96 unmodified linesreturn final_wavdef Vieneu(mode="standard", **kwargs):"""10 unmodified lines1112131415161718192021222324252683 unmodified lines110111112113114115116117603 unmodified lines72172272372472572672772872973025 unmodified lines756757758759760761762763764765691 unmodified lines1457145814591460146114621463146414651466146714681469147014711472147396 unmodified lines1570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182910 unmodified linesimport gcimport jsonimport requestsimport asynciofrom huggingface_hub import hf_hub_downloadfrom concurrent.futures import ThreadPoolExecutor# ============================================================================# Shared Utilities# ============================================================================def _linear_overlap_add(frames: list[np.ndarray], stride: int) -> np.ndarray:# original impl --> https://github.com/facebookresearch/encodec/blob/main/encodec/utils.pyassert len(frames)dtype = frames[0].dtypeshape = frames[0].shape[:-1]83 unmodified linesself.hop_length = 480self.streaming_overlap_frames = 1self.streaming_frames_per_chunk = 25self.streaming_lookforward = 10self.streaming_lookback = 100self.streaming_stride_samples = self.streaming_frames_per_chunk * self.hop_length# Flags603 unmodified lines)curr_codes = token_cache[tokens_start:tokens_end]recon = self._decode("".join(curr_codes))# Apply watermark if availableif self.watermarker:recon = self.watermarker.apply_watermark(recon, sample_rate=self.sample_rate)recon = recon[sample_start:sample_end]audio_cache.append(recon)25 unmodified lines) * self.hop_lengthcurr_codes = token_cache[tokens_start:]recon = self._decode("".join(curr_codes))# Apply watermark if availableif self.watermarker:recon = self.watermarker.apply_watermark(recon, sample_rate=self.sample_rate)recon = recon[sample_start:]audio_cache.append(recon)691 unmodified lineshf_token=hf_token)self.streaming_frames_per_chunk = 10self.streaming_lookforward = 5self.streaming_lookback = 50self.streaming_stride_samples = self.streaming_frames_per_chunk * self.hop_lengthself._load_voices_from_repo(model_name, hf_token)print(f"📡 RemoteVieNeuTTS ready! Using backend: {self.api_base}")def _load_backbone(self, backbone_repo, backbone_device):passdef _format_prompt(self, ref_codes: list[int], ref_text: str, input_text: str) -> str:"""Format prompt for remote LMDeploy server"""96 unmodified linesreturn final_wavdef 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]:"""Stream output audio (generator)."""if voice is not None:ref_codes = voice.get('codes', ref_codes)ref_text = voice.get('text', ref_text)# Auto-encode ref_audio locally if providedif ref_audio is not None and ref_codes is None:ref_codes = self.encode_reference(ref_audio)elif self._default_voice and (ref_codes is None or ref_text is None):try:voice_data = self.get_preset_voice(None)ref_codes = voice_data['codes']ref_text = voice_data['text']except Exception:passif ref_codes is None or ref_text is None:raise ValueError("Must provide either 'voice' dict or both 'ref_codes' and 'ref_text'.")chunks = split_text_into_chunks(text, max_chars=max_chars)for chunk in chunks:yield from self._infer_stream_chunk(chunk, ref_codes, ref_text, temperature, top_k)def _infer_stream_chunk(self, chunk, ref_codes, ref_text, temperature, top_k):"""Internal helper to stream a single text chunk"""if isinstance(ref_codes, torch.Tensor):ref_codes_list = ref_codes.cpu().numpy().flatten().tolist()elif isinstance(ref_codes, np.ndarray):ref_codes_list = ref_codes.flatten().tolist()else:ref_codes_list = ref_codesprompt = self._format_prompt(ref_codes_list, ref_text, chunk)payload = {"model": self.model_name,"messages": [{"role": "user", "content": prompt}],"max_tokens": 2048,"temperature": temperature,"top_k": top_k,"stop": ["<|SPEECH_GENERATION_END|>"],"stream": True # Enable streaming}# Streaming window stateaudio_cache: list[np.ndarray] = []token_cache: list[str] = [f"<|speech_{idx}|>" for idx in ref_codes_list]n_decoded_samples: int = 0n_decoded_tokens: int = len(ref_codes_list)try:with requests.post(f"{self.api_base}/chat/completions", json=payload, stream=True, timeout=60) as r:r.raise_for_status()# Iterate over SSE linesfor line in r.iter_lines():if not line:continueline_str = line.decode('utf-8')if not line_str.startswith('data: '):continuedata_str = line_str[6:] # Strip 'data: 'if data_str == '[DONE]':breaktry:content = json.loads(data_str)["choices"][0]["delta"].get("content", "")if content:token_cache.append(content)# --- Windowed Decoding Logic (Shared) ---if len(token_cache[n_decoded_tokens:]) >= self.streaming_frames_per_chunk + self.streaming_lookforward:tokens_start = max(n_decoded_tokens - self.streaming_lookback - self.streaming_overlap_frames, 0)tokens_end = n_decoded_tokens + self.streaming_frames_per_chunk + self.streaming_lookforward + self.streaming_overlap_framessample_start = (n_decoded_tokens - tokens_start) * self.hop_lengthsample_end = sample_start + (self.streaming_frames_per_chunk + 2 * self.streaming_overlap_frames) * self.hop_lengthcurr_codes = token_cache[tokens_start:tokens_end]recon = self._decode("".join(curr_codes))# Apply watermark if availableif self.watermarker:recon = self.watermarker.apply_watermark(recon, sample_rate=self.sample_rate)recon = recon[sample_start:sample_end]audio_cache.append(recon)processed_recon = _linear_overlap_add(audio_cache, stride=self.streaming_stride_samples)new_samples_end = len(audio_cache) * self.streaming_stride_samplesprocessed_recon = processed_recon[n_decoded_samples:new_samples_end]n_decoded_samples = new_samples_endn_decoded_tokens += self.streaming_frames_per_chunkyield processed_reconexcept json.JSONDecodeError:continueexcept Exception as e:print(f"Error streaming chunk: {e}")return# Final decoding (Flush remaining tokens)remaining_tokens = len(token_cache) - n_decoded_tokensif remaining_tokens > 0:tokens_start = max(len(token_cache) - (self.streaming_lookback + self.streaming_overlap_frames + remaining_tokens), 0)sample_start = (len(token_cache) - tokens_start - remaining_tokens - self.streaming_overlap_frames) * self.hop_lengthcurr_codes = token_cache[tokens_start:]recon = self._decode("".join(curr_codes))recon = recon[sample_start:]audio_cache.append(recon)processed_recon = _linear_overlap_add(audio_cache, stride=self.streaming_stride_samples)processed_recon = processed_recon[n_decoded_samples:]yield processed_reconasync 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:"""Asynchronous inference (Non-blocking I/O)."""try:import aiohttpexcept ImportError:raise ImportError("Async requires 'aiohttp'. Install with: pip install aiohttp")if voice is not None:ref_codes = voice.get('codes', ref_codes)ref_text = voice.get('text', ref_text)# Auto-encode ref_audio locally if providedif ref_audio is not None and ref_codes is None:ref_codes = self.encode_reference(ref_audio)elif self._default_voice and (ref_codes is None or ref_text is None):try:voice_data = self.get_preset_voice(None)ref_codes = voice_data['codes']ref_text = voice_data['text']except Exception:passif ref_codes is None or ref_text is None:raise ValueError("Must provide either 'voice' dict or both 'ref_codes' and 'ref_text'.")chunks = split_text_into_chunks(text, max_chars=max_chars)if not chunks:return np.array([], dtype=np.float32)# Handle Session: Use provided or create new oneshould_close_session = Falseif session is None:session = aiohttp.ClientSession()should_close_session = Truetry:tasks = []for chunk in chunks:tasks.append(self._infer_chunk_async(session, chunk, ref_codes, ref_text, temperature, top_k))# Process chunks in parallelwavs = await asyncio.gather(*tasks)# Join chunksfinal_wav = join_audio_chunks(wavs, self.sample_rate, silence_p, crossfade_p)if self.watermarker:final_wav = self.watermarker.apply_watermark(final_wav, sample_rate=self.sample_rate)return final_wavfinally:if should_close_session:await session.close()async def _infer_chunk_async(self, session, chunk, ref_codes, ref_text, temperature, top_k):"""Internal async helper for a single chunk"""if isinstance(ref_codes, torch.Tensor):ref_codes_list = ref_codes.cpu().numpy().flatten().tolist()elif isinstance(ref_codes, np.ndarray):ref_codes_list = ref_codes.flatten().tolist()else:ref_codes_list = ref_codesprompt = self._format_prompt(ref_codes_list, ref_text, chunk)payload = {"model": self.model_name,"messages": [{"role": "user", "content": prompt}],"max_tokens": 2048,"temperature": temperature,"top_k": top_k,"stop": ["<|SPEECH_GENERATION_END|>"],"stream": False}try:async with session.post(f"{self.api_base}/chat/completions", json=payload, timeout=60) as resp:resp.raise_for_status()data = await resp.json()output_str = data["choices"][0]["message"]["content"]return self._decode(output_str)except Exception as e:print(f"Error in async chunk: {e}")return np.array([], dtype=np.float32)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]:"""High-performance Asynchronous Batch Inference."""try:import aiohttpexcept ImportError:raise ImportError("Async requires 'aiohttp'. Install with: pip install aiohttp")# Pre-resolve voice refs onceif voice is not None:ref_codes = voice.get('codes', ref_codes)ref_text = voice.get('text', ref_text)if ref_audio is not None and ref_codes is None:ref_codes = self.encode_reference(ref_audio)elif self._default_voice and (ref_codes is None or ref_text is None):try:voice_data = self.get_preset_voice(None)ref_codes = voice_data['codes']ref_text = voice_data['text']except Exception:passif ref_codes is None or ref_text is None:raise ValueError("Must provide either 'voice' dict or both 'ref_codes' and 'ref_text'.")# Use Semaphore to control concurrencysem = asyncio.Semaphore(concurrency_limit)async with aiohttp.ClientSession() as session:async def bounded_infer(text):async with sem:return await self.infer_async(text, ref_codes=ref_codes, ref_text=ref_text,max_chars=max_chars, silence_p=silence_p, crossfade_p=crossfade_p,temperature=temperature, top_k=top_k,session=session # Reuse session)tasks = [bounded_infer(text) for text in texts]results = await asyncio.gather(*tasks)return resultsdef Vieneu(mode="standard", **kwargs):"""
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
import osimport timeimport asyncioimport numpy as npfrom fastapi import FastAPIfrom fastapi.responses import HTMLResponse, StreamingResponseimport uvicornfrom vieneu import Vieneuimport ioimport wavefrom huggingface_hub import hf_hub_download
# ==========================================# CONFIG GGUF MODELS# ==========================================AVAILABLE_MODELS = { "q4": { "id": "pnnbao-ump/VieNeu-TTS-0.3B-q4-gguf", "name": "VieNeu 0.3B (Q4_0) - Fast/Light", "desc": "Recommended for most CPUs (Speed > Quality)" }, "q8": { "id": "pnnbao-ump/VieNeu-TTS-0.3B-q8-gguf", "name": "VieNeu 0.3B (Q8_0) - High Quality", "desc": "Higher quality but slower (Requires strong CPU)" }, "ngochuyen": { "id": "pnnbao-ump/VieNeu-TTS-0.3B-ngoc-huyen-gguf-Q4_0", "name": "VieNeu 0.3B (Q4_0) - Ngoc Huyen", "desc": "Ngoc Huyen Voice" }}
DEFAULT_MODEL = "ngochuyen"current_model_id = DEFAULT_MODELapp = FastAPI()
# Global TTS Instancetts = None
def load_model_instance(model_key): global tts, current_model_id print(f"⏳ Loading Model: {model_key}...") repo_id = "" # Check if this is a preset model key if model_key in AVAILABLE_MODELS: repo_id = AVAILABLE_MODELS[model_key]["id"] else: # Assume it's a custom Hugging Face Repo ID # Validation: Must contain 'gguf' (case-insensitive) if "gguf" not in model_key.lower(): raise ValueError("Custom Model ID must contain 'gguf' (e.g. user/model-gguf)") repo_id = model_key.strip() print(f"🔄 Custom Model Detected: {repo_id}")
# Reload TTS try: new_tts = Vieneu( mode='standard', backbone_repo=repo_id, backbone_device="cpu", codec_repo="neuphonic/neucodec-onnx-decoder-int8", codec_device="cpu" ) tts = new_tts current_model_id = model_key print(f"✅ Model Loaded Successfully: {repo_id}") except Exception as e: print(f"❌ Failed to load model {repo_id}: {e}") raise e
# Initial Loadtry: load_model_instance(DEFAULT_MODEL)except Exception: print("⚠️ Initial model load failed. Server running but needs valid model.")
# ==========================================# UI SERVING# ==========================================try: with open("client/client.html", "r", encoding="utf-8") as f: HTML_CONTENT = f.read() HTML_CONTENT = HTML_CONTENT.replace("VieNeu Stream", "VieNeu GGUF (CPU)") HTML_CONTENT = HTML_CONTENT.replace("Server: LMDeploy (Remote)", "Server: Local GGUF (CPU)")except FileNotFoundError: HTML_CONTENT = "<h1>Error: client.html missing</h1>"
@app.get("/")async def get_ui(): return HTMLResponse(content=HTML_CONTENT)
@app.get("/models")async def get_models(): """Return available models""" return [ {"key": k, "name": v["name"], "desc": v["desc"], "active": k == current_model_id} for k, v in AVAILABLE_MODELS.items() ]
from pydantic import BaseModelclass ModelRequest(BaseModel): model_key: str
@app.post("/set_model")async def set_model(req: ModelRequest): """Switch Model""" try: load_model_instance(req.model_key) return {"status": "ok", "current_model": req.model_key} except Exception as e: return {"status": "error", "message": str(e)}
@app.get("/voices")async def get_voices(): """Return list of available voices. If none/error, return instruction.""" try: if tts is None: return [{"id": "error", "name": "Model not loaded yet"}]
voices = tts.list_preset_voices() if not voices: # Voices.json missing or empty return [{"id": "error_no_voices", "name": "⚠️ ERROR: No voices found! Please create voices.json in the model folder."}]
# Normalize to list of objects for easier JS handling result = [] if isinstance(voices[0], tuple): for desc, vid in voices: result.append({"id": vid, "name": desc}) else: # Fallback if list is just strings for vid in voices: result.append({"id": vid, "name": vid}) return result except Exception as e: print(f"Error listing voices: {e}") return [{"id": "error_exception", "name": f"⚠️ Error loading voices: {str(e)}"}]
def float32_to_pcm16(audio_float): """Convert float32 [-1, 1] to int16 bytes""" audio_int16 = (audio_float * 32767).clip(-32768, 32767).astype(np.int16) return audio_int16.tobytes()
@app.get("/stream")async def stream_audio(text: str, voice_id: str = None): """Streaming Endpoint with Voice Support""" voice_data = None if voice_id: try: voice_data = tts.get_preset_voice(voice_id) except Exception: print(f"Voice {voice_id} not found, using default.")
def audio_generator(): header = io.BytesIO() with wave.open(header, 'wb') as wav_file: wav_file.setnchannels(1) wav_file.setsampwidth(2) wav_file.setframerate(24000) wav_file.setnframes(100_000_000) yield header.getvalue() start = time.time() count = 0 try: for chunk in tts.infer_stream(text, voice=voice_data): if count == 0: print(f"⚡ First sound in {time.time() - start:.3f}s") count += 1 yield float32_to_pcm16(chunk) time.sleep(0.001) except Exception as e: print(f"Error during inference: {e}")
return StreamingResponse(audio_generator(), media_type="audio/wav")
if __name__ == "__main__": print("🌍 Open http://localhost:8001 to test GGUF Streaming") uvicorn.run(app, host="0.0.0.0", port=8001)README.md+13
client/client.htmlAdded+767
docs/sdk/README.mdDeleted-24
docs/sdk/remote_mode.pyDeleted-90
docs/sdk/standard_mode.pyDeleted-83
main_remote.py+63-10
vieneu/core.py+273-6
web_stream_gguf.pyAdded+188