rodrigomasini commited on
Commit
1e74e95
·
verified ·
1 Parent(s): e609716

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +1025 -0
app.py ADDED
@@ -0,0 +1,1025 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from email.policy import default
2
+ from json import encoder
3
+ import gradio as gr
4
+ import spaces
5
+ import numpy as np
6
+ import torch
7
+ import requests
8
+ import random
9
+ import os
10
+ import sys
11
+ import pickle
12
+ from PIL import Image
13
+ from tqdm.auto import tqdm
14
+ from datetime import datetime
15
+
16
+ import torch.nn as nn
17
+ import torch.nn.functional as F
18
+
19
+ class AttnProcessor(nn.Module):
20
+ r"""
21
+ Default processor for performing attention-related computations.
22
+ """
23
+ def __init__(
24
+ self,
25
+ hidden_size=None,
26
+ cross_attention_dim=None,
27
+ ):
28
+ super().__init__()
29
+
30
+ def __call__(
31
+ self,
32
+ attn,
33
+ hidden_states,
34
+ encoder_hidden_states=None,
35
+ attention_mask=None,
36
+ temb=None,
37
+ ):
38
+ residual = hidden_states
39
+
40
+ if attn.spatial_norm is not None:
41
+ hidden_states = attn.spatial_norm(hidden_states, temb)
42
+
43
+ input_ndim = hidden_states.ndim
44
+
45
+ if input_ndim == 4:
46
+ batch_size, channel, height, width = hidden_states.shape
47
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
48
+
49
+ batch_size, sequence_length, _ = (
50
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
51
+ )
52
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
53
+
54
+ if attn.group_norm is not None:
55
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
56
+
57
+ query = attn.to_q(hidden_states)
58
+
59
+ if encoder_hidden_states is None:
60
+ encoder_hidden_states = hidden_states
61
+ elif attn.norm_cross:
62
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
63
+
64
+ key = attn.to_k(encoder_hidden_states)
65
+ value = attn.to_v(encoder_hidden_states)
66
+
67
+ query = attn.head_to_batch_dim(query)
68
+ key = attn.head_to_batch_dim(key)
69
+ value = attn.head_to_batch_dim(value)
70
+
71
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
72
+ hidden_states = torch.bmm(attention_probs, value)
73
+ hidden_states = attn.batch_to_head_dim(hidden_states)
74
+
75
+ # linear proj
76
+ hidden_states = attn.to_out[0](hidden_states)
77
+ # dropout
78
+ hidden_states = attn.to_out[1](hidden_states)
79
+
80
+ if input_ndim == 4:
81
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
82
+
83
+ if attn.residual_connection:
84
+ hidden_states = hidden_states + residual
85
+
86
+ hidden_states = hidden_states / attn.rescale_output_factor
87
+
88
+ return hidden_states
89
+
90
+
91
+ class AttnProcessor2_0(torch.nn.Module):
92
+ r"""
93
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
94
+ """
95
+ def __init__(
96
+ self,
97
+ hidden_size=None,
98
+ cross_attention_dim=None,
99
+ ):
100
+ super().__init__()
101
+ if not hasattr(F, "scaled_dot_product_attention"):
102
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
103
+
104
+ def __call__(
105
+ self,
106
+ attn,
107
+ hidden_states,
108
+ encoder_hidden_states=None,
109
+ attention_mask=None,
110
+ temb=None,
111
+ ):
112
+ residual = hidden_states
113
+
114
+ if attn.spatial_norm is not None:
115
+ hidden_states = attn.spatial_norm(hidden_states, temb)
116
+
117
+ input_ndim = hidden_states.ndim
118
+
119
+ if input_ndim == 4:
120
+ batch_size, channel, height, width = hidden_states.shape
121
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
122
+
123
+ batch_size, sequence_length, _ = (
124
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
125
+ )
126
+
127
+ if attention_mask is not None:
128
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
129
+ # scaled_dot_product_attention expects attention_mask shape to be
130
+ # (batch, heads, source_length, target_length)
131
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
132
+
133
+ if attn.group_norm is not None:
134
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
135
+
136
+ query = attn.to_q(hidden_states)
137
+
138
+ if encoder_hidden_states is None:
139
+ encoder_hidden_states = hidden_states
140
+ elif attn.norm_cross:
141
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
142
+
143
+ key = attn.to_k(encoder_hidden_states)
144
+ value = attn.to_v(encoder_hidden_states)
145
+
146
+ inner_dim = key.shape[-1]
147
+ head_dim = inner_dim // attn.heads
148
+
149
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
150
+
151
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
152
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
153
+
154
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
155
+ # TODO: add support for attn.scale when we move to Torch 2.1
156
+ hidden_states = F.scaled_dot_product_attention(
157
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
158
+ )
159
+
160
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
161
+ hidden_states = hidden_states.to(query.dtype)
162
+
163
+ # linear proj
164
+ hidden_states = attn.to_out[0](hidden_states)
165
+ # dropout
166
+ hidden_states = attn.to_out[1](hidden_states)
167
+
168
+ if input_ndim == 4:
169
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
170
+
171
+ if attn.residual_connection:
172
+ hidden_states = hidden_states + residual
173
+
174
+ hidden_states = hidden_states / attn.rescale_output_factor
175
+
176
+ return hidden_states
177
+
178
+
179
+ def is_torch2_available():
180
+ return hasattr(F, "scaled_dot_product_attention")
181
+
182
+ if is_torch2_available():
183
+ from utils.gradio_utils import \
184
+ AttnProcessor2_0 as AttnProcessor
185
+ # from utils.gradio_utils import SpatialAttnProcessor2_0
186
+ else:
187
+ from utils.gradio_utils import AttnProcessor
188
+
189
+ import diffusers
190
+ from diffusers import StableDiffusionXLPipeline
191
+ from utils import PhotoMakerStableDiffusionXLPipeline
192
+ from diffusers import DDIMScheduler
193
+ import torch.nn.functional as F
194
+ def cal_attn_mask(total_length,id_length,sa16,sa32,sa64,device="cuda",dtype= torch.float16):
195
+ bool_matrix256 = torch.rand((1, total_length * 256),device = device,dtype = dtype) < sa16
196
+ bool_matrix1024 = torch.rand((1, total_length * 1024),device = device,dtype = dtype) < sa32
197
+ bool_matrix4096 = torch.rand((1, total_length * 4096),device = device,dtype = dtype) < sa64
198
+ bool_matrix256 = bool_matrix256.repeat(total_length,1)
199
+ bool_matrix1024 = bool_matrix1024.repeat(total_length,1)
200
+ bool_matrix4096 = bool_matrix4096.repeat(total_length,1)
201
+ for i in range(total_length):
202
+ bool_matrix256[i:i+1,id_length*256:] = False
203
+ bool_matrix1024[i:i+1,id_length*1024:] = False
204
+ bool_matrix4096[i:i+1,id_length*4096:] = False
205
+ bool_matrix256[i:i+1,i*256:(i+1)*256] = True
206
+ bool_matrix1024[i:i+1,i*1024:(i+1)*1024] = True
207
+ bool_matrix4096[i:i+1,i*4096:(i+1)*4096] = True
208
+ mask256 = bool_matrix256.unsqueeze(1).repeat(1,256,1).reshape(-1,total_length * 256)
209
+ mask1024 = bool_matrix1024.unsqueeze(1).repeat(1,1024,1).reshape(-1,total_length * 1024)
210
+ mask4096 = bool_matrix4096.unsqueeze(1).repeat(1,4096,1).reshape(-1,total_length * 4096)
211
+ return mask256,mask1024,mask4096
212
+
213
+ def cal_attn_mask_xl(total_length,id_length,sa32,sa64,height,width,device="cuda",dtype= torch.float16):
214
+ nums_1024 = (height // 32) * (width // 32)
215
+ nums_4096 = (height // 16) * (width // 16)
216
+ bool_matrix1024 = torch.rand((1, total_length * nums_1024),device = device,dtype = dtype) < sa32
217
+ bool_matrix4096 = torch.rand((1, total_length * nums_4096),device = device,dtype = dtype) < sa64
218
+ bool_matrix1024 = bool_matrix1024.repeat(total_length,1)
219
+ bool_matrix4096 = bool_matrix4096.repeat(total_length,1)
220
+ for i in range(total_length):
221
+ bool_matrix1024[i:i+1,id_length*nums_1024:] = False
222
+ bool_matrix4096[i:i+1,id_length*nums_4096:] = False
223
+ bool_matrix1024[i:i+1,i*nums_1024:(i+1)*nums_1024] = True
224
+ bool_matrix4096[i:i+1,i*nums_4096:(i+1)*nums_4096] = True
225
+ mask1024 = bool_matrix1024.unsqueeze(1).repeat(1,nums_1024,1).reshape(-1,total_length * nums_1024)
226
+ mask4096 = bool_matrix4096.unsqueeze(1).repeat(1,nums_4096,1).reshape(-1,total_length * nums_4096)
227
+ return mask1024,mask4096
228
+
229
+ import copy
230
+ import os
231
+ from huggingface_hub import hf_hub_download
232
+ from diffusers.utils import load_image
233
+ from utils.utils import get_comic # must remove this one
234
+
235
+ style_list = [
236
+ {
237
+ "name": "(No style)",
238
+ "prompt": "{prompt}",
239
+ "negative_prompt": "",
240
+ },
241
+ {
242
+ "name": "Japanese Anime",
243
+ "prompt": "anime artwork illustrating {prompt}. created by japanese anime studio. highly emotional. best quality, high resolution",
244
+ "negative_prompt": "low quality, low resolution"
245
+ },
246
+ {
247
+ "name": "Cinematic",
248
+ "prompt": "cinematic still {prompt} . emotional, harmonious, vignette, highly detailed, high budget, bokeh, cinemascope, moody, epic, gorgeous, film grain, grainy",
249
+ "negative_prompt": "anime, cartoon, graphic, text, painting, crayon, graphite, abstract, glitch, deformed, mutated, ugly, disfigured",
250
+ },
251
+ {
252
+ "name": "Disney Charactor",
253
+ "prompt": "A Pixar animation character of {prompt} . pixar-style, studio anime, Disney, high-quality",
254
+ "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",
255
+ },
256
+ {
257
+ "name": "Photographic",
258
+ "prompt": "cinematic photo {prompt} . 35mm photograph, film, bokeh, professional, 4k, highly detailed",
259
+ "negative_prompt": "drawing, painting, crayon, sketch, graphite, impressionist, noisy, blurry, soft, deformed, ugly",
260
+ },
261
+ {
262
+ "name": "Comic book",
263
+ "prompt": "comic {prompt} . graphic illustration, comic art, graphic novel art, vibrant, highly detailed",
264
+ "negative_prompt": "photograph, deformed, glitch, noisy, realistic, stock photo",
265
+ },
266
+ {
267
+ "name": "Line art",
268
+ "prompt": "line art drawing {prompt} . professional, sleek, modern, minimalist, graphic, line art, vector graphics",
269
+ "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",
270
+ }
271
+ ]
272
+
273
+ styles = {k["name"]: (k["prompt"], k["negative_prompt"]) for k in style_list}
274
+
275
+ image_encoder_path = "./data/models/ip_adapter/sdxl_models/image_encoder"
276
+ ip_ckpt = "./data/models/ip_adapter/sdxl_models/ip-adapter_sdxl_vit-h.bin"
277
+ os.environ["no_proxy"] = "localhost,127.0.0.1,::1"
278
+ STYLE_NAMES = list(styles.keys())
279
+ DEFAULT_STYLE_NAME = "Japanese Anime"
280
+ global models_dict
281
+ use_va = True
282
+ models_dict = {
283
+ # "Juggernaut": "RunDiffusion/Juggernaut-XL-v8",
284
+ "RealVision": "SG161222/RealVisXL_V4.0" ,
285
+ # "SDXL":"stabilityai/stable-diffusion-xl-base-1.0" ,
286
+ "Unstable": "stablediffusionapi/sdxl-unstable-diffusers-y"
287
+ }
288
+ photomaker_path = hf_hub_download(repo_id="TencentARC/PhotoMaker", filename="photomaker-v1.bin", repo_type="model")
289
+ MAX_SEED = np.iinfo(np.int32).max
290
+ def setup_seed(seed):
291
+ torch.manual_seed(seed)
292
+ torch.cuda.manual_seed_all(seed)
293
+ np.random.seed(seed)
294
+ random.seed(seed)
295
+ torch.backends.cudnn.deterministic = True
296
+ def set_text_unfinished():
297
+ return gr.update(visible=True, value="<h3>(Not Finished) Generating ··· The intermediate results will be shown.</h3>")
298
+ def set_text_finished():
299
+ return gr.update(visible=True, value="<h3>Generation Finished</h3>")
300
+ #################################################
301
+ def get_image_path_list(folder_name):
302
+ image_basename_list = os.listdir(folder_name)
303
+ image_path_list = sorted([os.path.join(folder_name, basename) for basename in image_basename_list])
304
+ return image_path_list
305
+
306
+ #################################################
307
+ class SpatialAttnProcessor2_0(torch.nn.Module):
308
+ r"""
309
+ Attention processor for IP-Adapater for PyTorch 2.0.
310
+ Args:
311
+ hidden_size (`int`):
312
+ The hidden size of the attention layer.
313
+ cross_attention_dim (`int`):
314
+ The number of channels in the `encoder_hidden_states`.
315
+ text_context_len (`int`, defaults to 77):
316
+ The context length of the text features.
317
+ scale (`float`, defaults to 1.0):
318
+ the weight scale of image prompt.
319
+ """
320
+
321
+ def __init__(self, hidden_size = None, cross_attention_dim=None,id_length = 4,device = "cuda",dtype = torch.float16):
322
+ super().__init__()
323
+ if not hasattr(F, "scaled_dot_product_attention"):
324
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
325
+ self.device = device
326
+ self.dtype = dtype
327
+ self.hidden_size = hidden_size
328
+ self.cross_attention_dim = cross_attention_dim
329
+ self.total_length = id_length + 1
330
+ self.id_length = id_length
331
+ self.id_bank = {}
332
+
333
+ def __call__(
334
+ self,
335
+ attn,
336
+ hidden_states,
337
+ encoder_hidden_states=None,
338
+ attention_mask=None,
339
+ temb=None):
340
+ # un_cond_hidden_states, cond_hidden_states = hidden_states.chunk(2)
341
+ # un_cond_hidden_states = self.__call2__(attn, un_cond_hidden_states,encoder_hidden_states,attention_mask,temb)
342
+ global total_count,attn_count,cur_step,mask1024,mask4096
343
+ global sa32, sa64
344
+ global write
345
+ global height,width
346
+ global num_steps
347
+ if write:
348
+ # print(f"white:{cur_step}")
349
+ self.id_bank[cur_step] = [hidden_states[:self.id_length], hidden_states[self.id_length:]]
350
+ else:
351
+ encoder_hidden_states = torch.cat((self.id_bank[cur_step][0].to(self.device),hidden_states[:1],self.id_bank[cur_step][1].to(self.device),hidden_states[1:]))
352
+ # 判断随机数是否大于0.5
353
+ if cur_step <=1:
354
+ hidden_states = self.__call2__(attn, hidden_states,None,attention_mask,temb)
355
+ else: # 256 1024 4096
356
+ random_number = random.random()
357
+ if cur_step <0.4 * num_steps:
358
+ rand_num = 0.3
359
+ else:
360
+ rand_num = 0.1
361
+ # print(f"hidden state shape {hidden_states.shape[1]}")
362
+ if random_number > rand_num:
363
+ # print("mask shape",mask1024.shape,mask4096.shape)
364
+ if not write:
365
+ if hidden_states.shape[1] == (height//32) * (width//32):
366
+ attention_mask = mask1024[mask1024.shape[0] // self.total_length * self.id_length:]
367
+ else:
368
+ attention_mask = mask4096[mask4096.shape[0] // self.total_length * self.id_length:]
369
+ else:
370
+ # print(self.total_length,self.id_length,hidden_states.shape,(height//32) * (width//32))
371
+ if hidden_states.shape[1] == (height//32) * (width//32):
372
+ attention_mask = mask1024[:mask1024.shape[0] // self.total_length * self.id_length,:mask1024.shape[0] // self.total_length * self.id_length]
373
+ else:
374
+ attention_mask = mask4096[:mask4096.shape[0] // self.total_length * self.id_length,:mask4096.shape[0] // self.total_length * self.id_length]
375
+ # print(attention_mask.shape)
376
+ # print("before attention",hidden_states.shape,attention_mask.shape,encoder_hidden_states.shape if encoder_hidden_states is not None else "None")
377
+ hidden_states = self.__call1__(attn, hidden_states,encoder_hidden_states,attention_mask,temb)
378
+ else:
379
+ hidden_states = self.__call2__(attn, hidden_states,None,attention_mask,temb)
380
+ attn_count +=1
381
+ if attn_count == total_count:
382
+ attn_count = 0
383
+ cur_step += 1
384
+ mask1024,mask4096 = cal_attn_mask_xl(self.total_length,self.id_length,sa32,sa64,height,width, device=self.device, dtype= self.dtype)
385
+
386
+ return hidden_states
387
+ def __call1__(
388
+ self,
389
+ attn,
390
+ hidden_states,
391
+ encoder_hidden_states=None,
392
+ attention_mask=None,
393
+ temb=None,
394
+ ):
395
+ # print("hidden state shape",hidden_states.shape,self.id_length)
396
+ residual = hidden_states
397
+ # if encoder_hidden_states is not None:
398
+ # raise Exception("not implement")
399
+ if attn.spatial_norm is not None:
400
+ hidden_states = attn.spatial_norm(hidden_states, temb)
401
+ input_ndim = hidden_states.ndim
402
+
403
+ if input_ndim == 4:
404
+ total_batch_size, channel, height, width = hidden_states.shape
405
+ hidden_states = hidden_states.view(total_batch_size, channel, height * width).transpose(1, 2)
406
+ total_batch_size,nums_token,channel = hidden_states.shape
407
+ img_nums = total_batch_size//2
408
+ hidden_states = hidden_states.view(-1,img_nums,nums_token,channel).reshape(-1,img_nums * nums_token,channel)
409
+
410
+ batch_size, sequence_length, _ = hidden_states.shape
411
+
412
+ if attn.group_norm is not None:
413
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
414
+
415
+ query = attn.to_q(hidden_states)
416
+
417
+ if encoder_hidden_states is None:
418
+ encoder_hidden_states = hidden_states # B, N, C
419
+ else:
420
+ encoder_hidden_states = encoder_hidden_states.view(-1,self.id_length+1,nums_token,channel).reshape(-1,(self.id_length+1) * nums_token,channel)
421
+
422
+ key = attn.to_k(encoder_hidden_states)
423
+ value = attn.to_v(encoder_hidden_states)
424
+
425
+
426
+ inner_dim = key.shape[-1]
427
+ head_dim = inner_dim // attn.heads
428
+
429
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
430
+
431
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
432
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
433
+ # print(key.shape,value.shape,query.shape,attention_mask.shape)
434
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
435
+ # TODO: add support for attn.scale when we move to Torch 2.1
436
+ #print(query.shape,key.shape,value.shape,attention_mask.shape)
437
+ hidden_states = F.scaled_dot_product_attention(
438
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
439
+ )
440
+
441
+ hidden_states = hidden_states.transpose(1, 2).reshape(total_batch_size, -1, attn.heads * head_dim)
442
+ hidden_states = hidden_states.to(query.dtype)
443
+
444
+
445
+
446
+ # linear proj
447
+ hidden_states = attn.to_out[0](hidden_states)
448
+ # dropout
449
+ hidden_states = attn.to_out[1](hidden_states)
450
+
451
+ # if input_ndim == 4:
452
+ # tile_hidden_states = tile_hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
453
+
454
+ # if attn.residual_connection:
455
+ # tile_hidden_states = tile_hidden_states + residual
456
+
457
+ if input_ndim == 4:
458
+ hidden_states = hidden_states.transpose(-1, -2).reshape(total_batch_size, channel, height, width)
459
+ if attn.residual_connection:
460
+ hidden_states = hidden_states + residual
461
+ hidden_states = hidden_states / attn.rescale_output_factor
462
+ # print(hidden_states.shape)
463
+ return hidden_states
464
+ def __call2__(
465
+ self,
466
+ attn,
467
+ hidden_states,
468
+ encoder_hidden_states=None,
469
+ attention_mask=None,
470
+ temb=None):
471
+ residual = hidden_states
472
+
473
+ if attn.spatial_norm is not None:
474
+ hidden_states = attn.spatial_norm(hidden_states, temb)
475
+
476
+ input_ndim = hidden_states.ndim
477
+
478
+ if input_ndim == 4:
479
+ batch_size, channel, height, width = hidden_states.shape
480
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
481
+
482
+ batch_size, sequence_length, channel = (
483
+ hidden_states.shape
484
+ )
485
+ # print(hidden_states.shape)
486
+ if attention_mask is not None:
487
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
488
+ # scaled_dot_product_attention expects attention_mask shape to be
489
+ # (batch, heads, source_length, target_length)
490
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
491
+
492
+ if attn.group_norm is not None:
493
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
494
+
495
+ query = attn.to_q(hidden_states)
496
+
497
+ if encoder_hidden_states is None:
498
+ encoder_hidden_states = hidden_states # B, N, C
499
+ else:
500
+ encoder_hidden_states = encoder_hidden_states.view(-1,self.id_length+1,sequence_length,channel).reshape(-1,(self.id_length+1) * sequence_length,channel)
501
+
502
+ key = attn.to_k(encoder_hidden_states)
503
+ value = attn.to_v(encoder_hidden_states)
504
+
505
+ inner_dim = key.shape[-1]
506
+ head_dim = inner_dim // attn.heads
507
+
508
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
509
+
510
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
511
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
512
+
513
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
514
+ # TODO: add support for attn.scale when we move to Torch 2.1
515
+ hidden_states = F.scaled_dot_product_attention(
516
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
517
+ )
518
+
519
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
520
+ hidden_states = hidden_states.to(query.dtype)
521
+
522
+ # linear proj
523
+ hidden_states = attn.to_out[0](hidden_states)
524
+ # dropout
525
+ hidden_states = attn.to_out[1](hidden_states)
526
+
527
+ if input_ndim == 4:
528
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
529
+
530
+ if attn.residual_connection:
531
+ hidden_states = hidden_states + residual
532
+
533
+ hidden_states = hidden_states / attn.rescale_output_factor
534
+
535
+ return hidden_states
536
+
537
+ def set_attention_processor(unet,id_length,is_ipadapter = False):
538
+ global total_count
539
+ total_count = 0
540
+ attn_procs = {}
541
+ for name in unet.attn_processors.keys():
542
+ cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
543
+ if name.startswith("mid_block"):
544
+ hidden_size = unet.config.block_out_channels[-1]
545
+ elif name.startswith("up_blocks"):
546
+ block_id = int(name[len("up_blocks.")])
547
+ hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
548
+ elif name.startswith("down_blocks"):
549
+ block_id = int(name[len("down_blocks.")])
550
+ hidden_size = unet.config.block_out_channels[block_id]
551
+ if cross_attention_dim is None:
552
+ if name.startswith("up_blocks") :
553
+ attn_procs[name] = SpatialAttnProcessor2_0(id_length = id_length)
554
+ total_count +=1
555
+ else:
556
+ attn_procs[name] = AttnProcessor()
557
+ else:
558
+ if is_ipadapter:
559
+ attn_procs[name] = IPAttnProcessor2_0(
560
+ hidden_size=hidden_size,
561
+ cross_attention_dim=cross_attention_dim,
562
+ scale=1,
563
+ num_tokens=4,
564
+ ).to(unet.device, dtype=torch.float16)
565
+ else:
566
+ attn_procs[name] = AttnProcessor()
567
+
568
+ unet.set_attn_processor(copy.deepcopy(attn_procs))
569
+ print("successsfully load paired self-attention")
570
+ print(f"number of the processor : {total_count}")
571
+
572
+
573
+ canvas_html = "<div id='canvas-root' style='max-width:400px; margin: 0 auto'></div>"
574
+ load_js = """
575
+ async () => {
576
+ const url = "https://huggingface.co/datasets/radames/gradio-components/raw/main/sketch-canvas.js"
577
+ fetch(url)
578
+ .then(res => res.text())
579
+ .then(text => {
580
+ const script = document.createElement('script');
581
+ script.type = "module"
582
+ script.src = URL.createObjectURL(new Blob([text], { type: 'application/javascript' }));
583
+ document.head.appendChild(script);
584
+ });
585
+ }
586
+ """
587
+
588
+ get_js_colors = """
589
+ async (canvasData) => {
590
+ const canvasEl = document.getElementById("canvas-root");
591
+ return [canvasEl._data]
592
+ }
593
+ """
594
+
595
+ css = '''
596
+ #color-bg{display:flex;justify-content: center;align-items: center;}
597
+ .color-bg-item{width: 100%; height: 32px}
598
+ #main_button{width:100%}
599
+ <style>
600
+ '''
601
+
602
+
603
+ #################################################
604
+ title = r"""
605
+ <h1 align="center">StoryDiffusion: Consistent Self-Attention for Long-Range Image and Video Generation</h1>
606
+ """
607
+
608
+ description = r"""
609
+ <b>Official 🤗 Gradio demo</b> for <a href='https://github.com/HVision-NKU/StoryDiffusion' target='_blank'><b>StoryDiffusion: Consistent Self-Attention for Long-Range Image and Video Generation</b></a>.<br>
610
+ ❗️❗️❗️[<b>Important</b>] Personalization steps:<br>
611
+ 1️⃣ Enter a Textual Description for Character, if you add the Ref-Image, making sure to <b>follow the class word</b> you want to customize with the <b>trigger word</b>: `img`, such as: `man img` or `woman img` or `girl img`.<br>
612
+ 2️⃣ Enter the prompt array, each line corrsponds to one generated image.<br>
613
+ 3️⃣ Choose your preferred style template.<br>
614
+ 4️⃣ Click the <b>Submit</b> button to start customizing.
615
+ """
616
+
617
+ article = r"""
618
+ If StoryDiffusion is helpful, please help to ⭐ the <a href='https://github.com/HVision-NKU/StoryDiffusion' target='_blank'>Github Repo</a>. Thanks!
619
+ [![GitHub Stars](https://img.shields.io/github/stars/HVision-NKU/StoryDiffusion?style=social)](https://github.com/HVision-NKU/StoryDiffusion)
620
+ ---
621
+ 📝 **Citation**
622
+ <br>
623
+ If our work is useful for your research, please consider citing:
624
+ ```bibtex
625
+ @article{Zhou2024storydiffusion,
626
+ title={StoryDiffusion: Consistent Self-Attention for Long-Range Image and Video Generation},
627
+ author={Zhou, Yupeng and Zhou, Daquan and Cheng, Ming-Ming and Feng, Jiashi and Hou, Qibin},
628
+ year={2024}
629
+ }
630
+ ```
631
+ 📋 **License**
632
+ <br>
633
+ The Contents you create are under Apache-2.0 LICENSE. The Code are under Attribution-NonCommercial 4.0 International.
634
+ 📧 **Contact**
635
+ <br>
636
+ If you have any questions, please feel free to reach me out at <b>[email protected]</b>.
637
+ """
638
+ version = r"""
639
+ <h3 align="center">StoryDiffusion Version 0.01 (test version)</h3>
640
+ <h5 >1. Support image ref image. (Cartoon Ref image is not support now)</h5>
641
+ <h5 >2. Support Typesetting Style and Captioning.(By default, the prompt is used as the caption for each image. If you need to change the caption, add a # at the end of each line. Only the part after the # will be added as a caption to the image.)</h5>
642
+ <h5 >3. [NC]symbol (The [NC] symbol is used as a flag to indicate that no characters should be present in the generated scene images. If you want do that, prepend the "[NC]" at the beginning of the line. For example, to generate a scene of falling leaves without any character, write: "[NC] The leaves are falling."),Currently, support is only using Textual Description</h5>
643
+ <h5>Tips: Not Ready Now! Just Test! It's better to use prompts to assist in controlling the character's attire. Depending on the limited code integration time, there might be some undiscovered bugs. If you find that a particular generation result is significantly poor, please email me ([email protected]) Thank you very much.</h4>
644
+ """
645
+
646
+ #################################################
647
+ global attn_count, total_count, id_length, total_length,cur_step, cur_model_type
648
+ global write
649
+ global sa32, sa64
650
+ global height,width
651
+ attn_count = 0
652
+ total_count = 0
653
+ cur_step = 0
654
+ id_length = 4
655
+ total_length = 5
656
+ cur_model_type = ""
657
+ device="cuda"
658
+ global attn_procs,unet
659
+ attn_procs = {}
660
+ ###
661
+ write = False
662
+ ###
663
+ sa32 = 0.5
664
+ sa64 = 0.5
665
+ height = 768
666
+ width = 768
667
+ ###
668
+
669
+ global sd_model_path
670
+ sd_model_path = models_dict["Unstable"]#"SG161222/RealVisXL_V4.0"
671
+ use_safetensors= False
672
+
673
+ ### LOAD Stable Diffusion Pipeline
674
+ # pipe1 = StableDiffusionXLPipeline.from_pretrained(sd_model_path, torch_dtype=torch.float16, use_safetensors= use_safetensors)
675
+ # pipe1 = pipe1.to("cpu")
676
+ # pipe1.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
677
+ # # pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
678
+ # pipe1.scheduler.set_timesteps(50)
679
+ ###
680
+ pipe2 = PhotoMakerStableDiffusionXLPipeline.from_pretrained(
681
+ models_dict["Unstable"], torch_dtype=torch.float16, use_safetensors=use_safetensors)
682
+ pipe2 = pipe2.to("cpu")
683
+ pipe2.load_photomaker_adapter(
684
+ os.path.dirname(photomaker_path),
685
+ subfolder="",
686
+ weight_name=os.path.basename(photomaker_path),
687
+ trigger_word="img" # define the trigger word
688
+ )
689
+ pipe2 = pipe2.to("cpu")
690
+ pipe2.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
691
+ pipe2.fuse_lora()
692
+
693
+ pipe4 = PhotoMakerStableDiffusionXLPipeline.from_pretrained(
694
+ models_dict["RealVision"], torch_dtype=torch.float16, use_safetensors=True)
695
+ pipe4 = pipe4.to("cpu")
696
+ pipe4.load_photomaker_adapter(
697
+ os.path.dirname(photomaker_path),
698
+ subfolder="",
699
+ weight_name=os.path.basename(photomaker_path),
700
+ trigger_word="img" # define the trigger word
701
+ )
702
+ pipe4 = pipe4.to("cpu")
703
+ pipe4.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
704
+ pipe4.fuse_lora()
705
+
706
+ # pipe3 = StableDiffusionXLPipeline.from_pretrained("SG161222/RealVisXL_V4.0", torch_dtype=torch.float16)
707
+ # pipe3 = pipe3.to("cpu")
708
+ # pipe3.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
709
+ # # pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
710
+ # pipe3.scheduler.set_timesteps(50)
711
+ ######### Gradio Fuction
712
+
713
+ def swap_to_gallery(images):
714
+ return gr.update(value=images, visible=True), gr.update(visible=True), gr.update(visible=False)
715
+
716
+ def upload_example_to_gallery(images, prompt, style, negative_prompt):
717
+ return gr.update(value=images, visible=True), gr.update(visible=True), gr.update(visible=False)
718
+
719
+ def remove_back_to_files():
720
+ return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)
721
+
722
+ def remove_tips():
723
+ return gr.update(visible=False)
724
+
725
+ def apply_style_positive(style_name: str, positive: str):
726
+ p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
727
+ return p.replace("{prompt}", positive)
728
+
729
+ def apply_style(style_name: str, positives: list, negative: str = ""):
730
+ p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
731
+ return [p.replace("{prompt}", positive) for positive in positives], n + ' ' + negative
732
+
733
+ def change_visiale_by_model_type(_model_type):
734
+ if _model_type == "Only Using Textual Description":
735
+ return gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
736
+ elif _model_type == "Using Ref Images":
737
+ return gr.update(visible=True), gr.update(visible=True), gr.update(visible=False)
738
+ else:
739
+ raise ValueError("Invalid model type",_model_type)
740
+
741
+
742
+ @spaces.GPU(duration=120)
743
+ def process_generation(_sd_type,_model_type,_upload_images, _num_steps,style_name, _Ip_Adapter_Strength ,_style_strength_ratio, guidance_scale, seed_, sa32_, sa64_, id_length_, general_prompt, negative_prompt,prompt_array,G_height,G_width,_comic_type):
744
+ _model_type = "Photomaker" if _model_type == "Using Ref Images" else "original"
745
+ if _model_type == "Photomaker" and "img" not in general_prompt:
746
+ raise gr.Error("Please add the triger word \" img \" behind the class word you want to customize, such as: man img or woman img")
747
+ if _upload_images is None and _model_type != "original":
748
+ raise gr.Error(f"Cannot find any input face image!")
749
+ if len(prompt_array.splitlines()) > 10:
750
+ raise gr.Error(f"No more than 10 prompts in huggface demo for Speed! But found {len(prompt_array.splitlines())} prompts!")
751
+ global sa32, sa64,id_length,total_length,attn_procs,unet,cur_model_type,device
752
+ global num_steps
753
+ global write
754
+ global cur_step,attn_count
755
+ global height,width
756
+ height = G_height
757
+ width = G_width
758
+ global pipe2,pipe4
759
+ global sd_model_path,models_dict
760
+ sd_model_path = models_dict[_sd_type]
761
+ num_steps =_num_steps
762
+ use_safe_tensor = True
763
+ if style_name == "(No style)":
764
+ sd_model_path = models_dict["RealVision"]
765
+ if _model_type == "original":
766
+ pipe = StableDiffusionXLPipeline.from_pretrained(sd_model_path, torch_dtype=torch.float16)
767
+ pipe = pipe.to(device)
768
+ pipe.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
769
+ # pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
770
+ # pipe.scheduler.set_timesteps(50)
771
+ set_attention_processor(pipe.unet,id_length_,is_ipadapter = False)
772
+ elif _model_type == "Photomaker":
773
+ if _sd_type != "RealVision" and style_name != "(No style)":
774
+ pipe = pipe2.to(device)
775
+ pipe.id_encoder.to(device)
776
+ set_attention_processor(pipe.unet,id_length_,is_ipadapter = False)
777
+ else:
778
+ pipe = pipe4.to(device)
779
+ pipe.id_encoder.to(device)
780
+ set_attention_processor(pipe.unet,id_length_,is_ipadapter = False)
781
+ else:
782
+ raise NotImplementedError("You should choice between original and Photomaker!",f"But you choice {_model_type}")
783
+
784
+
785
+ pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
786
+ pipe.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
787
+ cur_model_type = _sd_type+"-"+_model_type+""+str(id_length_)
788
+ if _model_type != "original":
789
+ input_id_images = []
790
+ for img in _upload_images:
791
+ print(img)
792
+ input_id_images.append(load_image(img))
793
+ prompts = prompt_array.splitlines()
794
+ start_merge_step = int(float(_style_strength_ratio) / 100 * _num_steps)
795
+ if start_merge_step > 30:
796
+ start_merge_step = 30
797
+ print(f"start_merge_step:{start_merge_step}")
798
+ generator = torch.Generator(device="cuda").manual_seed(seed_)
799
+ sa32, sa64 = sa32_, sa64_
800
+ id_length = id_length_
801
+ clipped_prompts = prompts[:]
802
+ prompts = [general_prompt + "," + prompt if "[NC]" not in prompt else prompt.replace("[NC]","") for prompt in clipped_prompts]
803
+ prompts = [prompt.rpartition('#')[0] if "#" in prompt else prompt for prompt in prompts]
804
+ print(prompts)
805
+ id_prompts = prompts[:id_length]
806
+ real_prompts = prompts[id_length:]
807
+ torch.cuda.empty_cache()
808
+ write = True
809
+ cur_step = 0
810
+
811
+ attn_count = 0
812
+ id_prompts, negative_prompt = apply_style(style_name, id_prompts, negative_prompt)
813
+ setup_seed(seed_)
814
+ total_results = []
815
+ if _model_type == "original":
816
+ id_images = pipe(id_prompts, num_inference_steps=_num_steps, guidance_scale=guidance_scale, height = height, width = width,negative_prompt = negative_prompt,generator = generator).images
817
+ elif _model_type == "Photomaker":
818
+ id_images = pipe(id_prompts,input_id_images=input_id_images, num_inference_steps=_num_steps, guidance_scale=guidance_scale, start_merge_step = start_merge_step, height = height, width = width,negative_prompt = negative_prompt,generator = generator).images
819
+ else:
820
+ raise NotImplementedError("You should choice between original and Photomaker!",f"But you choice {_model_type}")
821
+ total_results = id_images + total_results
822
+ yield total_results
823
+ real_images = []
824
+ write = False
825
+ for real_prompt in real_prompts:
826
+ setup_seed(seed_)
827
+ cur_step = 0
828
+ real_prompt = apply_style_positive(style_name, real_prompt)
829
+ if _model_type == "original":
830
+ real_images.append(pipe(real_prompt, num_inference_steps=_num_steps, guidance_scale=guidance_scale, height = height, width = width,negative_prompt = negative_prompt,generator = generator).images[0])
831
+ elif _model_type == "Photomaker":
832
+ real_images.append(pipe(real_prompt, input_id_images=input_id_images, num_inference_steps=_num_steps, guidance_scale=guidance_scale, start_merge_step = start_merge_step, height = height, width = width,negative_prompt = negative_prompt,generator = generator).images[0])
833
+ else:
834
+ raise NotImplementedError("You should choice between original and Photomaker!",f"But you choice {_model_type}")
835
+ total_results = [real_images[-1]] + total_results
836
+ yield total_results
837
+ if _comic_type != "No typesetting (default)":
838
+ captions= prompt_array.splitlines()
839
+ captions = [caption.replace("[NC]","") for caption in captions]
840
+ captions = [caption.split('#')[-1] if "#" in caption else caption for caption in captions]
841
+ from PIL import ImageFont
842
+ total_results = get_comic(id_images + real_images, _comic_type,captions= captions,font=ImageFont.truetype("./fonts/Inkfree.ttf", int(45))) + total_results
843
+ if _model_type == "Photomaker":
844
+ pipe = pipe2.to("cpu")
845
+ pipe.id_encoder.to("cpu")
846
+ set_attention_processor(pipe.unet,id_length_,is_ipadapter = False)
847
+ yield total_results
848
+
849
+
850
+
851
+ def array2string(arr):
852
+ stringtmp = ""
853
+ for i,part in enumerate(arr):
854
+ if i != len(arr)-1:
855
+ stringtmp += part +"\n"
856
+ else:
857
+ stringtmp += part
858
+
859
+ return stringtmp
860
+
861
+
862
+ with gr.Blocks(css=css) as demo:
863
+ binary_matrixes = gr.State([])
864
+ color_layout = gr.State([])
865
+
866
+ gr.Markdown(title)
867
+ gr.Markdown(description)
868
+
869
+ with gr.Row():
870
+ with gr.Group(elem_id="main-image"):
871
+
872
+ prompts = []
873
+ colors = []
874
+
875
+ with gr.Column(visible=True) as gen_prompt_vis:
876
+ sd_type = gr.Dropdown(choices=list(models_dict.keys()), value = "Unstable",label="sd_type", info="Select pretrained model")
877
+ model_type = gr.Radio(["Only Using Textual Description", "Using Ref Images"], label="model_type", value = "Only Using Textual Description", info="Control type of the Character")
878
+ with gr.Group(visible=False) as control_image_input:
879
+ files = gr.Files(
880
+ label="Drag (Select) 1 or more photos of your face",
881
+ file_types=["image"],
882
+ )
883
+ uploaded_files = gr.Gallery(label="Your images", visible=False, columns=5, rows=1, height=200)
884
+ with gr.Column(visible=False) as clear_button:
885
+ remove_and_reupload = gr.ClearButton(value="Remove and upload new ones", components=files, size="sm")
886
+ general_prompt = gr.Textbox(value='', label="(1) Textual Description for Character", interactive=True)
887
+ negative_prompt = gr.Textbox(value='', label="(2) Negative_prompt", interactive=True)
888
+ style = gr.Dropdown(label="Style template", choices=STYLE_NAMES, value=DEFAULT_STYLE_NAME)
889
+ prompt_array = gr.Textbox(lines = 3,value='', label="(3) Comic Description (each line corresponds to a frame).", interactive=True)
890
+ with gr.Accordion("(4) Tune the hyperparameters", open=True):
891
+ #sa16_ = gr.Slider(label=" (The degree of Paired Attention at 16 x 16 self-attention layers) ", minimum=0, maximum=1., value=0.3, step=0.1)
892
+ sa32_ = gr.Slider(label=" (The degree of Paired Attention at 32 x 32 self-attention layers) ", minimum=0, maximum=1., value=0.7, step=0.1)
893
+ sa64_ = gr.Slider(label=" (The degree of Paired Attention at 64 x 64 self-attention layers) ", minimum=0, maximum=1., value=0.7, step=0.1)
894
+ id_length_ = gr.Slider(label= "Number of id images in total images" , minimum=2, maximum=4, value=3, step=1)
895
+ # total_length_ = gr.Slider(label= "Number of total images", minimum=1, maximum=20, value=1, step=1)
896
+ seed_ = gr.Slider(label="Seed", minimum=-1, maximum=MAX_SEED, value=0, step=1)
897
+ num_steps = gr.Slider(
898
+ label="Number of sample steps",
899
+ minimum=25,
900
+ maximum=50,
901
+ step=1,
902
+ value=50,
903
+ )
904
+ G_height = gr.Slider(
905
+ label="height",
906
+ minimum=256,
907
+ maximum=1024,
908
+ step=32,
909
+ value=1024,
910
+ )
911
+ G_width = gr.Slider(
912
+ label="width",
913
+ minimum=256,
914
+ maximum=1024,
915
+ step=32,
916
+ value=1024,
917
+ )
918
+ comic_type = gr.Radio(["No typesetting (default)", "Four Pannel", "Classic Comic Style"], value = "Classic Comic Style", label="Typesetting Style", info="Select the typesetting style ")
919
+ guidance_scale = gr.Slider(
920
+ label="Guidance scale",
921
+ minimum=0.1,
922
+ maximum=10.0,
923
+ step=0.1,
924
+ value=5,
925
+ )
926
+ style_strength_ratio = gr.Slider(
927
+ label="Style strength of Ref Image (%)",
928
+ minimum=15,
929
+ maximum=50,
930
+ step=1,
931
+ value=20,
932
+ visible=False
933
+ )
934
+ Ip_Adapter_Strength = gr.Slider(
935
+ label="Ip_Adapter_Strength",
936
+ minimum=0,
937
+ maximum=1,
938
+ step=0.1,
939
+ value=0.5,
940
+ visible=False
941
+ )
942
+ final_run_btn = gr.Button("Generate ! 😺")
943
+
944
+
945
+ with gr.Column():
946
+ out_image = gr.Gallery(label="Result", columns=2, height='auto')
947
+ generated_information = gr.Markdown(label="Generation Details", value="",visible=False)
948
+ gr.Markdown(version)
949
+ model_type.change(fn = change_visiale_by_model_type , inputs = model_type, outputs=[control_image_input,style_strength_ratio,Ip_Adapter_Strength])
950
+ files.upload(fn=swap_to_gallery, inputs=files, outputs=[uploaded_files, clear_button, files])
951
+ remove_and_reupload.click(fn=remove_back_to_files, outputs=[uploaded_files, clear_button, files])
952
+
953
+ final_run_btn.click(fn=set_text_unfinished, outputs = generated_information
954
+ ).then(process_generation, inputs=[sd_type,model_type,files, num_steps,style, Ip_Adapter_Strength,style_strength_ratio, guidance_scale, seed_, sa32_, sa64_, id_length_, general_prompt, negative_prompt, prompt_array,G_height,G_width,comic_type], outputs=out_image
955
+ ).then(fn=set_text_finished,outputs = generated_information)
956
+
957
+
958
+ gr.Examples(
959
+ examples=[
960
+ [0,0.5,0.5,2,"a man, wearing black suit",
961
+ "bad anatomy, bad hands, missing fingers, extra fingers, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, bad face, fused face, cloned face, three crus, fused feet, fused thigh, extra crus, ugly fingers, horn, cartoon, cg, 3d, unreal, animate, amputation, disconnected limbs",
962
+ array2string(["at home, read new paper #at home, The newspaper says there is a treasure house in the forest.",
963
+ "on the road, near the forest",
964
+ "[NC] The car on the road, near the forest #He drives to the forest in search of treasure.",
965
+ "[NC]A tiger appeared in the forest, at night ",
966
+ "very frightened, open mouth, in the forest, at night",
967
+ "running very fast, in the forest, at night",
968
+ "[NC] A house in the forest, at night #Suddenly, he discovers the treasure house!",
969
+ "in the house filled with treasure, laughing, at night #He is overjoyed inside the house."
970
+ ]),
971
+ "Comic book","Only Using Textual Description",get_image_path_list('./examples/taylor'),768,768
972
+ ],
973
+ [0,0.5,0.5,2,"a policeman img, wearing a white shirt",
974
+ "bad anatomy, bad hands, missing fingers, extra fingers, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, bad face, fused face, cloned face, three crus, fused feet, fused thigh, extra crus, ugly fingers, horn, cartoon, cg, 3d, unreal, animate, amputation, disconnected limbs",
975
+ array2string(["Directing traffic on the road. ",
976
+ "walking on the streets.",
977
+ "Chasing a man on the street.",
978
+ "At the police station.",
979
+ ]),
980
+ "Japanese Anime","Using Ref Images",get_image_path_list('./examples/lecun'),768,768
981
+ ],
982
+ [1,0.5,0.5,3,"a woman img, wearing a white T-shirt, blue loose hair",
983
+ "bad anatomy, bad hands, missing fingers, extra fingers, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, bad face, fused face, cloned face, three crus, fused feet, fused thigh, extra crus, ugly fingers, horn, cartoon, cg, 3d, unreal, animate, amputation, disconnected limbs",
984
+ array2string(["wake up in the bed",
985
+ "have breakfast",
986
+ "is on the road, go to company",
987
+ "work in the company",
988
+ "Take a walk next to the company at noon",
989
+ "lying in bed at night"]),
990
+ "Japanese Anime", "Using Ref Images",get_image_path_list('./examples/taylor'),768,768
991
+ ],
992
+ [0,0.5,0.5,3,"a man, wearing black jacket",
993
+ "bad anatomy, bad hands, missing fingers, extra fingers, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, bad face, fused face, cloned face, three crus, fused feet, fused thigh, extra crus, ugly fingers, horn, cartoon, cg, 3d, unreal, animate, amputation, disconnected limbs",
994
+ array2string(["wake up in the bed",
995
+ "have breakfast",
996
+ "is on the road, go to the company, close look",
997
+ "work in the company",
998
+ "laughing happily",
999
+ "lying in bed at night"
1000
+ ]),
1001
+ "Japanese Anime","Only Using Textual Description",get_image_path_list('./examples/taylor'),768,768
1002
+ ],
1003
+ [0,0.3,0.5,3,"a girl, wearing white shirt, black skirt, black tie, yellow hair",
1004
+ "bad anatomy, bad hands, missing fingers, extra fingers, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, bad face, fused face, cloned face, three crus, fused feet, fused thigh, extra crus, ugly fingers, horn, cartoon, cg, 3d, unreal, animate, amputation, disconnected limbs",
1005
+ array2string([
1006
+ "at home #at home, began to go to drawing",
1007
+ "sitting alone on a park bench.",
1008
+ "reading a book on a park bench.",
1009
+ "[NC]A squirrel approaches, peeking over the bench. ",
1010
+ "look around in the park. # She looks around and enjoys the beauty of nature.",
1011
+ "[NC]leaf falls from the tree, landing on the sketchbook.",
1012
+ "picks up the leaf, examining its details closely.",
1013
+ "[NC]The brown squirrel appear.",
1014
+ "is very happy # She is very happy to see the squirrel again",
1015
+ "[NC]The brown squirrel takes the cracker and scampers up a tree. # She gives the squirrel cracker"]),
1016
+ "Japanese Anime","Only Using Textual Description",get_image_path_list('./examples/taylor'),768,768
1017
+ ]
1018
+ ],
1019
+ inputs=[seed_, sa32_, sa64_, id_length_, general_prompt, negative_prompt, prompt_array,style,model_type,files,G_height,G_width],
1020
+ label='😺 Examples 😺',
1021
+ )
1022
+ gr.Markdown(article)
1023
+
1024
+
1025
+ demo.launch()