File size: 19,806 Bytes
5c4e8c1
97256ff
f70898c
ad19934
5c4e8c1
4d6f2bc
 
d179c4c
 
 
 
 
 
 
 
 
aafe7f2
97256ff
ad19934
b7c0c19
97256ff
ad19934
b7c0c19
 
 
 
 
97256ff
 
ad19934
97256ff
 
 
 
 
5d1fc69
 
 
 
 
 
 
 
4d6f2bc
61ad3d2
 
60849d7
eb8fc69
60849d7
eb8fc69
60849d7
61ad3d2
 
 
 
 
 
 
 
39a6792
61ad3d2
 
 
60849d7
 
 
39a6792
61ad3d2
60849d7
 
fd9e8de
 
39a6792
eb8fc69
 
 
 
 
60849d7
 
39a6792
 
 
 
 
 
1e250ff
7736f5f
4d6f2bc
 
 
 
 
fd9e8de
 
 
 
 
 
 
 
dffd0bb
1e250ff
 
 
a8ad716
 
fd9e8de
a8ad716
1e250ff
 
a8ad716
dffd0bb
1a31768
dffd0bb
4d6f2bc
 
 
48c31e7
710fb68
 
4d6f2bc
 
48c31e7
4d6f2bc
 
 
 
 
48c31e7
4d6f2bc
23f4f95
 
4d6f2bc
b7fd57e
4d6f2bc
 
48c31e7
 
4d6f2bc
 
fd9e8de
 
 
 
48c31e7
b7fd57e
b70fffe
 
 
4d6f2bc
b70fffe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d6f2bc
23f4f95
b70fffe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97256ff
b70fffe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05246f1
b70fffe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d6f2bc
b70fffe
 
 
 
 
 
 
 
23f4f95
b70fffe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48c31e7
b70fffe
 
 
 
 
6ac2c39
b70fffe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd9e8de
b70fffe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61ad3d2
b70fffe
 
 
 
 
 
 
 
 
 
 
 
 
 
61ad3d2
 
 
b70fffe
61ad3d2
b70fffe
 
 
 
 
 
 
 
 
 
fd9e8de
b70fffe
 
 
 
 
 
61ad3d2
 
b70fffe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7c0c19
b70fffe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7c0c19
5d1fc69
ad19934
5d1fc69
97256ff
5d1fc69
4d6f2bc
5c4e8c1
61ad3d2
5c4e8c1
fd9e8de
5d1fc69
 
 
 
 
 
 
 
 
 
 
61ad3d2
60849d7
 
fd9e8de
61ad3d2
60849d7
 
 
 
 
 
 
 
 
 
61ad3d2
 
fd9e8de
 
61ad3d2
 
60849d7
 
 
 
 
 
 
 
fd9e8de
61ad3d2
 
 
 
 
60849d7
5d1fc69
 
 
 
 
 
 
5c4e8c1
 
fd9e8de
 
 
 
 
 
 
 
 
dffd0bb
 
ad19934
5d1fc69
4d6f2bc
 
 
 
60849d7
fd9e8de
61ad3d2
f70898c
 
 
 
23f4f95
97256ff
4d6f2bc
 
 
48c31e7
 
4d6f2bc
 
60849d7
9edebae
 
4d6f2bc
48c31e7
 
c348e53
48c31e7
fd9e8de
 
4d6f2bc
 
 
5c4e8c1
 
 
 
 
 
d179c4c
f70898c
65d64be
507ffa3
f70898c
 
 
 
 
 
 
 
 
 
5c4e8c1
b70fffe
5c4e8c1
 
 
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
import argparse
import json
import os
import random

import gradio as gr

from lib import (
    Config,
    async_call,
    disable_progress_bars,
    download_civit_file,
    download_repo_files,
    generate,
    read_file,
)

# the CSS `content` attribute expects a string so we need to wrap the number in quotes
refresh_seed_js = """
() => {
    const n = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
    const button = document.getElementById("refresh");
    button.style.setProperty("--seed", `"${n}"`);
    return n;
}
"""

seed_js = """
(seed) => {
    const button = document.getElementById("refresh");
    button.style.setProperty("--seed", `"${seed}"`);
    return seed;
}
"""

aspect_ratio_js = """
(ar, w, h) => {
    if (!ar) return [w, h];
    const [width, height] = ar.split(",");
    return [parseInt(width), parseInt(height)];
}
"""


def create_image_dropdown(images, locked=False):
    if locked:
        return gr.Dropdown(
            choices=[("๐Ÿ”’", -2)],
            interactive=False,
            value=-2,
        )
    else:
        return gr.Dropdown(
            choices=[("None", -1)] + [(str(i + 1), i) for i, _ in enumerate(images or [])],
            interactive=True,
            value=-1,
        )


async def gallery_fn(images, image, ip_image):
    return (
        create_image_dropdown(images, locked=image is not None),
        create_image_dropdown(images, locked=ip_image is not None),
    )


async def image_prompt_fn(images):
    return create_image_dropdown(images)


# handle selecting an image from the gallery
# -2 is the lock icon, -1 is None
async def image_select_fn(images, image, i):
    if i == -2:
        return gr.Image(image)
    if i == -1:
        return gr.Image(None)
    return gr.Image(images[i][0]) if i > -1 else None


async def random_fn():
    prompts = read_file("data/prompts.json")
    prompts = json.loads(prompts)
    return gr.Textbox(value=random.choice(prompts))


async def generate_fn(*args, progress=gr.Progress(track_tqdm=True)):
    if len(args) > 0:
        prompt = args[0]
    else:
        prompt = None
    if prompt is None or prompt.strip() == "":
        raise gr.Error("You must enter a prompt")

    DISABLE_IMAGE_PROMPT, DISABLE_IP_IMAGE_PROMPT = args[-2:]
    gen_args = list(args[:-2])
    if DISABLE_IMAGE_PROMPT:
        gen_args[2] = None
    if DISABLE_IP_IMAGE_PROMPT:
        gen_args[3] = None

    try:
        if Config.ZERO_GPU:
            progress((0, 100), desc="ZeroGPU init")

        images = await async_call(
            generate,
            *gen_args,
            Error=gr.Error,
            Info=gr.Info,
            progress=progress,
        )
    except RuntimeError:
        raise gr.Error("Error: Please try again")
    return images


with gr.Blocks(
    head=read_file("./partials/head.html"),
    css="./app.css",
    js="./app.js",
    theme=gr.themes.Default(
        # colors
        neutral_hue=gr.themes.colors.gray,
        primary_hue=gr.themes.colors.orange,
        secondary_hue=gr.themes.colors.blue,
        # sizing
        text_size=gr.themes.sizes.text_md,
        radius_size=gr.themes.sizes.radius_sm,
        spacing_size=gr.themes.sizes.spacing_md,
        # fonts
        font=[gr.themes.GoogleFont("Inter"), *Config.SANS_FONTS],
        font_mono=[gr.themes.GoogleFont("Ubuntu Mono"), *Config.MONO_FONTS],
    ).set(
        layout_gap="8px",
        block_shadow="0 0 #0000",
        block_shadow_dark="0 0 #0000",
        block_background_fill=gr.themes.colors.gray.c50,
        block_background_fill_dark=gr.themes.colors.gray.c900,
    ),
) as demo:
    # override image inputs without clearing them
    DISABLE_IMAGE_PROMPT = gr.State(False)
    DISABLE_IP_IMAGE_PROMPT = gr.State(False)

    gr.HTML(read_file("./partials/intro.html"))

    with gr.Tabs():
        with gr.TabItem("๐Ÿ  Text"):
            with gr.Column():
                with gr.Group():
                    output_images = gr.Gallery(
                        elem_classes=["gallery"],
                        show_share_button=False,
                        object_fit="cover",
                        interactive=False,
                        show_label=False,
                        label="Output",
                        format="png",
                        columns=2,
                    )
                    prompt = gr.Textbox(
                        placeholder="What do you want to see?",
                        autoscroll=False,
                        show_label=False,
                        label="Prompt",
                        max_lines=3,
                        lines=3,
                    )

                # Buttons
                with gr.Row():
                    generate_btn = gr.Button("Generate", variant="primary")
                    random_btn = gr.Button(
                        elem_classes=["icon-button", "popover"],
                        variant="secondary",
                        elem_id="random",
                        min_width=0,
                        value="๐ŸŽฒ",
                    )
                    refresh_btn = gr.Button(
                        elem_classes=["icon-button", "popover"],
                        variant="secondary",
                        elem_id="refresh",
                        min_width=0,
                        value="๐Ÿ”„",
                    )
                    clear_btn = gr.ClearButton(
                        elem_classes=["icon-button", "popover"],
                        components=[output_images],
                        variant="secondary",
                        elem_id="clear",
                        min_width=0,
                        value="๐Ÿ—‘๏ธ",
                    )

        # img2img tab
        with gr.TabItem("๐Ÿ–ผ๏ธ Image"):
            with gr.Group():
                with gr.Row():
                    image_prompt = gr.Image(
                        show_share_button=False,
                        label="Initial Image",
                        min_width=320,
                        format="png",
                        type="pil",
                    )
                    ip_image_prompt = gr.Image(
                        show_share_button=False,
                        label="IP-Adapter Image",
                        min_width=320,
                        format="png",
                        type="pil",
                    )

                with gr.Row():
                    image_select = gr.Dropdown(
                        info="Use an initial image from the gallery",
                        choices=[("None", -1)],
                        label="Gallery Image",
                        interactive=True,
                        filterable=False,
                        value=-1,
                    )
                    ip_image_select = gr.Dropdown(
                        info="Use an IP-Adapter image from the gallery",
                        label="Gallery Image (IP-Adapter)",
                        choices=[("None", -1)],
                        interactive=True,
                        filterable=False,
                        value=-1,
                    )

                with gr.Row():
                    denoising_strength = gr.Slider(
                        value=Config.DENOISING_STRENGTH,
                        label="Denoising Strength",
                        minimum=0.0,
                        maximum=1.0,
                        step=0.1,
                    )

                with gr.Row():
                    disable_image = gr.Checkbox(
                        elem_classes=["checkbox"],
                        label="Disable Initial Image",
                        value=False,
                    )
                    disable_ip_image = gr.Checkbox(
                        elem_classes=["checkbox"],
                        label="Disable IP-Adapter Image",
                        value=False,
                    )
                    ip_face = gr.Checkbox(
                        elem_classes=["checkbox"],
                        label="Use IP-Adapter Face",
                        value=False,
                    )

        # img2img tab
        with gr.TabItem("๐ŸŽฎ Control"):
            gr.Markdown(
                "[ControlNet](https://github.com/lllyasviel/ControlNet) with [preprocessors](https://github.com/huggingface/controlnet_aux) coming soon!"
            )

        with gr.TabItem("โš™๏ธ Menu"):
            with gr.Group():
                negative_prompt = gr.Textbox(
                    value="nsfw+",
                    label="Negative Prompt",
                    lines=2,
                )

                with gr.Row():
                    model = gr.Dropdown(
                        choices=Config.MODELS,
                        filterable=False,
                        value=Config.MODEL,
                        label="Model",
                        min_width=240,
                    )
                    scheduler = gr.Dropdown(
                        choices=Config.SCHEDULERS.keys(),
                        value=Config.SCHEDULER,
                        elem_id="scheduler",
                        label="Scheduler",
                        filterable=False,
                    )

                with gr.Row():
                    styles = json.loads(read_file("data/styles.json"))
                    style_ids = list(styles.keys())
                    style_ids = [sid for sid in style_ids if not sid.startswith("_")]
                    style = gr.Dropdown(
                        value=Config.STYLE,
                        label="Style",
                        min_width=240,
                        choices=[("None", "none")]
                        + [(styles[sid]["name"], sid) for sid in style_ids],
                    )
                    embeddings = gr.Dropdown(
                        elem_id="embeddings",
                        label="Embeddings",
                        choices=[(f"<{e}>", e) for e in Config.EMBEDDINGS],
                        multiselect=True,
                        value=[Config.EMBEDDING],
                        min_width=240,
                    )

                with gr.Row():
                    with gr.Group(elem_classes=["gap-0"]):
                        lora_1 = gr.Dropdown(
                            min_width=240,
                            label="LoRA #1",
                            value="none",
                            choices=[("None", "none")]
                            + [
                                (lora["name"], lora_id)
                                for lora_id, lora in Config.CIVIT_LORAS.items()
                            ],
                        )
                        lora_1_weight = gr.Slider(
                            value=0.0,
                            minimum=0.0,
                            maximum=1.0,
                            step=0.1,
                            show_label=False,
                        )
                    with gr.Group(elem_classes=["gap-0"]):
                        lora_2 = gr.Dropdown(
                            min_width=240,
                            label="LoRA #2",
                            value="none",
                            choices=[("None", "none")]
                            + [
                                (lora["name"], lora_id)
                                for lora_id, lora in Config.CIVIT_LORAS.items()
                            ],
                        )
                        lora_2_weight = gr.Slider(
                            value=0.0,
                            minimum=0.0,
                            maximum=1.0,
                            step=0.1,
                            show_label=False,
                        )

                with gr.Row():
                    guidance_scale = gr.Slider(
                        value=Config.GUIDANCE_SCALE,
                        label="Guidance Scale",
                        minimum=1.0,
                        maximum=15.0,
                        step=0.1,
                    )
                    inference_steps = gr.Slider(
                        value=Config.INFERENCE_STEPS,
                        label="Inference Steps",
                        minimum=1,
                        maximum=50,
                        step=1,
                    )
                    deepcache_interval = gr.Slider(
                        value=Config.DEEPCACHE_INTERVAL,
                        label="DeepCache",
                        minimum=1,
                        maximum=4,
                        step=1,
                    )

                with gr.Row():
                    width = gr.Slider(
                        value=Config.WIDTH,
                        label="Width",
                        minimum=256,
                        maximum=768,
                        step=32,
                    )
                    height = gr.Slider(
                        value=Config.HEIGHT,
                        label="Height",
                        minimum=256,
                        maximum=768,
                        step=32,
                    )
                    aspect_ratio = gr.Dropdown(
                        value=f"{Config.WIDTH},{Config.HEIGHT}",
                        label="Aspect Ratio",
                        filterable=False,
                        choices=[
                            ("Custom", None),
                            ("4:7 (384x672)", "384,672"),
                            ("7:9 (448x576)", "448,576"),
                            ("1:1 (512x512)", "512,512"),
                            ("9:7 (576x448)", "576,448"),
                            ("7:4 (672x384)", "672,384"),
                        ],
                    )

                with gr.Row():
                    file_format = gr.Dropdown(
                        choices=["png", "jpeg", "webp"],
                        label="File Format",
                        filterable=False,
                        value="png",
                    )
                    num_images = gr.Dropdown(
                        choices=list(range(1, 5)),
                        value=Config.NUM_IMAGES,
                        filterable=False,
                        label="Images",
                    )
                    scale = gr.Dropdown(
                        choices=[(f"{s}x", s) for s in Config.SCALES],
                        filterable=False,
                        value=Config.SCALE,
                        label="Scale",
                    )
                    seed = gr.Number(
                        value=Config.SEED,
                        label="Seed",
                        minimum=-1,
                        maximum=(2**64) - 1,
                    )

                with gr.Row():
                    use_karras = gr.Checkbox(
                        elem_classes=["checkbox"],
                        label="Karras ฯƒ",
                        value=True,
                    )
                    use_taesd = gr.Checkbox(
                        elem_classes=["checkbox"],
                        label="Tiny VAE",
                        value=False,
                    )
                    use_freeu = gr.Checkbox(
                        elem_classes=["checkbox"],
                        label="FreeU",
                        value=False,
                    )
                    use_clip_skip = gr.Checkbox(
                        elem_classes=["checkbox"],
                        label="Clip skip",
                        value=False,
                    )

    random_btn.click(random_fn, inputs=[], outputs=[prompt], show_api=False)

    refresh_btn.click(None, inputs=[], outputs=[seed], js=refresh_seed_js)

    seed.change(None, inputs=[seed], outputs=[], js=seed_js)

    file_format.change(
        lambda f: (gr.Gallery(format=f), gr.Image(format=f), gr.Image(format=f)),
        inputs=[file_format],
        outputs=[output_images, image_prompt, ip_image_prompt],
        show_api=False,
    )

    # input events are only user input; change events are both user and programmatic
    aspect_ratio.input(
        None,
        inputs=[aspect_ratio, width, height],
        outputs=[width, height],
        js=aspect_ratio_js,
    )

    # lock the input images so you don't lose them when the gallery updates
    output_images.change(
        gallery_fn,
        inputs=[output_images, image_prompt, ip_image_prompt],
        outputs=[image_select, ip_image_select],
        show_api=False,
    )

    # show the selected image in the image input
    image_select.change(
        image_select_fn,
        inputs=[output_images, image_prompt, image_select],
        outputs=[image_prompt],
        show_api=False,
    )
    ip_image_select.change(
        image_select_fn,
        inputs=[output_images, ip_image_prompt, ip_image_select],
        outputs=[ip_image_prompt],
        show_api=False,
    )

    # reset the dropdown on clear
    image_prompt.clear(
        image_prompt_fn,
        inputs=[output_images],
        outputs=[image_select],
        show_api=False,
    )
    ip_image_prompt.clear(
        image_prompt_fn,
        inputs=[output_images],
        outputs=[ip_image_select],
        show_api=False,
    )

    # show "Custom" aspect ratio when manually changing width or height
    gr.on(
        triggers=[width.input, height.input],
        fn=None,
        inputs=[],
        outputs=[aspect_ratio],
        js="() => { return null; }",
    )

    # toggle image prompts by updating session state
    gr.on(
        triggers=[disable_image.input, disable_ip_image.input],
        fn=lambda disable_image, disable_ip_image: (disable_image, disable_ip_image),
        inputs=[disable_image, disable_ip_image],
        outputs=[DISABLE_IMAGE_PROMPT, DISABLE_IP_IMAGE_PROMPT],
    )

    # generate images
    gr.on(
        triggers=[generate_btn.click, prompt.submit],
        fn=generate_fn,
        api_name="generate",
        outputs=[output_images],
        inputs=[
            prompt,
            negative_prompt,
            image_prompt,
            ip_image_prompt,
            ip_face,
            lora_1,
            lora_1_weight,
            lora_2,
            lora_2_weight,
            embeddings,
            style,
            seed,
            model,
            scheduler,
            width,
            height,
            guidance_scale,
            inference_steps,
            denoising_strength,
            deepcache_interval,
            scale,
            num_images,
            use_karras,
            use_taesd,
            use_freeu,
            use_clip_skip,
            DISABLE_IMAGE_PROMPT,
            DISABLE_IP_IMAGE_PROMPT,
        ],
    )

if __name__ == "__main__":
    parser = argparse.ArgumentParser(add_help=False, allow_abbrev=False)
    parser.add_argument("-s", "--server", type=str, metavar="STR", default="0.0.0.0")
    parser.add_argument("-p", "--port", type=int, metavar="INT", default=7860)
    args = parser.parse_args()

    disable_progress_bars()
    for repo_id, allow_patterns in Config.HF_MODELS.items():
        download_repo_files(repo_id, allow_patterns, token=Config.HF_TOKEN)

    # download civit loras
    for lora_id, lora in Config.CIVIT_LORAS.items():
        file_path = os.path.join(os.path.dirname(__file__), "loras")
        download_civit_file(
            lora_id,
            lora["model_version_id"],
            file_path=file_path,
            token=Config.CIVIT_TOKEN,
        )

    # https://www.gradio.app/docs/gradio/interface#interface-queue
    demo.queue(default_concurrency_limit=1).launch(
        server_name=args.server,
        server_port=args.port,
    )