import requests from pydub import AudioSegment import io # Voice mapping dictionary VOICE_MAPPING = { # Female Voices "seraphina": "XB0fDUnXU5powFXDhCwa", # Elegant and sophisticated "isabella": "LcfcDJNUP1GQjkzn1xUU", # Classic and timeless "astrid": "jsCqWAovK2LkecY7zXl4", # Strong and Nordic-inspired "lila": "jBpfuIE2acCO8z3wKNLl", # Playful and charming "elara": "z9fAnlkpzviPz146aGWa", # Mystical and enchanting "evelyn": "oWAxZDx7w5VEj9dCyTzz", # Graceful and refined # Male Voices "sebastian": "onwK4e9ZLuTAKqWW03F9", # Strong and authoritative "finnian": "N2lVS1w4EtoT3dr4eOWO", # Rugged and adventurous "theodore": "IKne3meq5aSn9XLyUdCD", # Warm and friendly "magnus": "2EiwWnXFnvU5JabPnv8n", # Bold and powerful "oliver": "CYw3kZ02Hs0563khs1Fj", # Reliable and approachable "liam": "g5CIjZEefAph4nQFvHAz", # Modern and confident "arthur": "SOYHLrjzK2X1ezoPC6cr", # Classic and noble "elliot": "ZQe5CZNOzWyzPSCn5a3c", # Sophisticated and calm "nathaniel": "bVMeCyTHy58xNoL34h3p", # Wise and thoughtful # Neutral Voices "rowan": "D38z5RcWu1voky8WS1ja", # Unisex, nature-inspired "avery": "zcAOhNBS3c14rBihAFp1", # Unisex, modern and versatile } def split_text_into_chunks(text, max_length=490): """Split text into chunks of max_length, ensuring chunks end with a full stop, comma, or word.""" chunks = [] while len(text) > max_length: chunk = text[:max_length] # Find the last occurrence of a full stop, comma, or space within the chunk last_punctuation = max(chunk.rfind("."), chunk.rfind(","), chunk.rfind(" ")) if last_punctuation == -1: # If no punctuation is found, force split at max_length last_punctuation = max_length chunks.append(chunk[:last_punctuation + 1].strip()) text = text[last_punctuation + 1:].strip() chunks.append(text) return chunks def generate_speech(voice, input_text, model="eleven_multilingual_v2"): # Convert voice name to voice ID if necessary voice_id = VOICE_MAPPING.get(voice.lower(), voice) # Split the input text into chunks if it exceeds 500 characters if len(input_text) > 500: chunks = split_text_into_chunks(input_text) combined_audio = AudioSegment.empty() for chunk in chunks: url = f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}?allow_unauthenticated=1" headers = { "Content-Type": "application/json" } data = { "text": chunk, "model_id": "eleven_multilingual_v2", } response = requests.post(url, json=data, headers=headers) if response.status_code != 200: # Raise an exception if the API response is not 200 raise Exception(f"Failed to generate speech for chunk: {response.status_code}, {response.text}") audio_segment = AudioSegment.from_file(io.BytesIO(response.content), format="mp3") combined_audio += audio_segment # Export the combined audio to a BytesIO object combined_audio_bytes = io.BytesIO() combined_audio.export(combined_audio_bytes, format="mp3") combined_audio_bytes.seek(0) return combined_audio_bytes.read() else: # If the input text is less than or equal to 500 characters, process it directly url = f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}?allow_unauthenticated=1" headers = { "Content-Type": "application/json" } data = { "text": input_text, "model_id": "eleven_multilingual_v2", } response = requests.post(url, json=data, headers=headers) if response.status_code != 200: # Raise an exception if the API response is not 200 raise Exception(f"Failed to generate speech: {response.status_code}") return response.content