File size: 43,127 Bytes
35cd3b9
 
 
c8d82c9
0d48286
35cd3b9
 
 
 
 
 
 
abf2378
 
 
35cd3b9
 
 
 
3a20ea0
6059158
d605940
e2739d1
21cd118
e5904f5
3577a96
 
6b13bd4
 
6c65f93
 
35cd3b9
d605940
e5904f5
bfeeff0
8068d4e
35cd3b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ebd2b8
 
 
 
 
abbbf4f
 
4ebd2b8
 
abbbf4f
 
35cd3b9
 
0d48286
35cd3b9
 
 
ad3b877
35cd3b9
 
ad3b877
c347d4f
ad3b877
 
 
 
 
35cd3b9
ad3b877
 
35cd3b9
ad3b877
59c4426
 
 
 
ad3b877
 
 
 
59c4426
 
9c92fe8
35cd3b9
0d48286
 
 
 
a0ecbf7
35cd3b9
 
0d48286
ad3b877
a0ecbf7
 
 
35cd3b9
ae2f804
a0ecbf7
 
 
 
0d48286
a0ecbf7
0d48286
 
 
 
 
a0ecbf7
0d48286
 
4ebd2b8
0d48286
a0ecbf7
0d48286
ae2f804
a0ecbf7
 
 
 
0d48286
ad3b877
0d48286
 
 
 
35cd3b9
9c92fe8
35cd3b9
ad3b877
35cd3b9
ad3b877
9c92fe8
35cd3b9
ad3b877
9c92fe8
ad3b877
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35cd3b9
ad3b877
 
 
 
35cd3b9
 
ad3b877
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c92fe8
ad3b877
 
 
 
 
 
 
 
 
9c92fe8
ad3b877
 
 
35cd3b9
 
 
 
c347d4f
35cd3b9
 
 
 
 
abbbf4f
 
abf2378
 
 
 
 
 
 
c347d4f
 
abf2378
 
 
 
35cd3b9
 
 
 
 
 
4ebd2b8
35cd3b9
 
 
791ee0f
 
5d8606e
 
35cd3b9
 
 
 
 
 
 
 
 
5d8606e
 
 
 
4ebd2b8
5d8606e
 
 
 
 
 
 
 
 
4ebd2b8
5d8606e
 
 
 
 
 
 
 
 
4ebd2b8
5d8606e
 
 
 
 
59c4426
 
 
 
 
 
 
 
 
 
5d8606e
 
 
 
 
35cd3b9
5d8606e
 
 
35cd3b9
5d8606e
 
4ebd2b8
5d8606e
 
 
 
 
 
 
 
 
 
4ebd2b8
5d8606e
 
 
 
 
 
 
 
 
4ebd2b8
5d8606e
 
 
 
 
 
 
 
 
35cd3b9
abf2378
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c347d4f
 
abf2378
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c347d4f
 
abf2378
0f9c8ea
abf2378
35cd3b9
 
 
 
 
 
 
 
c8d82c9
 
 
 
 
c347d4f
 
 
35cd3b9
 
 
 
 
 
 
 
 
59c4426
abf2378
35cd3b9
 
 
 
 
 
 
 
 
59c4426
abf2378
35cd3b9
 
 
 
 
 
 
abf2378
35cd3b9
 
 
 
 
 
 
 
 
 
 
59c4426
abf2378
35cd3b9
 
 
 
 
 
 
abf2378
35cd3b9
 
 
 
 
 
 
 
 
 
 
59c4426
abf2378
35cd3b9
 
 
 
 
 
 
abf2378
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35cd3b9
 
 
5068398
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
791ee0f
5068398
35cd3b9
791ee0f
 
 
c347d4f
791ee0f
c347d4f
791ee0f
0f9c8ea
791ee0f
abf2378
791ee0f
0f9c8ea
abf2378
0f9c8ea
35cd3b9
0f9c8ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d48286
791ee0f
35cd3b9
 
abf2378
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c347d4f
 
abf2378
 
791ee0f
35cd3b9
 
 
ad3b877
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
791ee0f
 
ad3b877
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f9c8ea
ad3b877
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f9c8ea
ad3b877
 
 
0f9c8ea
 
ad3b877
 
0f9c8ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad3b877
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35cd3b9
 
abbbf4f
35cd3b9
 
 
 
 
 
abbbf4f
5d8606e
abbbf4f
 
 
 
35cd3b9
abbbf4f
 
35cd3b9
 
 
abbbf4f
35cd3b9
 
 
 
 
 
 
 
 
ada8eef
21cd118
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
import gradio as gr
from novita_client import *
import logging
import random
import traceback


logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(filename)s(%(lineno)d) %(message)s')


first_stage_activication_words = "a ohwx"
second_stage_activication_words = "a closeup photo of ohwx"

first_stage_lora_scale_default = 0.3
second_stage_lora_scale_default = 1.0

suggestion_checkpoints = [
    "dreamshaper_8_93211.safetensors",
    "epicrealism_pureEvolutionV5_97793.safetensors",
    "v1-5-pruned-emaonly.safetensors",
    "majichenmixrealistic_v10_85701.safetensors",
    "realisticVisionV51_v51VAE_94301.safetensors",
    "WFChild_v1.0.ckpt",
    "chilloutmix_NiPrunedFp32Fix.safetensors",
    "darkSushiMixMix_225D_64380.safetensors",
    "dreamshaperXL09Alpha_alpha2Xl10_91562.safetensors",
    "protovisionXLHighFidelity3D_release0630Bakedvae_154359.safetensors",
    "sd_xl_base_1.0.safetensors",
    "sdxlUnstableDiffusers_v11_216694.safetensors",
    "realisticVisionV40_v40VAE_81510.safetensors",
    "xxmix9realistic_v10_37818.safetensors"
]

base_checkpoints = ["epicrealism_naturalSin_121250", "v1-5-pruned-emaonly", "WFChild_v1.0", "majichenmixrealistic_v10",
                    "realisticVisionV51_v51VAE_94301", "chilloutmix_NiPrunedFp32Fix", "darkSushiMixMix_225D_64380",
                    "stable-diffusion-xl-base-1.0", "protovisionXLHighFidelity3D_release0630Bakedvae_154359", "sdxlUnstableDiffusers_v11_216694", "realisticVisionV40_v40VAE_81510", "xxmix9realistic_v10_37818", "epicrealismXL_v10_247189"]


get_local_storage = """
    function() {
      globalThis.setStorage = (key, value)=>{
        localStorage.setItem(key, JSON.stringify(value))
      }
       globalThis.getStorage = (key, value)=>{
        return JSON.parse(localStorage.getItem(key))
      }

       const novita_key =  getStorage('novita_key')
       return [novita_key];
      }
    """


def get_noviata_client(novita_key):
    client = NovitaClient(novita_key, os.getenv('NOVITA_API_URI', None))
    client.set_extra_headers({"User-Agent": "stylization-playground"})
    return client


def create_ui():
    with gr.Blocks() as demo:
        gr.HTML(''' 
        <a href="https://novita.ai/?utm_source=huggingface&utm_medium=face-stylization&utm_campaign=face-stylization">
            <img src="https://raw.githubusercontent.com/wiki/novitalabs/sd-webui-cleaner/images/logo2.png" width="120px;" alt="Unsplash" />
        </a>
        <h1>Face Stylization Playground</h1>
        <h3>Start integrate with <a href="https://novita.ai/get-started/Model_training.html?utm_source=huggingface&utm_medium=face-stylization&utm_campaign=face-stylization">Model_training API</a> 
        <h3> Get Novita.AI API Key from <a href="https://novita.ai/get-started/Account_account_and_key.html?utm_source=huggingface&utm_medium=face-stylization&utm_campaign=face-stylization">Novita.AI</a></h2>
        '''
                )

        free_trial_notice = gr.HTML('', visible=False)
        with gr.Row():
            with gr.Column(scale=1):
                novita_key = gr.Textbox(value="", label="Novita.AI API KEY (store in broweser)", placeholder="novita.ai api key", type="password")
            with gr.Column(scale=1):
                user_balance = gr.Textbox(label="User Balance", value="0.0")

        with gr.Tab(label="Subject Training"):
            with gr.Row():
                with gr.Column(scale=1):
                    training_subject_base_model = gr.Dropdown(choices=base_checkpoints, label="Base Model", value=base_checkpoints[0])
                    training_subject_geneder = gr.Radio(choices=["man", "woman", "person"], value="man", label="Geneder")
                    training_subject_name = gr.Text(label="Training Name", placeholder="training name", elem_id="training_name", value="my-face-001")
                    training_subject_max_train_steps = gr.Slider(minimum=200, maximum=4000, step=1, label="Max Train Steps", value=2000)
                    training_subject_images = gr.File(file_types=["image"], file_count="multiple", label="6-10 face images.")
                    training_subject_button = gr.Button(value="Train")
                    training_subject_payload = gr.JSON(label="Training Payload, POST /v3/training/subject")
                with gr.Column(scale=1):
                    training_subject_refresh_button = gr.Button(value="Refresh Training Status")
                    training_subject_refresh_json = gr.JSON()

                def on_upload_training_subject_images(files):
                    if files is None:
                        return 2000
                    return min(2000, len(files) * 200)

                training_subject_images.change(
                    inputs=[training_subject_images],
                    outputs=training_subject_max_train_steps,
                    fn=on_upload_training_subject_images,
                )

                def train_subject(novita_key, base_model, training_name, training_subject_geneder, max_train_steps, training_images):
                    training_images = [_.name for _ in training_images]
                    try:
                        get_noviata_client(novita_key).create_training_subject(
                            base_model=base_model,
                            name=training_name,
                            instance_prompt=f"a closeup photo of ohwx person",
                            class_prompt="person",
                            max_train_steps=max_train_steps,
                            images=training_images,
                            components=FACE_TRAINING_DEFAULT_COMPONENTS,
                            learning_rate=3e-4,
                            seed=None,
                            lr_scheduler='cosine_with_restarts',
                            with_prior_preservation=True,
                            prior_loss_weight=1.0,
                            lora_r=32,
                            lora_alpha=32,
                            lora_text_encoder_r=32,
                            lora_text_encoder_alpha=32,
                        )

                        payload = dict(
                            name=training_name,
                            base_model=base_model,
                            image_dataset_items=["....assets_ids, please manually upload to novita.ai"],
                            expert_setting=TrainingExpertSetting(
                                instance_prompt=f"a closeup photo of ohwx person",
                                class_prompt="person",
                                max_train_steps=max_train_steps,
                                learning_rate="3e-4",
                                seed=None,
                                lr_scheduler='cosine_with_restarts',
                                with_prior_preservation=True,
                                prior_loss_weight=1.0,
                                lora_r=32,
                                lora_alpha=32,
                                lora_text_encoder_r=32,
                                lora_text_encoder_alpha=32,
                            ),
                            components=[_.to_dict() for _ in FACE_TRAINING_DEFAULT_COMPONENTS],
                        )
                    except Exception as e:
                        logging.error(e)
                        raise gr.Error(traceback.format_exc())

                    return gr.update(value=get_noviata_client(novita_key).list_training("subject").sort_by_created_at()), payload

                training_subject_refresh_button.click(
                    inputs=[novita_key],
                    outputs=training_subject_refresh_json,
                    fn=lambda novita_key: gr.update(value=get_noviata_client(novita_key).list_training("subject").sort_by_created_at())
                )
                training_subject_button.click(
                    inputs=[novita_key, training_subject_base_model, training_subject_name, training_subject_geneder, training_subject_max_train_steps, training_subject_images],
                    outputs=[training_subject_refresh_json, training_subject_payload],
                    fn=train_subject
                )

        with gr.Tab(label="Style Training"):
            with gr.Row():
                with gr.Column(scale=1):
                    training_style_base_model = gr.Dropdown(choices=base_checkpoints, label="Base Model", value="v1-5-pruned-emaonly")
                    training_style_name = gr.Text(label="Training Name", placeholder="training name", elem_id="training_name", value="my-style-001")
                    training_style_max_train_steps = gr.Slider(minimum=200, maximum=10000, step=1, label="Max Train Steps", value=2000)
                    training_style_images_and_captions = gr.File(file_types=["image", ".txt", ".caption"], file_count="multiple", label="10-50 style images.")
                    training_style_button = gr.Button(value="Train")
                    training_style_payload = gr.JSON(label="Training Payload, POST /v3/training/style")
                with gr.Column(scale=1):
                    training_style_refresh_button = gr.Button(value="Refresh Training Status")
                    training_style_refresh_json = gr.JSON()

                def on_upload_training_style_images(files):
                    if files is None:
                        return 2000

                    caption_files = [f for f in files if f.name.endswith(".caption") or f.name.endswith(".txt")]
                    image_files = [f for f in files if not f.name.endswith(".caption") and not f.name.endswith(".txt")]

                    if len(caption_files) != len(image_files):
                        raise gr.Error("caption files and image files must be same length")

                    return min(2000, len(image_files) * 200)

                training_style_images_and_captions.change(
                    inputs=[training_style_images_and_captions],
                    outputs=training_style_max_train_steps,
                    fn=on_upload_training_style_images,
                )

                def train_style(novita_key, base_model, training_name, max_train_steps, training_style_images_and_captions):
                    files = [_.name for _ in training_style_images_and_captions]
                    images_captions = {}
                    for f in files:
                        basename = os.path.basename(f).rsplit(".", 1)[0]
                        if basename not in images_captions:
                            images_captions[basename] = {}
                        if f.endswith(".caption") or f.endswith(".txt"):
                            images_captions[basename]["caption"] = f
                        else:
                            images_captions[basename]["image"] = f

                    for k, v in images_captions.items():
                        if len(v) != 2:
                            raise gr.Error(f"image and caption must be provided for {k}")

                    images = []
                    captions = []

                    for _, v in images_captions.items():
                        if "image" in v:
                            images.append(v["image"])
                        if "caption" in v:
                            with open(v["caption"], "r") as f:
                                captions.append(f.read().strip())

                    get_noviata_client(novita_key).create_training_style(
                        name=training_name,
                        base_model=base_model,
                        max_train_steps=max_train_steps,
                        images=images,
                        captions=captions,
                        learning_rate=1e-4,
                    )
                    payload = dict(
                        name=training_name,
                        base_model=base_model,
                        image_dataset_items=["....assets_ids, please manually upload to novita.ai"],
                        expert_setting=TrainingExpertSetting(
                            learning_rate=1e-4,
                        ),
                    )
                    return gr.update(value=get_noviata_client(novita_key).list_training("style").sort_by_created_at()), payload

                training_style_button.click(
                    inputs=[novita_key, training_style_base_model, training_style_name, training_style_max_train_steps, training_style_images_and_captions],
                    outputs=[training_style_refresh_json, training_style_payload],
                    fn=train_style
                )
                training_style_refresh_button.click(
                    inputs=[novita_key],
                    outputs=training_style_refresh_json,
                    fn=lambda novita_key: gr.update(value=get_noviata_client(novita_key).list_training("style").sort_by_created_at())
                )

        with gr.Tab(label="Subject Inferencing"):
            with gr.Row():
                with gr.Column(scale=1):
                    style_prompt = gr.TextArea(lines=3, label="Style Prompt")
                    style_negative_prompt = gr.TextArea(lines=3, label="Style Negative Prompt")
                    style_gender = gr.Radio(choices=["man", "woman", "person"], value="man", label="Gender")
                    style_model = gr.Dropdown(choices=suggestion_checkpoints, label="Style Model")
                    style_lora = gr.Dropdown(choices=[], label="Style LoRA", type="index")
                    _hide_lora_training_response = gr.JSON(visible=False)
                    style_height = gr.Slider(minimum=1, maximum=1024, step=1, label="Style Height", value=512)
                    style_width = gr.Slider(minimum=1, maximum=1024, step=1, label="Style Width", value=512)
                    style_method = gr.Radio(choices=["txt2img", "controlnet-depth", "controlnet-pose", "controlnet-canny",
                                            "controlnet-lineart", "controlnet-scribble", "controlnet-tile"], label="Style Method")

                    style_advanced = gr.Checkbox(label="Advanced")
                    with gr.Column(scale=1, visible=False) as style_advanced_tab:
                        first_stage_seed = gr.Slider(minimum=-1, maximum=1000000, step=1, label="First Stage Seed", value=-1)
                        second_stage_seed = gr.Slider(minimum=-1, maximum=1000000, step=1, label="Second Stage Seed", value=-1)
                        first_stage_lora_scale = gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label="First Stage LoRA Scale", value=0.3)
                        second_stage_lora_scale = gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label="Second Stage LoRA Scale", value=1.0)
                        second_stage_strength = gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label="Second Stage Strength", value=0.3)
                        second_stage_steps = gr.Slider(minimum=1, maximum=100, step=1, label="Second Stage Steps", value=20)
                        controlnet_weight = gr.Slider(minimum=0.0, maximum=2.0, step=0.01, label="Controlnet Weight", value=1.0)

                    style_advanced.change(inputs=[style_advanced], outputs=[style_advanced_tab], fn=lambda v: gr.update(visible=v))

                    style_reference_image = gr.Image(label="Style Reference Image", height=512)

                with gr.Column(scale=1):
                    inference_refresh_button = gr.Button(value="Refresh Style LoRA")
                    generate_button = gr.Button(value="Generate")
                    num_images = gr.Slider(minimum=1, maximum=10, step=1, label="Num Images", value=1)
                    gallery = gr.Gallery(label="Gallery", height="auto", object_fit="scale-down", show_share_button=False)

                    def inference_refresh_button_fn(novita_key):
                        # trained_loras_models = [_.name for _ in get_noviata_client(novita_key).models_v3(refresh=True).filter_by_type("lora").filter_by_visibility("private")]
                        serving_models = [_.models[0].model_name for _ in get_noviata_client(novita_key).list_training("subject").filter_by_model_status("SERVING")]
                        serving_models_labels = [_.task_name for _ in get_noviata_client(novita_key).list_training("subject").filter_by_model_status("SERVING")]
                        default_serving_model = serving_models_labels[0] if len(serving_models_labels) > 0 else None
                        return gr.update(choices=serving_models_labels, value=default_serving_model), gr.update(value=serving_models)

                    inference_refresh_button.click(
                        inputs=[novita_key],
                        outputs=[style_lora, _hide_lora_training_response],
                        fn=inference_refresh_button_fn
                    )

                    first_stage_request_body = gr.JSON(label="First Stage Request Body, POST /api/v2/txt2img")

            templates = [
                {
                    "style_prompt": "(masterpiece), (extremely intricate:1.3), (realistic), portrait of a person, the most handsome in the world, (medieval armor), metal reflections, upper body, outdoors, intense sunlight, far away castle, professional photograph of a stunning person detailed, sharp focus, dramatic, award winning, cinematic lighting, octane render unreal engine, volumetrics dtx, (film grain, blurry background, blurry foreground, bokeh, depth of field, sunset, motion blur:1.3), chainmail",
                    "style_negative_prompt": "BadDream_53202, UnrealisticDream_53204",
                    "style_gender": "man",
                    "style_model": "dreamshaper_8_93211.safetensors",
                    "style_method": "txt2img",
                    "style_height": 768,
                    "style_width": 512,
                    "style_reference_image": "./00001.jpg",
                },
                {
                    "style_prompt": "photo of beautiful age 18 girl, pastel hair, freckles sexy, beautiful, close up, young, dslr, 8k, 4k, ultrarealistic, realistic, natural skin, textured skin",
                    "style_negative_prompt": "BadDream_53202, UnrealisticDream_53204",
                    "style_gender": "woman",
                    "style_model": "dreamshaper_8_93211.safetensors",
                    "style_method": "controlnet-depth",
                    "style_height": 768,
                    "style_width": 512,
                    "style_reference_image": "./00002.jpg",
                },
                {
                    "style_prompt": "majesty, holy, saintly, godly, 1girl, an angel descending from heaven, upper body, beautiful asian goddess, looking at viewer, detail face and eyes, symmetrical eyes, glowing white eye, warm attitude, long hair, blonde hair, floating hair, royal clothes, gold armor, feathered wings, glowing wings, nice hands",
                    "style_negative_prompt": "BadDream_53202, UnrealisticDream_53204",
                    "style_gender": "woman",
                    "style_model": "dreamshaper_8_93211.safetensors",
                    "style_method": "controlnet-canny",
                    "style_height": 768,
                    "style_width": 512,
                    "style_reference_image": "./00003.jpg",
                },
                {
                    "style_prompt": "Iron Man, close up, digital art, character concept, magical realism, warm golden light, sunset, Marvel Cinematic Universe, Hogwarts, high-resolution, vibrant colors, realistic rendering, key art, fantasy fashion, Iron Man suit integration, elegant and powerful pose",
                    "style_negative_prompt": "BadDream_53202, UnrealisticDream_53204",
                    "style_gender": "man",
                    "style_model": "dreamshaper_8_93211.safetensors",
                    "style_method": "controlnet-depth",
                    "style_height": 768,
                    "style_width": 512,
                    "style_reference_image": "./00004.jpg",
                }
            ]

            def mirror(*args):
                return args

            with gr.Row():
                examples = gr.Examples(
                    [
                        [
                            _.get("style_prompt", ""),
                            _.get("style_negative_prompt", ""),
                            _.get("style_gender", "man"),
                            _.get("style_model", ""),
                            _.get("style_height", 512),
                            _.get("style_width", 512),
                            _.get("style_method", "txt2img"),
                            _.get("style_reference_image", ""),
                        ] for _ in templates
                    ],
                    [
                        style_prompt,
                        style_negative_prompt,
                        style_gender,
                        style_model,
                        style_height,
                        style_width,
                        style_method,
                        style_reference_image,
                    ],
                    [
                        style_prompt,
                        style_negative_prompt,
                        style_gender,
                        style_model,
                        style_height,
                        style_width,
                        style_method,
                        style_reference_image,
                    ],
                    mirror,
                    cache_examples=False,
                )

            def generate(novita_key,
                         style_gender,
                         style_prompt,
                         style_negative_prompt,
                         style_model,
                         style_lora,
                         _hide_lora_training_response,
                         style_hegiht,
                         style_width,
                         style_method,
                         style_reference_image,
                         first_stage_seed,
                         second_stage_seed,
                         first_stage_lora_scale,
                         second_stage_lora_scale,
                         second_stage_strength,
                         second_stage_steps,
                         controlnet_weight,
                         num_images):

                style_reference_image = Image.fromarray(style_reference_image)

                def style(style_method,
                          style_gender,
                          style_prompt,
                          style_negative_prompt,
                          style_model,
                          style_lora,
                          _hide_lora_training_response,
                          style_hegiht,
                          style_width,
                          style_reference_image,
                          first_stage_seed,
                          second_stage_seed,
                          first_stage_lora_scale,
                          second_stage_lora_scale,
                          second_stage_strength,
                          second_stage_steps,
                          controlnet_weight,
                          num_images
                          ):
                    if isinstance(style_lora, int):
                        style_lora = _hide_lora_training_response[style_lora].replace(".safetensors", "")
                    else:
                        style_lora = style_lora.replace(".safetensors", "")

                    height = int(style_hegiht)
                    width = int(style_width)

                    if first_stage_seed == -1:
                        first_stage_seed = random.randint(1, 2 ** 32 - 1)
                    if second_stage_seed == -1:
                        second_stage_seed = random.randint(1, 2 ** 32 - 1)

                    activication_words = f"{first_stage_activication_words} {style_gender}"

                    style_prompt = f"{activication_words}, <lora:{style_lora}:{first_stage_lora_scale}>, {style_prompt}"

                    if style_method == "txt2img":
                        req = Txt2ImgRequest(
                            prompt=style_prompt,
                            negative_prompt=style_negative_prompt,
                            width=width,
                            height=height,
                            model_name=style_model,
                            steps=30,
                            sampler_name=Samplers.DPMPP_M_KARRAS,
                            seed=first_stage_seed,
                        )
                    elif style_method == "controlnet-depth":
                        req = Txt2ImgRequest(
                            prompt=style_prompt,
                            negative_prompt=style_negative_prompt,
                            width=width,
                            height=height,
                            model_name=style_model,
                            steps=30,
                            sampler_name=Samplers.DPMPP_M_KARRAS,
                            seed=first_stage_seed,
                            controlnet_units=[
                                ControlnetUnit(
                                    input_image=image_to_base64(style_reference_image),
                                    control_mode=ControlNetMode.BALANCED,
                                    model="control_v11f1p_sd15_depth",
                                    module=ControlNetPreprocessor.DEPTH,
                                    resize_mode=ControlNetResizeMode.RESIZE_OR_CORP,
                                    weight=controlnet_weight,
                                )
                            ]
                        )
                    elif style_method == "controlnet-pose":
                        req = Txt2ImgRequest(
                            prompt=style_prompt,
                            negative_prompt=style_negative_prompt,
                            width=width,
                            height=height,
                            model_name=style_model,
                            steps=30,
                            sampler_name=Samplers.DPMPP_M_KARRAS,
                            seed=first_stage_seed,
                            controlnet_units=[
                                ControlnetUnit(
                                    input_image=image_to_base64(style_reference_image),
                                    control_mode=ControlNetMode.BALANCED,
                                    model="control_v11p_sd15_openpose",
                                    module=ControlNetPreprocessor.OPENPOSE,
                                    resize_mode=ControlNetResizeMode.RESIZE_OR_CORP,
                                    weight=controlnet_weight,
                                )
                            ]
                        )
                    elif style_method == "controlnet-canny":
                        req = Txt2ImgRequest(
                            prompt=style_prompt,
                            negative_prompt=style_negative_prompt,
                            width=width,
                            height=height,
                            model_name=style_model,
                            steps=30,
                            sampler_name=Samplers.DPMPP_M_KARRAS,
                            seed=first_stage_seed,
                            controlnet_units=[
                                ControlnetUnit(
                                    input_image=image_to_base64(style_reference_image),
                                    control_mode=ControlNetMode.BALANCED,
                                    model="control_v11p_sd15_canny",
                                    module=ControlNetPreprocessor.CANNY,
                                    resize_mode=ControlNetResizeMode.RESIZE_OR_CORP,
                                    weight=controlnet_weight,
                                )
                            ]
                        )
                    elif style_method == "controlnet-lineart":
                        req = Txt2ImgRequest(
                            prompt=style_prompt,
                            negative_prompt=style_negative_prompt,
                            width=width,
                            height=height,
                            model_name=style_model,
                            steps=30,
                            sampler_name=Samplers.DPMPP_M_KARRAS,
                            seed=first_stage_seed,
                            controlnet_units=[
                                ControlnetUnit(
                                    input_image=image_to_base64(style_reference_image),
                                    control_mode=ControlNetMode.BALANCED,
                                    model="control_v11p_sd15_lineart",
                                    module=ControlNetPreprocessor.LINEART,
                                    resize_mode=ControlNetResizeMode.RESIZE_OR_CORP,
                                    weight=controlnet_weight,
                                )
                            ]
                        )
                    elif style_method == "controlnet-scribble":
                        req = Txt2ImgRequest(
                            prompt=style_prompt,
                            negative_prompt=style_negative_prompt,
                            width=width,
                            height=height,
                            model_name=style_model,
                            steps=30,
                            sampler_name=Samplers.DPMPP_M_KARRAS,
                            seed=first_stage_seed,
                            controlnet_units=[
                                ControlnetUnit(
                                    input_image=image_to_base64(style_reference_image),
                                    control_mode=ControlNetMode.BALANCED,
                                    model="control_v11p_sd15_scribble",
                                    module=ControlNetPreprocessor.SCRIBBLE_HED,
                                    resize_mode=ControlNetResizeMode.RESIZE_OR_CORP,
                                    weight=controlnet_weight,
                                )
                            ]
                        )
                    elif style_method == "controlnet-tile":
                        req = Txt2ImgRequest(
                            prompt=style_prompt,
                            negative_prompt=style_negative_prompt,
                            width=width,
                            height=height,
                            model_name=style_model,
                            steps=30,
                            sampler_name=Samplers.DPMPP_M_KARRAS,
                            seed=first_stage_seed,
                            controlnet_units=[
                                ControlnetUnit(
                                    input_image=image_to_base64(style_reference_image),
                                    control_mode=ControlNetMode.BALANCED,
                                    model="control_v11f1e_sd15_tile",
                                    module=ControlNetPreprocessor.NULL,
                                    resize_mode=ControlNetResizeMode.RESIZE_OR_CORP,
                                    weight=controlnet_weight,
                                )
                            ],
                        )

                    ad_req = ADEtailer(
                        prompt=f"{second_stage_activication_words} {style_gender}, masterpiece, <lora:{style_lora}:{second_stage_lora_scale}>",
                        negative_prompt=style_negative_prompt,
                        strength=second_stage_strength,
                        seed=second_stage_seed,
                        steps=second_stage_steps,
                    )
                    req.batch_size = num_images
                    req.adetailer = ad_req

                    res = get_noviata_client(novita_key).sync_txt2img(req)
                    style_images = [Image.open(BytesIO(b)) for b in res.data.imgs_bytes]

                    return style_images, req.to_dict()
                images = []
                try:
                    final_images, first_stage_request_body = style(
                        style_method,
                        style_gender,
                        style_prompt,
                        style_negative_prompt,
                        style_model,
                        style_lora,
                        _hide_lora_training_response,
                        style_hegiht,
                        style_width,
                        style_reference_image,
                        first_stage_seed,
                        second_stage_seed,
                        first_stage_lora_scale,
                        second_stage_lora_scale,
                        second_stage_strength,
                        second_stage_steps,
                        controlnet_weight,
                        num_images
                    )
                    images.extend(final_images)
                except:
                    raise gr.Error(traceback.format_exc())

                return gr.update(value=images), first_stage_request_body

            generate_button.click(
                inputs=[novita_key,
                        style_gender,
                        style_prompt,
                        style_negative_prompt,
                        style_model,
                        style_lora,
                        _hide_lora_training_response,
                        style_height,
                        style_width,
                        style_method,
                        style_reference_image,
                        first_stage_seed,
                        second_stage_seed,
                        first_stage_lora_scale,
                        second_stage_lora_scale,
                        second_stage_strength,
                        second_stage_steps,
                        controlnet_weight,
                        num_images],
                outputs=[gallery, first_stage_request_body],
                fn=generate
            )

        with gr.Tab(label="Style Inferencing"):
            with gr.Row():
                with gr.Column(scale=1):
                    inference_style_prompt = gr.TextArea(lines=3, label="Style Prompt")
                    inference_style_negative_prompt = gr.TextArea(lines=3, label="Style Negative Prompt")
                    inference_style_model = gr.Dropdown(choices=suggestion_checkpoints, label="Style Model")
                    _inference_style_hide_lora_training_response = gr.JSON(visible=False)
                    inference_style_lora = gr.Dropdown(choices=[], label="Style LoRA", type="index")
                    inference_style_height = gr.Slider(minimum=1, maximum=1024, step=1, label="Style Height", value=512)
                    inference_style_width = gr.Slider(minimum=1, maximum=1024, step=1, label="Style Width", value=512)

                    inference_style_first_stage_seed = gr.Slider(minimum=-1, maximum=1000000, step=1, label="First Stage Seed", value=-1)
                    inference_style_first_stage_lora_scale = gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label="First Stage LoRA Scale", value=1.0)

                with gr.Column(scale=1):
                    inference_style_refresh_button = gr.Button(value="Refresh Style LoRA")
                    inference_style_generate_button = gr.Button(value="Generate")
                    inference_style_num_images = gr.Slider(minimum=1, maximum=10, step=1, label="Num Images", value=1)
                    inference_style_gallery = gr.Gallery(label="Gallery", height="auto", object_fit="scale-down", show_share_button=False)

                    def inference_style_refresh_button_fn(novita_key):
                        # trained_loras_models = [_.name for _ in get_noviata_client(novita_key).models_v3(refresh=True).filter_by_type("lora").filter_by_visibility("private")]
                        serving_models = [_.models[0].model_name for _ in get_noviata_client(novita_key).list_training("subject").filter_by_model_status("SERVING")]
                        serving_models_labels = [_.task_name for _ in get_noviata_client(novita_key).list_training("subject").filter_by_model_status("SERVING")]
                        default_serving_model = serving_models_labels[0] if len(serving_models_labels) > 0 else None
                        return gr.update(choices=serving_models_labels, value=default_serving_model), gr.update(value=serving_models)

                    inference_style_refresh_button.click(
                        inputs=[novita_key],
                        outputs=[inference_style_lora, _inference_style_hide_lora_training_response],
                        fn=inference_style_refresh_button_fn
                    )

                    inference_style_first_stage_request_body = gr.JSON(label="First Stage Request Body, POST /api/v2/txt2img")

            def inference_style_generate(novita_key,
                                         style_prompt,
                                         style_negative_prompt,
                                         style_model,
                                         style_lora,
                                         _hide_lora_training_response,
                                         style_hegiht,
                                         style_width,
                                         first_stage_seed,
                                         first_stage_lora_scale,
                                         num_images):

                def style(
                    style_prompt,
                    style_negative_prompt,
                    style_model,
                    style_lora,
                    _hide_lora_training_response,
                    style_hegiht,
                    style_width,
                    first_stage_seed,
                    first_stage_lora_scale,
                    num_images
                ):
                    if isinstance(style_lora, int):
                        style_lora = _hide_lora_training_response[style_lora].replace(".safetensors", "")
                    else:
                        style_lora = style_lora.replace(".safetensors", "")

                    height = int(style_hegiht)
                    width = int(style_width)

                    if first_stage_seed == -1:
                        first_stage_seed = random.randint(1, 2 ** 32 - 1)

                    style_prompt = f"{style_prompt}, <lora:{style_lora}:{first_stage_lora_scale}>"
                    req = Txt2ImgRequest(
                        prompt=style_prompt,
                        negative_prompt=style_negative_prompt,
                        width=width,
                        height=height,
                        model_name=style_model,
                        steps=30,
                        sampler_name=Samplers.DPMPP_M_KARRAS,
                        seed=first_stage_seed,
                        batch_size=num_images
                    )

                    res = get_noviata_client(novita_key).sync_txt2img(req)
                    style_images = [Image.open(BytesIO(b)) for b in res.data.imgs_bytes]
                    return style_images, req.to_dict()

                images = []
                try:
                    final_images, first_stage_request_body = style(
                        style_prompt,
                        style_negative_prompt,
                        style_model,
                        style_lora,
                        _hide_lora_training_response,
                        style_hegiht,
                        style_width,
                        first_stage_seed,
                        first_stage_lora_scale,
                        num_images
                    )
                    images.extend(final_images)
                except:
                    raise gr.Error(traceback.format_exc())

                return gr.update(value=images), first_stage_request_body

            inference_style_generate_button.click(
                inputs=[novita_key,
                        inference_style_prompt,
                        inference_style_negative_prompt,
                        inference_style_model,
                        inference_style_lora,
                        _inference_style_hide_lora_training_response,
                        inference_style_height,
                        inference_style_width,
                        inference_style_first_stage_seed,
                        inference_style_first_stage_lora_scale,
                        inference_style_num_images],
                outputs=[inference_style_gallery, inference_style_first_stage_request_body],
                fn=inference_style_generate
            )

        def onload(novita_key):
            if novita_key is None or novita_key == "":
                return novita_key, gr.update(choices=[], value=None), gr.update(value=None), f"$ UNKNOWN", gr.update(visible=False)
            try:
                user_info_json = get_noviata_client(novita_key).user_info()
                serving_models = [_.models[0].model_name for _ in get_noviata_client(novita_key).list_training().filter_by_model_status("SERVING")]
                serving_models_labels = [_.task_name for _ in get_noviata_client(novita_key).list_training().filter_by_model_status("SERVING")]
            except Exception as e:
                logging.error(e)
                return novita_key, gr.update(choices=[], value=None), gr.update(value=None), f"$ UNKNOWN", gr.update(visible=False)
            default_serving_model = serving_models_labels[0] if len(serving_models_labels) > 0 else None
            free_trial = user_info_json.free_trial.get('training', 0)
            trial_html = f'''<h2 style="color: red"> 🌟 Free trial quota: {free_trial} </h2>'''

            return novita_key, gr.update(choices=serving_models_labels, value=default_serving_model), gr.update(value=serving_models), f"$ {user_info_json.credit_balance / 100 / 100:.2f}", gr.update(value=trial_html, visible=free_trial > 0)

        novita_key.change(onload, inputs=novita_key, outputs=[novita_key, style_lora, _hide_lora_training_response,
                          user_balance, free_trial_notice], _js="(v)=>{ setStorage('novita_key',v); return [v]; }")

        demo.load(
            inputs=[novita_key],
            outputs=[novita_key, style_lora, _hide_lora_training_response, user_balance, free_trial_notice],
            fn=onload,
            _js=get_local_storage,
        )

    return demo


if __name__ == '__main__':
    demo = create_ui()
    demo.queue(api_open=False, concurrency_count=20)
    demo.launch(server_name="0.0.0.0", share=True)