from fastapi import FastAPI, HTTPException from pydantic import BaseModel import numpy as np from huggingface_hub import hf_hub_download, HfApi import joblib import os from datetime import datetime, timedelta app = FastAPI() REPO_ID = "GodfreyOwino/NPK_needs_mode2" FILENAME = "npk_needs_model.joblib" UPDATE_FREQUENCY = timedelta(days=1) def get_latest_model(): try: api = HfApi() remote_info = api.model_info(repo_id=REPO_ID) remote_mtime = remote_info.lastModified cached_path = hf_hub_download(repo_id=REPO_ID, filename=FILENAME) if os.path.exists(cached_path): local_mtime = datetime.fromtimestamp(os.path.getmtime(cached_path)) if datetime.now() - local_mtime < UPDATE_FREQUENCY: print("Using cached model (checked recently)") return joblib.load(cached_path) if remote_mtime > local_mtime: print("Downloading updated model") cached_path = hf_hub_download(repo_id=REPO_ID, filename=FILENAME, force_download=True) else: print("Cached model is up-to-date") else: print("Downloading model for the first time") cached_path = hf_hub_download(repo_id=REPO_ID, filename=FILENAME) except Exception as e: print(f"Error checking/downloading model: {e}") print(f"Error type: {type(e)}") print(f"Error details: {str(e)}") raise HTTPException(status_code=500, detail="Unable to download or find the model.") return joblib.load(cached_path) model = get_latest_model() print("Model loaded successfully") class InputData(BaseModel): features: list[float] @app.post("/predict") async def predict(data: InputData): try: input_data = np.array(data.features).reshape(1, -1) prediction = model.predict(input_data) return {"prediction": prediction.tolist()} except Exception as e: raise HTTPException(status_code=500, detail=f"Prediction error: {str(e)}") @app.get("/") async def root(): return {"message": "NPK Needs Prediction Model API"}