waste-classification-app / model_fetch.py
ioget's picture
Clean deployment for Hugging Face Spaces - no binary files
16dd7c8
"""Download the Keras model from Google Drive when it is not already on disk.
Public sharing link:
https://drive.google.com/file/d/1VHHRMPoqpTOy53s2mkYwrBp2LOYDbUWL/view
Override file id with env GDRIVE_MODEL_FILE_ID if you mirror the file elsewhere.
"""
from __future__ import annotations
import os
import sys
DEFAULT_DRIVE_FILE_ID = "1VHHRMPoqpTOy53s2mkYwrBp2LOYDbUWL"
def ensure_model_file(model_path: str, *, drive_file_id: str | None = None) -> bool:
"""Return True if ``model_path`` exists after a possible Drive download."""
if os.path.isfile(model_path):
return True
directory = os.path.dirname(model_path)
if directory:
os.makedirs(directory, exist_ok=True)
fid = (drive_file_id or os.environ.get("GDRIVE_MODEL_FILE_ID") or DEFAULT_DRIVE_FILE_ID).strip()
if not fid:
return False
try:
import gdown
except ImportError:
print("Install gdown to fetch the model from Google Drive.", file=sys.stderr)
return False
url = f"https://drive.google.com/uc?id={fid}"
try:
gdown.download(url, model_path, quiet=False)
except Exception as exc:
print(f"Google Drive download failed: {exc}", file=sys.stderr)
return False
return os.path.isfile(model_path)