typecast-python 0.1.3__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.
- typecast/__init__.py +25 -0
- typecast/async_client.py +105 -0
- typecast/client.py +87 -0
- typecast/conf.py +16 -0
- typecast/exceptions.py +49 -0
- typecast/models/__init__.py +15 -0
- typecast/models/error.py +9 -0
- typecast/models/tts.py +80 -0
- typecast/models/tts_wss.py +7 -0
- typecast/models/voices.py +9 -0
- typecast/sse.py +35 -0
- typecast/utils.py +19 -0
- typecast/websocket.py +47 -0
- typecast_python-0.1.3.dist-info/METADATA +435 -0
- typecast_python-0.1.3.dist-info/RECORD +17 -0
- typecast_python-0.1.3.dist-info/WHEEL +4 -0
- typecast_python-0.1.3.dist-info/licenses/LICENSE +202 -0
typecast/__init__.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
from .async_client import AsyncTypecast
|
|
2
|
+
from .client import Typecast
|
|
3
|
+
from .models import (
|
|
4
|
+
Error,
|
|
5
|
+
LanguageCode,
|
|
6
|
+
Output,
|
|
7
|
+
Prompt,
|
|
8
|
+
TTSRequest,
|
|
9
|
+
TTSResponse,
|
|
10
|
+
VoicesResponse,
|
|
11
|
+
WebSocketMessage,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"AsyncTypecast",
|
|
16
|
+
"Error",
|
|
17
|
+
"LanguageCode",
|
|
18
|
+
"Output",
|
|
19
|
+
"Prompt",
|
|
20
|
+
"Typecast",
|
|
21
|
+
"TTSRequest",
|
|
22
|
+
"TTSResponse",
|
|
23
|
+
"VoicesResponse",
|
|
24
|
+
"WebSocketMessage",
|
|
25
|
+
]
|
typecast/async_client.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
from typing import Optional
|
|
2
|
+
|
|
3
|
+
import aiohttp
|
|
4
|
+
|
|
5
|
+
from . import conf
|
|
6
|
+
from .exceptions import (
|
|
7
|
+
BadRequestError,
|
|
8
|
+
InternalServerError,
|
|
9
|
+
NotFoundError,
|
|
10
|
+
PaymentRequiredError,
|
|
11
|
+
TypecastError,
|
|
12
|
+
UnauthorizedError,
|
|
13
|
+
UnprocessableEntityError,
|
|
14
|
+
)
|
|
15
|
+
from .models import TTSRequest, TTSResponse, VoicesResponse
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class AsyncTypecast:
|
|
19
|
+
def __init__(self, host: Optional[str] = None, api_key: Optional[str] = None):
|
|
20
|
+
self.host = conf.get_host(host)
|
|
21
|
+
self.api_key = conf.get_api_key(api_key)
|
|
22
|
+
self.session: Optional[aiohttp.ClientSession] = None
|
|
23
|
+
|
|
24
|
+
async def __aenter__(self):
|
|
25
|
+
headers = {"Content-Type": "application/json"}
|
|
26
|
+
if self.api_key:
|
|
27
|
+
headers["X-API-KEY"] = self.api_key
|
|
28
|
+
self.session = aiohttp.ClientSession(headers=headers)
|
|
29
|
+
return self
|
|
30
|
+
|
|
31
|
+
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
|
32
|
+
if self.session:
|
|
33
|
+
await self.session.close()
|
|
34
|
+
|
|
35
|
+
def _handle_error(self, status_code: int, response_text: str):
|
|
36
|
+
"""Handle HTTP error responses with specific exception types"""
|
|
37
|
+
if status_code == 400:
|
|
38
|
+
raise BadRequestError(f"Bad request: {response_text}")
|
|
39
|
+
elif status_code == 401:
|
|
40
|
+
raise UnauthorizedError(f"Unauthorized: {response_text}")
|
|
41
|
+
elif status_code == 402:
|
|
42
|
+
raise PaymentRequiredError(f"Payment required: {response_text}")
|
|
43
|
+
elif status_code == 404:
|
|
44
|
+
raise NotFoundError(f"Not found: {response_text}")
|
|
45
|
+
elif status_code == 422:
|
|
46
|
+
raise UnprocessableEntityError(f"Validation error: {response_text}")
|
|
47
|
+
elif status_code == 500:
|
|
48
|
+
raise InternalServerError(f"Internal server error: {response_text}")
|
|
49
|
+
else:
|
|
50
|
+
raise TypecastError(
|
|
51
|
+
f"API request failed: {status_code}, {response_text}",
|
|
52
|
+
status_code=status_code,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
async def text_to_speech(self, request: TTSRequest) -> TTSResponse:
|
|
56
|
+
if not self.session:
|
|
57
|
+
raise TypecastError("Client session not initialized. Use async with.")
|
|
58
|
+
endpoint = "/v1/text-to-speech"
|
|
59
|
+
async with self.session.post(
|
|
60
|
+
f"{self.host}{endpoint}", json=request.model_dump(exclude_none=True)
|
|
61
|
+
) as response:
|
|
62
|
+
if response.status != 200:
|
|
63
|
+
error_text = await response.text()
|
|
64
|
+
self._handle_error(response.status, error_text)
|
|
65
|
+
|
|
66
|
+
audio_data = await response.read()
|
|
67
|
+
return TTSResponse(
|
|
68
|
+
audio_data=audio_data,
|
|
69
|
+
duration=float(response.headers.get("X-Audio-Duration", 0)),
|
|
70
|
+
format=response.headers.get("Content-Type", "audio/wav").split("/")[-1],
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
async def voices(self, model: Optional[str] = None) -> list[VoicesResponse]:
|
|
74
|
+
if not self.session:
|
|
75
|
+
raise TypecastError("Client session not initialized. Use async with.")
|
|
76
|
+
endpoint = "/v1/voices"
|
|
77
|
+
params = {}
|
|
78
|
+
if model:
|
|
79
|
+
params["model"] = model
|
|
80
|
+
|
|
81
|
+
async with self.session.get(
|
|
82
|
+
f"{self.host}{endpoint}", params=params
|
|
83
|
+
) as response:
|
|
84
|
+
if response.status != 200:
|
|
85
|
+
error_text = await response.text()
|
|
86
|
+
self._handle_error(response.status, error_text)
|
|
87
|
+
|
|
88
|
+
data = await response.json()
|
|
89
|
+
return [VoicesResponse.model_validate(item) for item in data]
|
|
90
|
+
|
|
91
|
+
async def get_voice(self, voice_id: str) -> VoicesResponse:
|
|
92
|
+
if not self.session:
|
|
93
|
+
raise TypecastError("Client session not initialized. Use async with.")
|
|
94
|
+
endpoint = f"/v1/voices/{voice_id}"
|
|
95
|
+
|
|
96
|
+
async with self.session.get(f"{self.host}{endpoint}") as response:
|
|
97
|
+
if response.status != 200:
|
|
98
|
+
error_text = await response.text()
|
|
99
|
+
self._handle_error(response.status, error_text)
|
|
100
|
+
|
|
101
|
+
data = await response.json()
|
|
102
|
+
# API returns a list, so we take the first element
|
|
103
|
+
if isinstance(data, list) and len(data) > 0:
|
|
104
|
+
return VoicesResponse.model_validate(data[0])
|
|
105
|
+
return VoicesResponse.model_validate(data)
|
typecast/client.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
from typing import Optional
|
|
2
|
+
|
|
3
|
+
import requests
|
|
4
|
+
|
|
5
|
+
from . import conf
|
|
6
|
+
from .exceptions import (
|
|
7
|
+
BadRequestError,
|
|
8
|
+
InternalServerError,
|
|
9
|
+
NotFoundError,
|
|
10
|
+
PaymentRequiredError,
|
|
11
|
+
TypecastError,
|
|
12
|
+
UnauthorizedError,
|
|
13
|
+
UnprocessableEntityError,
|
|
14
|
+
)
|
|
15
|
+
from .models import TTSRequest, TTSResponse, VoicesResponse
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Typecast:
|
|
19
|
+
"""Typecast API Client"""
|
|
20
|
+
|
|
21
|
+
def __init__(self, host: Optional[str] = None, api_key: Optional[str] = None):
|
|
22
|
+
self.host = conf.get_host(host)
|
|
23
|
+
self.api_key = conf.get_api_key(api_key)
|
|
24
|
+
self.session = requests.Session()
|
|
25
|
+
self.session.headers.update(
|
|
26
|
+
{"X-API-KEY": self.api_key, "Content-Type": "application/json"}
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
def _handle_error(self, status_code: int, response_text: str):
|
|
30
|
+
"""Handle HTTP error responses with specific exception types"""
|
|
31
|
+
if status_code == 400:
|
|
32
|
+
raise BadRequestError(f"Bad request: {response_text}")
|
|
33
|
+
elif status_code == 401:
|
|
34
|
+
raise UnauthorizedError(f"Unauthorized: {response_text}")
|
|
35
|
+
elif status_code == 402:
|
|
36
|
+
raise PaymentRequiredError(f"Payment required: {response_text}")
|
|
37
|
+
elif status_code == 404:
|
|
38
|
+
raise NotFoundError(f"Not found: {response_text}")
|
|
39
|
+
elif status_code == 422:
|
|
40
|
+
raise UnprocessableEntityError(f"Validation error: {response_text}")
|
|
41
|
+
elif status_code == 500:
|
|
42
|
+
raise InternalServerError(f"Internal server error: {response_text}")
|
|
43
|
+
else:
|
|
44
|
+
raise TypecastError(
|
|
45
|
+
f"API request failed: {status_code}, {response_text}",
|
|
46
|
+
status_code=status_code,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
def text_to_speech(self, request: TTSRequest) -> TTSResponse:
|
|
50
|
+
endpoint = "/v1/text-to-speech"
|
|
51
|
+
response = self.session.post(
|
|
52
|
+
f"{self.host}{endpoint}", json=request.model_dump(exclude_none=True)
|
|
53
|
+
)
|
|
54
|
+
if response.status_code != 200:
|
|
55
|
+
self._handle_error(response.status_code, response.text)
|
|
56
|
+
|
|
57
|
+
return TTSResponse(
|
|
58
|
+
audio_data=response.content,
|
|
59
|
+
duration=response.headers.get("X-Audio-Duration", 0),
|
|
60
|
+
format=response.headers.get("Content-Type", "audio/wav").split("/")[-1],
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
def voices(self, model: Optional[str] = None) -> list[VoicesResponse]:
|
|
64
|
+
endpoint = "/v1/voices"
|
|
65
|
+
params = {}
|
|
66
|
+
if model:
|
|
67
|
+
params["model"] = model
|
|
68
|
+
|
|
69
|
+
response = self.session.get(f"{self.host}{endpoint}", params=params)
|
|
70
|
+
|
|
71
|
+
if response.status_code != 200:
|
|
72
|
+
self._handle_error(response.status_code, response.text)
|
|
73
|
+
|
|
74
|
+
return [VoicesResponse.model_validate(item) for item in response.json()]
|
|
75
|
+
|
|
76
|
+
def get_voice(self, voice_id: str) -> VoicesResponse:
|
|
77
|
+
endpoint = f"/v1/voices/{voice_id}"
|
|
78
|
+
response = self.session.get(f"{self.host}{endpoint}")
|
|
79
|
+
|
|
80
|
+
if response.status_code != 200:
|
|
81
|
+
self._handle_error(response.status_code, response.text)
|
|
82
|
+
|
|
83
|
+
data = response.json()
|
|
84
|
+
# API returns a list, so we take the first element
|
|
85
|
+
if isinstance(data, list) and len(data) > 0:
|
|
86
|
+
return VoicesResponse.model_validate(data[0])
|
|
87
|
+
return VoicesResponse.model_validate(data)
|
typecast/conf.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
TYPECAST_API_HOST = "https://api.typecast.ai"
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def get_host(host=None):
|
|
7
|
+
if host: # Parameter takes priority
|
|
8
|
+
return host
|
|
9
|
+
env_host = os.getenv("TYPECAST_API_HOST") # Check environment variable
|
|
10
|
+
return env_host if env_host else TYPECAST_API_HOST # Use default if not set
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def get_api_key(api_key=None):
|
|
14
|
+
if api_key: # Parameter takes priority
|
|
15
|
+
return api_key
|
|
16
|
+
return os.getenv("TYPECAST_API_KEY") # Return from environment variable
|
typecast/exceptions.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
class TypecastError(Exception):
|
|
2
|
+
"""Base exception for Typecast SDK"""
|
|
3
|
+
|
|
4
|
+
def __init__(self, message: str, status_code: int = None):
|
|
5
|
+
self.message = message
|
|
6
|
+
self.status_code = status_code
|
|
7
|
+
super().__init__(self.message)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class BadRequestError(TypecastError):
|
|
11
|
+
"""400 Bad Request - Invalid request parameters"""
|
|
12
|
+
|
|
13
|
+
def __init__(self, message: str):
|
|
14
|
+
super().__init__(message, status_code=400)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class UnauthorizedError(TypecastError):
|
|
18
|
+
"""401 Unauthorized - Invalid or missing API key"""
|
|
19
|
+
|
|
20
|
+
def __init__(self, message: str):
|
|
21
|
+
super().__init__(message, status_code=401)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class PaymentRequiredError(TypecastError):
|
|
25
|
+
"""402 Payment Required - Insufficient credits or subscription required"""
|
|
26
|
+
|
|
27
|
+
def __init__(self, message: str):
|
|
28
|
+
super().__init__(message, status_code=402)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class NotFoundError(TypecastError):
|
|
32
|
+
"""404 Not Found - Resource not found"""
|
|
33
|
+
|
|
34
|
+
def __init__(self, message: str):
|
|
35
|
+
super().__init__(message, status_code=404)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class UnprocessableEntityError(TypecastError):
|
|
39
|
+
"""422 Unprocessable Entity - Validation error"""
|
|
40
|
+
|
|
41
|
+
def __init__(self, message: str):
|
|
42
|
+
super().__init__(message, status_code=422)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class InternalServerError(TypecastError):
|
|
46
|
+
"""500 Internal Server Error - Server error"""
|
|
47
|
+
|
|
48
|
+
def __init__(self, message: str):
|
|
49
|
+
super().__init__(message, status_code=500)
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from .error import Error
|
|
2
|
+
from .tts import LanguageCode, Output, Prompt, TTSRequest, TTSResponse
|
|
3
|
+
from .tts_wss import WebSocketMessage
|
|
4
|
+
from .voices import VoicesResponse
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"TTSRequest",
|
|
8
|
+
"Prompt",
|
|
9
|
+
"Output",
|
|
10
|
+
"TTSResponse",
|
|
11
|
+
"VoicesResponse",
|
|
12
|
+
"Error",
|
|
13
|
+
"WebSocketMessage",
|
|
14
|
+
"LanguageCode",
|
|
15
|
+
]
|
typecast/models/error.py
ADDED
typecast/models/tts.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
from enum import Enum
|
|
2
|
+
from typing import Optional, Union
|
|
3
|
+
|
|
4
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class TTSModel(str, Enum):
|
|
8
|
+
SSFM_V21 = "ssfm-v21"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class LanguageCode(str, Enum):
|
|
12
|
+
"""ISO 639-3 language codes supported by Typecast API"""
|
|
13
|
+
|
|
14
|
+
ENG = "eng" # English
|
|
15
|
+
KOR = "kor" # Korean
|
|
16
|
+
SPA = "spa" # Spanish
|
|
17
|
+
DEU = "deu" # German
|
|
18
|
+
FRA = "fra" # French
|
|
19
|
+
ITA = "ita" # Italian
|
|
20
|
+
POL = "pol" # Polish
|
|
21
|
+
NLD = "nld" # Dutch
|
|
22
|
+
RUS = "rus" # Russian
|
|
23
|
+
JPN = "jpn" # Japanese
|
|
24
|
+
ELL = "ell" # Greek
|
|
25
|
+
TAM = "tam" # Tamil
|
|
26
|
+
TGL = "tgl" # Tagalog
|
|
27
|
+
FIN = "fin" # Finnish
|
|
28
|
+
ZHO = "zho" # Chinese
|
|
29
|
+
SLK = "slk" # Slovak
|
|
30
|
+
ARA = "ara" # Arabic
|
|
31
|
+
HRV = "hrv" # Croatian
|
|
32
|
+
UKR = "ukr" # Ukrainian
|
|
33
|
+
IND = "ind" # Indonesian
|
|
34
|
+
DAN = "dan" # Danish
|
|
35
|
+
SWE = "swe" # Swedish
|
|
36
|
+
MSA = "msa" # Malay
|
|
37
|
+
CES = "ces" # Czech
|
|
38
|
+
POR = "por" # Portuguese
|
|
39
|
+
BUL = "bul" # Bulgarian
|
|
40
|
+
RON = "ron" # Romanian
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Prompt(BaseModel):
|
|
44
|
+
emotion_preset: Optional[str] = Field(
|
|
45
|
+
default="normal",
|
|
46
|
+
description="Emotion preset",
|
|
47
|
+
examples=["normal", "happy", "sad", "angry"],
|
|
48
|
+
)
|
|
49
|
+
emotion_intensity: Optional[float] = Field(default=1.0, ge=0.0, le=2.0)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class Output(BaseModel):
|
|
53
|
+
volume: Optional[int] = Field(default=100, ge=0, le=200)
|
|
54
|
+
audio_pitch: Optional[int] = Field(default=0, ge=-12, le=12)
|
|
55
|
+
audio_tempo: Optional[float] = Field(default=1.0, ge=0.5, le=2.0)
|
|
56
|
+
audio_format: Optional[str] = Field(
|
|
57
|
+
default="wav", description="Audio format", examples=["wav", "mp3"]
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class TTSRequest(BaseModel):
|
|
62
|
+
model_config = ConfigDict(json_schema_extra={"exclude_none": True})
|
|
63
|
+
|
|
64
|
+
voice_id: str = Field(
|
|
65
|
+
description="Voice ID", examples=["tc_62a8975e695ad26f7fb514d1"]
|
|
66
|
+
)
|
|
67
|
+
text: str = Field(description="Text", examples=["Hello. How are you?"])
|
|
68
|
+
model: TTSModel = Field(description="Voice model name", examples=["ssfm-v21"])
|
|
69
|
+
language: Optional[Union[LanguageCode, str]] = Field(
|
|
70
|
+
None, description="Language code (ISO 639-3)", examples=["eng"]
|
|
71
|
+
)
|
|
72
|
+
prompt: Optional[Prompt] = None
|
|
73
|
+
output: Optional[Output] = None
|
|
74
|
+
seed: Optional[int] = None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class TTSResponse(BaseModel):
|
|
78
|
+
audio_data: bytes
|
|
79
|
+
duration: float
|
|
80
|
+
format: str = "wav"
|
typecast/sse.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
from typing import AsyncIterator, Optional
|
|
2
|
+
|
|
3
|
+
import aiohttp
|
|
4
|
+
|
|
5
|
+
from . import conf
|
|
6
|
+
from .exceptions import TypecastError
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class TypecastSSE:
|
|
10
|
+
SSE_URL = f"{conf.get_host()}/v1/text-to-speech/sse"
|
|
11
|
+
|
|
12
|
+
def __init__(self, api_key: str):
|
|
13
|
+
self.api_key = conf.get_api_key(api_key)
|
|
14
|
+
self.session: Optional[aiohttp.ClientSession] = None
|
|
15
|
+
|
|
16
|
+
async def connect(self, endpoint: str) -> AsyncIterator[str]:
|
|
17
|
+
if self.session:
|
|
18
|
+
await self.session.close()
|
|
19
|
+
|
|
20
|
+
self.session = aiohttp.ClientSession(
|
|
21
|
+
headers={"X-API-KEY": self.api_key, "Accept": "text/event-stream"}
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
async with self.session.get(f"{self.SSE_URL}/{endpoint}") as response:
|
|
25
|
+
if response.status != 200:
|
|
26
|
+
raise TypecastError(f"SSE connection failed: {response.status}")
|
|
27
|
+
|
|
28
|
+
async for line in response.content:
|
|
29
|
+
decoded_line = line.decode("utf-8").strip()
|
|
30
|
+
if decoded_line.startswith("data: "):
|
|
31
|
+
yield decoded_line[6:]
|
|
32
|
+
|
|
33
|
+
async def close(self):
|
|
34
|
+
if self.session:
|
|
35
|
+
await self.session.close()
|
typecast/utils.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import wave
|
|
2
|
+
from math import floor
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def show_performance(processing_time: float, wave_path: str):
|
|
6
|
+
with wave.open(wave_path, "rb") as wav:
|
|
7
|
+
frames = wav.getnframes()
|
|
8
|
+
rate = wav.getframerate()
|
|
9
|
+
|
|
10
|
+
audio_duration = frames / float(rate)
|
|
11
|
+
num_tokens = floor(audio_duration * 20)
|
|
12
|
+
tokens_per_second = num_tokens / processing_time
|
|
13
|
+
|
|
14
|
+
print(f"[Performance] Time taken : {processing_time:.3f} secs")
|
|
15
|
+
print(f"[Performance] Audio duration : {audio_duration:.3f} secs")
|
|
16
|
+
print(f"[Performance] Number of tokens : {num_tokens} tokens")
|
|
17
|
+
print(
|
|
18
|
+
f"[Performance] Tokens per seconds : {tokens_per_second:.3f} tokens / sec"
|
|
19
|
+
)
|
typecast/websocket.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import json
|
|
3
|
+
from typing import Callable, Optional
|
|
4
|
+
|
|
5
|
+
import websockets
|
|
6
|
+
|
|
7
|
+
from .exceptions import TypecastError
|
|
8
|
+
from .models import WebSocketMessage
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class TypecastWebSocket:
|
|
12
|
+
WS_URL = "wss://api.typecast.ai/v1/ws"
|
|
13
|
+
|
|
14
|
+
def __init__(self, api_key: str):
|
|
15
|
+
self.api_key = api_key
|
|
16
|
+
self.ws: Optional[websockets.WebSocketClientProtocol] = None
|
|
17
|
+
self.callbacks: dict[str, Callable] = {}
|
|
18
|
+
|
|
19
|
+
async def connect(self):
|
|
20
|
+
self.ws = await websockets.connect(f"{self.WS_URL}?token={self.api_key}")
|
|
21
|
+
|
|
22
|
+
# Start message handler
|
|
23
|
+
asyncio.create_task(self._message_handler())
|
|
24
|
+
|
|
25
|
+
async def _message_handler(self):
|
|
26
|
+
if not self.ws:
|
|
27
|
+
return
|
|
28
|
+
|
|
29
|
+
async for message in self.ws:
|
|
30
|
+
data = json.loads(message)
|
|
31
|
+
msg = WebSocketMessage(**data)
|
|
32
|
+
|
|
33
|
+
if msg.type in self.callbacks:
|
|
34
|
+
await self.callbacks[msg.type](msg.payload)
|
|
35
|
+
|
|
36
|
+
def on(self, event_type: str, callback: Callable):
|
|
37
|
+
"""Register event callback"""
|
|
38
|
+
self.callbacks[event_type] = callback
|
|
39
|
+
|
|
40
|
+
async def send(self, message: WebSocketMessage):
|
|
41
|
+
if not self.ws:
|
|
42
|
+
raise TypecastError("WebSocket not connected")
|
|
43
|
+
await self.ws.send(message.model_dump_json())
|
|
44
|
+
|
|
45
|
+
async def close(self):
|
|
46
|
+
if self.ws:
|
|
47
|
+
await self.ws.close()
|
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: typecast-python
|
|
3
|
+
Version: 0.1.3
|
|
4
|
+
Summary: Official Typecast Python SDK - Convert text to lifelike speech using AI-powered voices
|
|
5
|
+
Project-URL: Homepage, https://typecast.ai
|
|
6
|
+
Project-URL: Documentation, https://typecast.ai/docs/overview
|
|
7
|
+
Project-URL: Repository, https://github.com/neosapience/typecast-python
|
|
8
|
+
Project-URL: Issues, https://github.com/neosapience/typecast-python/issues
|
|
9
|
+
Author-email: Neosapience <help@typecast.ai>
|
|
10
|
+
Maintainer-email: Neosapience <help@typecast.ai>
|
|
11
|
+
License: Apache License
|
|
12
|
+
Version 2.0, January 2004
|
|
13
|
+
http://www.apache.org/licenses/
|
|
14
|
+
|
|
15
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
16
|
+
|
|
17
|
+
1. Definitions.
|
|
18
|
+
|
|
19
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
20
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
21
|
+
|
|
22
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
23
|
+
the copyright owner that is granting the License.
|
|
24
|
+
|
|
25
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
26
|
+
other entities that control, are controlled by, or are under common
|
|
27
|
+
control with that entity. For the purposes of this definition,
|
|
28
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
29
|
+
direction or management of such entity, whether by contract or
|
|
30
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
31
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
32
|
+
|
|
33
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
34
|
+
exercising permissions granted by this License.
|
|
35
|
+
|
|
36
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
37
|
+
including but not limited to software source code, documentation
|
|
38
|
+
source, and configuration files.
|
|
39
|
+
|
|
40
|
+
"Object" form shall mean any form resulting from mechanical
|
|
41
|
+
transformation or translation of a Source form, including but
|
|
42
|
+
not limited to compiled object code, generated documentation,
|
|
43
|
+
and conversions to other media types.
|
|
44
|
+
|
|
45
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
46
|
+
Object form, made available under the License, as indicated by a
|
|
47
|
+
copyright notice that is included in or attached to the work
|
|
48
|
+
(an example is provided in the Appendix below).
|
|
49
|
+
|
|
50
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
51
|
+
form, that is based on (or derived from) the Work and for which the
|
|
52
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
53
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
54
|
+
of this License, Derivative Works shall not include works that remain
|
|
55
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
56
|
+
the Work and Derivative Works thereof.
|
|
57
|
+
|
|
58
|
+
"Contribution" shall mean any work of authorship, including
|
|
59
|
+
the original version of the Work and any modifications or additions
|
|
60
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
61
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
62
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
63
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
64
|
+
means any form of electronic, verbal, or written communication sent
|
|
65
|
+
to the Licensor or its representatives, including but not limited to
|
|
66
|
+
communication on electronic mailing lists, source code control systems,
|
|
67
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
68
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
69
|
+
excluding communication that is conspicuously marked or otherwise
|
|
70
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
71
|
+
|
|
72
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
73
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
74
|
+
subsequently incorporated within the Work.
|
|
75
|
+
|
|
76
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
77
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
78
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
79
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
80
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
81
|
+
Work and such Derivative Works in Source or Object form.
|
|
82
|
+
|
|
83
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
84
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
85
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
86
|
+
(except as stated in this section) patent license to make, have made,
|
|
87
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
88
|
+
where such license applies only to those patent claims licensable
|
|
89
|
+
by such Contributor that are necessarily infringed by their
|
|
90
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
91
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
92
|
+
institute patent litigation against any entity (including a
|
|
93
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
94
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
95
|
+
or contributory patent infringement, then any patent licenses
|
|
96
|
+
granted to You under this License for that Work shall terminate
|
|
97
|
+
as of the date such litigation is filed.
|
|
98
|
+
|
|
99
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
100
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
101
|
+
modifications, and in Source or Object form, provided that You
|
|
102
|
+
meet the following conditions:
|
|
103
|
+
|
|
104
|
+
(a) You must give any other recipients of the Work or
|
|
105
|
+
Derivative Works a copy of this License; and
|
|
106
|
+
|
|
107
|
+
(b) You must cause any modified files to carry prominent notices
|
|
108
|
+
stating that You changed the files; and
|
|
109
|
+
|
|
110
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
111
|
+
that You distribute, all copyright, patent, trademark, and
|
|
112
|
+
attribution notices from the Source form of the Work,
|
|
113
|
+
excluding those notices that do not pertain to any part of
|
|
114
|
+
the Derivative Works; and
|
|
115
|
+
|
|
116
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
117
|
+
distribution, then any Derivative Works that You distribute must
|
|
118
|
+
include a readable copy of the attribution notices contained
|
|
119
|
+
within such NOTICE file, excluding those notices that do not
|
|
120
|
+
pertain to any part of the Derivative Works, in at least one
|
|
121
|
+
of the following places: within a NOTICE text file distributed
|
|
122
|
+
as part of the Derivative Works; within the Source form or
|
|
123
|
+
documentation, if provided along with the Derivative Works; or,
|
|
124
|
+
within a display generated by the Derivative Works, if and
|
|
125
|
+
wherever such third-party notices normally appear. The contents
|
|
126
|
+
of the NOTICE file are for informational purposes only and
|
|
127
|
+
do not modify the License. You may add Your own attribution
|
|
128
|
+
notices within Derivative Works that You distribute, alongside
|
|
129
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
130
|
+
that such additional attribution notices cannot be construed
|
|
131
|
+
as modifying the License.
|
|
132
|
+
|
|
133
|
+
You may add Your own copyright statement to Your modifications and
|
|
134
|
+
may provide additional or different license terms and conditions
|
|
135
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
136
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
137
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
138
|
+
the conditions stated in this License.
|
|
139
|
+
|
|
140
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
141
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
142
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
143
|
+
this License, without any additional terms or conditions.
|
|
144
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
145
|
+
the terms of any separate license agreement you may have executed
|
|
146
|
+
with Licensor regarding such Contributions.
|
|
147
|
+
|
|
148
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
149
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
150
|
+
except as required for reasonable and customary use in describing the
|
|
151
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
152
|
+
|
|
153
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
154
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
155
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
156
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
157
|
+
implied, including, without limitation, any warranties or conditions
|
|
158
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
159
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
160
|
+
appropriateness of using or redistributing the Work and assume any
|
|
161
|
+
risks associated with Your exercise of permissions under this License.
|
|
162
|
+
|
|
163
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
164
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
165
|
+
unless required by applicable law (such as deliberate and grossly
|
|
166
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
167
|
+
liable to You for damages, including any direct, indirect, special,
|
|
168
|
+
incidental, or consequential damages of any character arising as a
|
|
169
|
+
result of this License or out of the use or inability to use the
|
|
170
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
171
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
172
|
+
other commercial damages or losses), even if such Contributor
|
|
173
|
+
has been advised of the possibility of such damages.
|
|
174
|
+
|
|
175
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
176
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
177
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
178
|
+
or other liability obligations and/or rights consistent with this
|
|
179
|
+
License. However, in accepting such obligations, You may act only
|
|
180
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
181
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
182
|
+
defend, and hold each Contributor harmless for any liability
|
|
183
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
184
|
+
of your accepting any such warranty or additional liability.
|
|
185
|
+
|
|
186
|
+
END OF TERMS AND CONDITIONS
|
|
187
|
+
|
|
188
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
189
|
+
|
|
190
|
+
To apply the Apache License to your work, attach the following
|
|
191
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
192
|
+
replaced with your own identifying information. (Don't include
|
|
193
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
194
|
+
comment syntax for the file format. We also recommend that a
|
|
195
|
+
file or class name and description of purpose be included on the
|
|
196
|
+
same "printed page" as the copyright notice for easier
|
|
197
|
+
identification within third-party archives.
|
|
198
|
+
|
|
199
|
+
Copyright 2025 Neosapience, Inc.
|
|
200
|
+
|
|
201
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
202
|
+
you may not use this file except in compliance with the License.
|
|
203
|
+
You may obtain a copy of the License at
|
|
204
|
+
|
|
205
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
206
|
+
|
|
207
|
+
Unless required by applicable law or agreed to in writing, software
|
|
208
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
209
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
210
|
+
See the License for the specific language governing permissions and
|
|
211
|
+
limitations under the License.
|
|
212
|
+
|
|
213
|
+
License-File: LICENSE
|
|
214
|
+
Keywords: ai,audio,speech-synthesis,text-to-speech,tts,typecast,voice,voice-generation
|
|
215
|
+
Classifier: Development Status :: 3 - Alpha
|
|
216
|
+
Classifier: Intended Audience :: Developers
|
|
217
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
218
|
+
Classifier: Operating System :: OS Independent
|
|
219
|
+
Classifier: Programming Language :: Python :: 3
|
|
220
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
221
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
222
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
223
|
+
Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
|
|
224
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
225
|
+
Requires-Python: >=3.11
|
|
226
|
+
Requires-Dist: aiohttp>=3.8.0
|
|
227
|
+
Requires-Dist: pydantic>=2.0.0
|
|
228
|
+
Requires-Dist: requests>=2.28.0
|
|
229
|
+
Requires-Dist: sseclient-py>=1.7.2
|
|
230
|
+
Requires-Dist: typing-extensions>=4.0.0
|
|
231
|
+
Requires-Dist: websockets>=10.0
|
|
232
|
+
Provides-Extra: dev
|
|
233
|
+
Requires-Dist: black>=23.0.0; extra == 'dev'
|
|
234
|
+
Requires-Dist: flake8>=6.0.0; extra == 'dev'
|
|
235
|
+
Requires-Dist: isort>=5.0.0; extra == 'dev'
|
|
236
|
+
Requires-Dist: mypy>=1.0.0; extra == 'dev'
|
|
237
|
+
Requires-Dist: pytest-asyncio>=0.21.0; extra == 'dev'
|
|
238
|
+
Requires-Dist: pytest-mock>=3.14.0; extra == 'dev'
|
|
239
|
+
Requires-Dist: pytest>=7.0.0; extra == 'dev'
|
|
240
|
+
Description-Content-Type: text/markdown
|
|
241
|
+
|
|
242
|
+
# Typecast Python SDK
|
|
243
|
+
|
|
244
|
+
Python SDK for Typecast API integration. Convert text to lifelike speech using AI-powered voices with emotion, pitch, and tempo control.
|
|
245
|
+
|
|
246
|
+
For comprehensive API documentation, visit [Typecast Documentation](https://typecast.ai/docs/overview).
|
|
247
|
+
|
|
248
|
+
## Installation
|
|
249
|
+
|
|
250
|
+
```bash
|
|
251
|
+
pip install typecast-python
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
## Quick Start
|
|
255
|
+
|
|
256
|
+
```python
|
|
257
|
+
from typecast.client import Typecast
|
|
258
|
+
from typecast.models import TTSRequest
|
|
259
|
+
|
|
260
|
+
# Initialize client
|
|
261
|
+
cli = Typecast(api_key="YOUR_API_KEY")
|
|
262
|
+
|
|
263
|
+
# Convert text to speech
|
|
264
|
+
response = cli.text_to_speech(TTSRequest(
|
|
265
|
+
text="Hello there! I'm your friendly text-to-speech agent.",
|
|
266
|
+
model="ssfm-v21",
|
|
267
|
+
voice_id="tc_62a8975e695ad26f7fb514d1"
|
|
268
|
+
))
|
|
269
|
+
|
|
270
|
+
# Save audio file
|
|
271
|
+
with open('output.wav', 'wb') as f:
|
|
272
|
+
f.write(response.audio_data)
|
|
273
|
+
|
|
274
|
+
print(f"Duration: {response.duration}s, Format: {response.format}")
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
## Features
|
|
278
|
+
|
|
279
|
+
- 🎙️ **Multiple Voice Models**: Support for various AI voice models (ssfm-v21, v20, etc.)
|
|
280
|
+
- 🌍 **Multi-language Support**: 27+ languages including English, Korean, Spanish, Japanese, Chinese, and more
|
|
281
|
+
- 😊 **Emotion Control**: Adjust emotional expression (happy, sad, angry, normal) with intensity control
|
|
282
|
+
- 🎚️ **Audio Customization**: Control volume, pitch, tempo, and output format (WAV/MP3)
|
|
283
|
+
- ⚡ **Async Support**: Built-in async client for high-performance applications
|
|
284
|
+
- 🔍 **Voice Discovery**: List and search available voices by model
|
|
285
|
+
|
|
286
|
+
## Advanced Usage
|
|
287
|
+
|
|
288
|
+
### Emotion and Audio Control
|
|
289
|
+
|
|
290
|
+
```python
|
|
291
|
+
from typecast.client import Typecast
|
|
292
|
+
from typecast.models import TTSRequest, Prompt, Output
|
|
293
|
+
|
|
294
|
+
cli = Typecast()
|
|
295
|
+
|
|
296
|
+
response = cli.text_to_speech(TTSRequest(
|
|
297
|
+
text="I am so excited to show you these features!",
|
|
298
|
+
model="ssfm-v21",
|
|
299
|
+
voice_id="tc_62a8975e695ad26f7fb514d1",
|
|
300
|
+
language="eng",
|
|
301
|
+
prompt=Prompt(
|
|
302
|
+
emotion_preset="happy", # Options: normal, happy, sad, angry
|
|
303
|
+
emotion_intensity=1.5 # Range: 0.0 to 2.0
|
|
304
|
+
),
|
|
305
|
+
output=Output(
|
|
306
|
+
volume=120, # Range: 0 to 200
|
|
307
|
+
audio_pitch=2, # Range: -12 to +12 semitones
|
|
308
|
+
audio_tempo=1.2, # Range: 0.5x to 2.0x
|
|
309
|
+
audio_format="mp3" # Options: wav, mp3
|
|
310
|
+
),
|
|
311
|
+
seed=42 # For reproducible results
|
|
312
|
+
))
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
### Voice Discovery
|
|
316
|
+
|
|
317
|
+
```python
|
|
318
|
+
# List all voices
|
|
319
|
+
voices = cli.voices()
|
|
320
|
+
|
|
321
|
+
# Filter by model
|
|
322
|
+
v21_voices = cli.voices(model="ssfm-v21")
|
|
323
|
+
|
|
324
|
+
# Get specific voice
|
|
325
|
+
voice = cli.get_voice("tc_62a8975e695ad26f7fb514d1")
|
|
326
|
+
print(f"Voice: {voice.voice_name}")
|
|
327
|
+
print(f"Available emotions: {voice.emotions}")
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
### Async Client
|
|
331
|
+
|
|
332
|
+
```python
|
|
333
|
+
import asyncio
|
|
334
|
+
from typecast.async_client import AsyncTypecast
|
|
335
|
+
from typecast.models import TTSRequest, LanguageCode
|
|
336
|
+
|
|
337
|
+
async def main():
|
|
338
|
+
async with AsyncTypecast() as cli:
|
|
339
|
+
response = await cli.text_to_speech(TTSRequest(
|
|
340
|
+
text="Hello from async!",
|
|
341
|
+
model="ssfm-v21",
|
|
342
|
+
voice_id="tc_62a8975e695ad26f7fb514d1",
|
|
343
|
+
language=LanguageCode.ENG
|
|
344
|
+
))
|
|
345
|
+
|
|
346
|
+
with open('async_output.wav', 'wb') as f:
|
|
347
|
+
f.write(response.audio_data)
|
|
348
|
+
|
|
349
|
+
asyncio.run(main())
|
|
350
|
+
```
|
|
351
|
+
|
|
352
|
+
## Supported Languages
|
|
353
|
+
|
|
354
|
+
The SDK supports 27 languages with ISO 639-3 codes:
|
|
355
|
+
|
|
356
|
+
| Language | Code | Language | Code | Language | Code |
|
|
357
|
+
|----------|------|----------|------|----------|------|
|
|
358
|
+
| English | `eng` | Japanese | `jpn` | Ukrainian | `ukr` |
|
|
359
|
+
| Korean | `kor` | Greek | `ell` | Indonesian | `ind` |
|
|
360
|
+
| Spanish | `spa` | Tamil | `tam` | Danish | `dan` |
|
|
361
|
+
| German | `deu` | Tagalog | `tgl` | Swedish | `swe` |
|
|
362
|
+
| French | `fra` | Finnish | `fin` | Malay | `msa` |
|
|
363
|
+
| Italian | `ita` | Chinese | `zho` | Czech | `ces` |
|
|
364
|
+
| Polish | `pol` | Slovak | `slk` | Portuguese | `por` |
|
|
365
|
+
| Dutch | `nld` | Arabic | `ara` | Bulgarian | `bul` |
|
|
366
|
+
| Russian | `rus` | Croatian | `hrv` | Romanian | `ron` |
|
|
367
|
+
|
|
368
|
+
Use the `LanguageCode` enum for type-safe language selection:
|
|
369
|
+
|
|
370
|
+
```python
|
|
371
|
+
from typecast.models import LanguageCode
|
|
372
|
+
|
|
373
|
+
request = TTSRequest(
|
|
374
|
+
text="Hello",
|
|
375
|
+
language=LanguageCode.ENG,
|
|
376
|
+
...
|
|
377
|
+
)
|
|
378
|
+
```
|
|
379
|
+
|
|
380
|
+
## Error Handling
|
|
381
|
+
|
|
382
|
+
The SDK provides specific exceptions for different HTTP status codes:
|
|
383
|
+
|
|
384
|
+
```python
|
|
385
|
+
from typecast.exceptions import (
|
|
386
|
+
BadRequestError, # 400
|
|
387
|
+
UnauthorizedError, # 401
|
|
388
|
+
PaymentRequiredError, # 402
|
|
389
|
+
NotFoundError, # 404
|
|
390
|
+
UnprocessableEntityError, # 422
|
|
391
|
+
InternalServerError, # 500
|
|
392
|
+
TypecastError # Base exception
|
|
393
|
+
)
|
|
394
|
+
|
|
395
|
+
try:
|
|
396
|
+
response = cli.text_to_speech(request)
|
|
397
|
+
except UnauthorizedError:
|
|
398
|
+
print("Invalid API key")
|
|
399
|
+
except PaymentRequiredError:
|
|
400
|
+
print("Insufficient credits")
|
|
401
|
+
except TypecastError as e:
|
|
402
|
+
print(f"Error: {e.message}, Status: {e.status_code}")
|
|
403
|
+
```
|
|
404
|
+
|
|
405
|
+
## Examples
|
|
406
|
+
|
|
407
|
+
Check out the [examples](./examples) directory for more usage examples:
|
|
408
|
+
|
|
409
|
+
- [`simple.py`](./examples/simple.py) - Basic text-to-speech conversion
|
|
410
|
+
- [`advanced.py`](./examples/advanced.py) - Emotion, pitch, and tempo control
|
|
411
|
+
- [`voices_example.py`](./examples/voices_example.py) - Discovering available voices
|
|
412
|
+
- [`async_example.py`](./examples/async_example.py) - Async client usage
|
|
413
|
+
|
|
414
|
+
## Configuration
|
|
415
|
+
|
|
416
|
+
Set your API key via environment variable or constructor:
|
|
417
|
+
|
|
418
|
+
```bash
|
|
419
|
+
export TYPECAST_API_KEY="your-api-key-here"
|
|
420
|
+
```
|
|
421
|
+
|
|
422
|
+
```python
|
|
423
|
+
# From environment variable
|
|
424
|
+
cli = Typecast()
|
|
425
|
+
|
|
426
|
+
# Or pass directly
|
|
427
|
+
cli = Typecast(api_key="your-api-key-here")
|
|
428
|
+
|
|
429
|
+
# Custom host (optional)
|
|
430
|
+
cli = Typecast(host="https://custom-api.example.com")
|
|
431
|
+
```
|
|
432
|
+
|
|
433
|
+
## License
|
|
434
|
+
|
|
435
|
+
Apache License 2.0
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
typecast/__init__.py,sha256=4myCSrkBPWo82PaySHS0DNWMfMe1zE-lHrDfrO-u6MQ,417
|
|
2
|
+
typecast/async_client.py,sha256=ayZjpUjPiblGy9vjybLTt3_sROhx2iD0qpFByTO8aW4,4118
|
|
3
|
+
typecast/client.py,sha256=UW50m25_ClmVyMDvIx8WfWhdBnBcgeAOmSzhx1Zeesw,3203
|
|
4
|
+
typecast/conf.py,sha256=Fn_T4XW7BaHRnj0tP11BT5at3Y-db7oGcbBA_E1fmF0,479
|
|
5
|
+
typecast/exceptions.py,sha256=Uo9Q2A1IvplBjZWE7Dx9gEId0YVFPPvw1QMBnPiccwo,1385
|
|
6
|
+
typecast/sse.py,sha256=yYO2h5E_1-uiIID0TZM03eRZfvgkCStxu-0J6ej4Bpo,1109
|
|
7
|
+
typecast/utils.py,sha256=XuNuX7gW8_CGKqZ-cv_tKlPVMPBluAYJBw2clwmjIMI,708
|
|
8
|
+
typecast/websocket.py,sha256=SwFmk2efGtMLY3UgEtZljZAhULl5HG6KaA-rqfJ0Jaw,1336
|
|
9
|
+
typecast/models/__init__.py,sha256=dgJZEe0ZEHN62nJu2QiZz0OvVKNihVHVw5bNGjk53g4,328
|
|
10
|
+
typecast/models/error.py,sha256=XomIjx7jvlCjItqzJuCAT4mXC9jwTjxR8lLDUk6P8KA,152
|
|
11
|
+
typecast/models/tts.py,sha256=tlQlmaoKuu11f7mLPK2DROiSSjELirpNhGuokMpEAqU,2304
|
|
12
|
+
typecast/models/tts_wss.py,sha256=zYfP3oNs5VuOkxI7bu0uSCHDYfSbQWaenqg0lLLqaSc,101
|
|
13
|
+
typecast/models/voices.py,sha256=n5cxgJPt3FoLJCHwyGH9SAQjcI1ZEwz2a4pQeUkh0Ss,144
|
|
14
|
+
typecast_python-0.1.3.dist-info/METADATA,sha256=kRWKfU1FTJyKW7PTPpmUbuLvYcUWg6G0Ao9qbyC9XiI,20151
|
|
15
|
+
typecast_python-0.1.3.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
16
|
+
typecast_python-0.1.3.dist-info/licenses/LICENSE,sha256=HvtJ-S89uUkuYmt-OvVk4MRxmzwtbn84__qJtSrGU2Q,11348
|
|
17
|
+
typecast_python-0.1.3.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2025 Neosapience, Inc.
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
202
|
+
|