File size: 9,106 Bytes
3f2461c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
import discord
from discord.ext import commands
import os
import re
import time
import requests
import pathlib
import tempfile
import random
from io import BytesIO

class FailedToGenerateResponseError(Exception):
    pass

class OpenAIFMTTS:
    headers = {
        "accept": "*/*",
        "accept-language": "en-US,en;q=0.9",
        "cache-control": "no-cache",
        "pragma": "no-cache",
        "sec-fetch-dest": "audio",
        "sec-fetch-mode": "no-cors",
        "sec-fetch-site": "same-origin",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
        "referer": "https://www.openai.fm"
    }

    SUPPORTED_MODELS = [
        "gpt-4o-mini-tts",
        "tts-1",
        "tts-1-hd"
    ]

    SUPPORTED_VOICES = [
        "alloy",
        "ash",
        "ballad",
        "coral",
        "echo",
        "fable",
        "nova",
        "onyx",
        "sage",
        "shimmer"
    ]

    voice_mapping = {
        "alloy": "alloy",
        "ash": "ash",
        "ballad": "ballad",
        "coral": "coral",
        "echo": "echo",
        "fable": "fable",
        "nova": "nova",
        "onyx": "onyx",
        "sage": "sage",
        "shimmer": "shimmer"
    }

    def __init__(self, timeout: int = 20, proxies: dict = None):
        self.api_url = "https://www.openai.fm/api/generate"
        self.session = requests.Session()
        self.session.headers.update(self.headers)
        if proxies:
            self.session.proxies.update(proxies)
        self.timeout = timeout
        self.temp_dir = tempfile.gettempdir()
        self.SUPPORTED_FORMATS = ["mp3", "opus", "aac", "flac", "wav", "pcm"]

    def validate_model(self, model: str) -> str:
        if model not in self.SUPPORTED_MODELS:
            raise ValueError(f"Unsupported model: {model}. Supported models: {self.SUPPORTED_MODELS}")
        return model

    def validate_voice(self, voice: str) -> str:
        if voice not in self.SUPPORTED_VOICES:
            raise ValueError(f"Unsupported voice: {voice}. Supported voices: {self.SUPPORTED_VOICES}")
        return voice

    def validate_format(self, response_format: str) -> str:
        if response_format not in self.SUPPORTED_FORMATS:
            raise ValueError(f"Unsupported format: {response_format}. Supported formats: {self.SUPPORTED_FORMATS}")
        return response_format

    def tts(self, text: str, model: str = "gpt-4o-mini-tts", voice: str = "coral", response_format: str = "mp3", instructions: str = None, verbose: bool = True) -> str:
        if not text or not isinstance(text, str):
            raise ValueError("Input text must be a non-empty string")
        if len(text) > 10000:
            raise ValueError("Input text exceeds maximum allowed length of 10,000 characters")

        model = self.validate_model(model)
        voice = self.validate_voice(voice)
        response_format = self.validate_format(response_format)

        voice_id = self.voice_mapping.get(voice, voice)

        if instructions is None:
            instructions = "Speak in a cheerful and positive tone."

        file_extension = f".{response_format}" if response_format != "pcm" else ".wav"
        with tempfile.NamedTemporaryFile(suffix=file_extension, dir=self.temp_dir, delete=False) as temp_file:
            filename = pathlib.Path(temp_file.name)

        params = {
            "input": text,
            "prompt": instructions,
            "voice": voice_id,
            "model": model,
            "response_format": response_format
        }

        try:
            response = self.session.get(
                self.api_url,
                params=params,
                timeout=self.timeout
            )
            response.raise_for_status()

            if not response.content:
                raise FailedToGenerateResponseError("Empty response from API")

            with open(filename, "wb") as f:
                f.write(response.content)

            if verbose:
                print(f"[debug] Speech generated successfully")
                print(f"[debug] Model: {model}")
                print(f"[debug] Voice: {voice}")
                print(f"[debug] Format: {response_format}")
                print(f"[debug] Audio saved to {filename}")

            return filename.as_posix()

        except requests.exceptions.RequestException as e:
            if verbose:
                print(f"[debug] Failed to generate speech: {e}")
            raise FailedToGenerateResponseError(f"Failed to generate speech: {e}")
        except Exception as e:
            if verbose:
                print(f"[debug] Unexpected error: {e}")
            raise FailedToGenerateResponseError(f"Unexpected error during speech generation: {e}")

    def create_speech(self, input: str, model: str = "gpt-4o-mini-tts", voice: str = "coral", response_format: str = "mp3", instructions: str = None, verbose: bool = False) -> str:
        return self.tts(text=input, model=model, voice=voice, response_format=response_format, instructions=instructions, verbose=verbose)

    def with_streaming_response(self):
        return StreamingResponseContextManager(self)


class StreamingResponseContextManager:
    def __init__(self, tts_provider: OpenAIFMTTS):
        self.tts_provider = tts_provider
        self.audio_file = None

    def create(self, input: str, model: str = "gpt-4o-mini-tts", voice: str = "coral", response_format: str = "mp3", instructions: str = None):
        self.audio_file = self.tts_provider.create_speech(input=input, model=model, voice=voice, response_format=response_format, instructions=instructions)
        return StreamingResponse(self.audio_file)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        pass


class StreamingResponse:
    def __init__(self, audio_file: str):
        self.audio_file = audio_file

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        pass

    def stream_to_file(self, file_path: str, chunk_size: int = 1024):
        import shutil
        shutil.copy2(self.audio_file, file_path)

    def iter_bytes(self, chunk_size: int = 1024):
        with open(self.audio_file, 'rb') as f:
            while chunk := f.read(chunk_size):
                yield chunk

intents = discord.Intents.default()
intents.message_content = True
intents.members = True

bot = commands.Bot(command_prefix='!', intents=intents)
tts_provider = OpenAIFMTTS()

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name} ({bot.user.id})')
    print('------')

@bot.command(name='tts')
async def text_to_speech(ctx, *, text: str = None):
    try:
        if not text:
            await ctx.send("Please provide text to convert to speech. Usage: `!tts [text]` or `!tts [text] --voice [voice]`")
            return

        voice = "coral"
        supported_voices = ["alloy", "ash", "ballad", "coral", "echo", "fable", "nova", "onyx", "sage", "shimmer"]

        voice_match_end = re.search(r'\s+--voice\s+(\w+)$', text)
        voice_match_start = re.search(r'^--voice\s+(\w+)\s+', text)

        if voice_match_end:
            requested_voice = voice_match_end.group(1).lower()
            text = re.sub(r'\s+--voice\s+\w+$', '', text).strip()
        elif voice_match_start:
            requested_voice = voice_match_start.group(1).lower()
            text = re.sub(r'^--voice\s+\w+\s+', '', text).strip()
        else:
            requested_voice = None

        if requested_voice:
            if requested_voice in supported_voices:
                voice = requested_voice
            else:
                await ctx.send(f"❌ Invalid voice: `{requested_voice}`")
                return

        if not text.strip():
            await ctx.send("Please provide text to convert to speech. Usage: `!tts [text]` or `!tts [text] --voice [voice]`")
            return

        if len(text) > 1000:
            await ctx.send("❌ Text is too long. Please keep it under 1000 characters.")
            return

        processing_msg = await ctx.send("🎵 Generating speech...")

        audio_file = tts_provider.create_speech(
            input=text,
            voice=voice,
            response_format="mp3",
            instructions="Speak clearly and naturally."
        )

        await processing_msg.delete()

        await ctx.send(
            content=f"🎵 TTS generated with voice: **{voice}**",
            file=discord.File(audio_file, filename=f"tts_{voice}.mp3")
        )

        os.remove(audio_file)

    except FailedToGenerateResponseError as e:
        await ctx.send(f"❌ Failed to generate speech: {str(e)}")
    except Exception as e:
        await ctx.send(f"❌ An error occurred: {str(e)}")
        print(f"TTS Error: {e}")

@bot.event
async def on_message(message):
    if message.author == bot.user:
        return
    await bot.process_commands(message)

TOKEN = os.getenv("DISCORD_BOT_TOKEN")

if TOKEN:
    bot.run(TOKEN)
else:
    print("Error: No bot token provided!")