updated one
Browse files- app.py +36 -42
- examples/Cabbage.jpg +0 -0
- examples/Carrot.jpg +0 -0
- examples/Cucumber.jpg +0 -0
- examples/Tomato.jpg +0 -0
app.py
CHANGED
|
@@ -2,75 +2,69 @@ import gradio as gr
|
|
| 2 |
import os
|
| 3 |
import torch
|
| 4 |
import torchvision.transforms as transforms
|
| 5 |
-
import torchvision.models
|
|
|
|
|
|
|
| 6 |
from PIL import Image
|
| 7 |
from timeit import default_timer as timer
|
| 8 |
from typing import Tuple, Dict
|
| 9 |
|
| 10 |
-
# 1.
|
| 11 |
-
class_names = ['Cabbage', 'Carrot', 'Cucumber', '
|
| 12 |
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
-
#
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
std=[0.229, 0.224, 0.225] # ImageNet std
|
| 21 |
-
)
|
| 22 |
-
])
|
| 23 |
-
|
| 24 |
-
# 3. Prepare the ResNet model
|
| 25 |
-
torch.serialization.add_safe_globals([torchvision.models.resnet.ResNet])
|
| 26 |
-
|
| 27 |
-
resnet = torchvision.models.resnet18(weights=None, num_classes=len(class_names))
|
| 28 |
-
|
| 29 |
-
# Load your saved state dict checkpoint safely
|
| 30 |
-
resnet.load_state_dict(
|
| 31 |
-
torch.load("resnet_model.pth", map_location=torch.device("cpu"), weights_only=True)
|
| 32 |
-
)
|
| 33 |
|
|
|
|
|
|
|
| 34 |
resnet.eval()
|
| 35 |
|
| 36 |
# 4. Prediction function
|
| 37 |
def predict(img: Image.Image) -> Tuple[Dict[str, float], float]:
|
| 38 |
start_time = timer()
|
| 39 |
-
img_tensor = manual_transforms(img).unsqueeze(0)
|
| 40 |
|
| 41 |
with torch.inference_mode():
|
| 42 |
-
|
|
|
|
| 43 |
|
| 44 |
-
pred_labels_and_probs = {class_names[i]: float(
|
| 45 |
pred_time = round(timer() - start_time, 5)
|
| 46 |
|
| 47 |
return pred_labels_and_probs, pred_time
|
| 48 |
|
| 49 |
-
# 5. Gradio app
|
| 50 |
with gr.Blocks() as gradio_app:
|
| 51 |
-
gr.HTML("<h1 style='text-align: center'>
|
| 52 |
-
gr.HTML(
|
| 53 |
-
"""
|
| 54 |
<h3 style='text-align: center'>
|
| 55 |
-
|
| 56 |
-
<a href='https://github.com/ExplorerGumel' target='_blank'>Github</a> |
|
| 57 |
-
<a href='https://www.linkedin.com/in/munzali-alhassan/' target='_blank'>Linkedin</a>
|
| 58 |
</h3>
|
| 59 |
-
|
| 60 |
-
)
|
| 61 |
|
| 62 |
with gr.Row():
|
| 63 |
with gr.Column():
|
| 64 |
-
|
| 65 |
-
|
| 66 |
|
| 67 |
-
example_list = [
|
| 68 |
-
|
|
|
|
|
|
|
| 69 |
|
| 70 |
with gr.Column():
|
| 71 |
-
|
| 72 |
-
|
|
|
|
|
|
|
| 73 |
|
| 74 |
-
|
| 75 |
|
| 76 |
-
gradio_app.launch(debug=True, share=True)
|
|
|
|
| 2 |
import os
|
| 3 |
import torch
|
| 4 |
import torchvision.transforms as transforms
|
| 5 |
+
import torchvision.models as models
|
| 6 |
+
from torchvision.models import ResNet18_Weights
|
| 7 |
+
import torch.nn as nn
|
| 8 |
from PIL import Image
|
| 9 |
from timeit import default_timer as timer
|
| 10 |
from typing import Tuple, Dict
|
| 11 |
|
| 12 |
+
# 1. Class names (must match training order!)
|
| 13 |
+
class_names = ['Cabbage', 'Carrot', 'Cucumber', 'Tomato']
|
| 14 |
|
| 15 |
+
# 2. Image preprocessing pipeline from ResNet18 weights
|
| 16 |
+
weights = ResNet18_Weights.DEFAULT
|
| 17 |
+
manual_transforms = weights.transforms()
|
| 18 |
|
| 19 |
+
# 3. Load model with correct architecture
|
| 20 |
+
def get_resnet18():
|
| 21 |
+
model = models.resnet18(weights=weights) # ← NEW: use correct weight object
|
| 22 |
+
num_ftrs = model.fc.in_features
|
| 23 |
+
model.fc = nn.Linear(num_ftrs, len(class_names)) # ← match training config
|
| 24 |
+
return model
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
+
resnet = get_resnet18()
|
| 27 |
+
resnet.load_state_dict(torch.load("resnet_model.pth", map_location=torch.device("cpu")))
|
| 28 |
resnet.eval()
|
| 29 |
|
| 30 |
# 4. Prediction function
|
| 31 |
def predict(img: Image.Image) -> Tuple[Dict[str, float], float]:
|
| 32 |
start_time = timer()
|
| 33 |
+
img_tensor = manual_transforms(img).unsqueeze(0)
|
| 34 |
|
| 35 |
with torch.inference_mode():
|
| 36 |
+
outputs = resnet(img_tensor)
|
| 37 |
+
probs = torch.softmax(outputs, dim=1)[0]
|
| 38 |
|
| 39 |
+
pred_labels_and_probs = {class_names[i]: float(probs[i]) for i in range(len(class_names))}
|
| 40 |
pred_time = round(timer() - start_time, 5)
|
| 41 |
|
| 42 |
return pred_labels_and_probs, pred_time
|
| 43 |
|
| 44 |
+
# 5. Gradio app
|
| 45 |
with gr.Blocks() as gradio_app:
|
| 46 |
+
gr.HTML("<h1 style='text-align: center'>Vegetable Classification with ResNet18</h1>")
|
| 47 |
+
gr.HTML("""
|
|
|
|
| 48 |
<h3 style='text-align: center'>
|
| 49 |
+
Created by <a href='https://github.com/ExplorerGumel' target='_blank'>@ExplorerGumel</a>
|
|
|
|
|
|
|
| 50 |
</h3>
|
| 51 |
+
""")
|
|
|
|
| 52 |
|
| 53 |
with gr.Row():
|
| 54 |
with gr.Column():
|
| 55 |
+
image_input = gr.Image(type="pil", label="Upload Image")
|
| 56 |
+
infer_btn = gr.Button("Predict")
|
| 57 |
|
| 58 |
+
example_list = []
|
| 59 |
+
if os.path.exists("examples"):
|
| 60 |
+
example_list = [["examples/" + fname] for fname in os.listdir("examples") if fname.endswith((".jpg", ".png"))]
|
| 61 |
+
gr.Examples(examples=example_list, inputs=[image_input])
|
| 62 |
|
| 63 |
with gr.Column():
|
| 64 |
+
label_output = gr.Label(num_top_classes=4, label="Predictions")
|
| 65 |
+
time_output = gr.Number(label="Prediction Time (seconds)")
|
| 66 |
+
|
| 67 |
+
infer_btn.click(fn=predict, inputs=image_input, outputs=[label_output, time_output])
|
| 68 |
|
| 69 |
+
gradio_app.launch()
|
| 70 |
|
|
|
examples/Cabbage.jpg
DELETED
|
Binary file (19.6 kB)
|
|
|
examples/Carrot.jpg
DELETED
|
Binary file (17.7 kB)
|
|
|
examples/Cucumber.jpg
DELETED
|
Binary file (18 kB)
|
|
|
examples/Tomato.jpg
DELETED
|
Binary file (16 kB)
|
|
|