Speech generation and voice creation
Voice generation is part of the backend API platform. It turns text or source speech into an audio take under a chosen voice and speech engine. The system checks the request, resolves the voice and language, selects a usable local compute target, produces speech, and returns either a saved take or a live preview. Voice profiles keep clone and design choices stable across requests. Engine routing, model compute, and OmniVoice inference connect this flow to engine placement and model execution.
Generation request
The generation request is the main path for interactive text-to-speech. It combines text, language, voice identity, style controls, quality settings, and output preferences before one selected engine produces audio.
Request lifecycle
The native POST /generate request in backend/…/generation.py accepts multipart form data. The OpenAI-compatible POST /v1/audio/speech request presents the same product through a familiar JSON contract. Both paths use the same engine and voice rules, while the native path also supports saved history and preview streaming.
When the system handles a native request, it follows this sequence:
flowchart TD
A[Text and voice request] --> B[Validate request and choose engine]
B --> C[Check voice conditioning and local compute target]
C --> D[Resolve profile or reference voice]
D --> E[Resolve language and prepare text]
E --> F[Load engine within its load budget]
F --> G[Produce and process audio]
G --> H{Delivery mode}
H --> I[Stream preview or live audio]
H --> J[Save WAV and generation history]
The selected engine and local compute target are checked before model work starts. The request loads the selected engine under a separate readiness budget, then gives speech production its own time budget. The engine remains in use for the full render, so cleanup cannot unload it while the request or a shared batch is still running.
The request checks voice conditioning before expensive model work. A reference clip requires an engine that can clone a voice. A design instruction requires an engine that can create a voice from a description. Emotion text, an emotion vector, or a line-level emotion direction also requires an engine that declares emotion support. These checks prevent an engine from silently ignoring a voice or expression control.
The request normalizes text once after the final language and profile values are known. The preparation uses NFC text form, removes unsafe control characters, keeps speech markup intact, and can turn safe numbers, times, percentages, ranges, and known abbreviations into spoken words for the selected language. It is conservative and idempotent. The OMNIVOICE_TEXT_NORMALIZATION override can disable it. If preparation fails, the raw text continues to synthesis. Pronunciation dictionary entries and inline overrides run after normalization so explicit user respellings remain final.
Long text can split at sentence or clause boundaries. The system joins the parts with a short crossfade. Inline pause markers and optional paragraph gaps add silence between spoken spans. SSML-lite span directions can also change the speed of one span. Each path uses the same assembly rules so a preview and a saved take represent the same request. A request seed is reused for every part of one take, which keeps a designed speaker stable across chunks.
The common TTS backend rejects empty or non-speakable input as a client input error. Batch generation validates the complete language input before it produces partial audio. Regional language names are reduced to the base language that engines understand at the shared engine boundary. A render holds the selected engine in use until its work finishes, including direct voice conversion and batch work, so memory cleanup cannot unload an engine during a batch or other shared generation call.
Profile conditioning is shared by native generation and voice conversion. A profile kind selects stored reference audio or a design instruction. A locked take takes priority. Request values fill gaps without replacing stored values that the request does not override. A changed design instruction or seed represents a new design rather than a re-render of the old saved sample. A missing transcript can be created from the reference and saved for later requests.
References: backend/…/generation.py• L330-493 backend/…/generation.py• L1675-1889 backend/…/generation.py• L1921-2058 backend/…/tts_backend.py• L204-247 backend/…/tts_backend.py• L5275-5331
Request controls
The request can set language, speed, target duration, sampling quality, a seed, denoise behavior, an effect preset, output bit depth, pronunciation behavior, expressive emotion controls, paragraph gaps, long-text joining, and a saved Voice Design draft. It can also select a built-in preset voice when the chosen engine provides one and does not use a cloning reference. The system resolves the final language before it prepares text. It applies pronunciation controls after normalization and before chunking, so native engines and alternate engines receive the same prepared text.
Emotion can be expressed as text or as a fixed vector. A line-level emotion direction is another text source used by supported workflows. These forms cannot conflict, and an emotion strength applies only to descriptive emotion text. The selected engine must support emotion controls. Invalid vector shape, values, or strength fail before model work starts rather than being ignored.
Normalization accepts display language names and language codes. It leaves ambiguous forms such as IDs, product codes, ranges with uncertain meaning, and leading-zero values unchanged. It does not rewrite bracketed voice, pause, rate, or inline pronunciation markup. This protects the small speech grammar while improving common written forms.
A request can supply a pronunciation dictionary and inline pronunciation overrides. These controls describe the speaker's intended pronunciation rather than one engine's private settings. They apply after text normalization and before chunking.
The request seed is made explicit when the caller and profile provide none. The seed then travels with the render and the saved take, which lets clients repeat a result or keep its seed for later use. A Voice Design draft is checked and re-derived on the server before it is stored as take metadata. It helps the client reopen the same design without changing the synthesis input.
References: backend/…/generation.py• L227-274 backend/…/generation.py• L1787-1950 backend/…/generation.py• L1805-1849 backend/…/generation.py• L2106-2295 backend/…/generation.py• L316-345 backend/…/tts_backend.py• L289-322
Engine routing
Engine routing decides which speech engine handles a request and whether that engine can run on the selected local machine. It exposes engine limits and placement results instead of silently changing the engine or falling back to an unsuitable device. See engine routing and model compute for the wider placement view.
Engine choice
An engine is the speech system that turns prepared text and voice conditioning into audio. The active engine comes from the application setting or OMNIVOICE_TTS_BACKEND. Native requests can override it with engine. OpenAI-compatible requests use model as the engine selector.
The engine catalogue reports readiness and capability before a request starts. Its metadata tells callers whether an engine supports reference cloning, delivery-preserving voice conversion, voice design, emotion controls, language coverage, reference length rules, preset voices, hardware targets, process isolation, and model-specific choices. It also reports the effective device and routing state for the current host. The catalogue gives the UI a setup hint, install action, documentation link, or engine document when an engine is unavailable. Available engines can also carry an upgrade hint. If an availability probe fails, the catalogue keeps the other engine rows available. Status text is scrubbed before it crosses the API boundary, including credential-shaped model-host tokens. A request that names an unknown or unavailable engine stops with a clear client error.
Some engine identifiers represent a family of models. In that case, the catalogue exposes the active model and the models that support a capability. This lets a user fix a cloning or language mismatch by changing the model without changing the whole engine.
Generation entry points use one shared resolution path. It checks the configured engine, its licence acceptance, availability, host routing, and any cloning requirement before it returns a cached live engine. Licence rejection happens before the current engine is released, so a failed switch does not interrupt a working engine. Voice conversion has a separate capability-aware selection path when the active engine cannot convert recordings directly. Neither path silently substitutes a different speech engine for an ordinary text render.
The selected engine is reused while it is active. Before a cold render, the service gives model loading its own readiness budget. Recognized first-use model download failures can retry within a bounded budget, including recovery from a closed shared model-download client. When the engine changes, the previous engine is released so large models do not remain resident together. A model-only change also releases the old model for engines that host several model choices. Engines that stay unused can later be unloaded, while an engine in use remains protected until its work finishes.
References: backend/…/tts_backend.py• L4396-4579 backend/…/tts_backend.py• L4936-5025 backend/…/tts_backend.py• L5275-5331 backend/…/generation.py• L2045-2179
Hardware target
For local work, the routing check compares the selected engine with the host's compute capabilities. It reports accelerated use, CPU use, or unavailability before audio is produced. It also exposes a rough device-memory floor when an engine has one, so a host can be marked under-provisioned before a long render. A request that cannot run on the local host is rejected rather than silently moved to a different engine or device.
The routing result also supplies the generation time budget. A cold engine load has a separate, longer budget from speech generation. Once the engine is ready, each render receives a budget that reflects the text and the available compute. This separates slow setup from a render that is too slow or too large for the host.
References: backend/…/tts_backend.py• L558-613 backend/…/tts_backend.py• L5302-5316 backend/…/tts_stream.py• L407-433 backend/…/generation.py• L2195-2242
Language support
Each engine declares the language set that it can support. The shared backend normalizes common language names and region tags, then checks an explicit language request against that set before synthesis. Automatic language selection remains available when the caller does not choose a language, while an unsupported explicit language returns a clear error instead of producing speech in an unintended language.
At the engine boundary, a regional variant such as a country-specific Portuguese label becomes the engine's base language. The dialect remains available to text preparation and the user interface. This keeps engine lookup consistent while preserving the requested speech variant for the parts of the system that use it.
Language matching also accepts a named variety when the engine declares its broader macrolanguage. This gives engines a stable base code without treating every variety as a different engine capability.
A profile can supply a saved language when the request leaves the picker on Auto. The service records that source and explains that the profile must be changed, overridden for the render, or paired with an engine that supports the language. The same non-retryable language error is used for all local generation paths, so an engine language mismatch is not mistaken for a reason to repeat the request.
The catalogue turns finite language sets into picker options. Engines with open or model-specific language coverage leave that choice to the engine. This keeps the language shown in the UI consistent with the check used during generation.
References: backend/…/tts_backend.py• L212-228 backend/…/tts_backend.py• L379-474 backend/…/tts_backend.py• L489-494 backend/…/generation.py• L1379-1469 backend/…/generation.py• L2051-2184
Process isolation
Some engines run inside the API process. Others run in a sidecar, which is a long-lived child process with its own runtime and environment. Isolation lets the service use conflicting engine dependencies and stop a failed or stuck engine without taking down the API process or leaving its device memory in use.
The engine catalogue keeps the same request contract for both forms. A sidecar sends a ready signal before heavy imports, accepts health checks, and exchanges bounded length-prefixed messages with the parent. A synthesis request can resolve an untranscribed reference inside the killable process, load the model lazily, and return PCM audio with its actual sample rate. Heartbeats and model-download progress keep slow model loads, reference transcription, and synthesis distinguishable from a wedged process. The sidecar writes protocol frames through a private clean channel while library logs go to diagnostics, so log output cannot corrupt later requests. The parent accepts only known operations, limits frame size, drains diagnostic output, and reclaims the process after a receive deadline. A later request can start the sidecar again. Idle sidecars can also be unloaded to release process and device resources while active synthesis remains protected.
References: backend/…/subprocess_backend.py• L78-109 backend/…/subprocess_backend.py• L134-206 backend/…/subprocess_backend.py• L380-414 backend/…/subprocess_backend.py• L492-590 backend/…/subprocess_backend.py• L783-923 backend/…/subprocess_backend.py• L986-1089 backend/…/main.py• L8-29 backend/…/main.py• L68-123 backend/…/main.py• L392-457 backend/…/tts_backend.py• L615-621
Voice controls
Voice controls define who speaks and how the speech sounds. A request can use a stored voice profile, a reference recording, an engine preset, a design description, or style and emotion settings supported by the selected engine.
Reference cloning
Reference cloning uses an audio sample as the speaker anchor. A profile can store the sample and its transcript so later requests can reuse the same speaker identity. If the transcript is missing, the system can use speech recognition to create it and cache the result.
The selected engine must support cloning when speaker identity matters. For engines with model-dependent capability, the active model must support cloning; changing the engine model can fix the request without changing the rest of the workflow. Engines with fixed preset voices cannot preserve an arbitrary speaker.
Engines describe how much of a long reference they use. The default clone path can rank fixed windows with an installed speech recognizer and use the window with the most useful speech. Other engines can keep the start of the clip or use a different limit. The selected window and its prompt can be reused only when the reference file version, recognizer identity, transcript, and preparation state are unchanged. Long-reference ranking can happen before the generation clock starts, so speech recognition time does not consume the main render budget.
Repeated use of the same reference can reuse prepared voice data in memory and across restarts when the persistent cache is available. Cache preparation is best-effort. A cache miss or cache error returns to the normal reference path instead of blocking generation. Isolated OmniVoice synthesis can also transcribe an unlabelled reference inside the sidecar and reuse one prepared reference encoding for later requests in that sidecar. Single-use references can avoid filling the shared cache, which protects reusable profile prompts during batch or dubbing work.
References: backend/…/generation.py• L386-495 backend/…/generation.py• L2047-2163 backend/…/generation.py• L2281-2346 backend/…/tts_backend.py• L763-895 backend/…/tts_backend.py• L936-1000 backend/…/tts_backend.py• L1368-1421 backend/…/tts_backend.py• L1503-1729 backend/…/main.py• L308-377
Voice archetype gallery
The voice archetype gallery offers designed voices that users can browse by category and traits before they create a profile. A preview may come from an opt-in pre-rendered gallery or a local engine render. Creating a reusable voice saves the archetype's design recipe as a profile without loading the engine; synthesis uses that recipe when the user later generates audio.
The gallery keeps preview rendering separate from profile creation. A preview can remain available while the local engine is not installed. The use action creates or refreshes one design profile with its instruction, language, sample script, and design traits, but it does not make the preview audio the profile's reference. Reusing an archetype is idempotent, so selecting the same designed voice does not create duplicate profiles.
Archetype previews reject unusable audio before it is cached or saved. The accepted synthetic audio receives the same provenance treatment as other generated audio, while user-recorded reference audio remains distinct from synthetic samples. Gallery preview downloads are optional and begin only after the user enables them; otherwise the service uses a local cached or newly rendered preview.
References: backend/…/archetypes.py• L1-24 backend/…/archetypes.py• L310-395 backend/…/archetypes.py• L443-590 backend/…/archetypes.py• L593-614
Voice design
Voice design creates a speaker from a description instead of a reference recording. The description maps to a controlled set of traits such as gender, age, pitch, style, English accent, and Chinese dialect. Terms outside that set remain visible as unmatched input so the caller can see what the design did not express.
A design-capable engine uses the resulting instruction or description to create the voice. The engine also declares whether its instruction vocabulary is controlled tags or free-form text. Capability metadata lets the client show the right editing guidance. A generation can store the design description and selected traits as metadata without changing the synthesis input. The server validates the saved recipe and recomputes its mapped traits, so a saved take can reopen with a trusted design draft.
When a design profile has a saved sample and the request makes no design change, its sample and instruction preserve the saved voice. A changed design instruction or seed represents a new design and does not condition the render on the old sample. A deferred profile, such as one created from an archetype, can instead use its stored design instruction until a concrete sample exists. This prevents an old sample from overriding the requested traits.
References: backend/…/describe_voice.py• L286-336 backend/…/generation.py• L225-345 backend/…/generation.py• L386-451 backend/…/tts_backend.py• L289-322 backend/…/tts_backend.py• L4556-4560
Style and emotion
Style instructions shape delivery when the selected engine supports them. Some engines also accept emotion text, an emotion vector, or an emotion strength value. Supported workflows can pass a line-level emotion direction that is folded into the same delivery instruction used by the full render. Capability metadata lets clients show only controls that can affect the result. The API rejects conflicting emotion forms and malformed values before synthesis. Engines can also declare the inline reaction tags they render, so the client does not offer controls that the active engine will speak as plain words.
The same voice controls support media localization and long-form audio. Those workflows add timing or chapter rules around speech generation, but they do not change the meaning of a voice profile or engine capability.
References: backend/…/tts_backend.py• L297-322 backend/…/tts_backend.py• L4396-4560 backend/…/tts_backend.py• L3548-3763 backend/…/generation.py• L1787-1950 backend/…/generation.py• L2073-2105 backend/…/generation.py• L2219-2258
Voice conversion
Voice conversion turns a spoken source clip into the voice of an existing profile. POST /convert first requires that profile and validates the upload before selecting a cloning-capable engine. In its normal mode, it transcribes the source words, cleans and prepares the text, synthesizes those words with the profile's conditioning, and saves the result through the normal generation path.
The route also supports a delivery-preserving mode. keep_delivery sends the source recording to a speech-to-speech engine when the active engine supports it, or to an installed compatible engine when it does not. The target voice changes while the source timing, rhythm, pauses, and intonation remain. This mode needs a profile with a usable reference sample and does not apply the normal transcript or duration-match steps. Long source recordings are split at quiet points when the selected conversion engine has a shorter source limit, then joined in order.
Supported video uploads always use delivery-preserving conversion so the new voice stays aligned with the picture. The result can include a rebuilt video with its picture retained, or an audio take with a note when video reconstruction is not possible. The original media stays unchanged.
The route saves the upload with a supported source suffix before heavy model work. It bounds the source upload and keeps temporary reference data alive until all local or isolated readers finish. In normal mode, it can move the result toward the source duration with a pitch-preserving stretch. This adjustment is optional and best-effort. If it cannot run, the generated take remains valid at its original duration.
flowchart TD
A[Source speech clip or supported video] --> B[Check profile, upload, and target engine]
B --> C{Keep source delivery?}
C -->|Yes or video| D[Convert recording with target voice]
C -->|No| E[Transcribe source words]
E --> F[Clean and normalize text]
F --> G[Synthesize profile voice]
G --> H{Duration match enabled}
H -->|Yes| I[Adjust pace toward source length]
H -->|No| J[Keep generated duration]
D --> K[Mark and save take]
I --> K
J --> K
Both audio conversion modes use the same profile resolution, engine selection, guarded generation, provenance mark, saved audio, and history rules as normal speech generation. Video conversion uses the same target-voice and protected generation controls, then publishes media output with any fallback notes. This keeps a converted take consistent with other saved speech while allowing one mode to preserve the source performance.
References: backend/…/voice_convert.py• L442-527 backend/…/voice_convert.py• L529-603 backend/…/voice_convert.py• L605-694 backend/…/voice_convert.py• L251-373 backend/…/voice_conversion.py• L48-83 backend/…/voice_conversion.py• L143-190 backend/…/tts_backend.py• L502-522 backend/…/tts_backend.py• L5275-5346
Voice profile lifecycle
A voice profile gives a voice a stable identity across requests. It stores either a user recording for cloning or the settings and sample for a designed voice. It can also preserve a chosen generated take as the profile's locked version.
Profile creation
The profile API creates clone and design profiles. Clone profiles need reference audio. Design profiles need design state and can be saved before the engine is ready. Their sample is created when the engine becomes available or when a later workflow needs concrete audio. This keeps voice setup separate from model download state.
When a clone profile has no transcript, the service makes a best-effort transcription while saving it. A later generation can fill an empty transcript as well, so the same reference does not require repeated speech recognition. Design instructions are cleaned and kept in step with the stored design traits.
Profiles can be listed, edited, previewed, used for generation, and deleted. The profile resolver supplies stored reference audio, transcript, instruction, language, and seed when a request does not provide a more specific value. The same rules apply when another route accepts a profile.
References: backend/…/profiles.py• L52-95 backend/…/profiles.py• L111-272 backend/…/profiles.py• L312-369 backend/…/generation.py• L388-493
Reference replacement
Clone profiles can replace their reference recording without changing the profile identity, portrait, or history. The replacement must be a supported and decodable audio file. The new sample becomes active only after the profile update succeeds, while older samples remain available to renders already in progress and are removed later when safe.
Designed profiles are changed through their design traits rather than by replacing their recorded sample. This keeps the distinction clear between changing a cloned speaker and creating a new designed voice.
References: backend/…/profiles.py• L372-482 backend/…/profiles.py• L493-552 backend/…/profiles.py• L623-732
Take locking
Locking copies a generated take into the profile and makes that take the preferred reference for future use. This turns a variable generation into a stable speaker sample. Unlocking returns the profile to its normal clone reference or design source.
A profile can also carry a verified-own-voice consent record. That record controls higher-risk voice features and sharing flows. Ordinary local speech generation does not require it.
References: backend/…/profiles.py• L363-423 backend/…/profiles.py• L425-529
Audio delivery
The system has separate delivery paths for saved speech, progressive previews, and low-latency conversation. They share engine choice and voice preparation, but they differ in completion and persistence behavior.
Saved outputs
The native generation path validates audio samples, applies the selected effects, adds an invisible provenance mark when enabled, saves a WAV, and records generation metadata. Studio engines can skip the shared mastering stage when they already provide mastered audio. The response returns the audio and identifiers for the saved take. History retention removes old unstarred takes over the configured limit while keeping starred takes.
History persistence is best-effort after the WAV is safe on disk. If the history table or an additive history field is missing, the service repairs the schema and retries; a remaining history failure does not discard the generated audio. Listing history also removes rows whose files no longer exist, so the client does not receive dead takes.
The saved WAV is also the source for Ogg/Opus responses. Those alternate responses use a bounded cache and do not create a second take or history entry. MP3 is a one-shot export from the same WAV and is not cached. The OpenAI-compatible speech endpoint returns the requested audio format at the API boundary and falls back to WAV when an encoder is not available.
References: backend/…/generation.py• L116-205 backend/…/generation.py• L1497-1642 backend/…/generation.py• L1737-1890 backend/…/generation.py• L2784-2893 backend/…/generation.py• L3117-3220 backend/…/generation.py• L82-130 backend/…/openai_compat.py• L205-262 backend/…/openai_compat.py• L297-318
Streaming previews
stream=true on the native request returns newline-delimited JSON events. A local render sends a start event, then base64 PCM16 chunks as text chunks finish, and finally a done event that identifies the saved take.
The final saved file uses the same assembly, processing, provenance, and history path as a non-streamed request. A client can therefore start playback early without creating a different kind of take. If a text chunk produces no audio, the stream reports a warning instead of hiding the missing text.
Long streamed text uses a separate generation budget for each text chunk, then assembles the raw chunks before the final effect pass. This lets first audio arrive early without changing the saved take's joining rules. The stream reports the engine's actual sample rate after the first rendered chunk is ready.
When a client disconnects, the in-progress stream is cancelled and no partial take is saved. Capacity and time-limit failures stay in the NDJSON channel as machine-readable error events, so a client can decide whether to retry.
References: backend/…/generation.py• L2287-2449 backend/…/generation.py• L2452-2808
Live audio streams
The live WS /ws/tts interface accepts repeated JSON requests on one connection. It checks the selected engine and local route for each request. It sends a routing notice when needed, then a start message, binary PCM16 audio chunks, and a completion message with duration and timing data. This path suits assistants, dictation feedback, and interactive previews where the first audio matters more than a saved artifact.
The stream prepares the text once. Engines with native streaming use their streaming path; other engines synthesize sentence-sized parts so the first completed part can play while later parts are still pending. A relative duration_factor selects pacing for engines that support it and disables the native stream path when that control cannot be applied safely. Each non-native part is mastered, loudness-normalized, and marked for provenance before it is sent.
The start message reports the sample rate from the active engine after the first part is ready. The completion message separates total socket time from synthesis time so time-to-first-audio and render speed remain useful even when a client reads slowly. The stream accepts supported emotion controls and resolves emotion-audio references only from application-owned voice or output files. It resolves voice profiles with the same locked-reference and stored-instruction rules as other generation paths. A native stream claims its engine while it runs, so buffered work cannot share the engine's model state. Routing limits and generation errors are sent as JSON frames, so a conversational client can continue using the connection for another request. This low-latency path runs on the local host and does not silently switch to another engine or device.
References: backend/…/text_normalization.py• L657-703 backend/…/tts_stream.py• L47-219 backend/…/tts_stream.py• L232-343 backend/…/tts_stream.py• L346-565 backend/…/tts_backend.py• L231-247 backend/…/tts_backend.py• L5065-5106
Related workflows
Speech generation is a shared service for product features that need many utterances or need to preserve voices across a media project. Those workflows add timing, translation, or book structure around the same voice and engine decisions.
Media localization
The dubbing workflow generates speech for translated segments and can require a cloning-capable engine to keep each speaker's identity. It also fits generated speech to media timing, so it is broader than a single text-to-speech request. See model compute for the engine and host constraints that also apply to these jobs.
References: backend/…/dub_generate.py• L157-212 backend/…/dub_generate.py• L253-260 backend/…/tts_backend.py• L3923-3989 backend/…/tts_backend.py• L5275-5331
Timing fit
Timing fit estimates how long translated text will take to speak in the target language, then optionally asks an enabled LLM skill to trim or expand a line toward its media slot. The fit pass runs with bounded concurrency and a shared time budget, while a line that cannot fit safely keeps its text rather than inventing dialogue.
After a real render, the workflow can make one evidence-based rewrite from the measured duration. A divergence check protects names, meaning, and target-language output. If the skill is unavailable or the budget ends, the existing line remains usable and the result reports the degraded fit.
References: backend/…/speech_rate.py• L86-118 backend/…/speech_rate.py• L131-233 backend/…/speech_rate.py• L236-436 backend/…/dub_translate.py• L1188-1248 backend/…/dub_translate.py• L1409-1468
Long-form speech
The audiobook workflow parses chapters and voice spans, renders each span through the active speech backend, and joins the results into a chapterized book file. It can map named voice tags to profiles, reuse finished segment audio, and resume an interrupted render.
References: backend/…/audiobook.py• L1-20 backend/…/audiobook.py• L217-260 backend/…/audiobook.py• L242-324
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the native
generate, OpenAI-compatible speech, WebSocket speech, and/convertcontracts aligned when adding a voice or engine control. - Keep profile-conditioning rules aligned for every route that accepts a profile. Preserve the precedence of locked takes, request values, and stored clone or design data.
- Keep design-profile edits separate from re-renders of the saved design sample. A changed instruction or seed must not silently use the old sample as the voice anchor.
- Keep clone-profile replacement separate from design-profile editing. A replacement must not clear or alter the profile's unrelated identity and history state.
- Keep profile-supplied language distinct from an explicitly selected language. A profile-filled language must produce a profile-aware, non-retryable error on every local generation path.
- Keep archetype preview sources separate from profile creation. Gallery audio may preview a voice, but it must not become the reference sample used for future cloning or silently materialize a profile.
- Keep archetype identity and design state stable so repeated use reuses one profile and does not overwrite a user-edited or locked profile.
- Update engine capability metadata when an engine gains or loses cloning, delivery-preserving conversion, design, emotion, language, reference-length, hardware, isolation, preset-voice, or model-picker support. For model-dependent engines, keep the catalogue result and the live request check aligned.
- Keep engine licence checks and generation-time resolution before engine switching or model loading. A rejected engine must not unload a working engine, and a batch or dubbing job must not silently fall back to another engine.
- Preserve the order of NFC cleanup, language and profile resolution, text normalization, and pronunciation processing. A change in this order can change speech output and pronunciation entries.
- Keep normalization conservative and markup-safe. A new language rule must not rewrite bracketed speech controls or ambiguous identifiers. Keep the gated entry point non-throwing so a normalization fault cannot stop synthesis.
- Keep streamed previews, converted takes, and saved generations on the same audio assembly and provenance path. A delivery change must not create a different artifact.
- Keep alternate audio encodings tied to the saved WAV version. Do not create a second history item or serve cached bytes for an older file.
- Keep live-stream start metadata tied to the engine's actual sample rate. Keep synthesis time separate from socket delivery time when changing stream metrics.
- Keep the live stream's native and sentence-based paths aligned. A pacing control that cannot be honored by native streaming must not be silently ignored.
- Keep temporary reference audio alive until cancelled local work or an isolated engine has finished reading it. Preserve the source suffix when a decoder needs it.
- Keep engine availability, language, and cloning checks before expensive ASR or synthesis work for routes that require them.
- Keep engine status messages scrubbed before they cross the API boundary. Availability hints, last errors, setup links, install actions, and documentation links must remain safe and point to the same engine row.
- Keep active-engine cache invalidation aligned with both engine changes and model-only changes. Do not let idle cleanup unload an engine that an active generation still holds.
- Keep clone-prompt cache keys tied to the reference file state, transcript, preprocessing choice, selected passage, and recognizer identity. Treat cache reads and writes as optional so cache failure cannot change synthesis success.
- Keep long-reference passage ranking outside the main generation budget when it is precomputed. The in-generation path must still use the same recognizer-specific selected passage when precomputation is unavailable.
- Keep model-load retry limits bounded and separate from the generation time budget. A download recovery path must not turn into an unbounded request loop.
- Keep sidecar frame limits, allowed operations, receive deadlines, and process cleanup aligned. A timeout must not leave a child process or device allocation available to a later request.
- Keep sidecar progress heartbeats and model-download progress on the clean protocol channel. Diagnostic output must not interleave with frames or make the parent misread a later request.
- Keep sidecar reference transcription and cached-reference generation inside the same cancellation and deadline boundary as synthesis. A failed transcript must still reach the installed-only fallback without repeating recognizer work.
- Keep adapter input errors mapped to client errors. Do not replace a clear empty-text, unsupported-language, or non-speakable-text response with an engine-specific server error.
- Keep the shared render lease around model readiness and generation. Idle cleanup must not release an engine between sentence renders or while another route holds it.
- Keep regional language variants mapped to the base language at the engine boundary. Do not remove the dialect information needed by text preparation or UI reporting.
- Keep live-stream emotion-audio paths restricted to application-owned voice or output files. Do not turn a socket value into an arbitrary filesystem read.
- Keep
keep_deliveryseparate from transcript-based conversion. It must preserve source timing without requiring source transcription or applying duration matching. - Keep video conversion on the delivery-preserving path. Preserve picture alignment, publish the audio fallback when video rebuild fails, and retain the fallback note without changing the original upload.
- Keep delivery-preserving conversion limits and split behavior aligned with the selected engine's source cap. Joining must preserve source order and must not turn an oversized recording into an unbounded queue.
- Keep MP3 exports tied to the current saved WAV. They must remain one-shot downloads and must report encoder failures without creating extra history entries.
- Keep emotion text, emotion vectors, strength values, line-level emotion directions, and pacing controls validated consistently between native and WebSocket speech requests.
- Keep generated audio finalization ordered as provenance mark, file save, history write, and retention. A history repair or retention failure must not remove a valid newly saved take.
- Keep streamed chunk budgets separate from the final assembly budget. A long preview must not consume one flat budget before its first audio reaches the client.
- Keep predicted slot-fit results tied to the final translated text, and keep measured correction within its shared LLM budget. A failed or divergent rewrite must leave the prior usable line.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| The selected engine is unknown or unavailable | The request stops before synthesis and returns an actionable client error | Registry lookup and availability checks run before engine use |
| An availability probe raises while the catalogue loads | One engine row can be wrong or disappear and hide a usable setup choice | The catalogue captures the probe failure for that row and continues listing other engines |
| The selected model licence is not accepted | The engine is refused before it can unload another active engine or load weights | Licence acceptance is checked during engine resolution |
| A design request uses an engine without voice-design support | The request stops before model work instead of producing an unintended preset voice | Conditioning capability is checked before loading the engine |
| A reference voice uses an engine without cloning support | The request stops instead of silently ignoring the reference sample | Reference conditioning is checked against the live engine or model capability |
| A delivery-preserving conversion has no compatible installed engine | The request returns a setup message instead of falling back to transcript-based speech or an arbitrary engine | Conversion routing checks declared conversion support, availability, licence, and host routing |
| A dubbing or batch job selects an engine that cannot clone | The job fails with a model or engine change that can fix it instead of using OmniVoice | Shared generation resolution checks cloning before job work |
| The engine cannot run on the local host | The request is rejected instead of silently changing engine or device | Host-aware routing reports accelerated, CPU, or unavailable status |
| The engine's device memory is below its stated floor | A render can become very slow or fail after a long wait | Catalogue routing exposes the under-provisioned condition before work starts |
| A required engine model or runtime is not set up | Generation cannot start even though the engine is listed | Availability probes expose the setup reason and the catalogue supplies the next action |
| A first-use model download fails or the shared download client is closed | Cold loading can fail even though the model is otherwise usable | Closed-client recovery and recognized network retries use bounded budgets and the resumable model cache |
| A sidecar sends an oversized, malformed, or unknown frame | The parent can waste memory, lose protocol sync, or act on an operation it does not support | Frame sizes and inbound operations are allowlisted before use |
| Sidecar logs or library output enter the frame stream | The parent reads log bytes as a length prefix and loses protocol sync for later requests | The sidecar duplicates a private frame descriptor and redirects library output to diagnostics |
| A sidecar stops sending progress or audio before its deadline | Generation stops and the child is reclaimed instead of blocking future work | Stage heartbeats, receive watchdogs, and process cleanup distinguish slow work from a silent wedge |
| A sidecar stays idle after generation | Its process and device memory remain occupied for later work | Idle reaping and explicit unload release it while busy operations remain protected |
| An availability or status message contains a model-host credential token | The frontend could expose a secret in an error or catalogue row | Credential-shaped tokens are redacted before status is cached or serialized |
| Text is empty or has no speakable content after cleanup | The request fails as a client input error instead of exposing a low-level audio or tensor error | The shared TTS input error maps invalid text to the API's client-error response |
| Normalization changes an ambiguous code or rewrites speech markup | The engine may speak the wrong meaning or fail to parse a pause or voice control | Conservative language rules skip ambiguous forms and bracketed markup; the gated pass falls back to raw text on error |
| A regional language label reaches an engine that accepts only base languages | The engine can reject a valid regional request or use the wrong default | The shared render boundary converts known variants to their base language before engine lookup |
| An explicit language is outside the selected engine's declared set | The request stops instead of producing speech in the wrong language | The shared engine contract validates language before generation |
| A profile supplies a language that the selected engine cannot speak | The request fails as a non-retryable input error, even when the picker shows Auto | Profile language provenance is carried into the same local rejection path |
| An emotion vector has the wrong shape or values, or emotion sources conflict | The request fails before model work instead of silently losing the requested expression | The API validates vector dimensions, numeric bounds, strength use, and engine capability |
| A line-level emotion direction reaches an engine without emotion support | The request stops instead of silently dropping the direction | Native generation checks emotion capability before model loading |
| A long reference is paired with a whole-clip transcript that the engine cannot align | Cloning can fail or use the wrong speech passage | The route rejects an explicit over-long transcript and lets the engine choose a usable passage when it is omitted |
| Long-reference passage ranking uses a different recognizer or stale file version | A cached window can represent the wrong speech or speaker context | Passage choices include the reference version and recognizer identity |
| A reference preparation or clone-prompt cache operation fails | Generation can lose its speed benefit but should still produce speech | Reference preparation and cache use fall back to the normal reference path |
| A sidecar reference transcription fails or returns no speech | Synthesis can repeat recognizer work or fail to condition the intended speaker | The sidecar records the ASR outcome and uses the model's installed-only reference fallback |
| A conversion request names a missing profile | No source transcription or synthesis starts | /convert requires the profile and returns a strict not-found response |
| A conversion request uses an engine or active model without cloning support | The result cannot preserve the target speaker | Backend resolution checks cloning capability before ASR and synthesis |
| A delivery-preserving conversion has no usable target reference | The source recording cannot be converted into the selected profile | The speech-to-speech path requires a concrete profile reference sample |
| A conversion upload exceeds its bound or has an unsupported source form | The request is rejected before heavy model work or decoding | Bounded upload handling preserves a supported suffix and enforces the source-audio or video limit |
| A video upload uses an unsupported container or exceeds the video bound | The request is rejected before voice conversion starts | Video type checks and separate bounded upload handling run before model work |
| A source conversion recording is longer than the supported conversion window | The request can fail before model work or create too many conversion jobs | The conversion service caps total source length and splits supported long inputs at quiet points |
| Video voice rebuilding cannot preserve the soundtrack or container | The service returns a valid converted audio take and explains the fallback while leaving the source video unchanged | Video swap publishes the available media result with explicit fallback notes |
| Source conversion audio contains no usable speech | There is no text to synthesize | Transcription is cleaned and checked before generation |
| A profile reference has no transcript | Reference preparation adds speech recognition work and can increase latency | The transcript is created when possible and cached on the profile |
| A clone replacement is too large, empty, or undecodable | The existing profile remains active and the new sample is rejected | Upload limits and positive audio decoding checks run before the profile update |
| A voice archetype preview is blank or a tonal artifact | A bad sample could be cached or become a reusable voice | Preview audio is checked before cache or profile persistence and retried once |
| A voice archetype is used more than once | Duplicate profiles or conflicting samples can appear | Archetype materialization uses a stable identity and rechecks it before insertion |
| A temporary reference is cleaned while a cancelled task or sidecar still reads it | The engine can fail with a missing or incomplete reference | Reference leases delete the file only after the request and all readers finish |
| Long-text synthesis produces an empty chunk | The saved take can miss a sentence | Chunk joining records dropped text and reports a warning or response header |
| A live stream starts while another native job holds the same engine | The stream or other job fails fast instead of corrupting shared model state | The engine-use lease rejects conflicting native and buffered work |
| A live stream's engine cannot run on the host | The client receives an error frame and no audio for that request | The WebSocket performs the routing gate before synthesis and keeps the connection available for another request |
| A live stream client disconnects during generation | Incomplete work is abandoned and no partial take is saved | Stream cancellation stops the render path and releases reference ownership |
| A live stream emotion-audio value points outside the application's voice or output folders | The engine could read an unrelated local file | Stream validation resolves only existing non-symlink files within owned roots |
| A live stream omits an optional emotion value | A minimal request can fail before audio starts | Stream argument building supplies the default emotion strength |
| A live stream pacing factor is outside its supported range | The request could produce an invalid or ignored timing control | The WebSocket validates the relative factor before building engine arguments |
| Optional duration matching fails during voice conversion | The converted take keeps its generated duration instead of failing | Duration adjustment is best-effort |
| Generated samples contain invalid numeric values | The audio file may be unreadable | The generation path replaces non-finite samples before processing and saving |
| An MP3 or Ogg/Opus encoder is unavailable or times out | The saved WAV remains valid, but the requested alternate download fails | Encoders report a bounded service error and use the saved WAV as the source; Ogg/Opus uses a versioned cache |
| History write or schema repair fails after audio save | The audio is available but the take may not appear in history | Finalization saves the WAV first and treats history repair and retention as non-fatal |
| A slot-fit LLM is disabled, times out, or returns a divergent rewrite | The translated line stays unchanged and may not fill its slot | The skill gate, shared deadline, and divergence guard degrade to the prior usable text |
Key files
| File | Why to read it |
|---|---|
| backend/…/generation.py | Main native request lifecycle from input handling through validation, local routing, profile resolution, text preparation, synthesis, streaming, saving, alternate audio delivery, history, and failure reporting |
| backend/…/tts_backend.py | Common engine contract, input and language checks, capability catalogue, licence and engine selection, cloning support, voice-conversion capability, reference-prompt reuse, model-load recovery, and protected engine lifecycle |
| backend/…/archetypes.py | Designed voice catalogue, preview sources, local sample validation, and conversion of an archetype into a deferred reusable profile |
| backend/…/text_normalization.py | Engine-independent text cleanup, language-aware number handling, markup protection, and the preference gate |
| backend/…/subprocess_backend.py | Isolation boundary for engines that need a separate runtime, including sidecar health, timeouts, frame safety, and idle cleanup |
| backend/…/main.py | OmniVoice sidecar contract, lazy model loading, reference transcription, progress heartbeats, PCM transport, and clean process shutdown |
| backend/…/voice_convert.py | Speech-to-speech conversion from bounded audio or video upload and transcription, or delivery-preserving conversion, through profile-conditioned synthesis and saved output |
| backend/…/voice_conversion.py | Direct delivery-preserving conversion selection, source limits, quiet-point splitting, and ordered audio assembly |
| backend/…/openai_compat.py | OpenAI-compatible speech request, voice lookup, output formats, and API error behavior |
| backend/…/tts_stream.py | Live WebSocket speech contract, profile, pacing, and emotion-audio controls, native or sentence-based delivery, local low-latency routing, and stream metrics |
| backend/…/profiles.py | Clone and design profile creation, reuse, locking, consent, and cleanup |
| backend/…/describe_voice.py | Mapping from natural-language voice descriptions to controlled design traits |
| backend/…/chunked_tts.py | Long-text boundaries, crossfade joining, and dropped-audio reporting |
| backend/…/speech_rate.py | Language-aware timing estimates and bounded text fitting for media slots |
| backend/…/dub_translate.py | Integration of predicted timing, bounded slot fitting, and measured post-render correction into dubbing |
| tests/test_generate_streaming.py | Contract checks for incremental delivery and equivalent saved output |
| tests/test_archetype_preview_quality.py | Contract checks that archetype previews are audible and do not persist unusable samples |