Spaces:
Sleeping
Sleeping
Create text_to_speech.py
Browse files
application/utils/text_to_speech.py
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# application/utils/text_to_speech.py - NEW FILE
|
2 |
+
import asyncio
|
3 |
+
import edge_tts
|
4 |
+
from aiohttp import web # Import aiohttp
|
5 |
+
|
6 |
+
async def generate_tts(text: str) -> bytes:
|
7 |
+
"""
|
8 |
+
Generates speech from text using edge-tts and returns the audio as a byte stream.
|
9 |
+
"""
|
10 |
+
try:
|
11 |
+
communicate = edge_tts.Communicate(text, "en-US-GuyNeural") # Or any other preferred voice
|
12 |
+
return await communicate.stream()
|
13 |
+
|
14 |
+
except Exception as e:
|
15 |
+
print(f"Error in TTS generation: {e}")
|
16 |
+
return b"" # Return empty bytes on error
|
17 |
+
|
18 |
+
|
19 |
+
async def tts_handler(request: web.Request) -> web.Response:
|
20 |
+
"""
|
21 |
+
aiohttp handler for the /tts endpoint. This is the correct way to handle
|
22 |
+
streaming with aiohttp (and thus edge-tts).
|
23 |
+
"""
|
24 |
+
text = request.query.get('text')
|
25 |
+
if not text:
|
26 |
+
return web.Response(status=400, text="No text provided")
|
27 |
+
|
28 |
+
try:
|
29 |
+
response = web.StreamResponse()
|
30 |
+
response.content_type = 'audio/mpeg'
|
31 |
+
await response.prepare(request)
|
32 |
+
|
33 |
+
async for chunk in generate_tts(text):
|
34 |
+
await response.write(chunk)
|
35 |
+
|
36 |
+
await response.write_eof()
|
37 |
+
return response
|
38 |
+
except Exception as e:
|
39 |
+
print(f"Error in TTS handler: {e}")
|
40 |
+
return web.Response(status=500, text=str(e))
|