File size: 3,962 Bytes
7d39c70
 
 
a0c4a5e
7d39c70
a0c4a5e
 
7d39c70
a0c4a5e
 
 
 
7d39c70
a0c4a5e
 
 
7d39c70
a0c4a5e
 
 
 
 
 
 
 
 
 
 
 
 
 
7d39c70
a0c4a5e
7d39c70
a0c4a5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d39c70
 
 
a0c4a5e
 
 
 
 
 
 
 
7d39c70
 
 
 
a0c4a5e
 
 
 
 
 
 
 
 
7d39c70
 
 
a0c4a5e
 
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import gradio as gr
import pandas as pd
import pickle
import numpy as np

# Extract unique values from the dataset
df = pd.read_csv('Fertilizer Prediction.csv')

# Create mapping dataframes based on your dataset
soil_types = df['Soil Type'].unique().tolist()
soil_type_mapping = {soil: idx+1 for idx, soil in enumerate(sorted(soil_types))}
Soil_Type = pd.DataFrame({'Encoded': list(soil_type_mapping.values())}, index=soil_type_mapping.keys())

crop_types = df['Crop Type'].unique().tolist()
crop_type_mapping = {crop: idx+1 for idx, crop in enumerate(sorted(crop_types))}
Crop_Type = pd.DataFrame({'Encoded': list(crop_type_mapping.values())}, index=crop_type_mapping.keys())

# Use the provided fertilizer mapping
fertilizer_types = ["Urea", "DAP", "14-35-14", "28-28", "17-17-17", "20-20", "10-26-26"]
Fertilizer = pd.DataFrame({'Encoded': [1, 2, 3, 4, 5, 6, 7]}, index=fertilizer_types)

# Load the trained model
def load_model():
    try:
        with open('Fertilizer_recommender.pkl', 'rb') as f:
            model = pickle.load(f)
        return model
    except FileNotFoundError:
        # For demonstration purposes
        import joblib
        return joblib.load('Fertilizer_recommender.pkl')

model = load_model()

def recommend_fertilizer(temperature, humidity, moisture, soil_type, crop_type, nitrogen, phosphorous, potassium):
    """
    Function to recommend fertilizer based on input parameters
    """
    # Get the encoded values for soil and crop types
    soil_type_encoded = Soil_Type.loc[soil_type]['Encoded']
    crop_type_encoded = Crop_Type.loc[crop_type]['Encoded']
    
    # Create input DataFrame with the exact column names used during training
    # Note: The CSV shows column names with exact spelling (including typo in 'Temparature')
    input_data = pd.DataFrame({
        'Temparature': [temperature],  # Maintaining the typo as in the dataset
        'Humidity ': [humidity],       # Note the space after Humidity
        'Moisture': [moisture],
        'Soil Type': [soil_type_encoded],
        'Crop Type': [crop_type_encoded],
        'Nitrogen': [nitrogen],
        'Potassium': [potassium],      # Note: In the CSV, Potassium comes before Phosphorous
        'Phosphorous': [phosphorous],
    })
    
    # Make prediction
    prediction = model.predict(input_data)[0]
    
    # Map prediction back to fertilizer name
    try:
        fertilizer_name = Fertilizer[Fertilizer['Encoded'] == prediction].index[0]
        return fertilizer_name
    except IndexError:
        return f"Unknown fertilizer code: {prediction} - Please check your Fertilizer mapping."

# Create Gradio interface with examples from the dataset
iface = gr.Interface(
    fn=recommend_fertilizer,
    inputs=[
        gr.Number(label="Temperature (°C)", value=26),
        gr.Number(label="Humidity (%)", value=52),
        gr.Number(label="Moisture (%)", value=38),
        gr.Dropdown(choices=sorted(soil_types), label="Soil Type", value="Black"),
        gr.Dropdown(choices=sorted(crop_types), label="Crop Type", value="Wheat"),
        gr.Number(label="Nitrogen (%)", value=37),
        gr.Number(label="Phosphorous (%)", value=0),
        gr.Number(label="Potassium (%)", value=0),
    ],
    outputs=gr.Text(label="Recommended Fertilizer"),
    title="Fertilizer Recommender",
    description="Enter the environmental and crop details to get the best fertilizer recommendation.",
    examples=[
        # Example from your initial test case
        [23, 40, 60, "Black", "Wheat", 30, 40, 50],
        # Examples from the dataset
        [26, 52, 38, "Sandy", "Maize", 37, 0, 0],  # Should recommend Urea
        [29, 52, 45, "Loamy", "Sugarcane", 12, 36, 0],  # Should recommend DAP
        [34, 65, 62, "Black", "Cotton", 7, 30, 9],  # Should recommend 14-35-14
        [32, 62, 34, "Red", "Tobacco", 22, 20, 0]   # Should recommend 28-28
    ],
    api_name="/api/predict_fertilizer"
)

# Launch the app
iface.launch(show_error=True)