# KaziVoice architecture

The active application is `voicellm.api.app:app`. `kazivoice serve` reads validated settings and starts Uvicorn. Static HTML, JavaScript, and CSS resolve relative to the installed package, while optional audio samples and temporary storage are configurable.

```mermaid
flowchart LR
    Client --> Middleware[Tracing, request deadline, rate limit]
    Middleware --> API[FastAPI routes]
    API --> Normalize[Swahili normalization]
    Normalize --> Cache[Audio LRU cache with TTL]
    Cache --> Engines[VITS or Edge]
    Engines --> Master[EQ, limiting, peak normalization]
    Master --> Encode[FFmpeg encoding]
    Encode --> Cache
    Cache --> Client
```

Normalization handles Unicode whitespace, hybrid Sheng forms, abbreviations, regional currencies, dates, Swahili clock times, Kenyan phone numbers, percentages, decimals, ordinals, grouped integers, optional phonetic substitutions, and symbols. The older `swahili_textnorm` package delegates to this implementation.

Eight curated Hugging Face VITS model choices are loaded lazily, with bounded resident-model capacity per worker. Long scripts are chunked without stripping African diacritics. Swahili retains the regional text-normalization pipeline; other voice languages preserve Unicode without Swahili number substitutions. Inference follows the configured CPU/CUDA device and CPU thread count. VITS inference, mastering, and encoding execute in a worker thread. Edge receives speech over its async network client, then sends decoding, mastering, and encoding to a worker thread. Dialogue decoding, resampling, and final encoding also execute off the request event loop.

Both JSON and binary synthesis use the same cache path. The key includes normalized text, voice ID, output format, sample rate, normalization flags, mastering profile, warmth, clarity, and reverb. Disabling the cache bypasses reads and writes. Each worker owns its cache, engine objects, rate limits, and telemetry.

The broadcast profile applies high-pass and peaking filters, subtle early reflection, soft limiting, and peak normalization. Podcast warmth adds low-mid emphasis and reduces clarity emphasis and reflection. Telephony uses a voiceband filter; raw neural output bypasses mastering. No LUFS measurement or G.711 encoding is claimed. Subtitle times are estimated from text weights, not forced alignment.

`/readyz` requires the configured default backend to be healthy and, for VITS, the actual default model to be loaded. Responses distinguish loaded model identifiers from registered voice profiles. Edge's remote catalog check has a five-second deadline and a thirty-second cache. `/metrics` exposes JSON operational statistics, subject to the metrics switch.

HTTP and individual synthesis calls have the configured deadline. FFmpeg is separately bounded and killed on timeout. An already running PyTorch worker thread may complete after cancellation; Python cannot forcibly terminate it. Latency depends on model, text length, CPU/GPU, worker count, model warmup, cache hit rate, encoding, and network conditions. Use `kazivoice benchmark` and representative workloads to obtain measurements.

Zonos request preparation and voicepack processing are separate utilities. The bridge does not enable a new trained acoustic model, and the builder never generates random placeholder embeddings.

The optional VoiceStudio API adapter uses an independently operated backend and an explicit language allowlist. It is disabled by default. See [Africa engine details](AFRICA_ENGINE.md) for capacity, supported markets and model terms.

## OmniVoice and saved references

`engines/omnivoice.py` adds nine language profiles and calls `omni_worker/app.py`
over a Unix socket; the API does not import the heavy OmniVoice runtime. The
worker loads pinned local assets once and serializes synthesis with a bounded
in-memory prompt cache. Reference-conditioned speech uses a private WAV and
its exact transcript, without a downloaded ASR model.

`core/clones.py` validates uploads and stores voices under hashed workspace
owners. `core/omni_jobs.py` queues user-submitted renders, persists job metadata
in SQLite and applies KaziVoice mastering, transcoding and estimated captions.
`api/v1/clones.py` checks workspace access on saved voices, references and jobs.
This queue currently requires one API process. The studio uses random workspace
keys and polls for results. See [the OmniVoice guide](OMNIVOICE_CLONING.md) for
retention, quotas, restart behavior and deployment boundaries.
