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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +789 -140
app.py CHANGED
@@ -1,154 +1,803 @@
 
 
1
  import gradio as gr
 
2
  import numpy as np
 
 
3
  import random
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
- # import spaces #[uncomment to use ZeroGPU]
6
- from diffusers import DiffusionPipeline
7
- import torch
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
- device = "cuda" if torch.cuda.is_available() else "cpu"
10
- model_repo_id = "stabilityai/sdxl-turbo" # Replace to the model you would like to use
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
- if torch.cuda.is_available():
13
- torch_dtype = torch.float16
14
- else:
15
- torch_dtype = torch.float32
 
 
 
 
 
 
 
16
 
17
- pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
18
- pipe = pipe.to(device)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
- MAX_SEED = np.iinfo(np.int32).max
21
- MAX_IMAGE_SIZE = 1024
22
-
23
-
24
- # @spaces.GPU #[uncomment to use ZeroGPU]
25
- def infer(
26
- prompt,
27
- negative_prompt,
28
- seed,
29
- randomize_seed,
30
- width,
31
- height,
32
- guidance_scale,
33
- num_inference_steps,
34
- progress=gr.Progress(track_tqdm=True),
35
- ):
36
- if randomize_seed:
37
- seed = random.randint(0, MAX_SEED)
38
-
39
- generator = torch.Generator().manual_seed(seed)
40
-
41
- image = pipe(
42
- prompt=prompt,
43
- negative_prompt=negative_prompt,
44
- guidance_scale=guidance_scale,
45
- num_inference_steps=num_inference_steps,
46
- width=width,
47
- height=height,
48
- generator=generator,
49
- ).images[0]
50
-
51
- return image, seed
52
-
53
-
54
- examples = [
55
- "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
56
- "An astronaut riding a green horse",
57
- "A delicious ceviche cheesecake slice",
58
- ]
59
-
60
- css = """
61
- #col-container {
62
- margin: 0 auto;
63
- max-width: 640px;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  }
65
  """
66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  with gr.Blocks(css=css) as demo:
68
- with gr.Column(elem_id="col-container"):
69
- gr.Markdown(" # Text-to-Image Gradio Template")
70
-
71
- with gr.Row():
72
- prompt = gr.Text(
73
- label="Prompt",
74
- show_label=False,
75
- max_lines=1,
76
- placeholder="Enter your prompt",
77
- container=False,
78
- )
79
-
80
- run_button = gr.Button("Run", scale=0, variant="primary")
81
-
82
- result = gr.Image(label="Result", show_label=False)
83
-
84
- with gr.Accordion("Advanced Settings", open=False):
85
- negative_prompt = gr.Text(
86
- label="Negative prompt",
87
- max_lines=1,
88
- placeholder="Enter a negative prompt",
89
- visible=False,
90
- )
91
-
92
- seed = gr.Slider(
93
- label="Seed",
94
- minimum=0,
95
- maximum=MAX_SEED,
96
- step=1,
97
- value=0,
98
- )
99
-
100
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
101
-
102
- with gr.Row():
103
- width = gr.Slider(
104
- label="Width",
105
- minimum=256,
106
- maximum=MAX_IMAGE_SIZE,
107
- step=32,
108
- value=1024, # Replace with defaults that work for your model
109
- )
110
-
111
- height = gr.Slider(
112
- label="Height",
113
- minimum=256,
114
- maximum=MAX_IMAGE_SIZE,
115
- step=32,
116
- value=1024, # Replace with defaults that work for your model
117
- )
118
-
119
- with gr.Row():
120
- guidance_scale = gr.Slider(
121
- label="Guidance scale",
122
- minimum=0.0,
123
- maximum=10.0,
124
- step=0.1,
125
- value=0.0, # Replace with defaults that work for your model
126
- )
127
-
128
- num_inference_steps = gr.Slider(
129
- label="Number of inference steps",
130
- minimum=1,
131
- maximum=50,
132
- step=1,
133
- value=2, # Replace with defaults that work for your model
134
- )
135
-
136
- gr.Examples(examples=examples, inputs=[prompt])
137
- gr.on(
138
- triggers=[run_button.click, prompt.submit],
139
- fn=infer,
140
- inputs=[
141
- prompt,
142
- negative_prompt,
143
- seed,
144
- randomize_seed,
145
- width,
146
- height,
147
- guidance_scale,
148
- num_inference_steps,
149
- ],
150
- outputs=[result, seed],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  )
 
 
 
152
 
153
- if __name__ == "__main__":
154
- demo.launch()
 
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
+ from utils.gradio_utils import is_torch2_available
16
+ if is_torch2_available():
17
+ from utils.gradio_utils import \
18
+ AttnProcessor2_0 as AttnProcessor
19
+ # from utils.gradio_utils import SpatialAttnProcessor2_0
20
+ else:
21
+ from utils.gradio_utils import AttnProcessor
22
 
23
+ import diffusers
24
+ from diffusers import StableDiffusionXLPipeline
25
+ from utils import PhotoMakerStableDiffusionXLPipeline
26
+ from diffusers import DDIMScheduler
27
+ import torch.nn.functional as F
28
+ from utils.gradio_utils import cal_attn_mask_xl
29
+ import copy
30
+ import os
31
+ from huggingface_hub import hf_hub_download
32
+ from diffusers.utils import load_image
33
+ from utils.utils import get_comic
34
+ from utils.style_template import styles
35
+ image_encoder_path = "./data/models/ip_adapter/sdxl_models/image_encoder"
36
+ ip_ckpt = "./data/models/ip_adapter/sdxl_models/ip-adapter_sdxl_vit-h.bin"
37
+ os.environ["no_proxy"] = "localhost,127.0.0.1,::1"
38
+ STYLE_NAMES = list(styles.keys())
39
+ DEFAULT_STYLE_NAME = "Japanese Anime"
40
+ global models_dict
41
+ use_va = True
42
+ models_dict = {
43
+ # "Juggernaut": "RunDiffusion/Juggernaut-XL-v8",
44
+ "RealVision": "SG161222/RealVisXL_V4.0" ,
45
+ # "SDXL":"stabilityai/stable-diffusion-xl-base-1.0" ,
46
+ "Unstable": "stablediffusionapi/sdxl-unstable-diffusers-y"
47
+ }
48
+ photomaker_path = hf_hub_download(repo_id="TencentARC/PhotoMaker", filename="photomaker-v1.bin", repo_type="model")
49
+ MAX_SEED = np.iinfo(np.int32).max
50
+ def setup_seed(seed):
51
+ torch.manual_seed(seed)
52
+ torch.cuda.manual_seed_all(seed)
53
+ np.random.seed(seed)
54
+ random.seed(seed)
55
+ torch.backends.cudnn.deterministic = True
56
+ def set_text_unfinished():
57
+ return gr.update(visible=True, value="<h3>(Not Finished) Generating ··· The intermediate results will be shown.</h3>")
58
+ def set_text_finished():
59
+ return gr.update(visible=True, value="<h3>Generation Finished</h3>")
60
+ #################################################
61
+ def get_image_path_list(folder_name):
62
+ image_basename_list = os.listdir(folder_name)
63
+ image_path_list = sorted([os.path.join(folder_name, basename) for basename in image_basename_list])
64
+ return image_path_list
65
 
66
+ #################################################
67
+ class SpatialAttnProcessor2_0(torch.nn.Module):
68
+ r"""
69
+ Attention processor for IP-Adapater for PyTorch 2.0.
70
+ Args:
71
+ hidden_size (`int`):
72
+ The hidden size of the attention layer.
73
+ cross_attention_dim (`int`):
74
+ The number of channels in the `encoder_hidden_states`.
75
+ text_context_len (`int`, defaults to 77):
76
+ The context length of the text features.
77
+ scale (`float`, defaults to 1.0):
78
+ the weight scale of image prompt.
79
+ """
80
 
81
+ def __init__(self, hidden_size = None, cross_attention_dim=None,id_length = 4,device = "cuda",dtype = torch.float16):
82
+ super().__init__()
83
+ if not hasattr(F, "scaled_dot_product_attention"):
84
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
85
+ self.device = device
86
+ self.dtype = dtype
87
+ self.hidden_size = hidden_size
88
+ self.cross_attention_dim = cross_attention_dim
89
+ self.total_length = id_length + 1
90
+ self.id_length = id_length
91
+ self.id_bank = {}
92
 
93
+ def __call__(
94
+ self,
95
+ attn,
96
+ hidden_states,
97
+ encoder_hidden_states=None,
98
+ attention_mask=None,
99
+ temb=None):
100
+ # un_cond_hidden_states, cond_hidden_states = hidden_states.chunk(2)
101
+ # un_cond_hidden_states = self.__call2__(attn, un_cond_hidden_states,encoder_hidden_states,attention_mask,temb)
102
+ # 生成一个0到1之间的随机数
103
+ global total_count,attn_count,cur_step,mask1024,mask4096
104
+ global sa32, sa64
105
+ global write
106
+ global height,width
107
+ global num_steps
108
+ if write:
109
+ # print(f"white:{cur_step}")
110
+ self.id_bank[cur_step] = [hidden_states[:self.id_length], hidden_states[self.id_length:]]
111
+ else:
112
+ 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:]))
113
+ # 判断随机数是否大于0.5
114
+ if cur_step <=1:
115
+ hidden_states = self.__call2__(attn, hidden_states,None,attention_mask,temb)
116
+ else: # 256 1024 4096
117
+ random_number = random.random()
118
+ if cur_step <0.4 * num_steps:
119
+ rand_num = 0.3
120
+ else:
121
+ rand_num = 0.1
122
+ # print(f"hidden state shape {hidden_states.shape[1]}")
123
+ if random_number > rand_num:
124
+ # print("mask shape",mask1024.shape,mask4096.shape)
125
+ if not write:
126
+ if hidden_states.shape[1] == (height//32) * (width//32):
127
+ attention_mask = mask1024[mask1024.shape[0] // self.total_length * self.id_length:]
128
+ else:
129
+ attention_mask = mask4096[mask4096.shape[0] // self.total_length * self.id_length:]
130
+ else:
131
+ # print(self.total_length,self.id_length,hidden_states.shape,(height//32) * (width//32))
132
+ if hidden_states.shape[1] == (height//32) * (width//32):
133
+ attention_mask = mask1024[:mask1024.shape[0] // self.total_length * self.id_length,:mask1024.shape[0] // self.total_length * self.id_length]
134
+ else:
135
+ attention_mask = mask4096[:mask4096.shape[0] // self.total_length * self.id_length,:mask4096.shape[0] // self.total_length * self.id_length]
136
+ # print(attention_mask.shape)
137
+ # print("before attention",hidden_states.shape,attention_mask.shape,encoder_hidden_states.shape if encoder_hidden_states is not None else "None")
138
+ hidden_states = self.__call1__(attn, hidden_states,encoder_hidden_states,attention_mask,temb)
139
+ else:
140
+ hidden_states = self.__call2__(attn, hidden_states,None,attention_mask,temb)
141
+ attn_count +=1
142
+ if attn_count == total_count:
143
+ attn_count = 0
144
+ cur_step += 1
145
+ mask1024,mask4096 = cal_attn_mask_xl(self.total_length,self.id_length,sa32,sa64,height,width, device=self.device, dtype= self.dtype)
146
 
147
+ return hidden_states
148
+ def __call1__(
149
+ self,
150
+ attn,
151
+ hidden_states,
152
+ encoder_hidden_states=None,
153
+ attention_mask=None,
154
+ temb=None,
155
+ ):
156
+ # print("hidden state shape",hidden_states.shape,self.id_length)
157
+ residual = hidden_states
158
+ # if encoder_hidden_states is not None:
159
+ # raise Exception("not implement")
160
+ if attn.spatial_norm is not None:
161
+ hidden_states = attn.spatial_norm(hidden_states, temb)
162
+ input_ndim = hidden_states.ndim
163
+
164
+ if input_ndim == 4:
165
+ total_batch_size, channel, height, width = hidden_states.shape
166
+ hidden_states = hidden_states.view(total_batch_size, channel, height * width).transpose(1, 2)
167
+ total_batch_size,nums_token,channel = hidden_states.shape
168
+ img_nums = total_batch_size//2
169
+ hidden_states = hidden_states.view(-1,img_nums,nums_token,channel).reshape(-1,img_nums * nums_token,channel)
170
+
171
+ batch_size, sequence_length, _ = hidden_states.shape
172
+
173
+ if attn.group_norm is not None:
174
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
175
+
176
+ query = attn.to_q(hidden_states)
177
+
178
+ if encoder_hidden_states is None:
179
+ encoder_hidden_states = hidden_states # B, N, C
180
+ else:
181
+ encoder_hidden_states = encoder_hidden_states.view(-1,self.id_length+1,nums_token,channel).reshape(-1,(self.id_length+1) * nums_token,channel)
182
+
183
+ key = attn.to_k(encoder_hidden_states)
184
+ value = attn.to_v(encoder_hidden_states)
185
+
186
+
187
+ inner_dim = key.shape[-1]
188
+ head_dim = inner_dim // attn.heads
189
+
190
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
191
+
192
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
193
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
194
+ # print(key.shape,value.shape,query.shape,attention_mask.shape)
195
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
196
+ # TODO: add support for attn.scale when we move to Torch 2.1
197
+ #print(query.shape,key.shape,value.shape,attention_mask.shape)
198
+ hidden_states = F.scaled_dot_product_attention(
199
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
200
+ )
201
+
202
+ hidden_states = hidden_states.transpose(1, 2).reshape(total_batch_size, -1, attn.heads * head_dim)
203
+ hidden_states = hidden_states.to(query.dtype)
204
+
205
+
206
+
207
+ # linear proj
208
+ hidden_states = attn.to_out[0](hidden_states)
209
+ # dropout
210
+ hidden_states = attn.to_out[1](hidden_states)
211
+
212
+ # if input_ndim == 4:
213
+ # tile_hidden_states = tile_hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
214
+
215
+ # if attn.residual_connection:
216
+ # tile_hidden_states = tile_hidden_states + residual
217
+
218
+ if input_ndim == 4:
219
+ hidden_states = hidden_states.transpose(-1, -2).reshape(total_batch_size, channel, height, width)
220
+ if attn.residual_connection:
221
+ hidden_states = hidden_states + residual
222
+ hidden_states = hidden_states / attn.rescale_output_factor
223
+ # print(hidden_states.shape)
224
+ return hidden_states
225
+ def __call2__(
226
+ self,
227
+ attn,
228
+ hidden_states,
229
+ encoder_hidden_states=None,
230
+ attention_mask=None,
231
+ temb=None):
232
+ residual = hidden_states
233
+
234
+ if attn.spatial_norm is not None:
235
+ hidden_states = attn.spatial_norm(hidden_states, temb)
236
+
237
+ input_ndim = hidden_states.ndim
238
+
239
+ if input_ndim == 4:
240
+ batch_size, channel, height, width = hidden_states.shape
241
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
242
+
243
+ batch_size, sequence_length, channel = (
244
+ hidden_states.shape
245
+ )
246
+ # print(hidden_states.shape)
247
+ if attention_mask is not None:
248
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
249
+ # scaled_dot_product_attention expects attention_mask shape to be
250
+ # (batch, heads, source_length, target_length)
251
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
252
+
253
+ if attn.group_norm is not None:
254
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
255
+
256
+ query = attn.to_q(hidden_states)
257
+
258
+ if encoder_hidden_states is None:
259
+ encoder_hidden_states = hidden_states # B, N, C
260
+ else:
261
+ encoder_hidden_states = encoder_hidden_states.view(-1,self.id_length+1,sequence_length,channel).reshape(-1,(self.id_length+1) * sequence_length,channel)
262
+
263
+ key = attn.to_k(encoder_hidden_states)
264
+ value = attn.to_v(encoder_hidden_states)
265
+
266
+ inner_dim = key.shape[-1]
267
+ head_dim = inner_dim // attn.heads
268
+
269
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
270
+
271
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
272
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
273
+
274
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
275
+ # TODO: add support for attn.scale when we move to Torch 2.1
276
+ hidden_states = F.scaled_dot_product_attention(
277
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
278
+ )
279
+
280
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
281
+ hidden_states = hidden_states.to(query.dtype)
282
+
283
+ # linear proj
284
+ hidden_states = attn.to_out[0](hidden_states)
285
+ # dropout
286
+ hidden_states = attn.to_out[1](hidden_states)
287
+
288
+ if input_ndim == 4:
289
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
290
+
291
+ if attn.residual_connection:
292
+ hidden_states = hidden_states + residual
293
+
294
+ hidden_states = hidden_states / attn.rescale_output_factor
295
+
296
+ return hidden_states
297
+
298
+ def set_attention_processor(unet,id_length,is_ipadapter = False):
299
+ global total_count
300
+ total_count = 0
301
+ attn_procs = {}
302
+ for name in unet.attn_processors.keys():
303
+ cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
304
+ if name.startswith("mid_block"):
305
+ hidden_size = unet.config.block_out_channels[-1]
306
+ elif name.startswith("up_blocks"):
307
+ block_id = int(name[len("up_blocks.")])
308
+ hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
309
+ elif name.startswith("down_blocks"):
310
+ block_id = int(name[len("down_blocks.")])
311
+ hidden_size = unet.config.block_out_channels[block_id]
312
+ if cross_attention_dim is None:
313
+ if name.startswith("up_blocks") :
314
+ attn_procs[name] = SpatialAttnProcessor2_0(id_length = id_length)
315
+ total_count +=1
316
+ else:
317
+ attn_procs[name] = AttnProcessor()
318
+ else:
319
+ if is_ipadapter:
320
+ attn_procs[name] = IPAttnProcessor2_0(
321
+ hidden_size=hidden_size,
322
+ cross_attention_dim=cross_attention_dim,
323
+ scale=1,
324
+ num_tokens=4,
325
+ ).to(unet.device, dtype=torch.float16)
326
+ else:
327
+ attn_procs[name] = AttnProcessor()
328
+
329
+ unet.set_attn_processor(copy.deepcopy(attn_procs))
330
+ print("successsfully load paired self-attention")
331
+ print(f"number of the processor : {total_count}")
332
+ #################################################
333
+ #################################################
334
+ canvas_html = "<div id='canvas-root' style='max-width:400px; margin: 0 auto'></div>"
335
+ load_js = """
336
+ async () => {
337
+ const url = "https://huggingface.co/datasets/radames/gradio-components/raw/main/sketch-canvas.js"
338
+ fetch(url)
339
+ .then(res => res.text())
340
+ .then(text => {
341
+ const script = document.createElement('script');
342
+ script.type = "module"
343
+ script.src = URL.createObjectURL(new Blob([text], { type: 'application/javascript' }));
344
+ document.head.appendChild(script);
345
+ });
346
+ }
347
+ """
348
+
349
+ get_js_colors = """
350
+ async (canvasData) => {
351
+ const canvasEl = document.getElementById("canvas-root");
352
+ return [canvasEl._data]
353
  }
354
  """
355
 
356
+ css = '''
357
+ #color-bg{display:flex;justify-content: center;align-items: center;}
358
+ .color-bg-item{width: 100%; height: 32px}
359
+ #main_button{width:100%}
360
+ <style>
361
+ '''
362
+
363
+
364
+ #################################################
365
+ title = r"""
366
+ <h1 align="center">StoryDiffusion: Consistent Self-Attention for Long-Range Image and Video Generation</h1>
367
+ """
368
+
369
+ description = r"""
370
+ <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>
371
+ ❗️❗️❗️[<b>Important</b>] Personalization steps:<br>
372
+ 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>
373
+ 2️⃣ Enter the prompt array, each line corrsponds to one generated image.<br>
374
+ 3️⃣ Choose your preferred style template.<br>
375
+ 4️⃣ Click the <b>Submit</b> button to start customizing.
376
+ """
377
+
378
+ article = r"""
379
+ If StoryDiffusion is helpful, please help to ⭐ the <a href='https://github.com/HVision-NKU/StoryDiffusion' target='_blank'>Github Repo</a>. Thanks!
380
+ [![GitHub Stars](https://img.shields.io/github/stars/HVision-NKU/StoryDiffusion?style=social)](https://github.com/HVision-NKU/StoryDiffusion)
381
+ ---
382
+ 📝 **Citation**
383
+ <br>
384
+ If our work is useful for your research, please consider citing:
385
+ ```bibtex
386
+ @article{Zhou2024storydiffusion,
387
+ title={StoryDiffusion: Consistent Self-Attention for Long-Range Image and Video Generation},
388
+ author={Zhou, Yupeng and Zhou, Daquan and Cheng, Ming-Ming and Feng, Jiashi and Hou, Qibin},
389
+ year={2024}
390
+ }
391
+ ```
392
+ 📋 **License**
393
+ <br>
394
+ The Contents you create are under Apache-2.0 LICENSE. The Code are under Attribution-NonCommercial 4.0 International.
395
+ 📧 **Contact**
396
+ <br>
397
+ If you have any questions, please feel free to reach me out at <b>[email protected]</b>.
398
+ """
399
+ version = r"""
400
+ <h3 align="center">StoryDiffusion Version 0.01 (test version)</h3>
401
+ <h5 >1. Support image ref image. (Cartoon Ref image is not support now)</h5>
402
+ <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>
403
+ <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>
404
+ <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>
405
+ """
406
+ #################################################
407
+ global attn_count, total_count, id_length, total_length,cur_step, cur_model_type
408
+ global write
409
+ global sa32, sa64
410
+ global height,width
411
+ attn_count = 0
412
+ total_count = 0
413
+ cur_step = 0
414
+ id_length = 4
415
+ total_length = 5
416
+ cur_model_type = ""
417
+ device="cuda"
418
+ global attn_procs,unet
419
+ attn_procs = {}
420
+ ###
421
+ write = False
422
+ ###
423
+ sa32 = 0.5
424
+ sa64 = 0.5
425
+ height = 768
426
+ width = 768
427
+ ###
428
+ global sd_model_path
429
+ sd_model_path = models_dict["Unstable"]#"SG161222/RealVisXL_V4.0"
430
+ use_safetensors= False
431
+ ### LOAD Stable Diffusion Pipeline
432
+ # pipe1 = StableDiffusionXLPipeline.from_pretrained(sd_model_path, torch_dtype=torch.float16, use_safetensors= use_safetensors)
433
+ # pipe1 = pipe1.to("cpu")
434
+ # pipe1.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
435
+ # # pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
436
+ # pipe1.scheduler.set_timesteps(50)
437
+ ###
438
+ pipe2 = PhotoMakerStableDiffusionXLPipeline.from_pretrained(
439
+ models_dict["Unstable"], torch_dtype=torch.float16, use_safetensors=use_safetensors)
440
+ pipe2 = pipe2.to("cpu")
441
+ pipe2.load_photomaker_adapter(
442
+ os.path.dirname(photomaker_path),
443
+ subfolder="",
444
+ weight_name=os.path.basename(photomaker_path),
445
+ trigger_word="img" # define the trigger word
446
+ )
447
+ pipe2 = pipe2.to("cpu")
448
+ pipe2.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
449
+ pipe2.fuse_lora()
450
+
451
+ pipe4 = PhotoMakerStableDiffusionXLPipeline.from_pretrained(
452
+ models_dict["RealVision"], torch_dtype=torch.float16, use_safetensors=True)
453
+ pipe4 = pipe4.to("cpu")
454
+ pipe4.load_photomaker_adapter(
455
+ os.path.dirname(photomaker_path),
456
+ subfolder="",
457
+ weight_name=os.path.basename(photomaker_path),
458
+ trigger_word="img" # define the trigger word
459
+ )
460
+ pipe4 = pipe4.to("cpu")
461
+ pipe4.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
462
+ pipe4.fuse_lora()
463
+
464
+ # pipe3 = StableDiffusionXLPipeline.from_pretrained("SG161222/RealVisXL_V4.0", torch_dtype=torch.float16)
465
+ # pipe3 = pipe3.to("cpu")
466
+ # pipe3.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
467
+ # # pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
468
+ # pipe3.scheduler.set_timesteps(50)
469
+ ######### Gradio Fuction #############
470
+
471
+ def swap_to_gallery(images):
472
+ return gr.update(value=images, visible=True), gr.update(visible=True), gr.update(visible=False)
473
+
474
+ def upload_example_to_gallery(images, prompt, style, negative_prompt):
475
+ return gr.update(value=images, visible=True), gr.update(visible=True), gr.update(visible=False)
476
+
477
+ def remove_back_to_files():
478
+ return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)
479
+
480
+ def remove_tips():
481
+ return gr.update(visible=False)
482
+
483
+ def apply_style_positive(style_name: str, positive: str):
484
+ p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
485
+ return p.replace("{prompt}", positive)
486
+
487
+ def apply_style(style_name: str, positives: list, negative: str = ""):
488
+ p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
489
+ return [p.replace("{prompt}", positive) for positive in positives], n + ' ' + negative
490
+
491
+ def change_visiale_by_model_type(_model_type):
492
+ if _model_type == "Only Using Textual Description":
493
+ return gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
494
+ elif _model_type == "Using Ref Images":
495
+ return gr.update(visible=True), gr.update(visible=True), gr.update(visible=False)
496
+ else:
497
+ raise ValueError("Invalid model type",_model_type)
498
+
499
+
500
+ ######### Image Generation ##############
501
+ @spaces.GPU(duration=120)
502
+ 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):
503
+ _model_type = "Photomaker" if _model_type == "Using Ref Images" else "original"
504
+ if _model_type == "Photomaker" and "img" not in general_prompt:
505
+ raise gr.Error("Please add the triger word \" img \" behind the class word you want to customize, such as: man img or woman img")
506
+ if _upload_images is None and _model_type != "original":
507
+ raise gr.Error(f"Cannot find any input face image!")
508
+ if len(prompt_array.splitlines()) > 10:
509
+ raise gr.Error(f"No more than 10 prompts in huggface demo for Speed! But found {len(prompt_array.splitlines())} prompts!")
510
+ global sa32, sa64,id_length,total_length,attn_procs,unet,cur_model_type,device
511
+ global num_steps
512
+ global write
513
+ global cur_step,attn_count
514
+ global height,width
515
+ height = G_height
516
+ width = G_width
517
+ global pipe2,pipe4
518
+ global sd_model_path,models_dict
519
+ sd_model_path = models_dict[_sd_type]
520
+ num_steps =_num_steps
521
+ use_safe_tensor = True
522
+ if style_name == "(No style)":
523
+ sd_model_path = models_dict["RealVision"]
524
+ if _model_type == "original":
525
+ pipe = StableDiffusionXLPipeline.from_pretrained(sd_model_path, torch_dtype=torch.float16)
526
+ pipe = pipe.to(device)
527
+ pipe.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
528
+ # pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
529
+ # pipe.scheduler.set_timesteps(50)
530
+ set_attention_processor(pipe.unet,id_length_,is_ipadapter = False)
531
+ elif _model_type == "Photomaker":
532
+ if _sd_type != "RealVision" and style_name != "(No style)":
533
+ pipe = pipe2.to(device)
534
+ pipe.id_encoder.to(device)
535
+ set_attention_processor(pipe.unet,id_length_,is_ipadapter = False)
536
+ else:
537
+ pipe = pipe4.to(device)
538
+ pipe.id_encoder.to(device)
539
+ set_attention_processor(pipe.unet,id_length_,is_ipadapter = False)
540
+ else:
541
+ raise NotImplementedError("You should choice between original and Photomaker!",f"But you choice {_model_type}")
542
+ ##### ########################
543
+ pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
544
+ pipe.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
545
+ cur_model_type = _sd_type+"-"+_model_type+""+str(id_length_)
546
+ if _model_type != "original":
547
+ input_id_images = []
548
+ for img in _upload_images:
549
+ print(img)
550
+ input_id_images.append(load_image(img))
551
+ prompts = prompt_array.splitlines()
552
+ start_merge_step = int(float(_style_strength_ratio) / 100 * _num_steps)
553
+ if start_merge_step > 30:
554
+ start_merge_step = 30
555
+ print(f"start_merge_step:{start_merge_step}")
556
+ generator = torch.Generator(device="cuda").manual_seed(seed_)
557
+ sa32, sa64 = sa32_, sa64_
558
+ id_length = id_length_
559
+ clipped_prompts = prompts[:]
560
+ prompts = [general_prompt + "," + prompt if "[NC]" not in prompt else prompt.replace("[NC]","") for prompt in clipped_prompts]
561
+ prompts = [prompt.rpartition('#')[0] if "#" in prompt else prompt for prompt in prompts]
562
+ print(prompts)
563
+ id_prompts = prompts[:id_length]
564
+ real_prompts = prompts[id_length:]
565
+ torch.cuda.empty_cache()
566
+ write = True
567
+ cur_step = 0
568
+
569
+ attn_count = 0
570
+ id_prompts, negative_prompt = apply_style(style_name, id_prompts, negative_prompt)
571
+ setup_seed(seed_)
572
+ total_results = []
573
+ if _model_type == "original":
574
+ 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
575
+ elif _model_type == "Photomaker":
576
+ 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
577
+ else:
578
+ raise NotImplementedError("You should choice between original and Photomaker!",f"But you choice {_model_type}")
579
+ total_results = id_images + total_results
580
+ yield total_results
581
+ real_images = []
582
+ write = False
583
+ for real_prompt in real_prompts:
584
+ setup_seed(seed_)
585
+ cur_step = 0
586
+ real_prompt = apply_style_positive(style_name, real_prompt)
587
+ if _model_type == "original":
588
+ 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])
589
+ elif _model_type == "Photomaker":
590
+ 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])
591
+ else:
592
+ raise NotImplementedError("You should choice between original and Photomaker!",f"But you choice {_model_type}")
593
+ total_results = [real_images[-1]] + total_results
594
+ yield total_results
595
+ if _comic_type != "No typesetting (default)":
596
+ captions= prompt_array.splitlines()
597
+ captions = [caption.replace("[NC]","") for caption in captions]
598
+ captions = [caption.split('#')[-1] if "#" in caption else caption for caption in captions]
599
+ from PIL import ImageFont
600
+ total_results = get_comic(id_images + real_images, _comic_type,captions= captions,font=ImageFont.truetype("./fonts/Inkfree.ttf", int(45))) + total_results
601
+ if _model_type == "Photomaker":
602
+ pipe = pipe2.to("cpu")
603
+ pipe.id_encoder.to("cpu")
604
+ set_attention_processor(pipe.unet,id_length_,is_ipadapter = False)
605
+ yield total_results
606
+
607
+
608
+
609
+ def array2string(arr):
610
+ stringtmp = ""
611
+ for i,part in enumerate(arr):
612
+ if i != len(arr)-1:
613
+ stringtmp += part +"\n"
614
+ else:
615
+ stringtmp += part
616
+
617
+ return stringtmp
618
+
619
+
620
+ #################################################
621
+ #################################################
622
+ ### define the interface
623
  with gr.Blocks(css=css) as demo:
624
+ binary_matrixes = gr.State([])
625
+ color_layout = gr.State([])
626
+
627
+ # gr.Markdown(logo)
628
+ gr.Markdown(title)
629
+ gr.Markdown(description)
630
+
631
+ with gr.Row():
632
+ with gr.Group(elem_id="main-image"):
633
+ # button_run = gr.Button("generate id images ! 😺", elem_id="main_button", interactive=True)
634
+
635
+ prompts = []
636
+ colors = []
637
+ # with gr.Column(visible=False) as post_sketch:
638
+ # for n in range(MAX_COLORS):
639
+ # if n == 0 :
640
+ # with gr.Row(visible=False) as color_row[n]:
641
+ # colors.append(gr.Image(shape=(100, 100), label="background", type="pil", image_mode="RGB", width=100, height=100))
642
+ # prompts.append(gr.Textbox(label="Prompt for the background (white region)", value=""))
643
+ # else:
644
+ # with gr.Row(visible=False) as color_row[n]:
645
+ # colors.append(gr.Image(shape=(100, 100), label="segment "+str(n), type="pil", image_mode="RGB", width=100, height=100))
646
+ # prompts.append(gr.Textbox(label="Prompt for the segment "+str(n)))
647
+
648
+ # get_genprompt_run = gr.Button("(2) I've finished segment labeling ! 😺", elem_id="prompt_button", interactive=True)
649
+
650
+ with gr.Column(visible=True) as gen_prompt_vis:
651
+ sd_type = gr.Dropdown(choices=list(models_dict.keys()), value = "Unstable",label="sd_type", info="Select pretrained model")
652
+ 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")
653
+ with gr.Group(visible=False) as control_image_input:
654
+ files = gr.Files(
655
+ label="Drag (Select) 1 or more photos of your face",
656
+ file_types=["image"],
657
+ )
658
+ uploaded_files = gr.Gallery(label="Your images", visible=False, columns=5, rows=1, height=200)
659
+ with gr.Column(visible=False) as clear_button:
660
+ remove_and_reupload = gr.ClearButton(value="Remove and upload new ones", components=files, size="sm")
661
+ general_prompt = gr.Textbox(value='', label="(1) Textual Description for Character", interactive=True)
662
+ negative_prompt = gr.Textbox(value='', label="(2) Negative_prompt", interactive=True)
663
+ style = gr.Dropdown(label="Style template", choices=STYLE_NAMES, value=DEFAULT_STYLE_NAME)
664
+ prompt_array = gr.Textbox(lines = 3,value='', label="(3) Comic Description (each line corresponds to a frame).", interactive=True)
665
+ with gr.Accordion("(4) Tune the hyperparameters", open=True):
666
+ #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)
667
+ 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)
668
+ 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)
669
+ id_length_ = gr.Slider(label= "Number of id images in total images" , minimum=2, maximum=4, value=3, step=1)
670
+ # total_length_ = gr.Slider(label= "Number of total images", minimum=1, maximum=20, value=1, step=1)
671
+ seed_ = gr.Slider(label="Seed", minimum=-1, maximum=MAX_SEED, value=0, step=1)
672
+ num_steps = gr.Slider(
673
+ label="Number of sample steps",
674
+ minimum=25,
675
+ maximum=50,
676
+ step=1,
677
+ value=50,
678
+ )
679
+ G_height = gr.Slider(
680
+ label="height",
681
+ minimum=256,
682
+ maximum=1024,
683
+ step=32,
684
+ value=1024,
685
+ )
686
+ G_width = gr.Slider(
687
+ label="width",
688
+ minimum=256,
689
+ maximum=1024,
690
+ step=32,
691
+ value=1024,
692
+ )
693
+ comic_type = gr.Radio(["No typesetting (default)", "Four Pannel", "Classic Comic Style"], value = "Classic Comic Style", label="Typesetting Style", info="Select the typesetting style ")
694
+ guidance_scale = gr.Slider(
695
+ label="Guidance scale",
696
+ minimum=0.1,
697
+ maximum=10.0,
698
+ step=0.1,
699
+ value=5,
700
+ )
701
+ style_strength_ratio = gr.Slider(
702
+ label="Style strength of Ref Image (%)",
703
+ minimum=15,
704
+ maximum=50,
705
+ step=1,
706
+ value=20,
707
+ visible=False
708
+ )
709
+ Ip_Adapter_Strength = gr.Slider(
710
+ label="Ip_Adapter_Strength",
711
+ minimum=0,
712
+ maximum=1,
713
+ step=0.1,
714
+ value=0.5,
715
+ visible=False
716
+ )
717
+ final_run_btn = gr.Button("Generate ! 😺")
718
+
719
+
720
+ with gr.Column():
721
+ out_image = gr.Gallery(label="Result", columns=2, height='auto')
722
+ generated_information = gr.Markdown(label="Generation Details", value="",visible=False)
723
+ gr.Markdown(version)
724
+ model_type.change(fn = change_visiale_by_model_type , inputs = model_type, outputs=[control_image_input,style_strength_ratio,Ip_Adapter_Strength])
725
+ files.upload(fn=swap_to_gallery, inputs=files, outputs=[uploaded_files, clear_button, files])
726
+ remove_and_reupload.click(fn=remove_back_to_files, outputs=[uploaded_files, clear_button, files])
727
+
728
+ final_run_btn.click(fn=set_text_unfinished, outputs = generated_information
729
+ ).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
730
+ ).then(fn=set_text_finished,outputs = generated_information)
731
+
732
+
733
+ gr.Examples(
734
+ examples=[
735
+ [0,0.5,0.5,2,"a man, wearing black suit",
736
+ "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",
737
+ array2string(["at home, read new paper #at home, The newspaper says there is a treasure house in the forest.",
738
+ "on the road, near the forest",
739
+ "[NC] The car on the road, near the forest #He drives to the forest in search of treasure.",
740
+ "[NC]A tiger appeared in the forest, at night ",
741
+ "very frightened, open mouth, in the forest, at night",
742
+ "running very fast, in the forest, at night",
743
+ "[NC] A house in the forest, at night #Suddenly, he discovers the treasure house!",
744
+ "in the house filled with treasure, laughing, at night #He is overjoyed inside the house."
745
+ ]),
746
+ "Comic book","Only Using Textual Description",get_image_path_list('./examples/taylor'),768,768
747
+ ],
748
+ [0,0.5,0.5,2,"a policeman img, wearing a white shirt",
749
+ "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",
750
+ array2string(["Directing traffic on the road. ",
751
+ "walking on the streets.",
752
+ "Chasing a man on the street.",
753
+ "At the police station.",
754
+ ]),
755
+ "Japanese Anime","Using Ref Images",get_image_path_list('./examples/lecun'),768,768
756
+ ],
757
+ [1,0.5,0.5,3,"a woman img, wearing a white T-shirt, blue loose hair",
758
+ "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",
759
+ array2string(["wake up in the bed",
760
+ "have breakfast",
761
+ "is on the road, go to company",
762
+ "work in the company",
763
+ "Take a walk next to the company at noon",
764
+ "lying in bed at night"]),
765
+ "Japanese Anime", "Using Ref Images",get_image_path_list('./examples/taylor'),768,768
766
+ ],
767
+ [0,0.5,0.5,3,"a man, wearing black jacket",
768
+ "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",
769
+ array2string(["wake up in the bed",
770
+ "have breakfast",
771
+ "is on the road, go to the company, close look",
772
+ "work in the company",
773
+ "laughing happily",
774
+ "lying in bed at night"
775
+ ]),
776
+ "Japanese Anime","Only Using Textual Description",get_image_path_list('./examples/taylor'),768,768
777
+ ],
778
+ [0,0.3,0.5,3,"a girl, wearing white shirt, black skirt, black tie, yellow hair",
779
+ "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",
780
+ array2string([
781
+ "at home #at home, began to go to drawing",
782
+ "sitting alone on a park bench.",
783
+ "reading a book on a park bench.",
784
+ "[NC]A squirrel approaches, peeking over the bench. ",
785
+ "look around in the park. # She looks around and enjoys the beauty of nature.",
786
+ "[NC]leaf falls from the tree, landing on the sketchbook.",
787
+ "picks up the leaf, examining its details closely.",
788
+ "[NC]The brown squirrel appear.",
789
+ "is very happy # She is very happy to see the squirrel again",
790
+ "[NC]The brown squirrel takes the cracker and scampers up a tree. # She gives the squirrel cracker"]),
791
+ "Japanese Anime","Only Using Textual Description",get_image_path_list('./examples/taylor'),768,768
792
+ ]
793
+ ],
794
+ inputs=[seed_, sa32_, sa64_, id_length_, general_prompt, negative_prompt, prompt_array,style,model_type,files,G_height,G_width],
795
+ # outputs=[post_sketch, binary_matrixes, *color_row, *colors, *prompts, gen_prompt_vis, general_prompt, seed_],
796
+ # run_on_click=True,
797
+ label='😺 Examples 😺',
798
  )
799
+ gr.Markdown(article)
800
+
801
+ # demo.load(None, None, None, _js=load_js)
802
 
803
+ demo.launch()