AICODER009 commited on
Commit
a4400ba
·
verified ·
1 Parent(s): f0f7289

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -0
app.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI
2
+ from pydantic import BaseModel
3
+ import pandas as pd
4
+ import pickle
5
+ from fastapi.middleware.cors import CORSMiddleware
6
+
7
+
8
+ # Load the saved Random Forest model
9
+ with open("random_forest_pkl.pkl", "rb") as f:
10
+ model = pickle.load(f)
11
+
12
+ # Initialize FastAPI app
13
+ app = FastAPI(
14
+ title="Soil Fertility Prediction API",
15
+ description="Predict soil fertility level (0=Low, 1=Medium, 2=High) using a trained Random Forest model.",
16
+ version="1.0.0"
17
+ )
18
+
19
+ # Enable CORS (for browser and external app access)
20
+ app.add_middleware(
21
+ CORSMiddleware,
22
+ allow_origins=["*"], # or replace * with your website URL for security
23
+ allow_credentials=True,
24
+ allow_methods=["*"],
25
+ allow_headers=["*"],
26
+ )
27
+
28
+ # Define input data model
29
+ class SoilInput(BaseModel):
30
+ N: float
31
+ P: float
32
+ K: float
33
+ pH: float
34
+ EC: float
35
+ OC: float
36
+ S: float
37
+ Zn: float
38
+ Fe: float
39
+ Cu: float
40
+ Mn: float
41
+ B: float
42
+
43
+ # Root endpoint
44
+ @app.get("/")
45
+ def root():
46
+ return {"message": "Welcome to the Soil Fertility Prediction API"}
47
+
48
+ # Prediction endpoint
49
+ @app.post("/predict")
50
+ def predict_fertility(data: SoilInput):
51
+ df = pd.DataFrame([data.model_dump()])
52
+ pred = model.predict(df)[0]
53
+ labels = {0: "Low Fertility", 1: "Medium Fertility", 2: "High Fertility"}
54
+ return {
55
+ "prediction": int(pred),
56
+ "class_label": labels[int(pred)]
57
+ }