Spaces:
Sleeping
Sleeping
File size: 20,772 Bytes
904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf c7bdb86 904f7cf | 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 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 | 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,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="%234CAF50"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/></svg>') 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 = """
<ul class="agrismart-precautions">
""" + "\n".join([f"<li>{p}</li>" for p in output['Top Precautions']]) + """
</ul>
"""
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("""
<ul class="agrismart-precautions">
<li>আপনার জমির তথ্য প্রদান করে বাটনে ক্লিক করুন</li>
</ul>
""")
# Example images of common Bangladeshi crops
gr.Markdown("### 🌾 বাংলাদেশের প্রধান ফসল")
gr.HTML("""
<div style="display: flex; flex-wrap: wrap; gap: 10px; justify-content: center;">
<div style="text-align: center;">
<div style="background: #e3f2fd; padding: 10px; border-radius: 10px; width: 100px;">
<div style="font-size: 40px;">🌾</div>
<div>ধান</div>
</div>
</div>
<div style="text-align: center;">
<div style="background: #e8f5e9; padding: 10px; border-radius: 10px; width: 100px;">
<div style="font-size: 40px;">🧶</div>
<div>পাট</div>
</div>
</div>
<div style="text-align: center;">
<div style="background: #fff3e0; padding: 10px; border-radius: 10px; width: 100px;">
<div style="font-size: 40px;">🥔</div>
<div>আলু</div>
</div>
</div>
<div style="text-align: center;">
<div style="background: #f3e5f5; padding: 10px; border-radius: 10px; width: 100px;">
<div style="font-size: 40px;">🍌</div>
<div>কলা</div>
</div>
</div>
</div>
""")
# 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() |