import os import gdown from fastapi import FastAPI app = FastAPI() def download_weights(): # Create necessary directories if they don't exist os.makedirs("/tmp/.cache/gdown", exist_ok=True) os.makedirs("/tmp/weights/icon_caption_florence", exist_ok=True) os.makedirs("/tmp/weights/icon_detect", exist_ok=True) # Set gdown's cache directory to a writable location os.environ["GDOWN_CACHE"] = "/tmp/.cache/gdown" # Correct file mapping with Drive file IDs and their corresponding local paths files_to_download = { "1hUCqZ3X8mcM-KcwWFjcsFg7PA0hUvE3k": "/tmp/weights/icon_caption_florence/model.safetensors", "1p-Y7rd0FfjNnv_jewCi7ZjXH3T-qtyAa": "/tmp/weights/icon_detect/best.pt" } for file_id, output_path in files_to_download.items(): if not os.path.exists(output_path): print(f"Downloading {output_path}...") url = f"https://drive.google.com/uc?id={file_id}" try: gdown.download(url, output_path, quiet=False) print(f"Downloaded {output_path}") except Exception as e: print(f"Failed to download {output_path}: {e}") else: print(f"File {output_path} already exists, skipping download") @app.on_event("startup") def startup_event(): print("FastAPI app is starting, checking and downloading weights if necessary...") download_weights() @app.get("/") def root(): return {"message": "FastAPI app is running and weights are ready!"}