File size: 2,014 Bytes
f7e620e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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