suraj-ml-projects's picture
Create utils.py
8a619f6 verified
Raw History Blame Contribute Delete
1.55 kB
import os
import shutil
import time
import glob
from config import Config
def setup_temp_folders():
"""Create temporary directories for the session."""
if not os.path.exists(Config.TEMP_DIR):
os.makedirs(Config.TEMP_DIR)
def cleanup_old_files(max_age_seconds=3600):
"""
Deletes files older than 1 hour to prevent Hugging Face storage from filling up.
This is critical for privacy and system stability.
"""
now = time.time()
for f in glob.glob(os.path.join(Config.TEMP_DIR, "*")):
if os.stat(f).st_mtime < now - max_age_seconds:
try:
if os.path.isfile(f):
os.remove(f)
else:
shutil.rmtree(f)
except Exception as e:
print(f"Error cleaning up {f}: {e}")
def format_timestamp(seconds):
"""Converts seconds to HH:MM:SS format."""
return time.strftime('%H:%M:%S', time.gmtime(seconds))
def save_uploaded_file(file_obj):
"""Saves the Gradio upload to a temporary path."""
setup_temp_folders()
file_path = os.path.join(Config.TEMP_DIR, f"video_{int(time.time())}.mp4")
shutil.copy(file_obj.name, file_path)
return file_path
class SessionManager:
"""Handles the temporary session memory state."""
@staticmethod
def clear_session():
# Clear the temporary directory
if os.path.exists(Config.TEMP_DIR):
shutil.rmtree(Config.TEMP_DIR)
setup_temp_folders()
# Note: In app.py, you would also clear the FAISS index