Yu Hung Tam commited on
Commit
e65bf54
1 Parent(s): 198c116

first commit

Browse files
.gitattributes CHANGED
@@ -32,3 +32,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
32
  *.zip filter=lfs diff=lfs merge=lfs -text
33
  *.zst filter=lfs diff=lfs merge=lfs -text
34
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
32
  *.zip filter=lfs diff=lfs merge=lfs -text
33
  *.zst filter=lfs diff=lfs merge=lfs -text
34
  *tfevents* filter=lfs diff=lfs merge=lfs -text
35
+ *.file_extension filter=lfs diff=lfs merge=lfs -text
36
+ Pretrained_vit_feature_extractor_RDDV2AMC.pth filter=lfs diff=lfs merge=lfs -text
Pretrained_vit_feature_extractor_RDDV2AMC.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f1cca05ced71d79538362045c346a0a223fd53057a45770798a83324a99c006b
3
+ size 343273361
app.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### 1. Imports and class names setup ###
2
+ import gradio as gr
3
+ import os
4
+ import torch
5
+
6
+ from model import create_vit_model
7
+ from timeit import default_timer as timer
8
+ from typing import Tuple, Dict
9
+
10
+ # Setup class names
11
+ class_names = ["D00-Longitudinal Crack", "D10-Transverse Crack", "D20-Aligator Crack", "D40-Pothole",
12
+ "D43-Cross Walk Blur", "D44-White Line Blur", "D50-Manhole Cover (TBC)"]
13
+
14
+ ### 2. Model and transforms preparation ###
15
+
16
+ # Create EffNetB2 model
17
+ vit, vit_transforms = create_effnetb2_model(
18
+ num_classes=len(class_names), # len(class_names) would also work
19
+ )
20
+
21
+ # Load saved weights
22
+ vit.load_state_dict(
23
+ torch.load(
24
+ f="Pretrained_vit_feature_extractor_RDDV2AMC.pth",
25
+ map_location=torch.device("cpu"), # load to CPU
26
+ )
27
+ )
28
+
29
+ ### 3. Predict function ###
30
+
31
+ # Create predict function
32
+ def predict(img) -> Tuple[Dict, float]:
33
+ """Transforms and performs a prediction on img and returns prediction and time taken.
34
+ """
35
+ # Start the timer
36
+ start_time = timer()
37
+
38
+ # Transform the target image and add a batch dimension
39
+ img = vit_transforms(img).unsqueeze(0)
40
+
41
+ # Put model into evaluation mode and turn on inference mode
42
+ vit.eval()
43
+ with torch.inference_mode():
44
+ # Pass the transformed image through the model and turn the prediction logits into prediction probabilities
45
+ pred_probs = torch.softmax(vit(img), dim=1)
46
+
47
+ # Create a prediction label and prediction probability dictionary for each prediction class (this is the required format for Gradio's output parameter)
48
+ pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}
49
+
50
+ # Calculate the prediction time
51
+ pred_time = round(timer() - start_time, 5)
52
+
53
+ # Return the prediction dictionary and prediction time
54
+ return pred_labels_and_probs, pred_time
55
+
56
+ ### 4. Gradio app ###
57
+
58
+ # Create title, description and article strings
59
+ title = "Road Damages Detection 🚧"
60
+ description = "An ViT feature extractor computer vision model to classify images of common road damages."
61
+ article = "Created at [Road Damages Detection](https:/xxx/)."
62
+
63
+ # Create examples list from "examples/" directory
64
+ example_list = [["examples/" + example] for example in os.listdir("examples")]
65
+
66
+ # Create the Gradio demo
67
+ demo = gr.Interface(fn=predict, # mapping function from input to output
68
+ inputs=gr.Image(type="pil"), # what are the inputs?
69
+ outputs=[gr.Label(num_top_classes=7, label="Predictions"), # what are the outputs?
70
+ gr.Number(label="Prediction time (s)")], # our fn has two outputs, therefore we have two outputs
71
+ # Create examples list from "examples/" directory
72
+ examples=example_list,
73
+ title=title,
74
+ description=description,
75
+ article=article)
76
+
77
+ # Launch the demo!
78
+ demo.launch()
examples/IMG_1440.jpg ADDED
examples/IMG_1441.jpg ADDED
examples/IMG_1442.jpg ADDED
model.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torchvision
3
+
4
+ from torch import nn
5
+
6
+
7
+ def create_vit_model(num_classes:int=7,
8
+ seed:int=42):
9
+ """Creates an ViT feature extractor model and transforms.
10
+
11
+ Args:
12
+ num_classes (int, optional): number of classes in the classifier head.
13
+ Defaults to 7.
14
+ seed (int, optional): random seed value. Defaults to 42.
15
+
16
+ Returns:
17
+ model (torch.nn.Module): ViT feature extractor model.
18
+ transforms (torchvision.transforms): ViT image transforms.
19
+ """
20
+ # Create ViT pretrained weights, transforms and model
21
+ weights = torchvision.models.ViT_B_16_Weights.DEFAULT
22
+ transforms = weights.transforms()
23
+ model = torchvision.models.vit_b_16(weights=weights)
24
+
25
+ # Freeze all layers in base model
26
+ for param in model.parameters():
27
+ param.requires_grad = False
28
+
29
+ # Change classifier head with random seed for reproducibility
30
+ torch.manual_seed(seed)
31
+ model.classifier = nn.Sequential(
32
+ nn.Dropout(p=0.3, inplace=True),
33
+ nn.Linear(in_features=768, out_features=num_classes),
34
+ )
35
+
36
+ return model, transforms
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ torch==1.12.0
2
+ torchvision==0.13.0
3
+ gradio==3.1.4