Spaces:
Running
on
Zero
Running
on
Zero
Commit
·
63df902
1
Parent(s):
215519d
modify model
Browse files- ace_inference.py +0 -356
- example.py +0 -370
- utils.py +0 -95
ace_inference.py
DELETED
@@ -1,356 +0,0 @@
|
|
1 |
-
# -*- coding: utf-8 -*-
|
2 |
-
# Copyright (c) Alibaba, Inc. and its affiliates.
|
3 |
-
import copy
|
4 |
-
import math
|
5 |
-
import random
|
6 |
-
|
7 |
-
import numpy as np
|
8 |
-
import torch
|
9 |
-
import torch.nn as nn
|
10 |
-
import torch.nn.functional as F
|
11 |
-
import torchvision.transforms.functional as TF
|
12 |
-
from PIL import Image
|
13 |
-
import torchvision.transforms as T
|
14 |
-
from scepter.modules.model.registry import DIFFUSIONS
|
15 |
-
from scepter.modules.model.utils.basic_utils import check_list_of_list
|
16 |
-
from scepter.modules.model.utils.basic_utils import \
|
17 |
-
pack_imagelist_into_tensor_v2 as pack_imagelist_into_tensor
|
18 |
-
from scepter.modules.model.utils.basic_utils import (
|
19 |
-
to_device, unpack_tensor_into_imagelist)
|
20 |
-
from scepter.modules.utils.distribute import we
|
21 |
-
from scepter.modules.utils.logger import get_logger
|
22 |
-
|
23 |
-
from scepter.modules.inference.diffusion_inference import DiffusionInference, get_model
|
24 |
-
|
25 |
-
|
26 |
-
def process_edit_image(images,
|
27 |
-
masks,
|
28 |
-
tasks,
|
29 |
-
max_seq_len=1024,
|
30 |
-
max_aspect_ratio=4,
|
31 |
-
d=16,
|
32 |
-
**kwargs):
|
33 |
-
|
34 |
-
if not isinstance(images, list):
|
35 |
-
images = [images]
|
36 |
-
if not isinstance(masks, list):
|
37 |
-
masks = [masks]
|
38 |
-
if not isinstance(tasks, list):
|
39 |
-
tasks = [tasks]
|
40 |
-
|
41 |
-
img_tensors = []
|
42 |
-
mask_tensors = []
|
43 |
-
for img, mask, task in zip(images, masks, tasks):
|
44 |
-
if mask is None or mask == '':
|
45 |
-
mask = Image.new('L', img.size, 0)
|
46 |
-
W, H = img.size
|
47 |
-
if H / W > max_aspect_ratio:
|
48 |
-
img = TF.center_crop(img, [int(max_aspect_ratio * W), W])
|
49 |
-
mask = TF.center_crop(mask, [int(max_aspect_ratio * W), W])
|
50 |
-
elif W / H > max_aspect_ratio:
|
51 |
-
img = TF.center_crop(img, [H, int(max_aspect_ratio * H)])
|
52 |
-
mask = TF.center_crop(mask, [H, int(max_aspect_ratio * H)])
|
53 |
-
|
54 |
-
H, W = img.height, img.width
|
55 |
-
scale = min(1.0, math.sqrt(max_seq_len / ((H / d) * (W / d))))
|
56 |
-
rH = int(H * scale) // d * d # ensure divisible by self.d
|
57 |
-
rW = int(W * scale) // d * d
|
58 |
-
|
59 |
-
img = TF.resize(img, (rH, rW),
|
60 |
-
interpolation=TF.InterpolationMode.BICUBIC)
|
61 |
-
mask = TF.resize(mask, (rH, rW),
|
62 |
-
interpolation=TF.InterpolationMode.NEAREST_EXACT)
|
63 |
-
|
64 |
-
mask = np.asarray(mask)
|
65 |
-
mask = np.where(mask > 128, 1, 0)
|
66 |
-
mask = mask.astype(
|
67 |
-
np.float32) if np.any(mask) else np.ones_like(mask).astype(
|
68 |
-
np.float32)
|
69 |
-
|
70 |
-
img_tensor = TF.to_tensor(img).to(we.device_id)
|
71 |
-
img_tensor = TF.normalize(img_tensor,
|
72 |
-
mean=[0.5, 0.5, 0.5],
|
73 |
-
std=[0.5, 0.5, 0.5])
|
74 |
-
mask_tensor = TF.to_tensor(mask).to(we.device_id)
|
75 |
-
if task in ['inpainting', 'Try On', 'Inpainting']:
|
76 |
-
mask_indicator = mask_tensor.repeat(3, 1, 1)
|
77 |
-
img_tensor[mask_indicator == 1] = -1.0
|
78 |
-
img_tensors.append(img_tensor)
|
79 |
-
mask_tensors.append(mask_tensor)
|
80 |
-
return img_tensors, mask_tensors
|
81 |
-
|
82 |
-
class TextEmbedding(nn.Module):
|
83 |
-
def __init__(self, embedding_shape):
|
84 |
-
super().__init__()
|
85 |
-
self.pos = nn.Parameter(data=torch.zeros(embedding_shape))
|
86 |
-
|
87 |
-
class ACEFluxLCInference(DiffusionInference):
|
88 |
-
def __init__(self, logger=None):
|
89 |
-
if logger is None:
|
90 |
-
logger = get_logger(name='scepter')
|
91 |
-
self.logger = logger
|
92 |
-
self.loaded_model = {}
|
93 |
-
self.loaded_model_name = [
|
94 |
-
'diffusion_model', 'first_stage_model', 'cond_stage_model', 'ref_cond_stage_model'
|
95 |
-
]
|
96 |
-
|
97 |
-
def init_from_cfg(self, cfg):
|
98 |
-
self.name = cfg.NAME
|
99 |
-
self.is_default = cfg.get('IS_DEFAULT', False)
|
100 |
-
self.use_dynamic_model = cfg.get('USE_DYNAMIC_MODEL', True)
|
101 |
-
module_paras = self.load_default(cfg.get('DEFAULT_PARAS', None))
|
102 |
-
assert cfg.have('MODEL')
|
103 |
-
self.size_factor = cfg.get('SIZE_FACTOR', 8)
|
104 |
-
self.diffusion_model = self.infer_model(
|
105 |
-
cfg.MODEL.DIFFUSION_MODEL, module_paras.get(
|
106 |
-
'DIFFUSION_MODEL',
|
107 |
-
None)) if cfg.MODEL.have('DIFFUSION_MODEL') else None
|
108 |
-
self.first_stage_model = self.infer_model(
|
109 |
-
cfg.MODEL.FIRST_STAGE_MODEL,
|
110 |
-
module_paras.get(
|
111 |
-
'FIRST_STAGE_MODEL',
|
112 |
-
None)) if cfg.MODEL.have('FIRST_STAGE_MODEL') else None
|
113 |
-
self.cond_stage_model = self.infer_model(
|
114 |
-
cfg.MODEL.COND_STAGE_MODEL,
|
115 |
-
module_paras.get(
|
116 |
-
'COND_STAGE_MODEL',
|
117 |
-
None)) if cfg.MODEL.have('COND_STAGE_MODEL') else None
|
118 |
-
|
119 |
-
self.ref_cond_stage_model = self.infer_model(
|
120 |
-
cfg.MODEL.REF_COND_STAGE_MODEL,
|
121 |
-
module_paras.get(
|
122 |
-
'REF_COND_STAGE_MODEL',
|
123 |
-
None)) if cfg.MODEL.have('REF_COND_STAGE_MODEL') else None
|
124 |
-
|
125 |
-
self.diffusion = DIFFUSIONS.build(cfg.MODEL.DIFFUSION,
|
126 |
-
logger=self.logger)
|
127 |
-
self.interpolate_func = lambda x: (F.interpolate(
|
128 |
-
x.unsqueeze(0),
|
129 |
-
scale_factor=1 / self.size_factor,
|
130 |
-
mode='nearest-exact') if x is not None else None)
|
131 |
-
|
132 |
-
self.max_seq_length = cfg.get("MAX_SEQ_LENGTH", 4096)
|
133 |
-
self.src_max_seq_length = cfg.get("SRC_MAX_SEQ_LENGTH", 1024)
|
134 |
-
self.image_token = cfg.MODEL.get("IMAGE_TOKEN", "<img>")
|
135 |
-
|
136 |
-
self.text_indentifers = cfg.MODEL.get('TEXT_IDENTIFIER', [])
|
137 |
-
self.use_text_pos_embeddings = cfg.MODEL.get('USE_TEXT_POS_EMBEDDINGS',
|
138 |
-
False)
|
139 |
-
if self.use_text_pos_embeddings:
|
140 |
-
self.text_position_embeddings = TextEmbedding(
|
141 |
-
(10, 4096)).eval().requires_grad_(False).to(we.device_id)
|
142 |
-
else:
|
143 |
-
self.text_position_embeddings = None
|
144 |
-
|
145 |
-
if not self.use_dynamic_model:
|
146 |
-
self.dynamic_load(self.first_stage_model, 'first_stage_model')
|
147 |
-
self.dynamic_load(self.cond_stage_model, 'cond_stage_model')
|
148 |
-
if self.ref_cond_stage_model is not None: self.dynamic_load(self.ref_cond_stage_model, 'ref_cond_stage_model')
|
149 |
-
self.dynamic_load(self.diffusion_model, 'diffusion_model')
|
150 |
-
|
151 |
-
def upscale_resize(self, image, interpolation=T.InterpolationMode.BILINEAR):
|
152 |
-
c, H, W = image.shape
|
153 |
-
scale = max(1.0, math.sqrt(self.max_seq_length / ((H / 16) * (W / 16))))
|
154 |
-
rH = int(H * scale) // 16 * 16 # ensure divisible by self.d
|
155 |
-
rW = int(W * scale) // 16 * 16
|
156 |
-
image = T.Resize((rH, rW), interpolation=interpolation, antialias=True)(image)
|
157 |
-
return image
|
158 |
-
|
159 |
-
|
160 |
-
@torch.no_grad()
|
161 |
-
def encode_first_stage(self, x, **kwargs):
|
162 |
-
_, dtype = self.get_function_info(self.first_stage_model, 'encode')
|
163 |
-
with torch.autocast('cuda',
|
164 |
-
enabled=dtype in ('float16', 'bfloat16'),
|
165 |
-
dtype=getattr(torch, dtype)):
|
166 |
-
def run_one_image(u):
|
167 |
-
zu = get_model(self.first_stage_model).encode(u)
|
168 |
-
if isinstance(zu, (tuple, list)):
|
169 |
-
zu = zu[0]
|
170 |
-
return zu
|
171 |
-
|
172 |
-
z = [run_one_image(u.unsqueeze(0) if u.dim() == 3 else u) for u in x]
|
173 |
-
return z
|
174 |
-
|
175 |
-
|
176 |
-
@torch.no_grad()
|
177 |
-
def decode_first_stage(self, z):
|
178 |
-
_, dtype = self.get_function_info(self.first_stage_model, 'decode')
|
179 |
-
with torch.autocast('cuda',
|
180 |
-
enabled=dtype in ('float16', 'bfloat16'),
|
181 |
-
dtype=getattr(torch, dtype)):
|
182 |
-
return [get_model(self.first_stage_model).decode(zu) for zu in z]
|
183 |
-
|
184 |
-
def noise_sample(self, num_samples, h, w, seed, device = None, dtype = torch.bfloat16):
|
185 |
-
noise = torch.randn(
|
186 |
-
num_samples,
|
187 |
-
16,
|
188 |
-
# allow for packing
|
189 |
-
2 * math.ceil(h / 16),
|
190 |
-
2 * math.ceil(w / 16),
|
191 |
-
device=device,
|
192 |
-
dtype=dtype,
|
193 |
-
generator=torch.Generator(device=device).manual_seed(seed),
|
194 |
-
)
|
195 |
-
return noise
|
196 |
-
|
197 |
-
# def preprocess_prompt(self, prompt):
|
198 |
-
# prompt_ = [[pp] if isinstance(pp, str) else pp for pp in prompt]
|
199 |
-
# for pp_id, pp in enumerate(prompt_):
|
200 |
-
# prompt_[pp_id] = [""] + pp
|
201 |
-
# for p_id, p in enumerate(prompt_[pp_id]):
|
202 |
-
# prompt_[pp_id][p_id] = self.image_token + self.text_indentifers[p_id] + " " + p
|
203 |
-
# prompt_[pp_id] = [f";".join(prompt_[pp_id])]
|
204 |
-
# return prompt_
|
205 |
-
|
206 |
-
@torch.no_grad()
|
207 |
-
def __call__(self,
|
208 |
-
image=None,
|
209 |
-
mask=None,
|
210 |
-
prompt='',
|
211 |
-
task=None,
|
212 |
-
negative_prompt='',
|
213 |
-
output_height=1024,
|
214 |
-
output_width=1024,
|
215 |
-
sampler='flow_euler',
|
216 |
-
sample_steps=20,
|
217 |
-
guide_scale=3.5,
|
218 |
-
seed=-1,
|
219 |
-
history_io=None,
|
220 |
-
tar_index=0,
|
221 |
-
align=0,
|
222 |
-
**kwargs):
|
223 |
-
input_image, input_mask = image, mask
|
224 |
-
seed = seed if seed >= 0 else random.randint(0, 2**32 - 1)
|
225 |
-
if input_image is not None:
|
226 |
-
# assert isinstance(input_image, list) and isinstance(input_mask, list)
|
227 |
-
if task is None:
|
228 |
-
task = [''] * len(input_image)
|
229 |
-
if not isinstance(prompt, list):
|
230 |
-
prompt = [prompt] * len(input_image)
|
231 |
-
prompt = [
|
232 |
-
pp.replace('{image}', f'{{image{i}}}') if i > 0 else pp
|
233 |
-
for i, pp in enumerate(prompt)
|
234 |
-
]
|
235 |
-
edit_image, edit_image_mask = process_edit_image(
|
236 |
-
input_image, input_mask, task, max_seq_len=self.src_max_seq_length)
|
237 |
-
image, image_mask = self.upscale_resize(edit_image[tar_index]), self.upscale_resize(edit_image_mask[
|
238 |
-
tar_index])
|
239 |
-
# edit_image, edit_image_mask = [[self.upscale_resize(i) for i in edit_image]], [[self.upscale_resize(i) for i in edit_image_mask]]
|
240 |
-
# image, image_mask = edit_image[tar_index], edit_image_mask[tar_index]
|
241 |
-
edit_image, edit_image_mask = [edit_image], [edit_image_mask]
|
242 |
-
else:
|
243 |
-
edit_image = edit_image_mask = [[]]
|
244 |
-
image = torch.zeros(
|
245 |
-
size=[3, int(output_height),
|
246 |
-
int(output_width)])
|
247 |
-
image_mask = torch.ones(
|
248 |
-
size=[1, int(output_height),
|
249 |
-
int(output_width)])
|
250 |
-
if not isinstance(prompt, list):
|
251 |
-
prompt = [prompt]
|
252 |
-
|
253 |
-
image, image_mask, prompt = [image], [image_mask], [prompt],
|
254 |
-
align = [align for p in prompt] if isinstance(align, int) else align
|
255 |
-
|
256 |
-
assert check_list_of_list(prompt) and check_list_of_list(
|
257 |
-
edit_image) and check_list_of_list(edit_image_mask)
|
258 |
-
# negative prompt is not used
|
259 |
-
image = to_device(image)
|
260 |
-
ctx = {}
|
261 |
-
# Get Noise Shape
|
262 |
-
self.dynamic_load(self.first_stage_model, 'first_stage_model')
|
263 |
-
x = self.encode_first_stage(image)
|
264 |
-
self.dynamic_unload(self.first_stage_model,
|
265 |
-
'first_stage_model',
|
266 |
-
skip_loaded=not self.use_dynamic_model)
|
267 |
-
|
268 |
-
g = torch.Generator(device=we.device_id).manual_seed(seed)
|
269 |
-
|
270 |
-
noise = [
|
271 |
-
torch.randn((1, 16, i.shape[2], i.shape[3]), device=we.device_id, dtype=torch.bfloat16).normal_(generator=g)
|
272 |
-
for i in x
|
273 |
-
]
|
274 |
-
noise, x_shapes = pack_imagelist_into_tensor(noise)
|
275 |
-
ctx['x_shapes'] = x_shapes
|
276 |
-
ctx['align'] = align
|
277 |
-
|
278 |
-
image_mask = to_device(image_mask, strict=False)
|
279 |
-
cond_mask = [self.interpolate_func(i) for i in image_mask
|
280 |
-
] if image_mask is not None else [None] * len(image)
|
281 |
-
ctx['x_mask'] = cond_mask
|
282 |
-
# Encode Prompt
|
283 |
-
instruction_prompt = [[pp[-1]] if "{image}" in pp[-1] else ["{image} " + pp[-1]] for pp in prompt]
|
284 |
-
self.dynamic_load(self.cond_stage_model, 'cond_stage_model')
|
285 |
-
function_name, dtype = self.get_function_info(self.cond_stage_model)
|
286 |
-
cont = getattr(get_model(self.cond_stage_model), function_name)(instruction_prompt)
|
287 |
-
cont["context"] = [ct[-1] for ct in cont["context"]]
|
288 |
-
cont["y"] = [ct[-1] for ct in cont["y"]]
|
289 |
-
self.dynamic_unload(self.cond_stage_model,
|
290 |
-
'cond_stage_model',
|
291 |
-
skip_loaded=not self.use_dynamic_model)
|
292 |
-
ctx.update(cont)
|
293 |
-
|
294 |
-
# Encode Edit Images
|
295 |
-
self.dynamic_load(self.first_stage_model, 'first_stage_model')
|
296 |
-
edit_image = [to_device(i, strict=False) for i in edit_image]
|
297 |
-
edit_image_mask = [to_device(i, strict=False) for i in edit_image_mask]
|
298 |
-
e_img, e_mask = [], []
|
299 |
-
for u, m in zip(edit_image, edit_image_mask):
|
300 |
-
if u is None:
|
301 |
-
continue
|
302 |
-
if m is None:
|
303 |
-
m = [None] * len(u)
|
304 |
-
e_img.append(self.encode_first_stage(u, **kwargs))
|
305 |
-
e_mask.append([self.interpolate_func(i) for i in m])
|
306 |
-
self.dynamic_unload(self.first_stage_model,
|
307 |
-
'first_stage_model',
|
308 |
-
skip_loaded=not self.use_dynamic_model)
|
309 |
-
ctx['edit_x'] = e_img
|
310 |
-
ctx['edit_mask'] = e_mask
|
311 |
-
# Encode Ref Images
|
312 |
-
if guide_scale is not None:
|
313 |
-
guide_scale = torch.full((noise.shape[0],), guide_scale, device=noise.device, dtype=noise.dtype)
|
314 |
-
else:
|
315 |
-
guide_scale = None
|
316 |
-
|
317 |
-
# Diffusion Process
|
318 |
-
self.dynamic_load(self.diffusion_model, 'diffusion_model')
|
319 |
-
function_name, dtype = self.get_function_info(self.diffusion_model)
|
320 |
-
with torch.autocast('cuda',
|
321 |
-
enabled=dtype in ('float16', 'bfloat16'),
|
322 |
-
dtype=getattr(torch, dtype)):
|
323 |
-
latent = self.diffusion.sample(
|
324 |
-
noise=noise,
|
325 |
-
sampler=sampler,
|
326 |
-
model=get_model(self.diffusion_model),
|
327 |
-
model_kwargs={
|
328 |
-
"cond": ctx, "guidance": guide_scale, "gc_seg": -1
|
329 |
-
},
|
330 |
-
steps=sample_steps,
|
331 |
-
show_progress=True,
|
332 |
-
guide_scale=guide_scale,
|
333 |
-
return_intermediate=None,
|
334 |
-
reverse_scale=-1,
|
335 |
-
**kwargs).float()
|
336 |
-
if self.use_dynamic_model: self.dynamic_unload(self.diffusion_model,
|
337 |
-
'diffusion_model',
|
338 |
-
skip_loaded=not self.use_dynamic_model)
|
339 |
-
|
340 |
-
# Decode to Pixel Space
|
341 |
-
self.dynamic_load(self.first_stage_model, 'first_stage_model')
|
342 |
-
samples = unpack_tensor_into_imagelist(latent, x_shapes)
|
343 |
-
x_samples = self.decode_first_stage(samples)
|
344 |
-
self.dynamic_unload(self.first_stage_model,
|
345 |
-
'first_stage_model',
|
346 |
-
skip_loaded=not self.use_dynamic_model)
|
347 |
-
x_samples = [x.squeeze(0) for x in x_samples]
|
348 |
-
|
349 |
-
imgs = [
|
350 |
-
torch.clamp((x_i.float() + 1.0) / 2.0,
|
351 |
-
min=0.0,
|
352 |
-
max=1.0).squeeze(0).permute(1, 2, 0).cpu().numpy()
|
353 |
-
for x_i in x_samples
|
354 |
-
]
|
355 |
-
imgs = [Image.fromarray((img * 255).astype(np.uint8)) for img in imgs]
|
356 |
-
return imgs
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
example.py
DELETED
@@ -1,370 +0,0 @@
|
|
1 |
-
# -*- coding: utf-8 -*-
|
2 |
-
# Copyright (c) Alibaba, Inc. and its affiliates.
|
3 |
-
import os
|
4 |
-
from PIL import Image
|
5 |
-
from scepter.modules.utils.file_system import FS
|
6 |
-
|
7 |
-
|
8 |
-
def download_image(image, local_path=None):
|
9 |
-
if not FS.exists(local_path):
|
10 |
-
local_path = FS.get_from(image, local_path=local_path)
|
11 |
-
if local_path.split(".")[-1] in ['jpg', 'jpeg']:
|
12 |
-
im = Image.open(local_path).convert("RGB")
|
13 |
-
im.save(local_path, format='JPEG')
|
14 |
-
return local_path
|
15 |
-
|
16 |
-
|
17 |
-
def get_examples(cache_dir):
|
18 |
-
print('Downloading Examples ...')
|
19 |
-
examples = [
|
20 |
-
[
|
21 |
-
'Facial Editing',
|
22 |
-
download_image(
|
23 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/e33edc106953.png?raw=true',
|
24 |
-
os.path.join(cache_dir, 'examples/e33edc106953.jpg')), None,
|
25 |
-
None, '{image} let the man smile', 6666
|
26 |
-
],
|
27 |
-
[
|
28 |
-
'Facial Editing',
|
29 |
-
download_image(
|
30 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/5d2bcc91a3e9.png?raw=true',
|
31 |
-
os.path.join(cache_dir, 'examples/5d2bcc91a3e9.jpg')), None,
|
32 |
-
None, 'let the man in {image} wear sunglasses', 9999
|
33 |
-
],
|
34 |
-
[
|
35 |
-
'Facial Editing',
|
36 |
-
download_image(
|
37 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/3a52eac708bd.png?raw=true',
|
38 |
-
os.path.join(cache_dir, 'examples/3a52eac708bd.jpg')), None,
|
39 |
-
None, '{image} red hair', 9999
|
40 |
-
],
|
41 |
-
[
|
42 |
-
'Facial Editing',
|
43 |
-
download_image(
|
44 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/3f4dc464a0ea.png?raw=true',
|
45 |
-
os.path.join(cache_dir, 'examples/3f4dc464a0ea.jpg')), None,
|
46 |
-
None, '{image} let the man serious', 99999
|
47 |
-
],
|
48 |
-
[
|
49 |
-
'Controllable Generation',
|
50 |
-
download_image(
|
51 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/131ca90fd2a9.png?raw=true',
|
52 |
-
os.path.join(cache_dir,
|
53 |
-
'examples/131ca90fd2a9.jpg')), None, None,
|
54 |
-
'"A person sits contemplatively on the ground, surrounded by falling autumn leaves. Dressed in a green sweater and dark blue pants, they rest their chin on their hand, exuding a relaxed demeanor. Their stylish checkered slip-on shoes add a touch of flair, while a black purse lies in their lap. The backdrop of muted brown enhances the warm, cozy atmosphere of the scene." , generate the image that corresponds to the given scribble {image}.',
|
55 |
-
613725
|
56 |
-
],
|
57 |
-
[
|
58 |
-
'Render Text',
|
59 |
-
download_image(
|
60 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/33e9f27c2c48.png?raw=true',
|
61 |
-
os.path.join(cache_dir, 'examples/33e9f27c2c48.jpg')),
|
62 |
-
download_image(
|
63 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/33e9f27c2c48_mask.png?raw=true',
|
64 |
-
os.path.join(cache_dir,
|
65 |
-
'examples/33e9f27c2c48_mask.jpg')), None,
|
66 |
-
'Put the text "C A T" at the position marked by mask in the {image}',
|
67 |
-
6666
|
68 |
-
],
|
69 |
-
[
|
70 |
-
'Style Transfer',
|
71 |
-
download_image(
|
72 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/9e73e7eeef55.png?raw=true',
|
73 |
-
os.path.join(cache_dir, 'examples/9e73e7eeef55.jpg')), None,
|
74 |
-
download_image(
|
75 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/2e02975293d6.png?raw=true',
|
76 |
-
os.path.join(cache_dir, 'examples/2e02975293d6.jpg')),
|
77 |
-
'edit {image} based on the style of {image1} ', 99999
|
78 |
-
],
|
79 |
-
[
|
80 |
-
'Outpainting',
|
81 |
-
download_image(
|
82 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/f2b22c08be3f.png?raw=true',
|
83 |
-
os.path.join(cache_dir, 'examples/f2b22c08be3f.jpg')),
|
84 |
-
download_image(
|
85 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/f2b22c08be3f_mask.png?raw=true',
|
86 |
-
os.path.join(cache_dir,
|
87 |
-
'examples/f2b22c08be3f_mask.jpg')), None,
|
88 |
-
'Could the {image} be widened within the space designated by mask, while retaining the original?',
|
89 |
-
6666
|
90 |
-
],
|
91 |
-
[
|
92 |
-
'Image Segmentation',
|
93 |
-
download_image(
|
94 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/db3ebaa81899.png?raw=true',
|
95 |
-
os.path.join(cache_dir, 'examples/db3ebaa81899.jpg')), None,
|
96 |
-
None, '{image} Segmentation', 6666
|
97 |
-
],
|
98 |
-
[
|
99 |
-
'Depth Estimation',
|
100 |
-
download_image(
|
101 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/f1927c4692ba.png?raw=true',
|
102 |
-
os.path.join(cache_dir, 'examples/f1927c4692ba.jpg')), None,
|
103 |
-
None, '{image} Depth Estimation', 6666
|
104 |
-
],
|
105 |
-
[
|
106 |
-
'Pose Estimation',
|
107 |
-
download_image(
|
108 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/014e5bf3b4d1.png?raw=true',
|
109 |
-
os.path.join(cache_dir, 'examples/014e5bf3b4d1.jpg')), None,
|
110 |
-
None, '{image} distinguish the poses of the figures', 999999
|
111 |
-
],
|
112 |
-
[
|
113 |
-
'Scribble Extraction',
|
114 |
-
download_image(
|
115 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/5f59a202f8ac.png?raw=true',
|
116 |
-
os.path.join(cache_dir, 'examples/5f59a202f8ac.jpg')), None,
|
117 |
-
None, 'Generate a scribble of {image}, please.', 6666
|
118 |
-
],
|
119 |
-
[
|
120 |
-
'Mosaic',
|
121 |
-
download_image(
|
122 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/3a2f52361eea.png?raw=true',
|
123 |
-
os.path.join(cache_dir, 'examples/3a2f52361eea.jpg')), None,
|
124 |
-
None, 'Adapt {image} into a mosaic representation.', 6666
|
125 |
-
],
|
126 |
-
[
|
127 |
-
'Edge map Extraction',
|
128 |
-
download_image(
|
129 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/b9d1e519d6e5.png?raw=true',
|
130 |
-
os.path.join(cache_dir, 'examples/b9d1e519d6e5.jpg')), None,
|
131 |
-
None, 'Get the edge-enhanced result for {image}.', 6666
|
132 |
-
],
|
133 |
-
[
|
134 |
-
'Grayscale',
|
135 |
-
download_image(
|
136 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/c4ebbe2ba29b.png?raw=true',
|
137 |
-
os.path.join(cache_dir, 'examples/c4ebbe2ba29b.jpg')), None,
|
138 |
-
None, 'transform {image} into a black and white one', 6666
|
139 |
-
],
|
140 |
-
[
|
141 |
-
'Contour Extraction',
|
142 |
-
download_image(
|
143 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/19652d0f6c4b.png?raw=true',
|
144 |
-
os.path.join(cache_dir,
|
145 |
-
'examples/19652d0f6c4b.jpg')), None, None,
|
146 |
-
'Would you be able to make a contour picture from {image} for me?',
|
147 |
-
6666
|
148 |
-
],
|
149 |
-
[
|
150 |
-
'Controllable Generation',
|
151 |
-
download_image(
|
152 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/249cda2844b7.png?raw=true',
|
153 |
-
os.path.join(cache_dir,
|
154 |
-
'examples/249cda2844b7.jpg')), None, None,
|
155 |
-
'Following the segmentation outcome in mask of {image}, develop a real-life image using the explanatory note in "a mighty cat lying on the bed”.',
|
156 |
-
6666
|
157 |
-
],
|
158 |
-
[
|
159 |
-
'Controllable Generation',
|
160 |
-
download_image(
|
161 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/411f6c4b8e6c.png?raw=true',
|
162 |
-
os.path.join(cache_dir,
|
163 |
-
'examples/411f6c4b8e6c.jpg')), None, None,
|
164 |
-
'use the depth map {image} and the text caption "a cut white cat" to create a corresponding graphic image',
|
165 |
-
999999
|
166 |
-
],
|
167 |
-
[
|
168 |
-
'Controllable Generation',
|
169 |
-
download_image(
|
170 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/a35c96ed137a.png?raw=true',
|
171 |
-
os.path.join(cache_dir,
|
172 |
-
'examples/a35c96ed137a.jpg')), None, None,
|
173 |
-
'help translate this posture schema {image} into a colored image based on the context I provided "A beautiful woman Climbing the climbing wall, wearing a harness and climbing gear, skillfully maneuvering up the wall with her back to the camera, with a safety rope."',
|
174 |
-
3599999
|
175 |
-
],
|
176 |
-
[
|
177 |
-
'Controllable Generation',
|
178 |
-
download_image(
|
179 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/dcb2fc86f1ce.png?raw=true',
|
180 |
-
os.path.join(cache_dir,
|
181 |
-
'examples/dcb2fc86f1ce.jpg')), None, None,
|
182 |
-
'Transform and generate an image using mosaic {image} and "Monarch butterflies gracefully perch on vibrant purple flowers, showcasing their striking orange and black wings in a lush garden setting." description',
|
183 |
-
6666
|
184 |
-
],
|
185 |
-
[
|
186 |
-
'Controllable Generation',
|
187 |
-
download_image(
|
188 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/4cd4ee494962.png?raw=true',
|
189 |
-
os.path.join(cache_dir,
|
190 |
-
'examples/4cd4ee494962.jpg')), None, None,
|
191 |
-
'make this {image} colorful as per the "beautiful sunflowers"',
|
192 |
-
6666
|
193 |
-
],
|
194 |
-
[
|
195 |
-
'Controllable Generation',
|
196 |
-
download_image(
|
197 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/a47e3a9cd166.png?raw=true',
|
198 |
-
os.path.join(cache_dir,
|
199 |
-
'examples/a47e3a9cd166.jpg')), None, None,
|
200 |
-
'Take the edge conscious {image} and the written guideline "A whimsical animated character is depicted holding a delectable cake adorned with blue and white frosting and a drizzle of chocolate. The character wears a yellow headband with a bow, matching a cozy yellow sweater. Her dark hair is styled in a braid, tied with a yellow ribbon. With a golden fork in hand, she stands ready to enjoy a slice, exuding an air of joyful anticipation. The scene is creatively rendered with a charming and playful aesthetic." and produce a realistic image.',
|
201 |
-
613725
|
202 |
-
],
|
203 |
-
[
|
204 |
-
'Controllable Generation',
|
205 |
-
download_image(
|
206 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/d890ed8a3ac2.png?raw=true',
|
207 |
-
os.path.join(cache_dir,
|
208 |
-
'examples/d890ed8a3ac2.jpg')), None, None,
|
209 |
-
'creating a vivid image based on {image} and description "This image features a delicious rectangular tart with a flaky, golden-brown crust. The tart is topped with evenly sliced tomatoes, layered over a creamy cheese filling. Aromatic herbs are sprinkled on top, adding a touch of green and enhancing the visual appeal. The background includes a soft, textured fabric and scattered white flowers, creating an elegant and inviting presentation. Bright red tomatoes in the upper right corner hint at the fresh ingredients used in the dish."',
|
210 |
-
6666
|
211 |
-
],
|
212 |
-
[
|
213 |
-
'Image Denoising',
|
214 |
-
download_image(
|
215 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/0844a686a179.png?raw=true',
|
216 |
-
os.path.join(cache_dir,
|
217 |
-
'examples/0844a686a179.jpg')), None, None,
|
218 |
-
'Eliminate noise interference in {image} and maximize the crispness to obtain superior high-definition quality',
|
219 |
-
6666
|
220 |
-
],
|
221 |
-
[
|
222 |
-
'Inpainting',
|
223 |
-
download_image(
|
224 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/fa91b6b7e59b.png?raw=true',
|
225 |
-
os.path.join(cache_dir, 'examples/fa91b6b7e59b.jpg')),
|
226 |
-
download_image(
|
227 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/fa91b6b7e59b_mask.png?raw=true',
|
228 |
-
os.path.join(cache_dir,
|
229 |
-
'examples/fa91b6b7e59b_mask.jpg')), None,
|
230 |
-
'Ensure to overhaul the parts of the {image} indicated by the mask.',
|
231 |
-
6666
|
232 |
-
],
|
233 |
-
[
|
234 |
-
'Inpainting',
|
235 |
-
download_image(
|
236 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/632899695b26.png?raw=true',
|
237 |
-
os.path.join(cache_dir, 'examples/632899695b26.jpg')),
|
238 |
-
download_image(
|
239 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/632899695b26_mask.png?raw=true',
|
240 |
-
os.path.join(cache_dir,
|
241 |
-
'examples/632899695b26_mask.jpg')), None,
|
242 |
-
'Refashion the mask portion of {image} in accordance with "A yellow egg with a smiling face painted on it"',
|
243 |
-
6666
|
244 |
-
],
|
245 |
-
[
|
246 |
-
'General Editing',
|
247 |
-
download_image(
|
248 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/354d17594afe.png?raw=true',
|
249 |
-
os.path.join(cache_dir,
|
250 |
-
'examples/354d17594afe.jpg')), None, None,
|
251 |
-
'{image} change the dog\'s posture to walking in the water, and change the background to green plants and a pond.',
|
252 |
-
6666
|
253 |
-
],
|
254 |
-
[
|
255 |
-
'General Editing',
|
256 |
-
download_image(
|
257 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/38946455752b.png?raw=true',
|
258 |
-
os.path.join(cache_dir,
|
259 |
-
'examples/38946455752b.jpg')), None, None,
|
260 |
-
'{image} change the color of the dress from white to red and the model\'s hair color red brown to blonde.Other parts remain unchanged',
|
261 |
-
6669
|
262 |
-
],
|
263 |
-
[
|
264 |
-
'Facial Editing',
|
265 |
-
download_image(
|
266 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/3ba5202f0cd8.png?raw=true',
|
267 |
-
os.path.join(cache_dir,
|
268 |
-
'examples/3ba5202f0cd8.jpg')), None, None,
|
269 |
-
'Keep the same facial feature in @3ba5202f0cd8, change the woman\'s clothing from a Blue denim jacket to a white turtleneck sweater and adjust her posture so that she is supporting her chin with both hands. Other aspects, such as background, hairstyle, facial expression, etc, remain unchanged.',
|
270 |
-
99999
|
271 |
-
],
|
272 |
-
[
|
273 |
-
'Facial Editing',
|
274 |
-
download_image(
|
275 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/369365b94725.png?raw=true',
|
276 |
-
os.path.join(cache_dir, 'examples/369365b94725.jpg')), None,
|
277 |
-
None, '{image} Make her looking at the camera', 6666
|
278 |
-
],
|
279 |
-
[
|
280 |
-
'Facial Editing',
|
281 |
-
download_image(
|
282 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/92751f2e4a0e.png?raw=true',
|
283 |
-
os.path.join(cache_dir, 'examples/92751f2e4a0e.jpg')), None,
|
284 |
-
None, '{image} Remove the smile from his face', 9899999
|
285 |
-
],
|
286 |
-
[
|
287 |
-
'Remove Text',
|
288 |
-
download_image(
|
289 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/8530a6711b2e.png?raw=true',
|
290 |
-
os.path.join(cache_dir, 'examples/8530a6711b2e.jpg')), None,
|
291 |
-
None, 'Aim to remove any textual element in {image}', 6666
|
292 |
-
],
|
293 |
-
[
|
294 |
-
'Remove Text',
|
295 |
-
download_image(
|
296 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/c4d7fb28f8f6.png?raw=true',
|
297 |
-
os.path.join(cache_dir, 'examples/c4d7fb28f8f6.jpg')),
|
298 |
-
download_image(
|
299 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/c4d7fb28f8f6_mask.png?raw=true',
|
300 |
-
os.path.join(cache_dir,
|
301 |
-
'examples/c4d7fb28f8f6_mask.jpg')), None,
|
302 |
-
'Rub out any text found in the mask sector of the {image}.', 6666
|
303 |
-
],
|
304 |
-
[
|
305 |
-
'Remove Object',
|
306 |
-
download_image(
|
307 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/e2f318fa5e5b.png?raw=true',
|
308 |
-
os.path.join(cache_dir,
|
309 |
-
'examples/e2f318fa5e5b.jpg')), None, None,
|
310 |
-
'Remove the unicorn in this {image}, ensuring a smooth edit.',
|
311 |
-
99999
|
312 |
-
],
|
313 |
-
[
|
314 |
-
'Remove Object',
|
315 |
-
download_image(
|
316 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/1ae96d8aca00.png?raw=true',
|
317 |
-
os.path.join(cache_dir, 'examples/1ae96d8aca00.jpg')),
|
318 |
-
download_image(
|
319 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/1ae96d8aca00_mask.png?raw=true',
|
320 |
-
os.path.join(cache_dir, 'examples/1ae96d8aca00_mask.jpg')),
|
321 |
-
None, 'Discard the contents of the mask area from {image}.', 99999
|
322 |
-
],
|
323 |
-
[
|
324 |
-
'Add Object',
|
325 |
-
download_image(
|
326 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/80289f48e511.png?raw=true',
|
327 |
-
os.path.join(cache_dir, 'examples/80289f48e511.jpg')),
|
328 |
-
download_image(
|
329 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/80289f48e511_mask.png?raw=true',
|
330 |
-
os.path.join(cache_dir,
|
331 |
-
'examples/80289f48e511_mask.jpg')), None,
|
332 |
-
'add a Hot Air Balloon into the {image}, per the mask', 613725
|
333 |
-
],
|
334 |
-
[
|
335 |
-
'Style Transfer',
|
336 |
-
download_image(
|
337 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/d725cb2009e8.png?raw=true',
|
338 |
-
os.path.join(cache_dir, 'examples/d725cb2009e8.jpg')), None,
|
339 |
-
None, 'Change the style of {image} to colored pencil style', 99999
|
340 |
-
],
|
341 |
-
[
|
342 |
-
'Style Transfer',
|
343 |
-
download_image(
|
344 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/e0f48b3fd010.png?raw=true',
|
345 |
-
os.path.join(cache_dir, 'examples/e0f48b3fd010.jpg')), None,
|
346 |
-
None, 'make {image} to Walt Disney Animation style', 99999
|
347 |
-
],
|
348 |
-
[
|
349 |
-
'Try On',
|
350 |
-
download_image(
|
351 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/ee4ca60b8c96.png?raw=true',
|
352 |
-
os.path.join(cache_dir, 'examples/ee4ca60b8c96.jpg')),
|
353 |
-
download_image(
|
354 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/ee4ca60b8c96_mask.png?raw=true',
|
355 |
-
os.path.join(cache_dir, 'examples/ee4ca60b8c96_mask.jpg')),
|
356 |
-
download_image(
|
357 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/ebe825bbfe3c.png?raw=true',
|
358 |
-
os.path.join(cache_dir, 'examples/ebe825bbfe3c.jpg')),
|
359 |
-
'Change the cloth in {image} to the one in {image1}', 99999
|
360 |
-
],
|
361 |
-
[
|
362 |
-
'Workflow',
|
363 |
-
download_image(
|
364 |
-
'https://github.com/ali-vilab/ace-page/blob/main/assets/examples/cb85353c004b.png?raw=true',
|
365 |
-
os.path.join(cache_dir, 'examples/cb85353c004b.jpg')), None,
|
366 |
-
None, '<workflow> ice cream {image}', 99999
|
367 |
-
],
|
368 |
-
]
|
369 |
-
print('Finish. Start building UI ...')
|
370 |
-
return examples
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
utils.py
DELETED
@@ -1,95 +0,0 @@
|
|
1 |
-
#copyright (c) Alibaba, Inc. and its affiliates.
|
2 |
-
import torch
|
3 |
-
import torchvision.transforms as T
|
4 |
-
from PIL import Image
|
5 |
-
from torchvision.transforms.functional import InterpolationMode
|
6 |
-
|
7 |
-
IMAGENET_MEAN = (0.485, 0.456, 0.406)
|
8 |
-
IMAGENET_STD = (0.229, 0.224, 0.225)
|
9 |
-
|
10 |
-
|
11 |
-
def build_transform(input_size):
|
12 |
-
MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
|
13 |
-
transform = T.Compose([
|
14 |
-
T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
|
15 |
-
T.Resize((input_size, input_size),
|
16 |
-
interpolation=InterpolationMode.BICUBIC),
|
17 |
-
T.ToTensor(),
|
18 |
-
T.Normalize(mean=MEAN, std=STD)
|
19 |
-
])
|
20 |
-
return transform
|
21 |
-
|
22 |
-
|
23 |
-
def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height,
|
24 |
-
image_size):
|
25 |
-
best_ratio_diff = float('inf')
|
26 |
-
best_ratio = (1, 1)
|
27 |
-
area = width * height
|
28 |
-
for ratio in target_ratios:
|
29 |
-
target_aspect_ratio = ratio[0] / ratio[1]
|
30 |
-
ratio_diff = abs(aspect_ratio - target_aspect_ratio)
|
31 |
-
if ratio_diff < best_ratio_diff:
|
32 |
-
best_ratio_diff = ratio_diff
|
33 |
-
best_ratio = ratio
|
34 |
-
elif ratio_diff == best_ratio_diff:
|
35 |
-
if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
|
36 |
-
best_ratio = ratio
|
37 |
-
return best_ratio
|
38 |
-
|
39 |
-
|
40 |
-
def dynamic_preprocess(image,
|
41 |
-
min_num=1,
|
42 |
-
max_num=12,
|
43 |
-
image_size=448,
|
44 |
-
use_thumbnail=False):
|
45 |
-
orig_width, orig_height = image.size
|
46 |
-
aspect_ratio = orig_width / orig_height
|
47 |
-
|
48 |
-
# calculate the existing image aspect ratio
|
49 |
-
target_ratios = set((i, j) for n in range(min_num, max_num + 1)
|
50 |
-
for i in range(1, n + 1) for j in range(1, n + 1)
|
51 |
-
if i * j <= max_num and i * j >= min_num)
|
52 |
-
target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
|
53 |
-
|
54 |
-
# find the closest aspect ratio to the target
|
55 |
-
target_aspect_ratio = find_closest_aspect_ratio(aspect_ratio,
|
56 |
-
target_ratios, orig_width,
|
57 |
-
orig_height, image_size)
|
58 |
-
|
59 |
-
# calculate the target width and height
|
60 |
-
target_width = image_size * target_aspect_ratio[0]
|
61 |
-
target_height = image_size * target_aspect_ratio[1]
|
62 |
-
blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
|
63 |
-
|
64 |
-
# resize the image
|
65 |
-
resized_img = image.resize((target_width, target_height))
|
66 |
-
processed_images = []
|
67 |
-
for i in range(blocks):
|
68 |
-
box = ((i % (target_width // image_size)) * image_size,
|
69 |
-
(i // (target_width // image_size)) * image_size,
|
70 |
-
((i % (target_width // image_size)) + 1) * image_size,
|
71 |
-
((i // (target_width // image_size)) + 1) * image_size)
|
72 |
-
# split the image
|
73 |
-
split_img = resized_img.crop(box)
|
74 |
-
processed_images.append(split_img)
|
75 |
-
assert len(processed_images) == blocks
|
76 |
-
if use_thumbnail and len(processed_images) != 1:
|
77 |
-
thumbnail_img = image.resize((image_size, image_size))
|
78 |
-
processed_images.append(thumbnail_img)
|
79 |
-
return processed_images
|
80 |
-
|
81 |
-
|
82 |
-
def load_image(image_file, input_size=448, max_num=12):
|
83 |
-
if isinstance(image_file, str):
|
84 |
-
image = Image.open(image_file).convert('RGB')
|
85 |
-
else:
|
86 |
-
image = image_file
|
87 |
-
transform = build_transform(input_size=input_size)
|
88 |
-
images = dynamic_preprocess(image,
|
89 |
-
image_size=input_size,
|
90 |
-
use_thumbnail=True,
|
91 |
-
max_num=max_num)
|
92 |
-
pixel_values = [transform(image) for image in images]
|
93 |
-
pixel_values = torch.stack(pixel_values)
|
94 |
-
return pixel_values
|
95 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|