sidharthism commited on
Commit
a05ef67
1 Parent(s): fb0de80

Added app.py

Browse files
Files changed (1) hide show
  1. app.py +482 -0
app.py ADDED
@@ -0,0 +1,482 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """With os FASHION-EYE_VITON-HD Integrated Full Model Final.ipynb
3
+
4
+ Automatically generated by Colaboratory.
5
+ """
6
+
7
+ # !rm -rf sample_data
8
+ # !rm -rf fashion-eye-try-on/
9
+
10
+ import sys
11
+ from threading import Thread
12
+ import gradio as gr
13
+ import torch
14
+ from collections import OrderedDict
15
+ from PIL import Image
16
+ import torch.nn.functional as F
17
+ import torchvision.transforms as transforms
18
+ from cloth_segmentation.networks import U2NET
19
+ import gdown
20
+ from os.path import exists, join, basename, splitext
21
+ import subprocess
22
+ import os
23
+ BASE_DIR = "/home/user/app/fashion-eye-try-on"
24
+
25
+ os.system(
26
+ f"git clone https://huggingface.co/spaces/sidharthism/fashion-eye-try-on {BASE_DIR}")
27
+
28
+ # !pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu113
29
+ # !pip install -r /content/fashion-eye-try-on/requirements.txt
30
+ os.system("pip install torch>=1.6.0 torchvision -f https://download.pytorch.org/whl/cu92/torch_stable.html")
31
+ os.system("pip install opencv-python torchgeometry gdown Pillow")
32
+
33
+ os.system(f"cd {BASE_DIR}")
34
+
35
+ # Download and save checkpoints for cloth mask generation
36
+ os.system(f"rm -rf {BASE_DIR}/cloth_segmentation/checkpoints/")
37
+ os.system(
38
+ f"gdown --id 1mhF3yqd7R-Uje092eypktNl-RoZNuiCJ -O {BASE_DIR}/cloth_segmentation/checkpoints/")
39
+
40
+ os.system(
41
+ f"git clone https://github.com/shadow2496/VITON-HD {BASE_DIR}/VITON-HD")
42
+
43
+ # checkpoints
44
+ os.system(
45
+ f"gdown 1RM4OthSM6V4r7kWCu8SbPIPY14Oz8B2u -O {BASE_DIR}/VITON-HD/checkpoints/alias_final.pth")
46
+ os.system(
47
+ f"gdown 1MBHBddaAs7sy8W40jzLmNL83AUh035F1 -O {BASE_DIR}/VITON-HD/checkpoints/gmm_final.pth")
48
+ os.system(
49
+ f"gdown 1MBHBddaAs7sy8W40jzLmNL83AUh035F1 -O {BASE_DIR}/VITON-HD/checkpoints/gmm_final.pth")
50
+ os.system(
51
+ f"gdown 17U1sooR3mVIbe8a7rZuFIF3kukPchHfZ -O {BASE_DIR}/VITON-HD/checkpoints/seg_final.pth")
52
+ # test data
53
+ os.system(
54
+ f"gdown 1ncEHn_6liOot8sgt3A2DOFJBffvx8tW8 -O {BASE_DIR}/VITON-HD/datasets/test_pairs.txt")
55
+ os.system(
56
+ f"gdown 1ZA2C8yMOprwc0TV4hvrt0X-ljZugrClq -O {BASE_DIR}/VITON-HD/datasets/test.zip")
57
+
58
+ os.system(
59
+ f"unzip {BASE_DIR}/VITON-HD/datasets/test.zip -d {BASE_DIR}/VITON-HD/datasets/")
60
+
61
+ # @title To clear all the already existing test data
62
+ # !rm -rf /content/fashion-eye-try-on/VITON-HD/datasets/test/image
63
+ # !rm -rf /content/fashion-eye-try-on/VITON-HD/datasets/test/image-parse
64
+ # !rm -rf /content/fashion-eye-try-on/VITON-HD/datasets/test/cloth
65
+ # !rm -rf /content/fashion-eye-try-on/VITON-HD/datasets/test/cloth-mask
66
+ # !rm -rf /content/fashion-eye-try-on/VITON-HD/datasets/test/openpose-img
67
+ # !rm -rf /content/fashion-eye-try-on/VITON-HD/datasets/test/openpose-json
68
+
69
+ """Paddle"""
70
+
71
+ os.system(
72
+ f"git clone https://huggingface.co/spaces/sidharthism/pipeline_paddle {BASE_DIR}/pipeline_paddle")
73
+
74
+ # Required for paddle and gradio (Jinja2 dependency)
75
+ os.system("pip install paddlepaddle-gpu pymatting")
76
+ os.system(f"pip install -r {BASE_DIR}/pipeline_paddle/requirements.txt")
77
+
78
+ os.system(f"rm -rf {BASE_DIR}/pipeline_paddle/models")
79
+ if not os.path.exists(f"{BASE_DIR}/pipeline_paddle/models/ppmatting-hrnet_w18-human_1024.pdparams"):
80
+ if not os.path.exists(f"{BASE_DIR}/pipeline_paddle/models"):
81
+ os.mkdir(f"{BASE_DIR}/pipeline_paddle/models")
82
+ os.system(
83
+ f"wget https://paddleseg.bj.bcebos.com/matting/models/ppmatting-hrnet_w18-human_1024.pdparams -O {BASE_DIR}/pipeline_paddle/models/ppmatting-hrnet_w18-human_1024.pdparams")
84
+ # !wget "https://bj.bcebos.com/paddleseg/dygraph/hrnet_w18_ssld.tar.gz" -O "/content/fashion-eye-try-on/pipeline_paddle/models/hrnet_w18_ssld.tar.gz"
85
+
86
+ """Initialization
87
+
88
+ Pose estimator - open pose
89
+ """
90
+
91
+ # Clone openpose model repo
92
+ # os.system(f"git clone https://github.com/CMU-Perceptual-Computing-Lab/openpose.git {BASE_DIR}/openpose")
93
+
94
+
95
+ # @ Building and Installation of openpose model
96
+
97
+
98
+ project_name = f"{BASE_DIR}/openpose"
99
+ print(project_name)
100
+ if not exists(project_name):
101
+ # see: https://github.com/CMU-Perceptual-Computing-Lab/openpose/issues/949
102
+ # install new CMake becaue of CUDA10
103
+ os.system(
104
+ f"wget -q https://cmake.org/files/v3.13/cmake-3.13.0-Linux-x86_64.tar.gz")
105
+ os.system(
106
+ f"tar xfz cmake-3.13.0-Linux-x86_64.tar.gz --strip-components=1 -C /usr/local")
107
+ # clone openpose
108
+ os.system(
109
+ f"cd {BASE_DIR} && git clone -q --depth 1 https://github.com/CMU-Perceptual-Computing-Lab/openpose.git")
110
+ os.system(
111
+ "sed -i 's/execute_process(COMMAND git checkout master WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}\/3rdparty\/caffe)/execute_process(COMMAND git checkout f019d0dfe86f49d1140961f8c7dec22130c83154 WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}\/3rdparty\/caffe)/g' %s/openpose/CMakeLists.txt" % (BASE_DIR, ))
112
+ # install system dependencies
113
+ os.system("apt-get -qq install -y libatlas-base-dev libprotobuf-dev libleveldb-dev libsnappy-dev libhdf5-serial-dev protobuf-compiler libgflags-dev libgoogle-glog-dev liblmdb-dev opencl-headers ocl-icd-opencl-dev libviennacl-dev")
114
+ # build openpose
115
+ print("Building openpose ... May take nearly 15 mins to build ...")
116
+ os.system(f"cd {BASE_DIR}/openpose && rm -rf {BASE_DIR}/openpose/build || true && mkdir {BASE_DIR}/openpose/build && cd {BASE_DIR}/openpose/build && cmake .. && make -j`nproc`")
117
+ print("Openpose successfully build and installed.")
118
+ # subprocess.Popen(f"cd {BASE_DIR}/openpose && rm -rf {BASE_DIR}/openpose/build || true && mkdir {BASE_DIR}/openpose/build && cd {BASE_DIR}/openpose/build && cmake .. && make -j`nproc`")
119
+ # subprocess.call(["cd", f"{BASE_DIR}/openpose"])
120
+ # subprocess.check_output(["rm", "-rf", f"{BASE_DIR}/openpose/build || true"])
121
+ # subprocess.check_output(["mkdir", f"{BASE_DIR}/openpose/build"])
122
+ # subprocess.check_output(["cd", f"{BASE_DIR}/openpose/build"])
123
+ # subprocess.check_output(["cmake", ".."])
124
+ # subprocess.check_output(["make","-j`nproc`"])
125
+
126
+ # !cd {BASE_DIR}/openpose && rm -rf {BASE_DIR}/openpose/build || true && mkdir {BASE_DIR}/openpose/build && cd {BASE_DIR}/openpose/build && cmake .. && make -j`nproc`
127
+
128
+ """Self correction human parsing"""
129
+
130
+ os.system(
131
+ f"git clone https://github.com/PeikeLi/Self-Correction-Human-Parsing.git {BASE_DIR}/human_parse")
132
+
133
+ os.system(f"cd {BASE_DIR}/human_parse")
134
+ os.system(f"mkdir {BASE_DIR}/human_parse/checkpoints")
135
+ # !mkdir inputs
136
+ # !mkdir outputs
137
+
138
+ dataset = 'lip'
139
+
140
+
141
+ dataset_url = 'https://drive.google.com/uc?id=1k4dllHpu0bdx38J7H28rVVLpU-kOHmnH'
142
+ output = f'{BASE_DIR}/human_parse/checkpoints/final.pth'
143
+ gdown.download(dataset_url, output, quiet=False)
144
+
145
+ # For human parse
146
+ os.system("pip install ninja")
147
+
148
+ """Preprocessing"""
149
+
150
+ # png to jpg
151
+
152
+
153
+ def convert_to_jpg(path):
154
+ from PIL import Image
155
+ import os
156
+ if os.path.exists(path):
157
+ cl = Image.open(path)
158
+ jpg_path = path[:-4] + ".jpg"
159
+ cl.save(jpg_path)
160
+
161
+
162
+ def resize_img(path):
163
+ from PIL import Image
164
+ print(path)
165
+ im = Image.open(path)
166
+ im = im.resize((768, 1024), Image.BICUBIC)
167
+ im.save(path)
168
+
169
+
170
+ def remove_ipynb_checkpoints():
171
+ import os
172
+ os.system(
173
+ f"rm -rf {BASE_DIR}/VITON-HD/datasets/test/image/.ipynb_checkpoints")
174
+ os.system(
175
+ f"rm -rf {BASE_DIR}/VITON-HD/datasets/test/cloth/.ipynb_checkpoints")
176
+ os.system(
177
+ f"rm -rf {BASE_DIR}/VITON-HD/datasets/test/cloth-mask/.ipynb_checkpoints")
178
+
179
+ # os.chdir('/content/fashion-eye-try-on')
180
+
181
+
182
+ def preprocess():
183
+ remove_ipynb_checkpoints()
184
+ for path in os.listdir(f'{BASE_DIR}/VITON-HD/datasets/test/image/'):
185
+ resize_img(f'{BASE_DIR}/VITON-HD/datasets/test/image/{path}')
186
+ for path in os.listdir(f'{BASE_DIR}/VITON-HD/datasets/test/cloth/'):
187
+ resize_img(f'{BASE_DIR}/VITON-HD/datasets/test/cloth/{path}')
188
+ # for path in os.listdir('/content/fashion-eye-try-on/VITON-HD/datasets/test/cloth-mask/'):
189
+ # resize_img(f'/content/fashion-eye-try-on/VITON-HD/datasets/test/cloth-mask/{path}')
190
+
191
+
192
+ """Paddle - removing background"""
193
+
194
+ # PPMatting hrnet 1024
195
+ # --fg_estimate True - for higher quality output but slower prediction
196
+
197
+
198
+ def upload_remove_background_and_save_person_image(person_img):
199
+ # !export CUDA_VISIBLE_DEVICES=0
200
+ person_img = person_img.resize((768, 1024), Image.BICUBIC)
201
+ if os.path.exists(f"{BASE_DIR}/pipeline_paddle/image/person.jpg"):
202
+ os.remove(f"{BASE_DIR}/pipeline_paddle/image/person.jpg")
203
+ person_img.save(f"{BASE_DIR}/pipeline_paddle/image/person.jpg")
204
+ # resize_img(f'/content/fashion-eye-try-on/pipeline_paddle/image/person.jpg')
205
+ os.system(f"cd {BASE_DIR}/pipeline_paddle/")
206
+ os.system(f"python {BASE_DIR}/pipeline_paddle/bg_replace.py \
207
+ --config {BASE_DIR}/pipeline_paddle/configs/ppmatting/ppmatting-hrnet_w18-human_1024.yml \
208
+ --model_path {BASE_DIR}/pipeline_paddle/models/ppmatting-hrnet_w18-human_1024.pdparams \
209
+ --image_path {BASE_DIR}/pipeline_paddle/image/person.jpg \
210
+ --background 'w' \
211
+ --save_dir {BASE_DIR}/VITON-HD/datasets/test/image \
212
+ --fg_estimate True")
213
+ # --save_dir /content/fashion-eye-try-on/pipeline_paddle/output \
214
+ try:
215
+ convert_to_jpg(f"{BASE_DIR}/VITON-HD/datasets/test/image/person.png")
216
+ # os.remove("/content/fashion-eye-try-on/pipeline_paddle/output/person_alpha.png")
217
+ os.remove(f"{BASE_DIR}/VITON-HD/datasets/test/image/person_alpha.png")
218
+ # os.remove("/content/fashion-eye-try-on/pipeline_paddle/output/person_rgba.png")
219
+ os.remove(f"{BASE_DIR}/VITON-HD/datasets/test/image/person_rgba.png")
220
+ os.system(f"cd {BASE_DIR}")
221
+ except Exception as e:
222
+ print(e)
223
+ os.system(f"cd {BASE_DIR}")
224
+
225
+
226
+ # @title If multiple GPU available,uncomment and try this code
227
+ os.system("export CUDA_VISIBLE_DEVICES=0")
228
+
229
+ # Openpose pose estimation
230
+ # Ubuntu and Mac
231
+
232
+
233
+ def estimate_pose():
234
+ os.system(f"cd {BASE_DIR}/openpose && ./build/examples/openpose/openpose.bin --image_dir {BASE_DIR}/VITON-HD/datasets/test/image --write_json {BASE_DIR}/VITON-HD/datasets/test/openpose-json/ --display 0 --face --hand --render_pose 0")
235
+ os.system(f"cd {BASE_DIR}/openpose && ./build/examples/openpose/openpose.bin --image_dir {BASE_DIR}/VITON-HD/datasets/test/image --write_images {BASE_DIR}/VITON-HD/datasets/test/openpose-img/ --display 0 --hand --render_pose 1 --disable_blending true")
236
+ os.system(f"cd {BASE_DIR}")
237
+ # !cd /content/fashion-eye-try-on/openpose && ./build/examples/openpose/openpose.bin --image_dir /content/fashion-eye-try-on/pipeline_paddle/output/ --write_images /content/fashion-eye-try-on/openpose_img/ --display 0 --hand --render_pose 1 --disable_blending true
238
+
239
+ # Run self correction human parser
240
+ # !python3 /content/fashion-eye-try-on/human_parse/simple_extractor.py --dataset 'lip' --model-restore '/content/fashion-eye-try-on/human_parse/checkpoints/final.pth' --input-dir '/content/fashion-eye-try-on/image' --output-dir '/content/fashion-eye-try-on/VITON-HD/datasets/test/image-parse'
241
+
242
+
243
+ def generate_human_segmentation_map():
244
+ # remove_ipynb_checkpoints()
245
+ os.system(f"python3 {BASE_DIR}/human_parse/simple_extractor.py --dataset 'lip' --model-restore '{BASE_DIR}/human_parse/checkpoints/final.pth' --input-dir '{BASE_DIR}/VITON-HD/datasets/test/image' --output-dir '{BASE_DIR}/VITON-HD/datasets/test/image-parse'")
246
+
247
+ # model_image = os.listdir('/content/fashion-eye-try-on/VITON-HD/datasets/test/image')
248
+ # cloth_image = os.listdir('/content/fashion-eye-try-on/VITON-HD/datasets/test/cloth')
249
+ # pairs = zip(model_image, cloth_image)
250
+
251
+ # with open('/content/fashion-eye-try-on/VITON-HD/datasets/test_pairs.txt', 'w') as file:
252
+ # for model, cloth in pairs:
253
+ # file.write(f"{model} {cloth}\n")
254
+
255
+
256
+ def generate_test_pairs_txt():
257
+ with open(f"{BASE_DIR}/VITON-HD/datasets/test_pairs.txt", 'w') as file:
258
+ file.write(f"person.jpg cloth.jpg\n")
259
+
260
+ # VITON-HD
261
+ # Transfer the cloth to the model
262
+
263
+
264
+ def generate_viton_hd():
265
+ os.system(f"python {BASE_DIR}/VITON-HD/test.py --name output --dataset_list {BASE_DIR}/VITON-HD/datasets/test_pairs.txt --dataset_dir {BASE_DIR}/VITON-HD/datasets/ --checkpoint_dir {BASE_DIR}/VITON-HD/checkpoints --save_dir {BASE_DIR}/")
266
+
267
+
268
+ # To resolve ModuleNotFoundError during imports
269
+ if BASE_DIR not in sys.path:
270
+ sys.path.append(BASE_DIR)
271
+ sys.path.append(f"{BASE_DIR}/cloth_segmentation")
272
+
273
+
274
+ device = 'cuda' if torch.cuda.is_available() else "cpu"
275
+
276
+ if device == 'cuda':
277
+ torch.cuda.empty_cache()
278
+
279
+ # for hugging face
280
+ # BASE_DIR = "/home/path/app"
281
+
282
+ image_dir = 'cloth'
283
+ result_dir = 'cloth_mask'
284
+ checkpoint_path = 'cloth_segmentation/checkpoints/cloth_segm_u2net_latest.pth'
285
+
286
+
287
+ def load_checkpoint_mgpu(model, checkpoint_path):
288
+ if not os.path.exists(checkpoint_path):
289
+ print("----No checkpoints at given path----")
290
+ return
291
+ model_state_dict = torch.load(
292
+ checkpoint_path, map_location=torch.device("cpu"))
293
+ new_state_dict = OrderedDict()
294
+ for k, v in model_state_dict.items():
295
+ name = k[7:] # remove `module.`
296
+ new_state_dict[name] = v
297
+
298
+ model.load_state_dict(new_state_dict)
299
+ print("----checkpoints loaded from path: {}----".format(checkpoint_path))
300
+ return model
301
+
302
+
303
+ class Normalize_image(object):
304
+ """Normalize given tensor into given mean and standard dev
305
+ Args:
306
+ mean (float): Desired mean to substract from tensors
307
+ std (float): Desired std to divide from tensors
308
+ """
309
+
310
+ def __init__(self, mean, std):
311
+ assert isinstance(mean, (float))
312
+ if isinstance(mean, float):
313
+ self.mean = mean
314
+
315
+ if isinstance(std, float):
316
+ self.std = std
317
+
318
+ self.normalize_1 = transforms.Normalize(self.mean, self.std)
319
+ self.normalize_3 = transforms.Normalize(
320
+ [self.mean] * 3, [self.std] * 3)
321
+ self.normalize_18 = transforms.Normalize(
322
+ [self.mean] * 18, [self.std] * 18)
323
+
324
+ def __call__(self, image_tensor):
325
+ if image_tensor.shape[0] == 1:
326
+ return self.normalize_1(image_tensor)
327
+
328
+ elif image_tensor.shape[0] == 3:
329
+ return self.normalize_3(image_tensor)
330
+
331
+ elif image_tensor.shape[0] == 18:
332
+ return self.normalize_18(image_tensor)
333
+
334
+ else:
335
+ assert "Please set proper channels! Normlization implemented only for 1, 3 and 18"
336
+
337
+
338
+ def get_palette(num_cls):
339
+ """ Returns the color map for visualizing the segmentation mask.
340
+ Args:
341
+ num_cls: Number of classes
342
+ Returns:
343
+ The color map
344
+ """
345
+ n = num_cls
346
+ palette = [0] * (n * 3)
347
+ for j in range(0, n):
348
+ lab = j
349
+ palette[j * 3 + 0] = 0
350
+ palette[j * 3 + 1] = 0
351
+ palette[j * 3 + 2] = 0
352
+ i = 0
353
+ while lab:
354
+ palette[j * 3 + 0] = 255
355
+ palette[j * 3 + 1] = 255
356
+ palette[j * 3 + 2] = 255
357
+ # palette[j * 3 + 0] |= (((lab >> 0) & 1) << (7 - i))
358
+ # palette[j * 3 + 1] |= (((lab >> 1) & 1) << (7 - i))
359
+ # palette[j * 3 + 2] |= (((lab >> 2) & 1) << (7 - i))
360
+ i += 1
361
+ lab >>= 3
362
+ return palette
363
+
364
+
365
+ def generate_cloth_mask(img_dir, output_dir, chkpt_dir):
366
+ global image_dir
367
+ global result_dir
368
+ global checkpoint_path
369
+ image_dir = img_dir
370
+ result_dir = output_dir
371
+ checkpoint_path = chkpt_dir
372
+ transforms_list = []
373
+ transforms_list += [transforms.ToTensor()]
374
+ transforms_list += [Normalize_image(0.5, 0.5)]
375
+ transform_rgb = transforms.Compose(transforms_list)
376
+
377
+ net = U2NET(in_ch=3, out_ch=4)
378
+ with torch.no_grad():
379
+ net = load_checkpoint_mgpu(net, checkpoint_path)
380
+ net = net.to(device)
381
+ net = net.eval()
382
+
383
+ palette = get_palette(4)
384
+
385
+ images_list = sorted(os.listdir(image_dir))
386
+ for image_name in images_list:
387
+ img = Image.open(os.path.join(
388
+ image_dir, image_name)).convert('RGB')
389
+ img_size = img.size
390
+ img = img.resize((768, 768), Image.BICUBIC)
391
+ image_tensor = transform_rgb(img)
392
+ image_tensor = torch.unsqueeze(image_tensor, 0)
393
+
394
+ output_tensor = net(image_tensor.to(device))
395
+ output_tensor = F.log_softmax(output_tensor[0], dim=1)
396
+ output_tensor = torch.max(output_tensor, dim=1, keepdim=True)[1]
397
+ output_tensor = torch.squeeze(output_tensor, dim=0)
398
+ output_tensor = torch.squeeze(output_tensor, dim=0)
399
+ output_arr = output_tensor.cpu().numpy()
400
+
401
+ output_img = Image.fromarray(output_arr.astype('uint8'), mode='L')
402
+ output_img = output_img.resize(img_size, Image.BICUBIC)
403
+
404
+ output_img.putpalette(palette)
405
+ output_img = output_img.convert('L')
406
+ output_img.save(os.path.join(result_dir, image_name[:-4]+'.jpg'))
407
+
408
+
409
+ os.system(f"cd {BASE_DIR}")
410
+
411
+
412
+ def upload_resize_generate_cloth_mask_and_move_to_viton_hd_test_inputs(cloth_img):
413
+ os.system(f"cd {BASE_DIR}")
414
+ cloth_img = cloth_img.resize((768, 1024), Image.BICUBIC)
415
+ cloth_img.save(f"{BASE_DIR}/cloth/cloth.jpg")
416
+ cloth_img.save(f"{BASE_DIR}/VITON-HD/datasets/test/cloth/cloth.jpg")
417
+ try:
418
+ generate_cloth_mask(f"{BASE_DIR}/cloth", f"{BASE_DIR}/cloth_mask",
419
+ f"{BASE_DIR}/cloth_segmentation/checkpoints/cloth_segm_u2net_latest.pth")
420
+ cloth_mask_img = Image.open(f"{BASE_DIR}/cloth_mask/cloth.jpg")
421
+ cloth_mask_img.save(
422
+ f"{BASE_DIR}/VITON-HD/datasets/test/cloth-mask/cloth.jpg")
423
+ except Exception as e:
424
+ print(e)
425
+
426
+
427
+ # Gradio
428
+ os.system("pip install gradio")
429
+
430
+ # import cv2
431
+ IMAGEPATH = '/content/fashion-eye-try-on/VITON-HD/datasets/test/image'
432
+ CLOTHPATH = '/content/fashion-eye-try-on/VITON-HD/datasets/test/cloth'
433
+ CLOTHMASKPATH = '/content/fashion-eye-try-on/VITON-HD/datasets/test/image'
434
+
435
+
436
+ def fashion_eye_tryon(person_img, cloth_img):
437
+ result_img = person_img
438
+ # img.save(IMAGEPATH + "person.jpg")
439
+ # dress.save(CLOTHPATH + "cloth.jpg")
440
+
441
+ # txt = open("/content/VITON-HD/datasets/test_pairs.txt", "a")
442
+ # txt.write("person_img.jpg dress_img.jpg\n")
443
+ # txt.close()
444
+ # # result
445
+ # print(person_img.info, cloth_img.info)
446
+ # p_t1 = Thread(target=upload_remove_background_and_save_person_image, args=(person_img, ))
447
+ # c_t2 = Thread(target=upload_resize_generate_cloth_mask_and_move_to_viton_hd_test_inputs, args=(cloth_img, ))
448
+ # p_t1.start()
449
+ # c_t2.start()
450
+ # p_t1.join()
451
+ # c_t2.join()
452
+ # Estimate pose
453
+ try:
454
+ upload_resize_generate_cloth_mask_and_move_to_viton_hd_test_inputs(
455
+ cloth_img)
456
+ upload_remove_background_and_save_person_image(person_img)
457
+ remove_ipynb_checkpoints()
458
+ estimate_pose()
459
+ # Generate human parse
460
+ remove_ipynb_checkpoints()
461
+ generate_human_segmentation_map()
462
+ generate_test_pairs_txt()
463
+ remove_ipynb_checkpoints()
464
+ generate_viton_hd()
465
+ for p in ["/content/fashion-eye-try-on/output/person_cloth.jpg", "/content/fashion-eye-try-on/output/person.jpg_cloth.jpg"]:
466
+ if os.path.exists(p):
467
+ result_img = Image.open(p)
468
+ except Exception as e:
469
+ print(e)
470
+ return
471
+ return result_img
472
+
473
+
474
+ # res = fashion_eye_tryon("", "")
475
+ # res.show()
476
+ gr.Interface(fn=fashion_eye_tryon,
477
+ inputs=[gr.Image(type="pil", label="Your image"),
478
+ gr.Image(type="pil", label="Dress")],
479
+ outputs="image"
480
+ ).launch(debug=True, inbrowser=True, share=True)
481
+
482
+ # !pip freeze > /content/requirements_final.txt