CoolFace
Apppublic

MOSES3377/ai-interview-app

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
tts_utils.py73 linesDownload Raw Back to root
1import os2from gtts import gTTS3import logging4from pydub import AudioSegment5 6# Configure logging7logging.basicConfig(level=logging.INFO)8 9CACHE_DIR = "tts_cache"10if not os.path.exists(CACHE_DIR):11    os.makedirs(CACHE_DIR)12    logging.info(f"Created TTS cache directory at: {CACHE_DIR}")13 14def speak_text_gtts(text: str) -> str:15    """16    Converts text to speech using gTTS, saves it as an MP3, and returns the file path.17    A simple hashing mechanism is used for caching.18 19    Args:20        text (str): The text to be converted to speech.21 22    Returns:23        str: The file path of the generated audio file. Returns None on failure.24    """25    try:26        # Create a simple, filename-safe hash of the text for caching27        filename = f"{hash(text)}.mp3"28        filepath = os.path.join(CACHE_DIR, filename)29 30        # If the file already exists in the cache, return its path31        if os.path.exists(filepath):32            logging.info(f"TTS audio found in cache: {filepath}")33            return filepath34        35        # Generate the audio file using gTTS36        tts = gTTS(text=text, lang='en', slow=False)37        tts.save(filepath)38        39        # Optional: Convert to a different format or bitrate if needed using pydub40        # For example, to ensure compatibility or reduce file size.41        # sound = AudioSegment.from_mp3(filepath)42        # sound.export(filepath, format="mp3", bitrate="128k")43 44        logging.info(f"TTS audio generated and saved to: {filepath}")45        return filepath46    except Exception as e:47        logging.error(f"gTTS failed to generate audio: {e}")48        return None49 50# --- Pluggable Architecture ---51# You can easily swap the TTS engine by changing this function call in app.py.52# For example, to use OpenAI's TTS or ElevenLabs, create a function like53# speak_text_openai(text) and call that instead.54 55# Example for OpenAI TTS (requires `openai` library):56# from openai import OpenAI57# client = OpenAI()58# def speak_text_openai(text: str) -> str:59#     filename = f"{hash(text)}.mp3"60#     filepath = os.path.join(CACHE_DIR, filename)61#     if os.path.exists(filepath):62#         return filepath63#     response = client.audio.speech.create(64#         model="tts-1",65#         voice="alloy",66#         input=text67#     )68#     response.stream_to_file(filepath)69#     return filepath70 71# Set the default TTS function to use72speak_text = speak_text_gtts73