Spaces:
Running
Running
""" | |
Utilities for persistent storage in Hugging Face Spaces. | |
""" | |
import os | |
from pathlib import Path | |
from typing import Optional | |
def get_persistent_data_dir() -> Optional[Path]: | |
"""Get the persistent data directory if available. | |
Returns: | |
Path to persistent storage directory if available, None otherwise. | |
""" | |
if os.path.isdir("/data"): | |
data_dir = Path("/data/app_data") | |
data_dir.mkdir(exist_ok=True) | |
return data_dir | |
return None | |
def get_cache_dir() -> Path: | |
"""Get the appropriate cache directory (persistent if available, temp otherwise). | |
Returns: | |
Path to cache directory. | |
""" | |
if os.path.isdir("/data"): | |
cache_dir = Path("/data/.cache") | |
cache_dir.mkdir(exist_ok=True) | |
return cache_dir | |
else: | |
# Fallback to temp directory | |
import tempfile | |
return Path(tempfile.gettempdir()) / "app_cache" | |
def save_uploaded_file(uploaded_file, filename: str) -> Optional[Path]: | |
"""Save an uploaded file to persistent storage. | |
Args: | |
uploaded_file: Gradio uploaded file object | |
filename: Name to save the file as | |
Returns: | |
Path to saved file if successful, None otherwise. | |
""" | |
persistent_dir = get_persistent_data_dir() | |
if persistent_dir and uploaded_file: | |
save_path = persistent_dir / filename | |
save_path.parent.mkdir(parents=True, exist_ok=True) | |
# Copy the uploaded file to persistent storage | |
import shutil | |
shutil.copy2(uploaded_file, save_path) | |
return save_path | |
return None | |
def is_persistent_storage_available() -> bool: | |
"""Check if persistent storage is available. | |
Returns: | |
True if persistent storage is available, False otherwise. | |
""" | |
return os.path.isdir("/data") | |
def get_persistent_results_dir() -> Optional[Path]: | |
"""Get the persistent results directory for storing pipeline results. | |
Returns: | |
Path to persistent results directory if available, None otherwise. | |
""" | |
persistent_dir = get_persistent_data_dir() | |
if persistent_dir: | |
results_dir = persistent_dir / "results" | |
results_dir.mkdir(exist_ok=True) | |
return results_dir | |
return None |