Hassan145 commited on
Commit
62e392d
·
1 Parent(s): c1ef9cb

updated one

Browse files
Files changed (1) hide show
  1. app.py +28 -28
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 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'>
@@ -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
- 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
 
 
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