""" File utility functions for EmotionMirror application. """ import os import uuid import logging from typing import Set, Optional, Tuple # Configure logging logger = logging.getLogger(__name__) def allowed_file(filename: str, allowed_extensions: Set[str]) -> bool: """ Check if a file has an allowed extension. Args: filename: Name of the file to check allowed_extensions: Set of allowed extensions Returns: True if file extension is allowed, False otherwise """ if '.' not in filename: return False extension = filename.rsplit('.', 1)[1].lower() return extension in allowed_extensions def generate_unique_filename(filename: str) -> str: """ Generate a unique filename preserving the original extension. Args: filename: Original filename Returns: Unique filename with original extension """ if '.' not in filename: return f"{uuid.uuid4().hex}" extension = filename.rsplit('.', 1)[1].lower() return f"{uuid.uuid4().hex}.{extension}" def save_uploaded_file(uploaded_file, upload_dir: str) -> Tuple[bool, str, Optional[str]]: """ Save an uploaded file to the specified directory. Args: uploaded_file: File object from Streamlit upload_dir: Directory to save the file Returns: Tuple of (success, message, file_path) """ try: os.makedirs(upload_dir, exist_ok=True) # Generate unique filename unique_filename = generate_unique_filename(uploaded_file.name) file_path = os.path.join(upload_dir, unique_filename) # Save the file with open(file_path, "wb") as f: f.write(uploaded_file.getbuffer()) return True, f"File saved successfully as {unique_filename}", file_path except Exception as e: logger.error(f"Error saving file: {e}") return False, f"Error saving file: {str(e)}", None