Jayanthk2004 commited on
Commit
a0c4a5e
·
verified ·
1 Parent(s): f56569e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -28
app.py CHANGED
@@ -1,47 +1,95 @@
1
  import gradio as gr
2
  import pandas as pd
3
- import joblib
4
  import pickle
 
5
 
6
- # Load the trained model
7
- with open('Fertilizer_recommender.pkl', 'rb') as f:
8
- model = pickle.load(f)
9
 
10
- # Step 4: Define prediction function with data preprocessing
11
- def recommend_fertilizer(temperature, humidity, moisture, soil_type, crop_type, nitrogen, phosphorous, potassium):
12
- # Example mappings for soil type and crop type (replace with your actual mappings)
13
- soil_type_mapping = {"Sandy": 1, "Clay": 2, "Loam": 3}
14
- crop_type_mapping = {"Wheat": 1, "Rice": 2, "Maize": 3}
15
 
16
- # Convert soil_type and crop_type to numerical values using the mappings
17
- soil_type_numerical = soil_type_mapping.get(soil_type, -1) # -1 for unknown soil type
18
- crop_type_numerical = crop_type_mapping.get(crop_type, -1) # -1 for unknown crop type
19
 
20
- # Prepare the input data for the model
21
- input_data = [[temperature, humidity, moisture, soil_type_numerical, crop_type_numerical, nitrogen, phosphorous, potassium]]
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
- # Make the prediction
24
- prediction = model.predict(input_data)
25
- return prediction[0]
26
 
27
- # Step 5: Create Gradio interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  iface = gr.Interface(
29
  fn=recommend_fertilizer,
30
  inputs=[
31
- gr.Number(label="Temperature"),
32
- gr.Number(label="Humidity"),
33
- gr.Number(label="Moisture"),
34
- gr.Textbox(label="Soil Type"), # Use Textbox for soil type input
35
- gr.Textbox(label="Crop Type"), # Use Textbox for crop type input
36
- gr.Number(label="Nitrogen"),
37
- gr.Number(label="Phosphorous"),
38
- gr.Number(label="Potassium"),
39
  ],
40
  outputs=gr.Text(label="Recommended Fertilizer"),
41
  title="Fertilizer Recommender",
42
  description="Enter the environmental and crop details to get the best fertilizer recommendation.",
 
 
 
 
 
 
 
 
 
43
  api_name="/api/predict_fertilizer"
44
  )
45
 
46
- # Step 6: Launch the app with show_error enabled
47
- iface.launch(show_error=True) # Added show_error=True to see detailed error messages
 
1
  import gradio as gr
2
  import pandas as pd
 
3
  import pickle
4
+ import numpy as np
5
 
6
+ # Extract unique values from the dataset
7
+ df = pd.read_csv('Fertilizer Prediction.csv')
 
8
 
9
+ # Create mapping dataframes based on your dataset
10
+ soil_types = df['Soil Type'].unique().tolist()
11
+ soil_type_mapping = {soil: idx+1 for idx, soil in enumerate(sorted(soil_types))}
12
+ Soil_Type = pd.DataFrame({'Encoded': list(soil_type_mapping.values())}, index=soil_type_mapping.keys())
 
13
 
14
+ crop_types = df['Crop Type'].unique().tolist()
15
+ crop_type_mapping = {crop: idx+1 for idx, crop in enumerate(sorted(crop_types))}
16
+ Crop_Type = pd.DataFrame({'Encoded': list(crop_type_mapping.values())}, index=crop_type_mapping.keys())
17
 
18
+ # Use the provided fertilizer mapping
19
+ fertilizer_types = ["Urea", "DAP", "14-35-14", "28-28", "17-17-17", "20-20", "10-26-26"]
20
+ Fertilizer = pd.DataFrame({'Encoded': [1, 2, 3, 4, 5, 6, 7]}, index=fertilizer_types)
21
+
22
+ # Load the trained model
23
+ def load_model():
24
+ try:
25
+ with open('Fertilizer_recommender.pkl', 'rb') as f:
26
+ model = pickle.load(f)
27
+ return model
28
+ except FileNotFoundError:
29
+ # For demonstration purposes
30
+ import joblib
31
+ return joblib.load('Fertilizer_recommender.pkl')
32
 
33
+ model = load_model()
 
 
34
 
35
+ def recommend_fertilizer(temperature, humidity, moisture, soil_type, crop_type, nitrogen, phosphorous, potassium):
36
+ """
37
+ Function to recommend fertilizer based on input parameters
38
+ """
39
+ # Get the encoded values for soil and crop types
40
+ soil_type_encoded = Soil_Type.loc[soil_type]['Encoded']
41
+ crop_type_encoded = Crop_Type.loc[crop_type]['Encoded']
42
+
43
+ # Create input DataFrame with the exact column names used during training
44
+ # Note: The CSV shows column names with exact spelling (including typo in 'Temparature')
45
+ input_data = pd.DataFrame({
46
+ 'Temparature': [temperature], # Maintaining the typo as in the dataset
47
+ 'Humidity ': [humidity], # Note the space after Humidity
48
+ 'Moisture': [moisture],
49
+ 'Soil Type': [soil_type_encoded],
50
+ 'Crop Type': [crop_type_encoded],
51
+ 'Nitrogen': [nitrogen],
52
+ 'Potassium': [potassium], # Note: In the CSV, Potassium comes before Phosphorous
53
+ 'Phosphorous': [phosphorous],
54
+ })
55
+
56
+ # Make prediction
57
+ prediction = model.predict(input_data)[0]
58
+
59
+ # Map prediction back to fertilizer name
60
+ try:
61
+ fertilizer_name = Fertilizer[Fertilizer['Encoded'] == prediction].index[0]
62
+ return fertilizer_name
63
+ except IndexError:
64
+ return f"Unknown fertilizer code: {prediction} - Please check your Fertilizer mapping."
65
+
66
+ # Create Gradio interface with examples from the dataset
67
  iface = gr.Interface(
68
  fn=recommend_fertilizer,
69
  inputs=[
70
+ gr.Number(label="Temperature (°C)", value=26),
71
+ gr.Number(label="Humidity (%)", value=52),
72
+ gr.Number(label="Moisture (%)", value=38),
73
+ gr.Dropdown(choices=sorted(soil_types), label="Soil Type", value="Black"),
74
+ gr.Dropdown(choices=sorted(crop_types), label="Crop Type", value="Wheat"),
75
+ gr.Number(label="Nitrogen (%)", value=37),
76
+ gr.Number(label="Phosphorous (%)", value=0),
77
+ gr.Number(label="Potassium (%)", value=0),
78
  ],
79
  outputs=gr.Text(label="Recommended Fertilizer"),
80
  title="Fertilizer Recommender",
81
  description="Enter the environmental and crop details to get the best fertilizer recommendation.",
82
+ examples=[
83
+ # Example from your initial test case
84
+ [23, 40, 60, "Black", "Wheat", 30, 40, 50],
85
+ # Examples from the dataset
86
+ [26, 52, 38, "Sandy", "Maize", 37, 0, 0], # Should recommend Urea
87
+ [29, 52, 45, "Loamy", "Sugarcane", 12, 36, 0], # Should recommend DAP
88
+ [34, 65, 62, "Black", "Cotton", 7, 30, 9], # Should recommend 14-35-14
89
+ [32, 62, 34, "Red", "Tobacco", 22, 20, 0] # Should recommend 28-28
90
+ ],
91
  api_name="/api/predict_fertilizer"
92
  )
93
 
94
+ # Launch the app
95
+ iface.launch(show_error=True)