sujoy0011 commited on
Commit
fbb633c
·
verified ·
1 Parent(s): c7d4cf5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -76
app.py CHANGED
@@ -1,76 +1,77 @@
1
- from fastapi import FastAPI, HTTPException
2
- from pydantic import BaseModel, Optional
3
- import pickle
4
- import numpy as np
5
- import pandas as pd
6
- import json
7
-
8
- app = FastAPI()
9
-
10
- # Load models
11
- with open("model_useing_Location_Seasion_Area.pkl", "rb") as f:
12
- location_model = pickle.load(f)
13
-
14
- with open("model_useing_npk.pkl", "rb") as f:
15
- npk_model = pickle.load(f)
16
-
17
- # Load unique values from the JSON file
18
- with open("unique_values.json", "r") as f:
19
- unique_values = json.load(f)
20
-
21
-
22
- class CropRequest(BaseModel):
23
- state: Optional[str] = None
24
- district: Optional[str] = None
25
- season: Optional[str] = None
26
- area: Optional[float] = None
27
- N: Optional[float] = None
28
- P: Optional[float] = None
29
- K: Optional[float] = None
30
- temperature: Optional[float] = None
31
- humidity: Optional[float] = None
32
- ph: Optional[float] = None
33
- rainfall: Optional[float] = None
34
-
35
-
36
- def get_top_recommendations(model, input_data, top_n=3):
37
- if hasattr(model, "predict_proba"):
38
- proba = model.predict_proba(input_data)
39
- top_indices = np.argsort(proba[0])[-top_n:][::-1]
40
- return [model.classes_[i] for i in top_indices]
41
- return model.predict(input_data).tolist()
42
-
43
-
44
- @app.post("/predict")
45
- def predict_crop(request: CropRequest):
46
- location_recommendations = []
47
- npk_recommendations = []
48
-
49
- if request.state and request.district and request.season and request.area:
50
- try:
51
- input_data = pd.DataFrame([[request.state, request.district, request.season, np.log1p(request.area)]],
52
- columns=['State_Name', 'District_Name', 'Season', 'Area'])
53
- location_recommendations = get_top_recommendations(location_model, input_data, top_n=3)
54
- except ValueError:
55
- pass # Handle invalid input
56
-
57
- if request.N is not None and request.P is not None and request.K is not None and request.temperature is not None \
58
- and request.humidity is not None and request.ph is not None and request.rainfall is not None:
59
- try:
60
- input_data = np.array([[request.N, request.P, request.K, request.temperature,
61
- request.humidity, request.ph, request.rainfall]])
62
- npk_recommendations = get_top_recommendations(npk_model, input_data, top_n=3)
63
- except ValueError:
64
- pass # Handle invalid input
65
-
66
- location_lower = {crop.lower(): crop for crop in location_recommendations}
67
- common_crops_lower = set(location_lower.keys()) & set(crop.lower() for crop in npk_recommendations)
68
- common_crops = [location_lower[crop] for crop in common_crops_lower]
69
-
70
- location_recommendations = [crop for crop in location_recommendations if crop.lower() not in common_crops_lower]
71
- npk_recommendations = [crop for crop in npk_recommendations if crop.lower() not in common_crops_lower]
72
-
73
- merged_crops = common_crops + npk_recommendations + location_recommendations
74
- final_recommendations = [crop.lower() for crop in merged_crops[:4]]
75
-
76
- return {"recommendations": final_recommendations if final_recommendations else []}
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from pydantic import BaseModel
3
+ from typing import Optional
4
+ import pickle
5
+ import numpy as np
6
+ import pandas as pd
7
+ import json
8
+
9
+ app = FastAPI()
10
+
11
+ # Load models
12
+ with open("model_useing_Location_Seasion_Area.pkl", "rb") as f:
13
+ location_model = pickle.load(f)
14
+
15
+ with open("model_useing_npk.pkl", "rb") as f:
16
+ npk_model = pickle.load(f)
17
+
18
+ # Load unique values from the JSON file
19
+ with open("unique_values.json", "r") as f:
20
+ unique_values = json.load(f)
21
+
22
+
23
+ class CropRequest(BaseModel):
24
+ state: Optional[str] = None
25
+ district: Optional[str] = None
26
+ season: Optional[str] = None
27
+ area: Optional[float] = None
28
+ N: Optional[float] = None
29
+ P: Optional[float] = None
30
+ K: Optional[float] = None
31
+ temperature: Optional[float] = None
32
+ humidity: Optional[float] = None
33
+ ph: Optional[float] = None
34
+ rainfall: Optional[float] = None
35
+
36
+
37
+ def get_top_recommendations(model, input_data, top_n=3):
38
+ if hasattr(model, "predict_proba"):
39
+ proba = model.predict_proba(input_data)
40
+ top_indices = np.argsort(proba[0])[-top_n:][::-1]
41
+ return [model.classes_[i] for i in top_indices]
42
+ return model.predict(input_data).tolist()
43
+
44
+
45
+ @app.post("/predict")
46
+ def predict_crop(request: CropRequest):
47
+ location_recommendations = []
48
+ npk_recommendations = []
49
+
50
+ if request.state and request.district and request.season and request.area:
51
+ try:
52
+ input_data = pd.DataFrame([[request.state, request.district, request.season, np.log1p(request.area)]],
53
+ columns=['State_Name', 'District_Name', 'Season', 'Area'])
54
+ location_recommendations = get_top_recommendations(location_model, input_data, top_n=3)
55
+ except ValueError:
56
+ pass # Handle invalid input
57
+
58
+ if request.N is not None and request.P is not None and request.K is not None and request.temperature is not None \
59
+ and request.humidity is not None and request.ph is not None and request.rainfall is not None:
60
+ try:
61
+ input_data = np.array([[request.N, request.P, request.K, request.temperature,
62
+ request.humidity, request.ph, request.rainfall]])
63
+ npk_recommendations = get_top_recommendations(npk_model, input_data, top_n=3)
64
+ except ValueError:
65
+ pass # Handle invalid input
66
+
67
+ location_lower = {crop.lower(): crop for crop in location_recommendations}
68
+ common_crops_lower = set(location_lower.keys()) & set(crop.lower() for crop in npk_recommendations)
69
+ common_crops = [location_lower[crop] for crop in common_crops_lower]
70
+
71
+ location_recommendations = [crop for crop in location_recommendations if crop.lower() not in common_crops_lower]
72
+ npk_recommendations = [crop for crop in npk_recommendations if crop.lower() not in common_crops_lower]
73
+
74
+ merged_crops = common_crops + npk_recommendations + location_recommendations
75
+ final_recommendations = [crop.lower() for crop in merged_crops[:4]]
76
+
77
+ return {"recommendations": final_recommendations if final_recommendations else []}