Hassan145 commited on
Commit
c1ef9cb
·
1 Parent(s): 779da14

updated one

Browse files
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.resnet
 
 
6
  from PIL import Image
7
  from timeit import default_timer as timer
8
  from typing import Tuple, Dict
9
 
10
- # 1. Setup class names
11
- class_names = ['Cabbage', 'Carrot', 'Cucumber', 'tomato']
12
 
 
 
 
13
 
14
- # 2. Define transforms (adjust as needed, example here)
15
- manual_transforms = transforms.Compose([
16
- transforms.Resize((224, 224)),
17
- transforms.ToTensor(),
18
- transforms.Normalize(
19
- mean=[0.485, 0.456, 0.406], # ImageNet mean
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) # add batch dimension
40
 
41
  with torch.inference_mode():
42
- preds = torch.softmax(resnet(img_tensor), dim=1)
 
43
 
44
- pred_labels_and_probs = {class_names[i]: float(preds[0][i]) for i in range(len(class_names))}
45
  pred_time = round(timer() - start_time, 5)
46
 
47
  return pred_labels_and_probs, pred_time
48
 
49
- # 5. Gradio app UI
50
  with gr.Blocks() as gradio_app:
51
- gr.HTML("<h1 style='text-align: center'>Rice Disease Classification - ResNet Model</h1>")
52
- gr.HTML(
53
- """
54
  <h3 style='text-align: center'>
55
- Follow me for more!
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
- image = gr.Image(type="pil", label="Upload Image")
65
- infer = gr.Button(value="Predict")
66
 
67
- example_list = [["examples/" + example] for example in os.listdir("examples")]
68
- gr.Examples(examples=example_list, inputs=[image])
 
 
69
 
70
  with gr.Column():
71
- label = gr.Label(num_top_classes=4, label="Predictions")
72
- pred_time = gr.Number(label="Prediction Time (s)")
 
 
73
 
74
- infer.click(fn=predict, inputs=[image], outputs=[label, pred_time])
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)