Upload inference_example.py with huggingface_hub
Browse files- inference_example.py +114 -0
inference_example.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
AgriBot Maize Disease Diagnosis - Inference Example
|
| 3 |
+
Ekip Crusaders - AYITI IA 2025 Hackathon
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import joblib
|
| 7 |
+
import torch
|
| 8 |
+
import numpy as np
|
| 9 |
+
from PIL import Image
|
| 10 |
+
from torchvision import models, transforms
|
| 11 |
+
import sys
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class AgribotInference:
|
| 16 |
+
"""Wrapper class for AgriBot model inference"""
|
| 17 |
+
|
| 18 |
+
def __init__(self, model_path='agribot_models.pkl'):
|
| 19 |
+
print("Loading AgriBot model...")
|
| 20 |
+
self.model = joblib.load(model_path)
|
| 21 |
+
|
| 22 |
+
print("Loading MobileNetV2 feature extractor...")
|
| 23 |
+
self.mobilenet = models.mobilenet_v2(pretrained=True)
|
| 24 |
+
self.mobilenet.classifier = torch.nn.Identity()
|
| 25 |
+
self.mobilenet.eval()
|
| 26 |
+
|
| 27 |
+
self.class_labels = [
|
| 28 |
+
"Cercospora Leaf Spot (Gray Leaf Spot)",
|
| 29 |
+
"Common Rust",
|
| 30 |
+
"Northern Leaf Blight",
|
| 31 |
+
"Healthy",
|
| 32 |
+
"Other"
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
self.transform = transforms.Compose([
|
| 36 |
+
transforms.Resize((224, 224)),
|
| 37 |
+
transforms.ToTensor(),
|
| 38 |
+
transforms.Normalize(
|
| 39 |
+
mean=[0.485, 0.456, 0.406],
|
| 40 |
+
std=[0.229, 0.224, 0.225]
|
| 41 |
+
)
|
| 42 |
+
])
|
| 43 |
+
|
| 44 |
+
print("Model loaded successfully!")
|
| 45 |
+
|
| 46 |
+
def preprocess_image(self, image_path):
|
| 47 |
+
image = Image.open(image_path).convert('RGB')
|
| 48 |
+
return self.transform(image).unsqueeze(0)
|
| 49 |
+
|
| 50 |
+
def extract_features(self, img_tensor):
|
| 51 |
+
with torch.no_grad():
|
| 52 |
+
features = self.mobilenet(img_tensor)
|
| 53 |
+
return features.numpy()
|
| 54 |
+
|
| 55 |
+
def predict(self, image_path):
|
| 56 |
+
img_tensor = self.preprocess_image(image_path)
|
| 57 |
+
features = self.extract_features(img_tensor)
|
| 58 |
+
|
| 59 |
+
prediction_idx = self.model.predict(features)[0]
|
| 60 |
+
probabilities = self.model.predict_proba(features)[0]
|
| 61 |
+
confidence = float(np.max(probabilities) * 100)
|
| 62 |
+
diagnosis = self.class_labels[prediction_idx]
|
| 63 |
+
|
| 64 |
+
prob_dist = {
|
| 65 |
+
label: float(prob * 100)
|
| 66 |
+
for label, prob in zip(self.class_labels, probabilities)
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
return {
|
| 70 |
+
'diagnosis': diagnosis,
|
| 71 |
+
'confidence': round(confidence, 2),
|
| 72 |
+
'prediction_index': int(prediction_idx),
|
| 73 |
+
'probabilities': prob_dist,
|
| 74 |
+
'is_healthy': diagnosis == "Healthy",
|
| 75 |
+
'is_maize': diagnosis != "Other"
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def main():
|
| 80 |
+
if len(sys.argv) < 2:
|
| 81 |
+
print("Usage: python inference_example.py <image_path>")
|
| 82 |
+
print("Example: python inference_example.py maize_leaf.jpg")
|
| 83 |
+
sys.exit(1)
|
| 84 |
+
|
| 85 |
+
image_path = sys.argv[1]
|
| 86 |
+
|
| 87 |
+
if not Path(image_path).exists():
|
| 88 |
+
print(f"Error: Image file '{image_path}' not found!")
|
| 89 |
+
sys.exit(1)
|
| 90 |
+
|
| 91 |
+
predictor = AgribotInference()
|
| 92 |
+
|
| 93 |
+
print(f"\nAnalyzing image: {image_path}")
|
| 94 |
+
print("-" * 50)
|
| 95 |
+
|
| 96 |
+
result = predictor.predict(image_path)
|
| 97 |
+
|
| 98 |
+
print(f"\n🌽 DIAGNOSIS: {result['diagnosis']}")
|
| 99 |
+
print(f"📊 Confidence: {result['confidence']:.2f}%")
|
| 100 |
+
print(f"🔍 Is Maize: {'Yes' if result['is_maize'] else 'No'}")
|
| 101 |
+
print(f"✅ Is Healthy: {'Yes' if result['is_healthy'] else 'No'}")
|
| 102 |
+
|
| 103 |
+
print("\n📈 Probability Distribution:")
|
| 104 |
+
for disease, prob in result['probabilities'].items():
|
| 105 |
+
bar_length = int(prob / 2)
|
| 106 |
+
bar = "█" * bar_length
|
| 107 |
+
print(f" {disease:40s} {prob:6.2f}% {bar}")
|
| 108 |
+
|
| 109 |
+
print("\n" + "-" * 50)
|
| 110 |
+
print("Analysis complete!")
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
if __name__ == "__main__":
|
| 114 |
+
main()
|