Gemini TTS Parent Voice Cloning & 300 DPI Print-to-Web Boardbook Pipeline
When building a peekaboo and hidden-object picture book for 12-to-24-month-old toddlers, two engineering requirements shaped every architectural decision from day one. First, the child should hear their own mother's and father's warm voices rather than a generic studio narrator. Second, the physical 300 DPI print boardbook and the NFC-triggered mobile sound remote and web boardbook had to stay lockstep synchronized through a Single Source of Truth (SSOT) manifest.
Turning that vision into a working pipeline turned out to be far harder than calling a text-to-speech endpoint. Recording parents in expressive, high-pitched "storytime" cadence immediately tripped gemini-3.8-flash-tts's child-voice safety filter (FINISH_REASON_INPUT_VR_TAKEDOWN). Standard Korean grapheme input stumbled over storytelling liaison rules and nickname-dependent grammatical particles. On the visual and print side, dense backgrounds overwhelmed toddler perception while headless Chromium silently reused stale image caches when generating print PDFs.
This post walks through the production architecture behind the AI Voice Cloning & Print-to-Web Interactive Boardbook Studio: ① eliminating VR_TAKEDOWN false positives with one-take declarative chest-voice splitting, ② Korean standard pronunciation G2P normalization and 3-tier prosody across 39 clips per speaker, ③ 70–90% polygon occlusion with +30% letterbox-inverted touch hit-testing, and ④ cache-busted 300 DPI dual PDF builds paired with a low-glare OLED dark sound remote.
1. Solving VR_TAKEDOWN False Positives via One-Take Declarative Splitting
In our earliest prototype, parents recorded 20 seconds of reference audio exactly the way they would read to a toddler—raising pitch, stretching vowels, and exaggerating onomatopoeia. Almost every attempt failed either during POST /v1beta/voices enrollment or initial synthesis verification with FINISH_REASON_INPUT_VR_TAKEDOWN.
Key Takeaway: Gemini Voice Replication's safety classifier flags high fundamental-frequency pitch spikes (
F0 > 350 Hz) and Infant-Directed Speech ("parentese") contours inside reference samples as potential unauthorized minor voice cloning. Worse, recording thesourcereference and mandatoryconsentstatement on separate days or at different mic distances introduces room-tone mismatch that degrades speaker verification accuracy.
1.1. Adult Chest-Voice Declarative + 3s Silence + Consent One-Take Spec
The permanent fix was decoupling timbre capture from expressive acting. Reference recordings now capture only a calm adult chest-voice fingerprint, while all warm, playful storytelling prosody is delegated strictly to synthesis-time speechMetadata.style prompting.
- Unified Preprocessing Chain: Apply an
80–85 Hzhigh-pass filter to remove room rumble, light de-essing around6.5 kHz, a gentle220 Hz -2 dBmud cut, and a1.8:1soft compressor to normalize vocal body. - Single Continuous One-Take Capture: Without stopping the recorder or moving off-axis from the microphone, the parent records
[Part 1: 20–23s calm declarative adult prose] → [3 seconds of silence] → [Part 2: mandatory Korean voice-consent sentence]. - Zero-Click Splitting (
faster-whisper+ffmpeg silencedetect): Word-level timestamps locate the exact onset of the consent opening token ("나는"), andsilencedetectfinds the exact midpoint of the preceding 3-second quiet window. Cutting at that midpoint with15msfades and0.25ssilence padding yields click-free24000 Hz, Mono, 16-bit PCMWAV pairs.
# ~/workspace/storybook-studio/scripts/audio/split_onetake_ref.py (Zero-click one-take splitter)
import re
import subprocess
from pathlib import Path
from faster_whisper import WhisperModel
def split_onetake_reference(raw_audio: Path, out_dir: Path, speaker: str = "dad") -> tuple[Path, Path]:
out_dir.mkdir(parents=True, exist_ok=True)
norm_wav = out_dir / f"{speaker}_onetake_24k.wav"
subprocess.run(
["ffmpeg", "-y", "-i", str(raw_audio), "-ar", "24000", "-ac", "1", "-c:a", "pcm_s16le", str(norm_wav)],
check=True, capture_output=True,
)
# 1. Locate the opening token of the Korean consent phrase ("나는") via word timestamps
wm = WhisperModel("mobiuslabsgmbh/faster-whisper-large-v3-turbo", device="cpu", compute_type="int8", local_files_only=True)
segments, _ = wm.transcribe(str(norm_wav), language="ko", word_timestamps=True)
consent_start_sec: float | None = None
for seg in segments:
for w in (seg.words or []):
token = re.sub(r"\s+", "", w.word or "")
if "나는" in token and w.start >= 12.0:
consent_start_sec = float(w.start)
break
if consent_start_sec is not None:
break
if consent_start_sec is None:
raise RuntimeError("Failed to detect consent phrase opening token ('나는').")
# 2. Compute exact midpoint of the preceding 3s silence window for a zero-click cut
sd = subprocess.run(
["ffmpeg", "-i", str(norm_wav), "-af", "silencedetect=noise=-40dB:d=1.2", "-f", "null", "-"],
check=True, capture_output=True, text=True,
)
starts = [float(m.group(1)) for m in re.finditer(r"silence_start:\s*([0-9.]+)", sd.stderr)]
ends = [float(m.group(1)) for m in re.finditer(r"silence_end:\s*([0-9.]+)", sd.stderr)]
cut_sec = consent_start_sec - 0.35
for s_t, e_t in zip(starts, ends):
if e_t <= consent_start_sec + 0.2 and (e_t - s_t) >= 1.2:
cut_sec = (s_t + e_t) / 2.0
# 3. Export 24kHz Mono PCM pair with 0.25s boundary padding and 15ms fade-in
src_wav = out_dir / f"{speaker}_source_24k.wav"
cons_wav = out_dir / f"{speaker}_consent_24k.wav"
trim_pad_af = (
"silenceremove=start_periods=1:start_silence=0.05:start_threshold=-40dB,"
"areverse,silenceremove=start_periods=1:start_silence=0.05:start_threshold=-40dB,areverse,"
"afade=t=in:st=0:d=0.015,adelay=250|250,apad=pad_dur=0.25"
)
for start_t, end_t, dest in [("0", f"{cut_sec:.3f}", src_wav), (f"{cut_sec:.3f}", None, cons_wav)]:
cmd = ["ffmpeg", "-y", "-i", str(norm_wav), "-ss", start_t]
if end_t:
cmd.extend(["-to", end_t])
cmd.extend(["-af", trim_pad_af, "-ar", "24000", "-ac", "1", "-c:a", "pcm_s16le", str(dest)])
subprocess.run(cmd, check=True, capture_output=True)
return src_wav, cons_wav
Before invoking POST /v1beta/voices, a pre-flight validation gate verifies that the reference audio remains within adult chest-voice pitch limits (F0 <= 350 Hz) and that back-transcription of the consent clip matches the mandatory script. Returned voice handles are cached under speaker slots such as VOICE_PROFILE_MOM and VOICE_PROFILE_DAD in config/gemini_voices.json, while API credentials stay isolated in runtime environment variables (YOUR_API_KEY).
2. Single-SSOT Architecture, Korean G2P Preprocessing, and 3-Tier Prosody Across 39 Clips
Once voice enrollment succeeded reliably, the next challenge was making Korean storytelling speech sound genuinely natural while keeping page indices identical across print, audio, and web targets. The diagram below shows how a single SSOT manifest fans out into the audio/remote pipeline and the occlusion/300 DPI print pipeline.
2.1. Korean Standard Pronunciation G2P Layer and <short pause> Breath Control
Toddler picture-book scripts behave differently from news copy: they are packed with mimetic words, native Korean counting numbers, and grammatical particles attached dynamically to a child's nickname. If a nickname ends with a final consonant (batchim) versus an open vowel, Korean vocative, subject, and comitative particles all change form—and naive grapheme input frequently misreads liaison or fortition boundaries.
To prevent robotic pronunciation before hitting the synthesis API, we inserted a Korean G2P (Grapheme-to-Phoneme) preprocessing stage with three responsibilities:
- Final-Consonant (Batchim) Particle Resolution: Inspects the Unicode Hangul syllable coda of the configured child nickname and automatically harmonizes vocative (
아/야), nominative (이/가), and comitative (이랑/랑) particles. - Selective Standard Pronunciation Correction: Flags high-risk compound numerals and onomatopoeia against a standard pronunciation lexicon without rewriting entire sentences phonetically—preserving natural phrasal intonation while fixing jagged liaison.
- Priority-Ranked
<short pause>Injection: Normalizes ellipses (...,…) and tildes (~), then injects at most5<short pause>breath markers per clip ranked by expressive priority: exclamations ("까꿍!"/ peekaboo, weight100) → child callout (95) → ellipsis (85) → internal sentence breaks (75) → comma boundaries inside clauses longer than 22 characters (40).
2.2. 3-Tier speechMetadata.style Prosody and 39-Clip Audio Mastering
Across 13 total pages (cover pageIndex: 0 plus 12 hidden-object spreads), each page generates three interactive clips (prompt, hint, and found). That produces 39 clips per speaker—or 78 mastered M4A assets for a two-parent edition—using distinct style directives per interaction state.
# ~/workspace/storybook-studio/scripts/audio/gemini_tts_synth.py (3-tier prosody & G2P synthesis)
import json
import os
import urllib.request
ACTING_STYLES = {
"prompt": (
"Warm parent storytelling tone reading a picture book with a toddler on their lap; "
"gentle smile in the voice, playful curiosity, softly rising inflection on the closing question."
),
"hint": (
"Cozy, reassuring storytelling tone whispering a playful secret clue into a toddler's ear, "
"articulating clearly with unhurried pauses between phrases."
),
"found": (
"Bright, joyful celebration greeting 'Peekaboo!' when the hidden character is discovered, "
"followed by warm praise; lively yet soft enough never to startle sensitive toddler ears."
),
"bedtime": (
"Lower-pitched, slower, softly hushed lullaby storytelling tone designed to wind down "
"after playtime and gently ease a toddler toward sleep."
),
}
def synthesize_story_clip(
normalized_ko: str,
clip_type: str,
speaker_profile: str = "PARENT_VOICE_ID",
) -> bytes:
api_key = os.environ.get("GEMINI_API_KEY", "YOUR_API_KEY")
payload = {
"contents": [{
"role": "user",
"parts": [{
"text": normalized_ko, # Korean G2P normalized text with <short pause> breath cues
"speechMetadata": {"style": ACTING_STYLES[clip_type]},
}],
}],
"generationConfig": {
"responseModalities": ["AUDIO"],
"speechConfig": {"voiceConfig": {"voice": speaker_profile}},
},
}
req = urllib.request.Request(
f"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash-tts:generateContent?key={api_key}",
data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(req, timeout=60) as resp:
return resp.read()
Every synthesized clip passes through an automated mastering and quality verification gate engineered specifically for toddler hearing safety and snappy touch responsiveness:
| Post-Processing Stage | Key Parameters & Thresholds | Engineering Purpose |
|---|---|---|
| Leading Silence Trim | found leading silence <= 50 ms (lead_pad = 18 ms) | Fires "Peekaboo!" immediately on tap with zero sluggish vocal lag |
| Toddler-Safe SFX Ducking | Sound effects -19 to -24 dB, ducked -22 dB under speech | Keeps playful sound cues subordinate to the parent's voice clarity |
| 2-Pass EBU R128 Loudness | I=-16 LUFS, TP=-1.5 dBTP, 44.1 kHz / 128k M4A | Eliminates abrupt peak spikes across devices and embeds +faststart atoms |
| Whisper Jamo QA Gate | NFD Jamo similarity sim >= 0.78, tail >= 0.62, onset check | Auto-quarantines clipped endings or slurred opening syllables for resynthesis |
3. 70–90% Occlusion Geometry and +30% Letterbox-Inverted Multitouch
Great audio cannot save an interactive boardbook if the visual composition or touch mechanics fight a toddler's motor skills. Every 1376×768 illustration and its web hit-testing layer enforce three quantitative geometry rules.
- Visual Clutter Restraint & 3-Zone Spatial Rotation: Toddlers between 12 and 24 months lose figure-ground separation when small props share the same saturation as the hidden character. Background objects are strictly rationed, and hiding spots rotate evenly across left, right, and upper-center zones so the child cannot game the book by tapping the lower center of every page.
- Foreground Polygon Occlusion Converged to
70–90%Visibility: Characters are partially tucked behind foreground objects defined via polygon masks (occlusionPolygons,1.5pxedge feather) inscenes.yaml. A local compositor measures the post-mask alpha ratio (alpha >= 32) and enforcesvisibleRatiostrictly inside0.70–0.90—hidden enough to feel like peekaboo, visible enough for a one-year-old to recognize. Position adjustments run throughcompose-direct -> finalizelocally at zero generative-image credit cost. +30% touchHitbox&object-fit: containLetterbox Inversion: The manifest expands each character's visible bounding box by30%on all sides intotouchHitboxNormalized. Because mobile phones and tablets render1376×768illustrations insideobject-fit: containviewports with arbitrary horizontal or vertical letterbox bars, pointer coordinates are algebraically inverted back into normalized[0, 1]illustration space before hit evaluation.
// ~/workspace/storybook-studio/web_remote/boardbookHitTest.ts (Letterbox inversion & palm rejection)
export interface NormalizedRect {
x: number
y: number
width: number
height: number
}
export function clientPointToIllustrationNormalized(
clientX: number,
clientY: number,
containerRect: DOMRect,
naturalW = 1376,
naturalH = 768,
): { nx: number; ny: number; insideImage: boolean } {
const containerRatio = containerRect.width / containerRect.height
const imageRatio = naturalW / naturalH
let renderW = containerRect.width
let renderH = containerRect.height
let offsetX = containerRect.left
let offsetY = containerRect.top
if (containerRatio > imageRatio) {
renderH = containerRect.height
renderW = renderH * imageRatio
offsetX = containerRect.left + (containerRect.width - renderW) / 2
} else {
renderW = containerRect.width
renderH = renderW / imageRatio
offsetY = containerRect.top + (containerRect.height - renderH) / 2
}
const nx = (clientX - offsetX) / renderW
const ny = (clientY - offsetY) / renderH
return { nx, ny, insideImage: nx >= 0 && nx <= 1 && ny >= 0 && ny <= 1 }
}
export function evaluateBoardbookPointerDown(
event: PointerEvent,
imgEl: HTMLImageElement,
hitbox: NormalizedRect,
): 'found' | 'miss' | 'ignored' {
const { nx, ny, insideImage } = clientPointToIllustrationNormalized(
event.clientX,
event.clientY,
imgEl.getBoundingClientRect(),
imgEl.naturalWidth || 1376,
imgEl.naturalHeight || 768,
)
if (!insideImage) return 'ignored'
const hit =
nx >= hitbox.x &&
nx <= hitbox.x + hitbox.width &&
ny >= hitbox.y &&
ny <= hitbox.y + hitbox.height
if (hit) return 'found'
// Reject accidental full-palm rests common with toddlers (contact box > 56px)
if ((event.width || 0) > 56 || (event.height || 0) > 56) return 'ignored'
return 'miss'
}
With full-palm contacts (> 56px) filtered out, three consecutive valid misses (debounced at 300ms) illuminate a subtle visual hint ring around the hiding spot and automatically play the second-tier hint clip—guiding the toddler to a self-directed discovery.
4. Low-Glare OLED Dark Sound Remote, NFC Deep Links, and iOS HTTP 206 Range
One of the highest-value real-world scenarios is reading the physical paper boardbook together while a smartphone acts solely as a silent companion sound remote. A bright white web UI sitting beside the book instantly steals a toddler's gaze away from the printed pages.
- Low-Stimulus OLED Darkroom UI: The remote renders on a matte-black
#16181Bsurface using<1%#E8661Asignal accents to minimize screen luminance. Everything fits cleanly inside a390×844mobile viewport—a[Mom's Voice]/[Dad's Voice]dynamic switcher plus[Prompt],[Hint], and[Peekaboo!]triggers—with zero text overlays on illustrations. AudioContext<100 msTrigger & NFC Deep Linking: Entering a spread pre-decodes its active M4A audio intoAudioContextmemory buffers so button taps fire in under100 ms. Tapping a paper page's embedded NFC tag (https://storybook-remote.example.com/?scene=03&clip=prompt) jumps straight to that scene and clip, then cleans up query parameters viahistory.replaceState.- iOS Safari HTTP
206Range &./Relative Paths: Mobile Safari<audio>playback stalls silently unless the media server answers its initialRange: bytes=0-1probe with a compliant206 Partial Content,Accept-Ranges: bytes,Content-Range, andAccess-Control-Expose-Headers. To survive subpath reverse-proxy deployments cleanly, every static asset and API request is normalized to./relative paths.
5. Single-SSOT 300 DPI A4 Landscape Dual PDF Builds with Cache Busting
While the web boardbook and sound remote consume scenes_manifest.json and audio_manifest.json, the print publishing pipeline reads the exact same SSOT to produce two press-ready 300 DPI PDFs. Early in development, one particularly insidious bug surfaced: after tweaking a character's occlusion mask and overwriting the scene PNG, headless Chromium's HTML-to-PDF renderer kept printing the old cached PNG into the new PDF.
- Destructive Pre-Clean & Forced 300 DPI Regeneration: Every build begins by removing stale PDF outputs with
rm -fand invokingupscaleCleanPrintPages(force=true)to regenerate full A4 landscape 300 DPI plates (297×210 mm,3508×2480 px) unconditionally. file://...?t=<epoch_ms>Cache Busting: Every local image URL injected into Chromium's print HTML receives a fresh millisecond epoch query string (?t=1764720000000), completely neutralizing Chromium's internal resource cache.- Dual Edition Output & Full-Page QA Contact Sheet: A single run builds both the Picture-Only Boardbook (
13p, text-free)—ideal for parent improvisation alongside the sound remote—and the Storybook Edition (15p) complete with single-line narration scripts and a parent answer/reading guide appendix. Immediately afterward, the builder rasterizes every printed page back intoall_12_scenes_qa_sheet.pngto audit margins and trim marks.
Key Takeaway: macOS Preview.app and Adobe Acrobat also cache open file buffers by filesystem path when a PDF is overwritten in place. Always fully quit (
Cmd+Q) the PDF viewer before reopening a freshly compiled print artifact to verify the true latest output.
Wrapping Up: Bridging a Toddler's Gaze and Parents' Voices in One Data Model
Integrating gemini-3.8-flash-tts voice cloning, Korean G2P normalization, 70–90% occlusion geometry, 300 DPI dual print PDFs, and a low-glare OLED sound remote around a single SSOT surfaced four engineering lessons:
- Decouple timbre capture from vocal acting for reliable voice cloning: Calm adult chest-voice one-take recordings (
F0 <= 350 Hz) paired with zero-click silence splitting eliminatedVR_TAKEDOWNfalse positives entirely, whilespeechMetadata.styledelivered consistent 3-tier prosody across all 39 clips. - Pair Korean G2P preprocessing with back-transcription QA: Resolving batchim-dependent particles, normalizing high-risk pronunciation, capping
<short pause>cues, and gating synthesis with Whisper NFD Jamo verification (sim >= 0.78) caught slurred onsets and truncated tails automatically. - Design toddler touch physics around geometry, not guesswork: Converging polygon occlusion to
70–90%, expanding touch targets by+30%, invertingobject-fit: containletterbox math, and rejecting> 56pxpalm contacts made the web boardbook genuinely playable by 12-to-24-month-olds. - Lock print and digital editions together with SSOT manifests and hard cache busting: Combining
file://...?t=<epoch_ms>300 DPI PDF regeneration with./-relative,206 Partial Content-compliant dark sound remotes guarantees that paper pages and voice triggers never drift out of sync.
Full architecture specifications and deliverable breakdowns are also documented on the AI Voice Cloning & Print-to-Web Interactive Boardbook Studio project page.