Skip to content

API Reference parrot.voice.tts.supertonic_inference

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot.voice.tts.supertonic_inference

View source

Supertonic ONNX inference wiring (4-graph flow-matching TTS).

The :class:SupertonicTTSBackend in supertonic_backend.py is intentionally agnostic about the concrete Supertonic ONNX graph I/O — it exposes an inference_fn seam (FEAT-231 §8 R-deps). This module fills that seam for the public Supertonic-3 weights (Supertone/supertonic-3 on Hugging Face), which ship the model split across four ONNX graphs run in sequence:

text  --tokenise-->  text_ids ----------------------------------+
                                                                 |
duration_predictor(text_ids, style_dp, text_mask)  -->  duration |
text_encoder(text_ids, style_ttl, text_mask)        -->  text_emb |
vector_estimator(noisy_latent, text_emb, ..., step) -->  latent   |  x total_step
vocoder(latent)                                     -->  waveform <+

The math mirrors the upstream reference (py/helper.py in supertone-inc/supertonic); it is reimplemented here against numpy/onnxruntime only — no upstream package dependency.

Expected on-disk layout (as produced by make install-supertonic)::

<model_dir>/
├── onnx/
│   ├── duration_predictor.onnx
│   ├── text_encoder.onnx
│   ├── vector_estimator.onnx
│   ├── vocoder.onnx
│   ├── tts.json              # config (sample_rate, chunk sizes, latent_dim)
│   └── unicode_indexer.json  # codepoint -> token id table
└── voice_styles/
    ├── M1.json … M5.json     # speaker style vectors (style_ttl + style_dp)
    └── F1.json … F5.json

SUPERTONIC_MODEL_PATH (or model_dir=) should point at <model_dir> (the directory that contains onnx/ and voice_styles/). Pointing it directly at the onnx/ directory is also tolerated. When neither is given, the backend falls back to <BASE_DIR>/models/supertonic-3 — exactly where make install-supertonic puts the weights — so a standard checkout works with no configuration at all.

Added by FEAT-231 follow-up (Supertonic 4-graph inference wiring).

Attribute AVAILABLE_LANGS

Class Style

A speaker style: the two conditioning tensors Supertonic consumes.

Parameter Type Default Description
ttl np.ndarray
dp np.ndarray

Attributes:

Attribute Type Description
ttl style_ttl tensor (text-encoder / vector-estimator conditioning).
dp style_dp tensor (duration-predictor conditioning).

Class SupertonicONNXBackend

:class:SupertonicTTSBackend wired for the real Supertonic-3 weights.

Overrides session creation to load the four-graph :class:SupertonicPipeline and bind it as the backend's inference_fn. Everything else (async offload, WAV wrapping, empty-text guard, truthful mime_format) is inherited unchanged.

Construction stays cheap — the heavy ONNX load happens lazily on the first synthesize call, via :meth:_ensure_session.

Parameter Type Default Description
model_dir Optional[str] None Directory with onnx/ and voice_styles/. Defaults to SUPERTONIC_MODEL_PATH.
voice Optional[str] None Default voice id (M1..F5). None → default_voice.
onnx_subdir str 'onnx' ONNX subdirectory name.
voice_styles_subdir str 'voice_styles' Voice-styles subdirectory name.
default_voice str 'M1' Voice used when neither voice nor the call supplies one.
total_step int 8 Flow-matching denoising steps.
speed float 1.05 Speech-rate multiplier.
use_gpu bool False Reserved (CPU only).
**kwargs {} Forwarded to :class:SupertonicTTSBackend.

Class SupertonicPipeline

Runs the Supertonic-3 four-graph pipeline and returns raw PCM.

The instance is callable with the signature SupertonicTTSBackend expects for inference_fn::

pipeline(session, text, *, voice, language, sample_rate) -> bytes

The session and sample_rate arguments are ignored (the pipeline owns its own four ONNX sessions and reports its native sample rate via :attr:sample_rate); they exist only to satisfy the seam contract.

Loading is eager — the constructor opens all four ONNX sessions, the config and the tokeniser table — so build it lazily (e.g. from the backend's _ensure_session) to keep object construction cheap.

Parameter Type Default Description
model_dir str Directory containing onnx/ and voice_styles/ (or the onnx directory itself).
onnx_subdir str 'onnx' Name of the ONNX subdirectory under model_dir.
voice_styles_subdir str 'voice_styles' Name of the voice-styles subdirectory.
default_voice str 'M1' Voice id used when the caller passes None.
total_step int 8 Number of flow-matching denoising steps (higher = smoother, slower). Upstream default is 8.
speed float 1.05 Speech-rate multiplier (>1 = faster). Upstream default is 1.05.
use_gpu bool False Reserved; CPU execution only for now.

Method SupertonicPipeline.synthesize_pcm

Synthesize text to raw PCM (16-bit LE mono at :attr:sample_rate).

Long text is chunked, synthesized chunk-by-chunk, and concatenated with short silences. The final waveform is trimmed to the predicted total duration and quantised to int16.

synthesize_pcm(text: str, *, voice: Optional[str] = None, language: Optional[str] = None, silence_duration: float = 0.3) -> bytes

Parameter Type Default Description
text str Text to speak (non-empty).
voice Optional[str] None Voice id (M1..M5 / F1..F5), a filename, or a path. None uses :attr:default_voice.
language Optional[str] None BCP-47 tag; only the primary subtag is used and unknown languages fall back to English.
silence_duration float 0.3 Gap inserted between chunks, in seconds.

Returns: bytes — Raw PCM bytes (16-bit little-endian, mono).

Alias SupertonicTTSBackend

Re-exported from parrot.voice.tts.supertonic_backend.SupertonicTTSBackend.

Class UnicodeProcessor

Codepoint-based text tokeniser for Supertonic.

Normalises text, strips emojis, applies a small punctuation rewrite, wraps it in <lang>…</lang> markers, then maps each character's Unicode codepoint to a token id via unicode_indexer.json (a list indexed by codepoint, or a {codepoint: id} dict).

Parameter Type Default Description
unicode_indexer_path str Path to unicode_indexer.json.

Function chunk_text

Split text into synthesis-sized chunks by paragraph then sentence.

Long agent answers are split so each chunk stays within the model's comfortable context; chunks are re-joined (with short silences) by the caller.

chunk_text(text: str, max_len: int = 300) -> list[str]

Parameter Type Default Description
text str Input text.
max_len int 300 Maximum characters per chunk.

Returns: list[str] — Ordered list of non-empty chunk strings (at least one).

Function get_latent_mask

Mask the latent sequence to the per-item audio length.

get_latent_mask(wav_lengths: np.ndarray, base_chunk_size: int, chunk_compress_factor: int) -> np.ndarray

Parameter Type Default Description
wav_lengths np.ndarray Per-item waveform sample counts, shape (B,).
base_chunk_size int Vocoder base chunk size (samples per latent frame).
chunk_compress_factor int Latent compression factor from the config.

Returns: np.ndarray — Latent mask of shape (B, 1, latent_len).

Function length_to_mask

Build a binary length mask of shape (B, 1, max_len).

length_to_mask(lengths: np.ndarray, max_len: Optional[int] = None) -> np.ndarray

Parameter Type Default Description
lengths np.ndarray Per-item valid lengths, shape (B,).
max_len Optional[int] None Mask width; defaults to lengths.max().

Returns: np.ndarray — Float32 mask, 1.0 for valid positions and 0.0 for padding.

Function load_voice_style

Load a single voice-style JSON into a batch-of-one :class:Style.

The JSON carries style_ttl/style_dp as {"dims": [...], "data": [...]} blocks; data is reshaped to dims[1:] and given a leading batch axis.

load_voice_style(path: str) -> Style

Parameter Type Default Description
path str Path to a voice_styles/<name>.json file.

Returns: Style — class:Style with batch size 1.

Attribute logger

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally