File size: 2,172 Bytes
31572a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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"}