File size: 4,060 Bytes
fd73412
d4cb7a1
 
fd73412
 
 
0511107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd73412
 
d4cb7a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd73412
 
 
 
d4cb7a1
 
 
 
 
 
 
 
 
 
 
52832fd
d4cb7a1
 
de2353d
 
 
 
 
d4cb7a1
 
 
 
 
fd73412
d4cb7a1
 
 
 
 
 
 
52832fd
d4cb7a1
 
de2353d
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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