Metadata-Version: 2.5
Name: gnani-vachana
Version: 0.11.0
Summary: Python client for Gnani's speech AI platform (STT, TTS, and more)
Project-URL: Homepage, https://gnani.ai
Project-URL: Documentation, https://docs.gnani.ai/
Project-URL: Repository, https://github.com/Gnani-AI-Mintlify/Gnani-Vachana
Project-URL: Issues, https://github.com/Gnani-AI-Mintlify/Gnani-Vachana/issues
Author-email: Genvoice <support@gnani.ai>
License-Expression: MIT
License-File: LICENSE
Keywords: asr,gnani,indian-languages,multilingual,realtime,speech-to-text,sse,streaming,stt,text-to-speech,transcription,tts,websocket
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Multimedia :: Sound/Audio :: Sound Synthesis
Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.9
Requires-Dist: requests>=2.28.0
Requires-Dist: websockets>=12.0
Provides-Extra: dev
Requires-Dist: build>=1.0; extra == 'dev'
Requires-Dist: mypy>=1.0; extra == 'dev'
Requires-Dist: openai>=1.40; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.21; extra == 'dev'
Requires-Dist: pytest-cov>=4.0; extra == 'dev'
Requires-Dist: pytest-timeout>=2.1; extra == 'dev'
Requires-Dist: pytest>=7.0; extra == 'dev'
Requires-Dist: python-dotenv>=1.0; extra == 'dev'
Requires-Dist: ruff>=0.4; extra == 'dev'
Requires-Dist: twine>=5.0; extra == 'dev'
Requires-Dist: types-requests>=2.28; extra == 'dev'
Provides-Extra: llm
Requires-Dist: openai>=1.40; extra == 'llm'
Description-Content-Type: text/markdown

# gnani-vachana
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)

Official Python client by [Gnani.ai](https://gnani.ai). Build multilingual voice workflows with Speech-to-Text (STT), Text-to-Speech (TTS) and LLM chat completions across REST, SSE streaming, and real-time WebSockets.

> **[Gnani.ai](https://gnani.ai)** is a production-ready speech AI platform with high-accuracy STT and low-latency TTS for 10+ Indian languages, with Timbre voices across REST, SSE, and WebSocket APIs.

## Installation

```bash
pip install gnani-vachana
```

Or with [uv](https://docs.astral.sh/uv/):

```bash
uv add gnani-vachana
```

The LLM chat completions client is built on the official `openai` package, which is installed
only when you ask for it:

```bash
pip install "gnani-vachana[llm]"
```

STT and TTS need no extra. Requires **Python 3.9+**.

## Quick Start

### STT REST (file-based transcription)

```python
from gnani.stt import GnaniSTTClient

client = GnaniSTTClient(api_key="your-api-key")

result = client.transcribe("audio.wav", language_code="hi-IN")
print(result["transcript"])
```

### STT Batch (many or long files)

```python
from gnani.stt import GnaniSTTBatchClient

client = GnaniSTTBatchClient()  # reads GNANI_API_KEY
result = client.transcribe(["call1.wav", "call2.wav"], language_code="hi-IN")

print(result[0].text)
result.save("./outputs")  # one JSON per file
```

See [Batch STT usage](#batch-stt-usage) for step-by-step control, diarization, and webhooks.

### Realtime Streaming (WebSocket)

```python
import asyncio
from gnani.stt import GnaniSTTStreamClient, StreamTranscriptEvent

async def main():
    async with GnaniSTTStreamClient(api_key="your-api-key", language_code="hi-IN") as stream:
        # Send audio chunks (raw PCM, 16-bit LE, 16 kHz, mono)
        with open("audio.pcm", "rb") as f:
            while chunk := f.read(1024):
                await stream.send_audio(chunk)
                await asyncio.sleep(0.032)  # real-time pacing (32 ms per frame)

        # Iterate over events
        async for event in stream:
            if isinstance(event, StreamTranscriptEvent):
                print(event.text)

asyncio.run(main())
```

### TTS REST (single response)

```python
from gnani.tts import GnaniTTSClient, AudioConfig

client = GnaniTTSClient(api_key="your-api-key")

# timbre-v2.5 (default model)
audio = client.synthesize(
    "नमस्ते, आप कैसे हैं?",
    voice="Pranav",
    model="timbre-v2.5",
    audio_config=AudioConfig(sample_rate=48000, encoding="linear_pcm", container="wav"),
)

# timbre-v3.0 — 34 voices, each speaks all ten languages
audio = client.synthesize(
    "नमस्ते, आप कैसे हैं?",
    voice="Shivani",
    model="timbre-v3.0",
    audio_config=AudioConfig(sample_rate=48000, encoding="linear_pcm", container="wav"),
)

# timbre-v2.5 — language control + speed
audio = client.synthesize(
    "नमस्ते, यह एक परीक्षण है।",
    voice="Nalini",
    model="timbre-v2.5",
    language="hi-IN",
    speed=1.0,
    audio_config=AudioConfig(container="mp3", sample_rate=48000, bitrate="128k"),
)

with open("tts_output.mp3", "wb") as f:
    f.write(audio)
```

### TTS SSE Streaming (lower latency)

```python
from gnani.tts import GnaniTTSStreamClient, AudioConfig

client = GnaniTTSStreamClient(api_key="your-api-key")
audio = client.synthesize(
    "Hello from Gnani TTS",
    voice="Pranav",
    model="timbre-v2.5",
    audio_config=AudioConfig(sample_rate=48000, encoding="linear_pcm", container="wav"),
    output_file="tts_sse.wav",
)
```

### TTS Realtime WebSocket (lowest latency)

```python
import asyncio
from gnani.tts import GnaniTTSRealtimeClient, AudioConfig

async def main():
    async with GnaniTTSRealtimeClient(api_key="your-api-key") as client:
        audio = await client.synthesize_and_collect(
            "Hello from Gnani TTS",
            voice="Pranav",
            model="timbre-v2.5",
            audio_config=AudioConfig(sample_rate=48000, encoding="linear_pcm", container="wav"),
            output_file="tts_realtime.wav",
        )

asyncio.run(main())
```

## LLM Chat Completions

`GnaniLLMClient` and `AsyncGnaniLLMClient` call the chat completions API
(`POST /v1/chat/completions`, default model `evon-v3.5`). They are the official
[`openai`](https://pypi.org/project/openai/) client, set up for Gnani, so you use them exactly as
you would use `OpenAI` and `AsyncOpenAI`: `client.chat.completions.create(...)`. Install the extra
first: `pip install "gnani-vachana[llm]"`.

The API is stateless: send the whole conversation in `messages` on every call. The API key must
have access to the LLM API (otherwise `403 SCOPE_NOT_ALLOWED`).

```python
from gnani.llm import GnaniLLMClient

client = GnaniLLMClient()  # reads GNANI_API_KEY

reply = client.chat.completions.create(
    messages=[
        {"role": "system", "content": "Be brief."},
        {"role": "user", "content": "Say hello in Hindi."},
    ],
)
print(reply.choices[0].message.content)
print(reply.usage.total_tokens)  # also prompt_tokens, completion_tokens
```

`reply` is the whole answer. `model` defaults to `evon-v3.5`, and `stream` to `False`.

> **Why `stream=False`?** The Gnani API streams unless told not to, the opposite of OpenAI's, and
> the `openai` package leaves `stream` out when you do not set it. Used directly, a plain
> `create()` would come back as raw server-sent events. These clients send `stream=False` for you.

### Streaming

Pass `stream=True` and read the chunks as they arrive. Each `chunk` is one small piece of the
answer.

```python
for chunk in client.chat.completions.create(
    messages=[{"role": "user", "content": "Count 1 to 3."}],
    stream=True,
    stream_options={"include_usage": True},  # adds a last chunk with token usage
):
    if chunk.choices:
        print(chunk.choices[0].delta.content or "", end="", flush=True)
    else:
        print("\n", chunk.usage)
```

### Async

`AsyncGnaniLLMClient` is the same, with `await` and `async for`:

```python
import asyncio
from gnani.llm import AsyncGnaniLLMClient

async def main():
    async with AsyncGnaniLLMClient() as client:
        reply = await client.chat.completions.create(
            messages=[{"role": "user", "content": "Say hello in Hindi."}],
        )
        print(reply.choices[0].message.content)

        stream = await client.chat.completions.create(
            messages=[{"role": "user", "content": "Count 1 to 3."}],
            stream=True,
        )
        async for chunk in stream:
            if chunk.choices:
                print(chunk.choices[0].delta.content or "", end="", flush=True)

asyncio.run(main())
```

### Reasoning

`evon-v3.5` is a reasoning model. Its thinking comes back in `message.reasoning`
(`delta.reasoning` when streaming), before the answer in `content`. Reasoning counts against
`max_tokens`: with a small limit the reply can end (`finish_reason == "length"`) before any
answer, and `content` is `None`.

### Tool calling and other options

```python
reply = client.chat.completions.create(
    messages=[{"role": "user", "content": "What is the weather in Pune? Use the tool."}],
    tools=[{
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Current weather for a city.",
            "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
        },
    }],
    max_tokens=600,
)
call = reply.choices[0].message.tool_calls[0]
print(call.function.name, call.function.arguments)  # get_weather {"city": "Pune"}
```

Also accepted: `temperature`, `top_p`, `max_tokens`, `stop`, `seed`, `frequency_penalty`,
`presence_penalty`, `tool_choice`, `response_format`, and the per-call `extra_headers`,
`extra_query`, `extra_body` and `timeout`. `n > 1` is not supported by the API.

To tag a request for support, send your own ID; the API echoes it back and logs it:
`extra_headers={"X-API-Request-ID": "my-request-1"}`.

### Client options

The clients take every `openai` option on top of `api_key` and `base_url`. The useful ones:

| Option        | Default                     | Notes |
| ------------- | --------------------------- | ----- |
| `api_key`     | `GNANI_API_KEY`             | `OPENAI_API_KEY` is never read. |
| `base_url`    | `https://api.vachana.ai`    | `/v1` is added when missing. |
| `timeout`     | `120` seconds               | Read timeout; it also applies between streamed chunks. |
| `max_retries` | `2`                         | Retries connection errors, 408, 409, 429 and 5xx with backoff. `0` turns them off. |

### LLM errors

Errors are the `openai` package's own:

```python
import openai

try:
    client.chat.completions.create(messages=messages)
except openai.APIStatusError as e:
    print(e.status_code, e.code, e.message)
    # 400 content_filter       -> blocked by the prompt-injection guardrail
    # 400 model_rejected_request, 404 model_not_found
    # 401 INVALID_API_KEY, 403 SCOPE_NOT_ALLOWED, 429 RATE_LIMITED   (from the gateway)
except openai.APIConnectionError as e:
    print(f"Could not reach the API: {e}")
```

Subclasses such as `openai.AuthenticationError`, `openai.RateLimitError` and
`openai.BadRequestError` are raised for the matching status codes. The API's gateway answers a bad
key in its own shape (`{"detail": {"error_code", "message"}}`); the clients keep its message and
put `error_code` in `e.code`, so a rejected key reads
`Error code: 401 - The API key is not valid. (INVALID_API_KEY)`.

A missing key raises `openai.OpenAIError` when the client is created. Phone numbers, PAN and email
addresses in a prompt are masked by the API (`[REDACTED_PHONE]`, `[REDACTED_PAN]`,
`[REDACTED_EMAIL]`), in the prompt and in the model's output.

> The model server behind the API adds fields that are not part of the documented response
> (`prompt_logprobs`, `kv_transfer_params`, `stop_reason`, ...). They are not removed. They are
> available in `reply.model_extra` / `reply.model_dump()`; ignore them.

## Authentication

All APIs (STT REST, STT Realtime, TTS, LLM) require a single API key:

| Parameter | Header         | Description                           |
|-----------|----------------|---------------------------------------|
| `api_key` | `X-API-Key-ID` | API key identifier for authentication |

### Obtaining Credentials

You need a Gnani API key. [Gnani APIs](https://app.gnani.ai/voice) have this.

### Passing Credentials

**Option 1 -- Constructor argument:**

```python
from gnani.stt import GnaniSTTClient, GnaniSTTStreamClient
from gnani.tts import GnaniTTSClient, GnaniTTSRealtimeClient, GnaniTTSStreamClient

client = GnaniSTTClient(api_key="your-api-key")
stream = GnaniSTTStreamClient(api_key="your-api-key")
tts_rest = GnaniTTSClient(api_key="your-api-key")
tts_stream = GnaniTTSStreamClient(api_key="your-api-key")
tts_realtime = GnaniTTSRealtimeClient(api_key="your-api-key")
```

**Option 2 -- Environment variable:**

```bash
export GNANI_API_KEY="your-api-key"
```

```python
from gnani.stt import GnaniSTTClient, GnaniSTTStreamClient
from gnani.tts import GnaniTTSClient

client = GnaniSTTClient()           # picks up GNANI_API_KEY
stream = GnaniSTTStreamClient()     # picks up GNANI_API_KEY
tts = GnaniTTSClient()              # picks up GNANI_API_KEY
```

## Supported Languages

### STT Languages (Speech-to-Text)

STT uses BCP-47 locale codes (e.g. `hi-IN`). For the full list of supported languages, see:

- **[STT REST — Supported Languages](https://docs.gnani.ai/api/STT/speech-to-text#supported-languages)**
- **[STT Realtime — Supported Languages](https://docs.gnani.ai/api/STT/stt-websocket#supported-languages)**

---

### TTS Voices & Models

TTS uses the **Timbre** engine. Two model IDs are supported:

| Model | Voices | `language` / `speed` |
|-------|--------|----------------------|
| `timbre-v2.5` (default) | 42 voices, one preferred language each | Supported |
| `timbre-v3.0` | 34 voices, each speaks all ten languages | Supported |

The two models have separate voice catalogs: a voice from one is refused with the other.

> **Migration:** `timbre-v2.0` (formerly `vachana-voice-v3`) is no longer accepted; the client raises `ValueError` for it. Use `timbre-v2.5` (or omit `model`).

#### timbre-v2.5 voices

42 Timbre voices across Hindi, English, Tamil, Telugu, Kannada, Malayalam, Marathi, Bengali, Gujarati, Punjabi, and Hinglish. Examples: `Nalini`, `Kaveri`, `Asmita`, `Suhana`, `Poorvi`.

#### timbre-v3.0 voices

34 voices, each speaking all ten languages: `Avinash`, `Shivani`, `Lakshmi`, `Kalpana`, `Shubham`, `Prakash`, `Devansh`, `Yashraj`, `Chetana`, `Vasudha`, `Riyaa`, `Tarika`, `Harshad`, `Anitasingh`, `Lakshmidevi`, `Priyasharm`, `Rahulmehta`, `Vikramdasu`, `Sohini`, `Arko`, `Sunaina`, `Rajeev`, `Rajni`, `Mahendra`, `Neelam`, `Rakesh`, `Shruthi`, `Manjunath`, `Rekha`, `Vinod`, `Santosh`, `Sneha`, `Nitin`, `Swathi`. Voice names are case-sensitive.

List voices programmatically:

```python
from gnani.tts import GnaniTTSClient

print(GnaniTTSClient.supported_voices())                    # timbre-v2.5 (default), 42 voices
print(GnaniTTSClient.supported_voices(model="timbre-v3.0")) # 34 voices
```

#### Optional controls (`timbre-v2.5` and `timbre-v3.0`)

Both models accept the `language` and `speed` parameters:

| Parameter | Type | Description |
|-----------|------|-------------|
| `language` | `str` | BCP-47 code: `auto`, `hi-IN`, `en-IN`, `ta-IN`, `te-IN`, `kn-IN`, `ml-IN`, `mr-IN`, `bn-IN`, `gu-IN`, `pa-IN` |
| `speed` | `float` | Speaking rate multiplier. The range depends on the model, see below. |

**Speed.** The allowed range is per model (`gnani.tts.SPEED_RANGES`). A value outside it raises
`ValueError` before anything is sent.

| Model | Range | Left out | Result |
|-------|-------|----------|--------|
| `timbre-v2.5` | `0.85`–`1.15` | `1.0` is sent | the speed you give |
| `timbre-v3.0` | `0.8`–`1.2` | nothing is sent | the voice's own speed |

`timbre-v3.0` produces only three speeds, `0.8`, `1.0` and `1.2`. The service rounds what you give
to the nearest of them (a value halfway between two, such as `0.9` or `1.1`, goes to `1.0`), so
`0.85` and `0.89` give `0.8`, and `1.11` and `1.15` give `1.2`. The SDK sends your value as it is.

`voice` is required for all Timbre models unless `speaker_embedding` is provided.

### TTS Languages (Text-to-Speech)

For the full list of supported languages, see **[TTS — Supported Languages](https://docs.gnani.ai/api/TTS/tts-inference#supported-languages)**.

## REST Usage

### Transcribe a file by path

```python
result = client.transcribe("meeting.wav", language_code="en-IN")
print(result["transcript"])
```

### Transcribe from a file object

```python
with open("meeting.mp3", "rb") as f:
    result = client.transcribe(f, language_code="ta-IN")
```

### Transcribe raw bytes

```python
audio_bytes = download_audio_from_somewhere()
result = client.transcribe_bytes(
    audio_bytes, filename="clip.wav", language_code="kn-IN"
)
```

### Custom request ID

```python
result = client.transcribe(
    "call.flac", language_code="hi-IN", request_id="my-trace-123"
)
```

### List supported languages

```python
for code, name in GnaniSTTClient.supported_languages().items():
    print(f"{code}: {name}")
```

## Prisma v3.0 (multilingual model)

`prisma-v3.0` is one model for all ten languages. It is **opt-in**: pass `model="prisma-v3.0"`;
without it nothing changes. It works on REST, streaming and batch.

```python
from gnani.stt import GnaniSTTClient

client = GnaniSTTClient()

# Let the model identify the language
result = client.transcribe("clip.wav", language_code="indic-auto", model="prisma-v3.0")
print(result["transcript"], result.get("detected_language_code"))   # "...", "ta-IN"

# Hint the likely languages (2-4); one transcript comes back, in the language heard
result = client.transcribe(
    "clip.wav",
    language_code="indic-auto",
    model="prisma-v3.0",
    language_candidates=["hi-IN", "en-IN"],
)

# Force a language, with context and an output style
result = client.transcribe(
    "clip.wav",
    language_code="hi-IN",
    model="prisma-v3.0",
    format="codemix",                     # or "verbatim" / "transcribe" / "transliterate"
    topic="Loan collection calls for a retail credit card portfolio",
    keywords=["HDFC Bank", "EMI", "खाता"],
)
```

| Option | Where | Notes |
|---|---|---|
| `language_code="indic-auto"` | REST, streaming | model identifies the language (batch: `"auto"`) |
| `language_candidates` | REST, streaming | 2-4 languages, only with `"indic-auto"`. A hint, not a limit. In batch, pass 2-4 comma-separated codes in `language_code` instead |
| `format="codemix"` | REST, streaming, batch | English stays in Latin, numbers as native words |
| `format="transliterate"` | REST, streaming | speech written in Latin letters. Not available in batch |
| `keywords` | REST, streaming, batch | words or short phrases to favour, up to 200 |
| `topic` | REST, batch | what the audio is about: up to 1,600 characters on REST; batch needs 30-1,600 |
| `speaker_names` | REST, batch | 1-4 names that may be spoken |
| `previous_text` | REST | transcript of the previous clip (the last 600 characters are used) |

REST and streaming take any combination of the context options. Batch accepts only `keywords`,
`topic`, `topic` + `keywords`, or `speaker_names`. These options raise `ValueError` with any other model. REST audio is limited
to 30 s per request with this model.

Responses add `detected_language_code` (judged from the transcript's script) and, if the
model had to cut the text short, `truncated: true`.

**Streaming:**

```python
from gnani.stt import GnaniSTTStreamClient, StreamTranscriptEvent

async with GnaniSTTStreamClient(
    language_code="indic-auto",
    model="prisma-v3.0",
    language_candidates=["hi-IN", "en-IN"],   # optional
    keywords=["Vachana", "UPI"],              # optional
) as stream:
    async for event in stream:
        if isinstance(event, StreamTranscriptEvent):
            print(event.detected_language_code, event.text)
```

**Batch:**

```python
from gnani.stt import GnaniSTTBatchClient

result = GnaniSTTBatchClient().transcribe(
    "./calls/",
    language_code="hi-IN,en-IN",        # one code, "auto", or 2-4 codes
    model="prisma-v3.0",
    format="transcribe",
    keywords=["HDFC Bank", "EMI"],
    speakers=2,
)
for f in result:
    print(f.name, f.language)           # language covering the most speech
    for seg in f.segments:
        print(seg.language, seg.text)   # language of each segment
```

With `prisma-v3.0` the language is decided per segment by the model, so there is no
fallback language and order in `language_code` does not matter.

## Batch STT Usage

Batch jobs run asynchronously: create, start, wait, fetch. `transcribe()` does all four.
Limits: 100 files per job, 10 MB per file (ZIP: 50 MB). Larger files are not supported yet.

```python
from gnani.stt import GnaniSTTBatchClient

client = GnaniSTTBatchClient()

# Files can be a path, a directory, a glob, a ZIP, bytes, a file object, or public URLs.
result = client.transcribe("./recordings/", language_code="hi-IN,en-IN", speakers=2)

for f in result:
    print(f.name, "OK" if f.ok else f"FAILED: {f.error}")
    if f.ok:
        for seg in f.segments:
            print(f"  [{seg.start:.1f}-{seg.end:.1f}] speaker {seg.speaker}: {seg.text}")
```

### Step by step (long jobs, resuming later)

```python
job = client.create_job("./recordings/*.wav", language_code="hi-IN")  # starts automatically
print(job.id)                      # keep this to resume
job.wait(timeout=3600, on_progress=lambda j: print(j.status, j.percent))

job = client.get_job("<job id>")   # e.g. after a restart
files = job.files()
job.save("./outputs", text_files=True)
```

`language_code` takes one code, several comma-separated (identified per speaker turn; the
first is the fallback), or `"auto"`. Other options: `model`, `diarization`, `speakers` (1-8),
`multi_channel`, `denoise`, `bias_words`, `bias_score`, `callback_url`, `start=False`, and
for `model="prisma-v3.0"` also `format`, `keywords`, `topic` and `speaker_names` (see
[Prisma v3.0](#prisma-v30-multilingual-model)).

### Async

`AsyncGnaniSTTBatchClient` has the same methods, awaited. Transcripts are downloaded
concurrently, so `.text` and `.segments` are plain attributes on what `transcribe()` returns
(after `job.files()` call `await f.load()`, or pass `load=True`).

```python
from gnani.stt import AsyncGnaniSTTBatchClient

client = AsyncGnaniSTTBatchClient()
result = await client.transcribe("./recordings/", language_code="hi-IN")
print(result[0].text)
await result.save("./outputs")

async for job in client.list_jobs(status="COMPLETED"):
    print(job.id)
```

`wait()` returns for `COMPLETED` and `PARTIAL_FAILURE` (check each `BatchFile.ok`) and raises
`BatchJobFailedError` for `FAILED`, `START_FAILED` and `CANCELLED`, and `BatchTimeoutError`
on timeout (the job keeps running). It polls every 10 s, the documented minimum.

## Realtime Streaming Usage

### Connection Flow

1. Client opens a WebSocket connection to `wss://api.vachana.ai/stt/v3/stream` with auth headers.
2. Server sends a `connected` event with the active configuration.
3. Client sends binary PCM audio frames (1024 bytes each = 512 samples at 16-bit).
4. Server detects speech via VAD and responds with `processing` and `transcript` events.
5. Either side may close the connection at any time.

### PCM Specification

All audio must be sent as **raw PCM binary frames**. No container format (WAV, MP3, etc.) is accepted mid-stream.

| Property          | 16 kHz                                    | 8 kHz                                     |
|-------------------|-------------------------------------------|-------------------------------------------|
| Encoding          | PCM signed 16-bit little-endian           | PCM signed 16-bit little-endian           |
| Sample Rate       | 16,000 Hz                                 | 8,000 Hz                                  |
| Channels          | 1 (mono)                                  | 1 (mono)                                  |
| Samples per chunk | 512                                       | 512                                       |
| **Bytes per frame** | **1,024 bytes** (512 samples × 2 bytes) | **1,024 bytes** (512 samples × 2 bytes)   |
| Frame duration    | 32 ms                                     | 64 ms                                     |

- Each binary frame must be **exactly 1,024 bytes**.
- Frames must be sent at **real-time cadence** — one frame every 32 ms (16 kHz) or 64 ms (8 kHz). Do not buffer and burst; this degrades VAD accuracy.
- For `44100` and `48000` Hz sources, the server resamples internally — still send 1,024-byte frames at the appropriate cadence.

For the full WebSocket protocol reference, see **[STT Realtime — PCM Specification](https://docs.gnani.ai/api/STT/stt-websocket#pcm-specification)**.

### Using the async context manager

```python
import asyncio
from gnani.stt import GnaniSTTStreamClient, StreamTranscriptEvent

async def main():
    async with GnaniSTTStreamClient(
        api_key="your-api-key",
        language_code="hi-IN",
        sample_rate=16000,
    ) as stream:
        print(f"Connected! Sample rate: {stream.connected_config.sample_rate}")

        with open("audio.pcm", "rb") as f:
            while chunk := f.read(1024):
                await stream.send_audio(chunk)
                await asyncio.sleep(0.032)

        async for event in stream:
            if isinstance(event, StreamTranscriptEvent):
                print(f"[{event.segment_index}] {event.text}")
                print(f"  Duration: {event.audio_duration_ms}ms, Latency: {event.latency}ms")

asyncio.run(main())
```

### Manual connect / close

```python
import asyncio
from gnani.stt import GnaniSTTStreamClient, StreamTranscriptEvent

async def main():
    stream = GnaniSTTStreamClient(api_key="your-api-key")
    config = await stream.connect()
    print(f"Server ready: {config.message}")

    await stream.send_audio(audio_chunk)
    transcripts = await stream.close()

    for t in transcripts:
        print(t.text)

asyncio.run(main())
```

### High-level stream_audio helper with callbacks

```python
import asyncio
from gnani.stt import GnaniSTTStreamClient, StreamTranscriptEvent, StreamProcessingEvent

async def main():
    async with GnaniSTTStreamClient(api_key="your-api-key") as stream:
        with open("audio.pcm", "rb") as f:
            transcripts = await stream.stream_audio(
                f,
                on_transcript=lambda t: print(f"Transcript: {t.text}"),
                on_processing=lambda p: print(f"Processing at {p.timestamp}..."),
                realtime_pace=True,
            )

    print(f"Total segments: {len(transcripts)}")

asyncio.run(main())
```

### Number formatting (ITN) on streaming

`format` is sent as `x-format`. Leave it out for the server default (ITN on for `hi-IN` and
`en-IN`, off for other languages), pass `"verbatim"` to switch ITN off, or `"transcribe"` to
switch it on. `enable_itn=True` (`x-enable-itn`) turns ITN on without choosing a format, and
`itn_native_numerals=True` (`x-itn-native-numerals`) writes digits in the native script
whenever ITN runs — it does not turn ITN on by itself.

```python
GnaniSTTStreamClient(language_code="hi-IN", format="verbatim")    # Hindi, ITN off
GnaniSTTStreamClient(language_code="ta-IN", enable_itn=True,      # Tamil, ITN on,
                     itn_native_numerals=True)                    # native digits
```

### Tuning voice-activity detection (VAD)

The server cuts the audio into speech segments with VAD. Six options tune it. Each is sent as a
connection header and is fixed for the life of the connection (to change one, reconnect). Leave an
option out to keep the server default. Values outside the range raise `ValueError` when the
client is created, before anything is sent.

| Option             | Header               | Default             | Range        | What it does |
| ------------------ | -------------------- | ------------------- | ------------ | ------------ |
| `vad_threshold`    | `x-vad-threshold`    | `0.7`               | `0.0`–`1.0`  | Speech-probability threshold. Higher rejects more noise but may miss soft speech. |
| `min_silence_ms`   | `x-min-silence-ms`   | `500`               | `100`–`2000` | Silence after speech before a segment is closed and transcribed. The main latency knob. |
| `min_speech_ms`    | `x-min-speech-ms`    | `100` (`200` at 8 kHz) | `50`–`2000` | Speech needed before a segment opens. Raise it in noisy rooms. |
| `min_segment_ms`   | `x-min-segment-ms`   | `120`               | `100`–`1000` | Shorter segments are dropped without a transcript. |
| `max_speech_s`     | `x-max-speech-s`     | no limit            | `5.0`–`120.0` | Longest a segment may run before it is cut. |
| `idle_timeout_sec` | `x-idle-timeout-sec` | `60`                | `5`–`900`    | Seconds without speech before the server ends the session. |

```python
# Faster final transcripts on a clean line (may split a sentence at a pause)
GnaniSTTStreamClient(language_code="hi-IN", vad_threshold=0.5, min_silence_ms=300)

# Noisy call: stricter detection, longer pauses allowed, one-minute segment cap
GnaniSTTStreamClient(language_code="en-IN", sample_rate=8000,
                     vad_threshold=0.75, min_speech_ms=300, max_speech_s=60.0)
```

The ranges are available as `gnani.stt.STREAM_TUNING_OPTIONS`, and
`gnani.stt.validate_stream_tuning(name, value)` checks one value.

### Using 8 kHz audio

```python
stream = GnaniSTTStreamClient(
    api_key="your-api-key",
    language_code="en-IN",
    sample_rate=8000,
)
```

### Event Types

All events are typed dataclasses:

| Event                    | Fields                                                                 | Description                                  |
|--------------------------|------------------------------------------------------------------------|----------------------------------------------|
| `StreamConnectedEvent`   | `message`, `timestamp`, `sample_rate`, `chunk_size`, `raw`             | Handshake confirmation with server config    |
| `StreamProcessingEvent`  | `timestamp`, `raw`                                                     | VAD detected end-of-speech, transcribing     |
| `StreamTranscriptEvent`  | `text`, `audio_duration_ms`, `segment_id`, `segment_index`, `latency`, `timestamp`, `raw`, `detected_language_code` (`prisma-v3.0` only) | Completed transcription for a speech segment |
| `StreamErrorEvent`       | `message`, `timestamp`, `raw`                                          | Server-side error                            |

### Accessing the raw JSON payload

Every event includes a `raw` field with the full server JSON:

```python
async for event in stream:
    print(event.raw)  # dict with the complete server response
```

## Text-to-Speech Usage

> Input text is normalized server-side; see the [Text Normalization Guide](https://docs.gnani.ai/api/TTS/tts-input-formating) for symbols, numbers, and abbreviations.

### TTS Models

```python
from gnani.tts import DEFAULT_MODEL, SUPPORTED_MODELS

print(DEFAULT_MODEL)              # timbre-v2.5
print(sorted(SUPPORTED_MODELS))   # timbre-v2.5, timbre-v3.0
```

### TTS REST

```python
from gnani.tts import GnaniTTSClient

client = GnaniTTSClient(api_key="your-api-key")
# Default audio_config uses sample_rate=48000
audio = client.synthesize("यह एक टेस्ट है", voice="Pranav", model="timbre-v2.5")
with open("tts_rest.wav", "wb") as f:
    f.write(audio)
```

### TTS Streaming (SSE)

Lower latency than REST — audio is streamed via Server-Sent Events.

```python
from gnani.tts import GnaniTTSStreamClient, AudioConfig

client = GnaniTTSStreamClient(api_key="your-api-key")

# synthesize() collects all chunks and returns audio matching audio_config
audio = client.synthesize(
    "Streaming TTS response",
    voice="Pranav",
    model="timbre-v2.5",
    audio_config=AudioConfig(sample_rate=48000, encoding="linear_pcm", container="wav"),
    output_file="tts_sse.wav",
)
```

For chunk-by-chunk streaming (e.g. real-time playback), use `synthesize_stream()`:

```python
for audio_chunk in client.synthesize_stream("Hello!", voice="Pranav", model="timbre-v2.5"):
    play_audio(audio_chunk)  # format depends on audio_config (PCM, OGG, MP3, etc.)
```

### TTS Realtime (WebSocket)

Lowest latency — audio is streamed over a persistent WebSocket connection.

```python
import asyncio
from gnani.tts import GnaniTTSRealtimeClient, AudioConfig

async def main():
    async with GnaniTTSRealtimeClient(api_key="your-api-key") as client:
        # synthesize_and_collect() returns audio matching audio_config
        audio = await client.synthesize_and_collect(
            "Realtime TTS response",
            voice="Kaveri",
            model="timbre-v2.5",
            audio_config=AudioConfig(sample_rate=48000, encoding="linear_pcm", container="wav"),
            output_file="tts_realtime.wav",
        )

asyncio.run(main())
```

For chunk-by-chunk streaming (e.g. real-time playback):

```python
async with GnaniTTSRealtimeClient(api_key="your-api-key") as client:
    async for audio_chunk in client.synthesize("Hello!", voice="Pranav", model="timbre-v2.5"):
        play_audio(audio_chunk)  # format depends on audio_config (PCM, OGG, MP3, etc.)
```

### TTS language and speed (`timbre-v2.5`, `timbre-v3.0`)

```python
from gnani.tts import GnaniTTSClient, AudioConfig

client = GnaniTTSClient(api_key="your-api-key")
audio = client.synthesize(
    "Hello, this is a Timbre test.",
    voice="Avinash",
    model="timbre-v3.0",
    language="en-IN",
    speed=1.2,                # timbre-v3.0: 0.8-1.2; omit to use the voice's own speed
    audio_config=AudioConfig(container="mp3", sample_rate=48000, bitrate="128k"),
)
```

The same `model`, `language` and `speed` parameters work on `GnaniTTSStreamClient` (SSE) and `GnaniTTSRealtimeClient` (WebSocket).

### TTS Telephony Formats

For telephony integrations (IVR, SIP), use 8 kHz A-law or μ-law:

```python
from gnani.tts import GnaniTTSClient, AudioConfig

client = GnaniTTSClient(api_key="your-api-key")

# A-law (G.711a) — common in European/Indian telephony
alaw_audio = client.synthesize(
    "Hello from Gnani",
    voice="Pranav",
    audio_config=AudioConfig(container="alaw", sample_rate=8000),
)

# μ-law (G.711u) — common in North American telephony
mulaw_audio = client.synthesize(
    "Hello from Gnani",
    voice="Pranav",
    audio_config=AudioConfig(container="mulaw", sample_rate=8000),
)
```

### TTS OGG/Opus

Returns a playable OGG Opus file (`OggS` header). Use either form:

- `container="ogg"` (encoding defaults to `oggopus`)
- `container="raw", encoding="oggopus"`

Supported at all standard sample rates (8000–48000).

```python
from gnani.tts import GnaniTTSClient, AudioConfig

client = GnaniTTSClient(api_key="your-api-key")

# Using container="ogg"
ogg_audio = client.synthesize(
    "Hello from Gnani",
    voice="Pranav",
    audio_config=AudioConfig(container="ogg", encoding="oggopus", sample_rate=48000),
)

with open("output.ogg", "wb") as f:
    f.write(ogg_audio)
```

**SSE / WebSocket:** OGG is delivered as one complete file in a single chunk (not streamable frame-by-frame). For chunk iteration, use `synthesize_stream()` (SSE) or async `synthesize()` (WebSocket) — the buffered `synthesize()` and `synthesize_and_collect()` methods correctly return the raw OGG bytes without WAV wrapping when using non-PCM encodings.

### TTS Audio Format Matrix

Supported combinations of `container`, `encoding`, `sample_rate`, and `bitrate`:

| Container | Encoding | Sample Rates | Bitrate | Notes |
|-----------|----------|--------------|---------|-------|
| `wav` | `linear_pcm` | 8000, 16000, 22050, 24000, 44100, 48000 | — | Standard WAV (RIFF header) |
| `mp3` | `linear_pcm` | 8000, 16000, 22050, 24000, 44100, 48000 | `32k`, `64k`, `96k`, `128k`, `192k` | All 5 bitrates supported |
| `raw` | `linear_pcm` | 8000, 16000, 22050, 24000, 44100, 48000 | — | Raw PCM, no header |
| `ogg` | `oggopus` | 8000, 16000, 22050, 24000, 44100, 48000 | — | Playable OGG Opus file |
| `raw` | `oggopus` | 8000, 16000, 22050, 24000, 44100, 48000 | — | Equivalent to `ogg` |
| `mulaw` | `linear_pcm` | 8000 | — | G.711μ telephony |
| `alaw` | `linear_pcm` | 8000 | — | G.711A telephony |

**Notes:**
- `bitrate` is **only** applicable to `container="mp3"`. It is ignored for all other containers.
- `mulaw` and `alaw` containers are **telephony-only** — they require `sample_rate=8000`.
- For telephony, prefer `container="alaw"` / `container="mulaw"` over `encoding="pcm_alaw"` / `encoding="pcm_mulaw"`.
- `container="ogg"` and `container="raw"` with `encoding="oggopus"` are equivalent — both return a playable OGG Opus file.

> **File extensions:** Match the output file extension to your `audio_config.container` — use `.wav` for WAV, `.mp3` for MP3, `.ogg` for OGG/Opus, `.raw` for raw PCM, `.alaw` / `.ulaw` for telephony.

### TTS Supported Constants

```python
from gnani.tts import (
    SUPPORTED_ENCODINGS,     # {"linear_pcm", "oggopus", "pcm_mulaw", "pcm_alaw"}
    SUPPORTED_CONTAINERS,    # {"raw", "mp3", "wav", "ogg", "mulaw", "alaw"}
    SUPPORTED_BITRATES,      # {"32k", "64k", "96k", "128k", "192k"}
    SUPPORTED_SAMPLE_RATES,  # (8000, 16000, 22050, 24000, 44100, 48000)
    DEFAULT_SPEED,           # 1.0
    MIN_SPEED,               # 0.85  (the timbre-v2.5 range, kept for compatibility)
    MAX_SPEED,               # 1.15
    SPEED_RANGES,            # {"timbre-v2.5": (0.85, 1.15), "timbre-v3.0": (0.8, 1.2)}
)
```

### TTS Voices

List voices for a specific model:

```python
from gnani.tts import GnaniTTSClient, TIMBRE_V25_VOICES, TIMBRE_V30_VOICES

print(GnaniTTSClient.supported_voices())                    # 42 voices (timbre-v2.5, the default)
print(GnaniTTSClient.supported_voices(model="timbre-v3.0")) # 34 voices
print(len(TIMBRE_V25_VOICES), len(TIMBRE_V30_VOICES))       # 42 34
```

Each voice is valid for its own model only.

## Audio Requirements

### STT REST

| Constraint       | Value                                      |
|------------------|--------------------------------------------|
| Formats          | WAV, MP3, FLAC, OGG, M4A                   |
| Max duration     | 60 seconds                                 |
| Channels         | Mono or stereo                             |
| Sample rate      | Automatically converted to 16 kHz mono     |

### STT Streaming (WebSocket)

| Constraint       | Value                                                  |
|------------------|--------------------------------------------------------|
| Encoding         | Raw PCM, signed 16-bit little-endian                   |
| Sample rate      | 16,000 Hz or 8,000 Hz                                  |
| Channels         | 1 (mono)                                               |
| Frame size       | 1,024 bytes (512 samples)                              |
| Pacing           | Send frames at real-time cadence for best VAD accuracy |

See **[PCM Specification](https://docs.gnani.ai/api/STT/stt-websocket#pcm-specification)** for full details.

## Response Format

### REST

```json
{
  "success": true,
  "request_id": "req_abc123",
  "timestamp": "20251226_143052.123",
  "transcript": "नमस्ते, आप कैसे हैं?"
}
```

### Realtime Streaming

**Connected:**
```json
{
  "type": "connected",
  "message": "STT service ready — VAD service connected",
  "timestamp": "2024-01-15T10:30:00.000Z",
  "config": { "sample_rate": 16000, "chunk_size": 512 }
}
```

**Transcript:**
```json
{
  "type": "transcript",
  "timestamp": "2024-01-15T10:30:05.987Z",
  "text": "Hello, how are you today?",
  "audio_duration_ms": 2340,
  "segment_id": "<segment_id>",
  "segment_index": "<segment_index>",
  "latency": 320
}
```

## Error Handling

```python
from gnani.stt import (
    AuthenticationError,
    InvalidAudioError,
    APIError,
    StreamConnectionError,
    StreamClosedError,
    StreamError,
)

# REST errors
try:
    result = client.transcribe("audio.wav", language_code="hi-IN")
except AuthenticationError:
    print("Check your credentials")
except InvalidAudioError as e:
    print(f"Bad audio file: {e}")
except APIError as e:
    print(f"API error {e.status_code}: {e}")

# Streaming errors
try:
    async with GnaniSTTStreamClient(api_key="key") as stream:
        await stream.send_audio(chunk)
except StreamConnectionError as e:
    print(f"Connection failed: {e}")
except StreamClosedError as e:
    print(f"Stream already closed: {e}")
except StreamError as e:
    print(f"Server error: {e} (at {e.timestamp})")
```

### TTS Errors

```python
from gnani.tts import (
    GnaniTTSClient,
    GnaniTTSRealtimeClient,
    AuthenticationError,
    APIError,
    StreamConnectionError,
    StreamError,
)

# REST / SSE errors
try:
    audio = GnaniTTSClient(api_key="key").synthesize("Hello", voice="Pranav")
except AuthenticationError:
    print("Check your API key")
except APIError as e:
    print(f"TTS API error {e.status_code}: {e}")

# WebSocket errors
try:
    async with GnaniTTSRealtimeClient(api_key="key") as client:
        audio = await client.synthesize_and_collect("Hello", voice="Pranav")
except StreamConnectionError as e:
    print(f"WebSocket connection failed: {e}")
except StreamError as e:
    print(f"TTS stream error: {e}")
```

## Documentation

Full API reference and guides are available at **[docs.gnani.ai](https://docs.gnani.ai/)**.

- [STT REST API](https://docs.gnani.ai/api/STT/speech-to-text)
- [STT Realtime WebSocket](https://docs.gnani.ai/api/STT/stt-websocket)
- [TTS REST API](https://docs.gnani.ai/api/TTS/tts-inference)
- [TTS Streaming (SSE)](https://docs.gnani.ai/api/TTS/tts-sse)
- [TTS Realtime WebSocket](https://docs.gnani.ai/api/TTS/tts-websocket)
- [Text Normalization Guide](https://docs.gnani.ai/api/TTS/tts-input-formating)

## License

This project is licensed under the MIT License -- see the [LICENSE](LICENSE) file for details.
