File size: 2,397 Bytes
31572a9
3987248
31572a9
 
f4a84cf
6e498bf
31572a9
 
3987248
 
 
 
 
 
 
31572a9
b6fa28f
f4a84cf
b6fa28f
31572a9
 
f4a84cf
 
 
 
 
 
 
 
 
31572a9
f4a84cf
31572a9
 
6e498bf
 
 
b6fa28f
 
 
 
 
 
 
 
 
 
 
 
 
 
6e498bf
 
 
 
 
b6fa28f
31572a9
f4a84cf
 
 
 
 
 
 
31572a9
6e498bf
f4a84cf
31572a9
f4a84cf
31572a9
f4a84cf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import joblib
import numpy as np
import pandas as pd

app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Allows all origins
    allow_credentials=True,
    allow_methods=["*"],  # Allows all methods
    allow_headers=["*"],  # Allows all headers
)

# Loading the  model and label encoder
model = joblib.load("soil_npk_joblib_model.joblib")
le = joblib.load("label_encoder.joblib")

class InputData(BaseModel):
    crop_name: str
    target_yield: float
    field_size: float
    ph: float
    organic_carbon: float
    nitrogen: float
    phosphorus: float
    potassium: float
    soil_moisture: float

@app.post("/predict")
async def predict(data: InputData):
    try:
        # Validating crop_name
        if data.crop_name not in le.classes_:
            raise ValueError(f"Invalid crop_name: {data.crop_name}")
        input_data = pd.DataFrame({
            'crop_name': [data.crop_name],
            'target_yield': [data.target_yield],
            'field_size': [data.field_size],
            'ph': [data.ph],
            'organic_carbon': [data.organic_carbon],
            'nitrogen': [data.nitrogen],
            'phosphorus': [data.phosphorus],
            'potassium': [data.potassium],
            'soil_moisture': [data.soil_moisture]
        })
        
        # Use the encoder to transform the crop_name
        input_data['crop_name'] = le.transform(input_data['crop_name'])
          # Validating the  input shape
        expected_shape = model.n_features_in_
        if input_data.shape[1] != expected_shape:
            raise ValueError(f"Input shape mismatch. Expected {expected_shape} features, got {input_data.shape[1]}")

        
        prediction = model.predict(input_data)
        return {
            "nitrogen_need": float(prediction[0][0]),
            "phosphorus_need": float(prediction[0][1]),
            "potassium_need": float(prediction[0][2]),
            "organic_matter_need": float(prediction[0][3]),
            "lime_need": float(prediction[0][4])
        }
    except Exception as e:
        logging.error(f"Error in predict function: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/")
async def root():
    return {"message": "NPK Needs Prediction API"}