File size: 2,772 Bytes
5669b22 | 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 | import abc
import os
import asyncio
from loguru import logger
class TTSInterface(metaclass=abc.ABCMeta):
async def async_generate_audio(self, text: str, file_name_no_ext=None) -> str:
"""
Asynchronously generate speech audio file using TTS.
By default, this runs the synchronous generate_audio in a coroutine.
Subclasses can override this method to provide true async implementation.
text: str
the text to speak
file_name_no_ext (optional and deprecated): str
name of the file without file extension
Returns:
str: the path to the generated audio file
"""
return await asyncio.to_thread(self.generate_audio, text, file_name_no_ext)
@abc.abstractmethod
def generate_audio(self, text: str, file_name_no_ext=None) -> str:
"""
Generate speech audio file using TTS.
text: str
the text to speak
file_name_no_ext (optional and deprecated): str
name of the file without file extension
Returns:
str: the path to the generated audio file
"""
raise NotImplementedError
def remove_file(self, filepath: str, verbose: bool = True) -> None:
"""
Remove a file from the file system.
This is a separate method instead of a part of the `play_audio_file_local()` because `play_audio_file_local()` is not the only way to play audio files. This method will be used to remove the audio file after it has been played.
Parameters:
filepath (str): The path to the file to remove.
verbose (bool): If True, print messages to the console.
"""
if not os.path.exists(filepath):
logger.warning(f"File {filepath} does not exist")
return
try:
logger.debug(f"Removing file {filepath}") if verbose else None
os.remove(filepath)
except Exception as e:
logger.error(f"Failed to remove file {filepath}: {e}")
def generate_cache_file_name(self, file_name_no_ext=None, file_extension="wav"):
"""
Generate a cross-platform cache file name.
file_name_no_ext: str
name of the file without extension
file_extension: str
file extension
Returns:
str: the path to the generated cache file
"""
cache_dir = "cache"
if not os.path.exists(cache_dir):
os.makedirs(cache_dir)
if file_name_no_ext is None:
file_name_no_ext = "temp"
file_name = f"{file_name_no_ext}.{file_extension}"
return os.path.join(cache_dir, file_name)
|