Metadata-Version: 2.5
Name: voice2voice
Version: 0.1.2
Summary: Synchronous and asynchronous Python SDK for the Voice2Voice Translator API
Project-URL: Homepage, https://voice2voice-translator.onrender.com/
Project-URL: Repository, https://github.com/ehsanulhaqislamyar-star/voice2voice-python
Project-URL: Issues, https://github.com/ehsanulhaqislamyar-star/voice2voice-python/issues
Author-email: Ehsanulhaq Islamyar <ehsanulhaqislamyar@gmail.com>
License-Expression: MIT
License-File: LICENSE
Keywords: API-client,async,audio,httpx,python,sdk,speech,speech-to-text,text-to-speech,translation,voice,voice-to-voice
Classifier: Development Status :: 3 - Alpha
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
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.9
Requires-Dist: httpx<1.0,>=0.27
Provides-Extra: dev
Requires-Dist: build>=1.2; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: twine>=5.0; extra == 'dev'
Description-Content-Type: text/markdown

# Voice2Voice Python SDK

### 🌐 **Official Website:** [Voice2Voice Translator](https://voice2voice-translator.onrender.com/)
#### Try the Voice2Voice Translator web application to convert speech between languages.

[![Python versions](https://img.shields.io/badge/python-3.9%2B-blue)](https://www.python.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)

A Python SDK for the **Voice2Voice Translator API**. It provides synchronous
and asynchronous clients for discovering supported languages, translating
audio, downloading generated audio, checking visitor quotas, and managing
administrator quota settings.

> **Release status:** `0.1.1` — early release. The SDK interface and server API
> may evolve.

## Features

- Synchronous client: `Voice2VoiceClient`
- Asynchronous client: `AsyncVoice2VoiceClient`
- Audio upload and translation
- Download translated audio
- Retrieve supported languages and visitor quota
- Optional administrator operations using a bearer token
- Typed result models and specific API exceptions
- Configurable request timeout
- Reusable HTTPX clients and context-manager support
- Persistent anonymous visitor ID when the server issues the
  `vt_visitor_id` cookie

## Requirements

- Python 3.9 or newer
- Access to a running Voice2Voice API server
- `httpx` (installed automatically)

## Installation

```bash
python -m pip install voice2voice
```

## Quick start

### Synchronous client

```python
from voice2voice import Voice2VoiceClient, APIError, QuotaExceededError

with Voice2VoiceClient() as client:
    languages = client.languages()
    print([(language.code, language.name) for language in languages])

    print("Quota:", client.quota())

    result = client.translate(
        file="sample.mp3",
        source_language="en",
        target_language="es",
        output_format="mp3",
    )

    print("Recognized:", result.recognized_text)
    print("Cleaned:", result.cleaned_text)
    print("Translated:", result.translated_text)

    audio = client.download_audio(result)
    with open(audio.filename, "wb") as output_file:
        output_file.write(audio.content)
```

Handle API-specific errors when needed:

```python
from voice2voice import Voice2VoiceClient, APIError, QuotaExceededError

try:
    with Voice2VoiceClient() as client:
        result = client.translate(
            file="sample.mp3",
            source_language="en",
            target_language="es",
        )
except QuotaExceededError as exc:
    print("Quota exceeded:", exc.message)
    print("Remaining seconds:", exc.remaining_seconds)
except APIError as exc:
    print(f"API request failed ({exc.status_code}): {exc.message}")
```

### Asynchronous client

Use `async with` to close the asynchronous HTTPX client reliably:

```python
import asyncio
from voice2voice import AsyncVoice2VoiceClient

async def main():
    async with AsyncVoice2VoiceClient() as client:
        languages = await client.languages()
        print([(language.code, language.name) for language in languages])

        result = await client.translate(
            file="sample.mp3",
            source_language="en",
            target_language="es",
            output_format="mp3",
        )

        print("Translated:", result.translated_text)

        audio = await client.download_audio(result)
        with open(audio.filename, "wb") as output_file:
            output_file.write(audio.content)

asyncio.run(main())
```

## Configuration

Both clients accept the following configuration options:

```python
from voice2voice import Voice2VoiceClient

client = Voice2VoiceClient(
    base_url="https://your-api.example.com",
    timeout=120.0,
)
```

| Option | Description |
|---|---|
| `base_url` | Base URL of the Voice2Voice API. Defaults to the hosted API configured by the SDK. |
| `visitor_id` | Optional previously obtained anonymous visitor ID. |
| `admin_token` | Bearer token used by administrator methods. |
| `timeout` | HTTPX request timeout in seconds. Set to `None` to disable the timeout. |
| `http_client` | Optional existing `httpx.Client`. The async client accepts an `httpx.AsyncClient`. |

When an external HTTPX client is injected, the SDK does **not** close it.
The caller remains responsible for managing its lifecycle. Requests use the
SDK's configured `base_url`, independently of the injected HTTPX client's
`base_url`.

Example with an externally managed HTTPX client:

```python
import httpx
from voice2voice import Voice2VoiceClient

transport = httpx.Client(timeout=45.0)

try:
    with Voice2VoiceClient(
        base_url="https://your-api.example.com",
        http_client=transport,
    ) as client:
        print(client.languages())
finally:
    transport.close()
```

## Anonymous visitor identity

The API server may issue a `vt_visitor_id` cookie to identify an anonymous
visitor and track that visitor's quota. The SDK exposes the current value:

```python
visitor_id = client.visitor_id
```

When the server issues this cookie, the SDK attempts to persist it at:

```text
~/.voice2voice/visitor.json
```

The SDK continues working if the file cannot be read or written. You can also
pass `visitor_id=...` explicitly to restore an identity.

Treat visitor IDs as private. Do not publish them, commit them to source
control, or expose them in logs.

## Administrator operations

Administrator methods require a valid server-issued admin token:

```python
from voice2voice import Voice2VoiceClient

with Voice2VoiceClient(admin_token="YOUR_ADMIN_TOKEN") as client:
    current = client.admin_quota()
    print(current)

    updated = client.update_admin_quota(
        quota_seconds=180,
        period_type="daily",
    )
    print(updated)
```

Keep the token in an environment variable or secret manager rather than
hard-coding it.

The async client provides the equivalent methods:

```python
current = await client.admin_quota()

updated = await client.update_admin_quota(
    quota_seconds=180,
    period_type="daily",
)
```

The accepted `period_type` values and quota-update semantics are defined by
the API server. Check the server's current documentation before changing
administrator settings.

## API methods

| Method | Description |
|---|---|
| `languages()` | Return the languages advertised by the API. |
| `translate(file, source_language, target_language, output_format="mp3")` | Upload audio and return translation data. |
| `quota()` | Retrieve the current visitor's quota information. |
| `download_audio(result_or_url)` | Download generated audio and return an `AudioDownload`. |
| `admin_quota()` | Retrieve administrator quota settings. |
| `update_admin_quota(quota_seconds, period_type, custom_period_seconds=86400)` | Update administrator quota settings. |

For `AsyncVoice2VoiceClient`, use `await` with each method. It also provides
`aclose()` and asynchronous context-manager support.

Language codes, supported audio formats, upload limits, and quota behavior
are determined by the API server. Retrieve the current language list with
`client.languages()` and consult the server's current API documentation for
accepted formats and limits.

## Return models

- `Language`: `name`, `code`
- `TranslationResult`: `recognized_text`, `cleaned_text`, `translated_text`,
  `audio_url`, `audio_filename`, and the original response dictionary in `raw`
- `AudioDownload`: downloaded `content` (`bytes`), `content_type`, and
  `filename`

These models are immutable dataclasses.

## Error handling

All SDK-specific exceptions inherit from `Voice2VoiceError`.

| Exception | Meaning |
|---|---|
| `Voice2VoiceError` | Base SDK exception. |
| `APIError` | Unsuccessful HTTP response; includes `status_code`, `message`, and `detail`. |
| `AuthenticationError` | HTTP 401 or 403 response. |
| `QuotaExceededError` | HTTP 429 response with the API's `quota_exceeded` error code. |

`QuotaExceededError` also exposes quota fields when the server includes them:
`limit_seconds`, `used_seconds`, `remaining_seconds`, `requested_seconds`,
and `reset_at`.

Network and file-system errors are not converted into `APIError`. Handle
exceptions such as `httpx.TimeoutException`, `httpx.ConnectError`, and
`OSError` where appropriate.

## Development

Clone the repository:

```bash
git clone https://github.com/ehsanulhaqislamyar-star/voice2voice-python.git
cd voice2voice-python
```

Install the development dependencies:

```bash
python -m pip install -e ".[dev]"
```

Run the test suite:

```bash
python -m pytest
```

Build the source distribution and wheel:

```bash
python -m build
```

Validate the distributions:

```bash
python -m twine check dist/*
```

## License

This project is licensed under the MIT License. See [LICENSE](LICENSE) for
the full license text.
