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 Bangladesh crops def generate_synthetic_dataset(num_samples=5000): np.random.seed(42) # Common crops in Bangladesh crops = [ 'Rice (Aman)', 'Rice (Boro)', 'Rice (Aus)', 'Jute', 'Wheat', 'Maize', 'Potato', 'Sugarcane', 'Pulses (Mungbean)', 'Pulses (Lentil)', 'Mustard', 'Sesame', 'Sunflower', 'Tea', 'Mango', 'Banana', 'Jackfruit', 'Litchi', 'Pineapple', 'Vegetables' ] # Soil types common in Bangladesh soil_types = ['Alluvial', 'Loamy', 'Clayey', 'Peaty', 'Sandy'] # Seasons in Bangladesh agriculture seasons = ['Kharif-1 (Mar-Jun)', 'Kharif-2 (Jul-Oct)', 'Rabi (Nov-Feb)', 'Whole Year'] # Generate synthetic data data = { 'Temperature (°C)': np.random.uniform(10, 40, num_samples), # Bangladesh has more moderate temperatures 'Rainfall (mm)': np.random.uniform(100, 400, num_samples), # Higher rainfall range 'Humidity (%)': np.random.uniform(60, 100, num_samples), # Generally high humidity 'Soil pH': np.random.uniform(5.0, 8.5, num_samples), # Slightly acidic to neutral '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 'Rice' in crop: df.at[idx, 'Temperature (°C)'] = np.random.uniform(25, 35) df.at[idx, 'Humidity (%)'] = np.random.uniform(70, 100) elif crop in ['Wheat', 'Mustard', 'Potato']: df.at[idx, 'Temperature (°C)'] = np.random.uniform(15, 25) elif crop in ['Jute', 'Tea']: df.at[idx, 'Temperature (°C)'] = np.random.uniform(20, 30) df.at[idx, 'Rainfall (mm)'] = np.random.uniform(200, 400) # Soil type adjustments if crop in ['Jute']: df.at[idx, 'Soil Type'] = 'Alluvial' elif crop in ['Tea']: df.at[idx, 'Soil Type'] = 'Loamy' elif crop in ['Rice (Boro)']: df.at[idx, 'Soil Type'] = random.choice(['Alluvial', 'Clayey']) # Season adjustments if crop in ['Rice (Aman)', 'Jute']: df.at[idx, 'Season'] = 'Kharif-2 (Jul-Oct)' elif crop in ['Rice (Boro)', 'Wheat', 'Mustard', 'Potato']: df.at[idx, 'Season'] = 'Rabi (Nov-Feb)' elif crop in ['Rice (Aus)']: df.at[idx, 'Season'] = 'Kharif-1 (Mar-Jun)' # Add profit estimates (in BDT per acre) profit_ranges = { 'Rice (Aman)': (30000, 60000), 'Rice (Boro)': (35000, 70000), 'Rice (Aus)': (25000, 50000), 'Jute': (40000, 80000), 'Wheat': (25000, 50000), 'Maize': (30000, 60000), 'Potato': (50000, 100000), 'Sugarcane': (60000, 120000), 'Pulses (Mungbean)': (20000, 45000), 'Pulses (Lentil)': (22000, 48000), 'Mustard': (25000, 55000), 'Sesame': (18000, 40000), 'Sunflower': (20000, 45000), 'Tea': (80000, 150000), 'Mango': (100000, 250000), 'Banana': (80000, 180000), 'Jackfruit': (70000, 150000), 'Litchi': (90000, 200000), 'Pineapple': (60000, 120000), 'Vegetables': (50000, 150000) } df['Profit (BDT/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 (BDT/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 (Aman)': [ "Transplant 25-30 day old seedlings", "Maintain 2-3 cm standing water during initial stage", "Apply 60-80 kg N, 15-20 kg P, and 30-40 kg K per hectare", "Control stem borer with proper insecticides" ], 'Rice (Boro)': [ "Ensure irrigation availability as it's dry season rice", "Use cold-tolerant varieties in northern regions", "Apply split doses of nitrogen fertilizer", "Control rats and birds during ripening stage" ], 'Jute': [ "Sow in well-prepared land with proper moisture", "Retting should be done in clean water for quality fiber", "Apply 40-60 kg N, 20-30 kg P, and 20-30 kg K per hectare", "Control jute hairy caterpillar with proper measures" ], 'Wheat': [ "Sow in rows with 20 cm spacing", "Apply irrigation at crown root initiation and flowering stages", "Use disease-resistant varieties to combat rust", "Harvest when moisture content is 20-25%" ], 'Maize': [ "Sow in rows with 60 cm row to row distance", "Apply 150-180 kg N, 35-40 kg P, and 60-70 kg K per hectare", "Control fall armyworm with integrated pest management", "Harvest when kernels have 20-25% moisture" ], 'Potato': [ "Use disease-free seed tubers", "Apply irrigation at critical growth stages", "Control late blight with fungicides", "Harvest when vines dry up" ], 'Tea': [ "Prune bushes regularly for new flush", "Apply balanced fertilizer with zinc and magnesium", "Control red spider mite with acaricides", "Pluck two leaves and a bud for quality" ], 'Mango': [ "Prune for proper canopy management", "Control mango hopper during flowering", "Apply irrigation during fruit development", "Harvest when shoulders develop" ], # 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 > 300: precautions.append("Ensure proper drainage to prevent waterlogging") if humidity > 85: precautions.append("Watch for fungal diseases and apply preventive sprays") # Add soil-specific precautions if soil_type == 'Alluvial': precautions.append("Apply organic matter to maintain soil fertility") elif soil_type == 'Peaty': precautions.append("Apply lime to reduce acidity if needed") 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 ['Alluvial', 'Loamy', 'Clayey', 'Peaty', 'Sandy']: input_data[f'Soil Type_{st}'] = [1 if soil_type == st else 0] # Add season columns (one-hot encoding) for s in ['Kharif-1 (Mar-Jun)', 'Kharif-2 (Jul-Oct)', 'Rabi (Nov-Feb)', '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 (BDT/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 (BDT 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 (BDT per acre):** {output['Expected Profit (BDT 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(""" # 🌱 বাংলাদেশের জন্য ফসল সুপারিশকারী ### আপনার জমির অবস্থা অনুযায়ী উপযুক্ত ফসলের পরামর্শ পান """) with gr.Row(): with gr.Column(elem_classes="agrismart-input"): gr.Markdown("### 🌦️ আপনার জমির তথ্য দিন", elem_classes="agrismart-label") with gr.Row(): temperature = gr.Slider(10, 40, label="1. তাপমাত্রা (°C)", info="ছায়াযুক্ত স্থানে বায়ুর তাপমাত্রা মাপুন", elem_classes="agrismart-slider") rainfall = gr.Slider(100, 400, label="2. বৃষ্টিপাত (mm)", info="আপনার এলাকার বার্ষিক বৃষ্টিপাতের পরিমাণ", elem_classes="agrismart-slider") with gr.Row(): humidity = gr.Slider(60, 100, label="3. আর্দ্রতা (%)", info="বাতাসে আর্দ্রতার পরিমাণ", elem_classes="agrismart-slider") soil_ph = gr.Slider(5, 8.5, label="4. মাটির pH মান", info="৭ হলো নিরপেক্ষ, ৭ এর নিচে অম্লীয়, ৭ এর উপরে ক্ষারীয়", elem_classes="agrismart-slider") with gr.Row(): soil_type = gr.Dropdown( ["Alluvial", "Loamy", "Clayey", "Peaty", "Sandy"], label="5. মাটির ধরন", info="বাংলাদেশের সাধারণ মাটির ধরন", elem_classes="agrismart-dropdown" ) season = gr.Dropdown( ["Kharif-1 (Mar-Jun)", "Kharif-2 (Jul-Oct)", "Rabi (Nov-Feb)", "Whole Year"], label="6. মৌসুম", elem_classes="agrismart-dropdown" ) with gr.Row(): nitrogen = gr.Slider(0, 150, label="7. মাটিতে নাইট্রোজেনের পরিমাণ (N)", info="গাছের পাতার বৃদ্ধির জন্য প্রয়োজনীয় (kg/ha)", elem_classes="agrismart-slider") phosphorus = gr.Slider(0, 100, label="8. মাটিতে ফসফরাসের পরিমাণ (P)", info="শিকড়ের উন্নতির জন্য গুরুত্বপূর্ণ (kg/ha)", elem_classes="agrismart-slider") potassium = gr.Slider(0, 200, label="9. মাটিতে পটাশিয়ামের পরিমাণ (K)", info="ফলের গুণগত মানের জন্য সহায়ক (kg/ha)", elem_classes="agrismart-slider") submit_btn = gr.Button("ফসলের সুপারিশ পান", elem_classes="agrismart-button") with gr.Column(elem_classes="agrismart-output"): gr.Markdown("### 📊 সুপারিশকৃত ফসলের বিবরণ", elem_classes="agrismart-label") with gr.Column(elem_classes="agrismart-result-card"): crop = gr.Markdown("**সুপারিশকৃত ফসল:** ", elem_classes="agrismart-result-value") profit = gr.Markdown("**আনুমানিক লাভ (প্রতি একরে):** ", elem_classes="agrismart-result-value") season_out = gr.Markdown("**উপযুক্ত মৌসুম:** ", elem_classes="agrismart-result-value") alternatives = gr.Markdown("**বিকল্প ফসল:** ", elem_classes="agrismart-result-value") gr.Markdown("### 🛡️ প্রয়োজনীয় সতর্কতা", elem_classes="agrismart-result-title") precautions = gr.HTML(""" """) # Example images of common Bangladeshi crops gr.Markdown("### 🌾 বাংলাদেশের প্রধান ফসল") gr.HTML("""
🌾
ধান
🧶
পাট
🥔
আলু
🍌
কলা
""") # 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()