Spaces:
Sleeping
Sleeping
File size: 19,702 Bytes
5bda5ea | 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 | """
=============================================================================
AgriShield β Model Setup Script
=============================================================================
This script does two things:
1. COPIES pre-trained DL models (CNN .h5 files from AgriGo sample project)
into backend/models/DL_models/
2. RETRAINS ML models (crop & fertilizer recommenders) from the CSV datasets
in sample/AgriGo/AgriGo/dataset/ and saves them to backend/models/ML_models/
Optionally it can also RETRAIN the DL models from scratch using the augmented
PlantVillage dataset (takes 30-90 min per crop on CPU / 5-15 min on GPU).
Run:
python setup_models.py # copy DL + retrain ML
python setup_models.py --retrain # also retrain all DL models from scratch
python setup_models.py --crop tomato --retrain # retrain one specific crop
=============================================================================
"""
import os
import sys
import shutil
import pickle
import argparse
import numpy as np
# ββ Paths ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
WORKSPACE_DIR = os.path.dirname(BASE_DIR)
AGRIGO_DIR = os.path.join(WORKSPACE_DIR, "sample", "AgriGo", "AgriGo")
SRC_DL_DIR = os.path.join(AGRIGO_DIR, "models", "DL_models")
SRC_ML_DIR = os.path.join(AGRIGO_DIR, "models", "ML_models")
SRC_DATASET = os.path.join(AGRIGO_DIR, "dataset")
# Primary augmented image dataset
AUGMENTED_DATASET_TRAIN = os.path.join(
WORKSPACE_DIR, "datasets",
"New Plant Diseases Dataset(Augmented)",
"New Plant Diseases Dataset(Augmented)", "train"
)
AUGMENTED_DATASET_VALID = os.path.join(
WORKSPACE_DIR, "datasets",
"New Plant Diseases Dataset(Augmented)",
"New Plant Diseases Dataset(Augmented)", "valid"
)
# Destination β backend/models/
DST_MODELS_DIR = os.path.join(BASE_DIR, "models")
DST_DL_DIR = os.path.join(DST_MODELS_DIR, "DL_models")
DST_ML_DIR = os.path.join(DST_MODELS_DIR, "ML_models")
os.makedirs(DST_DL_DIR, exist_ok=True)
os.makedirs(DST_ML_DIR, exist_ok=True)
# ββ Crop β class mapping (matches main.py exactly) βββββββββββββββββββββββββ
CROP_CLASS_MAP = {
"apple": ["Apple___Apple_scab", "Apple___Black_rot",
"Apple___Cedar_apple_rust", "Apple___healthy"],
"cherry": ["Cherry_(including_sour)___Powdery_mildew",
"Cherry_(including_sour)___healthy"],
"corn": ["Corn_(maize)___Cercospora_leaf_spot Gray_leaf_spot",
"Corn_(maize)___Common_rust_",
"Corn_(maize)___Northern_Leaf_Blight",
"Corn_(maize)___healthy"],
"grape": ["Grape___Black_rot", "Grape___Esca_(Black_Measles)",
"Grape___Leaf_blight_(Isariopsis_Leaf_Spot)", "Grape___healthy"],
"patato": ["Potato___Early_blight", "Potato___Late_blight", "Potato___healthy"],
"peach": ["Peach___Bacterial_spot", "Peach___healthy"],
"pepper": ["Pepper,_bell___Bacterial_spot", "Pepper,_bell___healthy"],
"strawberry": ["Strawberry___Leaf_scorch", "Strawberry___healthy"],
"tomato": ["Tomato___Bacterial_spot", "Tomato___Early_blight",
"Tomato___Late_blight", "Tomato___Leaf_Mold",
"Tomato___Septoria_leaf_spot",
"Tomato___Spider_mites Two-spotted_spider_mite",
"Tomato___Target_Spot",
"Tomato___Tomato_Yellow_Leaf_Curl_Virus",
"Tomato___Tomato_mosaic_virus", "Tomato___healthy"],
}
ALL_CROPS = list(CROP_CLASS_MAP.keys())
# =============================================================================
# STEP 1 β Copy pre-trained DL models from AgriGo sample
# =============================================================================
def copy_pretrained_dl_models(target_crops=None):
"""
Copies the pre-trained .h5 CNN models that ship with the AgriGo sample
project into backend/models/DL_models/.
These models were trained on PlantVillage with 224Γ224 input and achieve
~95% validation accuracy.
"""
print("\n" + "="*60)
print(" STEP 1: Copying pre-trained DL models from AgriGo sample")
print("="*60)
if not os.path.isdir(SRC_DL_DIR):
print(f"[ERROR] Source DL model directory not found:\n {SRC_DL_DIR}")
return False
crops_to_copy = target_crops if target_crops else ALL_CROPS
copied = 0
for crop in crops_to_copy:
src = os.path.join(SRC_DL_DIR, f"{crop}_model.h5")
dst = os.path.join(DST_DL_DIR, f"{crop}_model.h5")
if os.path.isfile(src):
shutil.copy2(src, dst)
size_mb = os.path.getsize(dst) / (1024 * 1024)
print(f" β {crop}_model.h5 ({size_mb:.1f} MB)")
copied += 1
else:
print(f" β {crop}_model.h5 β NOT FOUND at {src}")
print(f"\n Copied {copied}/{len(crops_to_copy)} DL models β {DST_DL_DIR}")
return copied > 0
# =============================================================================
# STEP 2 β Retrain ML models (crop & fertilizer recommenders)
# =============================================================================
def train_ml_models():
"""
Retrains the crop recommendation and fertilizer recommendation
Random Forest classifiers from the CSV datasets and saves them as
.pkl files in backend/models/ML_models/.
"""
print("\n" + "="*60)
print(" STEP 2: Training ML Recommendation Models")
print("="*60)
try:
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
except ImportError as e:
print(f"[ERROR] Missing Python package: {e}")
print(" Run: pip install pandas scikit-learn")
return False
# ββ 2a. Crop Recommender βββββββββββββββββββββββββββββββββββββββββββββ
print("\n [2a] Crop Recommender β loading dataset...")
crop_csv = os.path.join(SRC_DATASET, "Crop_recommendation.csv")
if not os.path.isfile(crop_csv):
print(f" [ERROR] Not found: {crop_csv}")
else:
df = pd.read_csv(crop_csv)
print(f" Loaded {len(df)} rows, columns: {list(df.columns)}")
CROPS_LIST = [
'apple', 'banana', 'blackgram', 'chickpea', 'coconut', 'coffee',
'cotton', 'grapes', 'jute', 'kidneybeans', 'lentil', 'maize',
'mango', 'mothbeans', 'mungbean', 'muskmelon', 'orange', 'papaya',
'pigeonpeas', 'pomegranate', 'rice', 'watermelon'
]
X = df[['N', 'P', 'K', 'temperature', 'humidity', 'ph', 'rainfall']].values
y = np.array([CROPS_LIST.index(c.lower().strip()) for c in df['label']])
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
model = RandomForestClassifier(
n_estimators=200, max_depth=None,
min_samples_split=2, random_state=42, n_jobs=-1
)
model.fit(X_scaled, y)
# Quick cross-val accuracy
scores = cross_val_score(model, X_scaled, y, cv=5, scoring='accuracy')
print(f" CV Accuracy: {scores.mean()*100:.2f}% Β± {scores.std()*100:.2f}%")
with open(os.path.join(DST_ML_DIR, "crop_scaler.pkl"), "wb") as f:
pickle.dump(scaler, f)
with open(os.path.join(DST_ML_DIR, "crop_model.pkl"), "wb") as f:
pickle.dump(model, f)
print(f" β crop_model.pkl + crop_scaler.pkl β {DST_ML_DIR}")
# ββ 2b. Fertilizer Recommender βββββββββββββββββββββββββββββββββββββββ
print("\n [2b] Fertilizer Recommender β loading dataset...")
fert_csv = os.path.join(SRC_DATASET, "Fertilizer Prediction.csv")
if not os.path.isfile(fert_csv):
print(f" [ERROR] Not found: {fert_csv}")
else:
df = pd.read_csv(fert_csv)
df.columns = [c.strip() for c in df.columns]
print(f" Loaded {len(df)} rows, columns: {list(df.columns)}")
FERTILIZER_CLASSES = ['10-26-26', '14-35-14', '17-17-17', '20-20', '28-28', 'DAP', 'Urea']
SOIL_MAP = {'Black': 0, 'Clayey': 1, 'Loamy': 2, 'Red': 3, 'Sandy': 4}
CROP_MAP = {
'Barley': 0, 'Cotton': 1, 'Ground Nuts': 2, 'Maize': 3,
'Millets': 4, 'Oil seeds': 5, 'Paddy': 6, 'Pulses': 7,
'Sugarcane': 8, 'Tobacco': 9, 'Wheat': 10
}
X_num = df[['Temparature', 'Humidity', 'Moisture',
'Nitrogen', 'Phosphorous', 'Potassium']].values
scaler = StandardScaler()
X_num_scaled = scaler.fit_transform(X_num)
soil_enc = np.array([SOIL_MAP[s.strip()] for s in df['Soil Type']]).reshape(-1, 1)
crop_enc = np.array([CROP_MAP[c.strip()] for c in df['Crop Type']]).reshape(-1, 1)
X_combined = np.concatenate([X_num_scaled, soil_enc, crop_enc], axis=1)
y = np.array([FERTILIZER_CLASSES.index(f.strip()) for f in df['Fertilizer Name']])
model = RandomForestClassifier(
n_estimators=200, max_depth=None,
min_samples_split=2, random_state=42, n_jobs=-1
)
model.fit(X_combined, y)
scores = cross_val_score(model, X_combined, y, cv=5, scoring='accuracy')
print(f" CV Accuracy: {scores.mean()*100:.2f}% Β± {scores.std()*100:.2f}%")
with open(os.path.join(DST_ML_DIR, "fertilizer_scaler.pkl"), "wb") as f:
pickle.dump(scaler, f)
with open(os.path.join(DST_ML_DIR, "fertilizer_model.pkl"), "wb") as f:
pickle.dump(model, f)
print(f" β fertilizer_model.pkl + fertilizer_scaler.pkl β {DST_ML_DIR}")
return True
# =============================================================================
# STEP 3 (OPTIONAL) β Retrain DL models from PlantVillage dataset
# =============================================================================
def retrain_dl_model(crop_key: str):
"""
Trains a CNN (MobileNetV2 transfer learning) for a single crop from the
augmented PlantVillage dataset. Input: 224Γ224, Output: per-crop softmax.
Saves to backend/models/DL_models/{crop_key}_model.h5
"""
print(f"\n [DL Retrain] Crop: {crop_key}")
try:
import tensorflow as tf
except ImportError:
print(" [ERROR] TensorFlow not installed. Run: pip install tensorflow")
return False
classes = CROP_CLASS_MAP[crop_key]
num_classes = len(classes)
IMG_SIZE = 224
BATCH = 32
EPOCHS = 15
# ββ Build per-crop image generators from the augmented dataset βββββββ
if not os.path.isdir(AUGMENTED_DATASET_TRAIN):
print(f" [ERROR] Dataset not found: {AUGMENTED_DATASET_TRAIN}")
return False
# Filter only the subdirs relevant to this crop
train_dirs = [d for d in os.listdir(AUGMENTED_DATASET_TRAIN) if d in classes]
if not train_dirs:
print(f" [WARN] No matching class folders found in train dir for {crop_key}")
print(f" Expected: {classes}")
return False
print(f" Classes found in dataset: {train_dirs}")
# Create a temporary symlinked directory with only this crop's classes
import tempfile, os
tmp_train = tempfile.mkdtemp(prefix=f"dl_train_{crop_key}_")
tmp_valid = tempfile.mkdtemp(prefix=f"dl_valid_{crop_key}_")
try:
for cls in classes:
src_t = os.path.join(AUGMENTED_DATASET_TRAIN, cls)
src_v = os.path.join(AUGMENTED_DATASET_VALID, cls)
if os.path.isdir(src_t):
# Use junctions on Windows to avoid copying gigabytes of data
dst_t = os.path.join(tmp_train, cls)
dst_v = os.path.join(tmp_valid, cls)
try:
os.symlink(src_t, dst_t)
except (OSError, NotImplementedError):
shutil.copytree(src_t, dst_t)
if os.path.isdir(src_v):
try:
os.symlink(src_v, dst_v)
except (OSError, NotImplementedError):
shutil.copytree(src_v, dst_v)
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.applications import MobileNetV2
from tensorflow.keras import layers, models, callbacks
datagen_train = ImageDataGenerator(
rescale=1.0/255,
rotation_range=15,
width_shift_range=0.1,
height_shift_range=0.1,
horizontal_flip=True,
zoom_range=0.1
)
datagen_valid = ImageDataGenerator(rescale=1.0/255)
train_gen = datagen_train.flow_from_directory(
tmp_train, target_size=(IMG_SIZE, IMG_SIZE),
batch_size=BATCH, classes=classes,
class_mode='categorical', shuffle=True
)
valid_gen = datagen_valid.flow_from_directory(
tmp_valid, target_size=(IMG_SIZE, IMG_SIZE),
batch_size=BATCH, classes=classes,
class_mode='categorical', shuffle=False
)
if train_gen.samples == 0:
print(f" [ERROR] No training images found for {crop_key}")
return False
print(f" Train samples: {train_gen.samples} | Valid samples: {valid_gen.samples}")
# ββ MobileNetV2 Transfer Learning βββββββββββββββββββββββββββββββββ
base = MobileNetV2(
input_shape=(IMG_SIZE, IMG_SIZE, 3),
include_top=False, weights='imagenet'
)
# Freeze base, train only top layers
base.trainable = False
model = models.Sequential([
base,
layers.GlobalAveragePooling2D(),
layers.BatchNormalization(),
layers.Dense(256, activation='relu'),
layers.Dropout(0.3),
layers.Dense(num_classes, activation='softmax')
])
model.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=1e-3),
loss='categorical_crossentropy',
metrics=['accuracy']
)
model.summary()
save_path = os.path.join(DST_DL_DIR, f"{crop_key}_model.h5")
cbs = [
callbacks.ModelCheckpoint(
save_path, monitor='val_accuracy',
save_best_only=True, verbose=1
),
callbacks.EarlyStopping(
monitor='val_loss', patience=4,
restore_best_weights=True, verbose=1
),
callbacks.ReduceLROnPlateau(
monitor='val_loss', factor=0.5,
patience=2, min_lr=1e-6, verbose=1
)
]
print(f"\n Training {crop_key} model ({EPOCHS} epochs max)...")
history = model.fit(
train_gen,
epochs=EPOCHS,
validation_data=valid_gen,
callbacks=cbs,
verbose=1
)
# Fine-tune: unfreeze last 30 layers
print("\n Fine-tuning last 30 layers of MobileNetV2...")
base.trainable = True
for layer in base.layers[:-30]:
layer.trainable = False
model.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=1e-5),
loss='categorical_crossentropy',
metrics=['accuracy']
)
model.fit(
train_gen,
epochs=5,
validation_data=valid_gen,
callbacks=cbs,
verbose=1
)
best_val_acc = max(history.history.get('val_accuracy', [0]))
print(f"\n β {crop_key}_model.h5 saved (best val_acc β {best_val_acc*100:.1f}%)")
return True
finally:
# Clean up temp symlink dirs
for d in [tmp_train, tmp_valid]:
try:
shutil.rmtree(d, ignore_errors=True)
except Exception:
pass
# =============================================================================
# Update main.py model paths to point to backend/models/
# =============================================================================
def update_main_py_paths():
"""
Patches main.py so DL_MODELS_DIR and ML_MODELS_DIR point to
backend/models/ instead of sample/AgriGo/...
"""
main_py = os.path.join(BASE_DIR, "main.py")
if not os.path.isfile(main_py):
return
with open(main_py, "r", encoding="utf-8") as f:
content = f.read()
new_dl = 'DL_MODELS_DIR = os.path.join(BASE_DIR, "models", "DL_models")'
new_ml = 'ML_MODELS_DIR = os.path.join(BASE_DIR, "models", "ML_models")'
# Replace the old AgriGo-relative paths
import re
content = re.sub(
r'DL_MODELS_DIR\s*=\s*os\.path\.join\(.*?DL_models.*?\)',
new_dl, content
)
content = re.sub(
r'ML_MODELS_DIR\s*=\s*os\.path\.join\(.*?ML_models.*?\)',
new_ml, content
)
# Remove AGRIGO_DIR, SAMPLE_DIR lines if present and replace with comment
content = re.sub(r'SAMPLE_DIR\s*=.*\n', '', content)
content = re.sub(r'AGRIGO_DIR\s*=.*\n', '', content)
with open(main_py, "w", encoding="utf-8") as f:
f.write(content)
print(f"\n β Updated model paths in main.py β backend/models/")
# =============================================================================
# Main Entry Point
# =============================================================================
def main():
parser = argparse.ArgumentParser(
description="AgriShield Model Setup β copy pre-trained DL + retrain ML models"
)
parser.add_argument(
"--retrain", action="store_true",
help="Also retrain DL models from PlantVillage dataset (slow on CPU)"
)
parser.add_argument(
"--crop", type=str, default=None,
help=f"Retrain a single crop only. Choices: {ALL_CROPS}"
)
parser.add_argument(
"--ml-only", action="store_true",
help="Only retrain ML models, skip DL copy/train"
)
args = parser.parse_args()
print("\n" + "="*60)
print(" AgriShield β Model Setup")
print("="*60)
print(f" Backend dir : {BASE_DIR}")
print(f" Output dir : {DST_MODELS_DIR}")
if not args.ml_only:
if args.retrain:
# Retrain DL from scratch
crops_to_train = [args.crop] if args.crop else ALL_CROPS
for crop in crops_to_train:
if crop not in CROP_CLASS_MAP:
print(f" [ERROR] Unknown crop '{crop}'. Choices: {ALL_CROPS}")
continue
retrain_dl_model(crop)
else:
# Copy pre-trained models (fast)
copy_pretrained_dl_models()
# Always retrain ML models (takes only seconds)
train_ml_models()
# Patch main.py paths
update_main_py_paths()
print("\n" + "="*60)
print(" Setup complete! Models are in:")
print(f" DL models : {DST_DL_DIR}")
print(f" ML models : {DST_ML_DIR}")
print("\n Start the backend with:")
print(" uvicorn main:app --host 0.0.0.0 --port 8000 --reload")
print("="*60 + "\n")
if __name__ == "__main__":
main()
|