|
import requests |
|
from pydub import AudioSegment |
|
import io |
|
|
|
|
|
VOICE_MAPPING = { |
|
|
|
"seraphina": "XB0fDUnXU5powFXDhCwa", |
|
"isabella": "LcfcDJNUP1GQjkzn1xUU", |
|
"astrid": "jsCqWAovK2LkecY7zXl4", |
|
"lila": "jBpfuIE2acCO8z3wKNLl", |
|
"elara": "z9fAnlkpzviPz146aGWa", |
|
"evelyn": "oWAxZDx7w5VEj9dCyTzz", |
|
|
|
|
|
"sebastian": "onwK4e9ZLuTAKqWW03F9", |
|
"finnian": "N2lVS1w4EtoT3dr4eOWO", |
|
"theodore": "IKne3meq5aSn9XLyUdCD", |
|
"magnus": "2EiwWnXFnvU5JabPnv8n", |
|
"oliver": "CYw3kZ02Hs0563khs1Fj", |
|
"liam": "g5CIjZEefAph4nQFvHAz", |
|
"arthur": "SOYHLrjzK2X1ezoPC6cr", |
|
"elliot": "ZQe5CZNOzWyzPSCn5a3c", |
|
"nathaniel": "bVMeCyTHy58xNoL34h3p", |
|
|
|
|
|
"rowan": "D38z5RcWu1voky8WS1ja", |
|
"avery": "zcAOhNBS3c14rBihAFp1", |
|
} |
|
|
|
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] |
|
|
|
last_punctuation = max(chunk.rfind("."), chunk.rfind(","), chunk.rfind(" ")) |
|
if last_punctuation == -1: |
|
|
|
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"): |
|
|
|
voice_id = VOICE_MAPPING.get(voice.lower(), voice) |
|
|
|
|
|
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 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 |
|
|
|
combined_audio_bytes = io.BytesIO() |
|
combined_audio.export(combined_audio_bytes, format="mp3") |
|
combined_audio_bytes.seek(0) |
|
return combined_audio_bytes.read() |
|
else: |
|
|
|
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 Exception(f"Failed to generate speech: {response.status_code}") |
|
return response.content |