TedYeh commited on
Commit
e774cd9
1 Parent(s): 8a7491d

update files

Browse files
Files changed (5) hide show
  1. app.py +25 -4
  2. dataloader.py +73 -0
  3. models/model_7.pt +3 -0
  4. predictor.py +284 -0
  5. requirements.txt +7 -0
app.py CHANGED
@@ -1,7 +1,28 @@
1
  import gradio as gr
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
 
5
 
6
- iface = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ from predictor import inference
3
 
4
+ def index_predict(name):
5
+ outputs, preds, heights, bust, waist, hips, description = inference(os.path.join(app.config['UPLOAD_FOLDER'], filename), epoch = 7)
6
+ return heights, round(float(bust)), round(float(waist)), round(float(hips)), description[0], description[1]
7
 
8
+ with gr.Blocks() as demo:
9
+ gr.Markdown(
10
+ """
11
+ # 身材數據評估器 - Body Index Predictor
12
+ ### Input A FACE and get the body index
13
+ """
14
+ )
15
+ image = gr.Image(type="pil")
16
+ # 設定輸出元件
17
+ heights = gr.Textbox(label="Heignt")
18
+ bust = gr.Textbox(label="Bust")
19
+ waist = gr.Textbox(label="Waist")
20
+ hips = gr.Textbox(label="Hips")
21
+ en_des = gr.Textbox(label="English description")
22
+ zh_des = gr.Textbox(label="Chinese description")
23
+
24
+ #設定按鈕
25
+ submit = gr.Button("Submit")
26
+ #設定按鈕點選事件
27
+ greet_btn.click(fn=index_predict, inputs=image, outputs=[heights, bust, waist, hips, en_des, zh_des])
28
+ demo.launch()
dataloader.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from random import shuffle
2
+ import torch
3
+ import csv, os
4
+ from torch.utils.data import TensorDataset, DataLoader, RandomSampler, Dataset, SequentialSampler
5
+ from sklearn.model_selection import train_test_split
6
+ from torchvision.io import read_image
7
+ import torch.nn as nn
8
+ from torchvision import transforms
9
+ import pandas as pd
10
+ import numpy as np
11
+ from PIL import Image
12
+ import math
13
+ from transformers import AutoImageProcessor
14
+
15
+ class imgDataset(Dataset):
16
+ def __init__(self, path, mode='train', use_processor=True):
17
+ self.path = path
18
+ self.mode = mode
19
+ self.use_processor = use_processor
20
+ self.image_processor = AutoImageProcessor.from_pretrained("microsoft/resnet-50")
21
+ self.transform = {
22
+ 'train': transforms.Compose([
23
+ transforms.RandomResizedCrop(224),
24
+ transforms.RandomHorizontalFlip(),
25
+ transforms.ToTensor(),
26
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
27
+ ]),
28
+ 'val': transforms.Compose([
29
+ transforms.Resize(256),
30
+ transforms.CenterCrop(224),
31
+ transforms.ToTensor(),
32
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
33
+ ])
34
+ }
35
+ self.trans = self.transform[mode]
36
+ self.data = self.get_data()
37
+
38
+ def convert_body_to_int(self, pos, file_name_list):
39
+ body_str = file_name_list[1].split('-')[pos]
40
+ if not body_str: body_str = '62'
41
+ body = int(body_str[1:3]) if not body_str.isdigit() else int(body_str)
42
+ body = 100+body if body <= 25 else body
43
+ return body
44
+
45
+ def get_data(self):
46
+ data = []
47
+ with open(self.path, 'r', encoding='utf-8') as f:
48
+ for line in f.readlines():
49
+ file_name_list = line.split(' ')
50
+ if not self.mode in file_name_list:continue
51
+ label, h = 0 if file_name_list[2]=="big" else 1, float(file_name_list[3])
52
+ b = self.convert_body_to_int(0, file_name_list)
53
+ w = self.convert_body_to_int(1, file_name_list)
54
+ hh = self.convert_body_to_int(2, file_name_list)
55
+ data.append([os.path.join('images', file_name_list[0], file_name_list[2], file_name_list[1]), label, h, b, w, hh])
56
+ return data
57
+
58
+ def __len__(self):
59
+ return len(self.data)
60
+
61
+ def __getitem__(self, idx):
62
+ img_path, label, h, b, w, hh = self.data[idx]
63
+ inp_img = Image.open(img_path).convert("RGB")
64
+ if not self.use_processor: image_tensor = self.trans(inp_img)
65
+ else:image_tensor = self.image_processor(images=inp_img, return_tensors="pt")
66
+ return image_tensor, label, torch.tensor(h, dtype=torch.float), torch.tensor(b, dtype=torch.float), torch.tensor(w, dtype=torch.float), torch.tensor(hh, dtype=torch.float)
67
+
68
+ if __name__ == "__main__":
69
+ train_dataset = imgDataset('labels.txt', mode='train')
70
+ test_dataset = imgDataset('labels.txt', mode='val')
71
+ train_dataloader = DataLoader(train_dataset, batch_size=64, shuffle=True)
72
+ print(len(train_dataset), len(test_dataset))
73
+ print(next(iter(train_dataloader)))
models/model_7.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:14e707cfc153a9bfe7d61b2eb87e7ab4b68a90cc9131d72ffd53fa96f18bcc3c
3
+ size 99083113
predictor.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import print_function, division
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.optim as optim
6
+ from torch.optim import lr_scheduler
7
+ import torch.backends.cudnn as cudnn
8
+ import numpy as np
9
+ import torchvision
10
+ from torchvision import datasets, models, transforms
11
+ from torch.utils.data import TensorDataset, DataLoader
12
+ from PIL import Image
13
+ import matplotlib.pyplot as plt
14
+ from dataloader import imgDataset
15
+ import time
16
+ import os
17
+ import copy
18
+ from transformers import BlipProcessor, BlipForConditionalGeneration
19
+ from transformers import AutoImageProcessor, ResNetModel
20
+ from translate import Translator
21
+
22
+ PATH = './images/'
23
+
24
+ class CUPredictor_v2(nn.Module):
25
+ def __init__(self, num_class=2):
26
+ super(CUPredictor_v2, self).__init__()
27
+ self.base = ResNetModel.from_pretrained("microsoft/resnet-50")
28
+ num_ftrs = 2048
29
+ #self.base.fc = nn.Linear(num_ftrs, num_ftrs//2)
30
+ self.classifier = nn.Linear(num_ftrs, num_class)
31
+ self.height_regressor = nn.Linear(num_ftrs, 1)
32
+ self.relu = nn.ReLU()
33
+
34
+ def forward(self, input_img):
35
+ output = self.base(input_img['pixel_values'].squeeze(1)).pooler_output.squeeze()
36
+ predict_cls = self.classifier(output)
37
+ predict_height = self.relu(self.height_regressor(output))
38
+ return predict_cls, predict_height
39
+
40
+ class CUPredictor(nn.Module):
41
+ def __init__(self, num_class=2):
42
+ super(CUPredictor, self).__init__()
43
+ self.base = torchvision.models.resnet50(pretrained=True)
44
+ for param in self.base.parameters():
45
+ param.requires_grad = False
46
+
47
+ num_ftrs = self.base.fc.in_features
48
+ self.base.fc = nn.Sequential(
49
+ nn.Linear(num_ftrs, num_ftrs//4),
50
+ nn.ReLU(),
51
+ nn.Linear(num_ftrs//4, num_ftrs//8),
52
+ nn.ReLU()
53
+ )
54
+ self.classifier = nn.Linear(num_ftrs//8, num_class)
55
+ self.regressor_h = nn.Linear(num_ftrs//8, 1)
56
+ self.regressor_b = nn.Linear(num_ftrs//8, 1)
57
+ self.regressor_w = nn.Linear(num_ftrs//8, 1)
58
+ self.regressor_hi = nn.Linear(num_ftrs//8, 1)
59
+ self.relu = nn.ReLU()
60
+
61
+ def forward(self, input_img):
62
+ output = self.base(input_img)
63
+ predict_cls = self.classifier(output)
64
+ predict_h = self.relu(self.regressor_h(output))
65
+ predict_b = self.relu(self.regressor_b(output))
66
+ predict_w = self.relu(self.regressor_w(output))
67
+ predict_hi = self.relu(self.regressor_hi(output))
68
+ return predict_cls, predict_h, predict_b, predict_w, predict_hi
69
+
70
+
71
+ def imshow(inp, title=None):
72
+ """Imshow for Tensor."""
73
+ inp = inp.numpy().transpose((1, 2, 0))
74
+ mean = np.array([0.485, 0.456, 0.406])
75
+ std = np.array([0.229, 0.224, 0.225])
76
+ inp = std * inp + mean
77
+ inp = np.clip(inp, 0, 1)
78
+ plt.imshow(inp)
79
+ if title is not None:
80
+ plt.title(title)
81
+ plt.pause(0.001) # pause a bit so that plots are updated
82
+ plt.savefig(f'images/preds/prediction.png')
83
+
84
+ def train_model(model, device, dataloaders, dataset_sizes, num_epochs=25):
85
+ since = time.time()
86
+ ce = nn.CrossEntropyLoss()
87
+ mse = nn.MSELoss()
88
+ optimizer = optim.AdamW(model.parameters(), lr=0.0008)
89
+ best_model_wts = copy.deepcopy(model.state_dict())
90
+ best_acc = 0.0
91
+
92
+ for epoch in range(num_epochs):
93
+ print(f'Epoch {epoch+1}/{num_epochs}')
94
+ print('-' * 10)
95
+
96
+ # Each epoch has a training and validation phase
97
+ for phase in ['train', 'val']:
98
+ if phase == 'train':
99
+ model.train() # Set model to training mode
100
+ else:
101
+ model.eval() # Set model to evaluate mode
102
+
103
+ running_ce_loss = 0.0
104
+ running_rmse_loss = 0.0
105
+ running_corrects = 0
106
+
107
+ # Iterate over data.
108
+ for inputs, labels, heights, bust, waist, hips in dataloaders[phase]:
109
+ inputs = inputs.to(device)
110
+ labels = labels.to(device)
111
+ heights = heights.to(device)
112
+ bust = bust.to(device)
113
+ waist, hips = waist.to(device), hips.to(device)
114
+ # zero the parameter gradients
115
+ optimizer.zero_grad()
116
+
117
+ # forward
118
+ # track history if only in train
119
+ with torch.set_grad_enabled(phase == 'train'):
120
+ outputs_c, outputs_h, outputs_b, outputs_w, outputs_hi = model(inputs)
121
+ _, preds = torch.max(outputs_c, 1)
122
+ ce_loss = ce(outputs_c, labels)
123
+ rmse_loss_h = torch.sqrt(mse(outputs_h, heights.unsqueeze(-1)))
124
+ rmse_loss_b = torch.sqrt(mse(outputs_b, bust.unsqueeze(-1)))
125
+ rmse_loss_w = torch.sqrt(mse(outputs_w, waist.unsqueeze(-1)))
126
+ rmse_loss_hi = torch.sqrt(mse(outputs_hi, hips.unsqueeze(-1)))
127
+ rmse_loss = rmse_loss_h*4 + rmse_loss_b*2 + rmse_loss_w + rmse_loss_hi
128
+ loss = ce_loss + (rmse_loss)*1
129
+
130
+ # backward + optimize only if in training phase
131
+ if phase == 'train':
132
+ loss.backward()
133
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
134
+ optimizer.step()
135
+
136
+ # statistics
137
+ running_ce_loss += ce_loss.item() * inputs.size(0)
138
+ running_rmse_loss += rmse_loss.item() * inputs.size(0)
139
+ running_corrects += torch.sum(preds == labels.data)
140
+
141
+ epoch_ce_loss = running_ce_loss / dataset_sizes[phase]
142
+ epoch_rmse_loss = running_rmse_loss / dataset_sizes[phase]
143
+ epoch_acc = running_corrects.double() / dataset_sizes[phase]
144
+
145
+ print(f'{phase} CE_Loss: {epoch_ce_loss:.4f} RMSE_Loss: {epoch_rmse_loss:.4f} Acc: {epoch_acc:.4f}')
146
+
147
+ # deep copy the model
148
+ if phase == 'val' and epoch_acc > best_acc:
149
+ best_acc = epoch_acc
150
+ best_model_wts = copy.deepcopy(model.state_dict())
151
+ #if epoch %2 == 0 and phase == 'val':print(outputs_c, outputs_h)
152
+ print()
153
+
154
+ time_elapsed = time.time() - since
155
+ print(f'Training complete in {time_elapsed // 60:.0f}m {time_elapsed % 60:.0f}s')
156
+ print(f'Best val Acc: {best_acc:4f}')
157
+
158
+ # load best model weights
159
+ model.load_state_dict(best_model_wts)
160
+ return model
161
+
162
+ def visualize_model(model, device, dataloaders, class_names, num_images=6):
163
+ was_training = model.training
164
+ model.eval()
165
+ images_so_far = 0
166
+ fig = plt.figure()
167
+
168
+ with torch.no_grad():
169
+ for i, (inputs, labels) in enumerate(dataloaders['val']):
170
+ inputs = inputs.to(device)
171
+ labels = labels.to(device)
172
+
173
+ outputs = model(inputs)
174
+ _, preds = torch.max(outputs, 1)
175
+
176
+ for j in range(inputs.size()[0]):
177
+ images_so_far += 1
178
+ ax = plt.subplot(num_images//2, 2, images_so_far)
179
+ ax.axis('off')
180
+ ax.set_title(f'pred: {class_names[preds[j]]}|tar: {class_names[labels[j]]}')
181
+ imshow(inputs.cpu().data[j])
182
+
183
+ if images_so_far == num_images:
184
+ model.train(mode=was_training)
185
+ return
186
+ model.train(mode=was_training)
187
+
188
+ def evaluation(model, epoch, device, dataloaders):
189
+ model.load_state_dict(torch.load(f'models/model_{epoch}.pt'))
190
+ model.eval()
191
+ with torch.no_grad():
192
+ for i, (inputs, labels) in enumerate(dataloaders['val']):
193
+ inputs = inputs.to(device)
194
+ labels = labels.to(device)
195
+
196
+ outputs = model(inputs)
197
+ _, preds = torch.max(outputs, 1)
198
+ print(preds)
199
+
200
+ def inference(inp_img, classes = ['big', 'small'], epoch = 6):
201
+ device = torch.device("cpu")
202
+ translator= Translator(to_lang="zh-TW")
203
+
204
+ model = model = CUPredictor()
205
+ model.load_state_dict(torch.load(f'models/model_{epoch}.pt'))
206
+ # load image-to-text model
207
+ processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
208
+ model_blip = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
209
+ model.eval()
210
+
211
+ trans = transforms.Compose([
212
+ transforms.Resize(256),
213
+ transforms.CenterCrop(224),
214
+ transforms.ToTensor(),
215
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
216
+ ])
217
+
218
+ image_tensor = trans(inp_img)
219
+ image_tensor = image_tensor.unsqueeze(0)
220
+ with torch.no_grad():
221
+ inputs = image_tensor.to(device)
222
+ outputs_c, outputs_h, outputs_b, outputs_w, outputs_hi = model(inputs)
223
+ _, preds = torch.max(outputs_c, 1)
224
+ idx = preds.numpy()[0]
225
+
226
+ # unconditional image captioning
227
+ inputs = processor(inp_img, return_tensors="pt")
228
+ out = model_blip.generate(**inputs)
229
+ description = processor.decode(out[0], skip_special_tokens=True)
230
+ description_tw = translator.translate(description)
231
+ return outputs_c, classes[idx], f"{outputs_h.numpy()[0][0]:.2f}", f"{outputs_b.numpy()[0][0]:.2f}", f"{outputs_w.numpy()[0][0]:.2f}", f"{outputs_hi.numpy()[0][0]:.2f}", [description, description_tw]
232
+
233
+ def main(epoch = 15, mode = 'val'):
234
+ cudnn.benchmark = True
235
+ plt.ion() # interactive mode
236
+ model = CUPredictor()
237
+ train_dataset = imgDataset('labels.txt', mode='train', use_processor=False)
238
+ test_dataset = imgDataset('labels.txt', mode='val', use_processor=False)
239
+ dataloaders = {
240
+ "train": DataLoader(train_dataset, batch_size=64, shuffle=True),
241
+ "val": DataLoader(test_dataset, batch_size=64, shuffle=False)
242
+ }
243
+ dataset_sizes = {
244
+ "train": len(train_dataset),
245
+ "val": len(test_dataset)
246
+ }
247
+ device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
248
+ #device = torch.device("cpu")
249
+ model = model.to(device)
250
+ model_conv = train_model(model, device, dataloaders, dataset_sizes, num_epochs=epoch)
251
+ torch.save(model_conv.state_dict(), f'models/model_{epoch}.pt')
252
+
253
+ def divide_class_dir(path):
254
+ file_list = os.listdir(path)
255
+ for img_name in file_list:
256
+ dest_path = os.path.join(path, img_name.split('-')[3])
257
+ if not os.path.exists(dest_path):
258
+ os.mkdir(dest_path) # 建立資料夾
259
+ os.replace(os.path.join(path, img_name), os.path.join(dest_path, img_name))
260
+
261
+ def get_label(types):
262
+ with open('labels.txt', 'w', encoding='utf-8') as f:
263
+ for f_type in types:
264
+ for img_type in CLASS:
265
+ path = os.path.join('images', f_type, img_type)
266
+ file_list = os.listdir(path)
267
+ for file_name in file_list:
268
+ file_name_list = file_name.split('-')
269
+ f.write(" ".join([f_type, file_name, img_type, file_name_list[4].split('_')[0], '\n']))
270
+
271
+ if __name__ == "__main__":
272
+
273
+ CLASS = ['big', 'small']
274
+ mode = 'train'
275
+ get_label(['train', 'val'])
276
+ epoch = 7
277
+ #main(epoch, mode = mode)
278
+
279
+ outputs, preds, heights, bust, waist, hips, description = inference('images/test/lin.png', CLASS, epoch=epoch)
280
+ print(outputs, preds, heights, bust, waist, hips)
281
+ #print(CUPredictor())
282
+ #divide_class_dir('./images/train_all')
283
+ #divide_class_dir('./images/val_all')
284
+ ''''''
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ torch
2
+ transformers
3
+ translate
4
+ torchvision
5
+ scikit-learn
6
+ pandas
7
+ numpy