### Install Project Dependencies Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/CONTRIBUTING.md Installs all necessary dependencies for the project using Poetry. ```bash poetry install ``` -------------------------------- ### Initialize Speechify Client Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/api-reference/client.md Demonstrates various ways to initialize the Speechify client, including basic setup, custom configurations for timeout and retries, using environment variables, and integrating a custom httpx client. ```python from speechify import Speechify # Basic initialization client = Speechify(api_key="your_api_key") ``` ```python client = Speechify( api_key="your_api_key", timeout=30.0, max_retries=3 ) ``` ```python import os os.environ["SPEECHIFY_API_KEY"] = "your_api_key" client = Speechify() ``` ```python import httpx client = Speechify( api_key="your_api_key", httpx_client=httpx.Client( proxy="http://proxy.example.com:8080", timeout=30.0 ) ) ``` -------------------------------- ### Install Speechifyinc Python Library Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/README.md Install the library using pip. This is the first step to using the Speechifyinc API in your Python projects. ```sh pip install speechify-api ``` -------------------------------- ### Get SDK Version Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/api-reference/core-utilities.md Prints the currently installed version of the Speechify SDK. This is useful for debugging and ensuring compatibility. ```python import speechify print(f"SDK version: {speechify.__version__}") ``` -------------------------------- ### Streaming with Custom Chunk Size Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/api-reference/request-options.md Configure the chunk size for streaming audio responses. This example sets it to 16 KB. ```python from speechify import Speechify client = Speechify(api_key="your_api_key") # Stream with 16 KB chunks chunks = [] for chunk in client.audio.stream( accept="audio/mpeg", input="Hello world", voice_id="george", request_options={ "chunk_size": 16384 # 16 KB } ): chunks.append(chunk) audio_data = b"".join(chunks) ``` -------------------------------- ### Stream Audio for Real-time Processing Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/api-reference/audio-client.md Shows how to process audio chunks as they are received from the stream() method, suitable for real-time playback or other immediate processing. This example prints the size of each received chunk. ```python # Or process chunks in real-time (e.g., play audio as it arrives) import time for chunk in audio_stream: # Send chunk to audio player, queue, etc. print(f"Received {len(chunk)} bytes") ``` -------------------------------- ### Configure Chunk Size for Streaming Responses Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/configuration.md Example of setting a custom chunk size for streaming audio responses. This allows control over how data is received in chunks. ```python from speechify import Speechify client = Speechify(api_key="your_api_key") # Configure chunk size for streaming for chunk in client.audio.stream( accept="audio/mpeg", input="Hello world", voice_id="george", request_options={ "chunk_size": 8192 # 8 KB chunks } ): # Process chunk pass ``` -------------------------------- ### Using Open Binary File Object for Upload Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/api-reference/request-options.md Shows how to use an open binary file object (IO[bytes]) for uploading files. Ensure the file is opened in binary read mode ('rb'). This example uses a 'with' statement for proper file handling. ```python with open("voice_sample.wav", "rb") as f: response = client.voices.create( name="Voice", sample=f, gender="male", consent=consent_json ) ``` -------------------------------- ### Async Error Handling for Voice Downloads Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/errors.md Handle errors asynchronously when downloading voice samples. This example shows how to manage 'not found' and 'rate limited' errors, including implementing a recursive retry with a delay for rate limiting. ```python import asyncio from speechify import AsyncSpeechify from speechify.errors import NotFoundError, TooManyRequestsError async def safe_voice_download(client, voice_id): try: chunks = [] async for chunk in await client.voices.download_sample(voice_id): chunks.append(chunk) return b" ".join(chunks) except NotFoundError: print(f"Voice {voice_id} not found") return None except TooManyRequestsError: print("Rate limited, backing off...") await asyncio.sleep(5) return await safe_voice_download(client, voice_id) async def main(): client = AsyncSpeechify(api_key="your_api_key") audio = await safe_voice_download(client, "george") asyncio.run(main()) ``` -------------------------------- ### Initialize Speechify Client with Default Environment Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/api-reference/core-utilities.md Demonstrates how to initialize the Speechify client using the default API environment. Ensure you have your API key available. ```python from speechify import Speechify, SpeechifyEnvironment client = Speechify( api_key="...", environment=SpeechifyEnvironment.DEFAULT ) ``` -------------------------------- ### Instantiate and Use Speechify Client Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/README.md Import the Speechify client and instantiate it with your API key. Then, use the client to make API calls, such as generating speech. ```python from speechify import Speechify client = Speechify( api_key="", ) client.audio.speech( audio_format="mp3", input="Hello! This is the Speechify text-to-speech API.", model="simba-english", voice_id="george", ) ``` -------------------------------- ### Example Speechify API Validation Error Response Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/errors.md An example of an error response indicating that request validation failed. The 'fields' object provides details on which specific fields caused the validation to fail. ```json { "error": { "code": "validation_failed", "message": "Request validation failed", "fields": { "input": "input must be a non-empty string", "voice_id": "voice_id must be a valid voice identifier" } }, "request_id": "req_1234567890abcdef" } ``` -------------------------------- ### client.voices.list() Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/reference.md Gets the list of voices available for the user. ```APIDOC ## client.voices.list() ### Description Gets the list of voices available for the user. ### Method client.voices.list() ### Parameters #### Query Parameters - **request_options** (typing.Optional[RequestOptions]) - Optional - Request-specific configuration. ### Response #### Success Response (200) - **voices** (typing.List[GetVoice]) - A list of available voices. ### Request Example ```python from speechify import Speechify from speechify.environment import SpeechifyEnvironment client = Speechify( api_key="", environment=SpeechifyEnvironment.DEFAULT, ) client.voices.list() ``` ``` -------------------------------- ### Initialize Speechify Client (Basic) Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/README.md Basic client initialization requires only an API key. ```python from speechify import Speechify # Basic client = Speechify(api_key="...") ``` -------------------------------- ### Basic Speech Synthesis and Voice Listing (Synchronous) Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/README.md Demonstrates how to initialize the Speechify client, synthesize speech to an MP3 file, and list available voices using synchronous calls. ```python from speechify import Speechify # Initialize client client = Speechify(api_key="your_api_key") # Synthesize speech response = client.audio.speech( input="Hello, world!", voice_id="george", model="simba-english", audio_format="mp3" ) # Access the synthesized audio import base64 audio_bytes = base64.b64decode(response.audio_data) with open("output.mp3", "wb") as f: f.write(audio_bytes) # List available voices voices = client.voices.list() for voice in voices: print(f"{voice.display_name} ({voice.id})") ``` -------------------------------- ### Override Request Timeout and Retries Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/configuration.md Example of overriding the default timeout and maximum retries for a single API request. Ensure `api_key` is set or provided. ```python from speechify import Speechify client = Speechify(api_key="your_api_key") # Override timeout for a single request response = client.audio.speech( input="Hello world", voice_id="george", request_options={ "timeout_in_seconds": 30, "max_retries": 5 } ) ``` -------------------------------- ### Initialize Speechify Client with Environment Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/configuration.md Initialize the Speechify client using a predefined environment or a custom base URL. Ensure you have your API key. ```python from speechify import Speechify, SpeechifyEnvironment client = Speechify( api_key="your_api_key", environment=SpeechifyEnvironment.DEFAULT ) # Or override with a custom base URL client = Speechify( api_key="your_api_key", base_url="https://custom.api.example.com" ) ``` -------------------------------- ### Voice Cloning with Different File Formats Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/api-reference/request-options.md Demonstrates creating a voice using audio samples provided as a file path, an open file object, raw bytes, or with explicit filename and content-type. Also shows how to include an avatar image. ```python from speechify import Speechify import json client = Speechify(api_key="your_api_key") consent = json.dumps({ "fullName": "John Doe", "email": "john@example.com" }) # From file path voice1 = client.voices.create( name="Voice from Path", gender="male", sample="voice_sample.wav", # SDK opens the file consent=consent ) # From open file object with open("voice_sample.wav", "rb") as f: voice2 = client.voices.create( name="Voice from File Object", gender="male", sample=f, consent=consent ) # From bytes with open("voice_sample.wav", "rb") as f: audio_bytes = f.read() voice3 = client.voices.create( name="Voice from Bytes", gender="male", sample=audio_bytes, consent=consent ) # With explicit filename and content-type voice4 = client.voices.create( name="Voice with Metadata", gender="male", sample=("sample.wav", audio_bytes, "audio/wav"), consent=consent ) # With avatar image voice5 = client.voices.create( name="Voice with Avatar", gender="male", sample=("sample.wav", audio_bytes, "audio/wav"), avatar=("avatar.png", open("avatar.png", "rb"), "image/png"), consent=consent ) ``` -------------------------------- ### NestedChunk Type Definition Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/types.md Provides detailed segment information within synthesized speech. This includes optional start and end times, type, and value for each segment. ```python class NestedChunk(UniversalBaseModel): end: typing.Optional[int] end_time: typing.Optional[float] start: typing.Optional[int] start_time: typing.Optional[float] type: typing.Optional[str] value: typing.Optional[str] ``` -------------------------------- ### Async Speechify Client with Custom Async HTTPX Client Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/configuration.md Initialize the AsyncSpeechify client with a custom httpx.AsyncClient, specifying limits and timeouts. Remember to close the client when done to release resources. ```python import httpx from speechify import AsyncSpeechify async def main(): httpx_client = httpx.AsyncClient( timeout=30.0, limits=httpx.Limits(max_connections=10) ) client = AsyncSpeechify( api_key="your_api_key", httpx_client=httpx_client # Must be AsyncClient, not Client ) # Use client... await httpx_client.aclose() # Clean up when done asyncio.run(main()) ``` -------------------------------- ### Access Raw HTTP Responses with VoicesClient Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/api-reference/voices-client.md Use the `with_raw_response` property on VoicesClient or AsyncVoicesClient to get a client instance that provides access to raw HTTP response details. ```python from speechify_api.voices import VoicesClient client = VoicesClient() raw_client = client.with_raw_response # Now you can use raw_client to make requests and access raw responses ``` -------------------------------- ### Initialize Speechify Client with Custom HTTPX Client Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/configuration.md Integrate a custom httpx.Client, including proxy settings and specific timeouts, with the Speechify client. This allows for advanced network configurations. ```python import httpx from speechify import Speechify httpx_client = httpx.Client( proxy="http://proxy.example.com:8080", timeout=30.0 ) client = Speechify( api_key="your_api_key", httpx_client=httpx_client ) ``` -------------------------------- ### Initialize AsyncSpeechify Client Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/api-reference/client.md Instantiate the AsyncSpeechify client with an API key. This client is used for asynchronous operations, such as generating speech or streaming audio. ```python import asyncio from speechify import AsyncSpeechify async def main(): client = AsyncSpeechify(api_key="your_api_key") # Use async methods response = await client.audio.speech( input="Hello world", voice_id="george", model="simba-english" ) # Stream audio asynchronously async for chunk in await client.audio.stream( accept="audio/mpeg", input="Hello world", voice_id="george" ): # Process audio chunk pass asyncio.run(main()) ``` -------------------------------- ### SpeechMarks Type Definition Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/types.md Represents metadata annotating synthesized audio with timing and segment details. It contains information about chunks, start and end times, and segment type. ```python class SpeechMarks(UniversalBaseModel): chunks: typing.List[NestedChunk] end: int end_time: float start: int start_time: float type: str value: typing.Optional[str] ``` -------------------------------- ### Build the Project Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/CONTRIBUTING.md Builds the project artifacts, typically for distribution. ```bash poetry build ``` -------------------------------- ### Configure Speechify Synchronous Client Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/configuration.md Instantiate the synchronous Speechify client with various configuration options. Use `api_key` or ensure `SPEECHIFY_API_KEY` environment variable is set. Advanced options include custom `httpx_client` for fine-grained control. ```python client = Speechify( base_url: typing.Optional[str] = None, environment: SpeechifyEnvironment = SpeechifyEnvironment.DEFAULT, api_key: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = os.getenv("SPEECHIFY_API_KEY"), headers: typing.Optional[typing.Dict[str, str]] = None, timeout: typing.Optional[float] = None, max_retries: typing.Optional[int] = None, follow_redirects: typing.Optional[bool] = True, httpx_client: typing.Optional[httpx.Client] = None, logging: typing.Optional[typing.Union[LogConfig, Logger]] = None, ) ``` -------------------------------- ### Async Client Usage Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/README.md Demonstrates how to use the asynchronous client for non-blocking audio processing and voice management operations. ```APIDOC ## Async Client Usage The SDK provides fully async clients for non-blocking operations: ```python import asyncio from speechify import AsyncSpeechify async def process_audio(): client = AsyncSpeechify(api_key="your_api_key") # All methods are async response = await client.audio.speech( input="Hello", voice_id="george" ) voices = await client.voices.list() created = await client.voices.create( name="...", gender="male", sample=..., consent=... ) async for chunk in await client.audio.stream( accept="audio/mpeg", input="...", voice_id="..." ): # Process chunk pass asyncio.run(process_audio()) ``` For async token refresh: ```python async def get_token(): # Refresh token via async API return "new_token" client = AsyncSpeechify( api_key="initial_key", async_token=get_token # Called before each request ) ``` ``` -------------------------------- ### Initialize Speechify Client with Environment Variable Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/configuration.md Initialize the Speechify client without explicitly providing an API key if it's set as the SPEECHIFY_API_KEY environment variable. ```python import os # Set API key as environment variable os.environ["SPEECHIFY_API_KEY"] = "your_api_key" from speechify import Speechify # No api_key parameter needed client = Speechify() ``` -------------------------------- ### Using Tuple with Filename for Upload Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/api-reference/request-options.md Demonstrates uploading a file by providing a tuple containing the filename hint and an open binary file object. This allows specifying a name for the uploaded file. ```python response = client.voices.create( name="Voice", sample=("voice_sample.wav", open("voice_sample.wav", "rb")), gender="male", consent=consent_json ) ``` -------------------------------- ### download_sample() Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/api-reference/voices-client.md Downloads an audio sample of a personal (cloned) voice. The audio is returned as a stream of bytes. ```APIDOC ## download_sample() ### Description Download an audio sample of a personal (cloned) voice. ### Method Signature ```python def download_sample( self, id: str, *, request_options: typing.Optional[RequestOptions] = None, ) -> typing.Iterator[bytes] ``` ### Parameters #### Path Parameters - **id** (str) - Required - The ID of the voice to download a sample for. - **request_options** (RequestOptions) - Optional - Request-specific configuration. Supports `chunk_size` to customize streaming chunk size. ### Returns `typing.Iterator[bytes]` An iterator yielding raw audio bytes of the voice sample. ### Example ```python from speechify import Speechify client = Speechify(api_key="your_api_key") # Stream voice sample to file with open("voice_sample_output.wav", "wb") as f: for chunk in client.voices.download_sample(id="voice_123"): f.write(chunk) print("Voice sample downloaded") # Or download in one shot sample_bytes = b"" for chunk in client.voices.download_sample(id="voice_123"): sample_bytes += chunk ``` ``` -------------------------------- ### Asynchronous Speech Synthesis, Voice Listing, and Streaming Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/README.md Illustrates how to perform speech synthesis, list voices, and stream audio using the asynchronous client. Requires `asyncio` to run. ```python import asyncio from speechify import AsyncSpeechify async def main(): client = AsyncSpeechify(api_key="your_api_key") # Synthesize speech asynchronously response = await client.audio.speech( input="Hello, world!", voice_id="george", model="simba-english" ) # List voices asynchronously voices = await client.voices.list() for voice in voices: print(f"{voice.display_name} ({voice.id})") # Stream audio asynchronously async for chunk in await client.audio.stream( accept="audio/mpeg", input="Hello", voice_id="george" ): # Process chunk pass asyncio.run(main()) ``` -------------------------------- ### Using File Path for Upload Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/api-reference/request-options.md Demonstrates how to pass a file path as a string to the SDK for file uploads. The SDK will handle opening and reading the file. ```python sample="voice_sample.wav" ``` -------------------------------- ### Initialize Async Speechify Client Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/README.md Instantiate the asynchronous Speechify client for non-blocking API calls. Ensure to use httpx.AsyncClient() if passing a pre-configured httpx client. ```python import asyncio from speechify import AsyncSpeechify client = AsyncSpeechify( api_key="", ) async def main() -> None: await client.audio.speech( audio_format="mp3", input="Hello! This is the Speechify text-to-speech API.", model="simba-english", voice_id="george", ) asyncio.run(main()) ``` -------------------------------- ### VoicesClient Methods Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/INDEX.md Documentation for the `VoicesClient` and `AsyncVoicesClient` including `list()`, `create()`, `delete()`, and `download_sample()` methods. ```APIDOC ## VoicesClient Methods ### Description These methods are part of the `VoicesClient` and `AsyncVoicesClient` for managing voices. ### Methods - **list()**: Retrieves a list of available voices. - **create()**: Creates a new voice. - **delete(voice_id: str)**: Deletes a voice by its ID. - **download_sample(voice_id: str)**: Downloads a sample of a voice. ### Parameters - **voice_id** (string) - Required for `delete()` and `download_sample()` - The ID of the voice. - **request_options** (RequestOptions) - Optional - Options for the request. ### Returns - **list()**: A list of voice objects. - **create()**: The created voice object. - **delete()**: Confirmation of deletion. - **download_sample()**: Audio data of the voice sample. ### Request Example ```python # Example for list() method voices = voices_client.list() # Example for delete() method voices_client.delete(voice_id="voice_to_delete") ``` ### Response Example ```json { "voices": [ { "id": "voice_id_1", "name": "Voice Name 1" } ] } ``` ``` -------------------------------- ### Voice Cloning with Different File Formats Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/api-reference/request-options.md Demonstrates various ways to provide the audio sample for voice cloning, including from a file path, an open file object, raw bytes, and with explicit metadata. It also shows how to include an avatar image. ```APIDOC ## Voice Cloning with Different File Formats This section illustrates how to use the `client.voices.create` method to upload audio samples for voice cloning, showcasing flexibility in input formats and additional options. ### Method `client.voices.create()` ### Parameters - **name** (string) - Required - The desired name for the cloned voice. - **gender** (string) - Required - The gender of the voice ('male' or 'female'). - **sample** (file path, file object, bytes, or tuple) - Required - The audio sample for cloning. Can be: - A string representing the file path to the audio file. - An open file object in binary read mode (`'rb'`). - A bytes object containing the audio data. - A tuple `(filename, data, content_type)` for explicit metadata. - **consent** (string) - Required - A JSON string containing user consent details, including `fullName` and `email`. - **avatar** (tuple) - Optional - A tuple `(filename, data, content_type)` for an avatar image. ### Examples #### 1. From file path ```python from speechify import Speechify import json client = Speechify(api_key="your_api_key") consent = json.dumps({ "fullName": "John Doe", "email": "john@example.com" }) voice1 = client.voices.create( name="Voice from Path", gender="male", sample="voice_sample.wav", # SDK opens the file consent=consent ) ``` #### 2. From open file object ```python with open("voice_sample.wav", "rb") as f: voice2 = client.voices.create( name="Voice from File Object", gender="male", sample=f, consent=consent ) ``` #### 3. From bytes ```python with open("voice_sample.wav", "rb") as f: audio_bytes = f.read() voice3 = client.voices.create( name="Voice from Bytes", gender="male", sample=audio_bytes, consent=consent ) ``` #### 4. With explicit filename and content-type ```python with open("voice_sample.wav", "rb") as f: audio_bytes = f.read() voice4 = client.voices.create( name="Voice with Metadata", gender="male", sample=("sample.wav", audio_bytes, "audio/wav"), consent=consent ) ``` #### 5. With avatar image ```python with open("voice_sample.wav", "rb") as f: audio_bytes = f.read() voice5 = client.voices.create( name="Voice with Avatar", gender="male", sample=("sample.wav", audio_bytes, "audio/wav"), avatar=("avatar.png", open("avatar.png", "rb"), "image/png"), consent=consent ) ``` ``` -------------------------------- ### Using Raw Bytes for Upload Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/api-reference/request-options.md Illustrates uploading files by passing raw audio bytes directly. This is useful when audio data is already in memory as a bytes object. ```python audio_bytes = b"..." # Audio data response = client.voices.create( name="Voice", sample=audio_bytes, gender="male", consent=consent_json ) ``` -------------------------------- ### Stream Audio to File (Synchronous) Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/README.md Shows how to stream synthesized audio directly to an MP3 file using a synchronous client. This is useful for long texts where intermediate storage is not desired. ```python from speechify import Speechify client = Speechify(api_key="your_api_key") # Stream audio to file with open("stream_output.mp3", "wb") as f: for chunk in client.audio.stream( accept="audio/mpeg", input="Hello, this is a long text that will stream.", voice_id="george" ): f.write(chunk) ``` -------------------------------- ### client.voices.download_sample() Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/reference.md Download a personal (cloned) voice sample. ```APIDOC ## client.voices.download_sample() ### Description Download a personal (cloned) voice sample. ### Method client.voices.download_sample(...) ### Parameters #### Path Parameters - **id** (str) - Required - The ID of the voice to download sample for - **request_options** (typing.Optional[RequestOptions]) - Optional - Request-specific configuration. ### Response #### Success Response (200) - **audio_data** (typing.Iterator[bytes]) - An iterator yielding the audio data in bytes. ### Request Example ```python from speechify import Speechify from speechify.environment import SpeechifyEnvironment client = Speechify( api_key="", environment=SpeechifyEnvironment.DEFAULT, ) client.voices.download_sample( id="id", ) ``` ``` -------------------------------- ### Stream Audio and Write to File Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/api-reference/audio-client.md Demonstrates how to use the stream() method to synthesize speech and write the resulting audio chunks to an MP3 file. Ensure you have an API key and the correct voice ID. ```python from speechify import Speechify client = Speechify(api_key="your_api_key") # Stream audio in chunks audio_stream = client.audio.stream( accept="audio/mpeg", input="This is a long text that will be streamed back in chunks.", voice_id="george", model="simba-english" ) # Write streamed audio to file with open("streaming_output.mp3", "wb") as f: for chunk in audio_stream: f.write(chunk) ``` -------------------------------- ### Configure Default Environment Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/README.md Initialize the Speechify client with the default environment settings. This is the standard way to set up the client for most use cases. ```python from speechify import Speechify from speechify.environment import SpeechifyEnvironment client = Speechify( environment=SpeechifyEnvironment.DEFAULT, ) ``` -------------------------------- ### create() Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/api-reference/voices-client.md Creates a new personal (cloned) voice for the user using an audio sample. Requires user consent. ```APIDOC ## create() ### Description Create a personal (cloned) voice for the user from an audio sample. ### Method Signature ```python def create( self, *, name: str, gender: CreateVoicesRequestGender, sample: core.File, consent: str, locale: typing.Optional[str] = OMIT, avatar: typing.Optional[core.File] = OMIT, request_options: typing.Optional[RequestOptions] = None, ) -> CreatedVoice ``` ### Parameters #### Required Parameters - **name** (`str`): Name of the personal voice. - **gender** (`CreateVoicesRequestGender`): Gender marker for the personal voice. Options: `male`, `female`, `notSpecified`. - **sample** (`core.File`): Audio file containing a voice sample. Can be a file path, file-like object, bytes, or tuple with optional filename and content-type. See `core.File` documentation. - **consent** (`str`): User consent information as a JSON string. Must include `fullName` and `email` of the consenting individual. Example: `{"fullName": "John Doe", "email": "john@example.com"}`. #### Optional Parameters - **locale** (`str`): Native language/locale of the voice (e.g., `en-US`, `es-ES`). If omitted, the system will attempt to auto-detect. - **avatar** (`core.File`): Optional avatar image for the voice. Same format as `sample` parameter. - **request_options** (`RequestOptions`): Request-specific configuration. ### Returns - `CreatedVoice`: The created voice object with ID, display name, gender, locale, type, models, and optional avatar image. ### Example ```python from speechify import Speechify import json client = Speechify(api_key="your_api_key") # Prepare consent as JSON string consent_data = { "fullName": "John Doe", "email": "john@example.com" } # Create a voice from a sample file created_voice = client.voices.create( name="My Custom Voice", gender="male", sample=open("voice_sample.wav", "rb"), consent=json.dumps(consent_data), locale="en-US" ) print(f"Voice created with ID: {created_voice.id}") print(f"Voice name: {created_voice.display_name}") print(f"Voice type: {created_voice.type}" ) # Will be 'personal' # Or use bytes directly with open("voice_sample.wav", "rb") as f: sample_bytes = f.read() created_voice = client.voices.create( name="Another Voice", gender="female", sample=sample_bytes, consent=json.dumps(consent_data) ) ``` ``` -------------------------------- ### AudioClient Methods Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/INDEX.md Documentation for the `AudioClient` and `AsyncAudioClient` including `speech()` and `stream()` methods. ```APIDOC ## `speech()` and `stream()` Methods ### Description These methods are part of the `AudioClient` and `AsyncAudioClient` for generating and streaming audio. ### Parameters - **text** (string) - Required - The text to convert to speech. - **voice_id** (string) - Optional - The ID of the voice to use. - **request_options** (RequestOptions) - Optional - Options for the request, such as file handling. ### Returns - **Audio data** or **stream** depending on the method used. ### Request Example ```python # Example for speech() method audio_data = audio_client.speech(text="Hello, world!", voice_id="example_voice_id") # Example for stream() method audio_stream = audio_client.stream(text="Streaming audio example", voice_id="example_voice_id") ``` ### Response Example ```json { "audio_content": "base64_encoded_audio_data" } ``` ``` -------------------------------- ### Authentication Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/MANIFEST.txt Documentation on various authentication methods supported by the SDK, including static API keys, API keys from environment variables, callable API keys, and async callable API keys. ```APIDOC ## Authentication ### Description This section details the supported methods for authenticating with the Speechify API using the SDK. ### Usage Patterns Documented - Static API key - API key from environment variable - Callable API key (dynamic) - Async callable API key (async refresh) ``` -------------------------------- ### async create() Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/api-reference/voices-client.md Asynchronously creates a new voice. This method requires voice name, gender, a sample audio file, and consent information. It mirrors the functionality of the synchronous `VoicesClient.create()` method. ```APIDOC ## async create() ### Description Asynchronously creates a new voice. This method requires voice name, gender, a sample audio file, and consent information. It mirrors the functionality of the synchronous `VoicesClient.create()` method. ### Method `async def create(self, *, name: str, gender: CreateVoicesRequestGender, sample: core.File, consent: str, locale: typing.Optional[str] = OMIT, avatar: typing.Optional[core.File] = OMIT, request_options: typing.Optional[RequestOptions] = None) -> CreatedVoice` ### Parameters #### Path Parameters - **name** (str) - Required - The name for the new voice. - **gender** (CreateVoicesRequestGender) - Required - The gender of the voice. - **sample** (core.File) - Required - A sample audio file for the voice. - **consent** (str) - Required - Consent information for creating the voice. - **locale** (str) - Optional - The locale for the voice (e.g., "en-US"). - **avatar** (core.File) - Optional - An avatar file for the voice. - **request_options** (RequestOptions) - Optional - Options for the request. ### Response #### Success Response - **CreatedVoice**: An object representing the newly created voice. ### Example ```python import asyncio import json from speechify import AsyncSpeechify async def main(): client = AsyncSpeechify(api_key="your_api_key") consent_data = { "fullName": "Jane Doe", "email": "jane@example.com" } created_voice = await client.voices.create( name="My Async Voice", gender="female", sample=open("voice_sample.wav", "rb"), consent=json.dumps(consent_data), locale="en-US" ) print(f"Voice created: {created_voice.id}") asyncio.run(main()) ``` ``` -------------------------------- ### client.voices.create() Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/reference.md Create a personal (cloned) voice for the user. ```APIDOC ## client.voices.create() ### Description Create a personal (cloned) voice for the user. ### Method client.voices.create(...) ### Parameters #### Path Parameters - **name** (str) - Required - Name of the personal voice - **gender** (CreateVoicesRequestGender) - Required - Gender marker for the personal voice (male, female, notSpecified) - **sample** (core.File) - Required - Audio sample file - **consent** (str) - Required - A string representing the user consent information in JSON format (e.g., `{"fullName": "John Doe", "email": "john@example.com"}`) - **locale** (typing.Optional[str]) - Optional - Native language (locale) of the personal voice (e.g. en-US, es-ES, etc.) - **avatar** (typing.Optional[core.File]) - Optional - Avatar image file - **request_options** (typing.Optional[RequestOptions]) - Optional - Request-specific configuration. ### Response #### Success Response (200) - **created_voice** (CreatedVoice) - Details of the created voice. ### Request Example ```python from speechify import Speechify from speechify.environment import SpeechifyEnvironment client = Speechify( api_key="", environment=SpeechifyEnvironment.DEFAULT, ) client.voices.create( sample="example_sample", avatar="example_avatar", name="name", gender="male", consent="consent", ) ``` ``` -------------------------------- ### async download_sample() Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/api-reference/voices-client.md Asynchronously downloads the sample audio for a voice by its ID. Returns an async iterator yielding raw audio bytes. This method has the same parameters as `VoicesClient.download_sample()` but returns an async iterator. ```APIDOC ## async download_sample() ### Description Asynchronously downloads the sample audio for a voice by its ID. Returns an async iterator yielding raw audio bytes. This method has the same parameters as `VoicesClient.download_sample()` but returns an async iterator. ### Method `async def download_sample(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> typing.AsyncIterator[bytes]` ### Parameters #### Path Parameters - **id** (str) - Required - The ID of the voice sample to download. - **request_options** (RequestOptions) - Optional - Options for the request. ### Response #### Success Response - **typing.AsyncIterator[bytes]**: An async iterator yielding raw audio bytes of the voice sample. ### Example ```python import asyncio from speechify import AsyncSpeechify async def main(): client = AsyncSpeechify(api_key="your_api_key") with open("voice_sample_output.wav", "wb") as f: async for chunk in await client.voices.download_sample(id="voice_123"): f.write(chunk) asyncio.run(main()) ``` ``` -------------------------------- ### Voice Cloning and Usage Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/README.md Demonstrates the process of creating a personal voice using voice cloning, synthesizing speech with the cloned voice, downloading its sample, and deleting the voice. Requires a local WAV file for the sample. ```python from speechify import Speechify import json client = Speechify(api_key="your_api_key") # Prepare consent information consent = json.dumps({ "fullName": "Jane Doe", "email": "jane@example.com" }) # Create a personal voice from a sample created_voice = client.voices.create( name="My Voice", gender="female", sample=open("voice_sample.wav", "rb"), consent=consent, locale="en-US" ) print(f"Voice created: {created_voice.id}") # Use the created voice in synthesis response = client.audio.speech( input="Hello from my cloned voice!", voice_id=created_voice.id, model="simba-english" ) # Download the voice sample later with open("downloaded_sample.wav", "wb") as f: for chunk in client.voices.download_sample(created_voice.id): f.write(chunk) # Delete the voice when no longer needed client.voices.delete(created_voice.id) ``` -------------------------------- ### Async Operations with Speechify SDK Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/README.md Demonstrates how to use the asynchronous client for non-blocking audio processing, voice listing, creation, and streaming. All methods are async and require awaiting. ```python import asyncio from speechify import AsyncSpeechify async def process_audio(): client = AsyncSpeechify(api_key="your_api_key") # All methods are async response = await client.audio.speech( input="Hello", voice_id="george" ) voices = await client.voices.list() created = await client.voices.create( name="...", gender="male", sample=..., consent=... ) async for chunk in await client.audio.stream( accept="audio/mpeg", input="...", voice_id="..." ): # Process chunk pass asyncio.run(process_audio()) ``` -------------------------------- ### Initialize Speechify Client with Custom Headers Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/README.md Add custom headers to all requests made by the client by providing a dictionary during initialization. ```python from speechify import Speechify # With custom headers client = Speechify( api_key="...", headers={ "X-Request-Source": "my-app" } ) ``` -------------------------------- ### Configure AsyncSpeechify Asynchronous Client Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/configuration.md Instantiate the asynchronous Speechify client. Supports synchronous `api_key` or an `async_token` callable for async token retrieval. Custom `httpx.AsyncClient` can be provided for advanced async configurations. ```python client = AsyncSpeechify( base_url: typing.Optional[str] = None, environment: SpeechifyEnvironment = SpeechifyEnvironment.DEFAULT, api_key: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = os.getenv("SPEECHIFY_API_KEY"), headers: typing.Optional[typing.Dict[str, str]] = None, async_token: typing.Optional[typing.Callable[[], typing.Awaitable[str]]] = None, timeout: typing.Optional[float] = None, max_retries: typing.Optional[int] = None, follow_redirects: typing.Optional[bool] = True, httpx_client: typing.Optional[httpx.AsyncClient] = None, logging: typing.Optional[typing.Union[LogConfig, Logger]] = None, ) ``` -------------------------------- ### Format Code Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/CONTRIBUTING.md Automatically formats the code according to project standards using Ruff. ```bash poetry run ruff format . ``` -------------------------------- ### AsyncSpeechify Constructor Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/api-reference/client.md Initializes the asynchronous Speechify API client. Allows customization of base URL, environment, API key, headers, token acquisition, timeouts, retries, redirects, and HTTP client. ```APIDOC ## AsyncSpeechify Constructor ### Description Initializes the asynchronous Speechify API client. Allows customization of base URL, environment, API key, headers, token acquisition, timeouts, retries, redirects, and HTTP client. ### Parameters | Parameter | Type | Default | Description | |---|---|---|---| | base_url | `typing.Optional[str]` | `None` | Override the default API base URL. | | environment | `SpeechifyEnvironment` | `SpeechifyEnvironment.DEFAULT` | The API environment to use. | | api_key | `typing.Optional[typing.Union[str, typing.Callable[[], str]]]` | `os.getenv("SPEECHIFY_API_KEY")` | API key for authentication. Required unless provided via environment variable. | | headers | `typing.Optional[typing.Dict[str, str]]` | `None` | Additional HTTP headers to send with every request. | | async_token | `typing.Optional[typing.Callable[[], typing.Awaitable[str]]]` | `None` | Async callable that returns a bearer token. Use when token acquisition involves async I/O (e.g., async token refresh). | | timeout | `typing.Optional[float]` | `60` | Request timeout in seconds. Defaults to 60 seconds. | | max_retries | `typing.Optional[int]` | `2` | Maximum number of retry attempts for failed requests. Defaults to 2. | | follow_redirects | `typing.Optional[bool]` | `True` | Whether to automatically follow HTTP redirects. | | httpx_client | `typing.Optional[httpx.AsyncClient]` | `None` | Custom `httpx.AsyncClient` instance for advanced async configuration. Must be `AsyncClient`, not `Client`. | | logging | `typing.Optional[typing.Union[LogConfig, Logger]]` | `None` | Logging configuration. Accepts a `LogConfig` dict or pre-configured `Logger` instance. | ### Returns `AsyncSpeechify` instance ### Raises | Error | Condition | |---|---| | `ApiError` | If `api_key` is `None` and `SPEECHIFY_API_KEY` environment variable is not set. | ### Example ```python import asyncio from speechify import AsyncSpeechify async def main(): client = AsyncSpeechify(api_key="your_api_key") # Use async methods response = await client.audio.speech( input="Hello world", voice_id="george", model="simba-english" ) # Stream audio asynchronously async for chunk in await client.audio.stream( accept="audio/mpeg", input="Hello world", voice_id="george" ): # Process audio chunk pass asyncio.run(main()) ``` ``` -------------------------------- ### Create Personal Voice - Python Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/reference.md Creates a new personal (cloned) voice for the user. Requires an audio sample, name, gender, and user consent. The consent must be a JSON string containing the full name and email of the consenting individual. ```python from speechify import Speechify from speechify.environment import SpeechifyEnvironment client = Speechify( api_key="", environment=SpeechifyEnvironment.DEFAULT, ) client.voices.create( sample="example_sample", avatar="example_avatar", name="name", gender="male", consent="consent", ) ``` -------------------------------- ### Advanced Configuration Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/MANIFEST.txt Details on advanced SDK configuration options, such as using a custom httpx client, proxy configuration, custom transport, debug logging, and accessing raw responses. ```APIDOC ## Advanced Configuration ### Description This section covers advanced configuration options for tailoring the SDK's behavior and integration. ### Usage Patterns Documented - Custom httpx client - Proxy configuration - Custom transport - Debug logging - Raw response access ``` -------------------------------- ### Async Token Refresh Configuration Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/README.md Shows how to configure the asynchronous client to refresh tokens automatically before each request using a provided async function. ```python async def get_token(): # Refresh token via async API return "new_token" client = AsyncSpeechify( api_key="initial_key", async_token=get_token # Called before each request ) ``` -------------------------------- ### Accessing Raw HTTP Responses (Sync and Async) Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/README.md Illustrates how to retrieve raw HTTP responses, including status codes, headers, and data, for both synchronous and asynchronous operations. ```python # Synchronous raw_response = client.audio.with_raw_response.speech( input="...", voice_id="..." ) print(f"Status: {raw_response.status_code}") print(f"Headers: {raw_response.headers}") print(f"Data: {raw_response.data}") # GetSpeechResponse object # Asynchronous raw_response = await client.audio.with_raw_response.speech(...) ``` -------------------------------- ### Create Voice Asynchronously Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/_autodocs/api-reference/voices-client.md Creates a new custom voice asynchronously. Requires a voice sample file and consent details. Ensure the sample file is in a compatible format (e.g., WAV). ```python import asyncio import json from speechify import AsyncSpeechify async def main(): client = AsyncSpeechify(api_key="your_api_key") consent_data = { "fullName": "Jane Doe", "email": "jane@example.com" } created_voice = await client.voices.create( name="My Async Voice", gender="female", sample=open("voice_sample.wav", "rb"), consent=json.dumps(consent_data), locale="en-US" ) print(f"Voice created: {created_voice.id}") asyncio.run(main()) ``` -------------------------------- ### Download Personal Voice Sample - Python Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/reference.md Downloads an audio sample of a personal (cloned) voice. The ID of the voice for which to download the sample must be provided. ```python from speechify import Speechify from speechify.environment import SpeechifyEnvironment client = Speechify( api_key="", environment=SpeechifyEnvironment.DEFAULT, ) client.voices.download_sample( id="id", ) ``` -------------------------------- ### Run Test Suite Source: https://github.com/speechifyinc/speechify-api-sdk-python/blob/master/CONTRIBUTING.md Executes the project's test suite using Pytest. ```bash poetry run pytest ```