import numpy as np import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split import gradio as gr import random # Generate synthetic dataset for Indian crops (focusing on South Indian states) def generate_synthetic_dataset(num_samples=5000): np.random.seed(42) # Common crops in Andhra Pradesh and Telangana crops = [ 'Rice', 'Maize', 'Cotton', 'Groundnut', 'Red Gram (Toor Dal)', 'Green Gram (Moong Dal)', 'Black Gram (Urad Dal)', 'Sunflower', 'Sugarcane', 'Turmeric', 'Chilli', 'Tomato', 'Onion', 'Mango', 'Banana', 'Coconut', 'Soybean', 'Jowar (Sorghum)', 'Bajra (Pearl Millet)' ] # Soil types common in the region soil_types = ['Black Cotton', 'Red Sandy', 'Clayey', 'Loamy', 'Sandy Loam'] # Seasons in Indian agriculture seasons = ['Kharif (June-Oct)', 'Rabi (Oct-Mar)', 'Zaid (Mar-Jun)', 'Whole Year'] # Generate synthetic data data = { 'Temperature (°C)': np.random.uniform(10, 60, num_samples), 'Rainfall (mm)': np.random.uniform(0, 300, num_samples), 'Humidity (%)': np.random.uniform(20, 100, num_samples), 'Soil pH': np.random.uniform(4.5, 9.5, num_samples), 'Soil Type': np.random.choice(soil_types, num_samples), 'Nitrogen (N) Level': np.random.uniform(0, 150, num_samples), 'Phosphorus (P) Level': np.random.uniform(0, 100, num_samples), 'Potassium (K) Level': np.random.uniform(0, 200, num_samples), 'Season': np.random.choice(seasons, num_samples), 'Crop': np.random.choice(crops, num_samples) } # Add some logical patterns based on real-world knowledge df = pd.DataFrame(data) # Adjust values based on crop preferences for idx, row in df.iterrows(): crop = row['Crop'] # Temperature adjustments if crop in ['Rice', 'Banana', 'Coconut']: df.at[idx, 'Temperature (°C)'] = np.random.uniform(25, 40) df.at[idx, 'Humidity (%)'] = np.random.uniform(60, 100) elif crop in ['Wheat', 'Barley']: df.at[idx, 'Temperature (°C)'] = np.random.uniform(10, 25) elif crop in ['Chilli', 'Tomato']: df.at[idx, 'Temperature (°C)'] = np.random.uniform(20, 35) # Soil type adjustments if crop in ['Cotton', 'Groundnut']: df.at[idx, 'Soil Type'] = 'Black Cotton' elif crop in ['Rice']: df.at[idx, 'Soil Type'] = random.choice(['Clayey', 'Loamy']) # Season adjustments if crop in ['Rice', 'Maize', 'Cotton', 'Groundnut']: df.at[idx, 'Season'] = 'Kharif (June-Oct)' elif crop in ['Wheat', 'Barley', 'Chickpea']: df.at[idx, 'Season'] = 'Rabi (Oct-Mar)' elif crop in ['Watermelon', 'Cucumber']: df.at[idx, 'Season'] = 'Zaid (Mar-Jun)' # Add profit estimates (in INR per acre) profit_ranges = { 'Rice': (25000, 50000), 'Maize': (20000, 45000), 'Cotton': (30000, 70000), 'Groundnut': (25000, 55000), 'Red Gram (Toor Dal)': (28000, 60000), 'Green Gram (Moong Dal)': (22000, 50000), 'Black Gram (Urad Dal)': (24000, 52000), 'Sunflower': (18000, 40000), 'Sugarcane': (35000, 75000), 'Turmeric': (40000, 90000), 'Chilli': (50000, 120000), 'Tomato': (30000, 80000), 'Onion': (25000, 65000), 'Mango': (60000, 150000), 'Banana': (50000, 120000), 'Coconut': (40000, 100000), 'Soybean': (22000, 48000), 'Jowar (Sorghum)': (18000, 40000), 'Bajra (Pearl Millet)': (15000, 35000) } df['Profit (INR/acre)'] = df['Crop'].apply(lambda x: random.randint(*profit_ranges[x])) return df # Generate the dataset df = generate_synthetic_dataset(10000) # Prepare data for ML model X = df.drop(['Crop', 'Profit (INR/acre)'], axis=1) X = pd.get_dummies(X) # Convert categorical variables to dummy variables y = df['Crop'] # Train-test split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Train Random Forest Classifier model = RandomForestClassifier(n_estimators=100, random_state=42) model.fit(X_train, y_train) # Crop precautions information precautions_db = { 'Rice': [ "Maintain proper water level (5-10 cm) in the field", "Control weeds through manual weeding or herbicides", "Use balanced fertilizers (N:P:K = 100:50:50 kg/ha)", "Watch for pests like stem borers and leaf folders" ], 'Maize': [ "Ensure proper spacing (60x20 cm)", "Apply fertilizers in split doses", "Control weeds during first 30-40 days", "Watch for fall armyworm and use pheromone traps" ], 'Cotton': [ "Use drip irrigation for water efficiency", "Monitor for pink bollworm regularly", "Practice crop rotation to prevent pest buildup", "Use recommended spacing (90x60 cm)" ], 'Groundnut': [ "Ensure well-drained soil to prevent fungal diseases", "Apply gypsum at flowering stage (500 kg/ha)", "Control weeds during first 45 days", "Harvest at proper maturity to avoid pod loss" ], 'Red Gram (Toor Dal)': [ "Sow in rows with 45 cm spacing", "Treat seeds with rhizobium culture", "Provide protective irrigation during flowering", "Watch for pod borer and apply neem oil" ], 'Tomato': [ "Use staking for better fruit quality", "Practice crop rotation to avoid soil diseases", "Monitor for fruit borer and whitefly", "Harvest at breaker stage for longer shelf life" ], 'Chilli': [ "Raise seedlings in nursery for 35-40 days", "Mulch to conserve soil moisture", "Monitor for thrips and mites regularly", "Harvest at regular intervals for higher yield" ], # Default precautions for other crops 'Default': [ "Use recommended spacing for the crop", "Monitor for pests and diseases regularly", "Apply balanced fertilizers as per soil test", "Ensure proper irrigation based on weather conditions" ] } # Function to get top precautions based on input features def get_precautions(crop, temperature, rainfall, humidity, soil_type): precautions = precautions_db.get(crop, precautions_db['Default']) # Add weather-specific precautions if temperature > 35: precautions.append("Provide mulch to reduce soil temperature") precautions.append("Increase irrigation frequency during hot days") if rainfall < 50: precautions.append("Use water conservation techniques like drip irrigation") if humidity > 80: precautions.append("Watch for fungal diseases and apply preventive sprays") # Add soil-specific precautions if soil_type == 'Black Cotton': precautions.append("Practice deep ploughing to break soil hardpans") elif soil_type == 'Sandy Loam': precautions.append("Apply organic manure to improve water retention") return precautions[:5] # Return top 5 precautions # Function to predict crop and details def predict_crop(temperature, rainfall, humidity, soil_ph, soil_type, nitrogen, phosphorus, potassium, season): # Create input dataframe input_data = { 'Temperature (°C)': [temperature], 'Rainfall (mm)': [rainfall], 'Humidity (%)': [humidity], 'Soil pH': [soil_ph], 'Nitrogen (N) Level': [nitrogen], 'Phosphorus (P) Level': [phosphorus], 'Potassium (K) Level': [potassium], 'Season': [season] } # Add soil type columns (one-hot encoding) for st in ['Black Cotton', 'Red Sandy', 'Clayey', 'Loamy', 'Sandy Loam']: input_data[f'Soil Type_{st}'] = [1 if soil_type == st else 0] # Add season columns (one-hot encoding) for s in ['Kharif (June-Oct)', 'Rabi (Oct-Mar)', 'Zaid (Mar-Jun)', 'Whole Year']: input_data[f'Season_{s}'] = [1 if season == s else 0] input_df = pd.DataFrame(input_data) # Ensure columns are in same order as training data input_df = input_df.reindex(columns=X.columns, fill_value=0) # Predict crop crop = model.predict(input_df)[0] # Get profit range profit = df[df['Crop'] == crop]['Profit (INR/acre)'].mean() # Get precautions precautions = get_precautions(crop, temperature, rainfall, humidity, soil_type) # Get similar crops (top 3 alternatives) probas = model.predict_proba(input_df)[0] top3_idx = np.argsort(probas)[-3:][::-1] similar_crops = [model.classes_[i] for i in top3_idx if model.classes_[i] != crop][:2] # Prepare output output = { "Recommended Crop": crop, "Expected Profit (INR per acre)": f"₹{int(profit):,}", "Top Precautions": precautions, "Alternative Crops": similar_crops, "Best Season": season } return output # Custom CSS for farmer-friendly interface custom_css = """ /* Main container styling */ .agrismart-container { background: linear-gradient(135deg, #f5f7fa 0%, #e4efe9 100%); border-radius: 15px; padding: 20px; box-shadow: 0 10px 20px rgba(0,0,0,0.1); font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; } /* Header styling */ .agrismart-header { background: linear-gradient(to right, #4CAF50, #2E8B57); color: white; padding: 15px 20px; border-radius: 10px; text-align: center; margin-bottom: 20px; box-shadow: 0 4px 8px rgba(0,0,0,0.1); } /* Input section styling */ .agrismart-input { background-color: rgba(255, 255, 255, 0.9); padding: 20px; border-radius: 10px; margin-bottom: 20px; box-shadow: 0 2px 5px rgba(0,0,0,0.05); } /* Output section styling */ .agrismart-output { background-color: #ffffff; padding: 20px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); border-left: 5px solid #4CAF50; } /* Button styling */ .agrismart-button { background: linear-gradient(to right, #4CAF50, #2E8B57) !important; color: white !important; border: none !important; padding: 12px 25px !important; border-radius: 8px !important; font-size: 16px !important; cursor: pointer !important; transition: all 0.3s !important; box-shadow: 0 4px 6px rgba(0,0,0,0.1) !important; } .agrismart-button:hover { transform: translateY(-2px) !important; box-shadow: 0 6px 8px rgba(0,0,0,0.15) !important; } /* Slider styling */ .agrismart-slider .gr-slider { background: #e0e0e0 !important; height: 10px !important; border-radius: 5px !important; } .agrismart-slider .gr-slider .gr-slider-selection { background: linear-gradient(to right, #4CAF50, #2E8B57) !important; } /* Label styling */ .agrismart-label { font-weight: bold !important; color: #2E8B57 !important; margin-bottom: 5px !important; font-size: 16px !important; } /* Dropdown styling */ .agrismart-dropdown { border: 1px solid #ddd !important; border-radius: 8px !important; padding: 8px 12px !important; box-shadow: inset 0 1px 3px rgba(0,0,0,0.1) !important; } /* Result card styling */ .agrismart-result-card { background: #f9f9f9; border-radius: 10px; padding: 15px; margin: 10px 0; border-left: 4px solid #4CAF50; } .agrismart-result-title { color: #2E8B57; font-weight: bold; margin-bottom: 10px; } .agrismart-result-value { font-size: 18px; color: #333; } /* Precautions list styling */ .agrismart-precautions { list-style-type: none; padding-left: 0; } .agrismart-precautions li { background: url('data:image/svg+xml;utf8,') no-repeat left center; padding-left: 25px; margin-bottom: 8px; line-height: 1.5; } /* Responsive design */ @media (max-width: 768px) { .agrismart-container { padding: 10px; } } """ # Function to format outputs def format_outputs(output): crop_md = f"**Recommended Crop:** {output['Recommended Crop']}" profit_md = f"**Expected Profit (INR per acre):** {output['Expected Profit (INR per acre)']}" season_md = f"**Best Season:** {output['Best Season']}" alt_md = f"**Alternative Crops:** {', '.join(output['Alternative Crops'])}" prec_html = """ """ return crop_md, profit_md, prec_html, alt_md, season_md # Create Gradio interface with gr.Blocks(css=custom_css) as demo: with gr.Column(elem_classes="agrismart-container"): with gr.Row(elem_classes="agrismart-header"): gr.Markdown(""" # 🌱 Crop Vision : Smart Crop Advisor for Farmers ### Get personalized crop recommendations based on your farm conditions """) with gr.Row(): with gr.Column(elem_classes="agrismart-input"): gr.Markdown("### 🌦️ Enter Your Farm Conditions", elem_classes="agrismart-label") with gr.Row(): temperature = gr.Slider(10, 60, label="1. Temperature (How hot is your area?)", info="Measure the air temperature in shade (°C)", elem_classes="agrismart-slider") rainfall = gr.Slider(0, 300, label="2. Rainfall (How much rain your area gets?)", info="Annual rainfall in your area (mm)", elem_classes="agrismart-slider") with gr.Row(): humidity = gr.Slider(20, 100, label="3. Humidity (How moist is your air?)", info="Relative humidity percentage (%)", elem_classes="agrismart-slider") soil_ph = gr.Slider(4, 10, label="4. Soil pH (Is your soil acidic or alkaline?)", info="7 is neutral, below 7 is acidic, above 7 is alkaline", elem_classes="agrismart-slider") with gr.Row(): soil_type = gr.Dropdown( ["Black Cotton", "Red Sandy", "Clayey", "Loamy", "Sandy Loam"], label="5. Soil Type (What type of soil do you have?)", info="Black Cotton is common in Andhra/Telangana", elem_classes="agrismart-dropdown" ) season = gr.Dropdown( ["Kharif (June-Oct)", "Rabi (Oct-Mar)", "Zaid (Mar-Jun)", "Whole Year"], label="6. Season (When will you cultivate?)", elem_classes="agrismart-dropdown" ) with gr.Row(): nitrogen = gr.Slider(0, 150, label="7. Nitrogen Level (N) in soil", info="Essential for leaf growth (kg/ha)", elem_classes="agrismart-slider") phosphorus = gr.Slider(0, 100, label="8. Phosphorus Level (P) in soil", info="Important for root development (kg/ha)", elem_classes="agrismart-slider") potassium = gr.Slider(0, 200, label="9. Potassium Level (K) in soil", info="Helps in fruit quality (kg/ha)", elem_classes="agrismart-slider") submit_btn = gr.Button("Get Crop Recommendation", elem_classes="agrismart-button") with gr.Column(elem_classes="agrismart-output"): gr.Markdown("### 📊 Recommended Crop Details", elem_classes="agrismart-label") with gr.Column(elem_classes="agrismart-result-card"): crop = gr.Markdown("**Recommended Crop:** ", elem_classes="agrismart-result-value") profit = gr.Markdown("**Expected Profit (INR per acre):** ", elem_classes="agrismart-result-value") season_out = gr.Markdown("**Best Season:** ", elem_classes="agrismart-result-value") alternatives = gr.Markdown("**Alternative Crops:** ", elem_classes="agrismart-result-value") gr.Markdown("### 🛡️ Top Precautions", elem_classes="agrismart-result-title") precautions = gr.HTML(""" """) # Example images (would need actual images in production) gr.Markdown("### 🌾 Common Crops in Andhra/Telangana") gr.HTML("""
🌾
Rice
🌽
Maize
🧶
Cotton
🥜
Groundnut
""") # Define button click action submit_btn.click( fn=lambda temp, rain, hum, ph, soil, n, p, k, seas: format_outputs( predict_crop(temp, rain, hum, ph, soil, n, p, k, seas) ), inputs=[temperature, rainfall, humidity, soil_ph, soil_type, nitrogen, phosphorus, potassium, season], outputs=[crop, profit, precautions, alternatives, season_out] ) # Launch the application if __name__ == "__main__": demo.launch()