coderprem commited on
Commit
930e37b
·
verified ·
1 Parent(s): 03ee8e8

Create handler.py

Browse files
Files changed (1) hide show
  1. handler.py +33 -0
handler.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Any
2
+ import numpy as np
3
+ import joblib
4
+
5
+ class EndpointHandler():
6
+ def __init__(self, path: str = ""):
7
+ """
8
+ Initialize the model and encoder when the endpoint starts.
9
+ """
10
+ self.model = joblib.load(f"{path}/soil.pkl")
11
+ self.label_encoder = joblib.load(f"{path}/label_encoder.pkl")
12
+
13
+ def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
14
+ """
15
+ Perform prediction using the trained model.
16
+ Expects input data in the format:
17
+ {
18
+ "inputs": [N, P, K, temperature, humidity, ph, rainfall]
19
+ }
20
+ Returns:
21
+ {
22
+ "crop": predicted_crop_name
23
+ }
24
+ """
25
+ inputs = data.get("inputs")
26
+ if inputs is None:
27
+ return {"error": "No input data provided."}
28
+
29
+ inputs = np.array(inputs).reshape(1, -1)
30
+ prediction = self.model.predict(inputs)
31
+ crop = self.label_encoder.inverse_transform(prediction)
32
+
33
+ return {"crop": crop[0]}