elevenlabs / elevenlabs-python

The official Python API for ElevenLabs Text to Speech.
https://elevenlabs.io/docs/api-reference/getting-started
MIT License
2.12k stars 240 forks source link

Setting timeout #318

Closed Eichhof closed 2 months ago

Eichhof commented 2 months ago

Hello

I'm using the latest python library of ElevenLabs and I'm synthesizing speech as provided below. Is there a possibility to set a timeout (e.g. 5 seconds) after which the call aborts and throws an exception? In addition, what exceptions are thrown and should be caught?

import os
import uuid
from elevenlabs import VoiceSettings
from elevenlabs.client import ElevenLabs

ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY")
client = ElevenLabs(
    api_key=ELEVENLABS_API_KEY,
)

def text_to_speech_file(text: str) -> str:
    # Calling the text_to_speech conversion API with detailed parameters
    response = client.text_to_speech.convert(
        voice_id="pNInz6obpgDQGcFmaJgB", # Adam pre-made voice
        optimize_streaming_latency="0",
        output_format="mp3_22050_32",
        text=text,
        model_id="eleven_turbo_v2", # use the turbo model for low latency, for other languages use the `eleven_multilingual_v2`
        voice_settings=VoiceSettings(
            stability=0.0,
            similarity_boost=1.0,
            style=0.0,
            use_speaker_boost=True,
        ),
    )

    # uncomment the line below to play the audio back
    # play(response)

    # Generating a unique file name for the output MP3 file
    save_file_path = f"{uuid.uuid4()}.mp3"

    # Writing the audio to a file
    with open(save_file_path, "wb") as f:
        for chunk in response:
            if chunk:
                f.write(chunk)

    print(f"{save_file_path}: A new audio file was saved successfully!")

    # Return the path of the saved audio file
    return save_file_path
dsinghvi commented 2 months ago

@Eichhof -- absolutely, you can use RequestOptions to do this which is the final parameter on every endpoint.

client.text_to_speech.convert(..., request_options = {
  timeout_in_seconds=60,
})

Feel free to reopen the issue if that doesn't solve your problem!