File size: 32,078 Bytes
558e11c
046f233
a001281
 
 
 
 
 
 
046f233
a001281
 
 
 
046f233
a001281
 
 
 
 
 
046f233
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e4d006
 
046f233
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62ab16e
a001281
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f302f51
 
 
 
 
 
 
 
 
 
a001281
 
 
 
 
 
 
 
 
 
 
 
 
2ba04d8
 
4a91629
f404d95
 
 
667d84a
aa4fc05
 
a001281
 
 
 
3317194
 
a001281
 
3317194
 
a001281
 
0647ed2
a001281
 
0647ed2
a001281
 
 
 
0647ed2
a001281
 
0647ed2
a001281
 
 
 
10ce1a3
a001281
 
0647ed2
a001281
 
0647ed2
a001281
 
0647ed2
a001281
 
 
 
0647ed2
a001281
 
 
 
0647ed2
a001281
 
 
 
 
 
 
 
 
c1f6c50
a001281
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
558e11c
a001281
 
 
 
 
 
 
62ab16e
 
 
 
 
 
 
 
 
 
0ee6af2
62ab16e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ee6af2
62ab16e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a001281
 
 
 
 
 
 
 
 
 
046f233
 
73e3005
a001281
 
62ab16e
00a4e2b
 
 
 
 
 
 
046f233
558e11c
00a4e2b
b36ce1d
00a4e2b
558e11c
a001281
 
046f233
a001281
f302f51
046f233
 
f302f51
a001281
046f233
 
a001281
73e3005
d4ba169
046f233
a001281
 
 
 
046f233
a001281
 
 
 
 
 
 
 
 
 
046f233
a001281
046f233
 
 
 
 
a001281
 
 
 
 
 
 
 
 
 
 
046f233
a001281
 
 
 
 
046f233
 
 
 
 
62ab16e
 
 
 
 
a001281
 
 
 
 
 
 
046f233
 
 
 
 
 
9e4d006
 
046f233
 
 
 
 
 
 
 
 
 
a001281
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
558e11c
 
046f233
 
 
 
 
 
9e4d006
 
 
046f233
 
 
 
 
 
558e11c
2d9f1b0
 
 
a001281
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73e3005
 
 
a001281
 
 
 
 
 
046f233
a001281
07e3768
a001281
 
 
046f233
 
 
 
 
a001281
 
 
 
 
 
 
 
 
 
 
 
 
 
046f233
 
 
 
62ab16e
 
a001281
 
 
 
 
 
 
 
 
 
 
 
 
73e3005
a001281
046f233
 
558e11c
62ab16e
558e11c
 
 
 
 
280b08b
046f233
558e11c
 
 
046f233
 
558e11c
62ab16e
 
 
 
 
 
 
558e11c
62ab16e
558e11c
 
 
 
 
280b08b
046f233
558e11c
 
 
046f233
 
558e11c
62ab16e
 
 
 
 
 
 
9e4d006
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
558e11c
62ab16e
558e11c
 
 
 
 
280b08b
046f233
558e11c
 
 
046f233
 
558e11c
62ab16e
 
 
 
 
 
 
a001281
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
046f233
 
a001281
 
 
 
 
 
046f233
 
a001281
 
 
 
 
 
 
 
 
 
 
 
 
046f233
 
a001281
 
 
 
 
 
046f233
 
a001281
 
 
 
 
 
 
 
 
 
 
 
046f233
 
a001281
 
 
 
 
 
046f233
 
a001281
 
 
 
 
 
046f233
 
a001281
 
 
 
 
 
 
 
 
 
 
046f233
 
a001281
 
 
 
 
 
046f233
 
a001281
 
 
 
 
 
046f233
 
a001281
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
046f233
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
import copy
import json
import os
import os.path as osp
import random
from argparse import ArgumentParser
from datetime import datetime

import gradio as gr
import moviepy.editor as mpy
import numpy as np
import torch
from huggingface_hub import hf_hub_download
from omegaconf import OmegaConf
from PIL import Image, ImageDraw, ImageFont

from animatediff.pipelines import I2VPipeline
from animatediff.utils.util import RANGE_LIST, save_videos_grid

sample_idx = 0


def convert_gif_to_mp4(gif_path, mp4_path):

    clip = mpy.VideoFileClip(gif_path)
    clip.write_videofile(mp4_path)


def add_text(gif_file: str, mp4_file: str, text_index: int):
    image = Image.open(gif_file)

    frames = []
    try:
        while True:
            frames.append(image.copy().convert('RGB'))
            image.seek(len(frames))
    except EOFError:
        pass

    text = ['Earn More Money!', 'Happy New Year!',
            'Bad Luck Go Away!', 'Happy New Year!'][text_index]
    size = [36, 36, 36, 36][text_index]

    for i, frame in enumerate(frames):
        font = ImageFont.truetype('zyhzx.ttf', size=size + i * 2)
        draw = ImageDraw.Draw(frame)

        text_width, text_height = draw.textsize(text, font=font)
        image_width, image_height = image.size
        x = (image_width - text_width) // 2
        y = (image_height - text_height) - (image_height - text_height) // 8

        draw.text((x, y), text, fill='red', font=font)

    frames[0].save(gif_file, save_all=True, append_images=frames[1:], loop=0)
    mp4_file = convert_gif_to_mp4(gif_file, mp4_file)
    return gif_file, mp4_file


css = """
.toolbutton {
    margin-buttom: 0em 0em 0em 0em;
    max-width: 2.5em;
    min-width: 2.5em !important;
    height: 2.5em;
}
"""

parser = ArgumentParser()
parser.add_argument('--config', type=str, default='example/config/base.yaml')
parser.add_argument('--server-name', type=str, default='0.0.0.0')
parser.add_argument('--port', type=int, default=7860)
parser.add_argument('--share', action='store_true')
parser.add_argument('--local-debug', action='store_true')

parser.add_argument('--save-path', default='samples')

args = parser.parse_args()
LOCAL_DEBUG = args.local_debug


BASE_CONFIG = 'example/config/base.yaml'
STYLE_CONFIG_LIST = {
    '3d_cartoon': './example/openxlab/3-3d.yaml',
}


# download models
PIA_PATH = './models/PIA'
VAE_PATH = './models/VAE'
DreamBooth_LoRA_PATH = './models/DreamBooth_LoRA'


def seed_everything(seed):
    import random

    import numpy as np
    torch.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    np.random.seed(seed % (2**32))
    random.seed(seed)


if not LOCAL_DEBUG:
    CACHE_PATH = './models'

    PIA_PATH = osp.join(CACHE_PATH, 'PIA')
    VAE_PATH = osp.join(CACHE_PATH, 'VAE')
    DreamBooth_LoRA_PATH = osp.join(CACHE_PATH, 'DreamBooth_LoRA')
    STABLE_DIFFUSION_PATH = osp.join(CACHE_PATH, 'StableDiffusion')

    os.makedirs(PIA_PATH, exist_ok=True)
    os.makedirs(VAE_PATH, exist_ok=True)
    os.makedirs(DreamBooth_LoRA_PATH, exist_ok=True)
    os.makedirs(STABLE_DIFFUSION_PATH, exist_ok=True)

    PIA_PATH = hf_hub_download(repo_id='Leoxing/PIA',
                               filename='pia.ckpt', cache_dir=PIA_PATH)
    PIA_PATH = '/'.join(PIA_PATH.split('/')[:-1])
    # os.system('bash download_bashscripts/2-RcnzCartoon.sh')
    print(os.listdir(DreamBooth_LoRA_PATH))
    hf_hub_download(repo_id='Leoxing/rcnz-backup',
                    filename='rcnzCartoon3d_v20.safetensors',
                    local_dir='models/DreamBooth_LoRA',
                    local_dir_use_symlinks=False)
    print(os.listdir(DreamBooth_LoRA_PATH))

    # unet
    unet_full_path = hf_hub_download(repo_id='runwayml/stable-diffusion-v1-5',
                                     subfolder='unet', filename='diffusion_pytorch_model.bin',
                                     cache_dir='models/StableDiffusion')
    STABLE_DIFFUSION_PATH = '/'.join(unet_full_path.split('/')[:-2])
    hf_hub_download(repo_id='runwayml/stable-diffusion-v1-5',
                    subfolder='unet', filename='config.json',
                    cache_dir='models/StableDiffusion')

    # vae
    hf_hub_download(repo_id='runwayml/stable-diffusion-v1-5',
                    subfolder='vae', filename='config.json',
                    cache_dir='models/StableDiffusion')
    hf_hub_download(repo_id='runwayml/stable-diffusion-v1-5',
                    subfolder='vae', filename='diffusion_pytorch_model.bin',
                    cache_dir='models/StableDiffusion')

    # text encoder
    hf_hub_download(repo_id='runwayml/stable-diffusion-v1-5',
                    subfolder='text_encoder', filename='config.json',
                    cache_dir='models/StableDiffusion')
    hf_hub_download(repo_id='runwayml/stable-diffusion-v1-5',
                    subfolder='text_encoder', filename='pytorch_model.bin',
                    cache_dir='models/StableDiffusion')

    # tokenizer
    hf_hub_download(repo_id='runwayml/stable-diffusion-v1-5',
                    subfolder='tokenizer', filename='merges.txt',
                    cache_dir='models/StableDiffusion')
    hf_hub_download(repo_id='runwayml/stable-diffusion-v1-5',
                    subfolder='tokenizer', filename='special_tokens_map.json',
                    cache_dir='models/StableDiffusion')
    hf_hub_download(repo_id='runwayml/stable-diffusion-v1-5',
                    subfolder='tokenizer', filename='tokenizer_config.json',
                    cache_dir='models/StableDiffusion')
    hf_hub_download(repo_id='runwayml/stable-diffusion-v1-5',
                    subfolder='tokenizer', filename='vocab.json',
                    cache_dir='models/StableDiffusion')

    # scheduler
    hf_hub_download(repo_id='runwayml/stable-diffusion-v1-5',
                    subfolder='scheduler', filename='scheduler_config.json',
                    cache_dir='models/StableDiffusion')

    # model index
    hf_hub_download(repo_id='runwayml/stable-diffusion-v1-5', filename='model_index.json',
                    cache_dir='models/StableDiffusion')

else:
    PIA_PATH = './models/PIA'
    VAE_PATH = './models/VAE'
    DreamBooth_LoRA_PATH = './models/DreamBooth_LoRA'
    STABLE_DIFFUSION_PATH = './models/StableDiffusion/sd15'


def preprocess_img(img_np, max_size: int = 1024):

    ori_image = Image.fromarray(img_np).convert('RGB')

    width, height = ori_image.size

    short_edge = max(width, height)
    if short_edge > max_size:
        scale_factor = max_size / short_edge
    else:
        scale_factor = 1
    width = int(width * scale_factor)
    height = int(height * scale_factor)
    ori_image = ori_image.resize((width, height))

    if (width % 8 != 0) or (height % 8 != 0):
        in_width = (width // 8) * 8
        in_height = (height // 8) * 8
    else:
        in_width = width
        in_height = height
        in_image = ori_image

    in_image = ori_image.resize((in_width, in_height))
    in_image_np = np.array(in_image)
    return in_image_np, in_height, in_width


class AnimateController:
    def __init__(self):

        # config dirs
        self.basedir = os.getcwd()
        self.savedir = os.path.join(
            self.basedir, args.save_path, datetime.now().strftime("Gradio-%Y-%m-%dT%H-%M-%S"))
        self.savedir_sample = os.path.join(self.savedir, "sample")
        os.makedirs(self.savedir, exist_ok=True)

        self.inference_config = OmegaConf.load(args.config)
        self.style_configs = {k: OmegaConf.load(
            v) for k, v in STYLE_CONFIG_LIST.items()}

        self.pipeline_dict = self.load_model_list()

    def load_model_list(self):
        pipeline_dict = dict()
        for style, cfg in self.style_configs.items():
            dreambooth_path = cfg.get('dreambooth', 'none')
            if dreambooth_path and dreambooth_path.upper() != 'NONE':
                dreambooth_path = osp.join(
                    DreamBooth_LoRA_PATH, dreambooth_path)
            lora_path = cfg.get('lora', None)
            if lora_path is not None:
                lora_path = osp.join(DreamBooth_LoRA_PATH, lora_path)
            lora_alpha = cfg.get('lora_alpha', 0.0)
            vae_path = cfg.get('vae', None)
            if vae_path is not None:
                vae_path = osp.join(VAE_PATH, vae_path)

            pipeline_dict[style] = I2VPipeline.build_pipeline(
                self.inference_config,
                STABLE_DIFFUSION_PATH,
                unet_path=osp.join(PIA_PATH, 'pia.ckpt'),
                dreambooth_path=dreambooth_path,
                lora_path=lora_path,
                lora_alpha=lora_alpha,
                vae_path=vae_path,
                ip_adapter_path='h94/IP-Adapter',
                ip_adapter_scale=0.1)
        return pipeline_dict

    def fetch_default_n_prompt(self, style: str):
        cfg = self.style_configs[style]
        n_prompt = cfg.get('n_prompt', '')
        ip_adapter_scale = cfg.get('ip_adapter_scale', 0)

        gr.Info('Set default negative prompt and ip_adapter_scale.')
        print('Set default negative prompt and ip_adapter_scale.')

        return n_prompt, ip_adapter_scale

    def animate(
        self,
        init_img,
        motion_scale,
        prompt_textbox,
        negative_prompt_textbox,
        sample_step_slider,
        cfg_scale_slider,
        seed_textbox,
        ip_adapter_scale,
        style,
        max_size=512,
        progress=gr.Progress(),
    ):

        global sample_idx

        if init_img is None:
            gr.Warning('Please upload image or use example images.')

        if seed_textbox != -1 and seed_textbox != "":
            torch.manual_seed(int(seed_textbox))
            seed = int(seed_textbox)
        else:
            seed = torch.initial_seed()
        generator = torch.Generator(device='cuda')
        generator.manual_seed(seed)
        seed_everything(seed)

        print(f'Seed: {seed}')

        pipeline = self.pipeline_dict[style]
        init_img, h, w = preprocess_img(init_img, max_size)
        print(f'img size: {h, w}')

        sample = pipeline(
            image=init_img,
            prompt=prompt_textbox,
            negative_prompt=negative_prompt_textbox,
            generator=generator,
            num_inference_steps=sample_step_slider,
            guidance_scale=cfg_scale_slider,
            width=w,
            height=h,
            video_length=16,
            mask_sim_template_idx=motion_scale - 1,
            ip_adapter_scale=ip_adapter_scale,
            progress_fn=progress,
        ).videos

        save_sample_path_mp4 = os.path.join(
            self.savedir_sample, f"{sample_idx}.mp4")
        save_sample_path_gif = os.path.join(
            self.savedir_sample, f"{sample_idx}.gif")

        save_videos_grid(sample, save_sample_path_mp4)
        save_videos_grid(sample, save_sample_path_gif)

        sample_config = {
            "prompt": prompt_textbox,
            "n_prompt": negative_prompt_textbox,
            "num_inference_steps": sample_step_slider,
            "guidance_scale": cfg_scale_slider,
            "width": w,
            "height": h,
            "seed": seed,
            "motion": motion_scale,
        }
        print(sample_config)
        json_str = json.dumps(sample_config, indent=4)
        with open(os.path.join(self.savedir, "logs.json"), "a") as f:
            f.write(json_str)
            f.write("\n\n")

        sample_idx += 1
        return (save_sample_path_mp4,
                [save_sample_path_mp4, save_sample_path_gif])

    def animate_example(
        self,
        init_img,
        motion_scale,
        prompt_textbox,
        negative_prompt_textbox,
        sample_step_slider,
        cfg_scale_slider,
        seed_textbox,
        ip_adapter_scale,
        style,
        with_text=False,
        text_idx=0,
        max_size=512,
        progress=gr.Progress(),

    ):
        print('init img', init_img)
        print('motion', motion_scale)
        print('prompt', prompt_textbox)
        print('sample step', sample_step_slider)
        print('ip-adapter', ip_adapter_scale)
        print('seed', seed_textbox)

        global sample_idx
        if init_img is None:
            print('Fetch example!!!!!!!!!!!')
            init_img = np.array(Image.open('__assets__/image_animation/zhening/zhening.jpeg'))
            gr.Info('Use example image for quick run.')

        if seed_textbox != -1 and seed_textbox != "":
            torch.manual_seed(int(seed_textbox))
            seed = int(seed_textbox)
        else:
            seed = torch.initial_seed()
        generator = torch.Generator(device='cuda')
        generator.manual_seed(seed)
        seed_everything(seed)

        print(f'Seed: {seed}')

        pipeline = self.pipeline_dict[style]
        init_img, h, w = preprocess_img(init_img, max_size)
        print(f'img size: {h, w}')

        sample = pipeline(
            image=init_img,
            prompt=prompt_textbox,
            negative_prompt=negative_prompt_textbox,
            generator=generator,
            num_inference_steps=sample_step_slider,
            guidance_scale=cfg_scale_slider,
            width=w,
            height=h,
            video_length=16,
            mask_sim_template_idx=motion_scale - 1,
            ip_adapter_scale=ip_adapter_scale,
            progress_fn=progress,
        ).videos

        save_sample_path_mp4 = os.path.join(
            self.savedir_sample, f"{sample_idx}.mp4")
        save_sample_path_gif = os.path.join(
            self.savedir_sample, f"{sample_idx}.gif")

        save_videos_grid(sample, save_sample_path_mp4)
        save_videos_grid(sample, save_sample_path_gif)

        sample_config = {
            "prompt": prompt_textbox,
            "n_prompt": negative_prompt_textbox,
            "num_inference_steps": sample_step_slider,
            "guidance_scale": cfg_scale_slider,
            "width": w,
            "height": h,
            "seed": seed,
            "motion": motion_scale,
        }
        print(sample_config)
        json_str = json.dumps(sample_config, indent=4)
        with open(os.path.join(self.savedir, "logs.json"), "a") as f:
            f.write(json_str)
            f.write("\n\n")

        if with_text:
            add_text(save_sample_path_gif, save_sample_path_mp4, text_idx)

        sample_idx += 1
        return (save_sample_path_mp4,
                [save_sample_path_mp4, save_sample_path_gif],
                seed,
                motion_scale,
                cfg_scale_slider,
                )


controller = AnimateController()


def ui():
    with gr.Blocks(css=css) as demo:
        # build state for default buttons
        default_motion = gr.State(value=1)
        default_prompt1 = gr.State(
            value='lift a red envelope, Chinese new year')
        default_prompt2 = gr.State(
            value='smiling, Chinese costume, Chinese new year')
        default_prompt3 = gr.State(
            value='angry, Chinese costume, Chinese new year')
        default_prompt4 = gr.State(value='sparklers, Chinese new year')
        default_n_prompt = gr.State(value='wrong white balance, dark, sketches,worst quality,low quality, deformed, distorted, disfigured, bad eyes, wrong lips,weird mouth, bad teeth, mutated hands and fingers, bad anatomy,wrong anatomy, amputation, extra limb, missing limb, floating,limbs, disconnected limbs, mutation, ugly, disgusting, bad_pictures, negative_hand-neg')
        default_seed = gr.State(10201304011203481448)
        default_ip_adapter_scale = gr.State(0.2)
        default_style = gr.State('3d_cartoon')
        default_cfg = gr.State(7.5)
        default_1_idx = gr.State(0)
        default_2_idx = gr.State(1)
        default_3_idx = gr.State(2)
        default_4_idx = gr.State(3)

        gr.HTML(
            "<div align='center'><font size='7'> <img src=\"file/pia.png\" style=\"height: 72px;\"/ > Your Personalized Image Animator</font></div>"
            "<div align='center'><font size='7'>via Plug-and-Play Modules in Text-to-Image Models </font></div>"
        )
        with gr.Row():
            gr.Markdown(
                "<div align='center'><font size='5'><a href='https://pi-animator.github.io/'>Project Page</a> &ensp;"  # noqa
                "<a href='https://arxiv.org/abs/2312.13964/'>Paper</a> &ensp;"
                "<a href='https://github.com/open-mmlab/PIA'>Code</a> &ensp;"  # noqa
                "Try More Style: <a href='https://openxlab.org.cn/apps/detail/zhangyiming/PiaPia-AnimationStyle'>Click here! </a></font></div>"  # noqa
            )

        with gr.Row(equal_height=False):
            with gr.Column():
                with gr.Row():
                    init_img = gr.Image(label='Input Image')

                gr.Markdown('## Fast Try!')
                with gr.Row():
                    with gr.Column(scale=1, min_width=50):
                        default_1 = gr.Button(
                            '🧧', variant='primary', size='sm')
                    with gr.Column(scale=1, min_width=50):
                        default_2 = gr.Button(
                            '🤗', variant='primary', size='sm')
                    with gr.Column(scale=1, min_width=50):
                        default_3 = gr.Button(
                            '😡', variant='primary', size='sm')
                    with gr.Column(scale=1, min_width=50):
                        default_4 = gr.Button(
                            '🧨', variant='primary', size='sm')

                    with gr.Column(scale=1.5, min_width=150):
                        with_wishes = gr.Checkbox(label='With Wishes✨')

                # style_dropdown = gr.Dropdown(label='Style', choices=list(
                #     STYLE_CONFIG_LIST.keys()), value=list(STYLE_CONFIG_LIST.keys())[0])
                style_dropdown = gr.State('3d_cartoon')

                with gr.Row():
                    prompt_textbox = gr.Textbox(label="Prompt", lines=1)
                    gift_button = gr.Button(
                        value='🎁', elem_classes='toolbutton'
                    )

                def append_gift(prompt):
                    rand = random.randint(0, 2)
                    if rand == 1:
                        prompt = prompt + 'wearing santa hats'
                    elif rand == 2:
                        prompt = prompt + 'lift a Christmas gift'
                    else:
                        prompt = prompt + 'in Christmas suit, lift a Christmas gift'
                    gr.Info('Merry Christmas! Add magic to your prompt!')
                    return prompt

                gift_button.click(
                    fn=append_gift,
                    inputs=[prompt_textbox],
                    outputs=[prompt_textbox],
                )

                motion_scale_silder = gr.Slider(
                    label='Motion Scale (Larger value means larger motion but less identity consistency)',
                    value=1, step=1, minimum=1, maximum=len(RANGE_LIST))
                max_size_silder = gr.Slider(
                    label='Max size (The long edge of the input image will be resized to this value, larger value means slower inference speed)',
                    value=512, step=64, minimum=512, maximum=1024)

                with gr.Accordion('Advance Options', open=False):
                    negative_prompt_textbox = gr.Textbox(
                        value=controller.fetch_default_n_prompt(
                            list(STYLE_CONFIG_LIST.keys())[0])[0],
                        label="Negative prompt", lines=2)

                    sample_step_slider = gr.Slider(
                        label="Sampling steps", value=25, minimum=10, maximum=100, step=1)

                    cfg_scale_slider = gr.Slider(
                        label="CFG Scale", value=7.5, minimum=0, maximum=20)
                    ip_adapter_scale = gr.Slider(
                        label='IP-Apdater Scale',
                        value=controller.fetch_default_n_prompt(
                            list(STYLE_CONFIG_LIST.keys())[0])[1],
                        minimum=0, maximum=1)

                    with gr.Row():
                        seed_textbox = gr.Textbox(label="Seed", value=-1)
                        seed_button = gr.Button(
                            value="\U0001F3B2", elem_classes="toolbutton")
                    seed_button.click(
                        fn=lambda x: random.randint(1, 1e8),
                        outputs=[seed_textbox],
                        queue=False
                    )

                generate_button = gr.Button(
                    value="Generate", variant='primary')

            with gr.Column():
                result_video = gr.Video(
                    label="Generated Animation", interactive=False)
                with gr.Row():
                    download = gr.Files(
                        file_types=['gif', 'mp4'], label='Donwload Output')

        generate_button.click(
            fn=controller.animate,
            inputs=[
                init_img,
                motion_scale_silder,
                prompt_textbox,
                negative_prompt_textbox,
                sample_step_slider,
                cfg_scale_slider,
                seed_textbox,
                ip_adapter_scale,
                style_dropdown,
                max_size_silder,
            ],
            outputs=[result_video, download])

        default_1.click(
            fn=controller.animate_example,
            inputs=[
                init_img,
                default_motion,
                default_prompt1,
                default_n_prompt,
                sample_step_slider,
                default_cfg,
                default_seed,
                default_ip_adapter_scale,
                default_style,
                with_wishes,
                default_1_idx,
            ],
            outputs=[
                result_video,
                download,
                default_seed,
                default_motion,
                default_cfg,
            ])
        default_2.click(
            fn=controller.animate_example,
            inputs=[
                init_img,
                default_motion,
                default_prompt2,
                default_n_prompt,
                sample_step_slider,
                default_cfg,
                default_seed,
                default_ip_adapter_scale,
                default_style,
                with_wishes,
                default_2_idx,
            ],
            outputs=[
                result_video,
                download,
                default_seed,
                default_motion,
                default_cfg,
            ])
        default_3.click(
            fn=controller.animate_example,
            inputs=[
                init_img,
                default_motion,
                default_prompt3,
                default_n_prompt,
                sample_step_slider,
                default_cfg,
                default_seed,
                default_ip_adapter_scale,
                default_style,
                with_wishes,
                default_3_idx,
            ],
            outputs=[
                result_video,
                download,
                default_seed,
                default_motion,
                default_cfg,
            ])
        default_4.click(
            fn=controller.animate_example,
            inputs=[
                init_img,
                default_motion,
                default_prompt4,
                default_n_prompt,
                sample_step_slider,
                default_cfg,
                default_seed,
                default_ip_adapter_scale,
                default_style,
                with_wishes,
                default_4_idx,
            ],
            outputs=[
                result_video,
                download,
                default_seed,
                default_motion,
                default_cfg,
            ])

        def create_example(input_list):
            return gr.Examples(
                examples=input_list,
                inputs=[
                    init_img,
                    result_video,
                    prompt_textbox,
                    negative_prompt_textbox,
                    style_dropdown,
                    motion_scale_silder,
                ],
            )

        gr.Markdown(
            '### Merry Christmas!'
        )
        create_example(
            [
                [
                    '__assets__/image_animation/yiming/yiming.jpeg',
                    '__assets__/image_animation/yiming/yiming.mp4',
                    '1boy in Christmas suit, lift a Christmas gift',
                    'wrong white balance, dark, sketches,worst quality,low quality, deformed, distorted, disfigured, bad eyes, wrong lips,weird mouth, bad teeth, mutated hands and fingers, bad anatomy,wrong anatomy, amputation, extra limb, missing limb, floating,limbs, disconnected limbs, mutation, ugly, disgusting, bad_pictures, negative_hand-neg',
                    '3d_cartoon',
                    2,
                ],
                [
                    '__assets__/image_animation/yanhong/yanhong.png',
                    '__assets__/image_animation/yanhong/yanhong.mp4',
                    '1girl lift a Christmas gift',
                    'wrong white balance, dark, sketches,worst quality,low quality, deformed, distorted, disfigured, bad eyes, wrong lips,weird mouth, bad teeth, mutated hands and fingers, bad anatomy,wrong anatomy, amputation, extra limb, missing limb, floating,limbs, disconnected limbs, mutation, ugly, disgusting, bad_pictures, negative_hand-neg',
                    '3d_cartoon',
                    2,
                ],
            ],

        )

        with gr.Accordion('More Examples for Style Transfer', open=False):
            create_example([
                [

                    '__assets__/image_animation/style_transfer/anya/anya.jpg',
                    '__assets__/image_animation/style_transfer/anya/2.mp4',
                    '1girl open mouth ',
                    'wrong white balance, dark, sketches,worst quality,low quality, deformed, distorted, disfigured, bad eyes, wrong lips,weird mouth, bad teeth, mutated hands and fingers, bad anatomy,wrong anatomy, amputation, extra limb, missing limb, floating,limbs, disconnected limbs, mutation, ugly, disgusting, bad_pictures, negative_hand-neg',
                    '3d_cartoon',
                    3,
                ],
                [
                    '__assets__/image_animation/magnitude/genshin/genshin.jpg',
                    '__assets__/image_animation/magnitude/genshin/3.mp4',
                    'cherry blossoms in the wind, raidenshogundef, yaemikodef, best quality, 4k',
                    'wrong white balance, dark, sketches,worst quality,low quality, deformed, distorted, disfigured, bad eyes, wrong lips,weird mouth, bad teeth, mutated hands and fingers, bad anatomy,wrong anatomy, amputation, extra limb, missing limb, floating,limbs, disconnected limbs, mutation, ugly, disgusting, bad_pictures, negative_hand-neg',
                    '3d_cartoon',
                    3,
                ],

            ])

        with gr.Accordion('More Examples for Prompt Changing', open=False):
            create_example(
                [
                    [
                        '__assets__/image_animation/rcnz/harry.png',
                        '__assets__/image_animation/rcnz/1.mp4',
                        '1boy smiling',
                        'wrong white balance, dark, sketches,worst quality,low quality, deformed, distorted, disfigured, bad eyes, wrong lips,weird mouth, bad teeth, mutated hands and fingers, bad anatomy,wrong anatomy, amputation, extra limb, missing limb, floating,limbs, disconnected limbs, mutation, ugly, disgusting, bad_pictures, negative_hand-neg',
                        '3d_cartoon',
                        2
                    ],
                    [
                        '__assets__/image_animation/rcnz/harry.png',
                        '__assets__/image_animation/rcnz/2.mp4',
                        '1boy playing magic fire',
                        'wrong white balance, dark, sketches,worst quality,low quality, deformed, distorted, disfigured, bad eyes, wrong lips,weird mouth, bad teeth, mutated hands and fingers, bad anatomy,wrong anatomy, amputation, extra limb, missing limb, floating,limbs, disconnected limbs, mutation, ugly, disgusting, bad_pictures, negative_hand-neg',
                        '3d_cartoon',
                        2
                    ],
                    [
                        '__assets__/image_animation/rcnz/harry.png',
                        '__assets__/image_animation/rcnz/3.mp4',
                        '1boy is waving hands',
                        'wrong white balance, dark, sketches,worst quality,low quality, deformed, distorted, disfigured, bad eyes, wrong lips,weird mouth, bad teeth, mutated hands and fingers, bad anatomy,wrong anatomy, amputation, extra limb, missing limb, floating,limbs, disconnected limbs, mutation, ugly, disgusting, bad_pictures, negative_hand-neg',
                        '3d_cartoon',
                        2
                    ]
                ])

            with gr.Accordion('Examples for Motion Magnitude', open=False):
                create_example(
                    [
                        [
                            '__assets__/image_animation/magnitude/labrador.png',
                            '__assets__/image_animation/magnitude/1.mp4',
                            'cherry blossoms in the wind, raidenshogundef, yaemikodef, best quality, 4k',
                            'wrong white balance, dark, sketches,worst quality,low quality, deformed, distorted, disfigured, bad eyes, wrong lips,weird mouth, bad teeth, mutated hands and fingers, bad anatomy,wrong anatomy, amputation, extra limb, missing limb, floating,limbs, disconnected limbs, mutation, ugly, disgusting, bad_pictures, negative_hand-neg',
                            '3d_cartoon',
                            1,
                        ],
                        [
                            '__assets__/image_animation/magnitude/labrador.png',
                            '__assets__/image_animation/magnitude/2.mp4',
                            'cherry blossoms in the wind, raidenshogundef, yaemikodef, best quality, 4k',
                            'wrong white balance, dark, sketches,worst quality,low quality, deformed, distorted, disfigured, bad eyes, wrong lips,weird mouth, bad teeth, mutated hands and fingers, bad anatomy,wrong anatomy, amputation, extra limb, missing limb, floating,limbs, disconnected limbs, mutation, ugly, disgusting, bad_pictures, negative_hand-neg',
                            '3d_cartoon',
                            2,
                        ],
                        [
                            '__assets__/image_animation/magnitude/labrador.png',
                            '__assets__/image_animation/magnitude/3.mp4',
                            'cherry blossoms in the wind, raidenshogundef, yaemikodef, best quality, 4k',
                            'wrong white balance, dark, sketches,worst quality,low quality, deformed, distorted, disfigured, bad eyes, wrong lips,weird mouth, bad teeth, mutated hands and fingers, bad anatomy,wrong anatomy, amputation, extra limb, missing limb, floating,limbs, disconnected limbs, mutation, ugly, disgusting, bad_pictures, negative_hand-neg',
                            '3d_cartoon',
                            3,
                        ]
                    ])

    return demo


if __name__ == "__main__":
    demo = ui()
    demo.queue(max_size=10)
    demo.launch(server_name=args.server_name,
                server_port=args.port, share=args.share,
                max_threads=40,
                allowed_paths=['pia.png', 'samples'])