File size: 906 Bytes
b515e8c
 
bd7030e
b515e8c
 
 
bd7030e
 
b515e8c
 
bd7030e
 
 
 
 
 
 
 
 
 
 
b515e8c
 
 
 
 
 
 
 
bd7030e
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
from typing import Optional
from fastapi import HTTPException
import logging
import io
from gtts import gTTS

# Configure logging
logger = logging.getLogger(__name__)

def text_to_speech(text: str, language: str = "en", slow: bool = False) -> bytes:
    """
    Convert text to speech using gTTS (Google Text-to-Speech)
    
    Args:
        text (str): The text to convert to speech
        language (str): Language code (default: "en")
        slow (bool): Whether to speak slowly (default: False)
    
    Returns:
        bytes: MP3 audio data
    """
    try:
        tts = gTTS(text=text, lang=language, slow=slow)
        mp3_fp = io.BytesIO()
        tts.write_to_fp(mp3_fp)
        mp3_fp.seek(0)
        return mp3_fp.read()
    except Exception as e:
        logger.error(f"Error in text-to-speech conversion: {e}")
        raise HTTPException(status_code=500, detail="Error generating speech")