Spaces:
Sleeping
Sleeping
Upload 17 files
Browse files- .gitattributes +1 -0
- __init__.py +0 -0
- app.py +51 -0
- checkpoints/epoch=12-step=10504.ckpt +3 -0
- checkpoints/epoch=14-step=12120.ckpt +3 -0
- requirements.txt +7 -0
- test_images/leaf_curl.jpeg +0 -0
- test_images/mosaic2.jpeg +0 -0
- test_images/mosaic_1.jpg +3 -0
- test_images/powdery_mildew1.jpeg +0 -0
- test_images/powdery_mildew2.jpeg +0 -0
- test_images/septoria1.jpeg +0 -0
- test_images/septoria2.jpeg +0 -0
- training notebooks/disease-classifier-efficientnetb0-acc-95.ipynb +0 -0
- utils/__init__.py +0 -0
- utils/__pycache__/__init__.cpython-310.pyc +0 -0
- utils/__pycache__/utils.cpython-310.pyc +0 -0
- utils/utils.py +117 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
test_images/mosaic_1.jpg filter=lfs diff=lfs merge=lfs -text
|
__init__.py
ADDED
|
File without changes
|
app.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import numpy as np
|
| 3 |
+
import matplotlib.pyplot as plt
|
| 4 |
+
from matplotlib import image
|
| 5 |
+
plt.style.use("fivethirtyeight")
|
| 6 |
+
import PIL
|
| 7 |
+
from PIL import Image
|
| 8 |
+
from PIL import ImageFile
|
| 9 |
+
from matplotlib import image
|
| 10 |
+
|
| 11 |
+
import os, shutil, tqdm
|
| 12 |
+
from tqdm.auto import tqdm, trange
|
| 13 |
+
import gradio as gr
|
| 14 |
+
|
| 15 |
+
import torch, torchvision
|
| 16 |
+
import torch.nn as nn
|
| 17 |
+
from torchvision.transforms import v2 as v2
|
| 18 |
+
import lightning.pytorch as pl
|
| 19 |
+
from lightning.pytorch import LightningModule, LightningDataModule
|
| 20 |
+
|
| 21 |
+
ImageFile.LOAD_TRUNCATED_IMAGES = True
|
| 22 |
+
|
| 23 |
+
import utils
|
| 24 |
+
from utils.utils import prepare_image, make_preds_return_class_class_confidence_dict, load_model
|
| 25 |
+
|
| 26 |
+
def run_gradio_app():
|
| 27 |
+
def return_class_x_label_conf_dict(img_path_):
|
| 28 |
+
lightning_model = load_model()
|
| 29 |
+
image = prepare_image(img_path = img_path_)
|
| 30 |
+
class_, label_conf_dict = make_preds_return_class_class_confidence_dict(img = image, model = lightning_model)
|
| 31 |
+
return f"Predicted class: {class_}", label_conf_dict
|
| 32 |
+
|
| 33 |
+
title = "Tomato Leaf Disease Classification with Prediction Confidence Visualization"
|
| 34 |
+
description = "This intuitive interface simplifies the process of diagnosing diseases in tomato plants using leaf imagery. \
|
| 35 |
+
By uploading a clear image of a tomato leaf, the application leverages a trained deep learning classifier to \
|
| 36 |
+
identify the most likely disease affecting the plant. The system returns the top predicted class, along with a \
|
| 37 |
+
ranked list of the top 5 possible diseases and their associated confidence scores. This layered feedback ensures \
|
| 38 |
+
users not only receive a diagnosis but also understand the certainty of each prediction.\n \
|
| 39 |
+
- Please ensure that uploaded images are of individual leaves with minimal background clutter for optimal accuracy.\n \
|
| 40 |
+
- The model was trained on a curated dataset of common tomato leaf diseases and performs best on clear, close-up images."
|
| 41 |
+
|
| 42 |
+
demo = gr.Interface(fn = return_class_x_label_conf_dict, inputs = [gr.Image(type = "pil", label = "Upload Image of Tomato Leaf here:")],
|
| 43 |
+
outputs=[gr.Textbox(label = "Predicted Disease Class"), gr.Label(label = "Top 5 Predicted Class Probability distribution")],
|
| 44 |
+
title = title,
|
| 45 |
+
description=description,
|
| 46 |
+
theme = gr.themes.Ocean())
|
| 47 |
+
demo.launch(share = False)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
if __name__ == "__main__":
|
| 51 |
+
run_gradio_app()
|
checkpoints/epoch=12-step=10504.ckpt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:032609b3a66633165b3449dab7fd3e97cd110757484ffa0f6bf891aefd88872a
|
| 3 |
+
size 48743457
|
checkpoints/epoch=14-step=12120.ckpt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:decb1b5d45cd85450772c07dc7415a7471bbf15e8df2d17d17f3c7cb18a3b632
|
| 3 |
+
size 48743457
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
matplotlib
|
| 3 |
+
gradio
|
| 4 |
+
numpy
|
| 5 |
+
pandas
|
| 6 |
+
lightning
|
| 7 |
+
pillow
|
test_images/leaf_curl.jpeg
ADDED
|
test_images/mosaic2.jpeg
ADDED
|
test_images/mosaic_1.jpg
ADDED
|
Git LFS Details
|
test_images/powdery_mildew1.jpeg
ADDED
|
test_images/powdery_mildew2.jpeg
ADDED
|
test_images/septoria1.jpeg
ADDED
|
test_images/septoria2.jpeg
ADDED
|
training notebooks/disease-classifier-efficientnetb0-acc-95.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
utils/__init__.py
ADDED
|
File without changes
|
utils/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (204 Bytes). View file
|
|
|
utils/__pycache__/utils.cpython-310.pyc
ADDED
|
Binary file (4.79 kB). View file
|
|
|
utils/utils.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import numpy as np
|
| 3 |
+
import matplotlib.pyplot as plt
|
| 4 |
+
from matplotlib import image
|
| 5 |
+
plt.style.use("fivethirtyeight")
|
| 6 |
+
import PIL
|
| 7 |
+
from PIL import Image
|
| 8 |
+
from PIL import ImageFile
|
| 9 |
+
from matplotlib import image
|
| 10 |
+
|
| 11 |
+
import os, shutil, tqdm
|
| 12 |
+
from tqdm.auto import tqdm, trange
|
| 13 |
+
import pathlib
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
import torch, torchvision, torchmetrics
|
| 17 |
+
import torch.nn as nn
|
| 18 |
+
from torchvision.transforms import v2 as v2
|
| 19 |
+
import lightning.pytorch as pl
|
| 20 |
+
from lightning.pytorch import LightningModule, LightningDataModule
|
| 21 |
+
|
| 22 |
+
ImageFile.LOAD_TRUNCATED_IMAGES = True
|
| 23 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
current_file = Path(__file__).resolve()
|
| 27 |
+
checkpoint_path = current_file.parent.parent / "checkpoints" / "epoch=14-step=12120.ckpt"
|
| 28 |
+
|
| 29 |
+
transform = v2.Compose(
|
| 30 |
+
[
|
| 31 |
+
v2.Resize(size = (224, 224)),
|
| 32 |
+
v2.ToImage(),
|
| 33 |
+
v2.ToDtype(dtype = torch.float32, scale = True),
|
| 34 |
+
v2.Normalize(
|
| 35 |
+
mean=[0.485, 0.456, 0.406],
|
| 36 |
+
std=[0.229, 0.224, 0.225]
|
| 37 |
+
)
|
| 38 |
+
]
|
| 39 |
+
)
|
| 40 |
+
idx_to_class = {0: 'Leaf mold',
|
| 41 |
+
1: 'Tomato mosaic virus',
|
| 42 |
+
2: 'Powdery mildew',
|
| 43 |
+
3: 'Spider mites',
|
| 44 |
+
4: 'Bacterial spot',
|
| 45 |
+
5: 'Early blight',
|
| 46 |
+
6: 'Healthy',
|
| 47 |
+
7: 'Late blight',
|
| 48 |
+
8: 'Tomato yellow leaf curl virus',
|
| 49 |
+
9: 'Septoria leaf spot',
|
| 50 |
+
10: 'Target spot'}
|
| 51 |
+
|
| 52 |
+
def prepare_image(img_path):
|
| 53 |
+
image_ = transform(img_path).unsqueeze(0)
|
| 54 |
+
return image_
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def make_preds_return_class_class_confidence_dict(img, model):
|
| 58 |
+
model.eval()
|
| 59 |
+
with torch.inference_mode():
|
| 60 |
+
logits = model(img)
|
| 61 |
+
|
| 62 |
+
pred_probs = torch.softmax(logits, dim = 1)
|
| 63 |
+
pred_probs_df = pd.DataFrame(data = torch.softmax(logits, dim = 1).numpy(), columns = idx_to_class.values())
|
| 64 |
+
class_ = idx_to_class[torch.argmax(pred_probs, axis = 1).item()]
|
| 65 |
+
pred_probs_df = pred_probs_df.T
|
| 66 |
+
pred_probs_df.columns = ["confidence"]
|
| 67 |
+
pred_probs_df = pred_probs_df.sort_values("confidence", ascending = False).head(5)
|
| 68 |
+
label_dict = dict()
|
| 69 |
+
for disease, confidence in zip(pred_probs_df.index, pred_probs_df["confidence"].values):
|
| 70 |
+
label_dict[disease] = confidence
|
| 71 |
+
return class_, label_dict
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def load_model():
|
| 75 |
+
class myLightningModel(pl.LightningModule):
|
| 76 |
+
def __init__(self, model, lr):
|
| 77 |
+
super().__init__()
|
| 78 |
+
self.model = model
|
| 79 |
+
self.lr = lr
|
| 80 |
+
self.loss_fn = nn.CrossEntropyLoss()
|
| 81 |
+
self.metric_fn = torchmetrics.classification.MulticlassAccuracy(num_classes = 11)
|
| 82 |
+
self.save_hyperparameters(ignore = ["model"])
|
| 83 |
+
|
| 84 |
+
def forward(self, x):
|
| 85 |
+
return self.model(x)
|
| 86 |
+
|
| 87 |
+
def training_step(self, batch, batch_idx):
|
| 88 |
+
self.model.train()
|
| 89 |
+
X, y = batch
|
| 90 |
+
logits = self.model(X)
|
| 91 |
+
loss = self.loss_fn(logits, y)
|
| 92 |
+
acc = self.metric_fn(torch.flatten(torch.argmax(torch.softmax(logits, dim = 1), axis = 1)), y)
|
| 93 |
+
self.log("Train accuracy", acc, prog_bar = True, on_epoch = True, on_step = False)
|
| 94 |
+
self.log("Train logloss", loss, prog_bar = True, on_epoch = True, on_step = False)
|
| 95 |
+
return {"Train Accuracy": acc, "loss": loss}
|
| 96 |
+
|
| 97 |
+
def validation_step(self, batch, batch_idx):
|
| 98 |
+
self.model.eval()
|
| 99 |
+
X, y = batch
|
| 100 |
+
logits = self.model(X)
|
| 101 |
+
val_loss = self.loss_fn(logits, y)
|
| 102 |
+
val_acc = self.metric_fn(torch.flatten(torch.argmax(torch.softmax(logits, dim = 1), axis = 1)), y)
|
| 103 |
+
self.log("Val accuracy", val_acc, prog_bar = True, on_epoch = True, on_step = False)
|
| 104 |
+
self.log("Val logloss", val_loss, prog_bar = True, on_epoch = True, on_step = False)
|
| 105 |
+
return {"Val Accuracy": val_acc, "Val loss": val_loss}
|
| 106 |
+
|
| 107 |
+
def configure_optimizers(self):
|
| 108 |
+
optimizer = torch.optim.Adam(params = self.model.parameters(), lr = self.lr, weight_decay = 1e-4)
|
| 109 |
+
return optimizer
|
| 110 |
+
|
| 111 |
+
model = torchvision.models.efficientnet.efficientnet_b0(progress = True, weights = torchvision.models.efficientnet.EfficientNet_B0_Weights.DEFAULT)
|
| 112 |
+
model.classifier = nn.Sequential(
|
| 113 |
+
nn.Dropout(p=0.2, inplace=True),
|
| 114 |
+
nn.Linear(in_features=1280, out_features=11, bias=True)
|
| 115 |
+
)
|
| 116 |
+
lightning_model = myLightningModel.load_from_checkpoint(checkpoint_path = checkpoint_path, map_location = device, model = model, lr = 1e-3)
|
| 117 |
+
return lightning_model
|