-
Notifications
You must be signed in to change notification settings - Fork 2
/
model.py
197 lines (165 loc) · 7.47 KB
/
model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# import cv2
# import matplotlib.pyplot as plt
# import numpy as np
# import torch
# import yaml
# from PIL import Image
# from transformers import CLIPProcessor, CLIPModel
# class Model:
# def __init__(self, settings_path: str = './settings.yaml'):
# with open(settings_path, "r") as file:
# self.settings = yaml.safe_load(file)
# self.device = self.settings['model-settings']['device']
# self.model_name = self.settings['model-settings']['model-name']
# self.threshold = self.settings['model-settings']['prediction-threshold']
# # Load the CLIP model and processor
# self.processor = CLIPProcessor.from_pretrained(self.model_name)
# self.model = CLIPModel.from_pretrained(self.model_name).to(self.device)
# self.labels = self.settings['label-settings']['labels']
# self.labels_ = [f'a photo of {label}' for label in self.labels]
# self.text_features = self.vectorize_text(self.labels_)
# self.default_label = self.settings['label-settings']['default-label']
# @torch.no_grad()
# def transform_image(self, image: np.ndarray):
# pil_image = Image.fromarray(image).convert('RGB')
# tf_image = self.processor(pil_image, return_tensors="pt").to(self.device)
# return tf_image
# @torch.no_grad()
# def vectorize_text(self, text: list):
# tokens = self.processor(text, return_tensors="pt", padding=True, truncation=True).to(self.device)
# text_features = self.model.get_text_features(**tokens)
# return text_features
# @torch.no_grad()
# def predict_(self, text_features: torch.Tensor,
# image_features: torch.Tensor):
# # Pick the top 5 most similar labels for the image
# image_features /= image_features.norm(dim=-1, keepdim=True)
# text_features /= text_features.norm(dim=-1, keepdim=True)
# similarity = image_features @ text_features.T
# values, indices = similarity.topk(1)
# return values, indices
# @torch.no_grad()
# def predict(self, image: np.array) -> dict:
# '''
# Does prediction on an input image
# Args:
# image (np.array): numpy image with RGB channel ordering type.
# Don't forget to convert image to RGB if you
# read images via opencv, otherwise model's accuracy
# will decrease.
# Returns:
# (dict): dict that contains predictions:
# {
# 'label': 'some_label',
# 'confidence': 0.X
# }
# confidence is calculated based on cosine similarity,
# thus you may see low conf. values for right predictions.
# '''
# tf_image = self.transform_image(image)
# image_features = self.model.get_image_features(**tf_image)
# values, indices = self.predict_(text_features=self.text_features,
# image_features=image_features)
# label_index = indices.item()
# label_text = self.default_label
# model_confidence = values.item()
# if model_confidence >= self.threshold:
# label_text = self.labels[label_index]
# prediction = {
# 'label': label_text,
# 'confidence': model_confidence
# }
# return prediction
# @staticmethod
# def plot_image(image: np.array, title_text: str):
# plt.figure(figsize=[13, 13])
# plt.title(title_text)
# plt.axis('off')
# if len(image.shape) == 3:
# image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# plt.imshow(image)
import clip
import cv2
import matplotlib.pyplot as plt
import numpy as np
import torch
import yaml
from PIL import Image
class Model:
def __init__(self, settings_path: str = './settings.yaml'):
with open(settings_path, "r") as file:
self.settings = yaml.safe_load(file)
self.device = self.settings['model-settings']['device']
self.model_name = self.settings['model-settings']['model-name']
self.threshold = self.settings['model-settings']['prediction-threshold']
self.model, self.preprocess = clip.load(self.model_name, device=self.device)
self.labels = self.settings['label-settings']['labels']
self.labels_ = []
for label in self.labels:
text = 'a photo of ' + label # will increase model's accuracy
self.labels_.append(text)
self.text_features = self.vectorize_text(self.labels_)
self.default_label = self.settings['label-settings']['default-label']
@torch.no_grad()
def transform_image(self, image: np.ndarray):
pil_image = Image.fromarray(image).convert('RGB')
tf_image = self.preprocess(pil_image).unsqueeze(0).to(self.device)
return tf_image
@torch.no_grad()
def tokenize(self, text: list):
text = clip.tokenize(text).to(self.device)
return text
@torch.no_grad()
def vectorize_text(self, text: list):
tokens = self.tokenize(text=text)
text_features = self.model.encode_text(tokens)
return text_features
@torch.no_grad()
def predict_(self, text_features: torch.Tensor,
image_features: torch.Tensor):
# Pick the top 5 most similar labels for the image
image_features /= image_features.norm(dim=-1, keepdim=True)
text_features /= text_features.norm(dim=-1, keepdim=True)
similarity = image_features @ text_features.T
values, indices = similarity[0].topk(1)
return values, indices
@torch.no_grad()
def predict(self, image: np.array) -> dict:
'''
Does prediction on an input image
Args:
image (np.array): numpy image with RGB channel ordering type.
Don't forget to convert image to RGB if you
read images via opencv, otherwise model's accuracy
will decrease.
Returns:
(dict): dict that contains predictions:
{
'label': 'some_label',
'confidence': 0.X
}
confidence is calculated based on cosine similarity,
thus you may see low conf. values for right predictions.
'''
tf_image = self.transform_image(image)
image_features = self.model.encode_image(tf_image)
values, indices = self.predict_(text_features=self.text_features,
image_features=image_features)
label_index = indices[0].cpu().item()
label_text = self.default_label
model_confidance = abs(values[0].cpu().item())
if model_confidance >= self.threshold:
label_text = self.labels[label_index]
prediction = {
'label': label_text,
'confidence': model_confidance
}
return prediction
@staticmethod
def plot_image(image: np.array, title_text: str):
plt.figure(figsize=[13, 13])
plt.title(title_text)
plt.axis('off')
if len(image.shape) == 3:
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
plt.imshow(image)