updated one
Browse files
app.py
CHANGED
|
@@ -1,48 +1,47 @@
|
|
| 1 |
import gradio as gr
|
| 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
|
| 13 |
class_names = ['Cabbage', 'Carrot', 'Cucumber', 'Tomato']
|
| 14 |
|
| 15 |
-
# 2.
|
| 16 |
weights = ResNet18_Weights.DEFAULT
|
| 17 |
-
|
| 18 |
|
| 19 |
-
# 3.
|
| 20 |
def get_resnet18():
|
| 21 |
-
model = models.resnet18(weights=weights)
|
| 22 |
num_ftrs = model.fc.in_features
|
| 23 |
-
model.fc = nn.Linear(num_ftrs, len(class_names))
|
| 24 |
return model
|
| 25 |
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
|
| 30 |
# 4. Prediction function
|
| 31 |
def predict(img: Image.Image) -> Tuple[Dict[str, float], float]:
|
| 32 |
-
|
| 33 |
-
img_tensor =
|
| 34 |
|
| 35 |
with torch.inference_mode():
|
| 36 |
-
|
| 37 |
-
probs = torch.softmax(
|
| 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 |
-
|
|
|
|
|
|
|
| 43 |
|
| 44 |
-
# 5. Gradio
|
| 45 |
-
with gr.Blocks() as
|
| 46 |
gr.HTML("<h1 style='text-align: center'>Vegetable Classification with ResNet18</h1>")
|
| 47 |
gr.HTML("""
|
| 48 |
<h3 style='text-align: center'>
|
|
@@ -53,18 +52,19 @@ with gr.Blocks() as gradio_app:
|
|
| 53 |
with gr.Row():
|
| 54 |
with gr.Column():
|
| 55 |
image_input = gr.Image(type="pil", label="Upload Image")
|
| 56 |
-
|
| 57 |
|
| 58 |
-
|
| 59 |
if os.path.exists("examples"):
|
| 60 |
-
|
| 61 |
-
gr.Examples(examples=
|
| 62 |
|
| 63 |
with gr.Column():
|
| 64 |
-
|
| 65 |
-
|
| 66 |
|
| 67 |
-
|
| 68 |
|
| 69 |
-
|
|
|
|
| 70 |
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import os
|
| 3 |
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
import torchvision.transforms as transforms
|
| 6 |
import torchvision.models as models
|
| 7 |
from torchvision.models import ResNet18_Weights
|
|
|
|
| 8 |
from PIL import Image
|
| 9 |
from timeit import default_timer as timer
|
| 10 |
from typing import Tuple, Dict
|
| 11 |
|
| 12 |
+
# 1. Class names (order must match your training)
|
| 13 |
class_names = ['Cabbage', 'Carrot', 'Cucumber', 'Tomato']
|
| 14 |
|
| 15 |
+
# 2. Load default preprocessing from pretrained weights
|
| 16 |
weights = ResNet18_Weights.DEFAULT
|
| 17 |
+
transform = weights.transforms()
|
| 18 |
|
| 19 |
+
# 3. Define and load the model
|
| 20 |
def get_resnet18():
|
| 21 |
+
model = models.resnet18(weights=weights)
|
| 22 |
num_ftrs = model.fc.in_features
|
| 23 |
+
model.fc = nn.Linear(num_ftrs, len(class_names))
|
| 24 |
return model
|
| 25 |
|
| 26 |
+
model = get_resnet18()
|
| 27 |
+
model.load_state_dict(torch.load("resnet_model.pth", map_location=torch.device("cpu"), weights_only=False))
|
| 28 |
+
model.eval()
|
| 29 |
|
| 30 |
# 4. Prediction function
|
| 31 |
def predict(img: Image.Image) -> Tuple[Dict[str, float], float]:
|
| 32 |
+
start = timer()
|
| 33 |
+
img_tensor = transform(img).unsqueeze(0)
|
| 34 |
|
| 35 |
with torch.inference_mode():
|
| 36 |
+
output = model(img_tensor)
|
| 37 |
+
probs = torch.softmax(output, dim=1)[0]
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
+
result = {class_names[i]: float(probs[i]) for i in range(len(class_names))}
|
| 40 |
+
elapsed = round(timer() - start, 5)
|
| 41 |
+
return result, elapsed
|
| 42 |
|
| 43 |
+
# 5. Build the Gradio interface
|
| 44 |
+
with gr.Blocks() as demo:
|
| 45 |
gr.HTML("<h1 style='text-align: center'>Vegetable Classification with ResNet18</h1>")
|
| 46 |
gr.HTML("""
|
| 47 |
<h3 style='text-align: center'>
|
|
|
|
| 52 |
with gr.Row():
|
| 53 |
with gr.Column():
|
| 54 |
image_input = gr.Image(type="pil", label="Upload Image")
|
| 55 |
+
predict_button = gr.Button("Predict")
|
| 56 |
|
| 57 |
+
examples = []
|
| 58 |
if os.path.exists("examples"):
|
| 59 |
+
examples = [["examples/" + fname] for fname in os.listdir("examples") if fname.lower().endswith((".png", ".jpg", ".jpeg"))]
|
| 60 |
+
gr.Examples(examples=examples, inputs=[image_input])
|
| 61 |
|
| 62 |
with gr.Column():
|
| 63 |
+
output_label = gr.Label(num_top_classes=4, label="Predictions")
|
| 64 |
+
output_time = gr.Number(label="Prediction Time (seconds)")
|
| 65 |
|
| 66 |
+
predict_button.click(fn=predict, inputs=image_input, outputs=[output_label, output_time])
|
| 67 |
|
| 68 |
+
# 6. Launch the app
|
| 69 |
+
demo.launch()
|
| 70 |
|