Metadata-Version: 2.4
Name: gl-speech
Version: 0.0.4
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. Rate limits (429) are retryable. Server errors (5xx), 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 after it was sent is not retryable, because the server may have accepted it already; check with `list_jobs` or `get_job` before sending it again. `e.recovery["retry_after_seconds"]` is set when a retryable response sent `Retry-After`, as the rate limiter does on a 429 with an empty body.

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 (`e.status_code` is the HTTP status). 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. `livekit-agents` retries every one of them up to `max_retry`, whatever `e.retryable` says, because `STT.recognize` and `ChunkedStream` do not check it. After the last STT attempt it raises its own `APIConnectionError`; read the GL Speech error from `e.__cause__`. 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 429 or 5xx handshake sends `Retry-After`, 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. `result.recovery` is `None` when the server does not send it, and `retryable` is `None` when `recovery` comes without 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.

## 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.
