jacktheporsche commited on
Commit
04c50e9
1 Parent(s): 560edb5

Added Files

Browse files
examples/lecun/yann-lecun2.png ADDED
examples/taylor/1-1.png ADDED
fonts/Inkfree.ttf ADDED
Binary file (41.2 kB). View file
 
images/logo.png ADDED
images/pad_images.png ADDED
utils/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from .model import PhotoMakerIDEncoder
2
+ from .pipeline import PhotoMakerStableDiffusionXLPipeline
3
+
4
+ __all__ = [
5
+ "PhotoMakerIDEncoder",
6
+ "PhotoMakerStableDiffusionXLPipeline",
7
+ ]
utils/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (309 Bytes). View file
 
utils/__pycache__/gradio_utils.cpython-39.pyc ADDED
Binary file (9.14 kB). View file
 
utils/__pycache__/model.cpython-39.pyc ADDED
Binary file (3.68 kB). View file
 
utils/__pycache__/pipeline.cpython-39.pyc ADDED
Binary file (14 kB). View file
 
utils/__pycache__/style_template.cpython-39.pyc ADDED
Binary file (2.07 kB). View file
 
utils/__pycache__/utils.cpython-39.pyc ADDED
Binary file (12.4 kB). View file
 
utils/gradio_utils.py ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import random
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+
6
+
7
+ class SpatialAttnProcessor2_0(torch.nn.Module):
8
+ r"""
9
+ Attention processor for IP-Adapater for PyTorch 2.0.
10
+ Args:
11
+ hidden_size (`int`):
12
+ The hidden size of the attention layer.
13
+ cross_attention_dim (`int`):
14
+ The number of channels in the `encoder_hidden_states`.
15
+ text_context_len (`int`, defaults to 77):
16
+ The context length of the text features.
17
+ scale (`float`, defaults to 1.0):
18
+ the weight scale of image prompt.
19
+ """
20
+
21
+ def __init__(self, hidden_size = None, cross_attention_dim=None,id_length = 4,device = "cuda",dtype = torch.float16):
22
+ super().__init__()
23
+ if not hasattr(F, "scaled_dot_product_attention"):
24
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
25
+ self.device = device
26
+ self.dtype = dtype
27
+ self.hidden_size = hidden_size
28
+ self.cross_attention_dim = cross_attention_dim
29
+ self.total_length = id_length + 1
30
+ self.id_length = id_length
31
+ self.id_bank = {}
32
+
33
+ def __call__(
34
+ self,
35
+ attn,
36
+ hidden_states,
37
+ encoder_hidden_states=None,
38
+ attention_mask=None,
39
+ temb=None):
40
+ # un_cond_hidden_states, cond_hidden_states = hidden_states.chunk(2)
41
+ # un_cond_hidden_states = self.__call2__(attn, un_cond_hidden_states,encoder_hidden_states,attention_mask,temb)
42
+ # 生成一个0到1之间的随机数
43
+ global total_count,attn_count,cur_step,mask256,mask1024,mask4096
44
+ global sa16, sa32, sa64
45
+ global write
46
+ if write:
47
+ self.id_bank[cur_step] = [hidden_states[:self.id_length], hidden_states[self.id_length:]]
48
+ else:
49
+ encoder_hidden_states = torch.cat(self.id_bank[cur_step][0],hidden_states[:1],self.id_bank[cur_step][1],hidden_states[1:])
50
+ # 判断随机数是否大于0.5
51
+ if cur_step <5:
52
+ hidden_states = self.__call2__(attn, hidden_states,encoder_hidden_states,attention_mask,temb)
53
+ else: # 256 1024 4096
54
+ random_number = random.random()
55
+ if cur_step <20:
56
+ rand_num = 0.3
57
+ else:
58
+ rand_num = 0.1
59
+ if random_number > rand_num:
60
+ if not write:
61
+ if hidden_states.shape[1] == 32* 32:
62
+ attention_mask = mask1024[mask1024.shape[0] // self.total_length * self.id_length:]
63
+ elif hidden_states.shape[1] ==16*16:
64
+ attention_mask = mask256[mask256.shape[0] // self.total_length * self.id_length:]
65
+ else:
66
+ attention_mask = mask4096[mask4096.shape[0] // self.total_length * self.id_length:]
67
+ else:
68
+ if hidden_states.shape[1] == 32* 32:
69
+ attention_mask = mask1024[:mask1024.shape[0] // self.total_length * self.id_length]
70
+ elif hidden_states.shape[1] ==16*16:
71
+ attention_mask = mask256[:mask256.shape[0] // self.total_length * self.id_length]
72
+ else:
73
+ attention_mask = mask4096[:mask4096.shape[0] // self.total_length * self.id_length]
74
+ hidden_states = self.__call1__(attn, hidden_states,encoder_hidden_states,attention_mask,temb)
75
+ else:
76
+ hidden_states = self.__call2__(attn, hidden_states,None,attention_mask,temb)
77
+ attn_count +=1
78
+ if attn_count == total_count:
79
+ attn_count = 0
80
+ cur_step += 1
81
+ mask256,mask1024,mask4096 = cal_attn_mask(self.total_length,self.id_length,sa16,sa32,sa64, device=self.device, dtype= self.dtype)
82
+
83
+ return hidden_states
84
+ def __call1__(
85
+ self,
86
+ attn,
87
+ hidden_states,
88
+ encoder_hidden_states=None,
89
+ attention_mask=None,
90
+ temb=None,
91
+ ):
92
+ residual = hidden_states
93
+ if encoder_hidden_states is not None:
94
+ raise Exception("not implement")
95
+ if attn.spatial_norm is not None:
96
+ hidden_states = attn.spatial_norm(hidden_states, temb)
97
+ input_ndim = hidden_states.ndim
98
+
99
+ if input_ndim == 4:
100
+ total_batch_size, channel, height, width = hidden_states.shape
101
+ hidden_states = hidden_states.view(total_batch_size, channel, height * width).transpose(1, 2)
102
+ total_batch_size,nums_token,channel = hidden_states.shape
103
+ img_nums = total_batch_size//2
104
+ hidden_states = hidden_states.view(-1,img_nums,nums_token,channel).reshape(-1,img_nums * nums_token,channel)
105
+
106
+ batch_size, sequence_length, _ = hidden_states.shape
107
+
108
+ if attn.group_norm is not None:
109
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
110
+
111
+ query = attn.to_q(hidden_states)
112
+
113
+ if encoder_hidden_states is None:
114
+ encoder_hidden_states = hidden_states # B, N, C
115
+ else:
116
+ encoder_hidden_states = encoder_hidden_states.view(-1,self.id_length+1,nums_token,channel).reshape(-1,(self.id_length+1) * nums_token,channel)
117
+
118
+ key = attn.to_k(encoder_hidden_states)
119
+ value = attn.to_v(encoder_hidden_states)
120
+
121
+
122
+ inner_dim = key.shape[-1]
123
+ head_dim = inner_dim // attn.heads
124
+
125
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
126
+
127
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
128
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
129
+
130
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
131
+ # TODO: add support for attn.scale when we move to Torch 2.1
132
+ hidden_states = F.scaled_dot_product_attention(
133
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
134
+ )
135
+
136
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
137
+ hidden_states = hidden_states.to(query.dtype)
138
+
139
+
140
+
141
+ # linear proj
142
+ hidden_states = attn.to_out[0](hidden_states)
143
+ # dropout
144
+ hidden_states = attn.to_out[1](hidden_states)
145
+
146
+ # if input_ndim == 4:
147
+ # tile_hidden_states = tile_hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
148
+
149
+ # if attn.residual_connection:
150
+ # tile_hidden_states = tile_hidden_states + residual
151
+
152
+ if input_ndim == 4:
153
+ hidden_states = hidden_states.transpose(-1, -2).reshape(total_batch_size, channel, height, width)
154
+ if attn.residual_connection:
155
+ hidden_states = hidden_states + residual
156
+ hidden_states = hidden_states / attn.rescale_output_factor
157
+
158
+ return hidden_states
159
+ def __call2__(
160
+ self,
161
+ attn,
162
+ hidden_states,
163
+ encoder_hidden_states=None,
164
+ attention_mask=None,
165
+ temb=None):
166
+ residual = hidden_states
167
+
168
+ if attn.spatial_norm is not None:
169
+ hidden_states = attn.spatial_norm(hidden_states, temb)
170
+
171
+ input_ndim = hidden_states.ndim
172
+
173
+ if input_ndim == 4:
174
+ batch_size, channel, height, width = hidden_states.shape
175
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
176
+
177
+ batch_size, sequence_length, _ = (
178
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
179
+ )
180
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
181
+
182
+ if attn.group_norm is not None:
183
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
184
+
185
+ query = attn.to_q(hidden_states)
186
+
187
+ if encoder_hidden_states is None:
188
+ encoder_hidden_states = hidden_states
189
+ elif attn.norm_cross:
190
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
191
+
192
+ key = attn.to_k(encoder_hidden_states)
193
+ value = attn.to_v(encoder_hidden_states)
194
+
195
+ query = attn.head_to_batch_dim(query)
196
+ key = attn.head_to_batch_dim(key)
197
+ value = attn.head_to_batch_dim(value)
198
+
199
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
200
+ hidden_states = torch.bmm(attention_probs, value)
201
+ hidden_states = attn.batch_to_head_dim(hidden_states)
202
+
203
+ # linear proj
204
+ hidden_states = attn.to_out[0](hidden_states)
205
+ # dropout
206
+ hidden_states = attn.to_out[1](hidden_states)
207
+
208
+ if input_ndim == 4:
209
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
210
+
211
+ if attn.residual_connection:
212
+ hidden_states = hidden_states + residual
213
+
214
+ hidden_states = hidden_states / attn.rescale_output_factor
215
+
216
+ return hidden_states
217
+
218
+
219
+ def cal_attn_mask(total_length,id_length,sa16,sa32,sa64,device="cuda",dtype= torch.float16):
220
+ bool_matrix256 = torch.rand((1, total_length * 256),device = device,dtype = dtype) < sa16
221
+ bool_matrix1024 = torch.rand((1, total_length * 1024),device = device,dtype = dtype) < sa32
222
+ bool_matrix4096 = torch.rand((1, total_length * 4096),device = device,dtype = dtype) < sa64
223
+ bool_matrix256 = bool_matrix256.repeat(total_length,1)
224
+ bool_matrix1024 = bool_matrix1024.repeat(total_length,1)
225
+ bool_matrix4096 = bool_matrix4096.repeat(total_length,1)
226
+ for i in range(total_length):
227
+ bool_matrix256[i:i+1,id_length*256:] = False
228
+ bool_matrix1024[i:i+1,id_length*1024:] = False
229
+ bool_matrix4096[i:i+1,id_length*4096:] = False
230
+ bool_matrix256[i:i+1,i*256:(i+1)*256] = True
231
+ bool_matrix1024[i:i+1,i*1024:(i+1)*1024] = True
232
+ bool_matrix4096[i:i+1,i*4096:(i+1)*4096] = True
233
+ mask256 = bool_matrix256.unsqueeze(1).repeat(1,256,1).reshape(-1,total_length * 256)
234
+ mask1024 = bool_matrix1024.unsqueeze(1).repeat(1,1024,1).reshape(-1,total_length * 1024)
235
+ mask4096 = bool_matrix4096.unsqueeze(1).repeat(1,4096,1).reshape(-1,total_length * 4096)
236
+ return mask256,mask1024,mask4096
237
+
238
+ def cal_attn_mask_xl(total_length,id_length,sa32,sa64,height,width,device="cuda",dtype= torch.float16):
239
+ nums_1024 = (height // 32) * (width // 32)
240
+ nums_4096 = (height // 16) * (width // 16)
241
+ bool_matrix1024 = torch.rand((1, total_length * nums_1024),device = device,dtype = dtype) < sa32
242
+ bool_matrix4096 = torch.rand((1, total_length * nums_4096),device = device,dtype = dtype) < sa64
243
+ bool_matrix1024 = bool_matrix1024.repeat(total_length,1)
244
+ bool_matrix4096 = bool_matrix4096.repeat(total_length,1)
245
+ for i in range(total_length):
246
+ bool_matrix1024[i:i+1,id_length*nums_1024:] = False
247
+ bool_matrix4096[i:i+1,id_length*nums_4096:] = False
248
+ bool_matrix1024[i:i+1,i*nums_1024:(i+1)*nums_1024] = True
249
+ bool_matrix4096[i:i+1,i*nums_4096:(i+1)*nums_4096] = True
250
+ mask1024 = bool_matrix1024.unsqueeze(1).repeat(1,nums_1024,1).reshape(-1,total_length * nums_1024)
251
+ mask4096 = bool_matrix4096.unsqueeze(1).repeat(1,nums_4096,1).reshape(-1,total_length * nums_4096)
252
+ return mask1024,mask4096
253
+
254
+
255
+ def cal_attn_indice_xl_effcient_memory(total_length,id_length,sa32,sa64,height,width,device="cuda",dtype= torch.float16):
256
+ nums_1024 = (height // 32) * (width // 32)
257
+ nums_4096 = (height // 16) * (width // 16)
258
+ bool_matrix1024 = torch.rand((total_length,nums_1024),device = device,dtype = dtype) < sa32
259
+ bool_matrix4096 = torch.rand((total_length,nums_4096),device = device,dtype = dtype) < sa64
260
+ # 用nonzero()函数获取所有为True的值的索引
261
+ indices1024 = [torch.nonzero(bool_matrix1024[i], as_tuple=True)[0] for i in range(total_length)]
262
+ indices4096 = [torch.nonzero(bool_matrix4096[i], as_tuple=True)[0] for i in range(total_length)]
263
+
264
+ return indices1024,indices4096
265
+
266
+
267
+ class AttnProcessor(nn.Module):
268
+ r"""
269
+ Default processor for performing attention-related computations.
270
+ """
271
+ def __init__(
272
+ self,
273
+ hidden_size=None,
274
+ cross_attention_dim=None,
275
+ ):
276
+ super().__init__()
277
+
278
+ def __call__(
279
+ self,
280
+ attn,
281
+ hidden_states,
282
+ encoder_hidden_states=None,
283
+ attention_mask=None,
284
+ temb=None,
285
+ ):
286
+ residual = hidden_states
287
+
288
+ if attn.spatial_norm is not None:
289
+ hidden_states = attn.spatial_norm(hidden_states, temb)
290
+
291
+ input_ndim = hidden_states.ndim
292
+
293
+ if input_ndim == 4:
294
+ batch_size, channel, height, width = hidden_states.shape
295
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
296
+
297
+ batch_size, sequence_length, _ = (
298
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
299
+ )
300
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
301
+
302
+ if attn.group_norm is not None:
303
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
304
+
305
+ query = attn.to_q(hidden_states)
306
+
307
+ if encoder_hidden_states is None:
308
+ encoder_hidden_states = hidden_states
309
+ elif attn.norm_cross:
310
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
311
+
312
+ key = attn.to_k(encoder_hidden_states)
313
+ value = attn.to_v(encoder_hidden_states)
314
+
315
+ query = attn.head_to_batch_dim(query)
316
+ key = attn.head_to_batch_dim(key)
317
+ value = attn.head_to_batch_dim(value)
318
+
319
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
320
+ hidden_states = torch.bmm(attention_probs, value)
321
+ hidden_states = attn.batch_to_head_dim(hidden_states)
322
+
323
+ # linear proj
324
+ hidden_states = attn.to_out[0](hidden_states)
325
+ # dropout
326
+ hidden_states = attn.to_out[1](hidden_states)
327
+
328
+ if input_ndim == 4:
329
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
330
+
331
+ if attn.residual_connection:
332
+ hidden_states = hidden_states + residual
333
+
334
+ hidden_states = hidden_states / attn.rescale_output_factor
335
+
336
+ return hidden_states
337
+
338
+
339
+ class AttnProcessor2_0(torch.nn.Module):
340
+ r"""
341
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
342
+ """
343
+ def __init__(
344
+ self,
345
+ hidden_size=None,
346
+ cross_attention_dim=None,
347
+ ):
348
+ super().__init__()
349
+ if not hasattr(F, "scaled_dot_product_attention"):
350
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
351
+
352
+ def __call__(
353
+ self,
354
+ attn,
355
+ hidden_states,
356
+ encoder_hidden_states=None,
357
+ attention_mask=None,
358
+ temb=None,
359
+ ):
360
+ residual = hidden_states
361
+
362
+ if attn.spatial_norm is not None:
363
+ hidden_states = attn.spatial_norm(hidden_states, temb)
364
+
365
+ input_ndim = hidden_states.ndim
366
+
367
+ if input_ndim == 4:
368
+ batch_size, channel, height, width = hidden_states.shape
369
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
370
+
371
+ batch_size, sequence_length, _ = (
372
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
373
+ )
374
+
375
+ if attention_mask is not None:
376
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
377
+ # scaled_dot_product_attention expects attention_mask shape to be
378
+ # (batch, heads, source_length, target_length)
379
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
380
+
381
+ if attn.group_norm is not None:
382
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
383
+
384
+ query = attn.to_q(hidden_states)
385
+
386
+ if encoder_hidden_states is None:
387
+ encoder_hidden_states = hidden_states
388
+ elif attn.norm_cross:
389
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
390
+
391
+ key = attn.to_k(encoder_hidden_states)
392
+ value = attn.to_v(encoder_hidden_states)
393
+
394
+ inner_dim = key.shape[-1]
395
+ head_dim = inner_dim // attn.heads
396
+
397
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
398
+
399
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
400
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
401
+
402
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
403
+ # TODO: add support for attn.scale when we move to Torch 2.1
404
+ hidden_states = F.scaled_dot_product_attention(
405
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
406
+ )
407
+
408
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
409
+ hidden_states = hidden_states.to(query.dtype)
410
+
411
+ # linear proj
412
+ hidden_states = attn.to_out[0](hidden_states)
413
+ # dropout
414
+ hidden_states = attn.to_out[1](hidden_states)
415
+
416
+ if input_ndim == 4:
417
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
418
+
419
+ if attn.residual_connection:
420
+ hidden_states = hidden_states + residual
421
+
422
+ hidden_states = hidden_states / attn.rescale_output_factor
423
+
424
+ return hidden_states
425
+
426
+
427
+ def is_torch2_available():
428
+ return hasattr(F, "scaled_dot_product_attention")
utils/model.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Merge image encoder and fuse module to create an ID Encoder
2
+ # send multiple ID images, we can directly obtain the updated text encoder containing a stacked ID embedding
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ from transformers.models.clip.modeling_clip import CLIPVisionModelWithProjection
7
+ from transformers.models.clip.configuration_clip import CLIPVisionConfig
8
+ from transformers import PretrainedConfig
9
+
10
+ VISION_CONFIG_DICT = {
11
+ "hidden_size": 1024,
12
+ "intermediate_size": 4096,
13
+ "num_attention_heads": 16,
14
+ "num_hidden_layers": 24,
15
+ "patch_size": 14,
16
+ "projection_dim": 768
17
+ }
18
+
19
+ class MLP(nn.Module):
20
+ def __init__(self, in_dim, out_dim, hidden_dim, use_residual=True):
21
+ super().__init__()
22
+ if use_residual:
23
+ assert in_dim == out_dim
24
+ self.layernorm = nn.LayerNorm(in_dim)
25
+ self.fc1 = nn.Linear(in_dim, hidden_dim)
26
+ self.fc2 = nn.Linear(hidden_dim, out_dim)
27
+ self.use_residual = use_residual
28
+ self.act_fn = nn.GELU()
29
+
30
+ def forward(self, x):
31
+ residual = x
32
+ x = self.layernorm(x)
33
+ x = self.fc1(x)
34
+ x = self.act_fn(x)
35
+ x = self.fc2(x)
36
+ if self.use_residual:
37
+ x = x + residual
38
+ return x
39
+
40
+
41
+ class FuseModule(nn.Module):
42
+ def __init__(self, embed_dim):
43
+ super().__init__()
44
+ self.mlp1 = MLP(embed_dim * 2, embed_dim, embed_dim, use_residual=False)
45
+ self.mlp2 = MLP(embed_dim, embed_dim, embed_dim, use_residual=True)
46
+ self.layer_norm = nn.LayerNorm(embed_dim)
47
+
48
+ def fuse_fn(self, prompt_embeds, id_embeds):
49
+ stacked_id_embeds = torch.cat([prompt_embeds, id_embeds], dim=-1)
50
+ stacked_id_embeds = self.mlp1(stacked_id_embeds) + prompt_embeds
51
+ stacked_id_embeds = self.mlp2(stacked_id_embeds)
52
+ stacked_id_embeds = self.layer_norm(stacked_id_embeds)
53
+ return stacked_id_embeds
54
+
55
+ def forward(
56
+ self,
57
+ prompt_embeds,
58
+ id_embeds,
59
+ class_tokens_mask,
60
+ ) -> torch.Tensor:
61
+ # id_embeds shape: [b, max_num_inputs, 1, 2048]
62
+ id_embeds = id_embeds.to(prompt_embeds.dtype)
63
+ num_inputs = class_tokens_mask.sum().unsqueeze(0) # TODO: check for training case
64
+ batch_size, max_num_inputs = id_embeds.shape[:2]
65
+ # seq_length: 77
66
+ seq_length = prompt_embeds.shape[1]
67
+ # flat_id_embeds shape: [b*max_num_inputs, 1, 2048]
68
+ flat_id_embeds = id_embeds.view(
69
+ -1, id_embeds.shape[-2], id_embeds.shape[-1]
70
+ )
71
+ # valid_id_mask [b*max_num_inputs]
72
+ valid_id_mask = (
73
+ torch.arange(max_num_inputs, device=flat_id_embeds.device)[None, :]
74
+ < num_inputs[:, None]
75
+ )
76
+ valid_id_embeds = flat_id_embeds[valid_id_mask.flatten()]
77
+
78
+ prompt_embeds = prompt_embeds.view(-1, prompt_embeds.shape[-1])
79
+ class_tokens_mask = class_tokens_mask.view(-1)
80
+ valid_id_embeds = valid_id_embeds.view(-1, valid_id_embeds.shape[-1])
81
+ # slice out the image token embeddings
82
+ image_token_embeds = prompt_embeds[class_tokens_mask]
83
+ stacked_id_embeds = self.fuse_fn(image_token_embeds, valid_id_embeds)
84
+ assert class_tokens_mask.sum() == stacked_id_embeds.shape[0], f"{class_tokens_mask.sum()} != {stacked_id_embeds.shape[0]}"
85
+ prompt_embeds.masked_scatter_(class_tokens_mask[:, None], stacked_id_embeds.to(prompt_embeds.dtype))
86
+ updated_prompt_embeds = prompt_embeds.view(batch_size, seq_length, -1)
87
+ return updated_prompt_embeds
88
+
89
+ class PhotoMakerIDEncoder(CLIPVisionModelWithProjection):
90
+ def __init__(self):
91
+ super().__init__(CLIPVisionConfig(**VISION_CONFIG_DICT))
92
+ self.visual_projection_2 = nn.Linear(1024, 1280, bias=False)
93
+ self.fuse_module = FuseModule(2048)
94
+
95
+ def forward(self, id_pixel_values, prompt_embeds, class_tokens_mask):
96
+ b, num_inputs, c, h, w = id_pixel_values.shape
97
+ id_pixel_values = id_pixel_values.view(b * num_inputs, c, h, w)
98
+
99
+ shared_id_embeds = self.vision_model(id_pixel_values)[1]
100
+ id_embeds = self.visual_projection(shared_id_embeds)
101
+ id_embeds_2 = self.visual_projection_2(shared_id_embeds)
102
+
103
+ id_embeds = id_embeds.view(b, num_inputs, 1, -1)
104
+ id_embeds_2 = id_embeds_2.view(b, num_inputs, 1, -1)
105
+
106
+ id_embeds = torch.cat((id_embeds, id_embeds_2), dim=-1)
107
+ updated_prompt_embeds = self.fuse_module(prompt_embeds, id_embeds, class_tokens_mask)
108
+
109
+ return updated_prompt_embeds
110
+
111
+
112
+ if __name__ == "__main__":
113
+ PhotoMakerIDEncoder()
utils/pipeline.py ADDED
@@ -0,0 +1,577 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Callable, Dict, List, Optional, Union, Tuple
2
+ from collections import OrderedDict
3
+ import os
4
+ import PIL
5
+ import numpy as np
6
+
7
+ import torch
8
+ from torchvision import transforms as T
9
+
10
+ from safetensors import safe_open
11
+ from huggingface_hub.utils import validate_hf_hub_args
12
+ from transformers import CLIPImageProcessor, CLIPTokenizer
13
+ from diffusers import StableDiffusionXLPipeline
14
+ from diffusers.pipelines.stable_diffusion_xl import StableDiffusionXLPipelineOutput
15
+ from diffusers.utils import (
16
+ _get_model_file,
17
+ is_transformers_available,
18
+ logging,
19
+ )
20
+
21
+ from . import PhotoMakerIDEncoder
22
+
23
+ PipelineImageInput = Union[
24
+ PIL.Image.Image,
25
+ torch.FloatTensor,
26
+ List[PIL.Image.Image],
27
+ List[torch.FloatTensor],
28
+ ]
29
+
30
+
31
+ class PhotoMakerStableDiffusionXLPipeline(StableDiffusionXLPipeline):
32
+ @validate_hf_hub_args
33
+ def load_photomaker_adapter(
34
+ self,
35
+ pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]],
36
+ weight_name: str,
37
+ subfolder: str = '',
38
+ trigger_word: str = 'img',
39
+ **kwargs,
40
+ ):
41
+ """
42
+ Parameters:
43
+ pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
44
+ Can be either:
45
+
46
+ - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
47
+ the Hub.
48
+ - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
49
+ with [`ModelMixin.save_pretrained`].
50
+ - A [torch state
51
+ dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
52
+
53
+ weight_name (`str`):
54
+ The weight name NOT the path to the weight.
55
+
56
+ subfolder (`str`, defaults to `""`):
57
+ The subfolder location of a model file within a larger model repository on the Hub or locally.
58
+
59
+ trigger_word (`str`, *optional*, defaults to `"img"`):
60
+ The trigger word is used to identify the position of class word in the text prompt,
61
+ and it is recommended not to set it as a common word.
62
+ This trigger word must be placed after the class word when used, otherwise, it will affect the performance of the personalized generation.
63
+ """
64
+
65
+ # Load the main state dict first.
66
+ cache_dir = kwargs.pop("cache_dir", None)
67
+ force_download = kwargs.pop("force_download", False)
68
+ resume_download = kwargs.pop("resume_download", False)
69
+ proxies = kwargs.pop("proxies", None)
70
+ local_files_only = kwargs.pop("local_files_only", None)
71
+ token = kwargs.pop("token", None)
72
+ revision = kwargs.pop("revision", None)
73
+
74
+ user_agent = {
75
+ "file_type": "attn_procs_weights",
76
+ "framework": "pytorch",
77
+ }
78
+
79
+ if not isinstance(pretrained_model_name_or_path_or_dict, dict):
80
+ model_file = _get_model_file(
81
+ pretrained_model_name_or_path_or_dict,
82
+ weights_name=weight_name,
83
+ cache_dir=cache_dir,
84
+ force_download=force_download,
85
+ resume_download=resume_download,
86
+ proxies=proxies,
87
+ local_files_only=local_files_only,
88
+ token=token,
89
+ revision=revision,
90
+ subfolder=subfolder,
91
+ user_agent=user_agent,
92
+ )
93
+ if weight_name.endswith(".safetensors"):
94
+ state_dict = {"id_encoder": {}, "lora_weights": {}}
95
+ with safe_open(model_file, framework="pt", device="cpu") as f:
96
+ for key in f.keys():
97
+ if key.startswith("id_encoder."):
98
+ state_dict["id_encoder"][key.replace("id_encoder.", "")] = f.get_tensor(key)
99
+ elif key.startswith("lora_weights."):
100
+ state_dict["lora_weights"][key.replace("lora_weights.", "")] = f.get_tensor(key)
101
+ else:
102
+ state_dict = torch.load(model_file, map_location="cpu")
103
+ else:
104
+ state_dict = pretrained_model_name_or_path_or_dict
105
+
106
+ keys = list(state_dict.keys())
107
+ if keys != ["id_encoder", "lora_weights"]:
108
+ raise ValueError("Required keys are (`id_encoder` and `lora_weights`) missing from the state dict.")
109
+
110
+ self.trigger_word = trigger_word
111
+ # load finetuned CLIP image encoder and fuse module here if it has not been registered to the pipeline yet
112
+ print(f"Loading PhotoMaker components [1] id_encoder from [{pretrained_model_name_or_path_or_dict}]...")
113
+ id_encoder = PhotoMakerIDEncoder()
114
+ id_encoder.load_state_dict(state_dict["id_encoder"], strict=True)
115
+ id_encoder = id_encoder.to(self.device, dtype=self.unet.dtype)
116
+ self.id_encoder = id_encoder
117
+ self.id_image_processor = CLIPImageProcessor()
118
+
119
+ # load lora into models
120
+ print(f"Loading PhotoMaker components [2] lora_weights from [{pretrained_model_name_or_path_or_dict}]")
121
+ self.load_lora_weights(state_dict["lora_weights"], adapter_name="photomaker")
122
+
123
+ # Add trigger word token
124
+ if self.tokenizer is not None:
125
+ self.tokenizer.add_tokens([self.trigger_word], special_tokens=True)
126
+
127
+ self.tokenizer_2.add_tokens([self.trigger_word], special_tokens=True)
128
+
129
+
130
+ def encode_prompt_with_trigger_word(
131
+ self,
132
+ prompt: str,
133
+ prompt_2: Optional[str] = None,
134
+ num_id_images: int = 1,
135
+ device: Optional[torch.device] = None,
136
+ prompt_embeds: Optional[torch.FloatTensor] = None,
137
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
138
+ class_tokens_mask: Optional[torch.LongTensor] = None,
139
+ ):
140
+ device = device or self._execution_device
141
+
142
+ if prompt is not None and isinstance(prompt, str):
143
+ batch_size = 1
144
+ elif prompt is not None and isinstance(prompt, list):
145
+ batch_size = len(prompt)
146
+ else:
147
+ batch_size = prompt_embeds.shape[0]
148
+
149
+ # Find the token id of the trigger word
150
+ image_token_id = self.tokenizer_2.convert_tokens_to_ids(self.trigger_word)
151
+
152
+ # Define tokenizers and text encoders
153
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
154
+ text_encoders = (
155
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
156
+ )
157
+
158
+ if prompt_embeds is None:
159
+ prompt_2 = prompt_2 or prompt
160
+ prompt_embeds_list = []
161
+ prompts = [prompt, prompt_2]
162
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
163
+ input_ids = tokenizer.encode(prompt) # TODO: batch encode
164
+ clean_index = 0
165
+ clean_input_ids = []
166
+ class_token_index = []
167
+ # Find out the corresponding class word token based on the newly added trigger word token
168
+ for i, token_id in enumerate(input_ids):
169
+ if token_id == image_token_id:
170
+ class_token_index.append(clean_index - 1)
171
+ else:
172
+ clean_input_ids.append(token_id)
173
+ clean_index += 1
174
+
175
+ if len(class_token_index) != 1:
176
+ raise ValueError(
177
+ f"PhotoMaker currently does not support multiple trigger words in a single prompt.\
178
+ Trigger word: {self.trigger_word}, Prompt: {prompt}."
179
+ )
180
+ class_token_index = class_token_index[0]
181
+
182
+ # Expand the class word token and corresponding mask
183
+ class_token = clean_input_ids[class_token_index]
184
+ clean_input_ids = clean_input_ids[:class_token_index] + [class_token] * num_id_images + \
185
+ clean_input_ids[class_token_index+1:]
186
+
187
+ # Truncation or padding
188
+ max_len = tokenizer.model_max_length
189
+ if len(clean_input_ids) > max_len:
190
+ clean_input_ids = clean_input_ids[:max_len]
191
+ else:
192
+ clean_input_ids = clean_input_ids + [tokenizer.pad_token_id] * (
193
+ max_len - len(clean_input_ids)
194
+ )
195
+
196
+ class_tokens_mask = [True if class_token_index <= i < class_token_index+num_id_images else False \
197
+ for i in range(len(clean_input_ids))]
198
+
199
+ clean_input_ids = torch.tensor(clean_input_ids, dtype=torch.long).unsqueeze(0)
200
+ class_tokens_mask = torch.tensor(class_tokens_mask, dtype=torch.bool).unsqueeze(0)
201
+
202
+ prompt_embeds = text_encoder(
203
+ clean_input_ids.to(device),
204
+ output_hidden_states=True,
205
+ )
206
+
207
+ # We are only ALWAYS interested in the pooled output of the final text encoder
208
+ pooled_prompt_embeds = prompt_embeds[0]
209
+ prompt_embeds = prompt_embeds.hidden_states[-2]
210
+ prompt_embeds_list.append(prompt_embeds)
211
+
212
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
213
+
214
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
215
+ class_tokens_mask = class_tokens_mask.to(device=device) # TODO: ignoring two-prompt case
216
+
217
+ return prompt_embeds, pooled_prompt_embeds, class_tokens_mask
218
+
219
+ @property
220
+ def interrupt(self):
221
+ return self._interrupt
222
+
223
+ @torch.no_grad()
224
+ def __call__(
225
+ self,
226
+ prompt: Union[str, List[str]] = None,
227
+ prompt_2: Optional[Union[str, List[str]]] = None,
228
+ height: Optional[int] = None,
229
+ width: Optional[int] = None,
230
+ num_inference_steps: int = 50,
231
+ denoising_end: Optional[float] = None,
232
+ guidance_scale: float = 5.0,
233
+ negative_prompt: Optional[Union[str, List[str]]] = None,
234
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
235
+ num_images_per_prompt: Optional[int] = 1,
236
+ eta: float = 0.0,
237
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
238
+ latents: Optional[torch.FloatTensor] = None,
239
+ prompt_embeds: Optional[torch.FloatTensor] = None,
240
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
241
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
242
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
243
+ output_type: Optional[str] = "pil",
244
+ return_dict: bool = True,
245
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
246
+ guidance_rescale: float = 0.0,
247
+ original_size: Optional[Tuple[int, int]] = None,
248
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
249
+ target_size: Optional[Tuple[int, int]] = None,
250
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
251
+ callback_steps: int = 1,
252
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
253
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
254
+ # Added parameters (for PhotoMaker)
255
+ input_id_images: PipelineImageInput = None,
256
+ start_merge_step: int = 0, # TODO: change to `style_strength_ratio` in the future
257
+ class_tokens_mask: Optional[torch.LongTensor] = None,
258
+ prompt_embeds_text_only: Optional[torch.FloatTensor] = None,
259
+ pooled_prompt_embeds_text_only: Optional[torch.FloatTensor] = None,
260
+ ):
261
+ r"""
262
+ Function invoked when calling the pipeline for generation.
263
+ Only the parameters introduced by PhotoMaker are discussed here.
264
+ For explanations of the previous parameters in StableDiffusionXLPipeline, please refer to https://github.com/huggingface/diffusers/blob/v0.25.0/src/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py
265
+
266
+ Args:
267
+ input_id_images (`PipelineImageInput`, *optional*):
268
+ Input ID Image to work with PhotoMaker.
269
+ class_tokens_mask (`torch.LongTensor`, *optional*):
270
+ Pre-generated class token. When the `prompt_embeds` parameter is provided in advance, it is necessary to prepare the `class_tokens_mask` beforehand for marking out the position of class word.
271
+ prompt_embeds_text_only (`torch.FloatTensor`, *optional*):
272
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
273
+ provided, text embeddings will be generated from `prompt` input argument.
274
+ pooled_prompt_embeds_text_only (`torch.FloatTensor`, *optional*):
275
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
276
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
277
+
278
+ Returns:
279
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:
280
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
281
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
282
+ """
283
+ # 0. Default height and width to unet
284
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
285
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
286
+
287
+ original_size = original_size or (height, width)
288
+ target_size = target_size or (height, width)
289
+
290
+ # 1. Check inputs. Raise error if not correct
291
+ self.check_inputs(
292
+ prompt,
293
+ prompt_2,
294
+ height,
295
+ width,
296
+ callback_steps,
297
+ negative_prompt,
298
+ negative_prompt_2,
299
+ prompt_embeds,
300
+ negative_prompt_embeds,
301
+ pooled_prompt_embeds,
302
+ negative_pooled_prompt_embeds,
303
+ callback_on_step_end_tensor_inputs,
304
+ )
305
+
306
+ self._interrupt = False
307
+
308
+ #
309
+ if prompt_embeds is not None and class_tokens_mask is None:
310
+ raise ValueError(
311
+ "If `prompt_embeds` are provided, `class_tokens_mask` also have to be passed. Make sure to generate `class_tokens_mask` from the same tokenizer that was used to generate `prompt_embeds`."
312
+ )
313
+ # check the input id images
314
+ if input_id_images is None:
315
+ raise ValueError(
316
+ "Provide `input_id_images`. Cannot leave `input_id_images` undefined for PhotoMaker pipeline."
317
+ )
318
+ if not isinstance(input_id_images, list):
319
+ input_id_images = [input_id_images]
320
+
321
+ # 2. Define call parameters
322
+ if prompt is not None and isinstance(prompt, str):
323
+ batch_size = 1
324
+ prompt = [prompt]
325
+ elif prompt is not None and isinstance(prompt, list):
326
+ batch_size = len(prompt)
327
+ else:
328
+ batch_size = prompt_embeds.shape[0]
329
+
330
+ device = self._execution_device
331
+
332
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
333
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
334
+ # corresponds to doing no classifier free guidance.
335
+ do_classifier_free_guidance = guidance_scale >= 1.0
336
+
337
+ assert do_classifier_free_guidance
338
+
339
+ # 3. Encode input prompt
340
+ num_id_images = len(input_id_images)
341
+ if isinstance(prompt, list):
342
+ prompt_arr = prompt
343
+ negative_prompt_embeds_arr = []
344
+ prompt_embeds_text_only_arr = []
345
+ prompt_embeds_arr = []
346
+ latents_arr = []
347
+ add_time_ids_arr = []
348
+ negative_pooled_prompt_embeds_arr = []
349
+ pooled_prompt_embeds_text_only_arr = []
350
+ pooled_prompt_embeds_arr = []
351
+ for prompt in prompt_arr:
352
+ (
353
+ prompt_embeds,
354
+ pooled_prompt_embeds,
355
+ class_tokens_mask,
356
+ ) = self.encode_prompt_with_trigger_word(
357
+ prompt=prompt,
358
+ prompt_2=prompt_2,
359
+ device=device,
360
+ num_id_images=num_id_images,
361
+ prompt_embeds=prompt_embeds,
362
+ pooled_prompt_embeds=pooled_prompt_embeds,
363
+ class_tokens_mask=class_tokens_mask,
364
+ )
365
+
366
+ # 4. Encode input prompt without the trigger word for delayed conditioning
367
+ # encode, remove trigger word token, then decode
368
+ tokens_text_only = self.tokenizer.encode(prompt, add_special_tokens=False)
369
+ trigger_word_token = self.tokenizer.convert_tokens_to_ids(self.trigger_word)
370
+ tokens_text_only.remove(trigger_word_token)
371
+ prompt_text_only = self.tokenizer.decode(tokens_text_only, add_special_tokens=False)
372
+ print(prompt_text_only)
373
+ (
374
+ prompt_embeds_text_only,
375
+ negative_prompt_embeds,
376
+ pooled_prompt_embeds_text_only, # TODO: replace the pooled_prompt_embeds with text only prompt
377
+ negative_pooled_prompt_embeds,
378
+ ) = self.encode_prompt(
379
+ prompt=prompt_text_only,
380
+ prompt_2=prompt_2,
381
+ device=device,
382
+ num_images_per_prompt=num_images_per_prompt,
383
+ do_classifier_free_guidance=True,
384
+ negative_prompt=negative_prompt,
385
+ negative_prompt_2=negative_prompt_2,
386
+ prompt_embeds=prompt_embeds_text_only,
387
+ negative_prompt_embeds=negative_prompt_embeds,
388
+ pooled_prompt_embeds=pooled_prompt_embeds_text_only,
389
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
390
+ )
391
+
392
+ # 5. Prepare the input ID images
393
+ dtype = next(self.id_encoder.parameters()).dtype
394
+ if not isinstance(input_id_images[0], torch.Tensor):
395
+ id_pixel_values = self.id_image_processor(input_id_images, return_tensors="pt").pixel_values
396
+
397
+ id_pixel_values = id_pixel_values.unsqueeze(0).to(device=device, dtype=dtype) # TODO: multiple prompts
398
+
399
+ # 6. Get the update text embedding with the stacked ID embedding
400
+ prompt_embeds = self.id_encoder(id_pixel_values, prompt_embeds, class_tokens_mask)
401
+
402
+ bs_embed, seq_len, _ = prompt_embeds.shape
403
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
404
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
405
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
406
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
407
+ bs_embed * num_images_per_prompt, -1
408
+ )
409
+
410
+
411
+ negative_prompt_embeds_arr.append(negative_prompt_embeds)
412
+ negative_prompt_embeds = None
413
+ negative_pooled_prompt_embeds_arr.append(negative_pooled_prompt_embeds)
414
+ negative_pooled_prompt_embeds = None
415
+ prompt_embeds_text_only_arr.append(prompt_embeds_text_only)
416
+ prompt_embeds_text_only = None
417
+ prompt_embeds_arr.append(prompt_embeds)
418
+ prompt_embeds = None
419
+ pooled_prompt_embeds_arr.append(pooled_prompt_embeds)
420
+ pooled_prompt_embeds = None
421
+ pooled_prompt_embeds_text_only_arr.append(pooled_prompt_embeds_text_only)
422
+ pooled_prompt_embeds_text_only = None
423
+ # 7. Prepare timesteps
424
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
425
+ timesteps = self.scheduler.timesteps
426
+
427
+ negative_prompt_embeds = torch.cat(negative_prompt_embeds_arr ,dim =0)
428
+ print(negative_prompt_embeds.shape)
429
+ prompt_embeds = torch.cat(prompt_embeds_arr ,dim = 0)
430
+ print(prompt_embeds.shape)
431
+
432
+ prompt_embeds_text_only = torch.cat(prompt_embeds_text_only_arr ,dim = 0)
433
+ print(prompt_embeds_text_only.shape)
434
+ pooled_prompt_embeds_text_only = torch.cat(pooled_prompt_embeds_text_only_arr ,dim = 0)
435
+ print(pooled_prompt_embeds_text_only.shape)
436
+
437
+ negative_pooled_prompt_embeds = torch.cat(negative_pooled_prompt_embeds_arr ,dim = 0)
438
+ print(negative_pooled_prompt_embeds.shape)
439
+ pooled_prompt_embeds = torch.cat(pooled_prompt_embeds_arr,dim = 0)
440
+ print(pooled_prompt_embeds.shape)
441
+ # 8. Prepare latent variables
442
+ num_channels_latents = self.unet.config.in_channels
443
+ latents = self.prepare_latents(
444
+ batch_size * num_images_per_prompt,
445
+ num_channels_latents,
446
+ height,
447
+ width,
448
+ prompt_embeds.dtype,
449
+ device,
450
+ generator,
451
+ latents,
452
+ )
453
+
454
+ # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
455
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
456
+
457
+ # 10. Prepare added time ids & embeddings
458
+ if self.text_encoder_2 is None:
459
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
460
+ else:
461
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
462
+
463
+ add_time_ids = self._get_add_time_ids(
464
+ original_size,
465
+ crops_coords_top_left,
466
+ target_size,
467
+ dtype=prompt_embeds.dtype,
468
+ text_encoder_projection_dim=text_encoder_projection_dim,
469
+ )
470
+ add_time_ids = torch.cat([add_time_ids, add_time_ids], dim=0)
471
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
472
+
473
+
474
+ print(latents.shape)
475
+ print(add_time_ids.shape)
476
+
477
+ # 11. Denoising loop
478
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
479
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
480
+ for i, t in enumerate(timesteps):
481
+ if self.interrupt:
482
+ continue
483
+
484
+ latent_model_input = (
485
+ torch.cat([latents] * 2) if do_classifier_free_guidance else latents
486
+ )
487
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
488
+
489
+ if i <= start_merge_step:
490
+ current_prompt_embeds = torch.cat(
491
+ [negative_prompt_embeds, prompt_embeds_text_only], dim=0
492
+ )
493
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, pooled_prompt_embeds_text_only], dim=0)
494
+ else:
495
+ current_prompt_embeds = torch.cat(
496
+ [negative_prompt_embeds, prompt_embeds], dim=0
497
+ )
498
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, pooled_prompt_embeds], dim=0)
499
+ # predict the noise residual
500
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
501
+ # print(latent_model_input.shape)
502
+ # print(t)
503
+ # print(current_prompt_embeds.shape)
504
+ # print(add_text_embeds.shape)
505
+ # print(add_time_ids.shape)
506
+ #zeros_matrix =
507
+ #global_mask1024 = torch.cat([torch.randn(1, 1024, 1, 1, device=device) for random_number])
508
+ #global_mask4096 =
509
+ noise_pred = self.unet(
510
+ latent_model_input,
511
+ t,
512
+ encoder_hidden_states=current_prompt_embeds,
513
+ cross_attention_kwargs=cross_attention_kwargs,
514
+ added_cond_kwargs=added_cond_kwargs,
515
+ return_dict=False,
516
+ )[0]
517
+ # print(noise_pred.shape)
518
+ # perform guidance
519
+ if do_classifier_free_guidance:
520
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
521
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
522
+
523
+ if do_classifier_free_guidance and guidance_rescale > 0.0:
524
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
525
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
526
+
527
+ # compute the previous noisy sample x_t -> x_t-1
528
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
529
+
530
+ if callback_on_step_end is not None:
531
+ callback_kwargs = {}
532
+ for k in callback_on_step_end_tensor_inputs:
533
+ callback_kwargs[k] = locals()[k]
534
+
535
+ ck_outputs = callback_on_step_end(self, i, t, callback_kwargs)
536
+
537
+ latents = callback_outputs.pop("latents", latents)
538
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
539
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
540
+ add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
541
+ # negative_pooled_prompt_embeds = callback_outputs.pop(
542
+ # "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
543
+ # )
544
+ # add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
545
+ # negative_add_time_ids = callback_outputs.pop("negative_add_time_ids", negative_add_time_ids)
546
+
547
+ # call the callback, if provided
548
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
549
+ progress_bar.update()
550
+ if callback is not None and i % callback_steps == 0:
551
+ step_idx = i // getattr(self.scheduler, "order", 1)
552
+ callback(step_idx, t, latents)
553
+
554
+ # make sure the VAE is in float32 mode, as it overflows in float16
555
+ if self.vae.dtype == torch.float16 and self.vae.config.force_upcast:
556
+ self.upcast_vae()
557
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
558
+
559
+ if not output_type == "latent":
560
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
561
+ else:
562
+ image = latents
563
+ return StableDiffusionXLPipelineOutput(images=image)
564
+
565
+ # apply watermark if available
566
+ # if self.watermark is not None:
567
+ # image = self.watermark.apply_watermark(image)
568
+
569
+ image = self.image_processor.postprocess(image, output_type=output_type)
570
+
571
+ # Offload all models
572
+ self.maybe_free_model_hooks()
573
+
574
+ if not return_dict:
575
+ return (image,)
576
+
577
+ return StableDiffusionXLPipelineOutput(images=image)
utils/style_template.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ style_list = [
2
+ {
3
+ "name": "(No style)",
4
+ "prompt": "{prompt}",
5
+ "negative_prompt": "",
6
+ },
7
+ {
8
+ "name": "Japanese Anime",
9
+ "prompt": "anime artwork illustrating {prompt}. created by japanese anime studio. highly emotional. best quality, high resolution",
10
+ "negative_prompt": "low quality, low resolution"
11
+ },
12
+ {
13
+ "name": "Cinematic",
14
+ "prompt": "cinematic still {prompt} . emotional, harmonious, vignette, highly detailed, high budget, bokeh, cinemascope, moody, epic, gorgeous, film grain, grainy",
15
+ "negative_prompt": "anime, cartoon, graphic, text, painting, crayon, graphite, abstract, glitch, deformed, mutated, ugly, disfigured",
16
+ },
17
+ {
18
+ "name": "Disney Charactor",
19
+ "prompt": "A Pixar animation character of {prompt} . pixar-style, studio anime, Disney, high-quality",
20
+ "negative_prompt": "lowres, bad anatomy, bad hands, text, bad eyes, bad arms, bad legs, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, blurry, grayscale, noisy, sloppy, messy, grainy, highly detailed, ultra textured, photo",
21
+ },
22
+ {
23
+ "name": "Photographic",
24
+ "prompt": "cinematic photo {prompt} . 35mm photograph, film, bokeh, professional, 4k, highly detailed",
25
+ "negative_prompt": "drawing, painting, crayon, sketch, graphite, impressionist, noisy, blurry, soft, deformed, ugly",
26
+ },
27
+ {
28
+ "name": "Comic book",
29
+ "prompt": "comic {prompt} . graphic illustration, comic art, graphic novel art, vibrant, highly detailed",
30
+ "negative_prompt": "photograph, deformed, glitch, noisy, realistic, stock photo",
31
+ },
32
+ {
33
+ "name": "Line art",
34
+ "prompt": "line art drawing {prompt} . professional, sleek, modern, minimalist, graphic, line art, vector graphics",
35
+ "negative_prompt": "anime, photorealistic, 35mm film, deformed, glitch, blurry, noisy, off-center, deformed, cross-eyed, closed eyes, bad anatomy, ugly, disfigured, mutated, realism, realistic, impressionism, expressionism, oil, acrylic",
36
+ }
37
+ ]
38
+
39
+ styles = {k["name"]: (k["prompt"], k["negative_prompt"]) for k in style_list}
utils/utils.py ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from email.mime import image
2
+ import torch
3
+ import base64
4
+ import gradio as gr
5
+ import numpy as np
6
+ from PIL import Image,ImageOps,ImageDraw, ImageFont
7
+ from io import BytesIO
8
+ import random
9
+ MAX_COLORS = 12
10
+ def get_random_bool():
11
+ return random.choice([True, False])
12
+
13
+ def add_white_border(input_image, border_width=10):
14
+ """
15
+ 为PIL图像添加指定宽度的白色边框。
16
+
17
+ :param input_image: PIL图像对象
18
+ :param border_width: 边框宽度(单位:像素)
19
+ :return: 带有白色边框的PIL图像对象
20
+ """
21
+ border_color = 'white' # 白色边框
22
+ # 添加边框
23
+ img_with_border = ImageOps.expand(input_image, border=border_width, fill=border_color)
24
+ return img_with_border
25
+
26
+ def process_mulline_text(draw, text, font, max_width):
27
+ """
28
+ Draw the text on an image with word wrapping.
29
+ """
30
+ lines = [] # Store the lines of text here
31
+ words = text.split()
32
+
33
+ # Start building lines of text, and wrap when necessary
34
+ current_line = ""
35
+ for word in words:
36
+ test_line = f"{current_line} {word}".strip()
37
+ # Check the width of the line with this word added
38
+ width, _ = draw.textsize(test_line, font=font)
39
+ if width <= max_width:
40
+ # If it fits, add this word to the current line
41
+ current_line = test_line
42
+ else:
43
+ # If not, store the line and start a new one
44
+ lines.append(current_line)
45
+ current_line = word
46
+ # Add the last line
47
+ lines.append(current_line)
48
+ return lines
49
+
50
+
51
+
52
+ def add_caption(image, text, position = "bottom-mid", font = None, text_color= 'black', bg_color = (255, 255, 255) , bg_opacity = 200):
53
+ if text == "":
54
+ return image
55
+ image = image.convert("RGBA")
56
+ draw = ImageDraw.Draw(image)
57
+ width, height = image.size
58
+ lines = process_mulline_text(draw,text,font,width)
59
+ text_positions = []
60
+ maxwidth = 0
61
+ for ind, line in enumerate(lines[::-1]):
62
+ text_width, text_height = draw.textsize(line, font=font)
63
+ if position == 'bottom-right':
64
+ text_position = (width - text_width - 10, height - (text_height + 20))
65
+ elif position == 'bottom-left':
66
+ text_position = (10, height - (text_height + 20))
67
+ elif position == 'bottom-mid':
68
+ text_position = ((width - text_width) // 2, height - (text_height + 20) ) # 居中文本
69
+ height = text_position[1]
70
+ maxwidth = max(maxwidth,text_width)
71
+ text_positions.append(text_position)
72
+ rectpos = (width - maxwidth) // 2
73
+ rectangle_position = [rectpos - 5, text_positions[-1][1] - 5, rectpos + maxwidth + 5, text_positions[0][1] + text_height + 5]
74
+ image_with_transparency = Image.new('RGBA', image.size)
75
+ draw_with_transparency = ImageDraw.Draw(image_with_transparency)
76
+ draw_with_transparency.rectangle(rectangle_position, fill=bg_color + (bg_opacity,))
77
+
78
+ image.paste(Image.alpha_composite(image.convert('RGBA'), image_with_transparency))
79
+ print(ind,text_position)
80
+ draw = ImageDraw.Draw(image)
81
+ for ind, line in enumerate(lines[::-1]):
82
+ text_position = text_positions[ind]
83
+ draw.text(text_position, line, fill=text_color, font=font)
84
+
85
+ return image.convert('RGB')
86
+
87
+ def get_comic(images,types = "4panel",captions = [],font = None,pad_image = None):
88
+ if pad_image == None:
89
+ pad_image = Image.open("./images/pad_images.png")
90
+ if font == None:
91
+ font = ImageFont.truetype("./fonts/Inkfree.ttf", int(30 * images[0].size[1] / 1024))
92
+ if types == "No typesetting (default)":
93
+ return images
94
+ elif types == "Four Pannel":
95
+ return get_comic_4panel(images,captions,font,pad_image)
96
+ else: # "Classic Comic Style"
97
+ return get_comic_classical(images,captions,font,pad_image)
98
+
99
+ def get_caption_group(images_groups,captions = []):
100
+ caption_groups = []
101
+ for i in range(len(images_groups)):
102
+ length = len(images_groups[i])
103
+ caption_groups.append(captions[:length])
104
+ captions = captions[length:]
105
+ if len(caption_groups[-1]) < len(images_groups[-1]):
106
+ caption_groups[-1] = caption_groups[-1] + [""] * (len(images_groups[-1]) - len(caption_groups[-1]))
107
+ return caption_groups
108
+
109
+ def get_comic_classical(images,captions = None,font = None,pad_image = None):
110
+ if pad_image == None:
111
+ raise ValueError("pad_image is None")
112
+ images = [add_white_border(image) for image in images]
113
+ pad_image = pad_image.resize(images[0].size, Image.ANTIALIAS)
114
+ images_groups = distribute_images2(images,pad_image)
115
+ print(images_groups)
116
+ if captions != None:
117
+ captions_groups = get_caption_group(images_groups,captions)
118
+ # print(images_groups)
119
+ row_images = []
120
+ for ind, img_group in enumerate(images_groups):
121
+ row_images.append(get_row_image2(img_group ,captions= captions_groups[ind] if captions != None else None,font = font))
122
+
123
+ return [combine_images_vertically_with_resize(row_images)]
124
+
125
+
126
+
127
+ def get_comic_4panel(images,captions = [],font = None,pad_image = None):
128
+ if pad_image == None:
129
+ raise ValueError("pad_image is None")
130
+ pad_image = pad_image.resize(images[0].size, Image.ANTIALIAS)
131
+ images = [add_white_border(image) for image in images]
132
+ assert len(captions) == len(images)
133
+ for i,caption in enumerate(captions):
134
+ images[i] = add_caption(images[i],caption,font = font)
135
+ images_nums = len(images)
136
+ pad_nums = int((4 - images_nums % 4) % 4)
137
+ images = images + [pad_image for _ in range(pad_nums)]
138
+ comics = []
139
+ assert len(images)%4 == 0
140
+ for i in range(len(images)//4):
141
+ comics.append(combine_images_vertically_with_resize([combine_images_horizontally(images[i*4:i*4+2]), combine_images_horizontally(images[i*4+2:i*4+4])]))
142
+
143
+ return comics
144
+
145
+ def get_row_image(images):
146
+ row_image_arr = []
147
+ if len(images)>3:
148
+ stack_img_nums = (len(images) - 2)//2
149
+ else:
150
+ stack_img_nums = 0
151
+ while(len(images)>0):
152
+ if stack_img_nums <=0:
153
+ row_image_arr.append(images[0])
154
+ images = images[1:]
155
+ elif len(images)>stack_img_nums*2:
156
+ if get_random_bool():
157
+ row_image_arr.append(concat_images_vertically_and_scale(images[:2]))
158
+ images = images[2:]
159
+ stack_img_nums -=1
160
+ else:
161
+ row_image_arr.append(images[0])
162
+ images = images[1:]
163
+ else:
164
+ row_image_arr.append(concat_images_vertically_and_scale(images[:2]))
165
+ images = images[2:]
166
+ stack_img_nums-=1
167
+ return combine_images_horizontally(row_image_arr)
168
+
169
+ def get_row_image2(images,captions = None, font = None):
170
+ row_image_arr = []
171
+ if len(images)== 6:
172
+ sequence_list = [1,1,2,2]
173
+ elif len(images)== 4:
174
+ sequence_list = [1,1,2]
175
+ else:
176
+ raise ValueError("images nums is not 4 or 6 found",len(images))
177
+ random.shuffle(sequence_list)
178
+ index = 0
179
+ for length in sequence_list:
180
+ if length == 1:
181
+ if captions != None:
182
+ images_tmp = add_caption(images[0],text = captions[index],font= font)
183
+ else:
184
+ images_tmp = images[0]
185
+ row_image_arr.append( images_tmp)
186
+ images = images[1:]
187
+ index +=1
188
+ elif length == 2:
189
+ row_image_arr.append(concat_images_vertically_and_scale(images[:2]))
190
+ images = images[2:]
191
+ index +=2
192
+
193
+ return combine_images_horizontally(row_image_arr)
194
+
195
+
196
+
197
+ def concat_images_vertically_and_scale(images,scale_factor=2):
198
+ # 加载所有图像
199
+ # 确保所有图像的宽度一致
200
+ widths = [img.width for img in images]
201
+ if not all(width == widths[0] for width in widths):
202
+ raise ValueError('All images must have the same width.')
203
+
204
+ # 计算总高度
205
+ total_height = sum(img.height for img in images)
206
+
207
+ # 创建新的图像,宽度与原图相同,高度为所有图像高度之和
208
+ max_width = max(widths)
209
+ concatenated_image = Image.new('RGB', (max_width, total_height))
210
+
211
+ # 竖直拼接图像
212
+ current_height = 0
213
+ for img in images:
214
+ concatenated_image.paste(img, (0, current_height))
215
+ current_height += img.height
216
+
217
+ # 缩放图像为1/n高度
218
+ new_height = concatenated_image.height // scale_factor
219
+ new_width = concatenated_image.width // scale_factor
220
+ resized_image = concatenated_image.resize((new_width, new_height), Image.ANTIALIAS)
221
+
222
+ return resized_image
223
+
224
+
225
+ def combine_images_horizontally(images):
226
+ # 读取所有图片并存入列表
227
+
228
+ # 获取每幅图像的宽度和高度
229
+ widths, heights = zip(*(i.size for i in images))
230
+
231
+ # 计算总宽度和最大高度
232
+ total_width = sum(widths)
233
+ max_height = max(heights)
234
+
235
+ # 创建新的空白图片,用于拼接
236
+ new_im = Image.new('RGB', (total_width, max_height))
237
+
238
+ # 将图片横向拼接
239
+ x_offset = 0
240
+ for im in images:
241
+ new_im.paste(im, (x_offset, 0))
242
+ x_offset += im.width
243
+
244
+ return new_im
245
+
246
+ def combine_images_vertically_with_resize(images):
247
+
248
+ # 获取所有图片的宽度和高度
249
+ widths, heights = zip(*(i.size for i in images))
250
+
251
+ # 确定新图片的宽度,即所有图片中最小的宽度
252
+ min_width = min(widths)
253
+
254
+ # 调整图片尺寸以保持宽度一致,长宽比不变
255
+ resized_images = []
256
+ for img in images:
257
+ # 计算新高度保持图片长宽比
258
+ new_height = int(min_width * img.height / img.width)
259
+ # 调整图片大小
260
+ resized_img = img.resize((min_width, new_height), Image.ANTIALIAS)
261
+ resized_images.append(resized_img)
262
+
263
+ # 计算所有调整尺寸后图片���总高度
264
+ total_height = sum(img.height for img in resized_images)
265
+
266
+ # 创建一个足够宽和高的新图片对象
267
+ new_im = Image.new('RGB', (min_width, total_height))
268
+
269
+ # 竖直拼接图片
270
+ y_offset = 0
271
+ for im in resized_images:
272
+ new_im.paste(im, (0, y_offset))
273
+ y_offset += im.height
274
+
275
+ return new_im
276
+
277
+ def distribute_images2(images, pad_image):
278
+ groups = []
279
+ remaining = len(images)
280
+ if len(images) <= 8:
281
+ group_sizes = [4]
282
+ else:
283
+ group_sizes = [4, 6]
284
+
285
+ size_index = 0
286
+ while remaining > 0:
287
+ size = group_sizes[size_index%len(group_sizes)]
288
+ if remaining < size and remaining < min(group_sizes):
289
+ size = min(group_sizes)
290
+ if remaining > size:
291
+ new_group = images[-remaining: -remaining + size]
292
+ else:
293
+ new_group = images[-remaining:]
294
+ groups.append(new_group)
295
+ size_index += 1
296
+ remaining -= size
297
+ print(remaining,groups)
298
+ groups[-1] = groups[-1] + [pad_image for _ in range(-remaining)]
299
+
300
+ return groups
301
+
302
+
303
+ def distribute_images(images, group_sizes=(4, 3, 2)):
304
+ groups = []
305
+ remaining = len(images)
306
+
307
+ while remaining > 0:
308
+ # 优先分配最大组(4张图片),再考虑3张,最后处理2张
309
+ for size in sorted(group_sizes, reverse=True):
310
+ # 如果剩下的图片数量大于等于当前组大小,或者为图片总数时(也就是第一次迭代)
311
+ # 开始创建新组
312
+ if remaining >= size or remaining == len(images):
313
+ if remaining > size:
314
+ new_group = images[-remaining: -remaining + size]
315
+ else:
316
+ new_group = images[-remaining:]
317
+ groups.append(new_group)
318
+ remaining -= size
319
+ break
320
+ # 如果剩下的图片少于最小的组大小(2张)并且已经有组了,就把剩下的图片加到最后一个组
321
+ elif remaining < min(group_sizes) and groups:
322
+ groups[-1].extend(images[-remaining:])
323
+ remaining = 0
324
+
325
+ return groups
326
+
327
+ def create_binary_matrix(img_arr, target_color):
328
+ mask = np.all(img_arr == target_color, axis=-1)
329
+ binary_matrix = mask.astype(int)
330
+ return binary_matrix
331
+
332
+ def preprocess_mask(mask_, h, w, device):
333
+ mask = np.array(mask_)
334
+ mask = mask.astype(np.float32)
335
+ mask = mask[None, None]
336
+ mask[mask < 0.5] = 0
337
+ mask[mask >= 0.5] = 1
338
+ mask = torch.from_numpy(mask).to(device)
339
+ mask = torch.nn.functional.interpolate(mask, size=(h, w), mode='nearest')
340
+ return mask
341
+
342
+ def process_sketch(canvas_data):
343
+ binary_matrixes = []
344
+ base64_img = canvas_data['image']
345
+ image_data = base64.b64decode(base64_img.split(',')[1])
346
+ image = Image.open(BytesIO(image_data)).convert("RGB")
347
+ im2arr = np.array(image)
348
+ colors = [tuple(map(int, rgb[4:-1].split(','))) for rgb in canvas_data['colors']]
349
+ colors_fixed = []
350
+
351
+ r, g, b = 255, 255, 255
352
+ binary_matrix = create_binary_matrix(im2arr, (r,g,b))
353
+ binary_matrixes.append(binary_matrix)
354
+ binary_matrix_ = np.repeat(np.expand_dims(binary_matrix, axis=(-1)), 3, axis=(-1))
355
+ colored_map = binary_matrix_*(r,g,b) + (1-binary_matrix_)*(50,50,50)
356
+ colors_fixed.append(gr.update(value=colored_map.astype(np.uint8)))
357
+
358
+ for color in colors:
359
+ r, g, b = color
360
+ if any(c != 255 for c in (r, g, b)):
361
+ binary_matrix = create_binary_matrix(im2arr, (r,g,b))
362
+ binary_matrixes.append(binary_matrix)
363
+ binary_matrix_ = np.repeat(np.expand_dims(binary_matrix, axis=(-1)), 3, axis=(-1))
364
+ colored_map = binary_matrix_*(r,g,b) + (1-binary_matrix_)*(50,50,50)
365
+ colors_fixed.append(gr.update(value=colored_map.astype(np.uint8)))
366
+
367
+ visibilities = []
368
+ colors = []
369
+ for n in range(MAX_COLORS):
370
+ visibilities.append(gr.update(visible=False))
371
+ colors.append(gr.update())
372
+ for n in range(len(colors_fixed)):
373
+ visibilities[n] = gr.update(visible=True)
374
+ colors[n] = colors_fixed[n]
375
+
376
+ return [gr.update(visible=True), binary_matrixes, *visibilities, *colors]
377
+
378
+ def process_prompts(binary_matrixes, *seg_prompts):
379
+ return [gr.update(visible=True), gr.update(value=' , '.join(seg_prompts[:len(binary_matrixes)]))]
380
+
381
+ def process_example(layout_path, all_prompts, seed_):
382
+
383
+ all_prompts = all_prompts.split('***')
384
+
385
+ binary_matrixes = []
386
+ colors_fixed = []
387
+
388
+ im2arr = np.array(Image.open(layout_path))[:,:,:3]
389
+ unique, counts = np.unique(np.reshape(im2arr,(-1,3)), axis=0, return_counts=True)
390
+ sorted_idx = np.argsort(-counts)
391
+
392
+ binary_matrix = create_binary_matrix(im2arr, (0,0,0))
393
+ binary_matrixes.append(binary_matrix)
394
+ binary_matrix_ = np.repeat(np.expand_dims(binary_matrix, axis=(-1)), 3, axis=(-1))
395
+ colored_map = binary_matrix_*(255,255,255) + (1-binary_matrix_)*(50,50,50)
396
+ colors_fixed.append(gr.update(value=colored_map.astype(np.uint8)))
397
+
398
+ for i in range(len(all_prompts)-1):
399
+ r, g, b = unique[sorted_idx[i]]
400
+ if any(c != 255 for c in (r, g, b)) and any(c != 0 for c in (r, g, b)):
401
+ binary_matrix = create_binary_matrix(im2arr, (r,g,b))
402
+ binary_matrixes.append(binary_matrix)
403
+ binary_matrix_ = np.repeat(np.expand_dims(binary_matrix, axis=(-1)), 3, axis=(-1))
404
+ colored_map = binary_matrix_*(r,g,b) + (1-binary_matrix_)*(50,50,50)
405
+ colors_fixed.append(gr.update(value=colored_map.astype(np.uint8)))
406
+
407
+ visibilities = []
408
+ colors = []
409
+ prompts = []
410
+ for n in range(MAX_COLORS):
411
+ visibilities.append(gr.update(visible=False))
412
+ colors.append(gr.update())
413
+ prompts.append(gr.update())
414
+
415
+ for n in range(len(colors_fixed)):
416
+ visibilities[n] = gr.update(visible=True)
417
+ colors[n] = colors_fixed[n]
418
+ prompts[n] = all_prompts[n+1]
419
+
420
+ return [gr.update(visible=True), binary_matrixes, *visibilities, *colors, *prompts,
421
+ gr.update(visible=True), gr.update(value=all_prompts[0]), int(seed_)]