CoolFace
Apppublic

HumeAI/expressive-tts-arena

sourceHugging Facemitupdated 11mo agoView on Hugging Face
68likes
utils.py104 linesDownload Raw Back to common
1# Standard Library Imports2import base643import os4import time5from pathlib import Path6 7# Local Application Imports8from .config import Config, logger9 10 11def _delete_files_older_than(directory: Path, minutes: int = 30) -> None:12    """13    Delete all files in the specified directory that are older than a given number of minutes.14 15    This function checks each file in the given directory and removes it if its last modification16    time is older than the specified threshold. By default, the threshold is set to 30 minutes.17 18    Args:19        directory (str): The path to the directory where files will be checked and possibly deleted.20        minutes (int, optional): The age threshold in minutes. Files older than this will be deleted.21                                 Defaults to 30 minutes.22 23    Returns: None24    """25    # Get the current time in seconds since the epoch.26    now = time.time()27    # Convert the minutes threshold to seconds.28    cutoff = now - (minutes * 60)29    dir_path = Path(directory)30 31    # Iterate over all files in the directory.32    for file_path in dir_path.iterdir():33        if file_path.is_file():34            file_mod_time = file_path.stat().st_mtime35            # If the file's modification time is older than the cutoff, delete it.36            if file_mod_time < cutoff:37                try:38                    file_path.unlink()39                    logger.info(f"Deleted: {file_path}")40                except Exception as e:41                    logger.exception(f"Error deleting {file_path}: {e}")42 43def save_base64_audio_to_file(base64_audio: str, filename: str, config: Config) -> str:44    """45    Decode a base64-encoded audio string and write the resulting binary data to a file46    within the preconfigured AUDIO_DIR directory. Prior to writing the bytes to an audio47    file, all files within the directory that are more than 30 minutes old are deleted.48    This function verifies the file was created, logs both the absolute and relative49    file paths, and returns a path relative to the current working directory50    (as required by Gradio for serving static files).51 52    Args:53        base64_audio (str): The base64-encoded string representing the audio data.54        filename (str): The name of the file (including extension, e.g.,55                        'b4a335da-9786-483a-b0a5-37e6e4ad5fd1.mp3') where the decoded56                        audio will be saved.57 58    Returns:59        str: The relative file path to the saved audio file.60 61    Raises:62        FileNotFoundError: If the audio file was not created.63    """64 65    audio_bytes = base64.b64decode(base64_audio)66    file_path = Path(config.audio_dir) / filename67    num_minutes = 3068 69    _delete_files_older_than(config.audio_dir, num_minutes)70 71    # Write the binary audio data to the file.72    with file_path.open("wb") as audio_file:73        audio_file.write(audio_bytes)74 75    # Verify that the file was created.76    if not file_path.exists():77        raise FileNotFoundError(f"Audio file was not created at {file_path}")78 79    # Compute a relative path for Gradio to serve (relative to the current working directory).80    relative_path = file_path.relative_to(Path.cwd())81    logger.debug(f"Audio file absolute path: {file_path}")82    logger.debug(f"Audio file relative path: {relative_path}")83 84    return str(relative_path)85 86def validate_env_var(var_name: str) -> str:87    """88    Validates that an environment variable is set and returns its value.89 90    Args:91        var_name (str): The name of the environment variable to validate.92 93    Returns:94        str: The value of the environment variable.95 96    Raises:97        ValueError: If the environment variable is not set.98    """99    value = os.environ.get(var_name, "")100    if not value:101        raise ValueError(f"{var_name} is not set. Please ensure it is defined in your environment variables.")102    return value103 104