Hassan145 commited on
Commit
82ec4aa
·
1 Parent(s): 581005c
app.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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("""
46
+ <div style="background-image: url('https://images.unsplash.com/photo-1501004318641-b39e6451bec6');
47
+ background-size: cover;
48
+ padding: 25px;
49
+ border-radius: 10px;
50
+ color: white;
51
+ font-family: 'Poppins', sans-serif;">
52
+ <h1 style='text-align: center;'>🌾 Vegetable Classifier with ResNet18 🌾</h1>
53
+ <h3 style='text-align: center;'>
54
+ Created by <a href='https://github.com/hassan1303' target='_blank' style='color: #f0e68c;'>@hassan1303</a>
55
+ </h3>
56
+ </div>
57
+ """)
58
+
59
+ with gr.Row():
60
+ with gr.Column():
61
+ image_input = gr.Image(type="pil", label="📸 Upload Vegetable Image")
62
+ predict_button = gr.Button("🔍 Predict")
63
+
64
+
65
+ examples = []
66
+ if os.path.exists("examples"):
67
+ examples = [["examples/" + fname] for fname in os.listdir("examples") if fname.lower().endswith((".png", ".jpg", ".jpeg"))]
68
+ gr.Examples(examples=examples, inputs=[image_input])
69
+
70
+ with gr.Column():
71
+ output_label = gr.Label(num_top_classes=4, label="🌽 Predictions")
72
+ output_time = gr.Number(label="⏱️ Prediction Time (seconds)")
73
+
74
+ predict_button.click(fn=predict, inputs=image_input, outputs=[output_label, output_time])
75
+
76
+ # 6. Launch the app
77
+ demo.launch()
78
+
79
+
80
+
examples/Cabbage.jpg ADDED
examples/Carrot.jpg ADDED
examples/Cucumber.jpg ADDED
examples/Tomato.jpg ADDED
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ torch
2
+ torchvision
3
+ gradio
4
+ Pillow
5
+
resnet_model.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8d9092b51f1fde37fa95bcd2e3a20b469bcf003999e5fe2cc46cf5433b4f9be1
3
+ size 44791988