Bilingual Article Audiobooks: Edge TTS Architecture, SOTA Speech Models and Agentic Spoken-Language Adaptation
How we built a free-tier bilingual article audiobook on Cloudflare Pages, Workers AI and R2; a late-2026 comparison of SOTA commercial and open-weight TTS models (ElevenLabs, MiniMax Speech 2.8, Cartesia Sonic 3.6, Inworld TTS-2, Deepgram Aura-2, Chirp 3, Qwen3-TTS, Fun-CosyVoice 3, IndexTTS 2, Fish Audio, Kokoro-82M); and a production blueprint comparing basic edge TTS against an AI-agent pre-synthesis pipeline that adapts written prose — including Standard Written Chinese to natural Hong Kong Cantonese — for the ear.
Adding a “Listen to this article” player to a bilingual technical site looks trivial until you try to ship one under real production constraints. Three engineering problems surface immediately:
- Written technical Markdown is hostile to speech synthesis: MDX imports, Svelte/Astro component tags, fenced code blocks, wide comparison tables, URLs and inline operators turn into unlistenable noise unless stripped and reformatted deterministically.
- Public text-to-speech endpoints are abuse magnets: An unauthenticated TTS route that synthesizes arbitrary query strings burns through AI quotas in minutes and becomes an open MP3 proxy for third-party bots.
- Bilingual diglossia (
zh-Hant-HKwritten vs. spoken Cantonese): Many fast, low-cost Western TTS engines support English only. Even when a model supports Chinese, feeding formal Standard Written Chinese (書面語) verbatim into a Cantonese voice produces stiff newsreader phrasing rather than natural Hong Kong spoken Cantonese (粵語口語), while rapid English technical terms dropped mid-sentence break prosody unless prepared explicitly.
You can test our live baseline implementation directly in the audiobook player at the top of this engineering note. Below, we document how gigantic.work built that hybrid Cloudflare free-tier audiobook architecture across English and Traditional Chinese (/zh-hant/), benchmark the late-2026 commercial and open-weight TTS models that can power it, and contrast the basic edge-native pipeline with a sophisticated AI-agent pre-synthesis pipeline that rewrites written text for the ear before a single frame of audio is generated.
Decouple script compilation & content-addressed hashing, tiered edge/object caching and optional LLM spoken-language adaptation. When the audio URL schema is keyed by a deterministic chunk hash inside a closed build-time manifest, the exact same Svelte player and Cloudflare R2 cache work identically whether audio is synthesized lazily on Workers AI or pre-rendered offline by an agentic Cantonese/English narration pipeline.
1. How we implemented the bilingual audiobook feature
Our production design runs on Cloudflare Pages, Workers AI and Cloudflare R2 within free-tier boundaries while degrading gracefully to zero-cost client synthesis whenever cloud audio is unavailable or a language track has not yet been pre-rendered to R2.
Astro Build (npm run build)
└─ src/lib/audiobook.ts (pure TS: no DOM / no fs)
├─► src/views/ArticleEntry.astro ──► embeds AudiobookScript into ArticleAudiobook.svelte
└─► src/pages/audiobook-manifest.json.ts ──► closed allowlist of { articleKey, chunkId, hash, text }
Runtime Playback (src/components/ArticleAudiobook.svelte)
├─► Optional direct R2 custom domain (PUBLIC_AUDIO_BASE_URL) ──► 0 Function calls
└─► GET /api/tts?article=...&chunk=...&hash=... (functions/api/tts.ts)
├─ Security gate: checkSameSite() + regex validation + manifest hash lookup
├─ Tier 0a: Cloudflare Edge Cache (caches.default, 1y immutable) ──► 0 Neurons
├─ Tier 0b: Cloudflare R2 (AUDIO_BUCKET) ──► 0 Neurons, $0 egress ──► warm Edge Cache
├─ Tier 1: Workers AI (env.AI, @cf/deepgram/aura-2-en or TTS_MODEL)
│ └─ per-IP throttle (30 / 10 min) ──► cache MP3 to R2 + Edge Cache via waitUntil()
└─ Tier 2: JSON { fallback: 'browser' } (501 zh-hant on Aura-2 / 429 / 503)
└─ Web Speech API utterance splitter + zh-HK / en-GB voice scorer
Offline Batch CLI (tools/audio/build-audiobooks.mjs · npm run build:audio)
├─► --provider=cloudflare (--max-chars=3500 daily free-tier drip) ──► .audio-cache ──► wrangler r2 put
└─► --provider=openai-compat (local Kokoro-82M / Qwen3-TTS server, --lang=all) ──► R2
Pure shared speech compiler (src/lib/audiobook.ts)
Every downstream consumer — Astro static pages (src/views/ArticleEntry.astro), the /audiobook-manifest.json endpoint (src/pages/audiobook-manifest.json.ts), the edge API (functions/api/tts.ts), the Svelte player and Vitest — imports the same dependency-free module src/lib/audiobook.ts. That guarantees the chunk boundaries and hashes computed in the browser never drift from the server manifest.
- MDX & Markdown narration cleaning (
cleanMarkdownForSpeech()):- Removes ESM
importstatements, multi-line Svelte/Astro component tags (such asVirtualLabDemo), HTML comments, inline SVG blocks, raw HTTPS URLs and Markdown formatting syntax (bold markers, backticks and link URLs). - Unwraps block HTML tags (
div,p,li,h1–h6,blockquote) into clean paragraph breaks and callsensurePunctuation()on headings, list items andcallout-titleheadings so TTS engines insert natural pauses instead of running titles directly into the following sentence. - Collapses fenced code blocks (including consecutive fences) into a single language-aware spoken signpost:
"See the code example in the article."(en) or"相關程式碼範例請參閱內文。"(zh-hant). - Converts compact Markdown tables (
tableToSpeech(), ≤6 body rows) into structured spoken pairs (Header: Value) and summarises dense multi-column matrices (>6 rows) with"See the comparison table in the article."/"詳細比較表請參閱內文。"so listeners are not subjected to five minutes of grid cells.
- Removes ESM
- Language-aware chunk ceilings & duration calibration:
splitSpeechChunks()splits paragraphs on sentence boundaries ([.!?]vs.[。!?]) and delegates long sentences to clause-splittingsplitOversizedSentence().- Because CJK characters pack far more semantic content per character than English prose — and trigger TTS latency/length caps sooner — we enforce
EN_MAX_CHUNK_CHARS = 1200(~155 words/min inestimateSpeechSeconds()) versusZH_MAX_CHUNK_CHARS = 600(~230 CJK characters/min, weighting inline Latin tokens like API names at1.6×character units).
- Content-addressed cache keys (
hashText()&audioObjectKey()):- Each chunk is hashed with a dual-seed 32-bit FNV-1a digest over
${lang}\0${text}to produce a 16-character hex signature. - R2 objects live at
audiobook/{lang}/{section}/{slug}/{chunkId}-{hash}.mp3. Editing one paragraph invalidates only that chunk’s hash; every untouched chapter remains immutably cached across deployments.
- Each chunk is hashed with a dual-seed 32-bit FNV-1a digest over
- Untranslated
/zh-hant/fallback safety (src/views/ArticleEntry.astro):- If a Traditional Chinese route falls back to rendering the English source article (
!translated),ArticleEntry.astrosetsaudioLang = pageLang === 'zh-hant' && !translated ? 'en' : pageLang— keeping the player UI in Traditional Chinese while passing the English script and voice profile so an English article is never fed to a Chinese voice.
- If a Traditional Chinese route falls back to rendering the English source article (
Closed-allowlist, 4-tier edge endpoint (functions/api/tts.ts)
Rather than exposing a generic /api/tts?text=... proxy, functions/api/tts.ts operates strictly against the build-time /audiobook-manifest.json allowlist:
- Anti-hotlink & parameter validation:
checkSameSite()enforcesSec-Fetch-Site(same-originornone),sameOrigin()and same-originRefererchecks. Query parameters must match strict article, chunk (\d+-\d+) and 16-hex-char hash regexes, and the exactchunk.hashmust match the manifest loaded viaenv.ASSETS(cached in isolate memory). Zero unverified or user-supplied text can reachenv.AI. - Tier 0a — Edge Cache (
caches.default): Serves matching canonical requests withCache-Control: public, max-age=31536000, immutableand headerx-audiobook-source: edge-cacheat 0 Neurons. - Tier 0b — Cloudflare R2 (
AUDIO_BUCKET): Fetches pre-generated or previously cached MP3s at 0 Neurons and $0 egress, then warmscaches.defaultasynchronously viawaitUntil(). - Tier 1 — On-demand Workers AI (
env.AI): Protected by both Cloudflare WAF rate limiting (/api/*at 20 req / 10s) and an in-isolate per-IP throttle (30uncached syntheses per10-minute window oncf-connecting-ip). Defaults to@cf/deepgram/aura-2-en(speakerluna), or switches via environment variableTTS_MODELto@cf/deepgram/aura-1(half the Neuron burn) orinworld/tts-2(automatically adapting payload keys to{ text, voice_id, output_format: 'mp3' }and decoding base64audioContentviaextractAudioBytes()). Synthesized MP3s are persisted to both R2 and Edge Cache viawaitUntil(). - Tier 2 — Deterministic browser fallback: When
entry.lang === 'zh-hant'hits an English-only Deepgram model (isDeepgramEnglishOnly()→ HTTP501),AIis unbound (503), or the synthesis throttle triggers (429), the endpoint returns structured JSON{ ok: false, error, fallback: 'browser' }.
// Core tiered lookup and payload adaptation inside functions/api/tts.ts
const model = (env.TTS_MODEL || '@cf/deepgram/aura-2-en').trim();
if (entry.lang === 'zh-hant' && isDeepgramEnglishOnly(model)) {
return jsonFallback('unsupported_language', 501, { fallback: 'browser', model });
}
const isInworld = /inworld\/tts/i.test(model);
const voice = (env.TTS_VOICE || (isInworld ? 'Dennis' : 'luna')).trim();
const payload = isInworld
? { text: chunk.text, voice_id: voice, output_format: 'mp3' }
: { text: chunk.text, speaker: voice, encoding: 'mp3' };
const out = await env.AI.run(model, payload, { returnRawResponse: true });
Svelte 5 playback engine & offline CLI pre-generator
On the client, src/components/ArticleAudiobook.svelte (client:idle) wires together chapter navigation (#slug deep jumps into headings), ±15s seeking, playback speed cycling (0.85×–2×), localStorage persistence (gw-audio-pos per article key and gw-audio-speed), IntersectionObserver-driven sticky mini-player docking clear of our chat widget, navigator.mediaSession lock-screen/headphone controls and blobCache cleanup (URL.revokeObjectURL on unmount). At 35% playback progress through any cloud chunk, prefetchNext() warms the next chunk so chapter transitions remain gapless.
When falling back to the browser’s Web Speech API, splitUtterances() breaks chunks into short segments (120 chars zh-hant, 220 chars en) to avoid browser speech-synthesis stalls on long passages, while pickVoice() ranks system voices prioritizing zh-HK / yue-HK (100) over zh-TW (85) and generic zh (50), plus +20 preference weight for enhanced/natural OS voices (Sin-ji, Mei-jia, HsiaoChen, Yunxi, Daniel, Serena, Ava).
To reach 0 runtime Workers AI Neurons across both English and Traditional Chinese, tools/audio/build-audiobooks.mjs (npm run build:audio) reads the built manifest, caches MP3s locally under .audio-cache, estimates Neuron or dollar cost with --dry-run, supports daily free-tier drip generation (--max-chars=3500), or targets any local OpenAI-compatible open-weight TTS server (--provider=openai-compat --model=kokoro --lang=all) before uploading directly to R2 via wrangler r2 object put --remote.
2. SOTA TTS model comparison (late 2026): commercial vs. open-weight
Choosing a speech engine for bilingual technical narration requires balancing Time-to-First-Audio (TTFA), per-million-character cost, licensing terms and native Cantonese + Chinese-English code-switching fidelity.
Note: All third-party API prices and hardware footprints below are indicative late-2026 market references for architecture sizing — not Gigantic Work consulting fees.
2.1 Commercial and managed API models
| Model & provider | Core architecture & strengths | Streaming TTFA | Languages & Cantonese / CJK bilingual quality | Indicative API pricing (late 2026) | Best-fit production role |
|---|---|---|---|---|---|
ElevenLabs (Eleven v4 / v4 Turbo / Flash v2.5) |
Expressive prosody, dialogue shifts and studio-grade instant/pro voice cloning | ~75–100 ms (Flash / Turbo) |
90+ languages; strong English/European baseline; default global voices carry non-native accents into zh-HK, so Cantonese requires cloning a native bilingual speaker |
~$40–$80 per 1M chars API overage equivalent (credit plans Starter $6/mo to Scale $299/mo) | Premium English/European narration or cloned-voice brand storytelling |
MiniMax Speech (Speech 2.8 HD / 2.8 Turbo) |
Cinematic storytelling cadence, fine-grained emotion controls and native sound tags (laughs, sighs, pauses) | ~250–325 ms median streaming | 40+ languages; top-tier Cantonese (zh-HK) and Mandarin fluency with natural Hong Kong-style English loan-word blending and zero-shot cloning |
Turbo: ~$60 / 1M chars · HD: ~$100 / 1M chars |
Expressive bilingual audiobooks, voiceovers and Cantonese character narration |
Cartesia Sonic (Sonic 3.6 / Sonic 3) |
State Space Model (SSM) acoustic backbone built for ultra-low latency | <90 ms | 44 languages; crisp English and major global languages; oriented toward conversational speed rather than specialised Cantonese prose | ~$37–$50 / 1M chars at scale (Pro from $5/mo, Startup $49/mo) | Real-time conversational voice agents and low-latency telephony |
Inworld TTS (Realtime TTS-2 / TTS-2 Flash) |
High-throughput conversational synthesis with unified voice identity across languages (natively integrated on Cloudflare Workers AI as inworld/tts-2) |
~45–81 ms median (Flash); <250 ms P90 (Max) |
200+ languages & locales including Chinese; maintains single speaker timbre across mid-sentence switches | $15 (Flash) – $25 / 1M chars (inworld/tts-2 on Cloudflare Workers AI / pay-as-you-go) |
Easiest managed bilingual upgrade inside Cloudflare without external keys |
Google Gemini TTS & Cloud Chirp 3 (Gemini 3.8 Flash TTS / Chirp 3 HD) |
Gemini TTS: prompt-steered accent/tone/pacing without SSML; Chirp 3: enterprise cloud HD + instant custom voice |
~500 ms+ (media-oriented) | 70–85+ languages including yue-Hant-HK / zh-HK; accurate baseline Cantonese, though sometimes stiff on rapid colloquial Hong Kong code-switching |
Gemini 3.8 Flash TTS: Chirp 3 HD: $30 / 1M chars |
High-volume batch generation and teams already standardised on Vertex AI / GCP |
Deepgram Aura (Aura-2 / Aura-1) |
Enterprise-grade normalization of numbers, dates, URLs and abbreviations (built-in Workers AI free tier) | ~90 ms | ~7 core languages (en, es, de, fr, nl, it, ja) — no Mandarin or Cantonese support |
$30 / 1M chars direct, or Cloudflare free tier (10,000 Neurons/day: ~2,727 Neurons/1k chars aura-2, ~1,364 aura-1) |
Zero-cost / low-cost English technical article narration at the edge |
Microsoft Azure AI Speech & OpenAI (zh-HK Neural / gpt-4o-mini-tts) |
Azure: mature SSML (phoneme with jyutping alphabet, say-as); OpenAI: token-metered speech (note Jan 6, 2027 deprecation for tts-1/gpt-4o-mini-tts toward gpt-realtime) |
~150–300 ms | Azure zh-HK neural voices are enterprise-compliant and deterministic with Jyutping SSML overrides, but sound more formal/institutional |
Azure: standard ~$15–$16 / 1M chars neural · OpenAI gpt-4o-mini-tts: ~$15 / 1M chars equiv. |
Regulated enterprise accessibility needing strict SSML pronunciation locks |
2.2 Open-weight and self-hosted models
| Model & origin | Parameters & minimum VRAM | License & commercial hygiene | Cantonese & Chinese-English code-switching | Cloning & prosody control | Best deployment fit |
|---|---|---|---|---|---|
| Qwen3-TTS (Alibaba Qwen Team) | 0.6B (~4–6 GB VRAM) · 1.7B (~8–12 GB VRAM) | Apache 2.0 (ungated, zero commercial restrictions) | Tier 1 native support: authentic Chinese prosody, Cantonese routing (chinese language mapping + reference prompt) and fluid bilingual HK English mixing |
Zero-shot voice cloning + natural-language instruction control for emotion and pacing | #1 self-hosted Apache 2.0 default for bilingual EN + Cantonese audiobooks |
| Fun-CosyVoice 3 (Alibaba / FunAudioLLM) | 0.5B open weights (~6–8 GB VRAM; hosted Plus ~1.5B) |
Apache 2.0 (open weights) | Outstanding dialect coverage: explicitly trained on 9 languages + 18+ Chinese dialects including Cantonese (粵語) | Instruction-driven dialect/accent steering + cross-lingual zero-shot cloning | Multi-dialect Chinese/Cantonese narration and fine-grained accent control |
| IndexTTS 2 / 2.5 (Bilibili / IndexTeam) | ~0.8B GPT backbone (~6–8 GB VRAM FP16) | bilibili Model Use License Agreement (bespoke terms — review before commercial deployment) | Very strong Mandarin/Chinese-English narration with crisp timing alignment | Emotion-disentanglement sliders + explicit Pinyin/phoneme overrides for heteronyms (破音字) |
Long-form Chinese-English articles needing explicit heteronym correction |
Fish Audio (Fish Speech S2 Pro / Drama 3) |
4B (S2 Pro, ~12–24 GB VRAM) · 35B MoE (Drama 3, ~32–46+ GB VRAM) |
Fish Audio Community License v1.0 (free commercial use only under $500k annual gross revenue; enterprise license above) | Strong multilingual & Chinese handling; requires a clean native Cantonese reference clip to prevent Cantonese from drifting toward Mandarin phonetics | Rich inline bracket tags ([laughs], [whispering], [sighs]) + top arena naturalness |
High-expression podcasts/dramas (or hosted API at $15/1M bytes S2 Pro) |
| Kokoro-82M (hexgrad) | 82M (<2 GB VRAM; fast on CPU) | Apache 2.0 (<$1 / 1M chars on serverless hosts) | Crisp English + Mandarin (misaki[zh] phonemizer); not native Cantonese |
Curated preset voices (af_heart, etc.); no arbitrary voice cloning |
Ultra-cheap batch English/Mandarin pre-generation on CPU or tiny GPUs |
| Chatterbox TTS (Resemble AI) | 350M (Turbo) · 500M (Multilingual V3, ~6–10 GB VRAM) |
MIT License (note: upstream repo archived/retired as a research release; rely on maintained forks) | 23+ languages including Chinese, tuned mainly for Mandarin + global languages | 5–10s zero-shot cloning + paralinguistic event tags | Lightweight research baselines or MIT-licensed English/Mandarin forks |
2.3 Benchmark and evaluation nuances for bilingual teams
- Provider Arena vs. Controlled Arena: Crowdsourced benchmarks such as the Artificial Analysis Speech Arena separate Provider Voice Arena (default showcase voices, where ElevenLabs and MiniMax benefit from polished studio talent) from Controlled Voice Arena (forcing every engine to clone identical reference clips to isolate prosody, pause placement and pronunciation). Open-weight models like Fish Audio, Qwen3-TTS and CosyVoice 3 close almost the entire quality gap under controlled cloning.
- Three Cantonese failure modes invisible on English leaderboards:
- Mandarin phonetic drift: Generic multilingual models given Traditional Chinese characters frequently hallucinate Mandarin consonants or tone contours halfway through long sentences unless anchored with Cantonese vocabulary and a clean
zh-HKreference prompt. - Code-switching collisions: Hong Kong technical speech mixes English nouns and verbs mid-clause (e.g., “喺 Cloudflare R2 度 cache 返啲 MP3”). Models without joint EN/CJK token alignment stumble at ASCII-to-Hanzi boundaries.
- Heteronyms (
破音字): Characters such as長,行,數,重,調and載change reading by semantic role (下載vs.三年兩載). Only models that either understand deep contextual semantics or accept explicit phoneme/Jyutping overrides handle them reliably.
- Mandarin phonetic drift: Generic multilingual models given Traditional Chinese characters frequently hallucinate Mandarin consonants or tone contours halfway through long sentences unless anchored with Cantonese vocabulary and a clean
3. The basic way: Cloudflare edge-native architecture
What we shipped in v4.13.0 is the basic edge-native architecture: deterministic Markdown cleaning (cleanMarkdownForSpeech), content-addressed chunking (EN_MAX_CHUNK_CHARS=1200 / ZH_MAX_CHUNK_CHARS=600), immutable R2 + Edge caching, Workers AI synthesis (Deepgram Aura-2 free tier or Inworld TTS-2), Web Speech browser fallback and an optional local batch builder (npm run build:audio).
Why the basic pipeline works so well out of the box
Consider a typical 30-article bilingual engineering & tutorial site (~12,000 English characters and ~6,000 Chinese characters per pair ≈ 360k EN + 180k ZH characters total):
- Zero-egress storage footprint: Roughly 9 hours of speech encoded at 64 kbps mono MP3 occupies ~260 MB — under 3% of Cloudflare R2’s permanent 10 GB monthly free tier, with 10M free Class B reads/month and $0 egress.
- Near-zero synthesis cost:
- Option A (Free daily drip): Using
@cf/deepgram/aura-2-en(~2,727 Neurons/1k chars),3,500chars/run stays inside Cloudflare’s 10,000 Neurons/day free allowance — pre-generating the entire 360k-char English library at $0 over ~100 automated nightly runs (or twice as fast on@cf/deepgram/aura-1). - Option B (Managed bilingual upgrade): Switching
TTS_MODELtoinworld/tts-2synthesizes all 540k bilingual characters on-demand or in batch for ~$13.50 USD one-time (540k × $25 / 1M), after which every replay hits R2/Edge Cache at $0. - Option C (Local GPU batch + R2): Running
npm run build:audio -- --provider=openai-compat --model=qwen3-tts --lang=all --upload-r2=gigantic-audioon a single workstation GPU generates all English and Cantonese/Mandarin MP3s for $0 API spend and zero ongoing GPU hosting.
- Option A (Free daily drip): Using
Where the basic approach hits its quality ceiling
Deterministic regex cleaning is fast, reproducible and cheap, but listening to full 18-minute engineering notes exposes three hard ceilings:
- Written Chinese vs. spoken Cantonese diglossia (
書面語粵讀): Even a strongzh-HKvoice sounds stiff when reading formal written articles verbatim. Words such as未能,便會,透過,以免,然而,並非and若要are grammatical Standard Written Chinese — natural to read with the eyes, yet stilted and tiring to hear for 20 minutes in Cantonese. - Literal reading of written English notation: Deterministic strippers cannot gracefully rewrite dense technical prose for the ear. Strings like
v4.13.0,2×–4×,>= 128 GB,SHA-256,mTLSor multi-parenthetical clauses ((see Section 3 — excluding legacy paths)) either read awkwardly or cause unnatural mid-phrase pauses. - No pronunciation memory or acoustic verification: Without a domain glossary and post-synthesis QA, a single mispronounced acronym (
Nginxread as"N-jinks"instead of"Engine-X", orJyutpingmangled by an English model) ships straight to R2 and gets cached for a year.
4. The sophisticated way: LLM & AI-agent spoken-language adaptation pipeline
To reach broadcast/podcast quality without sacrificing Cloudflare R2’s zero-egress edge economics, keep the runtime player and R2 cache layer unchanged, and insert a 5-stage AI-agent spoken-language adaptation pipeline at build/CI time between the Markdown source and TTS synthesis.
Source Article (.md / .mdx, EN + zh-hant)
│
▼ [Stage 1: Deterministic Structural Pre-Parser]
│ Splits H2 chapters; extracts numeric invariants, versions, URLs & proper nouns lockfile
▼ [Stage 2: Spoken-Language Adaptation Agent (LLM Writer)]
│ EN: written technical prose ──► crisp spoken briefing script
│ ZH: formal 書面語 ──► natural Hong Kong Spoken Cantonese (粵語口語) + preserved EN tech terms
▼ [Stage 3: Pronunciation Glossary & Prosody Annotator]
│ Applies pronunciation-glossary.json (Nginx → "Engine-X", heteronyms, EN/CJK boundary spacing, pause tags)
▼ [Stage 4: Independent Fidelity & Register Verifier Agent (Fail-Closed)]
│ Checks invariant retention (numbers/negations/entities) + register audit ──► PASS | REVISE | HUMAN-REVIEW
▼ [Stage 5: SOTA TTS + ASR Round-Trip QA + Immutable R2 Upload]
Qwen3-TTS / Fun-CosyVoice 3 / MiniMax 2.8 ──► Whisper/SenseVoice sanity check ──► R2 (en / yue-hk / zh)
Stage-by-stage design
- Stage 1 — Deterministic Structural Pre-Parser: Reuses our
buildAudiobookScript()chapter split, but also extracts an immutable fact lockfile per chapter containing every version number, latency bound, percentage, product name and negation (not,never,without,切勿,不會) so later LLM rewriting cannot silently hallucinate or invert technical claims. - Stage 2 — Spoken-Language Adaptation Agent (LLM Writer): Translates written structure into spoken rhythm without losing technical rigour:
- English (
en): Unpacks stacked parentheticals into short sequential sentences, expands symbols (2×–4×→"two to four times",>=→"at least"), and adds subtle spoken transitions when moving from prose to a table summary or code signpost. - Hong Kong Cantonese (
zh-hant→yue-hk): Rewrites Standard Written Chinese (書面語) into educated Hong Kong podcast/lecture Cantonese (粵語口語), keeping exact English engineering terms (Edge Cache,Workers AI,R2,mTLS) intact just as Hong Kong engineers naturally speak.
- English (
- Stage 3 — Pronunciation Glossary & Prosody Annotator: Applies a Git-tracked
pronunciation-glossary.jsonbefore synthesis:- Maps hard-to-guess tech terms to TTS-safe spellings or phoneme hints (
Nginx→"Engine-X",Kube→"Kube",JSON-LD→"J-S-O-N L-D"for engines that stumble on acronyms). - Inserts explicit spacing around inline English inside Cantonese (
喺 Cloudflare R2 度rather than喺CloudflareR2度) so bilingual tokenizers do not merge Hanzi and ASCII tones. - Annotates context-sensitive Chinese heteronyms (
破音字) and injects subtle pause markers or model-native prosody tags ([pause], punctuation lengthening) at long technical lists.
- Maps hard-to-guess tech terms to TTS-safe spellings or phoneme hints (
- Stage 4 — Independent Fidelity & Register Verifier Agent (Fail-Closed): Never let the rewriting LLM grade its own script. Mirroring our enterprise coding-agent verification discipline, an independent verifier pass checks two things:
- Deterministic invariant check: Every number, version string, benchmark score and technical proper noun in the Stage 1 lockfile still exists with identical polarity in the spoken script.
- Register audit (LLM-as-a-judge): Flags both residual stiff
書面語(並非,予以,然而,藉此) and overly casual street slang (超勁,搞掂曬) so the tone stays authoritative and natural. Any chunk failing after two rewrite attempts exits fail-closed (human-review) rather than publishing corrupted technical audio.
- Stage 5 — SOTA TTS Synthesis + ASR Round-Trip QA + Sidecar Caching:
- Synthesizes each verified chunk using Qwen3-TTS (
1.7B), Fun-CosyVoice 3 or MiniMax Speech 2.8 anchored to a clean 10-second reference voice clip per language/dialect (en,yue-hk, optionalzh-tw/zh-cn). - Optionally runs a fast ASR round-trip sanity check (
WhisperorSenseVoice) on the output MP3 to catch truncated final syllables, garbled English acronyms or tone hallucinations before promoting the artifact to R2. - Stores the approved spoken script in a versioned sidecar file (
*.speech.json) withscriptHash = hash(sourceChunk + promptVersion + glossaryVersion + dialect)and apinned: trueflag so human copy-edits survive automated rebuilds.
- Synthesizes each verified chunk using Qwen3-TTS (
Cantonese register calibration: side-by-side comparison
Getting Hong Kong Cantonese narration right requires hitting a tight register sweet spot — avoiding both robotic written-Chinese readouts and overly colloquial slang:
| Register tier | Actual text fed to TTS | Why it succeeds or fails in production |
|---|---|---|
Written source (書面語) |
若 Edge Cache 與 R2 均未命中,端點才會調用 Workers AI 即時合成並回寫快取,以免重複消耗每日免費配額。 |
Concise and formal on screen; serves as the canonical factual reference. |
Basic verbatim TTS (書面語粵讀) |
若 Edge Cache 與 R2 均未命中,端點才會調用 Workers AI 即時合成並回寫快取,以免重複消耗每日免費配額。 |
Sounds unnatural to the ear: constructions like 均未命中, 才會調用 and 以免 sound like a stiff news teleprompter rather than a human engineer explaining an architecture. |
| Overly casual slang (Anti-pattern) | 如果 Edge Cache 同 R2 都搵唔到喎,咁佢先會叫 Workers AI 即刻整條片出嚟,塞返落去免得嘥晒啲免費額度啦。 |
Breaks institutional trust: filler particles (喎, 啦) and sloppy nouns (整條片) undermine technical credibility for university and enterprise listeners. |
Calibrated Professional Cantonese (專業粵語口語) |
如果 Edge Cache 同 Cloudflare R2 都搵唔到對應音檔,端點先至會呼叫 Workers AI 即時合成,跟住自動寫返入 R2 同邊緣快取,咁之後再播就唔使重複扣減每日免費配額喇。 |
Broadcast sweet spot: natural Cantonese grammar (如果…都搵唔到, 先至會, 跟住, 寫返入, 咁之後…就唔使…喇), clean spacing around Edge Cache, Cloudflare R2 and Workers AI, and 100% technical precision preserved. |
Agent contract, glossary & verifier schema
In CI (build:audio:agent), each chunk flows through a structured JSON contract so human reviewers and automated gates inspect the exact same intermediate artifact before paying for GPU or API synthesis:
{
"articleKey": "zh-hant/engineering/bilingual-audiobook-tts-architecture",
"chunkId": "1-2",
"dialect": "yue-hk",
"promptVersion": "yue-hk-tech-v3",
"glossaryVersion": "2026-12-06",
"pinned": false,
"sourceText": "若 Edge Cache 與 R2 均未命中,端點才會調用 Workers AI 即時合成並回寫快取,以免重複消耗每日免費配額。",
"spokenText": "如果 Edge Cache 同 Cloudflare R2 都搵唔到對應音檔,端點先至會呼叫 Workers AI 即時合成,跟住自動寫返入 R2 同邊緣快取,咁之後再播就唔使重複扣減每日免費配額喇。",
"invariants": {
"entities": ["Edge Cache", "R2", "Workers AI"],
"numbers": [],
"negationPreserved": true
},
"glossaryApplied": {
"Nginx": "Engine-X",
"R2": "R2",
"mTLS": "M-T-L-S"
},
"verifier": {
"status": "pass",
"writtenResidualFlags": [],
"registerScore": 4.8
}
}
Extending /audiobook-manifest.json without breaking the player
Notice how cleanly this upgrades our existing runtime: instead of changing how ArticleAudiobook.svelte fetches or buffers audio, the build simply swaps chunk.text (or hashes per dialect track audiobook/{lang}/{section}/{slug}/{dialect}/{chunkId}-{hash}.mp3) when generating /audiobook-manifest.json from verified *.speech.json sidecars. Every R2 immutable cache header, prefetchNext() preload, MediaSession hook and Web Speech API fallback continues to work unchanged — and when the user hits Browser fallback, the browser’s own Sin-ji (zh-HK) system voice immediately sounds dramatically more natural because it is reading spoken Cantonese rather than written prose.
5. Architecture decision matrix and production rollout checklist
| Tier | Architecture | English quality | Cantonese (zh-HK) quality |
Ongoing monthly cost (after build) | Best suited for |
|---|---|---|---|---|---|
| Tier 1: Basic Free-Tier Edge (current default) | cleanMarkdownForSpeech + /api/tts + R2 + Deepgram Aura-2 (en) + Web Speech (zh-hant) |
High (natural neural EN) | OS-dependent (zh-HK browser voice reading written prose) |
$0 (Cloudflare Free plan + R2 10 GB free tier) | Launching fast with zero infrastructure or external voice bills |
| Tier 2: Basic Bilingual Pre-Gen R2 | cleanMarkdownForSpeech + npm run build:audio via Inworld TTS-2 or local Qwen3-TTS / CosyVoice 3 → R2 |
High | Good phonetic accuracy, but formal 書面語 cadence |
$0 (local GPU batch) or ~$13.50 one-time API / 30 articles | Consistent cross-device mobile/desktop Cantonese audio on a tight budget |
| Tier 3: Agent-Adapted Bilingual (recommended SOTA) | 5-stage LLM adaptation (書面語 → 粵語口語) + Glossary + Verifier + Qwen3-TTS / MiniMax 2.8 + ASR QA → R2 |
Broadcast-grade | Native Hong Kong podcast/lecture Cantonese with crisp code-switching | $0 R2 runtime + pennies per article edit at CI/build time | Flagship engineering blogs, university courses, bilingual NGO portals |
| Tier 4: Air-Gapped / Sovereign Audio | Local Qwen4-35B-A3B / Gemma 4 adaptation + Apache 2.0 Qwen3-TTS / CosyVoice 3 → internal MinIO/S3 |
Broadcast-grade (zero external egress) | Native HK Cantonese & Mandarin (zero external egress) | Server power & depreciation only | Regulated hospitals, defence labs and clinical biotech enclaves |
For teams implementing Tier 4 on-premise voice pipelines alongside local coding and RAG workloads, see our hardware sizing and zero-egress playbook in Air-Gapped Local AI Inference: Hardware Economics, Open Models and Zero-Egress Architecture.
Production rollout checklist
- Enforce a closed build-time manifest: Never synthesize arbitrary
textquery parameters at runtime; validate(article, chunk, hash)against a compiled allowlist plusSec-Fetch-Site/Origin/Refererchecks and per-IP rate limits. - Hash by
(lang, dialect, spokenText): Include the dialect code (en,yue-hk,zh-tw) inside your cache key (audiobook/.../{chunkId}-{hash}.mp3) so immutable 1-yearCache-Controlheaders never serve stale prose after an edit or glossary update. - Separate English and CJK chunk ceilings: Keep English chunks around 1,000–1,200 characters and CJK chunks around 500–600 characters (weighting inline Latin technical words) to balance latency, prefetch timing and TTS context stability.
- Harden the browser Web Speech fallback: Split chunks into 120–220 character utterances so mobile Safari and Chrome do not drop long synthesis queues, and rank
zh-HK/yue-HKvoices ahead ofzh-TWand genericzh. - Audit open-weight TTS licenses before production: Prefer Apache 2.0 checkpoints (
Qwen3-TTS,Fun-CosyVoice 3,Kokoro-82M) for unrestricted commercial and institutional self-hosting; flag revenue-capped (Fish Audio>$500k) or custom (IndexTTS 2) licenses with legal counsel first. - Lock Cantonese register + bilingual spacing rules: Calibrate your LLM adapter away from both stiff
書面語and sloppy slang, add explicit spaces around English technical tokens inside Hanzi clauses, and versionpronunciation-glossary.jsonin Git. - Gate synthesis with independent verification + ASR QA: Pair a deterministic invariant checker + independent register verifier before synthesis with an automated ASR round-trip check afterward — only promoting verified MP3s into production R2 storage.
Related engineering notes: Enterprise Coding Agents: Harness Discipline, pstack and Formal Verification (TDD, TLA+ & Lean 4), Air-Gapped Local AI Inference: Hardware Economics, Open Models and Zero-Egress Architecture, and Harness Engineering: Evaluation-Driven Testbeds for Frontier AI Agents.
Building an AI agent or assistant?
We design agent architectures, evaluation harnesses and secure tool access for universities, NGOs and SMEs — model-agnostic across Claude, Gemini, GPT, Grok and open-weight models, hosted where your data policy requires.