huzefa11 commited on
Commit
e21ad99
·
verified ·
1 Parent(s): f02359f

Upload 7 files

Browse files
Files changed (7) hide show
  1. __init__.py +7 -0
  2. gradio_utils.py +519 -0
  3. load_models_utils.py +57 -0
  4. model.py +113 -0
  5. pipeline.py +588 -0
  6. style_template.py +49 -0
  7. utils.py +426 -0
__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
+ ]
gradio_utils.py ADDED
@@ -0,0 +1,519 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from calendar import c
2
+ from operator import invert
3
+ from webbrowser import get
4
+ import torch
5
+ import random
6
+ import torch.nn as nn
7
+ import torch.nn.functional as F
8
+ import gradio as gr
9
+
10
+ class SpatialAttnProcessor2_0(torch.nn.Module):
11
+ r"""
12
+ Attention processor for IP-Adapater for PyTorch 2.0.
13
+ Args:
14
+ hidden_size (`int`):
15
+ The hidden size of the attention layer.
16
+ cross_attention_dim (`int`):
17
+ The number of channels in the `encoder_hidden_states`.
18
+ text_context_len (`int`, defaults to 77):
19
+ The context length of the text features.
20
+ scale (`float`, defaults to 1.0):
21
+ the weight scale of image prompt.
22
+ """
23
+
24
+ def __init__(self, hidden_size = None, cross_attention_dim=None,id_length = 4,device = "cuda",dtype = torch.float16):
25
+ super().__init__()
26
+ if not hasattr(F, "scaled_dot_product_attention"):
27
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
28
+ self.device = device
29
+ self.dtype = dtype
30
+ self.hidden_size = hidden_size
31
+ self.cross_attention_dim = cross_attention_dim
32
+ self.total_length = id_length + 1
33
+ self.id_length = id_length
34
+ self.id_bank = {}
35
+
36
+ def __call__(
37
+ self,
38
+ attn,
39
+ hidden_states,
40
+ encoder_hidden_states=None,
41
+ attention_mask=None,
42
+ temb=None):
43
+ # un_cond_hidden_states, cond_hidden_states = hidden_states.chunk(2)
44
+ # un_cond_hidden_states = self.__call2__(attn, un_cond_hidden_states,encoder_hidden_states,attention_mask,temb)
45
+ # 生成一个0到1之间的随机数
46
+ global total_count,attn_count,cur_step,mask256,mask1024,mask4096
47
+ global sa16, sa32, sa64
48
+ global write
49
+ if write:
50
+ self.id_bank[cur_step] = [hidden_states[:self.id_length], hidden_states[self.id_length:]]
51
+ else:
52
+ encoder_hidden_states = torch.cat(self.id_bank[cur_step][0],hidden_states[:1],self.id_bank[cur_step][1],hidden_states[1:])
53
+ # 判断随机数是否大于0.5
54
+ if cur_step <5:
55
+ hidden_states = self.__call2__(attn, hidden_states,encoder_hidden_states,attention_mask,temb)
56
+ else: # 256 1024 4096
57
+ random_number = random.random()
58
+ if cur_step <20:
59
+ rand_num = 0.3
60
+ else:
61
+ rand_num = 0.1
62
+ if random_number > rand_num:
63
+ if not write:
64
+ if hidden_states.shape[1] == 32* 32:
65
+ attention_mask = mask1024[mask1024.shape[0] // self.total_length * self.id_length:]
66
+ elif hidden_states.shape[1] ==16*16:
67
+ attention_mask = mask256[mask256.shape[0] // self.total_length * self.id_length:]
68
+ else:
69
+ attention_mask = mask4096[mask4096.shape[0] // self.total_length * self.id_length:]
70
+ else:
71
+ if hidden_states.shape[1] == 32* 32:
72
+ attention_mask = mask1024[:mask1024.shape[0] // self.total_length * self.id_length]
73
+ elif hidden_states.shape[1] ==16*16:
74
+ attention_mask = mask256[:mask256.shape[0] // self.total_length * self.id_length]
75
+ else:
76
+ attention_mask = mask4096[:mask4096.shape[0] // self.total_length * self.id_length]
77
+ hidden_states = self.__call1__(attn, hidden_states,encoder_hidden_states,attention_mask,temb)
78
+ else:
79
+ hidden_states = self.__call2__(attn, hidden_states,None,attention_mask,temb)
80
+ attn_count +=1
81
+ if attn_count == total_count:
82
+ attn_count = 0
83
+ cur_step += 1
84
+ mask256,mask1024,mask4096 = cal_attn_mask(self.total_length,self.id_length,sa16,sa32,sa64, device=self.device, dtype= self.dtype)
85
+
86
+ return hidden_states
87
+ def __call1__(
88
+ self,
89
+ attn,
90
+ hidden_states,
91
+ encoder_hidden_states=None,
92
+ attention_mask=None,
93
+ temb=None,
94
+ ):
95
+ residual = hidden_states
96
+ if encoder_hidden_states is not None:
97
+ raise Exception("not implement")
98
+ if attn.spatial_norm is not None:
99
+ hidden_states = attn.spatial_norm(hidden_states, temb)
100
+ input_ndim = hidden_states.ndim
101
+
102
+ if input_ndim == 4:
103
+ total_batch_size, channel, height, width = hidden_states.shape
104
+ hidden_states = hidden_states.view(total_batch_size, channel, height * width).transpose(1, 2)
105
+ total_batch_size,nums_token,channel = hidden_states.shape
106
+ img_nums = total_batch_size//2
107
+ hidden_states = hidden_states.view(-1,img_nums,nums_token,channel).reshape(-1,img_nums * nums_token,channel)
108
+
109
+ batch_size, sequence_length, _ = hidden_states.shape
110
+
111
+ if attn.group_norm is not None:
112
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
113
+
114
+ query = attn.to_q(hidden_states)
115
+
116
+ if encoder_hidden_states is None:
117
+ encoder_hidden_states = hidden_states # B, N, C
118
+ else:
119
+ encoder_hidden_states = encoder_hidden_states.view(-1,self.id_length+1,nums_token,channel).reshape(-1,(self.id_length+1) * nums_token,channel)
120
+
121
+ key = attn.to_k(encoder_hidden_states)
122
+ value = attn.to_v(encoder_hidden_states)
123
+
124
+
125
+ inner_dim = key.shape[-1]
126
+ head_dim = inner_dim // attn.heads
127
+
128
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
129
+
130
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
131
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
132
+
133
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
134
+ # TODO: add support for attn.scale when we move to Torch 2.1
135
+ hidden_states = F.scaled_dot_product_attention(
136
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
137
+ )
138
+
139
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
140
+ hidden_states = hidden_states.to(query.dtype)
141
+
142
+
143
+
144
+ # linear proj
145
+ hidden_states = attn.to_out[0](hidden_states)
146
+ # dropout
147
+ hidden_states = attn.to_out[1](hidden_states)
148
+
149
+ # if input_ndim == 4:
150
+ # tile_hidden_states = tile_hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
151
+
152
+ # if attn.residual_connection:
153
+ # tile_hidden_states = tile_hidden_states + residual
154
+
155
+ if input_ndim == 4:
156
+ hidden_states = hidden_states.transpose(-1, -2).reshape(total_batch_size, channel, height, width)
157
+ if attn.residual_connection:
158
+ hidden_states = hidden_states + residual
159
+ hidden_states = hidden_states / attn.rescale_output_factor
160
+
161
+ return hidden_states
162
+ def __call2__(
163
+ self,
164
+ attn,
165
+ hidden_states,
166
+ encoder_hidden_states=None,
167
+ attention_mask=None,
168
+ temb=None):
169
+ residual = hidden_states
170
+
171
+ if attn.spatial_norm is not None:
172
+ hidden_states = attn.spatial_norm(hidden_states, temb)
173
+
174
+ input_ndim = hidden_states.ndim
175
+
176
+ if input_ndim == 4:
177
+ batch_size, channel, height, width = hidden_states.shape
178
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
179
+
180
+ batch_size, sequence_length, _ = (
181
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
182
+ )
183
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
184
+
185
+ if attn.group_norm is not None:
186
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
187
+
188
+ query = attn.to_q(hidden_states)
189
+
190
+ if encoder_hidden_states is None:
191
+ encoder_hidden_states = hidden_states
192
+ elif attn.norm_cross:
193
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
194
+
195
+ key = attn.to_k(encoder_hidden_states)
196
+ value = attn.to_v(encoder_hidden_states)
197
+
198
+ query = attn.head_to_batch_dim(query)
199
+ key = attn.head_to_batch_dim(key)
200
+ value = attn.head_to_batch_dim(value)
201
+
202
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
203
+ hidden_states = torch.bmm(attention_probs, value)
204
+ hidden_states = attn.batch_to_head_dim(hidden_states)
205
+
206
+ # linear proj
207
+ hidden_states = attn.to_out[0](hidden_states)
208
+ # dropout
209
+ hidden_states = attn.to_out[1](hidden_states)
210
+
211
+ if input_ndim == 4:
212
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
213
+
214
+ if attn.residual_connection:
215
+ hidden_states = hidden_states + residual
216
+
217
+ hidden_states = hidden_states / attn.rescale_output_factor
218
+
219
+ return hidden_states
220
+
221
+
222
+ def cal_attn_mask(total_length,id_length,sa16,sa32,sa64,device="cuda",dtype= torch.float16):
223
+ bool_matrix256 = torch.rand((1, total_length * 256),device = device,dtype = dtype) < sa16
224
+ bool_matrix1024 = torch.rand((1, total_length * 1024),device = device,dtype = dtype) < sa32
225
+ bool_matrix4096 = torch.rand((1, total_length * 4096),device = device,dtype = dtype) < sa64
226
+ bool_matrix256 = bool_matrix256.repeat(total_length,1)
227
+ bool_matrix1024 = bool_matrix1024.repeat(total_length,1)
228
+ bool_matrix4096 = bool_matrix4096.repeat(total_length,1)
229
+ for i in range(total_length):
230
+ bool_matrix256[i:i+1,id_length*256:] = False
231
+ bool_matrix1024[i:i+1,id_length*1024:] = False
232
+ bool_matrix4096[i:i+1,id_length*4096:] = False
233
+ bool_matrix256[i:i+1,i*256:(i+1)*256] = True
234
+ bool_matrix1024[i:i+1,i*1024:(i+1)*1024] = True
235
+ bool_matrix4096[i:i+1,i*4096:(i+1)*4096] = True
236
+ mask256 = bool_matrix256.unsqueeze(1).repeat(1,256,1).reshape(-1,total_length * 256)
237
+ mask1024 = bool_matrix1024.unsqueeze(1).repeat(1,1024,1).reshape(-1,total_length * 1024)
238
+ mask4096 = bool_matrix4096.unsqueeze(1).repeat(1,4096,1).reshape(-1,total_length * 4096)
239
+ return mask256,mask1024,mask4096
240
+
241
+ def cal_attn_mask_xl(total_length,id_length,sa32,sa64,height,width,device="cuda",dtype= torch.float16):
242
+ nums_1024 = (height // 32) * (width // 32)
243
+ nums_4096 = (height // 16) * (width // 16)
244
+ bool_matrix1024 = torch.rand((1, total_length * nums_1024),device = device,dtype = dtype) < sa32
245
+ bool_matrix4096 = torch.rand((1, total_length * nums_4096),device = device,dtype = dtype) < sa64
246
+ bool_matrix1024 = bool_matrix1024.repeat(total_length,1)
247
+ bool_matrix4096 = bool_matrix4096.repeat(total_length,1)
248
+ for i in range(total_length):
249
+ bool_matrix1024[i:i+1,id_length*nums_1024:] = False
250
+ bool_matrix4096[i:i+1,id_length*nums_4096:] = False
251
+ bool_matrix1024[i:i+1,i*nums_1024:(i+1)*nums_1024] = True
252
+ bool_matrix4096[i:i+1,i*nums_4096:(i+1)*nums_4096] = True
253
+ mask1024 = bool_matrix1024.unsqueeze(1).repeat(1,nums_1024,1).reshape(-1,total_length * nums_1024)
254
+ mask4096 = bool_matrix4096.unsqueeze(1).repeat(1,nums_4096,1).reshape(-1,total_length * nums_4096)
255
+ return mask1024,mask4096
256
+
257
+
258
+ def cal_attn_indice_xl_effcient_memory(total_length,id_length,sa32,sa64,height,width,device="cuda",dtype= torch.float16):
259
+ nums_1024 = (height // 32) * (width // 32)
260
+ nums_4096 = (height // 16) * (width // 16)
261
+ bool_matrix1024 = torch.rand((total_length,nums_1024),device = device,dtype = dtype) < sa32
262
+ bool_matrix4096 = torch.rand((total_length,nums_4096),device = device,dtype = dtype) < sa64
263
+ # 用nonzero()函数获取所有为True的值的索引
264
+ indices1024 = [torch.nonzero(bool_matrix1024[i], as_tuple=True)[0] for i in range(total_length)]
265
+ indices4096 = [torch.nonzero(bool_matrix4096[i], as_tuple=True)[0] for i in range(total_length)]
266
+
267
+ return indices1024,indices4096
268
+
269
+
270
+ class AttnProcessor(nn.Module):
271
+ r"""
272
+ Default processor for performing attention-related computations.
273
+ """
274
+ def __init__(
275
+ self,
276
+ hidden_size=None,
277
+ cross_attention_dim=None,
278
+ ):
279
+ super().__init__()
280
+
281
+ def __call__(
282
+ self,
283
+ attn,
284
+ hidden_states,
285
+ encoder_hidden_states=None,
286
+ attention_mask=None,
287
+ temb=None,
288
+ ):
289
+ residual = hidden_states
290
+
291
+ if attn.spatial_norm is not None:
292
+ hidden_states = attn.spatial_norm(hidden_states, temb)
293
+
294
+ input_ndim = hidden_states.ndim
295
+
296
+ if input_ndim == 4:
297
+ batch_size, channel, height, width = hidden_states.shape
298
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
299
+
300
+ batch_size, sequence_length, _ = (
301
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
302
+ )
303
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
304
+
305
+ if attn.group_norm is not None:
306
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
307
+
308
+ query = attn.to_q(hidden_states)
309
+
310
+ if encoder_hidden_states is None:
311
+ encoder_hidden_states = hidden_states
312
+ elif attn.norm_cross:
313
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
314
+
315
+ key = attn.to_k(encoder_hidden_states)
316
+ value = attn.to_v(encoder_hidden_states)
317
+
318
+ query = attn.head_to_batch_dim(query)
319
+ key = attn.head_to_batch_dim(key)
320
+ value = attn.head_to_batch_dim(value)
321
+
322
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
323
+ hidden_states = torch.bmm(attention_probs, value)
324
+ hidden_states = attn.batch_to_head_dim(hidden_states)
325
+
326
+ # linear proj
327
+ hidden_states = attn.to_out[0](hidden_states)
328
+ # dropout
329
+ hidden_states = attn.to_out[1](hidden_states)
330
+
331
+ if input_ndim == 4:
332
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
333
+
334
+ if attn.residual_connection:
335
+ hidden_states = hidden_states + residual
336
+
337
+ hidden_states = hidden_states / attn.rescale_output_factor
338
+
339
+ return hidden_states
340
+
341
+
342
+ class AttnProcessor2_0(torch.nn.Module):
343
+ r"""
344
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
345
+ """
346
+ def __init__(
347
+ self,
348
+ hidden_size=None,
349
+ cross_attention_dim=None,
350
+ ):
351
+ super().__init__()
352
+ if not hasattr(F, "scaled_dot_product_attention"):
353
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
354
+
355
+ def __call__(
356
+ self,
357
+ attn,
358
+ hidden_states,
359
+ encoder_hidden_states=None,
360
+ attention_mask=None,
361
+ temb=None,
362
+ ):
363
+ residual = hidden_states
364
+
365
+ if attn.spatial_norm is not None:
366
+ hidden_states = attn.spatial_norm(hidden_states, temb)
367
+
368
+ input_ndim = hidden_states.ndim
369
+
370
+ if input_ndim == 4:
371
+ batch_size, channel, height, width = hidden_states.shape
372
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
373
+
374
+ batch_size, sequence_length, _ = (
375
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
376
+ )
377
+
378
+ if attention_mask is not None:
379
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
380
+ # scaled_dot_product_attention expects attention_mask shape to be
381
+ # (batch, heads, source_length, target_length)
382
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
383
+
384
+ if attn.group_norm is not None:
385
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
386
+
387
+ query = attn.to_q(hidden_states)
388
+
389
+ if encoder_hidden_states is None:
390
+ encoder_hidden_states = hidden_states
391
+ elif attn.norm_cross:
392
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
393
+
394
+ key = attn.to_k(encoder_hidden_states)
395
+ value = attn.to_v(encoder_hidden_states)
396
+
397
+ inner_dim = key.shape[-1]
398
+ head_dim = inner_dim // attn.heads
399
+
400
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
401
+
402
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
403
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
404
+
405
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
406
+ # TODO: add support for attn.scale when we move to Torch 2.1
407
+ hidden_states = F.scaled_dot_product_attention(
408
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
409
+ )
410
+
411
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
412
+ hidden_states = hidden_states.to(query.dtype)
413
+
414
+ # linear proj
415
+ hidden_states = attn.to_out[0](hidden_states)
416
+ # dropout
417
+ hidden_states = attn.to_out[1](hidden_states)
418
+
419
+ if input_ndim == 4:
420
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
421
+
422
+ if attn.residual_connection:
423
+ hidden_states = hidden_states + residual
424
+
425
+ hidden_states = hidden_states / attn.rescale_output_factor
426
+
427
+ return hidden_states
428
+
429
+
430
+ def is_torch2_available():
431
+ return hasattr(F, "scaled_dot_product_attention")
432
+
433
+
434
+ # 将列表转换为字典的函数
435
+ def character_to_dict(general_prompt):
436
+ character_dict = {}
437
+ generate_prompt_arr = general_prompt.splitlines()
438
+ character_index_dict = {}
439
+ invert_character_index_dict = {}
440
+ character_list = []
441
+ for ind,string in enumerate(generate_prompt_arr):
442
+ # 分割字符串寻找key和value
443
+ start = string.find('[')
444
+ end = string.find(']')
445
+ if start != -1 and end != -1:
446
+ key = string[start:end+1]
447
+ value = string[end+1:]
448
+ if "#" in value:
449
+ value = value.rpartition('#')[0]
450
+ if key in character_dict:
451
+ raise gr.Error("duplicate character descirption: " + key)
452
+ character_dict[key] = value
453
+ character_list.append(key)
454
+
455
+
456
+ return character_dict,character_list
457
+
458
+ def get_id_prompt_index(character_dict,id_prompts):
459
+ replace_id_prompts = []
460
+ character_index_dict = {}
461
+ invert_character_index_dict = {}
462
+ for ind,id_prompt in enumerate(id_prompts):
463
+ for key in character_dict.keys():
464
+ if key in id_prompt:
465
+ if key not in character_index_dict:
466
+ character_index_dict[key] = []
467
+ character_index_dict[key].append(ind)
468
+ invert_character_index_dict[ind] = key
469
+ replace_id_prompts.append(id_prompt.replace(key,character_dict[key]))
470
+
471
+ return character_index_dict,invert_character_index_dict,replace_id_prompts
472
+
473
+ def get_cur_id_list(real_prompt,character_dict,character_index_dict):
474
+ list_arr = []
475
+ for keys in character_index_dict.keys():
476
+ if keys in real_prompt:
477
+ list_arr = list_arr + character_index_dict[keys]
478
+ real_prompt = real_prompt.replace(keys,character_dict[keys])
479
+ return list_arr,real_prompt
480
+
481
+ def process_original_prompt(character_dict,prompts,id_length):
482
+ replace_prompts = []
483
+ character_index_dict = {}
484
+ invert_character_index_dict = {}
485
+ for ind,prompt in enumerate(prompts):
486
+ for key in character_dict.keys():
487
+ if key in prompt:
488
+ if key not in character_index_dict:
489
+ character_index_dict[key] = []
490
+ character_index_dict[key].append(ind)
491
+ if ind not in invert_character_index_dict:
492
+ invert_character_index_dict[ind] = []
493
+ invert_character_index_dict[ind].append(key)
494
+ cur_prompt = prompt
495
+ if ind in invert_character_index_dict:
496
+ for key in invert_character_index_dict[ind]:
497
+ cur_prompt = cur_prompt.replace(key,character_dict[key] + " ")
498
+ replace_prompts.append(cur_prompt)
499
+ ref_index_dict = {}
500
+ ref_totals = []
501
+ print(character_index_dict)
502
+ for character_key in character_index_dict.keys():
503
+ if character_key not in character_index_dict:
504
+ raise gr.Error("{} not have prompt description, please remove it".format(character_key))
505
+ index_list = character_index_dict[character_key]
506
+ index_list = [index for index in index_list if len(invert_character_index_dict[index]) == 1]
507
+ if len(index_list) < id_length:
508
+ raise gr.Error(f"{character_key} not have enough prompt description, need no less than {id_length}, but you give {len(index_list)}")
509
+ ref_index_dict[character_key] = index_list[:id_length]
510
+ ref_totals = ref_totals + index_list[:id_length]
511
+ return character_index_dict,invert_character_index_dict,replace_prompts,ref_index_dict,ref_totals
512
+
513
+
514
+ def get_ref_character(real_prompt,character_dict):
515
+ list_arr = []
516
+ for keys in character_dict.keys():
517
+ if keys in real_prompt:
518
+ list_arr = list_arr + [keys]
519
+ return list_arr
load_models_utils.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import yaml
2
+ import torch
3
+ from diffusers import StableDiffusionXLPipeline
4
+ from utils import PhotoMakerStableDiffusionXLPipeline
5
+ import os
6
+
7
+ def get_models_dict():
8
+ # 打开并读取YAML文件
9
+ with open('config/models.yaml', 'r') as stream:
10
+ try:
11
+ # 解析YAML文件内容
12
+ data = yaml.safe_load(stream)
13
+
14
+ # 此时 'data' 是一个Python字典,里面包含了YAML文件的所有数据
15
+ print(data)
16
+ return data
17
+
18
+ except yaml.YAMLError as exc:
19
+ # 如果在解析过程中发生了错误,打印异常信息
20
+ print(exc)
21
+
22
+ def load_models(model_info,device,photomaker_path):
23
+ path = model_info["path"]
24
+ single_files = model_info["single_files"]
25
+ use_safetensors = model_info["use_safetensors"]
26
+ model_type = model_info["model_type"]
27
+
28
+ if model_type == "original":
29
+ if single_files:
30
+ pipe = StableDiffusionXLPipeline.from_single_file(
31
+ path,
32
+ torch_dtype=torch.float16
33
+ )
34
+ else:
35
+ pipe = StableDiffusionXLPipeline.from_pretrained(path, torch_dtype=torch.float16, use_safetensors=use_safetensors)
36
+ pipe = pipe.to(device)
37
+ elif model_type == "Photomaker":
38
+ if single_files:
39
+ print("loading from a single_files")
40
+ pipe = PhotoMakerStableDiffusionXLPipeline.from_single_file(
41
+ path,
42
+ torch_dtype=torch.float16
43
+ )
44
+ else:
45
+ pipe = PhotoMakerStableDiffusionXLPipeline.from_pretrained(
46
+ path, torch_dtype=torch.float16, use_safetensors=use_safetensors)
47
+ pipe = pipe.to(device)
48
+ pipe.load_photomaker_adapter(
49
+ os.path.dirname(photomaker_path),
50
+ subfolder="",
51
+ weight_name=os.path.basename(photomaker_path),
52
+ trigger_word="img" # define the trigger word
53
+ )
54
+ pipe.fuse_lora()
55
+ else:
56
+ raise NotImplementedError("You should choice between original and Photomaker!",f"But you choice {model_type}")
57
+ return pipe
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()
pipeline.py ADDED
@@ -0,0 +1,588 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ nc_flag: bool = False,
140
+ ):
141
+ device = device or self._execution_device
142
+
143
+ if prompt is not None and isinstance(prompt, str):
144
+ batch_size = 1
145
+ elif prompt is not None and isinstance(prompt, list):
146
+ batch_size = len(prompt)
147
+ else:
148
+ batch_size = prompt_embeds.shape[0]
149
+
150
+ # Find the token id of the trigger word
151
+ image_token_id = self.tokenizer_2.convert_tokens_to_ids(self.trigger_word)
152
+
153
+ # Define tokenizers and text encoders
154
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
155
+ text_encoders = (
156
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
157
+ )
158
+
159
+ if prompt_embeds is None:
160
+ prompt_2 = prompt_2 or prompt
161
+ prompt_embeds_list = []
162
+ prompts = [prompt, prompt_2]
163
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
164
+ input_ids = tokenizer.encode(prompt) # TODO: batch encode
165
+ clean_index = 0
166
+ clean_input_ids = []
167
+ class_token_index = []
168
+ # Find out the corresponding class word token based on the newly added trigger word token
169
+ for i, token_id in enumerate(input_ids):
170
+ if token_id == image_token_id:
171
+ class_token_index.append(clean_index - 1)
172
+ else:
173
+ clean_input_ids.append(token_id)
174
+ clean_index += 1
175
+ if nc_flag:
176
+ return None, None, None
177
+ if len(class_token_index) > 1:
178
+ raise ValueError(
179
+ f"PhotoMaker currently does not support multiple trigger words in a single prompt.\
180
+ Trigger word: {self.trigger_word}, Prompt: {prompt}."
181
+ )
182
+ elif len(class_token_index) == 0 and not nc_flag:
183
+ raise ValueError(
184
+ f"PhotoMaker currently does not support multiple trigger words in a single prompt.\
185
+ Trigger word: {self.trigger_word}, Prompt: {prompt}."
186
+ )
187
+ class_token_index = class_token_index[0]
188
+
189
+ # Expand the class word token and corresponding mask
190
+ class_token = clean_input_ids[class_token_index]
191
+ clean_input_ids = clean_input_ids[:class_token_index] + [class_token] * num_id_images + \
192
+ clean_input_ids[class_token_index+1:]
193
+
194
+ # Truncation or padding
195
+ max_len = tokenizer.model_max_length
196
+ if len(clean_input_ids) > max_len:
197
+ clean_input_ids = clean_input_ids[:max_len]
198
+ else:
199
+ clean_input_ids = clean_input_ids + [tokenizer.pad_token_id] * (
200
+ max_len - len(clean_input_ids)
201
+ )
202
+
203
+ class_tokens_mask = [True if class_token_index <= i < class_token_index+num_id_images else False \
204
+ for i in range(len(clean_input_ids))]
205
+
206
+ clean_input_ids = torch.tensor(clean_input_ids, dtype=torch.long).unsqueeze(0)
207
+ class_tokens_mask = torch.tensor(class_tokens_mask, dtype=torch.bool).unsqueeze(0)
208
+
209
+ prompt_embeds = text_encoder(
210
+ clean_input_ids.to(device),
211
+ output_hidden_states=True,
212
+ )
213
+
214
+ # We are only ALWAYS interested in the pooled output of the final text encoder
215
+ pooled_prompt_embeds = prompt_embeds[0]
216
+ prompt_embeds = prompt_embeds.hidden_states[-2]
217
+ prompt_embeds_list.append(prompt_embeds)
218
+
219
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
220
+
221
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
222
+ class_tokens_mask = class_tokens_mask.to(device=device) # TODO: ignoring two-prompt case
223
+
224
+ return prompt_embeds, pooled_prompt_embeds, class_tokens_mask
225
+
226
+ @property
227
+ def interrupt(self):
228
+ return self._interrupt
229
+
230
+ @torch.no_grad()
231
+ def __call__(
232
+ self,
233
+ prompt: Union[str, List[str]] = None,
234
+ prompt_2: Optional[Union[str, List[str]]] = None,
235
+ height: Optional[int] = None,
236
+ width: Optional[int] = None,
237
+ num_inference_steps: int = 50,
238
+ denoising_end: Optional[float] = None,
239
+ guidance_scale: float = 5.0,
240
+ negative_prompt: Optional[Union[str, List[str]]] = None,
241
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
242
+ num_images_per_prompt: Optional[int] = 1,
243
+ eta: float = 0.0,
244
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
245
+ latents: Optional[torch.FloatTensor] = None,
246
+ prompt_embeds: Optional[torch.FloatTensor] = None,
247
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
248
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
249
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
250
+ output_type: Optional[str] = "pil",
251
+ return_dict: bool = True,
252
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
253
+ guidance_rescale: float = 0.0,
254
+ original_size: Optional[Tuple[int, int]] = None,
255
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
256
+ target_size: Optional[Tuple[int, int]] = None,
257
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
258
+ callback_steps: int = 1,
259
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
260
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
261
+ # Added parameters (for PhotoMaker)
262
+ input_id_images: PipelineImageInput = None,
263
+ start_merge_step: int = 0, # TODO: change to `style_strength_ratio` in the future
264
+ class_tokens_mask: Optional[torch.LongTensor] = None,
265
+ prompt_embeds_text_only: Optional[torch.FloatTensor] = None,
266
+ pooled_prompt_embeds_text_only: Optional[torch.FloatTensor] = None,
267
+ nc_flag = False,
268
+ ):
269
+ r"""
270
+ Function invoked when calling the pipeline for generation.
271
+ Only the parameters introduced by PhotoMaker are discussed here.
272
+ 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
273
+
274
+ Args:
275
+ input_id_images (`PipelineImageInput`, *optional*):
276
+ Input ID Image to work with PhotoMaker.
277
+ class_tokens_mask (`torch.LongTensor`, *optional*):
278
+ 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.
279
+ prompt_embeds_text_only (`torch.FloatTensor`, *optional*):
280
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
281
+ provided, text embeddings will be generated from `prompt` input argument.
282
+ pooled_prompt_embeds_text_only (`torch.FloatTensor`, *optional*):
283
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
284
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
285
+
286
+ Returns:
287
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:
288
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
289
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
290
+ """
291
+ # 0. Default height and width to unet
292
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
293
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
294
+
295
+ original_size = original_size or (height, width)
296
+ target_size = target_size or (height, width)
297
+
298
+ # 1. Check inputs. Raise error if not correct
299
+ self.check_inputs(
300
+ prompt,
301
+ prompt_2,
302
+ height,
303
+ width,
304
+ callback_steps,
305
+ negative_prompt,
306
+ negative_prompt_2,
307
+ prompt_embeds,
308
+ negative_prompt_embeds,
309
+ pooled_prompt_embeds,
310
+ negative_pooled_prompt_embeds,
311
+ callback_on_step_end_tensor_inputs,
312
+ )
313
+
314
+ self._interrupt = False
315
+
316
+ #
317
+ if prompt_embeds is not None and class_tokens_mask is None:
318
+ raise ValueError(
319
+ "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`."
320
+ )
321
+ # check the input id images
322
+ if input_id_images is None:
323
+ raise ValueError(
324
+ "Provide `input_id_images`. Cannot leave `input_id_images` undefined for PhotoMaker pipeline."
325
+ )
326
+ if not isinstance(input_id_images, list):
327
+ input_id_images = [input_id_images]
328
+
329
+ # 2. Define call parameters
330
+ if prompt is not None and isinstance(prompt, str):
331
+ batch_size = 1
332
+ prompt = [prompt]
333
+ elif prompt is not None and isinstance(prompt, list):
334
+ batch_size = len(prompt)
335
+ else:
336
+ batch_size = prompt_embeds.shape[0]
337
+
338
+ device = self._execution_device
339
+
340
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
341
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
342
+ # corresponds to doing no classifier free guidance.
343
+ do_classifier_free_guidance = guidance_scale >= 1.0
344
+
345
+ assert do_classifier_free_guidance
346
+
347
+ # 3. Encode input prompt
348
+ num_id_images = len(input_id_images)
349
+ if isinstance(prompt, list):
350
+ prompt_arr = prompt
351
+ negative_prompt_embeds_arr = []
352
+ prompt_embeds_text_only_arr = []
353
+ prompt_embeds_arr = []
354
+ latents_arr = []
355
+ add_time_ids_arr = []
356
+ negative_pooled_prompt_embeds_arr = []
357
+ pooled_prompt_embeds_text_only_arr = []
358
+ pooled_prompt_embeds_arr = []
359
+ for prompt in prompt_arr:
360
+ (
361
+ prompt_embeds,
362
+ pooled_prompt_embeds,
363
+ class_tokens_mask,
364
+ ) = self.encode_prompt_with_trigger_word(
365
+ prompt=prompt,
366
+ prompt_2=prompt_2,
367
+ device=device,
368
+ num_id_images=num_id_images,
369
+ prompt_embeds=prompt_embeds,
370
+ pooled_prompt_embeds=pooled_prompt_embeds,
371
+ class_tokens_mask=class_tokens_mask,
372
+ nc_flag = nc_flag,
373
+ )
374
+
375
+ # 4. Encode input prompt without the trigger word for delayed conditioning
376
+ # encode, remove trigger word token, then decode
377
+ tokens_text_only = self.tokenizer.encode(prompt, add_special_tokens=False)
378
+ trigger_word_token = self.tokenizer.convert_tokens_to_ids(self.trigger_word)
379
+ if not nc_flag:
380
+ tokens_text_only.remove(trigger_word_token)
381
+ prompt_text_only = self.tokenizer.decode(tokens_text_only, add_special_tokens=False)
382
+ print(prompt_text_only)
383
+ (
384
+ prompt_embeds_text_only,
385
+ negative_prompt_embeds,
386
+ pooled_prompt_embeds_text_only, # TODO: replace the pooled_prompt_embeds with text only prompt
387
+ negative_pooled_prompt_embeds,
388
+ ) = self.encode_prompt(
389
+ prompt=prompt_text_only,
390
+ prompt_2=prompt_2,
391
+ device=device,
392
+ num_images_per_prompt=num_images_per_prompt,
393
+ do_classifier_free_guidance=True,
394
+ negative_prompt=negative_prompt,
395
+ negative_prompt_2=negative_prompt_2,
396
+ prompt_embeds=prompt_embeds_text_only,
397
+ negative_prompt_embeds=negative_prompt_embeds,
398
+ pooled_prompt_embeds=pooled_prompt_embeds_text_only,
399
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
400
+ )
401
+
402
+ # 5. Prepare the input ID images
403
+ dtype = next(self.id_encoder.parameters()).dtype
404
+ if not isinstance(input_id_images[0], torch.Tensor):
405
+ id_pixel_values = self.id_image_processor(input_id_images, return_tensors="pt").pixel_values
406
+
407
+ id_pixel_values = id_pixel_values.unsqueeze(0).to(device=device, dtype=dtype) # TODO: multiple prompts
408
+
409
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
410
+ if not nc_flag:
411
+ # 6. Get the update text embedding with the stacked ID embedding
412
+ prompt_embeds = self.id_encoder(id_pixel_values, prompt_embeds, class_tokens_mask)
413
+
414
+ bs_embed, seq_len, _ = prompt_embeds.shape
415
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
416
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
417
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
418
+ bs_embed * num_images_per_prompt, -1
419
+ )
420
+ pooled_prompt_embeds_arr.append(pooled_prompt_embeds)
421
+ pooled_prompt_embeds = None
422
+
423
+ negative_prompt_embeds_arr.append(negative_prompt_embeds)
424
+ negative_prompt_embeds = None
425
+ negative_pooled_prompt_embeds_arr.append(negative_pooled_prompt_embeds)
426
+ negative_pooled_prompt_embeds = None
427
+ prompt_embeds_text_only_arr.append(prompt_embeds_text_only)
428
+ prompt_embeds_text_only = None
429
+ prompt_embeds_arr.append(prompt_embeds)
430
+ prompt_embeds = None
431
+ pooled_prompt_embeds_text_only_arr.append(pooled_prompt_embeds_text_only)
432
+ pooled_prompt_embeds_text_only = None
433
+ # 7. Prepare timesteps
434
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
435
+ timesteps = self.scheduler.timesteps
436
+
437
+ negative_prompt_embeds = torch.cat(negative_prompt_embeds_arr ,dim =0)
438
+ print(negative_prompt_embeds.shape)
439
+ if not nc_flag:
440
+ prompt_embeds = torch.cat(prompt_embeds_arr ,dim = 0)
441
+ print(prompt_embeds.shape)
442
+ pooled_prompt_embeds = torch.cat(pooled_prompt_embeds_arr,dim = 0)
443
+ print(pooled_prompt_embeds.shape)
444
+
445
+ prompt_embeds_text_only = torch.cat(prompt_embeds_text_only_arr ,dim = 0)
446
+ print(prompt_embeds_text_only.shape)
447
+ pooled_prompt_embeds_text_only = torch.cat(pooled_prompt_embeds_text_only_arr ,dim = 0)
448
+ print(pooled_prompt_embeds_text_only.shape)
449
+
450
+ negative_pooled_prompt_embeds = torch.cat(negative_pooled_prompt_embeds_arr ,dim = 0)
451
+ print(negative_pooled_prompt_embeds.shape)
452
+ # 8. Prepare latent variables
453
+ num_channels_latents = self.unet.config.in_channels
454
+ latents = self.prepare_latents(
455
+ batch_size * num_images_per_prompt,
456
+ num_channels_latents,
457
+ height,
458
+ width,
459
+ prompt_embeds.dtype if not nc_flag else prompt_embeds_text_only.dtype,
460
+ device,
461
+ generator,
462
+ latents,
463
+ )
464
+
465
+ # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
466
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
467
+
468
+ # 10. Prepare added time ids & embeddings
469
+ if self.text_encoder_2 is None:
470
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
471
+ else:
472
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
473
+
474
+ add_time_ids = self._get_add_time_ids(
475
+ original_size,
476
+ crops_coords_top_left,
477
+ target_size,
478
+ dtype=prompt_embeds.dtype if not nc_flag else prompt_embeds_text_only.dtype,
479
+ text_encoder_projection_dim=text_encoder_projection_dim,
480
+ )
481
+ add_time_ids = torch.cat([add_time_ids, add_time_ids], dim=0)
482
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
483
+
484
+
485
+ print(latents.shape)
486
+ print(add_time_ids.shape)
487
+
488
+ # 11. Denoising loop
489
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
490
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
491
+ for i, t in enumerate(timesteps):
492
+ if self.interrupt:
493
+ continue
494
+
495
+ latent_model_input = (
496
+ torch.cat([latents] * 2) if do_classifier_free_guidance else latents
497
+ )
498
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
499
+
500
+ if i <= start_merge_step or nc_flag:
501
+ current_prompt_embeds = torch.cat(
502
+ [negative_prompt_embeds, prompt_embeds_text_only], dim=0
503
+ )
504
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, pooled_prompt_embeds_text_only], dim=0)
505
+ else:
506
+ current_prompt_embeds = torch.cat(
507
+ [negative_prompt_embeds, prompt_embeds], dim=0
508
+ )
509
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, pooled_prompt_embeds], dim=0)
510
+ # predict the noise residual
511
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
512
+ # print(latent_model_input.shape)
513
+ # print(t)
514
+ # print(current_prompt_embeds.shape)
515
+ # print(add_text_embeds.shape)
516
+ # print(add_time_ids.shape)
517
+ #zeros_matrix =
518
+ #global_mask1024 = torch.cat([torch.randn(1, 1024, 1, 1, device=device) for random_number])
519
+ #global_mask4096 =
520
+ noise_pred = self.unet(
521
+ latent_model_input,
522
+ t,
523
+ encoder_hidden_states=current_prompt_embeds,
524
+ cross_attention_kwargs=cross_attention_kwargs,
525
+ added_cond_kwargs=added_cond_kwargs,
526
+ return_dict=False,
527
+ )[0]
528
+ # print(noise_pred.shape)
529
+ # perform guidance
530
+ if do_classifier_free_guidance:
531
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
532
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
533
+
534
+ if do_classifier_free_guidance and guidance_rescale > 0.0:
535
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
536
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
537
+
538
+ # compute the previous noisy sample x_t -> x_t-1
539
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
540
+
541
+ if callback_on_step_end is not None:
542
+ callback_kwargs = {}
543
+ for k in callback_on_step_end_tensor_inputs:
544
+ callback_kwargs[k] = locals()[k]
545
+
546
+ ck_outputs = callback_on_step_end(self, i, t, callback_kwargs)
547
+
548
+ latents = callback_outputs.pop("latents", latents)
549
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
550
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
551
+ add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
552
+ # negative_pooled_prompt_embeds = callback_outputs.pop(
553
+ # "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
554
+ # )
555
+ # add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
556
+ # negative_add_time_ids = callback_outputs.pop("negative_add_time_ids", negative_add_time_ids)
557
+
558
+ # call the callback, if provided
559
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
560
+ progress_bar.update()
561
+ if callback is not None and i % callback_steps == 0:
562
+ step_idx = i // getattr(self.scheduler, "order", 1)
563
+ callback(step_idx, t, latents)
564
+
565
+ # make sure the VAE is in float32 mode, as it overflows in float16
566
+ if self.vae.dtype == torch.float16 and self.vae.config.force_upcast:
567
+ self.upcast_vae()
568
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
569
+
570
+ if not output_type == "latent":
571
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
572
+ else:
573
+ image = latents
574
+ return StableDiffusionXLPipelineOutput(images=image)
575
+
576
+ # apply watermark if available
577
+ # if self.watermark is not None:
578
+ # image = self.watermark.apply_watermark(image)
579
+
580
+ image = self.image_processor.postprocess(image, output_type=output_type)
581
+
582
+ # Offload all models
583
+ self.maybe_free_model_hooks()
584
+
585
+ if not return_dict:
586
+ return (image,)
587
+
588
+ return StableDiffusionXLPipelineOutput(images=image)
style_template.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, (Anime Style, Manga Style:1.3), Low detail, sketch, concept art, line art, webtoon, manhua, hand drawn, defined lines, simple shades, minimalistic, High contrast, Linear compositions, Scalable artwork, Digital art, High Contrast Shadows",
10
+ "negative_prompt": "lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry",
11
+ },
12
+ {
13
+ "name": "Digital/Oil Painting",
14
+ "prompt": "{prompt} . (Extremely Detailed Oil Painting:1.2), glow effects, godrays, Hand drawn, render, 8k, octane render, cinema 4d, blender, dark, atmospheric 4k ultra detailed, cinematic sensual, Sharp focus, humorous illustration, big depth of field",
15
+ "negative_prompt": "anime, cartoon, graphic, text, painting, crayon, graphite, abstract, glitch, deformed, mutated, ugly, disfigured, lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry",
16
+ },
17
+ {
18
+ "name": "Pixar/Disney Character",
19
+ "prompt": "Create a Disney Pixar 3D style illustration on {prompt} . The scene is vibrant, motivational, filled with vivid colors and a sense of wonder.",
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} . Hyperrealistic, Hyperdetailed, detailed skin, matte skin, soft lighting, realistic, best quality, ultra realistic, 8k, golden ratio, Intricate, High Detail, film photography, soft focus",
25
+ "negative_prompt": "drawing, painting, crayon, sketch, graphite, impressionist, noisy, blurry, soft, deformed, ugly, lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry",
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, lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry",
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, lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry",
36
+ },
37
+ {
38
+ "name": "Black and White Film Noir",
39
+ "prompt": "{prompt} . (b&w, Monochromatic, Film Photography:1.3), film noir, analog style, soft lighting, subsurface scattering, realistic, heavy shadow, masterpiece, best quality, ultra realistic, 8k",
40
+ "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, lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry",
41
+ },
42
+ {
43
+ "name": "Isometric Rooms",
44
+ "prompt": "Tiny cute isometric {prompt} . in a cutaway box, soft smooth lighting, soft colors, 100mm lens, 3d blender render",
45
+ "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, lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry",
46
+ },
47
+ ]
48
+
49
+ styles = {k["name"]: (k["prompt"], k["negative_prompt"]) for k in style_list}
utils.py ADDED
@@ -0,0 +1,426 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ bbox = draw.textbbox((0, 0), test_line, font=font)
39
+ text_left, text_top, text_right, text_bottom = bbox
40
+
41
+ width, _ = (text_right - text_left, text_bottom - text_top)
42
+
43
+ if width <= max_width:
44
+ # If it fits, add this word to the current line
45
+ current_line = test_line
46
+ else:
47
+ # If not, store the line and start a new one
48
+ lines.append(current_line)
49
+ current_line = word
50
+ # Add the last line
51
+ lines.append(current_line)
52
+ return lines
53
+
54
+
55
+
56
+ def add_caption(image, text, position = "bottom-mid", font = None, text_color= 'black', bg_color = (255, 255, 255) , bg_opacity = 200):
57
+ if text == "":
58
+ return image
59
+ image = image.convert("RGBA")
60
+ draw = ImageDraw.Draw(image)
61
+ width, height = image.size
62
+ lines = process_mulline_text(draw,text,font,width)
63
+ text_positions = []
64
+ maxwidth = 0
65
+ for ind, line in enumerate(lines[::-1]):
66
+ bbox = draw.textbbox((0, 0), line, font=font)
67
+ text_left, text_top, text_right, text_bottom = bbox
68
+ text_width, text_height = (text_right - text_left, text_bottom - text_top)
69
+ if position == 'bottom-right':
70
+ text_position = (width - text_width - 10, height - (text_height + 20))
71
+ elif position == 'bottom-left':
72
+ text_position = (10, height - (text_height + 20))
73
+ elif position == 'bottom-mid':
74
+ text_position = ((width - text_width) // 2, height - (text_height + 20) ) # 居中文本
75
+ height = text_position[1]
76
+ maxwidth = max(maxwidth,text_width)
77
+ text_positions.append(text_position)
78
+ rectpos = (width - maxwidth) // 2
79
+ rectangle_position = [rectpos - 5, text_positions[-1][1] - 5, rectpos + maxwidth + 5, text_positions[0][1] + text_height + 5]
80
+ image_with_transparency = Image.new('RGBA', image.size)
81
+ draw_with_transparency = ImageDraw.Draw(image_with_transparency)
82
+ draw_with_transparency.rectangle(rectangle_position, fill=bg_color + (bg_opacity,))
83
+
84
+ image.paste(Image.alpha_composite(image.convert('RGBA'), image_with_transparency))
85
+ print(ind,text_position)
86
+ draw = ImageDraw.Draw(image)
87
+ for ind, line in enumerate(lines[::-1]):
88
+ text_position = text_positions[ind]
89
+ draw.text(text_position, line, fill=text_color, font=font)
90
+
91
+ return image.convert('RGB')
92
+
93
+ def get_comic(images,types = "4panel",captions = [],font = None,pad_image = None):
94
+ if pad_image == None:
95
+ pad_image = Image.open("./images/pad_images.png")
96
+
97
+ if types == "No typesetting (default)":
98
+ return images
99
+ elif types == "Four Pannel":
100
+ return get_comic_4panel(images,captions,font,pad_image)
101
+ else: # "Classic Comic Style"
102
+ return get_comic_classical(images,captions,font,pad_image)
103
+
104
+ def get_caption_group(images_groups,captions = []):
105
+ caption_groups = []
106
+ for i in range(len(images_groups)):
107
+ length = len(images_groups[i])
108
+ caption_groups.append(captions[:length])
109
+ captions = captions[length:]
110
+ if len(caption_groups[-1]) < len(images_groups[-1]):
111
+ caption_groups[-1] = caption_groups[-1] + [""] * (len(images_groups[-1]) - len(caption_groups[-1]))
112
+ return caption_groups
113
+
114
+ def get_comic_classical(images,captions = None,font = None,pad_image = None):
115
+ if pad_image == None:
116
+ raise ValueError("pad_image is None")
117
+ images = [add_white_border(image) for image in images]
118
+ pad_image = pad_image.resize(images[0].size, Image.LANCZOS)
119
+ images_groups = distribute_images2(images,pad_image)
120
+ print(images_groups)
121
+ if captions != None:
122
+ captions_groups = get_caption_group(images_groups,captions)
123
+ # print(images_groups)
124
+ row_images = []
125
+ for ind, img_group in enumerate(images_groups):
126
+ row_images.append(get_row_image2(img_group ,captions= captions_groups[ind] if captions != None else None,font = font))
127
+
128
+ return [combine_images_vertically_with_resize(row_images)]
129
+
130
+
131
+
132
+ def get_comic_4panel(images,captions = [],font = None,pad_image = None):
133
+ if pad_image == None:
134
+ raise ValueError("pad_image is None")
135
+ pad_image = pad_image.resize(images[0].size, Image.LANCZOS)
136
+ images = [add_white_border(image) for image in images]
137
+ assert len(captions) == len(images)
138
+ for i,caption in enumerate(captions):
139
+ images[i] = add_caption(images[i],caption,font = font)
140
+ images_nums = len(images)
141
+ pad_nums = int((4 - images_nums % 4) % 4)
142
+ images = images + [pad_image for _ in range(pad_nums)]
143
+ comics = []
144
+ assert len(images)%4 == 0
145
+ for i in range(len(images)//4):
146
+ 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])]))
147
+
148
+ return comics
149
+
150
+ def get_row_image(images):
151
+ row_image_arr = []
152
+ if len(images)>3:
153
+ stack_img_nums = (len(images) - 2)//2
154
+ else:
155
+ stack_img_nums = 0
156
+ while(len(images)>0):
157
+ if stack_img_nums <=0:
158
+ row_image_arr.append(images[0])
159
+ images = images[1:]
160
+ elif len(images)>stack_img_nums*2:
161
+ if get_random_bool():
162
+ row_image_arr.append(concat_images_vertically_and_scale(images[:2]))
163
+ images = images[2:]
164
+ stack_img_nums -=1
165
+ else:
166
+ row_image_arr.append(images[0])
167
+ images = images[1:]
168
+ else:
169
+ row_image_arr.append(concat_images_vertically_and_scale(images[:2]))
170
+ images = images[2:]
171
+ stack_img_nums-=1
172
+ return combine_images_horizontally(row_image_arr)
173
+
174
+ def get_row_image2(images,captions = None, font = None):
175
+ row_image_arr = []
176
+ if len(images)== 6:
177
+ sequence_list = [1,1,2,2]
178
+ elif len(images)== 4:
179
+ sequence_list = [1,1,2]
180
+ else:
181
+ raise ValueError("images nums is not 4 or 6 found",len(images))
182
+ random.shuffle(sequence_list)
183
+ index = 0
184
+ for length in sequence_list:
185
+ if length == 1:
186
+ if captions != None:
187
+ images_tmp = add_caption(images[0],text = captions[index],font= font)
188
+ else:
189
+ images_tmp = images[0]
190
+ row_image_arr.append( images_tmp)
191
+ images = images[1:]
192
+ index +=1
193
+ elif length == 2:
194
+ row_image_arr.append(concat_images_vertically_and_scale(images[:2]))
195
+ images = images[2:]
196
+ index +=2
197
+
198
+ return combine_images_horizontally(row_image_arr)
199
+
200
+
201
+
202
+ def concat_images_vertically_and_scale(images,scale_factor=2):
203
+ # 加载所有图像
204
+ # 确保所有图像的宽度一致
205
+ widths = [img.width for img in images]
206
+ if not all(width == widths[0] for width in widths):
207
+ raise ValueError('All images must have the same width.')
208
+
209
+ # 计算总高度
210
+ total_height = sum(img.height for img in images)
211
+
212
+ # 创建新的图像,宽度与原图相同,高度为所有图像高度之和
213
+ max_width = max(widths)
214
+ concatenated_image = Image.new('RGB', (max_width, total_height))
215
+
216
+ # 竖直拼接图像
217
+ current_height = 0
218
+ for img in images:
219
+ concatenated_image.paste(img, (0, current_height))
220
+ current_height += img.height
221
+
222
+ # 缩放图像为1/n高度
223
+ new_height = concatenated_image.height // scale_factor
224
+ new_width = concatenated_image.width // scale_factor
225
+ resized_image = concatenated_image.resize((new_width, new_height), Image.LANCZOS)
226
+
227
+ return resized_image
228
+
229
+
230
+ def combine_images_horizontally(images):
231
+ # 读取所有图片并存入列表
232
+
233
+ # 获取每幅图像的宽度和高度
234
+ widths, heights = zip(*(i.size for i in images))
235
+
236
+ # 计算总宽度和最大高度
237
+ total_width = sum(widths)
238
+ max_height = max(heights)
239
+
240
+ # 创建新的空白图片,用于拼接
241
+ new_im = Image.new('RGB', (total_width, max_height))
242
+
243
+ # 将图片横向拼接
244
+ x_offset = 0
245
+ for im in images:
246
+ new_im.paste(im, (x_offset, 0))
247
+ x_offset += im.width
248
+
249
+ return new_im
250
+
251
+ def combine_images_vertically_with_resize(images):
252
+
253
+ # 获取所有图片的宽度和高度
254
+ widths, heights = zip(*(i.size for i in images))
255
+
256
+ # 确定新图片的宽度,即所有图片中最小的宽度
257
+ min_width = min(widths)
258
+
259
+ # 调整图片尺寸以保持宽度一致,长宽比不变
260
+ resized_images = []
261
+ for img in images:
262
+ # 计算新高度保持图片长宽比
263
+ new_height = int(min_width * img.height / img.width)
264
+ # 调整图片大小
265
+ resized_img = img.resize((min_width, new_height), Image.LANCZOS)
266
+ resized_images.append(resized_img)
267
+
268
+ # 计算所有调整尺寸后图片的总高度
269
+ total_height = sum(img.height for img in resized_images)
270
+
271
+ # 创建一个足够宽和���的新图片对象
272
+ new_im = Image.new('RGB', (min_width, total_height))
273
+
274
+ # 竖直拼接图片
275
+ y_offset = 0
276
+ for im in resized_images:
277
+ new_im.paste(im, (0, y_offset))
278
+ y_offset += im.height
279
+
280
+ return new_im
281
+
282
+ def distribute_images2(images, pad_image):
283
+ groups = []
284
+ remaining = len(images)
285
+ if len(images) <= 8:
286
+ group_sizes = [4]
287
+ else:
288
+ group_sizes = [4, 6]
289
+
290
+ size_index = 0
291
+ while remaining > 0:
292
+ size = group_sizes[size_index%len(group_sizes)]
293
+ if remaining < size and remaining < min(group_sizes):
294
+ size = min(group_sizes)
295
+ if remaining > size:
296
+ new_group = images[-remaining: -remaining + size]
297
+ else:
298
+ new_group = images[-remaining:]
299
+ groups.append(new_group)
300
+ size_index += 1
301
+ remaining -= size
302
+ print(remaining,groups)
303
+ groups[-1] = groups[-1] + [pad_image for _ in range(-remaining)]
304
+
305
+ return groups
306
+
307
+
308
+ def distribute_images(images, group_sizes=(4, 3, 2)):
309
+ groups = []
310
+ remaining = len(images)
311
+
312
+ while remaining > 0:
313
+ # 优先分配最大组(4张图片),再考虑3张,最后处理2张
314
+ for size in sorted(group_sizes, reverse=True):
315
+ # 如果剩下的图片数量大于等于当前组大小,或者为图片总数时(也就是第一次迭代)
316
+ # 开始创建新组
317
+ if remaining >= size or remaining == len(images):
318
+ if remaining > size:
319
+ new_group = images[-remaining: -remaining + size]
320
+ else:
321
+ new_group = images[-remaining:]
322
+ groups.append(new_group)
323
+ remaining -= size
324
+ break
325
+ # 如果剩下的图片少于最小的组大小(2张)并且已经有组了,就把剩下的图片加到最后一个组
326
+ elif remaining < min(group_sizes) and groups:
327
+ groups[-1].extend(images[-remaining:])
328
+ remaining = 0
329
+
330
+ return groups
331
+
332
+ def create_binary_matrix(img_arr, target_color):
333
+ mask = np.all(img_arr == target_color, axis=-1)
334
+ binary_matrix = mask.astype(int)
335
+ return binary_matrix
336
+
337
+ def preprocess_mask(mask_, h, w, device):
338
+ mask = np.array(mask_)
339
+ mask = mask.astype(np.float32)
340
+ mask = mask[None, None]
341
+ mask[mask < 0.5] = 0
342
+ mask[mask >= 0.5] = 1
343
+ mask = torch.from_numpy(mask).to(device)
344
+ mask = torch.nn.functional.interpolate(mask, size=(h, w), mode='nearest')
345
+ return mask
346
+
347
+ def process_sketch(canvas_data):
348
+ binary_matrixes = []
349
+ base64_img = canvas_data['image']
350
+ image_data = base64.b64decode(base64_img.split(',')[1])
351
+ image = Image.open(BytesIO(image_data)).convert("RGB")
352
+ im2arr = np.array(image)
353
+ colors = [tuple(map(int, rgb[4:-1].split(','))) for rgb in canvas_data['colors']]
354
+ colors_fixed = []
355
+
356
+ r, g, b = 255, 255, 255
357
+ binary_matrix = create_binary_matrix(im2arr, (r,g,b))
358
+ binary_matrixes.append(binary_matrix)
359
+ binary_matrix_ = np.repeat(np.expand_dims(binary_matrix, axis=(-1)), 3, axis=(-1))
360
+ colored_map = binary_matrix_*(r,g,b) + (1-binary_matrix_)*(50,50,50)
361
+ colors_fixed.append(gr.update(value=colored_map.astype(np.uint8)))
362
+
363
+ for color in colors:
364
+ r, g, b = color
365
+ if any(c != 255 for c in (r, g, b)):
366
+ binary_matrix = create_binary_matrix(im2arr, (r,g,b))
367
+ binary_matrixes.append(binary_matrix)
368
+ binary_matrix_ = np.repeat(np.expand_dims(binary_matrix, axis=(-1)), 3, axis=(-1))
369
+ colored_map = binary_matrix_*(r,g,b) + (1-binary_matrix_)*(50,50,50)
370
+ colors_fixed.append(gr.update(value=colored_map.astype(np.uint8)))
371
+
372
+ visibilities = []
373
+ colors = []
374
+ for n in range(MAX_COLORS):
375
+ visibilities.append(gr.update(visible=False))
376
+ colors.append(gr.update())
377
+ for n in range(len(colors_fixed)):
378
+ visibilities[n] = gr.update(visible=True)
379
+ colors[n] = colors_fixed[n]
380
+
381
+ return [gr.update(visible=True), binary_matrixes, *visibilities, *colors]
382
+
383
+ def process_prompts(binary_matrixes, *seg_prompts):
384
+ return [gr.update(visible=True), gr.update(value=' , '.join(seg_prompts[:len(binary_matrixes)]))]
385
+
386
+ def process_example(layout_path, all_prompts, seed_):
387
+
388
+ all_prompts = all_prompts.split('***')
389
+
390
+ binary_matrixes = []
391
+ colors_fixed = []
392
+
393
+ im2arr = np.array(Image.open(layout_path))[:,:,:3]
394
+ unique, counts = np.unique(np.reshape(im2arr,(-1,3)), axis=0, return_counts=True)
395
+ sorted_idx = np.argsort(-counts)
396
+
397
+ binary_matrix = create_binary_matrix(im2arr, (0,0,0))
398
+ binary_matrixes.append(binary_matrix)
399
+ binary_matrix_ = np.repeat(np.expand_dims(binary_matrix, axis=(-1)), 3, axis=(-1))
400
+ colored_map = binary_matrix_*(255,255,255) + (1-binary_matrix_)*(50,50,50)
401
+ colors_fixed.append(gr.update(value=colored_map.astype(np.uint8)))
402
+
403
+ for i in range(len(all_prompts)-1):
404
+ r, g, b = unique[sorted_idx[i]]
405
+ if any(c != 255 for c in (r, g, b)) and any(c != 0 for c in (r, g, b)):
406
+ binary_matrix = create_binary_matrix(im2arr, (r,g,b))
407
+ binary_matrixes.append(binary_matrix)
408
+ binary_matrix_ = np.repeat(np.expand_dims(binary_matrix, axis=(-1)), 3, axis=(-1))
409
+ colored_map = binary_matrix_*(r,g,b) + (1-binary_matrix_)*(50,50,50)
410
+ colors_fixed.append(gr.update(value=colored_map.astype(np.uint8)))
411
+
412
+ visibilities = []
413
+ colors = []
414
+ prompts = []
415
+ for n in range(MAX_COLORS):
416
+ visibilities.append(gr.update(visible=False))
417
+ colors.append(gr.update())
418
+ prompts.append(gr.update())
419
+
420
+ for n in range(len(colors_fixed)):
421
+ visibilities[n] = gr.update(visible=True)
422
+ colors[n] = colors_fixed[n]
423
+ prompts[n] = all_prompts[n+1]
424
+
425
+ return [gr.update(visible=True), binary_matrixes, *visibilities, *colors, *prompts,
426
+ gr.update(visible=True), gr.update(value=all_prompts[0]), int(seed_)]