File size: 14,376 Bytes
ad0abab 98652ba ad0abab 76d7049 98652ba ad0abab 76d7049 ad0abab 76d7049 ad0abab 76d7049 ad0abab 76d7049 ad0abab 76d7049 ad0abab 76d7049 98652ba ad0abab 98652ba ad0abab 76d7049 ad0abab 98652ba ad0abab 98652ba ad0abab 98652ba ad0abab 98652ba ad0abab 98652ba ad0abab 98652ba ad0abab 98652ba ad0abab 98652ba ad0abab 98652ba ad0abab 98652ba ad0abab 98652ba ad0abab 98652ba ad0abab 98652ba ad0abab 98652ba ad0abab 98652ba ad0abab 98652ba ad0abab 98652ba ad0abab 98652ba ad0abab 98652ba ad0abab 98652ba ad0abab 98652ba ad0abab 98652ba ad0abab 98652ba ad0abab 98652ba | 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 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 | from transformers import (
ViTImageProcessor,
ViTForImageClassification,
CLIPProcessor,
CLIPModel
)
from PIL import Image
import torch
from src.config import MODEL_NAME
# ============================================================
# GLOBAL VARIABLES
# ============================================================
processor = None
model = None
# Validity gate
clip_processor = None
clip_model = None
device = torch.device(
"cuda" if torch.cuda.is_available() else "cpu"
)
# ============================================================
# LOAD DISEASE CLASSIFIER
# ============================================================
def load_model():
"""Load ViT disease classifier."""
global processor, model
if processor is None or model is None:
print(f"Loading disease model: {MODEL_NAME}")
processor = ViTImageProcessor.from_pretrained(
MODEL_NAME
)
model = ViTForImageClassification.from_pretrained(
MODEL_NAME
)
model = model.to(device)
model.eval()
print(
f"Disease model loaded on device: {device}"
)
return processor, model
# ============================================================
# LOAD VALIDITY GATE
# ============================================================
def load_validity_gate():
"""
Load CLIP model used to determine whether the
uploaded image looks like a supported crop leaf.
"""
global clip_processor, clip_model
if clip_processor is None or clip_model is None:
print("Loading CropPilot validity gate...")
clip_model_name = "openai/clip-vit-base-patch32"
clip_processor = CLIPProcessor.from_pretrained(
clip_model_name
)
clip_model = CLIPModel.from_pretrained(
clip_model_name
)
clip_model = clip_model.to(device)
clip_model.eval()
print(
f"Validity gate loaded on device: {device}"
)
return clip_processor, clip_model
# ============================================================
# VALIDITY GATE
# ============================================================
def check_image_validity(image):
"""
Determine whether the uploaded image appears to be
a supported crop leaf.
Returns:
dict containing:
is_valid
validity_confidence
valid_score
invalid_score
"""
clip_processor, clip_model = load_validity_gate()
image = image.convert("RGB")
# --------------------------------------------------------
# VALID IMAGE PROMPTS
# --------------------------------------------------------
valid_prompts = [
"a clear photograph of a corn leaf",
"a clear photograph of a potato leaf",
"a clear photograph of a rice leaf",
"a clear photograph of a wheat leaf",
"a close-up photograph of a corn plant leaf",
"a close-up photograph of a potato plant leaf",
"a close-up photograph of a rice plant leaf",
"a close-up photograph of a wheat plant leaf",
"a photograph of a diseased crop leaf",
"a photograph of a healthy crop leaf"
]
# --------------------------------------------------------
# INVALID IMAGE PROMPTS
# --------------------------------------------------------
invalid_prompts = [
"a photograph of a dog",
"a photograph of a cat",
"a photograph of a person",
"a photograph of a car",
"a photograph of a building",
"a photograph of food",
"a photograph of cooked corn",
"a photograph of a corn cob",
"a photograph of harvested grains",
"a photograph of a landscape",
"a photograph of a random object",
"a photograph that does not contain a plant leaf",
"a photograph of an unrelated plant"
]
all_prompts = valid_prompts + invalid_prompts
# --------------------------------------------------------
# CLIP PROCESSING
# --------------------------------------------------------
inputs = clip_processor(
text=all_prompts,
images=image,
return_tensors="pt",
padding=True
)
inputs = {
key: value.to(device)
for key, value in inputs.items()
}
with torch.no_grad():
outputs = clip_model(**inputs)
logits = outputs.logits_per_image[0]
# --------------------------------------------------------
# SPLIT VALID / INVALID SCORES
# --------------------------------------------------------
valid_logits = logits[:len(valid_prompts)]
invalid_logits = logits[len(valid_prompts):]
# Use strongest matching prompt from each group
valid_score = valid_logits.max().item()
invalid_score = invalid_logits.max().item()
# Difference between valid and invalid
score_difference = valid_score - invalid_score
# Convert difference to 0-1 value
validity_confidence = torch.sigmoid(
torch.tensor(score_difference)
).item()
# Conservative initial threshold
is_valid = (
validity_confidence >= 0.60
and valid_score > invalid_score
)
print(
f"Validity score: {validity_confidence:.3f}"
)
print(
f"Valid CLIP score: {valid_score:.3f}"
)
print(
f"Invalid CLIP score: {invalid_score:.3f}"
)
print(
f"Image accepted: {is_valid}"
)
return {
"is_valid": is_valid,
"validity_confidence": round(
validity_confidence,
3
),
"valid_score": valid_score,
"invalid_score": invalid_score
}
# ============================================================
# DISEASE CLASSIFICATION
# ============================================================
def classify_disease(image_path: str) -> dict:
"""
Classify plant disease from image.
Pipeline:
Image
β
Validity Gate
β
ViT Disease Classifier
"""
# --------------------------------------------------------
# LOAD IMAGE
# --------------------------------------------------------
image = Image.open(
image_path
).convert("RGB")
# ========================================================
# STEP 1 β VALIDITY GATE
# ========================================================
validity_result = check_image_validity(
image
)
# --------------------------------------------------------
# INVALID IMAGE
# --------------------------------------------------------
if not validity_result["is_valid"]:
print(
"β Image rejected by validity gate."
)
return {
"status": "invalid",
"message": (
"β οΈ Unable to Diagnose\n\n"
"This image could not be identified as a\n"
"supported crop leaf.\n\n"
"Please upload a clear image of:\n\n"
"π½ Corn\n"
"π₯ Potato\n"
"πΎ Rice\n"
"πΎ Wheat"
),
"validity_confidence":
validity_result[
"validity_confidence"
]
}
# ========================================================
# STEP 2 β LOAD DISEASE MODEL
# ========================================================
processor, model = load_model()
# ========================================================
# STEP 3 β PROCESS IMAGE
# ========================================================
inputs = processor(
images=image,
return_tensors="pt"
)
inputs = {
key: value.to(device)
for key, value in inputs.items()
}
# ========================================================
# STEP 4 β VIΠ’ PREDICTION
# ========================================================
with torch.no_grad():
logits = model(
**inputs
).logits
# ========================================================
# STEP 5 β SOFTMAX
# ========================================================
probs = torch.softmax(
logits,
dim=-1
)[0]
# ========================================================
# STEP 6 β CHECK INVALID CLASS
# ========================================================
invalid_id = None
for idx, label in model.config.id2label.items():
if label.lower().strip() == "invalid":
invalid_id = int(idx)
break
# --------------------------------------------------------
# If model itself predicts Invalid
# --------------------------------------------------------
if invalid_id is not None:
invalid_probability = probs[
invalid_id
].item()
print(
f"Model Invalid probability: "
f"{invalid_probability:.3f}"
)
else:
invalid_probability = 0.0
# ========================================================
# STEP 7 β GET TOP VALID CLASS
# ========================================================
valid_predictions = []
for idx, prob in enumerate(probs):
label = model.config.id2label[
idx
]
# DO NOT allow Invalid to become
# a disease diagnosis
if (
label.lower().strip()
== "invalid"
):
continue
valid_predictions.append({
"label": label,
"confidence": round(
prob.item(),
3
)
})
# Sort highest confidence first
valid_predictions.sort(
key=lambda x: x["confidence"],
reverse=True
)
# ========================================================
# STEP 8 β NO VALID CLASS
# ========================================================
if not valid_predictions:
return {
"status": "invalid",
"message": (
"β οΈ Unable to Diagnose\n\n"
"No supported crop disease "
"could be identified."
)
}
# ========================================================
# STEP 9 β TOP PREDICTION
# ========================================================
top_prediction = valid_predictions[0]
confidence = top_prediction[
"confidence"
]
print(
f"Top prediction: "
f"{top_prediction['label']}"
)
print(
f"Confidence: {confidence}"
)
# ========================================================
# STEP 10 β CLASSIFIER CONFIDENCE CHECK
# ========================================================
CLASSIFIER_THRESHOLD = 0.50
if confidence < CLASSIFIER_THRESHOLD:
return {
"status": "uncertain",
"message": (
"β οΈ Diagnosis Uncertain\n\n"
"The image appears to contain "
"a supported crop leaf, but the "
"disease classification is uncertain.\n\n"
f"Confidence: {confidence:.1%}\n\n"
"Please upload a clearer image "
"of the affected leaf."
),
"top_prediction": top_prediction,
"confidence": confidence
}
# ========================================================
# STEP 11 β TOP 3 ALTERNATIVES
# ========================================================
top3 = valid_predictions[:3]
for pred in top3:
print(
f"Prediction: {pred['label']} "
f"| Confidence: "
f"{pred['confidence']}"
)
# ========================================================
# STEP 12 β RETURN SUCCESS
# ========================================================
return {
"status": "success",
"top_prediction": top3[0],
"alternatives": (
top3[1:]
if len(top3) > 1
else []
),
"confidence": confidence,
"validity_confidence":
validity_result[
"validity_confidence"
]
}
# ============================================================
# LABEL PARSER
# ============================================================
def parse_label(raw_label: str) -> tuple:
print(
f"Parsing label: '{raw_label}'"
)
if "___" in raw_label:
parts = raw_label.split(
"___"
)
crop = parts[0].replace(
"_",
" "
).strip()
disease = parts[1].replace(
"_",
" "
).strip()
elif " - " in raw_label:
parts = raw_label.split(
" - "
)
crop = parts[0].strip()
disease = (
parts[1].strip()
if len(parts) > 1
else "Unknown"
)
elif " with " in raw_label.lower():
parts = raw_label.split(
" with "
)
crop = parts[0].strip()
disease = (
parts[1].strip()
if len(parts) > 1
else "Unknown"
)
else:
full = raw_label.replace(
"_",
" "
).strip()
if "healthy" in full.lower():
crop = (
full.lower()
.replace(
"healthy",
""
)
.strip()
.title()
)
disease = "Healthy"
else:
words = full.split()
if len(words) >= 2:
crop = words[0].title()
disease = " ".join(
words[1:]
)
else:
crop = "Unknown"
disease = full
# Handle Invalid
if (
crop.lower() == "invalid"
or
disease.lower() == "invalid"
):
crop = "Unknown"
disease = "Unknown Disease"
print(
f"Parsed -> Crop: '{crop}', "
f"Disease: '{disease}'"
)
return crop, disease |