Metadata-Version: 2.4
Name: gl-speech
Version: 0.0.6
Summary: GL Speech Python Client - Python client library for Prosa Speech API
Author-email: GDP Labs <jobs@gdplabs.id>
Requires-Python: <3.14,>=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: gllm-core<0.5.0,>=0.4.53
Requires-Dist: httpx>=0.28.1
Requires-Dist: pydantic>=2.0.0
Provides-Extra: livekit
Requires-Dist: livekit-agents<2.0.0,>=1.1.0; extra == "livekit"
Requires-Dist: websockets>=12.0; extra == "livekit"
Dynamic: license-file

# GL Speech

A Python library for interacting with the GL Speech API, providing speech-to-text (STT), text-to-speech (TTS), and webhook management capabilities.

## Prerequisites

- **Python** ≥3.11,<3.14 (3.11, 3.12, or 3.13)

## Installation

```bash
pip install gl-speech
```

Or with uv:

```bash
uv add gl-speech
```

## Quick Start

STT and TTS use different API keys and base URLs. Create two clients. Webhooks for STT jobs use the STT client; webhooks for TTS jobs use the TTS client.

```python
from gl_speech import SpeechClient

stt_client = SpeechClient(api_key="your-stt-api-key", base_url="https://api.prosa.ai/v2/speech/")
tts_client = SpeechClient(api_key="your-tts-api-key", base_url="https://api.prosa.ai/v2/speech/")

# Speech-to-Text
result = stt_client.stt.transcribe(
    data="<base64-encoded-audio>",
    model="stt-general",
    wait=True
)
print(result.result)

# Text-to-Speech
result = tts_client.tts.synthesize(
    text="Hello, world!",
    model="tts-dimas-formal",
    wait=True
)
print(result.result)

# Webhooks: STT job events use STT client, TTS job events use TTS client
stt_endpoint = stt_client.webhooks.create_endpoint(
    url="https://your-server.com/webhook-stt",
    event_filters=["stt.job.completed"]
)
tts_endpoint = tts_client.webhooks.create_endpoint(
    url="https://your-server.com/webhook-tts",
    event_filters=["tts.job.completed"]
)
```

## Configuration

### Environment Variables

Set separate credentials for STT and TTS:

- `GLSPEECH_STT_API_KEY`: API key for Speech-to-Text
- `GLSPEECH_STT_BASE_URL`: Base URL for STT (default: `https://api.prosa.ai/v2/speech/`)
- `GLSPEECH_TTS_API_KEY`: API key for Text-to-Speech
- `GLSPEECH_TTS_BASE_URL`: Base URL for TTS (default: `https://api.prosa.ai/v2/speech/`)

Webhook management is per job type: use the STT client for STT job webhooks, the TTS client for TTS job webhooks.

### Client Initialization

```python
from gl_speech import SpeechClient

# Two clients (STT and TTS have different keys)
stt_client = SpeechClient(
    api_key="your-stt-api-key",
    base_url="https://api.prosa.ai/v2/speech/",
    timeout=60.0,
    default_headers={"X-Custom-Header": "value"}
)
tts_client = SpeechClient(
    api_key="your-tts-api-key",
    base_url="https://api.prosa.ai/v2/speech/",
    timeout=60.0,
    default_headers={"X-Custom-Header": "value"}
)

# Or from environment variables
import os
os.environ["GLSPEECH_STT_API_KEY"] = "your-stt-api-key"
os.environ["GLSPEECH_STT_BASE_URL"] = "https://api.prosa.ai/v2/speech/"
os.environ["GLSPEECH_TTS_API_KEY"] = "your-tts-api-key"
os.environ["GLSPEECH_TTS_BASE_URL"] = "https://api.prosa.ai/v2/speech/"
stt_client = SpeechClient(api_key=os.getenv("GLSPEECH_STT_API_KEY"), base_url=os.getenv("GLSPEECH_STT_BASE_URL"))
tts_client = SpeechClient(api_key=os.getenv("GLSPEECH_TTS_API_KEY"), base_url=os.getenv("GLSPEECH_TTS_BASE_URL"))
```

## Speech-to-Text (STT)

Use `stt_client` for all STT operations.

### List Available Models

```python
models = stt_client.stt.list_models()
for model in models:
    print(f"{model['name']}: {model['label']}")
```

### Transcribe Audio

```python
# Synchronous (wait for result)
result = stt_client.stt.transcribe(
    model="stt-general",
    wait=True,
    data="<base64-encoded-audio>",
    label="My audio file"
)
print(result.result)

# Asynchronous (get job_id, poll later)
result = stt_client.stt.transcribe(
    model="stt-general",
    wait=False,
    uri="https://example.com/audio.wav"
)
job_id = result.job_id

# Check status
status = stt_client.stt.get_status(job_id)
print(f"Status: {status.status}, Progress: {status.progress}")

# Get result when complete
result = stt_client.stt.get_job(job_id)
print(result.result)
```

### Advanced Configuration

```python
result = stt_client.stt.transcribe(
    model="stt-general",
    wait=True,
    data="<base64-encoded-audio>",
    speaker_count=2,           # Expected number of speakers
    include_filler=True,       # Include filler words
    auto_punctuation=True,     # Auto-add punctuation
    enable_spoken_numerals=True,  # Convert "one" to "1"
    enable_speech_insights=True,  # Speech analytics
    enable_voice_insights=True,   # Voice analytics
)
```

### List and Manage Jobs

```python
# List jobs with filters
jobs = stt_client.stt.list_jobs(
    page=1,
    per_page=10,
    from_date="2024-01-01",
    until_date="2024-01-31",
    query_text="hello"
)

# Archive a job
stt_client.stt.archive(job_id)
```

## Text-to-Speech (TTS)

Use `tts_client` for all TTS operations.

### List Available Models

```python
models = tts_client.tts.list_models()
for model in models:
    print(f"{model['name']}: {model['voice']} ({model['gender']})")
```

### Synthesize Speech

```python
# Synchronous (wait for result)
result = tts_client.tts.synthesize(
    text="Hello, world!",
    model="tts-dimas-formal",
    wait=True
)
audio_data = result.result["data"]  # Base64-encoded audio

# Get as signed URL instead
result = tts_client.tts.synthesize(
    text="Hello, world!",
    model="tts-dimas-formal",
    wait=True,
    as_signed_url=True
)
audio_url = result.result["path"]

# Asynchronous
result = tts_client.tts.synthesize(
    text="Long text content...",
    model="tts-dimas-formal",
    wait=False
)
job_id = result.job_id

# Poll for completion
result = tts_client.tts.get_job(job_id, as_signed_url=True)
```

### Advanced Configuration

```python
result = tts_client.tts.synthesize(
    text="Hello, world!",
    model="tts-dimas-formal",
    wait=True,
    pitch=0.5,           # Pitch adjustment (-1.0 to 1.0)
    tempo=1.2,           # Speed adjustment (0.5 to 2.0)
    audio_format="mp3",  # "opus", "mp3", or "wav"
    label="My synthesis"
)
```

### List and Manage Jobs

```python
# List jobs
jobs = tts_client.tts.list_jobs(page=1, per_page=10)

# Count jobs
count = tts_client.tts.count_jobs(from_date="2024-01-01")

# Get job status
status = tts_client.tts.get_status(job_id)

# Archive a job
tts_client.tts.archive(job_id)
```

## Webhook Management

### Webhooks and API keys

Webhook **management** is split by job type:

- **STT job webhooks** (e.g. `stt.job.completed`) use the **STT** API key and base URL → use `stt_client.webhooks`.
- **TTS job webhooks** (e.g. `tts.job.completed`) use the **TTS** API key and base URL → use `tts_client.webhooks`.

Create and manage endpoints on the client that matches the events you want to receive.

### Create a Webhook Endpoint

```python
# Endpoint for STT job events (uses STT key)
stt_endpoint = stt_client.webhooks.create_endpoint(
    url="https://your-server.com/webhook-stt",
    event_filters=["stt.job.completed"],
    ssl_verification=True
)

# Endpoint for TTS job events (uses TTS key)
tts_endpoint = tts_client.webhooks.create_endpoint(
    url="https://your-server.com/webhook-tts",
    event_filters=["tts.job.completed"],
    ssl_verification=True
)
print(f"STT Endpoint ID: {stt_endpoint.id}, Secret: {stt_endpoint.secrets[0].key}")
print(f"TTS Endpoint ID: {tts_endpoint.id}, Secret: {tts_endpoint.secrets[0].key}")
```

### List Endpoints

```python
# List STT webhook endpoints
stt_endpoints = stt_client.webhooks.list_endpoints()

# List TTS webhook endpoints
tts_endpoints = tts_client.webhooks.list_endpoints()
for ep in tts_endpoints:
    print(f"{ep.id}: {ep.url}")
```

### Update and Delete Endpoints

```python
# Update/delete on the same client you used to create (STT or TTS)
stt_client.webhooks.update_endpoint(
    endpoint_id="endpoint-123",
    url="https://your-server.com/new-webhook",
    event_filters=[]
)
stt_client.webhooks.delete_endpoint("endpoint-123")
```

### Rotate Secrets

```python
tts_client.webhooks.rotate_secret(
    endpoint_id="endpoint-123",
    days=3,  # Old secret valid for 3 days
    hours=0
)
```

### Event Management

```python
# List events (from the client whose webhooks you're querying)
events = tts_client.webhooks.list_events(
    from_date="2024-01-01",
    to_date="2024-01-31"
)
event = tts_client.webhooks.get_event("event-123")
print(event.data)
```

### Delivery Management

```python
deliveries = tts_client.webhooks.list_deliveries("endpoint-123")
ticket = tts_client.webhooks.replay_delivery("delivery-123")
tickets = tts_client.webhooks.replay_failed_deliveries("endpoint-123")
ticket = tts_client.webhooks.test_endpoint("endpoint-123")
```

## LiveKit Integration

GL Speech provides LiveKit agent plugins for real-time STT and TTS via WebSocket. Install the extra dependency first:

```bash
pip install "gl-speech[livekit]"
# or
uv add "gl-speech[livekit]"
```

### STT Plugin

```python
from gl_speech.livekit import STT

stt = STT(
    api_key="your-stt-api-key",
    wss_url="wss://your-stt-websocket-url",
    model="stt-general-online",  # default
    language="id-ID",            # default
)
```

### TTS Plugin

```python
from gl_speech.livekit import TTS

tts = TTS(
    api_key="your-tts-api-key",
    wss_url="wss://your-tts-websocket-url",
    model="tts-dimas-formal",  # default
)
```

### Voice Agent Example

Use both plugins together in a LiveKit `AgentSession` (livekit-agents 1.1 or later). The STT plugin transcribes whole utterances rather than streaming, so the session needs a VAD to split speech, here Silero (`pip install livekit-plugins-silero`):

```python
from livekit.agents import Agent, AgentSession, JobContext, WorkerOptions, cli
from livekit.plugins import openai, silero  # or any LLM plugin

from gl_speech.livekit import STT, TTS


async def entrypoint(ctx: JobContext):
    await ctx.connect()

    session = AgentSession(
        stt=STT(
            api_key="your-stt-api-key",
            wss_url="wss://your-stt-websocket-url",
        ),
        llm=openai.LLM(),
        tts=TTS(
            api_key="your-tts-api-key",
            wss_url="wss://your-tts-websocket-url",
        ),
        vad=silero.VAD.load(),
    )
    await session.start(
        agent=Agent(instructions="You are a helpful voice assistant."),
        room=ctx.room,
    )


if __name__ == "__main__":
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
```

Run the agent with:

```bash
python agent.py start
```

## Error Handling

API failures are subclasses of both `SpeechAPIError` and `httpx.HTTPStatusError`. `e.code` is the SDK code (`GL-SPCH-NOT-FOUND`, and so on). `e.api_code` is the server's code. `str(e)` is the server's message. `e.request` and `e.response` are unchanged, so existing `except httpx.HTTPStatusError` handlers still run.

Every SDK error has `e.recovery`, which says whether retrying can succeed without repeating a write. When the error body has the server's `recovery`, the SDK follows it; without one, as from older servers, rate limits (429), 408, 425, and server errors (5xx, except 501) are retryable. A `false` from the server is always kept. Connection failures and timeouts are retryable when the request never reached the server (a refused connection, or a connect or pool timeout) or its method is idempotent (GET, HEAD, OPTIONS, PUT, DELETE). A POST, such as `transcribe`, `synthesize`, or `create_endpoint`, that fails with a 5xx or after it was sent is not retryable, even when the server says it is, because the server may have accepted it already and its `recovery` cannot tell; check with `list_jobs` or `get_job` before sending it again. The one exception is a code that says the request was not acted on: a `job_queue_unavailable` 500 says the job was not created, so it is retryable. `e.recovery["retry_after_seconds"]` is set when a retryable error says how long to wait, in the body's `recovery` or a `Retry-After` header.

Retry a retryable error a few times with a growing wait, starting from `retry_after_seconds` when it is set. If it still fails, or right away for a non-retryable error you cannot fix by changing the request, contact support and quote `e.request_id` (for a failed job, its `job_id`).

Invalid arguments are `SpeechInvalidArgumentError` (also a `ValueError`). A body that is not JSON, is not a dict, list, or int, or does not match the response model is `SpeechMalformedResponseError` (also a `TypeError` and a `ValueError`, so existing `except ValueError` blocks still catch it). Empty and 204 responses are still `{}`.

Network failures are `SpeechTimeoutError` (also an `httpx.TimeoutException`) or `SpeechConnectionError`. Both are `SpeechTransportError`, which is also an `httpx.TransportError`. A handler for a narrower httpx type, such as `httpx.ConnectError`, no longer catches them. Catch `SpeechConnectionError` instead, and read the original httpx error from `e.__cause__`. `e.debug_info` names the original error's type but not its message, which can repeat a secret such as the API key.

```python
import httpx
from gl_speech import SpeechAuthError, SpeechClient, SpeechNotFoundError

stt_client = SpeechClient(api_key="your-stt-api-key", base_url="https://api.prosa.ai/v2/speech/")

try:
    result = stt_client.stt.transcribe(model="stt-general", data="invalid")
except SpeechAuthError as e:
    print(e.code, e.api_code, e.request_id, e.message)
except SpeechNotFoundError as e:
    print(e.message, e.request_id)
except httpx.HTTPStatusError as e:
    print(f"HTTP Error: {e.response.status_code}")
    print(e.message)
```

LiveKit plugins raise `SpeechStreamError` for an error frame, a 4000–4999 close, or a rejected websocket handshake. For a rejected handshake, `e.status_code` is the HTTP status, and `e.api_code` and `e.message` come from the server's error body, such as `auth_token_expired` for an expired token. `e.request_id` is set when the server sends one, in the body or the `X-Request-ID` header; the Speech API does not send one on a refused handshake today. They raise `SpeechStreamTimeoutError` when the stream times out, and `SpeechStreamConnectionError` when the stream cannot connect or closes unexpectedly. An invalid `wss_url` raises `SpeechInvalidArgumentError`. The stream errors are also LiveKit API errors, so `livekit-agents` retry and `FallbackAdapter` still apply. Whether `livekit-agents` honours `e.retryable` depends on its version. Older releases, such as the 1.5 this package's lock pins, retry every one of them up to `max_retry`, because `STT.recognize` and `ChunkedStream` do not check it, and after the last STT attempt raise their own `APIConnectionError`; read the GL Speech error from `e.__cause__`. Newer releases, such as 1.8.8, stop at an error whose `e.retryable` is false and raise it as is. A TTS stream that fails after it has sent audio ends with the audio it has, instead of raising, so a retry cannot play that audio twice. `e.retryable` follows the server's `recovery.retryable` when the error frame sends it. `e.recovery["retryable"]` gives the same answer. `e.context` is the frame's `context`, such as `{"reason": "token_expired"}` on `invalid_auth`. When a retryable frame sends `context.retry_after`, or a rejected retryable handshake sends a wait in its `recovery` body or `Retry-After` header, it is also `e.recovery["retry_after_seconds"]`. `SpeechStreamError` remains a `RuntimeError`.

The STT plugin returns the transcript when the server reports the session `complete` or closes the socket. If neither happens within the timeout, it raises `SpeechStreamTimeoutError`, even when some text has arrived, because that transcript is cut short. The wait for the server to be ready uses the same `conn_options.timeout`, and a socket that closes before the server is ready raises `SpeechStreamConnectionError`.

The TTS plugin raises `SpeechStreamConnectionError` when the socket closes before any audio arrives. After the first audio, it reads trailing chunks for a short window and then ends normally, because the server keeps the session open and sends no frame to mark the end.

A job that fails is not an exception: its `status` is `failed`. Its `result.error` is the server's error code, and newer servers repeat it as `result.code`. `result.message` says what failed, and `result.context` (a `JobErrorContext`) says why for a code with more than one cause, such as a `download_error` with `reason` `forbidden` and `upstream_status` `403`. `result.recovery.retryable` (a `JobErrorRecovery`) says whether submitting the same job again can succeed, and `result.recovery.retry_after_seconds` how long to wait first. `result.version` is the version of the error's shape. `result.recovery` is `None` when the server does not send it, and `retryable` and `retry_after_seconds` are `None` when `recovery` comes without them.

A failed webhook delivery from `list_deliveries` has `error_code`, such as `webhook_timeout` or `webhook_endpoint_rejected`, which says why it failed. It is `None` for a delivered event and on servers that do not send it.

Debug logs mask the API key, the `Authorization` header and webhook secrets. They log URLs without their query string, fragment or user info, so a signed URL's credential is not written. Inline audio is logged as its length. The LiveKit TTS plugin logs the text to synthesize as its length.

### Error codes

`e.code` is one of these SDK codes. It says what kind of failure happened and is set on every SDK error, including those that never reached the server. `e.api_code` is the server's own code, verbatim, such as `job_queue_unavailable` or `auth_token_expired`, and is set only on API and stream errors whose response or frame sent one; it is the finer-grained reason, so one `e.code` covers many `e.api_code` values. Branch on `e.code` for the kind of failure and on `e.api_code` for the exact reason, never on the message, whose wording may change. `e.version` is the version of the server's error shape when it sends one. The server's codes are on the GitBook Error Codes and Streaming Errors pages.

| Code | Class | Raised when | Retryable |
|---|---|---|---|
| `GL-SPCH-AUTH` | `SpeechAuthError` | The API rejects the credentials (401 or 403). | No |
| `GL-SPCH-VALIDATION` | `SpeechValidationError` | The API rejects the request payload (400 or 422). | No |
| `GL-SPCH-NOT-FOUND` | `SpeechNotFoundError` | The API cannot find the resource (404). | No |
| `GL-SPCH-RATE-LIMIT` | `SpeechRateLimitError` | The API rate-limits the caller (429). | Yes |
| `GL-SPCH-SERVER` | `SpeechServerError` | The API fails with a 5xx. | As the server's `recovery` says; without it, yes except for 501. Never for a POST, unless the code says it was not acted on (`job_queue_unavailable`) |
| `GL-SPCH-REQUEST-FAILED` | `SpeechRequestError` | Any other failed response, such as another 4xx or an unfollowed 3xx. | As the server's `recovery` says; without it, only 408 and 425 |
| `GL-SPCH-CONNECTION` | `SpeechConnectionError` | The SDK cannot connect to or talk with the API. | When the request was not sent, or its method is idempotent |
| `GL-SPCH-TIMEOUT` | `SpeechTimeoutError` | A request times out. | When the request was not sent, or its method is idempotent |
| `GL-SPCH-INVALID-ARG` | `SpeechInvalidArgumentError` | An argument the SDK cannot send, or an invalid `wss_url`. | No |
| `GL-SPCH-BAD-RESPONSE` | `SpeechMalformedResponseError` | The API returns a body the SDK cannot decode or that does not match its model. | No |
| `GL-SPCH-STREAM-ERROR` | `SpeechStreamError` | A LiveKit stream gets an error frame or a 4000–4999 close, or its handshake is refused. | As the frame's or the handshake body's `recovery` says. A refused handshake without one, as the Speech API sends today: 408, 425, 429, and 5xx except 501 |
| `GL-SPCH-STREAM-TIMEOUT` | `SpeechStreamTimeoutError` | A LiveKit stream times out before a usable result. | Yes |
| `GL-SPCH-STREAM-CONNECT` | `SpeechStreamConnectionError` | A LiveKit stream cannot connect or closes unexpectedly. | Yes |

## Testing

### Unit tests

```bash
cd libs/gl-speech
uv sync --group dev
uv run pytest tests/unit_tests/ -v
```

### Integration tests (live)

The integration tests exercise a real Prosa Speech instance. They carry the
`integration` marker and are **excluded from the default run**, so `uv run pytest`
never touches the network. Copy `.env.example` to `.env`, fill in your Prosa Speech
API keys, then select them explicitly with `-m integration`:

```bash
uv run pytest tests/integration_tests/ -m integration -v
```

STT and TTS are gated independently on `GLSPEECH_STT_API_KEY` / `GLSPEECH_TTS_API_KEY`,
so each service's live tests are skipped unless its key is present. Read-only calls
(`list_models`, `list_jobs`, `count_jobs`) run by default; set
`GLSPEECH_TEST_CREATE_JOBS=1` to also exercise the transcription/synthesis endpoints
that create real jobs. For a scheduled live job that must fail rather than skip when
credentials are missing, set `GLSPEECH_TEST_REQUIRE_LIVE=1`.

For a one-off manual check of every endpoint (including `archive` and the `webhooks`
surface, which the pytest suite does not cover), run the standalone acceptance
script instead:

```bash
python examples/verify_sdk.py
```

## API Reference

- [STT API Documentation](https://gdplabs.gitbook.io/gl-speech/api-contract/speech-to-text-stt)
- [TTS API Documentation](https://gdplabs.gitbook.io/gl-speech/api-contract/text-to-speech-tts)
- [Webhook API Documentation](https://gdplabs.gitbook.io/gl-speech/api-contract/webhooks)

## License

MIT License.
