File size: 2,492 Bytes
4765a68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import pandas as pd
from sklearn.preprocessing import LabelEncoder

# Load data
data = pd.read_csv('chittor_final1.csv')

# Encoding
encode_soil = LabelEncoder()
data['Soil_Type'] = encode_soil.fit_transform(data['Soil_type'])

encode_crop = LabelEncoder()
data['Crop_Type'] = encode_crop.fit_transform(data['Crop_type'])

# nutrient thresholds
thresholds = {
    'Avail_P': 10,
    'Exch_K': 50,
    'Avail_Ca': 200,
    'Avail_Mg': 50,
    'Avail_S': 10,
    'Avail_Zn': 1,
    'Avail_B': 0.5,
    'Avail_Fe': 4,
    'Avail_Cu': 0.3,
    'Avail_Mn': 5
}

# application rates
application_rates = {
    'P': 30,
    'K': 50,
    'Ca': 40,
    'Mg': 20,
    'S': 25,
    'Zn': 5,
    'B': 2,
    'Fe': 10,
    'Cu': 1,
    'Mn': 4
}

# soil density and depth
soil_density = 1800
soil_depth = 0.2

# calculate amounts
def get_fertilizer_recommendation(row, land_size_m2, fallow_years):
    deficiencies = []
    fertilizer_amounts = {}
    for nutrient, threshold in thresholds.items():
        if row[nutrient] < threshold:
            nutrient_name = nutrient.split('_')[-1]
            deficiencies.append(nutrient_name)
            base_amount_per_m2 = application_rates[nutrient_name] / 10000
            total_amount = base_amount_per_m2 * land_size_m2 * (1 + 0.1 * fallow_years)
            fertilizer_amounts[nutrient_name] = round(total_amount, 2)
    if deficiencies:
        return 'Fertilizer needed for'+ ', '.join(deficiencies), fertilizer_amounts
    else:
        return 'No deficiency', {}

# Gradio app
demo = gr.Interface(
    fn=lambda soil_type, crop_type, land_size_m2, fallow_years: get_fertilizer_recommendation(
        data[(data['Soil_Type'] == encode_soil.transform([soil_type])[0]) & (data['Crop_Type'] == encode_crop.transform([crop_type])[0])].iloc[0],
        land_size_m2,
        fallow_years
    ),
    inputs=[
        gr.Dropdown(list(data['Soil_type'].unique()), label="Soil Type"), # Convert the numpy array to a list
        gr.Dropdown(list(data['Crop_type'].unique()), label="Crop Type"), # Convert the numpy array to a list
        gr.Number(label="Land Size (m²)"),
        gr.Number(label="Fallow Years")
    ],
    outputs=[
        gr.Textbox(label="Recommendation"),
        gr.JSON(label="Fertilizer Amounts (in kg)")
    ],
    title="Fertilizer Recommendation App",
    description="Get fertilizer recommendations based on soil type, crop type, land size, and fallow years."
)

if __name__ == "__main__":
    demo.launch()