Spaces:
Sleeping
Sleeping
File size: 19,351 Bytes
904f7cf cc1911f 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 | 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,<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 (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 = """
<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("""
# 🌱 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("""
<ul class="agrismart-precautions">
<li>Enter your farm details and click the button to get recommendations</li>
</ul>
""")
# Example images (would need actual images in production)
gr.Markdown("### 🌾 Common Crops in Andhra/Telangana")
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>Rice</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>Maize</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>Cotton</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>Groundnut</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() |