torch.cuda.graph() captures in "global" mode. If another thread
allocates, frees, synchronises or samples on the device while a graph
is being recorded, the capture can break; when cudaStreamEndCapture
fails, PyTorch never clears the CUDA generator's "capturing" flag, and
every later sampling call or graph replay in the process raises "Offset
increment outside graph capture encountered unexpectedly" until the
process restarts. A user of the VieNeu desktop app's local GPU server
(SDK 3.8.3) got this error and synthesis kept failing until a reboot;
a capture overlapping other GPU work is the most likely trigger.
v3 Turbo captures lazily (a new batch bucket, cache length or sampling
setting mid-request) from whichever thread needs the graph, and
_fused_lock (2f73298) only serialises the runs of one engine. Still
outside any lock: prompt embeddings and speaker anchors, the codec
decode after a batch, reference encoding (encode_reference), the
single-path engine, the stream scheduler's wor…
fix(api): free the stream slot as soon as the client disconnects
- Add _SpeechResponse class that closes body immediately when response ends
(done, failed, or client gone), replacing weakref.finalize dependency on GC
- _speech_chunks: close infer_stream iterator in finally to cancel GPU
scheduler row immediately
- _audio_body / _sse_body: close chunks iterator in finally
- Update test to simulate real client disconnect via ASGI with GC disabled
Fixes slot leak when client disconnects while queued or mid-stream.
fix: harden Web UI, speech API and GPU streaming
Đoàn Quang Huy
ff63dc3
Web UI
- Stop running code from repos typed into "Custom Model":
trust_remote_code is off unless VIENEU_TRUST_REMOTE_CODE=1 (the
official v1/v2/0.3B checkpoints are stock Qwen2/Qwen3 and need
none). Custom repos take the LMDeploy path only with that flag set,
since older LMDeploy releases trust remote code on their own.
- Optional login via VIENEU_WEB_AUTH=user:password; warn when the UI
is reachable beyond localhost without one.
Speech API (apps/openai_speech.py)
- Listen on 127.0.0.1 by default and warn on a public bind without
VIENEU_API_KEY; the Docker profiles set HOST=0.0.0.0.
- POST /v1/voices refuses (409) built-in voice names and aliases, so
a client can no longer replace the default voice for everyone.
- Range-check temperature, top_k, top_p, repetition_penalty and
max_chars. Validation errors return 400 in OpenAI's error shape;
the default handler turned a NaN into a 500.
- /health and new requests return 503 once the GPU stream scheduler
has died, so th…
feat(voices): đổi tên Minh Quân → Minh Quân Pro, giữ "Minh Quân" làm alias tương thích
Voices JSON có trường `aliases` theo entry; SDK resolve alias ở get_preset_voice,
_resolve_ref (infer/infer_stream/infer_batch), remove_voice; save_voices giữ alias;
list_preset_voices không liệt kê alias. API: voice qua alias vẫn hợp lệ, /v1/voices
trả `aliases` + `featured`. README dùng tên mới, ghi rõ tên cũ vẫn gọi được.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
feat(voices): trường `featured` — 10 giọng tuyển chọn có ⭐ và đứng đầu ở list_preset_voices, dropdown Web UI
`featured` 1..N trong voices JSON đánh dấu thứ tự giọng tuyển; SDK gắn nhãn ⭐ và
xếp trước, phần còn lại theo thứ tự file; save_voices giữ trường này. uv.lock cập
nhật version 3.8.0.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
fix(api): kiểm tra tên giọng / đuôi file ở /v1/voices, đọc upload đồng bộ; client kiểm --base
SonarCloud báo trên code mới: tên giọng và tên file upload đi thẳng vào add_voice
(log injection / path traversal), tempfile đồng bộ trong hàm async, và --base của
client mẫu (SSRF). Tên giọng và mô tả phải khớp [^\W_][\w .\-]{0,63}; đuôi file ánh
xạ sang hằng (.wav mặc định); giới hạn 20 MB; endpoint thành def thường (thread pool).
Client chỉ nhận --base dạng http(s)://host[:port].
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
- Voice Cloning: save button on its own line at natural size; saved-voice
dropdown is label-less/container-less so the small delete button lines up.
- Story and conversation boxes start empty (placeholders only); switching
backbone no longer refills the story box with a sample.
- SRT tab shows examples/srt/sample_vi.srt below the button as a format
example; sample files ship as package data.
- Batch Size default 16 for v3 (was 32), slider maximum 64.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Gradio: Voice Cloning as a top-level tab with saveable voices; PyTorch engine clones without torchaudio
- Voice Cloning moves out of the story tab's inner Preset/Cloning switch and
sits next to Đọc truyện / Hội thoại / SRT, with its own text box and button.
- Save a cloned voice under a name (apps/user_voices.py): it appears in every
preset dropdown (story, conversation, SRT) and persists in
~/.vieneu/user_voices_v3_{turbo,nano}.json across restarts; delete from the
same tab. Built-in voice names are protected.
- inference_v3_turbo: read references with soundfile and resample with soxr
(both base deps); torchaudio is only a fallback. The [cuda] extra never
installed torchaudio, so cloning on GPU failed with 'No module named
torchaudio'.
- Version 3.6.4.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Gradio SRT: cue-by-cue on CPU with per-cue progress; batches only on CUDA
Upload a .srt that is already in Vietnamese, pick a preset voice, get one
audio file: every cue is spoken with infer_batch (32 cues per call — the
GPU batches, CPU runs them in order) and laid on the subtitle timeline. A
clip that overruns its slot pushes the next cue later instead of
overlapping it; nothing is time-stretched. Optional "nối liền" mode joins
cues with 0.5 s gaps. MP3 via libsndfile when available, WAV otherwise.
v3 Turbo / Nano only; no translation, video or STT — the desktop app has
those.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
- OnnxV3NanoEngine.prepare_reference: reference clip -> (192-d x-vector,
50x256 style tokens) torch-free, following the Nano export recipe (Kaldi fbank
x-vector; codec_encoder latent of the first 5 s, normalised with the training
mean/std/scale, grouped x6, cropped to ref_max_frames -> reference_encoder).
The cloning graphs (speaker_encoder / codec_encoder / reference_encoder, plus
the optional denoiser) are fetched from the Nano HF repo on first use.
- V3NanoVieNeuTTS: encode_reference, add_voice, remove_voice, save_voices,
ref_audio= and denoise= on infer / infer_stream / infer_batch (batch enrolls
the clip once). Same edge-silence pre-clean as v3 Turbo.
- Gradio: cloning enabled for the Nano backbone. README/docstrings updated.
- Tests: engine reference path + grouping, full TTS cloning paths (fake ORT).
Verified against the torch-built presets: style tokens identical, x-vector
cosine >= 0.997 (fbank implementation differences only).
Co-Authored-By: Claude Fable 5.1 …
v3.5.1: chunk join with fixed pauses, soft chunk cap, new preset voices
- join_audio_chunks(silence_ps=...): trim+fade each chunk edge, then pad zeros so
the real pause equals V3_GAP_SILENCE (para 0.55 / sentence 0.32 / minor 0.14 s).
Pauses no longer depend on the voice: presets emitted ~300 ms of silence before
EOS while cloned voices emitted almost none, so cloned chunks sounded crammed.
v3 Turbo/Nano infer_stream now insert the same pauses between text chunks.
- Chunk cap is soft: a remainder shorter than 15 chars (e.g. "phương.") merges
into the previous chunk instead of being glued to the next sentence.
- Presets: Xuân Vĩnh re-enrolled (Northern), add Anh Khôi (storytelling),
Mạnh Dũng, Minh Quân (natural) — 23 voices.
- Gradio conversation tab: default inter-turn silence 0.3 s.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Add VieNeu-TTS v3 Nano (preview) for edge devices and weak CPUs
- New `Vieneu(mode="v3nano")` backend: 48M-param flow-matching model, ONNX/CPU,
torch-free, 24 kHz, 6 preset voices (no cloning), emotion tags supported.
- Gradio: add "VieNeu-TTS-v3-Nano (preview)" to the model list; v3 Turbo (fp32)
stays the default on CPU and GPU; CPU banner rewritten (no int8 recommendation).
- Docs: Nano section with RTF table and quality caveats (weaker EN / bilingual).
- Tests for the Nano engine and factory; version bump to 3.5.0.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
v3.4.0: SDK v3 Turbo mac dinh fp32 + sua watermark/UI theo issue #191
- SDK: precision mac dinh cua v3 Turbo (ONNX/CPU) doi int8 -> fp32; int8 thanh
tuy chon Vieneu(precision="int8") (can CPU co VNNI). web_stream cung theo fp32.
- Watermark (#191): go goi `perth` sai (thu vien threading) khoi deps + uv.lock;
them extra `vieneu[watermark]` (resemble-perth, can torch). _init_watermarker
canh bao ro thay vi nuot loi; Web UI chi hien dong "da dong dau" khi co watermarker.
- Web UI (#191): sua info o Batch Processing (v3 chi can CUDA, khong can LMDeploy);
bang vi du clone co cot transcript chi hien voi v2, v3 dung bang chi co audio.
- Docs: bo nhan early access/preview cua v3 Turbo; them link v3 Turbo vao header
Models cua Gradio; README ghi fp32 mac dinh.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
- Repetition penalty doi sang cua so truot (RepetitionHistory, window=64
frame ~2.5s): chi phat code trong cua so gan nhat thay vi phat vinh vien
ca chunk — het nguy co troi giong cuoi chunk dai. Ap dung dong bo ca 3
duong: PyTorch, ONNX/CPU, batched serve. Tham so moi `repetition_window`
(0 = hanh vi cu), kem tests/test_rep_history.py.
- Xoa giong Son Tran khoi voices_v3_turbo.json (20 -> 19 giong).
- Giam mac dinh max_new_frames 600 -> 300 (SDK + gradio app).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Chia chunk theo ranh giới câu, nhận biết trích dẫn; max_new_frames 600
Chia chunk
----------
Trước đây thứ tự là normalize -> tách câu. Normalizer của sea-g2p xoá sạch
dấu ngoặc ("..." / (...) -> dấu phẩy), nên khi tách câu thì mọi dấu .!? trong
trích dẫn đều bị nhầm là kết câu. Câu
Có phải ... kiểu như: "Rồi sao nữa? Mình phải tiếp tục đến bao giờ?", đúng không anh?
bị vỡ thành 4 mảnh, mảnh cuối ", đúng không anh?" mở đầu bằng dấu phẩy —
không phải một câu. Với max_chars=384 nó thành chunk riêng 17 ký tự, bị
punc_norm ép "?" -> "." (luật câu < 5 từ) nên mất luôn ngữ điệu hỏi, rồi
được chèn 0.18s im lặng phía trước.
Đảo thứ tự thành: tách câu trên text THÔ (nhận biết ngoặc/trích dẫn) ->
normalize từng câu -> đóng gói theo độ dài ĐÃ chuẩn hoá -> chốt dấu câu cuối
mỗi chunk. Vẫn giữ tính chất cũ là đo độ dài sau normalize nên chunk không
phình khi normalizer nở text ("100$" -> "một trăm u s d").
Cùng câu trên, max_chars=384 giờ ra [105, 296] — cắt đúng ở dấu chấm, khớp
trực giác người đọc. Cửa sổ xấu 388-396 biến mất; mọi max_chars 300-396 đều
cho cùn…
- v3_turbo_serve: guard in generate_batch — rows shorter than 0.25 frames
per phoneme char (markup stripped, floor 3) are regenerated up to 2x,
keeping the longest attempt; core loop split into _generate_codes_batch
- Length bucketing (sort chunks by phoneme length before batching) in
v3turbo._infer_chunks and both gradio batch paths — less left-padding
- gradio sequential path: keep empty wavs so v3_gaps stays aligned on join
- Default v3 Turbo voice -> Minh Duc (voices_v3_turbo.json + README examples)
- Bump sea-g2p to >=0.7.31
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
docs: rename tts → vieneu in examples/demos and note GPU→ONNX/CPU switch
Vieneu() defaults to device="auto", which picks the PyTorch/GPU backend when
torch+CUDA are present — silently breaking this ONNX/CPU int8 streaming demo.
Pin backend="onnx" so it always runs the intended int8 CPU path.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The 12-layer fp32 backbone was ~58% of per-frame CPU cost. Quantizing it to int8
(per-channel, reduce_range for non-VNNI AVX2) makes decode_step ~3x faster
(21.7 -> 7.0 ms/frame) and the weights ~4x smaller (415MB -> 99MB), with voice
quality confirmed by ear across multiple voices/utterances (single-step hidden
cosine 0.9996; trajectory divergence is benign stochastic-sampling chaos, not
degradation — RMS/peak/EOS-timing all match fp32).
- ONNX engine default subfolder -> `onnx_int8` (int8 backbone); `onnx_update` = fp32
- `Vieneu(precision="int8"|"fp32")` toggle (int8 default); explicit `onnx_subfolder`
still overrides. Only affects the CPU/ONNX path (GPU stays PyTorch).
- Gradio: two backbone options — "VieNeu-TTS-v3-Turbo (int8)" (default) and
"VieNeu-TTS-v3-Turbo" (fp32/quality) — plus a CPU advisory note.
Requires the `onnx_int8` subfolder on the model repo (uploaded separately).
Bump 3.1.4 -> 3.2.0.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Wire OnnxV3LiteEngine to the speaker-embedding + single-layer-acoustic
model (HF `onnx_update` subfolder):
- acoustic KV-cache generic over local_num_hidden_layers (was hard-coded 2)
- speaker anchor (xvec_proj) applied in numpy from heads.npz, added to every
inputs_embeds row (prefill + each decode slot)
- style-token prompt layout; public API mirrors the PyTorch engine
(prepare_reference / infer with speaker_emb + style + use_ref_codes; .denoiser)
- cloning via repo-root speaker_encoder.onnx + denoiser.onnx (lazy; preset
synth stays fully torch-free)
Verified vs the PyTorch engine (prompt-embeds max|Δ|≈1e-6, prefill-h ≈4e-7,
ONNX-codec ref-codes identical) and end-to-end pulling from the public HF repo.
Also ships gap-aware inter-chunk silence (paragraph/sentence/minor boundaries)
and a unified default chunk size of 256.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
fix(gradio): hide download button immediately on new generation instead of waiting for completion
- Add PyMuPDF dependency for PDF text extraction
- Add extract_text_from_pdf() function reading text from all PDF pages
- Add collapsible 'Upload PDF' section in the Single Speaker tab
- Extracted PDF text auto-fills the text box, editable before TTS
- Add DownloadButton to save generated audio files locally
- Download button auto-shows on successful generation, hides on Stop
The v3 Turbo path chunked at the PHONEME level (chunk_phonemes), but phonemes run
~1.2-1.4x longer than text, so at the same max_chars it split far more than the
v2-gpu path (which chunks normalized TEXT via normalize_to_chunks) → choppy,
extra mid-turn pauses in conversation.
- Add normalize_to_chunks_v3: chunk by normalized-text length identical to v2-gpu,
while preserving inline emotion cues ([cười]/<|emotion_k|>) that plain
normalize would otherwise strip; phonemize each chunk afterwards. With no cues
it delegates to normalize_to_chunks → byte-identical to v2-gpu.
- v3 Turbo infer/infer_stream, gradio v3 standard + conversation paths now use it.
- Remove now-unused chunk_phonemes helper.
Result: v2-gpu and v3-turbo now chunk consistently (e.g. 8 vs previously 10).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Chunk boundaries are now computed on the NORMALIZED text/phoneme stream instead
of raw text, so a chunk never overflows max_chars after the normalizer expands
it (e.g. "100$" -> "một trăm u s d").
- normalize_to_chunks: normalize (per-paragraph batch) THEN split; tag-aware so
it never cuts inside an <en>...</en> span
- phonemize_to_chunks / v3 Turbo / conversation / gradio paths: phonemize the
whole text first, then chunk the phoneme stream
- v3/emotion paths use normal greedy sentence packing (chunk_phonemes) instead of
per-sentence split_into_chunks_v2 (fewer, fuller chunks)
- every chunk ends with a sentence terminator via sea_g2p.punc_norm (single
source of truth; drop the local _ensure_terminal_punct reimplementation)
- require sea-g2p>=0.7.11 (exposes punc_norm)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>