-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.py
1588 lines (1452 loc) · 74.5 KB
/
app.py
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
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#@title Prepare the Concepts Library to be used
import json
import shutil
import sqlite3
import subprocess
import sys
sys.path.append('src/blip')
sys.path.append('src/clip')
import clip
import hashlib
import math
import numpy as np
import pickle
import torchvision.transforms as T
import torchvision.transforms.functional as TF
import requests
import wget
import gradio as grad, random, re
import gradio as gr
import torch
import os
import utils
import html
import re
import base64
import subprocess
import argparse
import logging
import streamlit as st
import pandas as pd
import datasets
import yaml
import textwrap
import tornado
import time
import cv2 as cv
from torch import autocast
from diffusers import StableDiffusionPipeline
from transformers import pipeline, set_seed
from huggingface_hub import HfApi
from huggingface_hub import hf_hub_download
from transformers import CLIPTextModel, CLIPTokenizer
from diffusers import AutoencoderKL, UNet2DConditionModel
from diffusers import StableDiffusionImg2ImgPipeline
from PIL import Image
from datasets import load_dataset
from share_btn import community_icon_html, loading_icon_html, share_js
from io import BytesIO
from models.blip import blip_decoder
from torch import nn
from torch.nn import functional as F
from tqdm import tqdm
from pathlib import Path
from flask import Flask, request, jsonify, g
from flask_expects_json import expects_json
from flask_cors import CORS
from huggingface_hub import Repository
from flask_apscheduler import APScheduler
from jsonschema import ValidationError
from os import mkdir
from os.path import isdir
from colorthief import ColorThief
from data_measurements.dataset_statistics import DatasetStatisticsCacheClass as dmt_cls
from utils import dataset_utils
from utils import streamlit_utils as st_utils
from dataclasses import asdict
from .transfer import transfer_color
from .utils import convert_bytes_to_pil
from diffusers import DiffusionPipeline
#from torch import autocast
#from diffusers import StableDiffusionPipeline
#from io import BytesIO
#import base64
#import torch
from share_btn import community_icon_html, loading_icon_html, share_js
pipeline = DiffusionPipeline.from_pretrained("flax/waifu-diffusion")
pipeline = DiffusionPipeline.from_pretrained("flax/Cyberpunk-Anime-Diffusion")
pipeline = DiffusionPipeline.from_pretrained("technillogue/waifu-diffusion")
pipeline = DiffusionPipeline.from_pretrained("svjack/Stable-Diffusion-Pokemon-en")
pipeline = DiffusionPipeline.from_pretrained("AdamOswald1/Idk")
stable_inversion = "user/my-stable-inversion" #@param {type:"string"}
inversion_path = hf_hub_download(repo_id=stable_inversion, filename="token_embeddings.pt")
text_encoder.text_model.embeddings.token_embedding.weight = torch.load(inversion_path)
subprocess.run(["make", "build-all"], shell=False)
img_to_text = gr.Blocks.load(name="spaces/pharma/CLIP-Interrogator")
stable_diffusion = gr.Blocks.load(name="spaces/stabilityai/stable-diffusion")
is_colab = utils.is_google_colab()
MODE = os.environ.get('FLASK_ENV', 'production')
IS_DEV = MODE == 'development'
app = Flask(__name__, static_url_path='/static')
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False
schema = {
"type": "object",
"properties": {
"prompt": {"type": "string"},
"images": {
"type": "array",
"items": {
"type": "object",
"minProperties": 2,
"maxProperties": 2,
"properties": {
"colors": {
"type": "array",
"items": {
"type": "string"
},
"maxItems": 5,
"minItems": 5
},
"imgURL": {"type": "string"}}
}
}
},
"minProperties": 2,
"maxProperties": 2
}
CORS(app)
DB_FILE = Path("./data.db")
TOKEN = os.environ.get('HUGGING_FACE_HUB_TOKEN')
repo = Repository(
local_dir="data",
repo_type="dataset",
clone_from="huggingface-projects/color-palettes-sd",
use_auth_token=TOKEN
)
repo.git_pull()
# copy db on db to local path
shutil.copyfile("./data/data.db", DB_FILE)
db = sqlite3.connect(DB_FILE)
try:
data = db.execute("SELECT * FROM palettes").fetchall()
if IS_DEV:
print(f"Loaded {len(data)} palettes from local db")
db.close()
except sqlite3.OperationalError:
db.execute(
'CREATE TABLE palettes (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, data json, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL)')
db.commit()
api = HfApi()
models_list = api.list_models(author="sd-concepts-library", sort="likes", direction=-1)
models = []
if torch.cuda.is_available():
torchfloat = torch.float16
else:
torchfloat = torch.float32
class Model:
def __init__(self, name, path, prefix):
self.name = name
self.path = path
self.prefix = prefix
models = [
Model("Custom model", "", ""),
Model("Arcane", "nitrosocke/Arcane-Diffusion", "arcane style"),
Model("Archer", "nitrosocke/archer-diffusion", "archer style"),
Model("Elden Ring", "nitrosocke/elden-ring-diffusion", "elden ring style"),
Model("Spider-Verse", "nitrosocke/spider-verse-diffusion", "spiderverse style"),
Model("Modern Disney", "nitrosocke/modern-disney-diffusion", "modern disney style"),
Model("Classic Disney", "nitrosocke/classic-anim-diffusion", "classic disney style"),
Model("Waifu", "hakurei/waifu-diffusion", ""),
Model("Pokémon", "lambdalabs/sd-pokemon-diffusers", "pokemon style"),
Model("Pokémon", "svjack/Stable-Diffusion-Pokemon-en", "pokemon style"),
Model("Pony Diffusion", "AstraliteHeart/pony-diffusion", "pony style"),
Model("Robo Diffusion", "nousr/robo-diffusion", "robo style"),
Model("Cyberpunk Anime", "DGSpitzer/Cyberpunk-Anime-Diffusion, flax/Cyberpunk-Anime-Diffusion", "cyberpunk style"),
Model("Cyberpunk Anime", "DGSpitzer/Cyberpunk-Anime-Diffusion", "cyberpunk style"),
Model("Cyberpunk Anime", "flax/Cyberpunk-Anime-Diffusion", "cyberpunk style"),
Model("Cyberware", "Eppinette/Cyberware", "cyberware"),
Model("Tron Legacy", "dallinmackay/Tron-Legacy-diffusion", "trnlgcy"),
Model("Waifu", "flax/waifu-diffusion", ""),
Model("Dark Souls", "Guizmus/DarkSoulsDiffusion", "dark souls style"),
Model("Waifu", "technillogue/waifu-diffusion", ""),
Model("Ouroborus", "Eppinette/Ouroboros", "m_ouroboros style"),
Model("Ouroborus alt", "Eppinette/Ouroboros", "m_ouroboros"),
Model("Waifu", "Eppinette/Mona", "Mona"),
Model("Waifu", "Eppinette/Mona", "Mona Woman"),
Model("Waifu", "Eppinette/Mona", "Mona Genshin"),
Model("Genshin", "Eppinette/Mona", "Mona"),
Model("Genshin", "Eppinette/Mona", "Mona Woman"),
Model("Genshin", "Eppinette/Mona", "Mona Genshin"),
Model("Space Machine", "rabidgremlin/sd-db-epic-space-machine", "EpicSpaceMachine"),
Model("Spacecraft", "rabidgremlin/sd-db-epic-space-machine", "EpicSpaceMachine"),
Model("TARDIS", "Guizmus/Tardisfusion", "Classic Tardis style"),
Model("TARDIS", "Guizmus/Tardisfusion", "Modern Tardis style"),
Model("TARDIS", "Guizmus/Tardisfusion", "Tardis Box style"),
Model("Spacecraft", "Guizmus/Tardisfusion", "Classic Tardis style"),
Model("Spacecraft", "Guizmus/Tardisfusion", "Modern Tardis style"),
Model("Spacecraft", "Guizmus/Tardisfusion", "Tardis Box style"),
Model("CLIP", "EleutherAI/clip-guided-diffusion", "CLIP"),
Model("Face Swap", "felixrosberg/face-swap", "faceswap"),
Model("Face Swap", "felixrosberg/face-swap", "faceswap with"),
Model("Face Swap", "felixrosberg/face-swap", "faceswapped"),
Model("Face Swap", "felixrosberg/face-swap", "faceswapped with"),
Model("Face Swap", "felixrosberg/face-swap", "face on"),
Model("Waifu", "Fampai/lumine_genshin_impact", "lumine_genshin"),
Model("Waifu", "Fampai/lumine_genshin_impact", "lumine"),
Model("Waifu", "Fampai/lumine_genshin_impact", "Lumine Genshin"),
Model("Waifu", "Fampai/lumine_genshin_impact", "Lumine_genshin"),
Model("Waifu", "Fampai/lumine_genshin_impact", "Lumine_Genshin"),
Model("Waifu", "Fampai/lumine_genshin_impact", "Lumine"),
Model("Genshin", "Fampai/lumine_genshin_impact", "Lumine_genshin"),
Model("Genshin", "Fampai/lumine_genshin_impact", "Lumine_Genshin"),
Model("Genshin", "Fampai/lumine_genshin_impact", "Lumine"),
Model("Genshin", "Fampai/lumine_genshin_impact", "Lumine Genshin"),
Model("Genshin", "Fampai/lumine_genshin_impact", "lumine"),
Model("Genshin", "sd-concepts-library/ganyu-genshin-impact", "Ganyu"),
Model("Genshin", "sd-concepts-library/ganyu-genshin-impact", "Ganyu Woman"),
Model("Genshin", "sd-concepts-library/ganyu-genshin-impact", "Ganyu Genshin"),
Model("Waifu", "sd-concepts-library/ganyu-genshin-impact", "Ganyu"),
Model("Waifu", "sd-concepts-library/ganyu-genshin-impact", "Ganyu Woman"),
Model("Waifu", "sd-concepts-library/ganyu-genshin-impact", "Ganyu Genshin"),
Model("Waifu", "Fampai/raiden_genshin_impact", "raiden_ei"),
Model("Waifu", "Fampai/raiden_genshin_impact", "Raiden Ei"),
Model("Waifu", "Fampai/raiden_genshin_impact", "Ei Genshin"),
Model("Waifu", "Fampai/raiden_genshin_impact", "Raiden Genshin"),
Model("Waifu", "Fampai/raiden_genshin_impact", "Raiden_Genshin"),
Model("Waifu", "Fampai/raiden_genshin_impact", "Ei_Genshin"),
Model("Waifu", "Fampai/raiden_genshin_impact", "Raiden"),
Model("Waifu", "Fampai/raiden_genshin_impact", "Ei"),
Model("Genshin", "Fampai/raiden_genshin_impact", "Raiden Ei"),
Model("Genshin", "Fampai/raiden_genshin_impact", "raiden_ei"),
Model("Genshin", "Fampai/raiden_genshin_impact", "Raiden"),
Model("Genshin", "Fampai/raiden_genshin_impact", "Raiden Genshin"),
Model("Genshin", "Fampai/raiden_genshin_impact", "Ei Genshin"),
Model("Genshin", "Fampai/raiden_genshin_impact", "Raiden_Genshin"),
Model("Genshin", "Fampai/raiden_genshin_impact", "Ei_Genshin"),
Model("Genshin", "Fampai/raiden_genshin_impact", "Ei"),
Model("Waifu", "Fampai/hutao_genshin_impact", "hutao_genshin"),
Model("Waifu", "Fampai/hutao_genshin_impact", "HuTao_Genshin"),
Model("Waifu", "Fampai/hutao_genshin_impact", "HuTao Genshin"),
Model("Waifu", "Fampai/hutao_genshin_impact", "HuTao"),
Model("Waifu", "Fampai/hutao_genshin_impact", "hutao_genshin"),
Model("Genshin", "Fampai/hutao_genshin_impact", "hutao_genshin"),
Model("Genshin", "Fampai/hutao_genshin_impact", "HuTao_Genshin"),
Model("Genshin", "Fampai/hutao_genshin_impact", "HuTao Genshin"),
Model("Genshin", "Fampai/hutao_genshin_impact", "HuTao"),
Model("Genshin", "Fampai/lumine_genshin_impact, Eppinette/Mona, sd-concepts-library/ganyu-genshin-impact, Fampai/raiden_genshin_impact, Fampai/hutao_genshin_impact", "Female"),
Model("Genshin", "Fampai/lumine_genshin_impact, Eppinette/Mona, sd-concepts-library/ganyu-genshin-impact, Fampai/raiden_genshin_impact, Fampai/hutao_genshin_impact", "female"),
Model("Genshin", "Fampai/lumine_genshin_impact, Eppinette/Mona, sd-concepts-library/ganyu-genshin-impact, Fampai/raiden_genshin_impact, Fampai/hutao_genshin_impact", "Woman"),
Model("Genshin", "Fampai/lumine_genshin_impact, Eppinette/Mona, sd-concepts-library/ganyu-genshin-impact, Fampai/raiden_genshin_impact, Fampai/hutao_genshin_impact", "woman"),
Model("Genshin", "Fampai/lumine_genshin_impact, Eppinette/Mona, sd-concepts-library/ganyu-genshin-impact, Fampai/raiden_genshin_impact, Fampai/hutao_genshin_impact", "Girl"),
Model("Genshin", "Fampai/lumine_genshin_impact, Eppinette/Mona, sd-concepts-library/ganyu-genshin-impact, Fampai/raiden_genshin_impact, Fampai/hutao_genshin_impact", "girl"),
Model("Genshin", "Fampai/lumine_genshin_impact", "Female"),
Model("Genshin", "Fampai/lumine_genshin_impact", "female"),
Model("Genshin", "Fampai/lumine_genshin_impact", "Woman"),
Model("Genshin", "Fampai/lumine_genshin_impact", "woman"),
Model("Genshin", "Fampai/lumine_genshin_impact", "Girl"),
Model("Genshin", "Fampai/lumine_genshin_impact", "girl"),
Model("Genshin", "Eppinette/Mona", "Female"),
Model("Genshin", "Eppinette/Mona", "female"),
Model("Genshin", "Eppinette/Mona", "Woman"),
Model("Genshin", "Eppinette/Mona", "woman"),
Model("Genshin", "Eppinette/Mona", "Girl"),
Model("Genshin", "Eppinette/Mona", "girl"),
Model("Genshin", "sd-concepts-library/ganyu-genshin-impact", "Female"),
Model("Genshin", "sd-concepts-library/ganyu-genshin-impact", "female"),
Model("Genshin", "sd-concepts-library/ganyu-genshin-impact", "Woman"),
Model("Genshin", "sd-concepts-library/ganyu-genshin-impact", "woman"),
Model("Genshin", "sd-concepts-library/ganyu-genshin-impact", "Girl"),
Model("Genshin", "sd-concepts-library/ganyu-genshin-impact", "girl"),
Model("Genshin", "Fampai/raiden_genshin_impact", "Female"),
Model("Genshin", "Fampai/raiden_genshin_impact", "female"),
Model("Genshin", "Fampai/raiden_genshin_impact", "Woman"),
Model("Genshin", "Fampai/raiden_genshin_impact", "woman"),
Model("Genshin", "Fampai/raiden_genshin_impact", "Girl"),
Model("Genshin", "Fampai/raiden_genshin_impact", "girl"),
Model("Genshin", "Fampai/hutao_genshin_impact", "Female"),
Model("Genshin", "Fampai/hutao_genshin_impact", "female"),
Model("Genshin", "Fampai/hutao_genshin_impact", "Woman"),
Model("Genshin", "Fampai/hutao_genshin_impact", "woman"),
Model("Genshin", "Fampai/hutao_genshin_impact", "Girl"),
Model("Genshin", "Fampai/hutao_genshin_impact", "girl"),
Model("Waifu", "crumb/genshin-stable-inversion, yuiqena/GenshinImpact, Fampai/lumine_genshin_impact, Eppinette/Mona, sd-concepts-library/ganyu-genshin-impact, Fampai/raiden_genshin_impact, Fampai/hutao_genshin_impact", "Genshin"),
Model("Waifu", "crumb/genshin-stable-inversion, yuiqena/GenshinImpact, Fampai/lumine_genshin_impact, Eppinette/Mona, sd-concepts-library/ganyu-genshin-impact, Fampai/raiden_genshin_impact, Fampai/hutao_genshin_impact", "Genshin Impact"),
Model("Genshin", "crumb/genshin-stable-inversion, yuiqena/GenshinImpact, Fampai/lumine_genshin_impact, Eppinette/Mona, sd-concepts-library/ganyu-genshin-impact, Fampai/raiden_genshin_impact, Fampai/hutao_genshin_impact", ""),
Model("Waifu", "crumb/genshin-stable-inversion", "Genshin"),
Model("Waifu", "crumb/genshin-stable-inversion", "Genshin Impact"),
Model("Genshin", "crumb/genshin-stable-inversion", ""),
Model("Waifu", "yuiqena/GenshinImpact", "Genshin"),
Model("Waifu", "yuiqena/GenshinImpact", "Genshin Impact"),
Model("Genshin", "yuiqena/GenshinImpact", ""),
Model("Waifu", "hakurei/waifu-diffusion, flax/waifu-diffusion, technillogue/waifu-diffusion", ""),
Model("Pokémon", "lambdalabs/sd-pokemon-diffusers, svjack/Stable-Diffusion-Pokemon-en", "pokemon style"),
Model("Pokémon", "lambdalabs/sd-pokemon-diffusers, svjack/Stable-Diffusion-Pokemon-en", ""),
Model("Test", "AdamoOswald1/Idk", ""),
]
last_mode = "txt2img"
current_model = models[1]
current_model_path = current_model.path
models = [
"DGSpitzer/Cyberpunk-Anime-Diffusion"
]
prompt_prefixes = {
models[0]: "dgs illustration style "
}
current_model = models[0]
model_id = "CompVis/stable-diffusion-v1-4"
device = "cuda"
#If you are running this code locally, you need to either do a 'huggingface-cli login` or paste your User Access Token from here https://huggingface.co/settings/tokens into the use_auth_token field below.
#pipe = StableDiffusionPipeline.from_pretrained(model_id, use_auth_token=True, revision="fp16", torch_dtype=torch.float16)
#pipe = pipe.to(device)
#torch.backends.cudnn.benchmark = True
#auth_token = os.environ.get("test") or True
#pipe = StableDiffusionPipeline.from_pretrained(current_model, use_auth_token=auth_token, torch_dtype=torchfloat, revision="fp16")
#model_id = "hakurei/waifu-diffusion"
pipe = StableDiffusionPipeline.from_pretrained("hakurei/waifu-diffusion", torch_type=torch.float16, revision="fp16")
pipe = StableDiffusionPipeline.from_pretrained(current_model, torch_dtype=torchfloat, revision="fp16")
gpt2_pipe = pipeline('text-generation', model='Gustavosta/MagicPrompt-Stable-Diffusion', tokenizer='gpt2')
pipe = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", use_auth_token=True, revision="fp16", torch_dtype=torch.float16).to("cuda")
pipe = StableDiffusionPipeline.from_pretrained(current_model.path, torch_dtype=torch.float16)
pipeline = DiffusionPipeline.from_pretrained("flax/waifu-diffusion")
pipeline = DiffusionPipeline.from_pretrained("flax/Cyberpunk-Anime-Diffusion")
pipeline = DiffusionPipeline.from_pretrained("technillogue/waifu-diffusion")
pipeline = DiffusionPipeline.from_pretrained("svjack/Stable-Diffusion-Pokemon-en")
pipeline = DiffusionPipeline.from_pretrained("AdamOswald1/Idk")
# pipe_i2i = StableDiffusionImg2ImgPipeline.from_pretrained(current_model.path, torch_dtype=torch.float16)
with open("ideas.txt", "r") as f:
line = f.readlines()
if torch.cuda.is_available():
pipe = pipe.to("cuda")
# pipe_i2i = pipe_i2i.to("cuda")
else:
pipe = pipe.to("cpu")
device = "GPU 🔥" if torch.cuda.is_available() else "CPU 🥶"
#torch.backends.cudnn.benchmark = True
num_samples = 2
is_gpu_busy = False
def on_model_change(model):
global current_model
global pipe
if model != current_model:
current_model = model
pipe = StableDiffusionPipeline.from_pretrained(current_model, torch_dtype=torchfloat)
if torch.cuda.is_available():
pipe = pipe.to("cuda")
def inference(prompt, guidance, steps):
promptPrev = prompt
prompt = prompt_prefixes[current_model] + prompt
image = pipe(prompt, num_inference_steps=int(steps), guidance_scale=guidance, width=512, height=512).images[0]
return image, gr.update(visible=True), gr.update(visible=True), gr.update(visible=True), gr.update(placeholder=promptPrev)
def inference_example(prompt, guidance, steps):
prompt = prompt_prefixes[current_model] + prompt
image = pipe(prompt, num_inference_steps=int(steps), guidance_scale=guidance, width=512, height=512).images[0]
return image
def infer(prompt):
images = pipe([prompt] * num_samples, guidance_scale=7.5)["sample"]
global is_gpu_busy
samples = 4
steps = 50
scale = 7.5
#generator = torch.Generator(device=device).manual_seed(seed)
#print("Is GPU busy? ", is_gpu_busy)
images = []
#if(not is_gpu_busy):
# is_gpu_busy = True
# images_list = pipe(
# [prompt] * samples,
# num_inference_steps=steps,
# guidance_scale=scale,
#generator=generator,
# )
# is_gpu_busy = False
# for i, image in enumerate(images_list["sample"]):
# images.append(image)
#else:
url = os.getenv('JAX_BACKEND_URL')
payload = {'prompt': prompt}
images_request = requests.post(url, json = payload)
for image in images_request.json()["images"]:
image_b64 = (f"data:image/jpeg;base64,{image}")
images.append(image_b64)
return images
def generate(starting_text):
seed = random.randint(100, 1000000)
set_seed(seed)
if starting_text == "":
starting_text: str = line[random.randrange(0, len(line))].replace("\n", "").lower().capitalize()
starting_text: str = re.sub(r"[,:\-–.!;?_]", '', starting_text)
response = gpt2_pipe(starting_text, max_length=(len(starting_text) + random.randint(60, 90)), num_return_sequences=4)
response_list = []
for x in response:
resp = x['generated_text'].strip()
if resp != starting_text and len(resp) > (len(starting_text) + 4) and resp.endswith((":", "-", "—")) is False:
response_list.append(resp+'\n')
response_end = "\n".join(response_list)
response_end = re.sub('[^ ]+\.[^ ]+','', response_end)
response_end = response_end.replace("<", "").replace(">", "")
if response_end != "":
return response_end
def load_learned_embed_in_clip(learned_embeds_path, text_encoder, tokenizer, token=None):
loaded_learned_embeds = torch.load(learned_embeds_path, map_location="cpu")
# separate token and the embeds
trained_token = list(loaded_learned_embeds.keys())[0]
embeds = loaded_learned_embeds[trained_token]
# cast to dtype of text_encoder
dtype = text_encoder.get_input_embeddings().weight.dtype
# add the token in tokenizer
token = token if token is not None else trained_token
num_added_tokens = tokenizer.add_tokens(token)
i = 1
while(num_added_tokens == 0):
print(f"The tokenizer already contains the token {token}.")
token = f"{token[:-1]}-{i}>"
print(f"Attempting to add the token {token}.")
num_added_tokens = tokenizer.add_tokens(token)
i+=1
# resize the token embeddings
text_encoder.resize_token_embeddings(len(tokenizer))
# get the id for the token and assign the embeds
token_id = tokenizer.convert_tokens_to_ids(token)
text_encoder.get_input_embeddings().weight.data[token_id] = embeds
return token
print("Setting up the public library")
for model in models_list:
model_content = {}
model_id = model.modelId
model_content["id"] = model_id
embeds_url = f"https://huggingface.co/{model_id}/resolve/main/learned_embeds.bin"
os.makedirs(model_id,exist_ok = True)
if not os.path.exists(f"{model_id}/learned_embeds.bin"):
try:
wget.download(embeds_url, out=model_id)
except:
continue
token_identifier = f"https://huggingface.co/{model_id}/raw/main/token_identifier.txt"
response = requests.get(token_identifier)
token_name = response.text
concept_type = f"https://huggingface.co/{model_id}/raw/main/type_of_concept.txt"
response = requests.get(concept_type)
concept_name = response.text
model_content["concept_type"] = concept_name
images = []
for i in range(4):
url = f"https://huggingface.co/{model_id}/resolve/main/concept_images/{i}.jpeg"
image_download = requests.get(url)
url_code = image_download.status_code
if(url_code == 200):
file = open(f"{model_id}/{i}.jpeg", "wb") ## Creates the file for image
file.write(image_download.content) ## Saves file content
file.close()
images.append(f"{model_id}/{i}.jpeg")
model_content["images"] = images
#if token cannot be loaded, skip it
try:
learned_token = load_learned_embed_in_clip(f"{model_id}/learned_embeds.bin", pipe.text_encoder, pipe.tokenizer, token_name)
except:
continue
model_content["token"] = learned_token
models.append(model_content)
#@title Run the app to navigate around [the Library](https://huggingface.co/sd-concepts-library)
#@markdown Click the `Running on public URL:` result to run the Gradio app
SELECT_LABEL = "Select concept"
def assembleHTML(model):
html_gallery = ''
html_gallery = html_gallery+'''
<div class="flex gr-gap gr-form-gap row gap-4 w-full flex-wrap" id="main_row">
'''
cap = 0
for model in models:
html_gallery = html_gallery+f'''
<div class="gr-block gr-box relative w-full overflow-hidden border-solid border border-gray-200 gr-panel">
<div class="output-markdown gr-prose" style="max-width: 100%;">
<h3>
<a href="https://huggingface.co/{model["id"]}" target="_blank">
<code>{html.escape(model["token"])}</code>
</a>
</h3>
</div>
<div id="gallery" class="gr-block gr-box relative w-full overflow-hidden border-solid border border-gray-200">
<div class="wrap svelte-17ttdjv opacity-0"></div>
<div class="absolute left-0 top-0 py-1 px-2 rounded-br-lg shadow-sm text-xs text-gray-500 flex items-center pointer-events-none bg-white z-20 border-b border-r border-gray-100 dark:bg-gray-900">
<span class="mr-2 h-[12px] w-[12px] opacity-80">
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="feather feather-image">
<rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
<circle cx="8.5" cy="8.5" r="1.5"></circle>
<polyline points="21 15 16 10 5 21"></polyline>
</svg>
</span> {model["concept_type"]}
</div>
<div class="overflow-y-auto h-full p-2" style="position: relative;">
<div class="grid gap-2 grid-cols-2 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-2 xl:grid-cols-2 2xl:grid-cols-2 svelte-1g9btlg pt-6">
'''
for image in model["images"]:
html_gallery = html_gallery + f'''
<button class="gallery-item svelte-1g9btlg">
<img alt="" loading="lazy" class="h-full w-full overflow-hidden object-contain" src="file/{image}">
</button>
'''
html_gallery = html_gallery+'''
</div>
<iframe style="display: block; position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow: hidden; border: 0; opacity: 0; pointer-events: none; z-index: -1;" aria-hidden="true" tabindex="-1" src="about:blank"></iframe>
</div>
</div>
</div>
'''
cap += 1
if(cap == 99):
break
html_gallery = html_gallery+'''
</div>
'''
return html_gallery
def title_block(title, id):
return gr.Markdown(f"### [`{title}`](https://huggingface.co/{id})")
def image_block(image_list, concept_type):
return gr.Gallery(
label=concept_type, value=image_list, elem_id="gallery"
).style(grid=[2], height="auto")
def checkbox_block():
checkbox = gr.Checkbox(label=SELECT_LABEL).style(container=False)
return checkbox
def infer(text):
with autocast("cuda"):
images_list = pipe(
[text]*2,
num_inference_steps=50,
guidance_scale=7.5
)
output_images = []
for i, image in enumerate(images_list["sample"]):
output_images.append(image)
return output_images, gr.update(visible=True), gr.update(visible=True), gr.update(visible=True)
# idetnical to `infer` function without gradio state updates for share btn
def infer_examples(text):
with autocast("cuda"):
images_list = pipe(
[text]*2,
num_inference_steps=50,
guidance_scale=7.5
)
output_images = []
for i, image in enumerate(images_list["sample"]):
output_images.append(image)
return output_images
txt = grad.Textbox(lines=1, label="Initial Text", placeholder="English Text here")
out = grad.Textbox(lines=4, label="Generated Prompts")
examples = []
for x in range(8):
examples.append(line[random.randrange(0, len(line))].replace("\n", "").lower().capitalize())
def custom_model_changed(path):
models[0].path = path
global current_model
current_model = models[0]
def inference(model_name, prompt, guidance, steps, width=512, height=512, seed=0, img=None, strength=0.5, neg_prompt=""):
global current_model
for model in models:
if model.name == model_name:
current_model = model
model_path = current_model.path
generator = torch.Generator('cuda').manual_seed(seed) if seed != 0 else None
if img is not None:
return img_to_img(model_path, prompt, neg_prompt, img, strength, guidance, steps, width, height, generator)
else:
return txt_to_img(model_path, prompt, neg_prompt, guidance, steps, width, height, generator)
def txt_to_img(model_path, prompt, neg_prompt, guidance, steps, width, height, generator=None):
global last_mode
global pipe
global current_model_path
if model_path != current_model_path or last_mode != "txt2img":
current_model_path = model_path
pipe = StableDiffusionPipeline.from_pretrained(current_model_path, torch_dtype=torch.float16)
if torch.cuda.is_available():
pipe = pipe.to("cuda")
last_mode = "txt2img"
prompt = current_model.prefix + prompt
result = pipe(
prompt,
negative_prompt = neg_prompt,
# num_images_per_prompt=n_images,
num_inference_steps = int(steps),
guidance_scale = guidance,
width = width,
height = height,
generator = generator)
def img_to_img(model_path, prompt, neg_prompt, img, strength, guidance, steps, width, height, generator=None):
global last_mode
global pipe
global current_model_path
if model_path != current_model_path or last_mode != "img2img":
current_model_path = model_path
pipe = StableDiffusionImg2ImgPipeline.from_pretrained(current_model_path, torch_dtype=torch.float16)
if torch.cuda.is_available():
pipe = pipe.to("cuda")
last_mode = "img2img"
prompt = current_model.prefix + prompt
ratio = min(height / img.height, width / img.width)
img = img.resize((int(img.width * ratio), int(img.height * ratio)), Image.LANCZOS)
result = pipe(
prompt,
negative_prompt = neg_prompt,
# num_images_per_prompt=n_images,
init_image = img,
num_inference_steps = int(steps),
strength = strength,
guidance_scale = guidance,
width = width,
height = height,
generator = generator)
def get_images(prompt):
gallery_dir = stable_diffusion(prompt, fn_index=2)
sd_output = [os.path.join(gallery_dir, image) for image in os.listdir(gallery_dir)]
return sd_output, gr.update(visible=True), gr.update(visible=True), gr.update(visible=True)
def get_prompts(uploaded_image):
return img_to_text(uploaded_image, fn_index=1)[0]
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect(DB_FILE)
db.row_factory = sqlite3.Row
return db
@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
if db is not None:
db.close()
def update_repository():
repo.git_pull()
# copy db on db to local path
shutil.copyfile(DB_FILE, "./data/data.db")
with sqlite3.connect("./data/data.db") as db:
db.row_factory = sqlite3.Row
palettes = db.execute("SELECT * FROM palettes").fetchall()
data = [{'id': row['id'], 'data': json.loads(
row['data']), 'created_at': row['created_at']} for row in palettes]
with open('./data/data.json', 'w') as f:
json.dump(data, f, separators=(',', ':'))
print("Updating repository")
subprocess.Popen(
"git add . && git commit --amend -m 'update' && git push --force", cwd="./data", shell=True)
repo.push_to_hub(blocking=False)
@app.route('/')
def index():
return app.send_static_file('index.html')
@app.route('/force_push')
def push():
if (request.headers['token'] == TOKEN):
update_repository()
return jsonify({'success': True})
else:
return "Error", 401
def getAllData():
palettes = get_db().execute("SELECT * FROM palettes").fetchall()
data = [{'id': row['id'], 'data': json.loads(
row['data']), 'created_at': row['created_at']} for row in palettes]
return data
@app.route('/data')
def getdata():
return jsonify(getAllData())
@app.route('/new_palette', methods=['POST'])
@expects_json(schema)
def create():
data = g.data
db = get_db()
cursor = db.cursor()
cursor.execute("INSERT INTO palettes(data) VALUES (?)", [json.dumps(data)])
db.commit()
return jsonify(getAllData())
@app.errorhandler(400)
def bad_request(error):
if isinstance(error.description, ValidationError):
original_error = error.description
return jsonify({'error': original_error.message}), 400
return error
if __name__ == '__main__':
if not IS_DEV:
print("Starting scheduler -- Running Production")
scheduler = APScheduler()
scheduler.add_job(id='Update Dataset Repository',
func=update_repository, trigger='interval', hours=1)
scheduler.start()
else:
print("Not Starting scheduler -- Running Development")
app.run(host='0.0.0.0', port=int(
os.environ.get('PORT', 7860)), debug=True, use_reloader=IS_DEV)
title = "Stable Diffusion Prompt Generator"
description = 'This is a demo of the model series: "MagicPrompt", in this case, aimed at: "Stable Diffusion". To use it, simply submit your text or click on one of the examples. To learn more about the model, [click here](https://huggingface.co/Gustavosta/MagicPrompt-Stable-Diffusion).<br>'
grad.Interface(fn=generate,
inputs=txt,
outputs=out,
examples=examples,
title=title,
description=description,
article='',
allow_flagging='never',
cache_examples=False,
theme="default").launch(enable_queue=True, debug=True)
css = """
.animate-spin {
animation: spin 1s linear infinite;
}
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
#share-btn-container {
display: flex; padding-left: 0.5rem !important; padding-right: 0.5rem !important; background-color: #000000; justify-content: center; align-items: center; border-radius: 9999px !important; width: 13rem;
}
#share-btn {
all: initial; color: #ffffff;font-weight: 600; cursor:pointer; font-family: 'IBM Plex Sans', sans-serif; margin-left: 0.5rem !important; padding-top: 0.25rem !important; padding-bottom: 0.25rem !important;
}
#share-btn * {
all: unset;
}
#share-btn-container div:nth-child(-n+2){
width: auto !important;
min-height: 0px !important;
}
#share-btn-container .wrap {
display: none !important;
}
a {text-decoration-line: underline;}
<style>
.finetuned-diffusion-div {
text-align: center;
max-width: 700px;
margin: 0 auto;
}
.finetuned-diffusion-div div {
display: inline-flex;
align-items: center;
gap: 0.8rem;
font-size: 1.75rem;
}
.finetuned-diffusion-div div h1 {
font-weight: 900;
margin-bottom: 7px;
}
.finetuned-diffusion-div p {
margin-bottom: 10px;
font-size: 94%;
}
.finetuned-diffusion-div p a {
text-decoration: underline;
}
.tabs {
margin-top: 0px;
margin-bottom: 0px;
}
#gallery {
min-height: 20rem;
}
</style>
.gradio-container {font-family: 'IBM Plex Sans', sans-serif}
#top_title{margin-bottom: .5em}
#top_title h2{margin-bottom: 0; text-align: center}
/*#main_row{flex-wrap: wrap; gap: 1em; max-height: 550px; overflow-y: scroll; flex-direction: row}*/
#component-3{height: 760px; overflow: auto}
#component-9{position: sticky;top: 0;align-self: flex-start;}
@media (min-width: 768px){#main_row > div{flex: 1 1 32%; margin-left: 0 !important}}
.gr-prose code::before, .gr-prose code::after {content: "" !important}
::-webkit-scrollbar {width: 10px}
::-webkit-scrollbar-track {background: #f1f1f1}
::-webkit-scrollbar-thumb {background: #888}
::-webkit-scrollbar-thumb:hover {background: #555}
.gr-button {white-space: nowrap}
.gr-button:focus {
border-color: rgb(147 197 253 / var(--tw-border-opacity));
outline: none;
box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000);
--tw-border-opacity: 1;
--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px var(--tw-ring-offset-width)) var(--tw-ring-color);
--tw-ring-color: rgb(191 219 254 / var(--tw-ring-opacity));
--tw-ring-opacity: .5;
}
#prompt_input{flex: 1 3 auto; width: auto !important;}
#prompt_area{margin-bottom: .75em}
#prompt_area > div:first-child{flex: 1 3 auto}
.animate-spin {
animation: spin 1s linear infinite;
}
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
#share-btn-container {
display: flex; padding-left: 0.5rem !important; padding-right: 0.5rem !important; background-color: #000000; justify-content: center; align-items: center; border-radius: 9999px !important; width: 13rem;
}
#share-btn {
all: initial; color: #ffffff;font-weight: 600; cursor:pointer; font-family: 'IBM Plex Sans', sans-serif; margin-left: 0.5rem !important; padding-top: 0.25rem !important; padding-bottom: 0.25rem !important;
}
#share-btn * {
all: unset;
}
#col-container {max-width: 700px; margin-left: auto; margin-right: auto;}
a {text-decoration-line: underline; font-weight: 600;}
.animate-spin {
animation: spin 1s linear infinite;
}
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
#share-btn-container {
display: flex; padding-left: 0.5rem !important; padding-right: 0.5rem !important; background-color: #000000; justify-content: center; align-items: center; border-radius: 9999px !important; width: 13rem;
}
#share-btn {
all: initial; color: #ffffff;font-weight: 600; cursor:pointer; font-family: 'IBM Plex Sans', sans-serif; margin-left: 0.5rem !important; padding-top: 0.25rem !important; padding-bottom: 0.25rem !important;right:0;
}
#share-btn * {
all: unset;
}
#share-btn-container div:nth-child(-n+2){
width: auto !important;
min-height: 0px !important;
}
#share-btn-container .wrap {
display: none !important;
}
.gradio-container
font-family: 'IBM Plex Sans', sans-serif;
}
.gr-button {
color: white;
border-color: black;
background: black;
}
input[type='range'] {
accent-color: black;
}
.dark input[type='range'] {
accent-color: #dfdfdf;
}
.container {
max-width: 730px;
margin: auto;
padding-top: 1.5rem;
}
#gallery {
min-height: 22rem;
margin-bottom: 15px;
margin-left: auto;
margin-right: auto;
border-bottom-right-radius: .5rem !important;
border-bottom-left-radius: .5rem !important;
}
#gallery>div>.h-full {
min-height: 20rem;
}
.details:hover {
text-decoration: underline;
}
.gr-button {
white-space: nowrap;
}
.gr-button:focus {
border-color: rgb(147 197 253 / var(--tw-border-opacity));
outline: none;
box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000);
--tw-border-opacity: 1;
--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px var(--tw-ring-offset-width)) var(--tw-ring-color);
--tw-ring-color: rgb(191 219 254 / var(--tw-ring-opacity));
--tw-ring-opacity: .5;
}
#advanced-btn {
font-size: .7rem !important;
line-height: 19px;
margin-top: 12px;
margin-bottom: 12px;
padding: 2px 8px;
border-radius: 14px !important;
}
#advanced-options {
display: none;
margin-bottom: 20px;
}
.footer {
margin-bottom: 45px;
margin-top: 35px;
text-align: center;
border-bottom: 1px solid #e5e5e5;
}
.footer>p {
font-size: .8rem;
display: inline-block;
padding: 0 10px;
transform: translateY(10px);
background: white;
}
.dark .footer {
border-color: #303030;
}
.dark .footer>p {
background: #0b0f19;
}
.acknowledgments h4{
margin: 1.25em 0 .25em 0;
font-weight: bold;
font-size: 115%;
}
#container-advanced-btns{
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-items: center;
}