Create handler.py
Browse files- handler.py +38 -0
handler.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import joblib
|
| 3 |
+
import numpy as np
|
| 4 |
+
from lightgbm import LGBMRegressor
|
| 5 |
+
|
| 6 |
+
# Load the model once when the endpoint starts
|
| 7 |
+
model = joblib.load("lgbm_model.joblib") # <-- Your saved model
|
| 8 |
+
|
| 9 |
+
def preprocess(inputs):
|
| 10 |
+
"""
|
| 11 |
+
Convert JSON input into the appropriate format for LightGBM model
|
| 12 |
+
inputs: dict or list of dicts
|
| 13 |
+
"""
|
| 14 |
+
# If input is a single dict, convert it to a list
|
| 15 |
+
if isinstance(inputs, dict):
|
| 16 |
+
inputs = [inputs]
|
| 17 |
+
|
| 18 |
+
# Convert to numpy array (feature order must match training!)
|
| 19 |
+
feature_order = sorted(inputs[0].keys())
|
| 20 |
+
X = np.array([[sample[f] for f in feature_order] for sample in inputs])
|
| 21 |
+
return X
|
| 22 |
+
|
| 23 |
+
def predict(inputs):
|
| 24 |
+
X = preprocess(inputs)
|
| 25 |
+
preds = model.predict(X)
|
| 26 |
+
# Return a list of predictions
|
| 27 |
+
return preds.tolist()
|
| 28 |
+
|
| 29 |
+
def handle(inputs):
|
| 30 |
+
"""
|
| 31 |
+
Function called by Hugging Face Inference Endpoint
|
| 32 |
+
"""
|
| 33 |
+
# If input is a JSON string
|
| 34 |
+
if isinstance(inputs, str):
|
| 35 |
+
inputs = json.loads(inputs)
|
| 36 |
+
|
| 37 |
+
preds = predict(inputs)
|
| 38 |
+
return {"predictions": preds}
|