convozen 0.3.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
convozen/__init__.py ADDED
@@ -0,0 +1,45 @@
1
+ __version__ = "0.3.1"
2
+
3
+ from .client import Client, STT, TTS
4
+
5
+ from convozen._internal.exceptions import (
6
+ ConvozenError,
7
+ AuthenticationError,
8
+ RateLimitError,
9
+ APIError,
10
+ )
11
+ from convozen._internal.enums import Language, AudioFormat, VoiceId
12
+ from convozen._internal.types import (
13
+ TTSResponse,
14
+ STTResponse,
15
+ CreditBalance,
16
+ Credits,
17
+ AccountInfo,
18
+ RateLimitInfo,
19
+ UsageSummary,
20
+ UsageByDay,
21
+ )
22
+
23
+ __all__ = [
24
+ "Client",
25
+ "STT",
26
+ "TTS",
27
+ # Enums
28
+ "Language",
29
+ "AudioFormat",
30
+ "VoiceId",
31
+ # Types
32
+ "TTSResponse",
33
+ "STTResponse",
34
+ "CreditBalance",
35
+ "Credits",
36
+ "AccountInfo",
37
+ "RateLimitInfo",
38
+ "UsageSummary",
39
+ "UsageByDay",
40
+ # Errors
41
+ "ConvozenError",
42
+ "AuthenticationError",
43
+ "RateLimitError",
44
+ "APIError",
45
+ ]
File without changes
@@ -0,0 +1,115 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import List
4
+
5
+ from .config import Config
6
+ from .transport.http import HTTPClient
7
+ from .transport.async_http import AsyncHTTPClient
8
+ from .types import AccountInfo, CreditBalance, Credits, RateLimitInfo, UsageSummary, UsageByDay
9
+
10
+
11
+ class AccountClient:
12
+ """
13
+ HTTP client for account- and usage-related endpoints.
14
+
15
+ Expects the API gateway to expose:
16
+ - GET /v1/account
17
+ - GET /v1/usage?start_date=YYYY-MM-DD&end_date=YYYY-MM-DD
18
+ """
19
+
20
+ def __init__(self, config: Config) -> None:
21
+ self._config = config
22
+ self._http = HTTPClient(config)
23
+ self._async_http = AsyncHTTPClient(config)
24
+
25
+ # ---- Synchronous API -------------------------------------------------
26
+
27
+ def info(self) -> AccountInfo:
28
+ response = self._http.get("/v1/account")
29
+ payload = response.json()
30
+
31
+ creds = payload.get("credits") or {}
32
+ tts_creds = creds.get("tts") or {}
33
+ stt_creds = creds.get("stt") or {}
34
+ credits = Credits(
35
+ tts=CreditBalance(balance=tts_creds.get("balance", 0)),
36
+ stt=CreditBalance(balance=stt_creds.get("balance", 0)),
37
+ )
38
+
39
+ rate = payload.get("rate_limit") or {}
40
+ rate_limit = RateLimitInfo(
41
+ requests_per_minute=rate.get("requests_per_minute", 0),
42
+ requests_per_day=rate.get("requests_per_day", 0),
43
+ )
44
+
45
+ return AccountInfo(
46
+ account_id=payload.get("account_id", ""),
47
+ plan=payload.get("plan", ""),
48
+ credits=credits,
49
+ rate_limit=rate_limit,
50
+ )
51
+
52
+ def usage(self, start_date: str, end_date: str) -> UsageSummary:
53
+ response = self._http.get(
54
+ "/v1/usage",
55
+ params={"start_date": start_date, "end_date": end_date},
56
+ )
57
+ payload = response.json()
58
+
59
+ by_day_payload = payload.get("by_day") or []
60
+ by_day: List[UsageByDay] = [
61
+ UsageByDay(date=item.get("date", ""), credits=item.get("credits", 0))
62
+ for item in by_day_payload
63
+ ]
64
+
65
+ return UsageSummary(
66
+ total_credits_used=payload.get("total_credits_used", 0),
67
+ by_model=payload.get("by_model", {}),
68
+ by_day=by_day,
69
+ )
70
+
71
+ # ---- Async API -------------------------------------------------------
72
+
73
+ async def ainfo(self) -> AccountInfo:
74
+ response = await self._async_http.get("/v1/account")
75
+ payload = response.json()
76
+
77
+ creds = payload.get("credits") or {}
78
+ tts_creds = creds.get("tts") or {}
79
+ stt_creds = creds.get("stt") or {}
80
+ credits = Credits(
81
+ tts=CreditBalance(balance=tts_creds.get("balance", 0)),
82
+ stt=CreditBalance(balance=stt_creds.get("balance", 0)),
83
+ )
84
+
85
+ rate = payload.get("rate_limit") or {}
86
+ rate_limit = RateLimitInfo(
87
+ requests_per_minute=rate.get("requests_per_minute", 0),
88
+ requests_per_day=rate.get("requests_per_day", 0),
89
+ )
90
+
91
+ return AccountInfo(
92
+ account_id=payload.get("account_id", ""),
93
+ plan=payload.get("plan", ""),
94
+ credits=credits,
95
+ rate_limit=rate_limit,
96
+ )
97
+
98
+ async def ausage(self, start_date: str, end_date: str) -> UsageSummary:
99
+ response = await self._async_http.get(
100
+ "/v1/usage",
101
+ params={"start_date": start_date, "end_date": end_date},
102
+ )
103
+ payload = response.json()
104
+
105
+ by_day_payload = payload.get("by_day") or []
106
+ by_day: List[UsageByDay] = [
107
+ UsageByDay(date=item.get("date", ""), credits=item.get("credits", 0))
108
+ for item in by_day_payload
109
+ ]
110
+
111
+ return UsageSummary(
112
+ total_credits_used=payload.get("total_credits_used", 0),
113
+ by_model=payload.get("by_model", {}),
114
+ by_day=by_day,
115
+ )
@@ -0,0 +1 @@
1
+ from .client import STT
@@ -0,0 +1,52 @@
1
+ import logging
2
+
3
+ from ..transport.http import HTTPClient
4
+ from ..transport.async_http import AsyncHTTPClient
5
+ from ..config import Config
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+
10
+ class STT:
11
+
12
+ def __init__(self, config: Config) -> None:
13
+ self.http = HTTPClient(config)
14
+ self.async_http = AsyncHTTPClient(config)
15
+
16
+ def transcribe(
17
+ self,
18
+ audio: str,
19
+ model: str = "akshara-v1",
20
+ ) -> str:
21
+ logger.debug("STT request: audio=%s model=%s", audio, model)
22
+
23
+ with open(audio, "rb") as f:
24
+ response = self.http.post(
25
+ "/v1/akshara/transcribe",
26
+ files={"file": f},
27
+ data={"model": model},
28
+ )
29
+
30
+ text: str = response.json()["text"]
31
+ logger.debug("STT response: text_length=%d", len(text))
32
+ return text
33
+
34
+ async def atranscribe(
35
+ self,
36
+ audio: str,
37
+ model: str = "akshara-v1",
38
+ ) -> str:
39
+ logger.debug("async STT request: audio=%s model=%s", audio, model)
40
+
41
+ with open(audio, "rb") as f:
42
+ audio_bytes = f.read()
43
+
44
+ response = await self.async_http.post(
45
+ "/v1/akshara/transcribe",
46
+ files={"file": ("audio", audio_bytes)},
47
+ data={"model": model},
48
+ )
49
+
50
+ text: str = response.json()["text"]
51
+ logger.debug("async STT response: text_length=%d", len(text))
52
+ return text
@@ -0,0 +1,36 @@
1
+ import os
2
+ from dataclasses import dataclass, field
3
+ from urllib.parse import urlparse
4
+
5
+
6
+ @dataclass
7
+ class Config:
8
+ api_key: str = field(default_factory=lambda: os.environ.get("CONVOZEN_API_KEY", ""))
9
+ base_url: str = field(
10
+ default_factory=lambda: os.environ.get("CONVOZEN_BASE_URL", "https://voice.convozen.ai/sdk-models/developer-api/api")
11
+ )
12
+ timeout: int = 60
13
+
14
+ def __post_init__(self) -> None:
15
+ if not self.api_key:
16
+ raise ValueError(
17
+ "api_key is required. Pass it explicitly or set the "
18
+ "CONVOZEN_API_KEY environment variable."
19
+ )
20
+ if not self.base_url:
21
+ raise ValueError(
22
+ "base_url is required. Pass it explicitly or set the "
23
+ "CONVOZEN_BASE_URL environment variable."
24
+ )
25
+
26
+ parsed = urlparse(self.base_url)
27
+ if parsed.scheme not in ("http", "https"):
28
+ raise ValueError(
29
+ f"base_url must start with http:// or https://, got: {self.base_url}"
30
+ )
31
+
32
+ if self.timeout <= 0:
33
+ raise ValueError(f"timeout must be positive, got: {self.timeout}")
34
+
35
+ # Strip trailing slash for consistent URL joining
36
+ self.base_url = self.base_url.rstrip("/")
@@ -0,0 +1,43 @@
1
+ from __future__ import annotations
2
+
3
+ from enum import Enum
4
+
5
+
6
+ class Language(str, Enum):
7
+ """Supported language codes (ISO 639-1)."""
8
+
9
+ EN = "en"
10
+ HI = "hi"
11
+ TA = "ta"
12
+ TE = "te"
13
+ KN = "kn"
14
+ MR = "mr"
15
+ BN = "bn"
16
+ GU = "gu"
17
+ ML = "ml"
18
+
19
+
20
+ class AudioFormat(str, Enum):
21
+ """Supported audio output formats for TTS."""
22
+
23
+ WAV = "wav"
24
+
25
+
26
+ class VoiceId(str, Enum):
27
+ """
28
+ Available voice IDs for TTS synthesis.
29
+
30
+ Backends may support more voices than are listed here; validation
31
+ functions are designed to accept any non-empty string so we do not
32
+ block new voices.
33
+ """
34
+
35
+ ROOHI = "roohi"
36
+ AMAYA = "amaya"
37
+ KIYANSH = "kiyansh"
38
+ NEERAJ = "neeraj"
39
+ MANYA = "manya"
40
+ NIDHI = "nidhi"
41
+ IRA = "ira"
42
+ TRISHA = "trisha"
43
+ CHARVI = "charvi"
@@ -0,0 +1,14 @@
1
+ class ConvozenError(Exception):
2
+ pass
3
+
4
+
5
+ class AuthenticationError(ConvozenError):
6
+ pass
7
+
8
+
9
+ class RateLimitError(ConvozenError):
10
+ pass
11
+
12
+
13
+ class APIError(ConvozenError):
14
+ pass
@@ -0,0 +1 @@
1
+ from .client import TTS
@@ -0,0 +1,123 @@
1
+ import logging
2
+ from typing import AsyncGenerator, Generator, Union
3
+
4
+ from ..transport.http import HTTPClient
5
+ from ..transport.async_http import AsyncHTTPClient
6
+ from ..config import Config
7
+ from ..utils.validation import (
8
+ validate_text,
9
+ validate_language,
10
+ validate_audio_format,
11
+ validate_voice,
12
+ )
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ class TTS:
18
+
19
+ def __init__(self, config: Config) -> None:
20
+ self.http = HTTPClient(config)
21
+ self.async_http = AsyncHTTPClient(config)
22
+
23
+ def synthesize(
24
+ self,
25
+ text: str,
26
+ language: str = "en",
27
+ voice: str = "roohi",
28
+ model: str = "ragini-v1",
29
+ format: str = "wav",
30
+ sample_rate: int = 24000,
31
+ speed: float = 1.0,
32
+ stream: bool = False,
33
+ ) -> Union[bytes, Generator[bytes, None, None]]:
34
+ text = validate_text(text)
35
+ language = validate_language(language)
36
+ format = validate_audio_format(format)
37
+ voice = validate_voice(voice)
38
+
39
+ logger.debug(
40
+ "TTS request: text_length=%d language=%s voice=%s model=%s "
41
+ "format=%s sample_rate=%d speed=%.2f stream=%s",
42
+ len(text), language, voice, model, format, sample_rate, speed, stream,
43
+ )
44
+
45
+ files = {
46
+ "text": (None, text),
47
+ "language": (None, language),
48
+ "speaker": (None, voice),
49
+ "model": (None, model),
50
+ "format": (None, format),
51
+ "sample_rate": (None, str(sample_rate)),
52
+ "speed": (None, str(speed)),
53
+ "stream": (None, "true" if stream else "false"),
54
+ }
55
+
56
+ if stream:
57
+ return self.http.post_stream("/v1/ragini/tts", files=files)
58
+
59
+ response = self.http.post("/v1/ragini/tts", files=files)
60
+
61
+ logger.debug("TTS response: content_length=%d", len(response.content))
62
+ return response.content
63
+
64
+ async def asynthesize(
65
+ self,
66
+ text: str,
67
+ language: str = "en",
68
+ voice: str = "roohi",
69
+ model: str = "ragini-v1",
70
+ format: str = "wav",
71
+ sample_rate: int = 24000,
72
+ speed: float = 1.0,
73
+ stream: bool = False,
74
+ ) -> Union[bytes, AsyncGenerator[bytes, None]]:
75
+ text = validate_text(text)
76
+ language = validate_language(language)
77
+ format = validate_audio_format(format)
78
+ voice = validate_voice(voice)
79
+
80
+ logger.debug(
81
+ "async TTS request: text_length=%d language=%s voice=%s model=%s "
82
+ "format=%s sample_rate=%d speed=%.2f stream=%s",
83
+ len(text), language, voice, model, format, sample_rate, speed, stream,
84
+ )
85
+
86
+ files = {
87
+ "text": (None, text),
88
+ "language": (None, language),
89
+ "speaker": (None, voice),
90
+ "model": (None, model),
91
+ "format": (None, format),
92
+ "sample_rate": (None, str(sample_rate)),
93
+ "speed": (None, str(speed)),
94
+ "stream": (None, "true" if stream else "false"),
95
+ }
96
+
97
+ if stream:
98
+ return self.async_http.post_stream("/v1/ragini/tts", files=files)
99
+
100
+ response = await self.async_http.post("/v1/ragini/tts", files=files)
101
+
102
+ logger.debug("async TTS response: content_length=%d", len(response.content))
103
+ return response.content
104
+
105
+ def generate(
106
+ self,
107
+ text: str,
108
+ language: str = "en",
109
+ voice: str = "roohi",
110
+ model: str = "ragini-v1",
111
+ speed: float = 1.0,
112
+ ) -> bytes:
113
+ return self.synthesize(text=text, language=language, voice=voice, model=model, speed=speed)
114
+
115
+ async def agenerate(
116
+ self,
117
+ text: str,
118
+ language: str = "en",
119
+ voice: str = "roohi",
120
+ model: str = "ragini-v1",
121
+ speed: float = 1.0,
122
+ ) -> bytes:
123
+ return await self.asynthesize(text=text, language=language, voice=voice, model=model, speed=speed)
File without changes
@@ -0,0 +1,165 @@
1
+ import asyncio
2
+ import logging
3
+ from typing import Any, AsyncGenerator, Dict, Optional
4
+
5
+ try:
6
+ import httpx
7
+ except ImportError:
8
+ httpx = None # type: ignore[assignment]
9
+
10
+ from ..exceptions import AuthenticationError, RateLimitError, APIError
11
+ from ..config import Config
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ # Exceptions that should NOT be retried (non-transient)
16
+ _NON_RETRYABLE = (AuthenticationError, RateLimitError, ValueError, TypeError)
17
+
18
+
19
+ def _require_httpx() -> None:
20
+ if httpx is None:
21
+ raise ImportError(
22
+ "httpx is required for async support. "
23
+ "Install it with: pip install convozen[async]"
24
+ )
25
+
26
+
27
+ async def async_retry_request(func, retries: int = 3, delay: float = 1.0):
28
+ _require_httpx()
29
+ for attempt in range(retries):
30
+ try:
31
+ return await func()
32
+ except _NON_RETRYABLE:
33
+ raise
34
+ except (httpx.ConnectError, httpx.TimeoutException, OSError) as exc:
35
+ if attempt == retries - 1:
36
+ raise
37
+ wait = delay * (2 ** attempt)
38
+ logger.warning("Request failed (attempt %d/%d), retrying in %.1fs: %s",
39
+ attempt + 1, retries, wait, exc)
40
+ await asyncio.sleep(wait)
41
+ raise RuntimeError("Unreachable")
42
+
43
+
44
+ class AsyncHTTPClient:
45
+
46
+ def __init__(self, config: Config) -> None:
47
+ self.config = config
48
+ self._client = None
49
+
50
+ async def _get_client(self):
51
+ _require_httpx()
52
+ if self._client is None or self._client.is_closed:
53
+ self._client = httpx.AsyncClient(
54
+ timeout=self.config.timeout,
55
+ headers={"x-api-key": self.config.api_key},
56
+ )
57
+ return self._client
58
+
59
+ async def close(self) -> None:
60
+ if self._client is not None and not self._client.is_closed:
61
+ await self._client.aclose()
62
+ self._client = None
63
+
64
+ async def __aenter__(self) -> "AsyncHTTPClient":
65
+ return self
66
+
67
+ async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
68
+ await self.close()
69
+
70
+ async def post(
71
+ self,
72
+ endpoint: str,
73
+ json: Optional[Dict[str, Any]] = None,
74
+ files: Optional[Dict[str, Any]] = None,
75
+ data: Optional[Dict[str, Any]] = None,
76
+ ):
77
+ return await async_retry_request(
78
+ lambda: self._request(
79
+ "POST",
80
+ endpoint,
81
+ json=json,
82
+ files=files,
83
+ data=data,
84
+ )
85
+ )
86
+
87
+ async def post_stream(
88
+ self,
89
+ endpoint: str,
90
+ json: Optional[Dict[str, Any]] = None,
91
+ files: Optional[Dict[str, Any]] = None,
92
+ data: Optional[Dict[str, Any]] = None,
93
+ chunk_size: int = 4096,
94
+ ) -> AsyncGenerator[bytes, None]:
95
+ """POST request that yields response body in chunks (async)."""
96
+ _require_httpx()
97
+ url = f"{self.config.base_url}{endpoint}"
98
+ logger.debug("async stream POST %s", url)
99
+
100
+ client = await self._get_client()
101
+
102
+ async def _connect():
103
+ """Establish the stream connection (retryable)."""
104
+ return await client.send(
105
+ client.build_request(
106
+ "POST", url, json=json, files=files, data=data,
107
+ ),
108
+ stream=True,
109
+ )
110
+
111
+ response = await async_retry_request(_connect)
112
+ try:
113
+ self._handle_response(response)
114
+ async for chunk in response.aiter_bytes(chunk_size=chunk_size):
115
+ yield chunk
116
+ finally:
117
+ await response.aclose()
118
+
119
+ async def get(
120
+ self,
121
+ endpoint: str,
122
+ params: Optional[Dict[str, Any]] = None,
123
+ ):
124
+ return await async_retry_request(
125
+ lambda: self._request("GET", endpoint, params=params)
126
+ )
127
+
128
+ async def _request(
129
+ self,
130
+ method: str,
131
+ endpoint: str,
132
+ json: Optional[Dict[str, Any]] = None,
133
+ files: Optional[Dict[str, Any]] = None,
134
+ data: Optional[Dict[str, Any]] = None,
135
+ params: Optional[Dict[str, Any]] = None,
136
+ ):
137
+ url = f"{self.config.base_url}{endpoint}"
138
+
139
+ logger.debug("async %s %s", method, url)
140
+
141
+ client = await self._get_client()
142
+ response = await client.request(
143
+ method,
144
+ url,
145
+ json=json,
146
+ files=files,
147
+ data=data,
148
+ params=params,
149
+ )
150
+
151
+ logger.debug("async response: status=%d", response.status_code)
152
+ self._handle_response(response)
153
+ return response
154
+
155
+ def _handle_response(self, response) -> None:
156
+ if response.status_code == 401:
157
+ raise AuthenticationError("Invalid API key")
158
+ if response.status_code == 429:
159
+ raise RateLimitError("Rate limit exceeded")
160
+ if not response.is_success:
161
+ try:
162
+ body = response.text
163
+ except Exception:
164
+ body = f"(status {response.status_code})"
165
+ raise APIError(f"API error {response.status_code}: {body}")
@@ -0,0 +1,126 @@
1
+ import logging
2
+ from typing import Any, Dict, Generator, Optional
3
+
4
+ import requests
5
+
6
+ from ..exceptions import AuthenticationError, RateLimitError, APIError
7
+ from ..config import Config
8
+ from .retry import retry_request
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+
13
+ class HTTPClient:
14
+
15
+ def __init__(self, config: Config) -> None:
16
+ self.config = config
17
+ self._session: Optional[requests.Session] = None
18
+
19
+ def _get_session(self) -> requests.Session:
20
+ if self._session is None:
21
+ self._session = requests.Session()
22
+ self._session.headers.update({
23
+ "x-api-key": self.config.api_key,
24
+ })
25
+ return self._session
26
+
27
+ def close(self) -> None:
28
+ if self._session is not None:
29
+ self._session.close()
30
+ self._session = None
31
+
32
+ def __enter__(self) -> "HTTPClient":
33
+ return self
34
+
35
+ def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
36
+ self.close()
37
+
38
+ def post(
39
+ self,
40
+ endpoint: str,
41
+ json: Optional[Dict[str, Any]] = None,
42
+ files: Optional[Dict[str, Any]] = None,
43
+ data: Optional[Dict[str, Any]] = None,
44
+ stream: bool = False,
45
+ ) -> requests.Response:
46
+ return retry_request(
47
+ lambda: self._request(
48
+ "POST",
49
+ endpoint,
50
+ json=json,
51
+ files=files,
52
+ data=data,
53
+ stream=stream,
54
+ )
55
+ )
56
+
57
+ def post_stream(
58
+ self,
59
+ endpoint: str,
60
+ json: Optional[Dict[str, Any]] = None,
61
+ files: Optional[Dict[str, Any]] = None,
62
+ data: Optional[Dict[str, Any]] = None,
63
+ chunk_size: int = 4096,
64
+ ) -> Generator[bytes, None, None]:
65
+ """POST request that yields response body in chunks."""
66
+ response = retry_request(
67
+ lambda: self._request(
68
+ "POST",
69
+ endpoint,
70
+ json=json,
71
+ files=files,
72
+ data=data,
73
+ stream=True,
74
+ )
75
+ )
76
+ for chunk in response.iter_content(chunk_size=chunk_size):
77
+ if chunk:
78
+ yield chunk
79
+
80
+ def get(
81
+ self,
82
+ endpoint: str,
83
+ params: Optional[Dict[str, Any]] = None,
84
+ ) -> requests.Response:
85
+ return retry_request(
86
+ lambda: self._request("GET", endpoint, params=params)
87
+ )
88
+
89
+ def _request(
90
+ self,
91
+ method: str,
92
+ endpoint: str,
93
+ json: Optional[Dict[str, Any]] = None,
94
+ files: Optional[Dict[str, Any]] = None,
95
+ data: Optional[Dict[str, Any]] = None,
96
+ params: Optional[Dict[str, Any]] = None,
97
+ stream: bool = False,
98
+ ) -> requests.Response:
99
+ url = f"{self.config.base_url}{endpoint}"
100
+
101
+ logger.debug("%s %s", method, url)
102
+
103
+ session = self._get_session()
104
+
105
+ response = session.request(
106
+ method,
107
+ url,
108
+ json=json,
109
+ files=files,
110
+ data=data,
111
+ params=params,
112
+ timeout=self.config.timeout,
113
+ stream=stream,
114
+ )
115
+
116
+ logger.debug("Response: status=%d", response.status_code)
117
+ self._handle_response(response)
118
+ return response
119
+
120
+ def _handle_response(self, response: requests.Response) -> None:
121
+ if response.status_code == 401:
122
+ raise AuthenticationError("Invalid API key")
123
+ if response.status_code == 429:
124
+ raise RateLimitError("Rate limit exceeded")
125
+ if not response.ok:
126
+ raise APIError(f"API error {response.status_code}: {response.text}")
@@ -0,0 +1,30 @@
1
+ import logging
2
+ import time
3
+ from typing import Callable, TypeVar
4
+
5
+ import requests
6
+
7
+ from ..exceptions import AuthenticationError, RateLimitError
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+ T = TypeVar("T")
12
+
13
+ # Exceptions that should NOT be retried (non-transient)
14
+ _NON_RETRYABLE = (AuthenticationError, RateLimitError, ValueError, TypeError)
15
+
16
+
17
+ def retry_request(func: Callable[[], T], retries: int = 3, delay: float = 1.0) -> T:
18
+ for attempt in range(retries):
19
+ try:
20
+ return func()
21
+ except _NON_RETRYABLE:
22
+ raise
23
+ except (requests.ConnectionError, requests.Timeout, OSError) as exc:
24
+ if attempt == retries - 1:
25
+ raise
26
+ wait = delay * (2 ** attempt)
27
+ logger.warning("Request failed (attempt %d/%d), retrying in %.1fs: %s",
28
+ attempt + 1, retries, wait, exc)
29
+ time.sleep(wait)
30
+ raise RuntimeError("Unreachable")
@@ -0,0 +1,52 @@
1
+ from dataclasses import dataclass
2
+ from typing import Dict, List
3
+
4
+
5
+ @dataclass
6
+ class TTSResponse:
7
+ audio: bytes
8
+ duration: float
9
+
10
+
11
+ @dataclass
12
+ class STTResponse:
13
+ text: str
14
+ language: str
15
+
16
+
17
+ @dataclass
18
+ class CreditBalance:
19
+ balance: int
20
+
21
+
22
+ @dataclass
23
+ class Credits:
24
+ tts: CreditBalance
25
+ stt: CreditBalance
26
+
27
+
28
+ @dataclass
29
+ class RateLimitInfo:
30
+ requests_per_minute: int
31
+ requests_per_day: int
32
+
33
+
34
+ @dataclass
35
+ class AccountInfo:
36
+ account_id: str
37
+ plan: str
38
+ credits: Credits
39
+ rate_limit: RateLimitInfo
40
+
41
+
42
+ @dataclass
43
+ class UsageByDay:
44
+ date: str
45
+ credits: int
46
+
47
+
48
+ @dataclass
49
+ class UsageSummary:
50
+ total_credits_used: int
51
+ by_model: Dict[str, int]
52
+ by_day: List[UsageByDay]
File without changes
@@ -0,0 +1,7 @@
1
+ from pathlib import Path
2
+ from typing import Union
3
+
4
+
5
+ def save_wav(audio_bytes: bytes, path: Union[str, Path]) -> None:
6
+ with open(path, "wb") as f:
7
+ f.write(audio_bytes)
@@ -0,0 +1,56 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Union
4
+
5
+ from ..enums import Language, AudioFormat, VoiceId
6
+
7
+
8
+ def validate_text(text: str) -> str:
9
+ if not text:
10
+ raise ValueError("Text cannot be empty")
11
+ return text
12
+
13
+
14
+ def validate_language(language: Union[str, Language]) -> str:
15
+ """
16
+ Ensure the language is one of the supported ISO 639-1 codes.
17
+ """
18
+ if isinstance(language, Language):
19
+ return language.value
20
+
21
+ lang = language.lower()
22
+ if lang not in {l.value for l in Language}:
23
+ raise ValueError(f"Unsupported language code: {language}")
24
+ return lang
25
+
26
+
27
+ def validate_audio_format(fmt: Union[str, AudioFormat]) -> str:
28
+ """
29
+ Ensure the audio format is supported for TTS outputs.
30
+ """
31
+ if isinstance(fmt, AudioFormat):
32
+ return fmt.value
33
+
34
+ norm = fmt.lower()
35
+ if norm not in {AudioFormat.WAV.value}:
36
+ raise ValueError(f"Unsupported audio format: {fmt}")
37
+ return norm
38
+
39
+
40
+ def validate_voice(voice: Union[str, VoiceId]) -> str:
41
+ """
42
+ Basic validation for voice identifiers.
43
+
44
+ For now we accept any non-empty string so that new voices can be
45
+ introduced server-side without requiring an SDK update, but keep a
46
+ typed enum for common voices.
47
+ """
48
+ if isinstance(voice, VoiceId):
49
+ value = voice.value
50
+ else:
51
+ value = str(voice).strip()
52
+
53
+ if not value:
54
+ raise ValueError("Voice identifier cannot be empty")
55
+
56
+ return value
convozen/client.py ADDED
@@ -0,0 +1,102 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Optional, Any
4
+
5
+ from convozen._internal.config import Config
6
+ from convozen._internal.akshara_stt.client import STT as _STTImpl
7
+ from convozen._internal.ragini_tts.client import TTS as _TTSImpl
8
+ from convozen._internal.account import AccountClient
9
+
10
+
11
+ class Client:
12
+ """
13
+ Public entrypoint for the ConvoZen SDK.
14
+
15
+ Usage::
16
+
17
+ import convozen
18
+
19
+ client = convozen.Client(api_key="your-api-key-here")
20
+ text = client.stt.transcribe("audio.wav")
21
+ audio = client.tts.synthesize("Hello world")
22
+ """
23
+
24
+ def __init__(
25
+ self,
26
+ api_key: Optional[str] = None,
27
+ base_url: Optional[str] = None,
28
+ timeout: Optional[int] = None,
29
+ ) -> None:
30
+ config_kwargs = {}
31
+ if api_key is not None:
32
+ config_kwargs["api_key"] = api_key
33
+ if base_url is not None:
34
+ config_kwargs["base_url"] = base_url
35
+ if timeout is not None:
36
+ config_kwargs["timeout"] = timeout
37
+
38
+ config = Config(**config_kwargs)
39
+
40
+ self.stt = _STTImpl(config)
41
+ self.tts = _TTSImpl(config)
42
+ self.account = AccountClient(config)
43
+
44
+
45
+ class STT:
46
+ """
47
+ Convenience wrapper::
48
+
49
+ from convozen import STT
50
+ stt = STT(api_key="...")
51
+ stt.transcribe("audio.wav")
52
+ """
53
+
54
+ def __init__(
55
+ self,
56
+ api_key: Optional[str] = None,
57
+ base_url: Optional[str] = None,
58
+ timeout: Optional[int] = None,
59
+ ) -> None:
60
+ config_kwargs = {}
61
+ if api_key is not None:
62
+ config_kwargs["api_key"] = api_key
63
+ if base_url is not None:
64
+ config_kwargs["base_url"] = base_url
65
+ if timeout is not None:
66
+ config_kwargs["timeout"] = timeout
67
+
68
+ config = Config(**config_kwargs)
69
+ self._client = _STTImpl(config)
70
+
71
+ def __getattr__(self, name: str) -> Any:
72
+ return getattr(self._client, name)
73
+
74
+
75
+ class TTS:
76
+ """
77
+ Convenience wrapper::
78
+
79
+ from convozen import TTS
80
+ tts = TTS(api_key="...")
81
+ tts.synthesize("Hello world")
82
+ """
83
+
84
+ def __init__(
85
+ self,
86
+ api_key: Optional[str] = None,
87
+ base_url: Optional[str] = None,
88
+ timeout: Optional[int] = None,
89
+ ) -> None:
90
+ config_kwargs = {}
91
+ if api_key is not None:
92
+ config_kwargs["api_key"] = api_key
93
+ if base_url is not None:
94
+ config_kwargs["base_url"] = base_url
95
+ if timeout is not None:
96
+ config_kwargs["timeout"] = timeout
97
+
98
+ config = Config(**config_kwargs)
99
+ self._client = _TTSImpl(config)
100
+
101
+ def __getattr__(self, name: str) -> Any:
102
+ return getattr(self._client, name)
convozen/py.typed ADDED
File without changes
@@ -0,0 +1,206 @@
1
+ Metadata-Version: 2.4
2
+ Name: convozen
3
+ Version: 0.3.1
4
+ Summary: Python SDK for ConvoZen TTS and STT services
5
+ Author: Convozen
6
+ License-Expression: MIT
7
+ Keywords: tts,stt,speech,voice,convozen
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.9
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Requires-Python: >=3.9
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: requests<3.0,>=2.28.0
21
+ Provides-Extra: async
22
+ Requires-Dist: httpx<1.0,>=0.24.0; extra == "async"
23
+ Provides-Extra: dev
24
+ Requires-Dist: pytest; extra == "dev"
25
+ Requires-Dist: responses; extra == "dev"
26
+ Requires-Dist: pytest-asyncio; extra == "dev"
27
+ Requires-Dist: anyio[trio]; extra == "dev"
28
+ Requires-Dist: respx; extra == "dev"
29
+ Requires-Dist: httpx<1.0,>=0.24.0; extra == "dev"
30
+ Dynamic: license-file
31
+
32
+ # ConvoZen Voice SDK
33
+
34
+ Text-to-Speech (TTS) and Speech-to-Text (STT) for Python.
35
+
36
+ > One API key for both TTS and STT.
37
+
38
+ ## Install
39
+
40
+ ```bash
41
+ pip install convozen
42
+ ```
43
+
44
+ Requires Python 3.9+
45
+
46
+ ---
47
+
48
+ ## TTS — Convert Text to Speech
49
+
50
+ Copy and run:
51
+
52
+ ```python
53
+ import convozen
54
+
55
+ client = convozen.Client(api_key="your-api-key")
56
+
57
+ audio = client.tts.synthesize("नमस्ते… मुझे आपके सर्विस के बारे में थोड़ी जानकारी चाहिए।", language="hi")
58
+
59
+ with open("output.wav", "wb") as f:
60
+ f.write(audio)
61
+ ```
62
+
63
+ With options:
64
+
65
+ ```python
66
+ import convozen
67
+
68
+ client = convozen.Client(api_key="your-api-key")
69
+
70
+ audio = client.tts.synthesize(
71
+ text="Welcome to Playground.",
72
+ language="en", # default: "en"
73
+ voice="roohi", # default: "roohi"
74
+ model="ragini-v1", # default: "ragini-v1"
75
+ speed=1.2, # default: 1.0
76
+ )
77
+
78
+ with open("output.wav", "wb") as f:
79
+ f.write(audio)
80
+ ```
81
+
82
+ ### Parameters
83
+
84
+ | Parameter | Type | Default | Description |
85
+ |-----------|------|---------|-------------|
86
+ | `text` | `str` | *required* | Text to convert to speech |
87
+ | `language` | `str` | `"en"` | Language code (see supported languages below) |
88
+ | `voice` | `str` | `"roohi"` | Voice ID for synthesis (see available voices below) |
89
+ | `model` | `str` | `"ragini-v1"` | TTS model to use. Currently only `ragini-v1` is available |
90
+ | `speed` | `float` | `1.0` | Speech speed. `0.5` = half speed, `2.0` = double speed |
91
+ | `stream` | `bool` | `False` | If `True`, returns audio chunks as they are generated |
92
+ | `format` | `str` | `"wav"` | Audio output format. Currently only `wav` is supported |
93
+
94
+ ### Streaming
95
+
96
+ ```python
97
+ import convozen
98
+
99
+ client = convozen.Client(api_key="your-api-key")
100
+
101
+ for chunk in client.tts.synthesize("Long text here...", language="en", stream=True):
102
+ audio_player.write(chunk)
103
+ ```
104
+
105
+ ### Available Voices
106
+
107
+ | Voice | ID | Default |
108
+ |-------|----|---------|
109
+ | Roohi | `roohi` | Yes |
110
+ | Amaya | `amaya` | |
111
+ | Kiyansh | `kiyansh` | |
112
+ | Neeraj | `neeraj` | |
113
+ | Manya | `manya` | |
114
+ | Nidhi | `nidhi` | |
115
+ | Ira | `ira` | |
116
+ | Trisha | `trisha` | |
117
+ | Charvi | `charvi` | |
118
+
119
+ ```python
120
+ audio = client.tts.synthesize("Hello", language="en", voice="roohi")
121
+ ```
122
+
123
+ ---
124
+
125
+ ## STT — Convert Speech to Text
126
+
127
+ Copy and run:
128
+
129
+ ```python
130
+ import convozen
131
+
132
+ client = convozen.Client(api_key="your-api-key")
133
+
134
+ text = client.stt.transcribe("recording.wav")
135
+ print(text)
136
+ ```
137
+
138
+ ### Parameters
139
+
140
+ | Parameter | Type | Default | Description |
141
+ |-----------|------|---------|-------------|
142
+ | `audio` | `str` | *required* | Path to the audio file (WAV format) |
143
+ | `model` | `str` | `"akshara-v1"` | STT model to use. Currently only `akshara-v1` is available |
144
+
145
+ ---
146
+
147
+ ## Supported Languages
148
+
149
+ | Code | Language | TTS | STT |
150
+ |------|----------|:---:|:---:|
151
+ | `en` | English | Yes | Yes |
152
+ | `hi` | Hindi | Yes | Yes |
153
+ | `ta` | Tamil | Yes | Yes |
154
+ | `te` | Telugu | Yes | Yes |
155
+ | `kn` | Kannada | Yes | Yes |
156
+ | `mr` | Marathi | — | Yes |
157
+ | `bn` | Bengali | — | Yes |
158
+ | `gu` | Gujarati | — | Yes |
159
+ | `ml` | Malayalam | — | Yes |
160
+
161
+ ---
162
+
163
+ ## Check Credits
164
+
165
+ ```python
166
+ import convozen
167
+
168
+ client = convozen.Client(api_key="your-api-key")
169
+ info = client.account.info()
170
+ print(info.credits.tts.balance)
171
+ print(info.credits.stt.balance)
172
+ ```
173
+
174
+ ---
175
+
176
+ ## Error Handling
177
+
178
+ ```python
179
+ import convozen
180
+ from convozen import AuthenticationError, RateLimitError, APIError
181
+
182
+ client = convozen.Client(api_key="your-api-key")
183
+
184
+ try:
185
+ audio = client.tts.synthesize("Hello")
186
+ except AuthenticationError:
187
+ print("Invalid API key")
188
+ except RateLimitError:
189
+ print("Too many requests")
190
+ except APIError as e:
191
+ print(f"Server error: {e}")
192
+ ```
193
+
194
+ ---
195
+
196
+ ## Standalone Clients
197
+
198
+ ```python
199
+ from convozen import TTS, STT
200
+
201
+ tts = TTS(api_key="your-api-key")
202
+ audio = tts.synthesize("Hello", language="hi")
203
+
204
+ stt = STT(api_key="your-api-key")
205
+ text = stt.transcribe("audio.wav")
206
+ ```
@@ -0,0 +1,25 @@
1
+ convozen/__init__.py,sha256=I6VwAF-RadaZMB5jnr1JL1x2szhLO_IFcXUdkDgvGlM,806
2
+ convozen/client.py,sha256=ahxK73-cM5_lZDr5k9W0myhZ4QGzm-A92cf3veUqUzM,2698
3
+ convozen/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ convozen/_internal/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ convozen/_internal/account.py,sha256=D3jBTStJPaAwgULKvBRrUyY8X53u8OO6d6PXgOyOO4c,3858
6
+ convozen/_internal/config.py,sha256=RDDdzShkUft7alzylCT1a2XFfhb9WqRZ_Iq6H9Dx6pU,1265
7
+ convozen/_internal/enums.py,sha256=TcroRu7-J04fdsYU7c_A-ak6Iuwpe0JkGZUuQWxiAb8,799
8
+ convozen/_internal/exceptions.py,sha256=wTpqBoM5tNrgDnKUkbqFLEKSUT0Z0Z9CWNoGtYr2t1g,184
9
+ convozen/_internal/types.py,sha256=AlvqktxTMKhjk9qeqVOYdxaf_YpvSENUxvMD43mZccs,709
10
+ convozen/_internal/akshara_stt/__init__.py,sha256=aNN4N9nAZnlS_5haDEWWUde1Zzqmb7arMg1cmGIDm6k,24
11
+ convozen/_internal/akshara_stt/client.py,sha256=JLTi1A8kyzVjyny_W37PLx5EEywJCIIEvfX6IGUg7sQ,1410
12
+ convozen/_internal/ragini_tts/__init__.py,sha256=DU2AnUeJpZtvkAAX2JJq2gioYsxehjQ5OiqRgEpGYMI,24
13
+ convozen/_internal/ragini_tts/client.py,sha256=OAjBFcTi-Apz2z8hzfR_M1J-dPOgifQ1ckGmogU3MYY,3892
14
+ convozen/_internal/transport/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
15
+ convozen/_internal/transport/async_http.py,sha256=fF9iVF8p-u044frOAYTN2kP3K5ARE7X3iYvdB4jrDpA,5076
16
+ convozen/_internal/transport/http.py,sha256=MoLN1QX7DUWZ47nRUO5Zeza5rQWCrgsvLWhV7ukOqxY,3627
17
+ convozen/_internal/transport/retry.py,sha256=LFbU0j3vGYd90gHjR9VgUOKRAfUgTzRh4-u-6njQj8Y,935
18
+ convozen/_internal/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
19
+ convozen/_internal/utils/audio.py,sha256=KL_mrERWyZqI94iKoBbs9p7-j7nXG8jRd0fXzzGCWBc,179
20
+ convozen/_internal/utils/validation.py,sha256=NAjj9sX_3qHiqCLolv2CzhhFAvkikrQYLRQbkJ6xd7o,1453
21
+ convozen-0.3.1.dist-info/licenses/LICENSE,sha256=XE2zp0Dsy70q77MwihQBxfquD5zTonLOer5wyhyPzN4,1065
22
+ convozen-0.3.1.dist-info/METADATA,sha256=pDcnhwSY1GxLMRN73--4WNZlRlncHozAFA1ZxFMT2YA,5054
23
+ convozen-0.3.1.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
24
+ convozen-0.3.1.dist-info/top_level.txt,sha256=CPeafodt_r-UaGseHmK4ROv0yr9V8Jk7I7WZ5Cg544s,9
25
+ convozen-0.3.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Convozen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ convozen