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

Your commit message

Browse files
Files changed (1) hide show
  1. app.py +35 -49
app.py CHANGED
@@ -1,90 +1,76 @@
1
- ### 1. Imports and class names setup ###
2
  import gradio as gr
3
  import os
4
  import torch
5
- from torchvision import models, transforms
 
6
  from PIL import Image
7
  from timeit import default_timer as timer
8
  from typing import Tuple, Dict
9
 
10
- # Setup class names
11
  class_names = ['Cabbage', 'Carrot', 'Cucumber', 'tomato']
12
 
13
- ### 2. Model and transforms preparation ###
14
 
15
- # Load a pretrained ResNet model (e.g. ResNet18) and adjust final layer for 4 classes
16
- resnet = models.resnet18(pretrained=False)
17
- num_features = resnet.fc.in_features
18
- resnet.fc = torch.nn.Linear(num_features, len(class_names))
19
-
20
- # Load your trained weights
21
- resnet.load_state_dict(torch.load("resnet_model.pth", map_location=torch.device("cpu")))
22
-
23
- # Define the transforms to match ResNet input requirements
24
  manual_transforms = transforms.Compose([
25
- transforms.Resize(256),
26
- transforms.CenterCrop(224),
27
  transforms.ToTensor(),
28
  transforms.Normalize(
29
- mean=[0.485, 0.456, 0.406], # Standard ImageNet mean
30
- std=[0.229, 0.224, 0.225] # Standard ImageNet std
31
  )
32
  ])
33
 
34
- ### 3. Predict function ###
35
- def predict(img: Image.Image) -> Tuple[Dict, float]:
 
 
 
 
 
 
 
 
 
 
 
 
36
  start_time = timer()
37
-
38
- img = manual_transforms(img).unsqueeze(0) # Add batch dimension
39
-
40
- resnet.eval()
41
  with torch.inference_mode():
42
- pred_logits = resnet(img)
43
- pred_probs = torch.softmax(pred_logits, dim=1)
44
-
45
- pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}
46
-
47
  pred_time = round(timer() - start_time, 5)
48
-
49
- return pred_labels_and_probs, pred_time
50
 
51
- ### 4. Gradio app ###
52
 
 
53
  with gr.Blocks() as gradio_app:
54
- gr.HTML(
55
- """
56
- <h1 style='text-align: center'>
57
- Rice Disease Classification - ResNet Model
58
- </h1>
59
- """
60
- )
61
-
62
  gr.HTML(
63
  """
64
  <h3 style='text-align: center'>
65
  Follow me for more!
66
  <a href='https://github.com/ExplorerGumel' target='_blank'>Github</a> |
67
- <a href='https://www.linkedin.com/in/munzali-alhassan/' target='_blank'>Linkedin</a>
68
  </h3>
69
  """
70
  )
71
-
72
  with gr.Row():
73
  with gr.Column():
74
  image = gr.Image(type="pil", label="Upload Image")
75
  infer = gr.Button(value="Predict")
76
-
77
  example_list = [["examples/" + example] for example in os.listdir("examples")]
78
- gr.Examples(
79
- examples=example_list,
80
- inputs=[image]
81
- )
82
-
83
  with gr.Column():
84
  label = gr.Label(num_top_classes=4, label="Predictions")
85
  pred_time = gr.Number(label="Prediction Time (s)")
86
-
87
  infer.click(fn=predict, inputs=[image], outputs=[label, pred_time])
88
 
89
  gradio_app.launch(debug=True, share=True)
90
-
 
 
1
  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)