Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, HTTPException
|
2 |
+
from pydantic import BaseModel
|
3 |
+
import numpy as np
|
4 |
+
from huggingface_hub import hf_hub_download, HfApi
|
5 |
+
import joblib
|
6 |
+
import os
|
7 |
+
from datetime import datetime, timedelta
|
8 |
+
|
9 |
+
app = FastAPI()
|
10 |
+
|
11 |
+
REPO_ID = "GodfreyOwino/NPK_needs_mode2"
|
12 |
+
FILENAME = "npk_needs_model.joblib"
|
13 |
+
UPDATE_FREQUENCY = timedelta(days=1)
|
14 |
+
|
15 |
+
def get_latest_model():
|
16 |
+
try:
|
17 |
+
api = HfApi()
|
18 |
+
remote_info = api.model_info(repo_id=REPO_ID)
|
19 |
+
remote_mtime = remote_info.lastModified
|
20 |
+
|
21 |
+
cached_path = hf_hub_download(repo_id=REPO_ID, filename=FILENAME)
|
22 |
+
|
23 |
+
if os.path.exists(cached_path):
|
24 |
+
local_mtime = datetime.fromtimestamp(os.path.getmtime(cached_path))
|
25 |
+
|
26 |
+
if datetime.now() - local_mtime < UPDATE_FREQUENCY:
|
27 |
+
print("Using cached model (checked recently)")
|
28 |
+
return joblib.load(cached_path)
|
29 |
+
|
30 |
+
if remote_mtime > local_mtime:
|
31 |
+
print("Downloading updated model")
|
32 |
+
cached_path = hf_hub_download(repo_id=REPO_ID, filename=FILENAME, force_download=True)
|
33 |
+
else:
|
34 |
+
print("Cached model is up-to-date")
|
35 |
+
else:
|
36 |
+
print("Downloading model for the first time")
|
37 |
+
cached_path = hf_hub_download(repo_id=REPO_ID, filename=FILENAME)
|
38 |
+
|
39 |
+
except Exception as e:
|
40 |
+
print(f"Error checking/downloading model: {e}")
|
41 |
+
print(f"Error type: {type(e)}")
|
42 |
+
print(f"Error details: {str(e)}")
|
43 |
+
raise HTTPException(status_code=500, detail="Unable to download or find the model.")
|
44 |
+
|
45 |
+
return joblib.load(cached_path)
|
46 |
+
|
47 |
+
model = get_latest_model()
|
48 |
+
print("Model loaded successfully")
|
49 |
+
|
50 |
+
class InputData(BaseModel):
|
51 |
+
features: list[float]
|
52 |
+
|
53 |
+
@app.post("/predict")
|
54 |
+
async def predict(data: InputData):
|
55 |
+
try:
|
56 |
+
input_data = np.array(data.features).reshape(1, -1)
|
57 |
+
prediction = model.predict(input_data)
|
58 |
+
return {"prediction": prediction.tolist()}
|
59 |
+
except Exception as e:
|
60 |
+
raise HTTPException(status_code=500, detail=f"Prediction error: {str(e)}")
|
61 |
+
|
62 |
+
@app.get("/")
|
63 |
+
async def root():
|
64 |
+
return {"message": "NPK Needs Prediction Model API"}
|