Spaces:
Sleeping
Sleeping
File size: 7,971 Bytes
818ceb3 c7401d9 818ceb3 c7401d9 818ceb3 c7401d9 818ceb3 c7401d9 818ceb3 c7401d9 818ceb3 c7401d9 818ceb3 c7401d9 818ceb3 c7401d9 818ceb3 cc721f8 824fa39 d0e98fd 824fa39 818ceb3 824fa39 d0e98fd 824fa39 d0e98fd 818ceb3 d0e98fd 0f667f6 d0e98fd c7401d9 d0e98fd c7401d9 0f667f6 d0e98fd c7401d9 0f667f6 c7401d9 cc721f8 c7401d9 0f667f6 c7401d9 cc721f8 d0e98fd c7401d9 0f667f6 c7401d9 cc721f8 0f667f6 cc721f8 c7401d9 0f667f6 c7401d9 824fa39 d0e98fd 0f667f6 818ceb3 0f667f6 818ceb3 c7401d9 0f667f6 c7401d9 818ceb3 824fa39 818ceb3 824fa39 c7401d9 0f667f6 e12c2ed 0f667f6 e12c2ed 0f667f6 c7401d9 0f667f6 824fa39 0f667f6 824fa39 818ceb3 cc721f8 818ceb3 824fa39 0f667f6 d0e98fd e12c2ed 818ceb3 c7401d9 | 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 | # import gradio as gr
# from transformers import AutoImageProcessor, AutoModelForImageClassification
# from PIL import Image
# import torch
# # Model you selected
# MODEL_NAME = "google/vit-base-patch16-224"
# print("π Loading model...")
# processor = AutoImageProcessor.from_pretrained(MODEL_NAME)
# model = AutoModelForImageClassification.from_pretrained(MODEL_NAME)
# print("β
Model loaded successfully!")
# def classify_image(image):
# try:
# img = Image.fromarray(image).convert("RGB")
# inputs = processor(images=img, return_tensors="pt")
# with torch.no_grad():
# outputs = model(**inputs)
# logits = outputs.logits
# pred_id = logits.argmax(-1).item()
# label = model.config.id2label[pred_id]
# return {label: float(logits.softmax(-1)[0][pred_id])}
# except Exception as e:
# return {"error": str(e)}
# # UI
# interface = gr.Interface(
# fn=classify_image,
# inputs=gr.Image(type="numpy"),
# outputs=gr.Label(num_top_classes=5),
# title="πΏ KrishiSetu β Crop Disease Classifier",
# description="Upload leaf images. The model uses `google/vit-base-patch16-224` to classify plant diseases.",
# )
# if __name__ == "__main__":
# interface.launch()
# import gradio as gr
# from transformers import (
# AutoImageProcessor,
# AutoModelForImageClassification,
# pipeline
# )
# from PIL import Image
# import torch
# MODEL_NAME = "google/vit-base-patch16-224"
# processor = AutoImageProcessor.from_pretrained(MODEL_NAME)
# model = AutoModelForImageClassification.from_pretrained(MODEL_NAME)
# validator = pipeline(
# "zero-shot-image-classification",
# model="openai/clip-vit-base-patch32"
# )
# def is_valid_leaf_image(img):
# candidate_labels = [
# "a plant leaf",
# "a plant",
# "tree leaves",
# "crop leaf",
# "person",
# "animal",
# "vehicle",
# "food",
# "object"
# ]
# result = validator(img, candidate_labels=candidate_labels)
# top_label = result[0]["label"]
# top_score = result[0]["score"]
# valid_labels = ["a plant leaf", "a plant", "tree leaves", "crop leaf"]
# return top_label in valid_labels and top_score >= 0.30
# def classify_image(image):
# try:
# img = Image.fromarray(image).convert("RGB")
# # Step 1: Validation
# if not is_valid_leaf_image(img):
# return "β Invalid input, please send image containing plant and leaf", None
# # Step 2: Prediction
# inputs = processor(images=img, return_tensors="pt")
# with torch.no_grad():
# outputs = model(**inputs)
# probs = torch.nn.functional.softmax(outputs.logits, dim=-1)[0]
# top_k = torch.topk(probs, k=5)
# results = {}
# for score, idx in zip(top_k.values, top_k.indices):
# label = model.config.id2label[idx.item()]
# results[label] = float(score)
# return "β
Valid leaf image", results
# except Exception as e:
# return f"Error: {str(e)}", None
# interface = gr.Interface(
# fn=classify_image,
# inputs=gr.Image(type="numpy"),
# outputs=[
# gr.Textbox(label="Status"),
# gr.Label(num_top_classes=5, label="Prediction")
# ],
# title="πΏ KrishiSetu β Crop Disease Classifier",
# description="Upload leaf images. Invalid images will be rejected.",
# )
# if __name__ == "__main__":
# interface.launch()
import gradio as gr
from transformers import AutoImageProcessor, CLIPForImageClassification, pipeline
from PIL import Image
import torch
MODEL_NAME = "VaigandlaHemanth/leaf-disease-clip-vit"
print("Loading disease model...")
processor = AutoImageProcessor.from_pretrained(MODEL_NAME)
model = CLIPForImageClassification.from_pretrained(MODEL_NAME)
model.eval()
print("Disease model loaded successfully!")
print("Loading validator model...")
validator = pipeline(
"zero-shot-image-classification",
model="openai/clip-vit-base-patch32"
)
print("Validator model loaded successfully!")
def is_valid_leaf_image(img):
candidate_labels = [
"a plant leaf",
"a crop leaf",
"a diseased leaf",
"a healthy leaf",
"a plant",
"tree leaves",
"person",
"animal",
"vehicle",
"food",
"building",
"random object"
]
result = validator(img, candidate_labels=candidate_labels)
top_label = result[0]["label"]
top_score = result[0]["score"]
valid_labels = [
"a plant leaf",
"a crop leaf",
"a diseased leaf",
"a healthy leaf",
"a plant",
"tree leaves"
]
return top_label in valid_labels and top_score >= 0.30, top_label, top_score
def clean_label(label):
return label.replace("___", " - ").replace("_", " ")
def get_confidence_status(confidence):
if confidence >= 0.70:
return "High confidence"
elif confidence >= 0.40:
return "Medium confidence"
else:
return "Low confidence"
def classify_image(image):
try:
if image is None:
return "Please upload an image."
img = Image.fromarray(image).convert("RGB")
is_valid, detected_type, validation_score = is_valid_leaf_image(img)
if not is_valid:
return (
"Invalid input, please send image containing plant and leaf\n\n"
f"Detected image type: {detected_type}\n"
f"Validation confidence: {validation_score * 100:.2f}%"
)
inputs = processor(images=img, return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
probs = torch.nn.functional.softmax(outputs.logits, dim=-1)[0]
top_k = torch.topk(probs, k=5)
predictions = []
for score, idx in zip(top_k.values, top_k.indices):
raw_label = model.config.id2label[idx.item()]
label = clean_label(raw_label)
confidence = float(score)
predictions.append((label, confidence))
top_label, top_confidence = predictions[0]
confidence_status = get_confidence_status(top_confidence)
response = ""
response += "Image validation: Valid plant/leaf image\n"
response += f"Validator detected: {detected_type} ({validation_score * 100:.2f}%)\n\n"
if top_confidence < 0.30:
response += "Final result: Disease/health prediction is uncertain\n"
response += (
"Reason: The image is a valid plant/leaf image, but model confidence is low. "
"Please upload a clear close-up image of a single leaf with plain background.\n\n"
)
elif "healthy" in top_label.lower():
response += f"Final result: Healthy plant ({top_confidence * 100:.2f}%)\n"
response += f"Confidence level: {confidence_status}\n\n"
else:
response += "Final result: Disease detected\n"
response += f"Disease name: {top_label}\n"
response += f"Confidence: {top_confidence * 100:.2f}%\n"
response += f"Confidence level: {confidence_status}\n\n"
response += "Top 5 predictions:\n"
for i, (label, confidence) in enumerate(predictions, start=1):
response += f"{i}. {label}: {confidence * 100:.2f}%\n"
return response
except Exception as e:
return f"Error: {str(e)}"
interface = gr.Interface(
fn=classify_image,
inputs=gr.Image(type="numpy"),
outputs=gr.Textbox(label="Result", lines=12),
title="KrishiSetu β Crop Disease Classifier",
description=(
"Upload plant/leaf image. Invalid images will be rejected. "
"Valid images will show disease/healthy result with top predictions."
)
)
if __name__ == "__main__":
interface.launch() |