File size: 3,780 Bytes
2efb262
467cf44
2efb262
467cf44
2efb262
467cf44
54fc1c8
 
 
 
 
 
467cf44
2efb262
f6cce53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2efb262
467cf44
54fc1c8
2efb262
467cf44
 
2efb262
467cf44
2efb262
 
467cf44
54fc1c8
 
 
 
 
2efb262
 
54fc1c8
2efb262
 
 
 
 
 
 
 
 
 
 
 
 
 
54fc1c8
 
 
 
 
 
 
2efb262
54fc1c8
2efb262
 
f6cce53
 
 
 
2efb262
f6cce53
2efb262
54fc1c8
2efb262
 
 
54fc1c8
2efb262
 
 
f6cce53
 
 
 
 
 
 
 
2efb262
f6cce53
2efb262
f6cce53
54fc1c8
2efb262
 
54fc1c8
 
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
96
97
98
99
100
101
102
103
104
105
106
107
108
import gradio as gr
import pandas as pd
import joblib
import os
import google.generativeai as genai

# Load models
try:
    rf_ferti_name = joblib.load("rf_ferti_name.pkl")
    rf_ferti_value = joblib.load("rf_ferti_value.pkl")
except Exception as e:
    raise RuntimeError(f"Model loading failed: {e}")

# Encodings
soil_type_encodings = {
    'Black': 0, 'Clayey': 1, 'Loamy': 2, 'Red': 3, 'Sandy': 4
}
crop_type_encodings = {
    'Barley': 0, 'Cotton': 1, 'Ground Nuts': 2, 'Maize': 3, 'Millets': 4,
    'Oil seeds': 5, 'Other Variety': 6, 'Paddy': 7, 'Pulses': 8, 'Sugarcane': 9,
    'Tobacco': 10, 'Wheat': 11
}
fertilizer_name_encodings = {
    '10-26-26': 0, '14-35-14': 1, '15-15-15': 2, '17-17-17': 3, '20-20': 4,
    '20-20-20': 5, '28-28': 6, 'Ammonium sulfate': 7, 'Biofertilizer (e.g., Rhizobium)': 8,
    'Calcium nitrate': 9, 'DAP': 10, 'Ferrous sulfate': 11, 'Magnesium sulfate': 12,
    'Potassium chloride/Muriate of potash (MOP)': 13,
    'Potassium sulfate/Sulfate of potash (SOP)': 14, 'Rock phosphate (RP)': 15,
    'Single superphosphate (SSP)': 16, 'Triple superphosphate (TSP)': 17,
    'Urea': 18, 'Zinc sulfate': 19
}
inv_fert_name_encodings = {v: k for k, v in fertilizer_name_encodings.items()}

# Setup Gemini API
genai.configure(api_key=os.getenv("GEMINI_API"))
model = genai.GenerativeModel("gemini-1.5-flash")

def generate_ai_suggestions(fertilizer_name):
    prompt = (
        f"For {fertilizer_name} fertilizer, generate 3–4 short suggestions. "
        "Each on a new line. Text should be justified and not contain special characters."
    )
    try:
        response = model.generate_content(prompt)
        return response.text.strip()
    except Exception as e:
        return f"AI suggestion error: {str(e)}"

def predict_fertilizer(temp, humidity, moisture, soil_type, crop_type, nitrogen, potassium, phosphorous):
    # Encode input
    soil_encoded = soil_type_encodings.get(soil_type, -1)
    crop_encoded = crop_type_encodings.get(crop_type, -1)

    input_df = pd.DataFrame([{
        "Temperature": temp,
        "Humidity": humidity,
        "Moisture": moisture,
        "Nitrogen": nitrogen,
        "Potassium": potassium,
        "Phosphorous": phosphorous,
        "Soil Type": soil_encoded,
        "Crop Type": crop_encoded,
    }])

    try:
        # Predict
        pred_name_encoded = rf_ferti_name.predict(input_df)[0]
        fert_name = inv_fert_name_encodings[pred_name_encoded]
        fert_qty = rf_ferti_value.predict(input_df)[0]
    except Exception as e:
        return f"❌ Model prediction failed: {str(e)}"

    # Gemini suggestions
    ai_info = generate_ai_suggestions(fert_name)

    result = (
        f"🌾 **Recommended Fertilizer**: `{fert_name}`\n"
        f"📦 **Estimated Quantity**: `{fert_qty:.2f} units`\n\n"
        f"📘 **AI Suggestions**:\n{ai_info}"
    )
    return result

# Dropdown options
soil_list = list(soil_type_encodings.keys())
crop_list = list(crop_type_encodings.keys())

# Gradio Interface
interface = gr.Interface(
    fn=predict_fertilizer,
    inputs=[
        gr.Slider(0, 50, label="🌡️ Temperature (°C)"),
        gr.Slider(0, 100, label="💧 Humidity (%)"),
        gr.Slider(0, 100, label="🌱 Moisture (%)"),
        gr.Dropdown(soil_list, label="🧱 Soil Type"),
        gr.Dropdown(crop_list, label="🌾 Crop Type"),
        gr.Number(label="🧪 Nitrogen Level"),
        gr.Number(label="🧪 Potassium Level"),
        gr.Number(label="🧪 Phosphorous Level")
    ],
    outputs=gr.Markdown(label="🧾 Result"),
    title="🌿 Fertilizer Recommendation System",
    description="Enter environmental and soil parameters to get fertilizer suggestions powered by AI.",
    allow_flagging="never"
)

# Launch for Hugging Face
interface.launch()