Spaces:
Running
Running
Upload 5 files
Browse files- README.md +14 -12
- all_models.py +130 -0
- app.py +672 -0
- blacklist.py +35 -0
- externalmod.py +584 -0
README.md
CHANGED
@@ -1,12 +1,14 @@
|
|
1 |
-
---
|
2 |
-
title:
|
3 |
-
emoji:
|
4 |
-
colorFrom:
|
5 |
-
colorTo:
|
6 |
-
sdk: gradio
|
7 |
-
sdk_version: 4.
|
8 |
-
app_file: app.py
|
9 |
-
pinned: false
|
10 |
-
|
11 |
-
|
12 |
-
|
|
|
|
|
|
1 |
+
---
|
2 |
+
title: TestDifs (Gradio 4.x)
|
3 |
+
emoji: 🛕🛕
|
4 |
+
colorFrom: green
|
5 |
+
colorTo: blue
|
6 |
+
sdk: gradio
|
7 |
+
sdk_version: 4.42.0
|
8 |
+
app_file: app.py
|
9 |
+
pinned: false
|
10 |
+
duplicated_from: DemiPoto/TestDifs
|
11 |
+
short_description: TestDifs
|
12 |
+
---
|
13 |
+
|
14 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
all_models.py
ADDED
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from blacklist import bad_tags,bad_models,fav_models
|
2 |
+
models = []
|
3 |
+
models_plus_tags=[]
|
4 |
+
tags_plus_models=[]
|
5 |
+
|
6 |
+
|
7 |
+
def list_uniq(l):
|
8 |
+
return sorted(set(l), key=l.index)
|
9 |
+
|
10 |
+
def find_model_list(author: str="", tags: list[str]=[], not_tag="", sort: str="last_modified", limit: int=30, force_gpu=False, check_status=False, bad_models=bad_models):
|
11 |
+
from huggingface_hub import HfApi
|
12 |
+
api = HfApi()
|
13 |
+
default_tags = ["diffusers"]
|
14 |
+
if not sort: sort = "last_modified"
|
15 |
+
models = []
|
16 |
+
models_plus_tags=[]
|
17 |
+
try:
|
18 |
+
model_infos = api.list_models(author=author, task="text-to-image",
|
19 |
+
tags=list_uniq(default_tags + tags), cardData=True, sort=sort, limit=limit)
|
20 |
+
except Exception as e:
|
21 |
+
print(f"Error: Failed to list models.")
|
22 |
+
print(e)
|
23 |
+
return models
|
24 |
+
for model in model_infos:
|
25 |
+
|
26 |
+
if not model.private and not model.gated:
|
27 |
+
loadable = True
|
28 |
+
if not_tag and not_tag in model.tags or not loadable: continue
|
29 |
+
if model.id not in bad_models :
|
30 |
+
models.append(model.id)
|
31 |
+
#models_plus_tags.append([model.id,process_tags(model.tags)])
|
32 |
+
models_plus_tags.append([model.id,process_tags(model.cardData.tags)])
|
33 |
+
if len(models) == limit: break
|
34 |
+
return models , models_plus_tags
|
35 |
+
|
36 |
+
def process_tags(tags,bad_tags=bad_tags):
|
37 |
+
t1=True
|
38 |
+
new_tags=[]
|
39 |
+
for tag in tags:
|
40 |
+
if tag not in bad_tags:
|
41 |
+
if tag == 'en':
|
42 |
+
t1=False
|
43 |
+
if t1 :
|
44 |
+
new_tags.append(tag)
|
45 |
+
return new_tags
|
46 |
+
|
47 |
+
def clas_tags(models_plus_tags,min):
|
48 |
+
tags_plus_models=[]
|
49 |
+
listTemp=[]
|
50 |
+
listAllModels=['all',0,[]]
|
51 |
+
new_tag=True
|
52 |
+
for ent in models_plus_tags:
|
53 |
+
listAllModels[1]+=1
|
54 |
+
listAllModels[2].append(ent[0])
|
55 |
+
for tagClas in ent[1]:
|
56 |
+
new_tag=True
|
57 |
+
for tag in listTemp:
|
58 |
+
if tag[0] == tagClas:
|
59 |
+
tag[1]+=1
|
60 |
+
tag[2].append(ent[0])
|
61 |
+
new_tag=False
|
62 |
+
if new_tag:
|
63 |
+
listTemp.append([tagClas,1,[ent[0]]])
|
64 |
+
tags_plus_models.append(listAllModels)
|
65 |
+
for t in listTemp:
|
66 |
+
if t[1]>=min and t[1]!=len(models_plus_tags):
|
67 |
+
tags_plus_models.append(t)
|
68 |
+
return tags_plus_models
|
69 |
+
|
70 |
+
def orga_tag(tags_plus_models):
|
71 |
+
output=[]
|
72 |
+
while(len(output)<len(tags_plus_models)):
|
73 |
+
max=0
|
74 |
+
for tag in tags_plus_models:
|
75 |
+
if tag[1]>max:
|
76 |
+
if tag not in output:
|
77 |
+
max=tag[1]
|
78 |
+
tagMax=tag
|
79 |
+
output.append(tagMax)
|
80 |
+
return output
|
81 |
+
def tag_new(models,limit=40):
|
82 |
+
output=["NEW",0,[]]
|
83 |
+
if limit>len(models):
|
84 |
+
limit=len(models)
|
85 |
+
for i in range(limit):
|
86 |
+
output[1]+=1
|
87 |
+
output[2].append(models[i])
|
88 |
+
return output
|
89 |
+
|
90 |
+
def tag_fav(models=models,fav_models=fav_models):
|
91 |
+
output=["FAV",0,[]]
|
92 |
+
for m in fav_models:
|
93 |
+
if m in models:
|
94 |
+
output[1]+=1
|
95 |
+
output[2].append(m)
|
96 |
+
return output
|
97 |
+
|
98 |
+
def update_tag(models_plus_tags,list_new_tag):
|
99 |
+
for m_new in list_new_tag[2]:
|
100 |
+
for m in models_plus_tags:
|
101 |
+
if m_new == m[0]:
|
102 |
+
m[1].append(list_new_tag[0])
|
103 |
+
return models_plus_tags
|
104 |
+
|
105 |
+
|
106 |
+
from operator import itemgetter
|
107 |
+
|
108 |
+
#models = find_model_list("Yntec", [], "", "last_modified", 20)
|
109 |
+
models , models_plus_tags = find_model_list("John6666", ["stable-diffusion-xl"], "", "last_modified", 40)
|
110 |
+
#tags_plus_models = orga_tag(clas_tags(models_plus_tags,2))
|
111 |
+
tags_plus_models = orga_tag(clas_tags(sorted(models_plus_tags, key=itemgetter(0)),2))
|
112 |
+
list_new=tag_new(models,40)
|
113 |
+
models_plus_tags=update_tag(models_plus_tags,list_new)
|
114 |
+
tags_plus_models.insert(1,list_new)
|
115 |
+
list_fav=tag_fav()
|
116 |
+
if list_fav[1]>0:
|
117 |
+
tags_plus_models.insert(1,list_fav)
|
118 |
+
models_plus_tags=update_tag(models_plus_tags,list_fav)
|
119 |
+
|
120 |
+
#models.extend(find_model_list("John6666", ["stable-diffusion-xl"], "", "last_modified", 200))
|
121 |
+
|
122 |
+
#models.extend(find_model_list("John6666", [], "", "last_modified", 20)) # The latest 20 models will be added to the models written above.
|
123 |
+
|
124 |
+
# Examples:
|
125 |
+
#models = ['yodayo-ai/kivotos-xl-2.0', 'yodayo-ai/holodayo-xl-2.1'] # specific models
|
126 |
+
#models = find_model_list("Yntec", [], "", "last_modified", 20) # Yntec's latest 20 models
|
127 |
+
#models = find_model_list("Yntec", ["anime"], "", "last_modified", 20) # Yntec's latest 20 models with 'anime' tag
|
128 |
+
#models = find_model_list("Yntec", [], "anime", "last_modified", 20) # Yntec's latest 20 models without 'anime' tag
|
129 |
+
#models = find_model_list("", [], "", "last_modified", 20) # latest 20 text-to-image models of huggingface
|
130 |
+
#models = find_model_list("", [], "", "downloads", 20) # monthly most downloaded 20 text-to-image models of huggingface
|
app.py
ADDED
@@ -0,0 +1,672 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import gradio as gr
|
3 |
+
from random import randint
|
4 |
+
from operator import itemgetter
|
5 |
+
import bisect
|
6 |
+
from all_models import tags_plus_models,models,models_plus_tags
|
7 |
+
from datetime import datetime
|
8 |
+
from externalmod import gr_Interface_load
|
9 |
+
import asyncio
|
10 |
+
import os
|
11 |
+
from threading import RLock
|
12 |
+
lock = RLock()
|
13 |
+
HF_TOKEN = os.environ.get("HF_TOKEN") if os.environ.get("HF_TOKEN") else None # If private or gated models aren't used, ENV setting is unnecessary.
|
14 |
+
|
15 |
+
|
16 |
+
now2 = 0
|
17 |
+
inference_timeout = 300
|
18 |
+
MAX_SEED = 2**32-1
|
19 |
+
|
20 |
+
|
21 |
+
nb_rep=2
|
22 |
+
nb_mod_dif=20
|
23 |
+
nb_models=nb_mod_dif*nb_rep
|
24 |
+
|
25 |
+
cache_image={}
|
26 |
+
cache_image_actu={}
|
27 |
+
|
28 |
+
def split_models(models,nb_models):
|
29 |
+
models_temp=[]
|
30 |
+
models_lis_temp=[]
|
31 |
+
i=0
|
32 |
+
for m in models:
|
33 |
+
models_temp.append(m)
|
34 |
+
i=i+1
|
35 |
+
if i%nb_models==0:
|
36 |
+
models_lis_temp.append(models_temp)
|
37 |
+
models_temp=[]
|
38 |
+
if len(models_temp)>1:
|
39 |
+
models_lis_temp.append(models_temp)
|
40 |
+
return models_lis_temp
|
41 |
+
|
42 |
+
def split_models_axb(models,a,b):
|
43 |
+
models_temp=[]
|
44 |
+
models_lis_temp=[]
|
45 |
+
i=0
|
46 |
+
nb_models=b
|
47 |
+
for m in models:
|
48 |
+
for j in range(a):
|
49 |
+
models_temp.append(m)
|
50 |
+
i=i+1
|
51 |
+
if i%nb_models==0:
|
52 |
+
models_lis_temp.append(models_temp)
|
53 |
+
models_temp=[]
|
54 |
+
if len(models_temp)>1:
|
55 |
+
models_lis_temp.append(models_temp)
|
56 |
+
return models_lis_temp
|
57 |
+
|
58 |
+
def split_models_8x3(models,nb_models):
|
59 |
+
models_temp=[]
|
60 |
+
models_lis_temp=[]
|
61 |
+
i=0
|
62 |
+
nb_models_x3=8
|
63 |
+
for m in models:
|
64 |
+
models_temp.append(m)
|
65 |
+
i=i+1
|
66 |
+
if i%nb_models_x3==0:
|
67 |
+
models_lis_temp.append(models_temp+models_temp+models_temp)
|
68 |
+
models_temp=[]
|
69 |
+
if len(models_temp)>1:
|
70 |
+
models_lis_temp.append(models_temp+models_temp+models_temp)
|
71 |
+
return models_lis_temp
|
72 |
+
|
73 |
+
def construct_list_models(tags_plus_models,nb_rep,nb_mod_dif):
|
74 |
+
list_temp=[]
|
75 |
+
output=[]
|
76 |
+
for tag_plus_models in tags_plus_models:
|
77 |
+
list_temp=split_models_axb(tag_plus_models[2],nb_rep,nb_mod_dif)
|
78 |
+
list_temp2=[]
|
79 |
+
i=0
|
80 |
+
for elem in list_temp:
|
81 |
+
list_temp2.append([f"{tag_plus_models[0]}_{i+1}/{len(list_temp)} ({len(elem)}) : {elem[0]} - {elem[len(elem)-1]}" ,elem])
|
82 |
+
i+=1
|
83 |
+
output.append([f"{tag_plus_models[0]} ({tag_plus_models[1]})",list_temp2])
|
84 |
+
tag_plus_models[0]=f"{tag_plus_models[0]} ({tag_plus_models[1]})"
|
85 |
+
return output
|
86 |
+
|
87 |
+
models_test = []
|
88 |
+
models_test = construct_list_models(tags_plus_models,nb_rep,nb_mod_dif)
|
89 |
+
|
90 |
+
def get_current_time():
|
91 |
+
now = datetime.now()
|
92 |
+
now2 = now
|
93 |
+
current_time = now2.strftime("%Y-%m-%d %H:%M:%S")
|
94 |
+
kii = "" # ?
|
95 |
+
ki = f'{kii} {current_time}'
|
96 |
+
return ki
|
97 |
+
|
98 |
+
def load_fn_original(models):
|
99 |
+
global models_load
|
100 |
+
global num_models
|
101 |
+
global default_models
|
102 |
+
models_load = {}
|
103 |
+
num_models = len(models)
|
104 |
+
if num_models!=0:
|
105 |
+
default_models = models[:num_models]
|
106 |
+
else:
|
107 |
+
default_models = {}
|
108 |
+
for model in models:
|
109 |
+
if model not in models_load.keys():
|
110 |
+
try:
|
111 |
+
m = gr.load(f'models/{model}')
|
112 |
+
except Exception as error:
|
113 |
+
m = gr.Interface(lambda txt: None, ['text'], ['image'])
|
114 |
+
print(error)
|
115 |
+
models_load.update({model: m})
|
116 |
+
|
117 |
+
def load_fn(models):
|
118 |
+
global models_load
|
119 |
+
global num_models
|
120 |
+
global default_models
|
121 |
+
models_load = {}
|
122 |
+
num_models = len(models)
|
123 |
+
i=0
|
124 |
+
if num_models!=0:
|
125 |
+
default_models = models[:num_models]
|
126 |
+
else:
|
127 |
+
default_models = {}
|
128 |
+
for model in models:
|
129 |
+
i+=1
|
130 |
+
if i%50==0:
|
131 |
+
print("\n\n\n-------"+str(i)+'/'+str(len(models))+"-------\n\n\n")
|
132 |
+
if model not in models_load.keys():
|
133 |
+
try:
|
134 |
+
m = gr_Interface_load(f'models/{model}', hf_token=HF_TOKEN)
|
135 |
+
except Exception as error:
|
136 |
+
m = gr.Interface(lambda txt: None, ['text'], ['image'])
|
137 |
+
print(error)
|
138 |
+
models_load.update({model: m})
|
139 |
+
|
140 |
+
|
141 |
+
"""models = models_test[1]"""
|
142 |
+
#load_fn_original
|
143 |
+
load_fn(models)
|
144 |
+
"""models = {}
|
145 |
+
load_fn(models)"""
|
146 |
+
|
147 |
+
|
148 |
+
def extend_choices(choices):
|
149 |
+
return choices + (nb_models - len(choices)) * ['NA']
|
150 |
+
"""return choices + (num_models - len(choices)) * ['NA']"""
|
151 |
+
|
152 |
+
def extend_choices_b(choices):
|
153 |
+
choices_plus = extend_choices(choices)
|
154 |
+
return [gr.Textbox(m, visible=False) for m in choices_plus]
|
155 |
+
|
156 |
+
def update_imgbox(choices):
|
157 |
+
choices_plus = extend_choices(choices)
|
158 |
+
return [gr.Image(None, label=m,interactive=False, visible=(m != 'NA'),show_share_button=False) for m in choices_plus]
|
159 |
+
|
160 |
+
def choice_group_a(group_model_choice):
|
161 |
+
return group_model_choice
|
162 |
+
|
163 |
+
def choice_group_b(group_model_choice):
|
164 |
+
choiceTemp =choice_group_a(group_model_choice)
|
165 |
+
choiceTemp = extend_choices(choiceTemp)
|
166 |
+
"""return [gr.Image(label=m, min_width=170, height=170) for m in choice]"""
|
167 |
+
return [gr.Image(None, label=m,interactive=False, visible=(m != 'NA'),show_share_button=False) for m in choiceTemp]
|
168 |
+
|
169 |
+
def choice_group_c(group_model_choice):
|
170 |
+
choiceTemp=choice_group_a(group_model_choice)
|
171 |
+
choiceTemp = extend_choices(choiceTemp)
|
172 |
+
return [gr.Textbox(m) for m in choiceTemp]
|
173 |
+
|
174 |
+
def choice_group_d(group_model_choice):
|
175 |
+
choiceTemp=choice_group_a(group_model_choice)
|
176 |
+
choiceTemp = extend_choices(choiceTemp)
|
177 |
+
return [gr.Textbox(choiceTemp[i*nb_rep], visible=(choiceTemp[i*nb_rep] != 'NA'),show_label=False) for i in range(nb_mod_dif)]
|
178 |
+
def choice_group_e(group_model_choice):
|
179 |
+
choiceTemp=choice_group_a(group_model_choice)
|
180 |
+
choiceTemp = extend_choices(choiceTemp)
|
181 |
+
return [gr.Column(visible=(choiceTemp[i*nb_rep] != 'NA')) for i in range(nb_mod_dif)]
|
182 |
+
|
183 |
+
def cutStrg(longStrg,start,end):
|
184 |
+
shortStrg=''
|
185 |
+
for i in range(end-start):
|
186 |
+
shortStrg+=longStrg[start+i]
|
187 |
+
return shortStrg
|
188 |
+
|
189 |
+
def aff_models_perso(txt_list_perso,nb_models=nb_models,models=models):
|
190 |
+
list_perso=[]
|
191 |
+
t1=True
|
192 |
+
start=txt_list_perso.find('\"')
|
193 |
+
if start!=-1:
|
194 |
+
while t1:
|
195 |
+
start+=1
|
196 |
+
end=txt_list_perso.find('\"',start)
|
197 |
+
if end != -1:
|
198 |
+
txtTemp=cutStrg(txt_list_perso,start,end)
|
199 |
+
if txtTemp in models:
|
200 |
+
list_perso.append(cutStrg(txt_list_perso,start,end))
|
201 |
+
else :
|
202 |
+
t1=False
|
203 |
+
start=txt_list_perso.find('\"',end+1)
|
204 |
+
if start==-1:
|
205 |
+
t1=False
|
206 |
+
if len(list_perso)>=nb_models:
|
207 |
+
t1=False
|
208 |
+
return list_perso
|
209 |
+
|
210 |
+
def aff_models_perso_b(txt_list_perso):
|
211 |
+
return choice_group_b(aff_models_perso(txt_list_perso))
|
212 |
+
|
213 |
+
def aff_models_perso_c(txt_list_perso):
|
214 |
+
return choice_group_c(aff_models_perso(txt_list_perso))
|
215 |
+
|
216 |
+
|
217 |
+
def tag_choice(group_tag_choice):
|
218 |
+
return gr.Dropdown(label="List of Models with the chosen Tag", show_label=True, choices=list(group_tag_choice) , interactive = True , filterable = False)
|
219 |
+
|
220 |
+
def test_pass(test):
|
221 |
+
if test==os.getenv('p'):
|
222 |
+
print("ok")
|
223 |
+
return gr.Dropdown(label="Lists Tags", show_label=True, choices=list(models_test) , interactive = True)
|
224 |
+
else:
|
225 |
+
print("nop")
|
226 |
+
return gr.Dropdown(label="Lists Tags", show_label=True, choices=list([]) , interactive = True)
|
227 |
+
|
228 |
+
def test_pass_aff(test):
|
229 |
+
if test==os.getenv('p'):
|
230 |
+
return gr.Accordion( open=True, visible=True) ,gr.Row(visible=False)
|
231 |
+
else:
|
232 |
+
return gr.Accordion( open=True, visible=False) , gr.Row()
|
233 |
+
|
234 |
+
|
235 |
+
# https://huggingface.co/docs/api-inference/detailed_parameters
|
236 |
+
# https://huggingface.co/docs/huggingface_hub/package_reference/inference_client
|
237 |
+
async def infer(model_str, prompt, nprompt="", height=None, width=None, steps=None, cfg=None, seed=-1, timeout=inference_timeout):
|
238 |
+
from pathlib import Path
|
239 |
+
kwargs = {}
|
240 |
+
if height is not None and height >= 256: kwargs["height"] = height
|
241 |
+
if width is not None and width >= 256: kwargs["width"] = width
|
242 |
+
if steps is not None and steps >= 1: kwargs["num_inference_steps"] = steps
|
243 |
+
if cfg is not None and cfg > 0: cfg = kwargs["guidance_scale"] = cfg
|
244 |
+
noise = ""
|
245 |
+
if seed >= 0: kwargs["seed"] = seed
|
246 |
+
else:
|
247 |
+
rand = randint(1, 500)
|
248 |
+
for i in range(rand):
|
249 |
+
noise += " "
|
250 |
+
task = asyncio.create_task(asyncio.to_thread(models_load[model_str].fn,
|
251 |
+
prompt=f'{prompt} {noise}', negative_prompt=nprompt, **kwargs, token=HF_TOKEN))
|
252 |
+
await asyncio.sleep(0)
|
253 |
+
try:
|
254 |
+
result = await asyncio.wait_for(task, timeout=timeout)
|
255 |
+
except (Exception, asyncio.TimeoutError) as e:
|
256 |
+
print(e)
|
257 |
+
print(f"Task timed out: {model_str}")
|
258 |
+
if not task.done(): task.cancel()
|
259 |
+
result = None
|
260 |
+
if task.done() and result is not None:
|
261 |
+
with lock:
|
262 |
+
png_path = "image.png"
|
263 |
+
result.save(png_path)
|
264 |
+
image = str(Path(png_path).resolve())
|
265 |
+
return image
|
266 |
+
return None
|
267 |
+
|
268 |
+
def gen_fn(model_str, prompt, nprompt="", height=None, width=None, steps=None, cfg=None, seed=-1):
|
269 |
+
if model_str == 'NA':
|
270 |
+
return None
|
271 |
+
try:
|
272 |
+
loop = asyncio.new_event_loop()
|
273 |
+
result = loop.run_until_complete(infer(model_str, prompt, nprompt,
|
274 |
+
height, width, steps, cfg, seed, inference_timeout))
|
275 |
+
except (Exception, asyncio.CancelledError) as e:
|
276 |
+
print(e)
|
277 |
+
print(f"Task aborted: {model_str}")
|
278 |
+
result = None
|
279 |
+
finally:
|
280 |
+
loop.close()
|
281 |
+
return result
|
282 |
+
|
283 |
+
def gen_fn_original(model_str, prompt):
|
284 |
+
if model_str == 'NA':
|
285 |
+
return None
|
286 |
+
noise = str(randint(0, 9999))
|
287 |
+
try :
|
288 |
+
m=models_load[model_str](f'{prompt} {noise}')
|
289 |
+
except Exception as error :
|
290 |
+
print("error : " + model_str)
|
291 |
+
print(error)
|
292 |
+
m=False
|
293 |
+
|
294 |
+
return m
|
295 |
+
|
296 |
+
|
297 |
+
def add_gallery(image, model_str, gallery):
|
298 |
+
if gallery is None: gallery = []
|
299 |
+
#with lock:
|
300 |
+
if image is not None: gallery.append((image, model_str))
|
301 |
+
return gallery
|
302 |
+
|
303 |
+
def reset_gallery(gallery):
|
304 |
+
return add_gallery(None,"",[])
|
305 |
+
|
306 |
+
def load_gallery(gallery,id):
|
307 |
+
gallery = reset_gallery(gallery)
|
308 |
+
for c in cache_image[f"{id}"]:
|
309 |
+
gallery=add_gallery(c[0],c[1],gallery)
|
310 |
+
return gallery
|
311 |
+
def load_gallery_sorted(gallery,id):
|
312 |
+
gallery = reset_gallery(gallery)
|
313 |
+
for c in sorted(cache_image[f"{id}"], key=itemgetter(1)):
|
314 |
+
gallery=add_gallery(c[0],c[1],gallery)
|
315 |
+
return gallery
|
316 |
+
def load_gallery_actu(gallery,id):
|
317 |
+
gallery = reset_gallery(gallery)
|
318 |
+
for c in cache_image_actu[f"{id}"]:
|
319 |
+
gallery=add_gallery(c[0],c[1],gallery)
|
320 |
+
return gallery
|
321 |
+
|
322 |
+
def add_cache_image(image, model_str,id,cache_image=cache_image):
|
323 |
+
if image is not None:
|
324 |
+
cache_image[f"{id}"].append((image,model_str))
|
325 |
+
#cache_image=sorted(cache_image, key=itemgetter(1))
|
326 |
+
return
|
327 |
+
def add_cache_image_actu(image, model_str,id,cache_image_actu=cache_image_actu):
|
328 |
+
if image is not None:
|
329 |
+
bisect.insort(cache_image_actu[f"{id}"],(image, model_str), key=itemgetter(1))
|
330 |
+
#cache_image_actu=sorted(cache_image_actu, key=itemgetter(1))
|
331 |
+
return
|
332 |
+
def reset_cache_image(id,cache_image=cache_image):
|
333 |
+
cache_image[f"{id}"].clear()
|
334 |
+
return
|
335 |
+
def reset_cache_image_actu(id,cache_image_actu=cache_image_actu):
|
336 |
+
cache_image_actu[f"{id}"].clear()
|
337 |
+
return
|
338 |
+
def reset_cache_image_all_sessions(cache_image=cache_image,cache_image_actu=cache_image_actu):
|
339 |
+
for key, listT in cache_image.items():
|
340 |
+
listT.clear()
|
341 |
+
for key, listT in cache_image_actu.items():
|
342 |
+
listT.clear()
|
343 |
+
return
|
344 |
+
|
345 |
+
def set_session(id):
|
346 |
+
if id==0:
|
347 |
+
randTemp=randint(1,MAX_SEED)
|
348 |
+
cache_image[f"{randTemp}"]=[]
|
349 |
+
cache_image_actu[f"{randTemp}"]=[]
|
350 |
+
return gr.Number(visible=False,value=randTemp)
|
351 |
+
else :
|
352 |
+
return id
|
353 |
+
def print_info_sessions():
|
354 |
+
lenTot=0
|
355 |
+
print("###################################")
|
356 |
+
print("number of sessions : "+str(len(cache_image)))
|
357 |
+
for key, listT in cache_image.items():
|
358 |
+
print("session "+key+" : "+str(len(listT)))
|
359 |
+
lenTot+=len(listT)
|
360 |
+
print("images total = "+str(lenTot))
|
361 |
+
print("###################################")
|
362 |
+
return
|
363 |
+
|
364 |
+
def disp_models(group_model_choice,nb_rep=nb_rep):
|
365 |
+
listTemp=[]
|
366 |
+
strTemp='\n'
|
367 |
+
i=0
|
368 |
+
for m in group_model_choice:
|
369 |
+
if m not in listTemp:
|
370 |
+
listTemp.append(m)
|
371 |
+
for m in listTemp:
|
372 |
+
i+=1
|
373 |
+
strTemp+="\"" + m + "\",\n"
|
374 |
+
if i%(8/nb_rep)==0:
|
375 |
+
strTemp+="\n"
|
376 |
+
return gr.Textbox(label="models",value=strTemp)
|
377 |
+
|
378 |
+
def search_models(str_search,tags_plus_models=tags_plus_models):
|
379 |
+
output1="\n"
|
380 |
+
output2=""
|
381 |
+
for m in tags_plus_models[0][2]:
|
382 |
+
if m.find(str_search)!=-1:
|
383 |
+
output1+="\"" + m + "\",\n"
|
384 |
+
outputPlus="\n From tags : \n\n"
|
385 |
+
for tag_plus_models in tags_plus_models:
|
386 |
+
if str_search.lower() == tag_plus_models[0].lower() and str_search!="":
|
387 |
+
for m in tag_plus_models[2]:
|
388 |
+
output2+="\"" + m + "\",\n"
|
389 |
+
if output2 != "":
|
390 |
+
output=output1+outputPlus+output2
|
391 |
+
else :
|
392 |
+
output=output1
|
393 |
+
return gr.Textbox(label="out",value=output)
|
394 |
+
|
395 |
+
def search_info(txt_search_info,models_plus_tags=models_plus_tags):
|
396 |
+
outputList=[]
|
397 |
+
if txt_search_info.find("\"")!=-1:
|
398 |
+
start=txt_search_info.find("\"")+1
|
399 |
+
end=txt_search_info.find("\"",start)
|
400 |
+
m_name=cutStrg(txt_search_info,start,end)
|
401 |
+
else :
|
402 |
+
m_name = txt_search_info
|
403 |
+
for m in models_plus_tags:
|
404 |
+
if m_name == m[0]:
|
405 |
+
outputList=m[1]
|
406 |
+
if len(outputList)==0:
|
407 |
+
outputList.append("Model Not Find")
|
408 |
+
return gr.Textbox(label="out",value=outputList)
|
409 |
+
|
410 |
+
def add_in_blacklist(bl,model):
|
411 |
+
return gr.Textbox(bl+(f"\"{model}\",\n"))
|
412 |
+
def add_in_fav(fav,model):
|
413 |
+
return gr.Textbox(fav+(f"\"{model}\",\n"))
|
414 |
+
def rand_from_all_all_models():
|
415 |
+
if len(tags_plus_models[0][2])<nb_mod_dif:
|
416 |
+
return choice_group_c(tags_plus_models[0][2])
|
417 |
+
else:
|
418 |
+
result=[]
|
419 |
+
list_index_temp=[]
|
420 |
+
for i in range(len(tags_plus_models[0][2])):
|
421 |
+
list_index_temp.append(i)
|
422 |
+
for i in range(nb_mod_dif):
|
423 |
+
index_temp=randint(1,len(list_index_temp))-1
|
424 |
+
for j in range(nb_rep):
|
425 |
+
result.append(gr.Textbox(tags_plus_models[0][2][list_index_temp[index_temp]]))
|
426 |
+
list_index_temp.remove(list_index_temp[index_temp])
|
427 |
+
return result
|
428 |
+
def rand_from_tag_all_models(index):
|
429 |
+
if len(tags_plus_models[index][2])<nb_mod_dif:
|
430 |
+
return choice_group_c(models_test[index][1][0][1])
|
431 |
+
else:
|
432 |
+
result=[]
|
433 |
+
list_index_temp=[]
|
434 |
+
for i in range(len(tags_plus_models[index][2])):
|
435 |
+
list_index_temp.append(i)
|
436 |
+
for i in range(nb_mod_dif):
|
437 |
+
index_temp=randint(1,len(list_index_temp))-1
|
438 |
+
for j in range(nb_rep):
|
439 |
+
result.append(gr.Textbox(tags_plus_models[index][2][list_index_temp[index_temp]]))
|
440 |
+
list_index_temp.remove(list_index_temp[index_temp])
|
441 |
+
return result
|
442 |
+
|
443 |
+
def find_index_tag(group_tag_choice):
|
444 |
+
for i in (range(len(models_test)-1)):
|
445 |
+
if models_test[i][1]==group_tag_choice:
|
446 |
+
return gr.Number(i)
|
447 |
+
return gr.Number(0)
|
448 |
+
|
449 |
+
def ratio_chosen(choice_ratio,width,height):
|
450 |
+
if choice_ratio == [None,None]:
|
451 |
+
return width , height
|
452 |
+
else :
|
453 |
+
return gr.Slider(label="Width", info="If 0, the default value is used.", maximum=2024, step=32, value=choice_ratio[0]), gr.Slider(label="Height", info="If 0, the default value is used.", maximum=2024, step=32, value=choice_ratio[1])
|
454 |
+
|
455 |
+
list_ratios=[["None",[None,None]],
|
456 |
+
["4:1 (2048 x 512)",[2048,512]],
|
457 |
+
["12:5 (1536 x 640)",[1536,640]],
|
458 |
+
["~16:9 (1344 x 768)",[1344,768]],
|
459 |
+
["~3:2 (1216 x 832)",[1216,832]],
|
460 |
+
["~4:3 (1152 x 896)",[1152,896]],
|
461 |
+
["1:1 (1024 x 1024)",[1024,1024]],
|
462 |
+
["~3:4 (896 x 1152)",[896,1152]],
|
463 |
+
["~2:3 (832 x 1216)",[832,1216]],
|
464 |
+
["~9:16 (768 x 1344)",[768,1344]],
|
465 |
+
["5:12 (640 x 1536)",[640,1536]],
|
466 |
+
["1:4 (512 x 2048)",[512,2048]]]
|
467 |
+
|
468 |
+
def make_me():
|
469 |
+
# with gr.Tab('The Dream'):
|
470 |
+
with gr.Row():
|
471 |
+
#txt_input = gr.Textbox(lines=3, width=300, max_height=100)
|
472 |
+
#txt_input = gr.Textbox(label='Your prompt:', lines=3, width=300, max_height=100)
|
473 |
+
with gr.Column(scale=4):
|
474 |
+
with gr.Group():
|
475 |
+
txt_input = gr.Textbox(label='Your prompt:', lines=3)
|
476 |
+
with gr.Accordion("Advanced", open=False, visible=True):
|
477 |
+
neg_input = gr.Textbox(label='Negative prompt:', lines=1)
|
478 |
+
with gr.Row():
|
479 |
+
width = gr.Slider(label="Width", info="If 0, the default value is used.", maximum=1216, step=32, value=0)
|
480 |
+
height = gr.Slider(label="Height", info="If 0, the default value is used.", maximum=1216, step=32, value=0)
|
481 |
+
with gr.Row():
|
482 |
+
choice_ratio = gr.Dropdown(label="Ratio Width/Height",
|
483 |
+
info="OverWrite Width and Height (W*H<1024*1024)",
|
484 |
+
show_label=True, choices=list(list_ratios) , interactive = True, value=list_ratios[0][1])
|
485 |
+
choice_ratio.change(ratio_chosen,[choice_ratio,width,height],[width,height])
|
486 |
+
with gr.Row():
|
487 |
+
steps = gr.Slider(label="Number of inference steps", info="If 0, the default value is used.", maximum=100, step=1, value=0)
|
488 |
+
cfg = gr.Slider(label="Guidance scale", info="If 0, the default value is used.", maximum=30.0, step=0.1, value=0)
|
489 |
+
seed = gr.Slider(label="Seed", info="Randomize Seed if -1.", minimum=-1, maximum=MAX_SEED, step=1, value=-1)
|
490 |
+
#gen_button = gr.Button('Generate images', width=150, height=30)
|
491 |
+
#stop_button = gr.Button('Stop', variant='secondary', interactive=False, width=150, height=30)
|
492 |
+
gen_button = gr.Button('Generate images', scale=3)
|
493 |
+
stop_button = gr.Button('Stop', variant='secondary', interactive=False, scale=1)
|
494 |
+
|
495 |
+
gen_button.click(lambda: gr.update(interactive=True), None, stop_button)
|
496 |
+
#gr.HTML("""
|
497 |
+
#<div style="text-align: center; max-width: 100%; margin: 0 auto;">
|
498 |
+
# <body>
|
499 |
+
# </body>
|
500 |
+
#</div>
|
501 |
+
#""")
|
502 |
+
with gr.Row() as block_images:
|
503 |
+
choices=[models_test[0][1][0][1][0]]
|
504 |
+
output = []
|
505 |
+
current_models = []
|
506 |
+
#text_disp_models = []
|
507 |
+
block_images_liste = []
|
508 |
+
block_images_options_liste = []
|
509 |
+
button_rand_from_tag=[]
|
510 |
+
button_rand_from_all=[]
|
511 |
+
button_rand_from_fav=[]
|
512 |
+
button_blacklisted=[]
|
513 |
+
button_favorites=[]
|
514 |
+
choices_plus = extend_choices(choices)
|
515 |
+
for i in range(nb_mod_dif):
|
516 |
+
with gr.Column(visible=(choices_plus[i*nb_rep] != 'NA')) as block_Temp :
|
517 |
+
block_images_liste.append(block_Temp)
|
518 |
+
with gr.Group():
|
519 |
+
with gr.Row():
|
520 |
+
for j in range(nb_rep):
|
521 |
+
output.append(gr.Image(None, label=choices_plus[i*nb_rep+j],interactive=False,
|
522 |
+
visible=(choices_plus[i*nb_rep+j] != 'NA'),show_label=False,show_share_button=False))
|
523 |
+
for j in range(nb_rep):
|
524 |
+
current_models.append(gr.Textbox(choices_plus[i*nb_rep+j], visible=(j==0),show_label=False))
|
525 |
+
#text_disp_models.append(gr.Textbox(choices_plus[i*nb_rep], visible=(choices_plus[i*nb_rep] != 'NA'),show_label=False))
|
526 |
+
with gr.Row(visible=False) as block_Temp:
|
527 |
+
block_images_options_liste.append(block_Temp)
|
528 |
+
button_rand_from_tag.append(gr.Button("Random\nfrom tag"))
|
529 |
+
button_rand_from_all.append(gr.Button("Random\nfrom all"))
|
530 |
+
button_rand_from_fav.append(gr.Button("Random\nfrom fav"))
|
531 |
+
button_blacklisted.append(gr.Button("put in\nblacklist"))
|
532 |
+
button_favorites.append(gr.Button("put in\nfavorites"))
|
533 |
+
|
534 |
+
|
535 |
+
#output = update_imgbox([choices[0]])
|
536 |
+
#current_models = extend_choices_b([choices[0]])
|
537 |
+
|
538 |
+
for m, o in zip(current_models, output):
|
539 |
+
gen_event = gr.on(triggers=[gen_button.click, txt_input.submit], fn=gen_fn,
|
540 |
+
inputs=[m, txt_input, neg_input, height, width, steps, cfg, seed], outputs=[o])
|
541 |
+
stop_button.click(lambda: gr.update(interactive=False), None, stop_button, cancels=[gen_event])
|
542 |
+
|
543 |
+
with gr.Row() as blockPass:
|
544 |
+
txt_input_p = gr.Textbox(label="Pass", lines=1)
|
545 |
+
test_button = gr.Button(' ')
|
546 |
+
|
547 |
+
|
548 |
+
with gr.Accordion( open=True, visible=False) as stuffs:
|
549 |
+
with gr.Accordion("Advanced",open=False):
|
550 |
+
images_options=gr.Checkbox(False,label="Images Options")
|
551 |
+
images_options.change(lambda x:[gr.Row(visible=x) for b in range(nb_mod_dif)],[images_options],block_images_options_liste)
|
552 |
+
blacklist_perso=gr.Textbox(label="Blacklist perso")
|
553 |
+
fav_perso=gr.Textbox(label="Fav perso")
|
554 |
+
button_rand_from_tag_all_models=gr.Button("Random all models from tag")
|
555 |
+
button_rand_from_all_all_models=gr.Button("Random all models from all")
|
556 |
+
button_rand_from_fav_all_models=gr.Button("Random all models from fav")
|
557 |
+
|
558 |
+
|
559 |
+
with gr.Accordion("Gallery",open=False):
|
560 |
+
with gr.Row():
|
561 |
+
#global cache_image
|
562 |
+
#global cache_image_actu
|
563 |
+
id_session=gr.Number(visible=False,value=0)
|
564 |
+
gen_button.click(set_session, id_session, id_session)
|
565 |
+
cache_image[f"{id_session.value}"]=[]
|
566 |
+
cache_image_actu[f"{id_session.value}"]=[]
|
567 |
+
with gr.Column():
|
568 |
+
b11 = gr.Button('Load Galerry Actu')
|
569 |
+
b12 = gr.Button('Load Galerry All')
|
570 |
+
b13 = gr.Button('Load Galerry All (sorted)')
|
571 |
+
gallery = gr.Gallery(label="Output", show_download_button=True, elem_classes="gallery",
|
572 |
+
interactive=False, show_share_button=True, container=True, format="png",
|
573 |
+
preview=True, object_fit="cover",columns=4,rows=4)
|
574 |
+
with gr.Column():
|
575 |
+
b21 = gr.Button('Reset Gallery')
|
576 |
+
b22 = gr.Button('Reset Gallery All')
|
577 |
+
b23 = gr.Button('Reset All Sessions')
|
578 |
+
b24 = gr.Button('print info sessions')
|
579 |
+
b11.click(load_gallery_actu,[gallery,id_session],gallery)
|
580 |
+
b12.click(load_gallery,[gallery,id_session],gallery)
|
581 |
+
b13.click(load_gallery_sorted,[gallery,id_session],gallery)
|
582 |
+
b21.click(reset_gallery,[gallery],gallery)
|
583 |
+
b22.click(reset_cache_image,[id_session],gallery)
|
584 |
+
b23.click(reset_cache_image_all_sessions,[],[])
|
585 |
+
b24.click(print_info_sessions,[],[])
|
586 |
+
for m, o in zip(current_models, output):
|
587 |
+
#o.change(add_gallery, [o, m, gallery], [gallery])
|
588 |
+
o.change(add_cache_image,[o,m,id_session],[])
|
589 |
+
o.change(add_cache_image_actu,[o,m,id_session],[])
|
590 |
+
gen_button.click(reset_cache_image_actu, [id_session], [])
|
591 |
+
gen_button.click(lambda id:gr.Button('Load Galerry All ('+str(len(cache_image[f"{id}"]))+")"), [id_session], [b12])
|
592 |
+
|
593 |
+
with gr.Group():
|
594 |
+
with gr.Row():
|
595 |
+
#group_tag_choice = gr.Dropdown(label="Lists Tags", show_label=True, choices=list([]) , interactive = True)
|
596 |
+
group_tag_choice = gr.Dropdown(label="Lists Tags", show_label=True, choices=list(models_test), interactive = True,value=models_test[0][1])
|
597 |
+
#group_tag_choice = gr.Dropdown(label="Lists Tags", show_label=True, choices=list(models_test), interactive = True)
|
598 |
+
index_tag=gr.Number(0,visible=False)
|
599 |
+
|
600 |
+
with gr.Row():
|
601 |
+
group_model_choice = gr.Dropdown(label="List of Models with the chosen Tag", show_label=True, choices=list([]), interactive = True)
|
602 |
+
group_model_choice.change(choice_group_b,group_model_choice,output)
|
603 |
+
group_model_choice.change(choice_group_c,group_model_choice,current_models)
|
604 |
+
#group_model_choice.change(choice_group_d,group_model_choice,text_disp_models)
|
605 |
+
group_model_choice.change(choice_group_e,group_model_choice,block_images_liste)
|
606 |
+
group_tag_choice.change(tag_choice,group_tag_choice,group_model_choice)
|
607 |
+
group_tag_choice.change(find_index_tag,group_tag_choice,index_tag)
|
608 |
+
|
609 |
+
with gr.Accordion("Display/Load Models") :
|
610 |
+
with gr.Row():
|
611 |
+
txt_list_models=gr.Textbox(label="Models Actu",value="")
|
612 |
+
group_model_choice.change(disp_models,group_model_choice,txt_list_models)
|
613 |
+
|
614 |
+
with gr.Column():
|
615 |
+
txt_list_perso = gr.Textbox(label='List Models Perso to Load')
|
616 |
+
|
617 |
+
button_list_perso = gr.Button('Load')
|
618 |
+
button_list_perso.click(aff_models_perso_b,txt_list_perso,output)
|
619 |
+
button_list_perso.click(aff_models_perso_c,txt_list_perso,current_models)
|
620 |
+
|
621 |
+
with gr.Row():
|
622 |
+
txt_search = gr.Textbox(label='Search in')
|
623 |
+
txt_output_search = gr.Textbox(label='Search out')
|
624 |
+
button_search = gr.Button('Research')
|
625 |
+
button_search.click(search_models,txt_search,txt_output_search)
|
626 |
+
|
627 |
+
with gr.Row():
|
628 |
+
txt_search_info = gr.Textbox(label='Search info in')
|
629 |
+
txt_output_search_info = gr.Textbox(label='Search info out')
|
630 |
+
button_search_info = gr.Button('Research info')
|
631 |
+
button_search_info.click(search_info,txt_search_info,txt_output_search_info)
|
632 |
+
|
633 |
+
|
634 |
+
with gr.Row():
|
635 |
+
test_button.click(test_pass_aff,txt_input_p,[stuffs,blockPass])
|
636 |
+
#test_button.click(test_pass,txt_input_p,group_tag_choice)
|
637 |
+
|
638 |
+
#text_disp_models = []
|
639 |
+
#button_rand_from_tag=[]
|
640 |
+
#button_rand_from_all=[]
|
641 |
+
button_rand_from_all_all_models.click(rand_from_all_all_models,[],current_models)
|
642 |
+
button_rand_from_tag_all_models.click(rand_from_tag_all_models,index_tag,current_models)
|
643 |
+
for i in range(nb_mod_dif):
|
644 |
+
#######################################################################################################################
|
645 |
+
#button_rand_from_tag.click()
|
646 |
+
#button_rand_from_all.click()
|
647 |
+
#button_rand_from_fav.click()
|
648 |
+
button_blacklisted[i].click(add_in_blacklist,[blacklist_perso,current_models[i*nb_rep]],blacklist_perso)
|
649 |
+
button_favorites[i].click(add_in_fav,[fav_perso,current_models[i*nb_rep]],fav_perso)
|
650 |
+
|
651 |
+
|
652 |
+
|
653 |
+
gr.HTML("""
|
654 |
+
<div class="footer">
|
655 |
+
<p> Based on the <a href="https://huggingface.co/spaces/derwahnsinn/TestGen">TestGen</a> Space by derwahnsinn, the <a href="https://huggingface.co/spaces/RdnUser77/SpacIO_v1">SpacIO</a> Space by RdnUser77 and Omnibus's Maximum Multiplier!
|
656 |
+
</p>
|
657 |
+
""")
|
658 |
+
|
659 |
+
js_code = """
|
660 |
+
|
661 |
+
console.log('ghgh');
|
662 |
+
"""
|
663 |
+
|
664 |
+
with gr.Blocks(theme="Nymbo/Nymbo_Theme", fill_width=True, css="div.float.svelte-1mwvhlq { position: absolute; top: var(--block-label-margin); left: var(--block-label-margin); background: none; border: none;}") as demo:
|
665 |
+
gr.Markdown("<script>" + js_code + "</script>")
|
666 |
+
make_me()
|
667 |
+
|
668 |
+
|
669 |
+
# https://www.gradio.app/guides/setting-up-a-demo-for-maximum-performance
|
670 |
+
#demo.queue(concurrency_count=999) # concurrency_count is deprecated in 4.x
|
671 |
+
demo.queue(default_concurrency_limit=200, max_size=200)
|
672 |
+
demo.launch(max_threads=400)
|
blacklist.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
bad_tags= [
|
2 |
+
"safetensors",
|
3 |
+
"region:us",
|
4 |
+
"autotrain_compatible",
|
5 |
+
"endpoints_compatible",
|
6 |
+
"diffusers:StableDiffusionXLPipeline",
|
7 |
+
"license:other",
|
8 |
+
"license:creativeml-openrail-m",
|
9 |
+
"base_model:cagliostrolab/animagine-xl-3.1",
|
10 |
+
"base_model:finetune:cagliostrolab/animagine-xl-3.1",
|
11 |
+
"base_model:da2el/ioliPonyMix",
|
12 |
+
"base_model:finetune:da2el/ioliPonyMix",
|
13 |
+
|
14 |
+
]
|
15 |
+
|
16 |
+
bad_models=[
|
17 |
+
"John6666/aua-09-sdxl",
|
18 |
+
"John6666/beyond-experimental-v28loramerge-sdxl",
|
19 |
+
"John6666/aua-always-use-artists-auap08-sdxl",
|
20 |
+
"John6666/artiwaifu-diffusion-v20-sdxl",
|
21 |
+
"John6666/flyx3-mix-xl-v1-sdxl",
|
22 |
+
"John6666/flyx3-mix-xl-v2-sdxl",
|
23 |
+
|
24 |
+
]
|
25 |
+
|
26 |
+
fav_models=[
|
27 |
+
"John6666/3x3mix-xl-typed-v1-sdxl",
|
28 |
+
"John6666/florag-pony-half-xl-sdxl",
|
29 |
+
"John6666/red-blue-fantasy-pony-sdxl",
|
30 |
+
"John6666/catloaf-v1-sdxl",
|
31 |
+
"John6666/peroperositai-v1-sdxl",
|
32 |
+
"John6666/hda-matrix-copdxl-v1-sdxl",
|
33 |
+
"John6666/animeliner-ponyxl-v1-sdxl",
|
34 |
+
]
|
35 |
+
|
externalmod.py
ADDED
@@ -0,0 +1,584 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""This module should not be used directly as its API is subject to change. Instead,
|
2 |
+
use the `gr.Blocks.load()` or `gr.load()` functions."""
|
3 |
+
|
4 |
+
from __future__ import annotations
|
5 |
+
|
6 |
+
import json
|
7 |
+
import os
|
8 |
+
import re
|
9 |
+
import tempfile
|
10 |
+
import warnings
|
11 |
+
from pathlib import Path
|
12 |
+
from typing import TYPE_CHECKING, Callable
|
13 |
+
|
14 |
+
import httpx
|
15 |
+
import huggingface_hub
|
16 |
+
from gradio_client import Client
|
17 |
+
from gradio_client.client import Endpoint
|
18 |
+
from gradio_client.documentation import document
|
19 |
+
from packaging import version
|
20 |
+
|
21 |
+
import gradio
|
22 |
+
from gradio import components, external_utils, utils
|
23 |
+
from gradio.context import Context
|
24 |
+
from gradio.exceptions import (
|
25 |
+
GradioVersionIncompatibleError,
|
26 |
+
ModelNotFoundError,
|
27 |
+
TooManyRequestsError,
|
28 |
+
)
|
29 |
+
from gradio.processing_utils import save_base64_to_cache, to_binary
|
30 |
+
|
31 |
+
if TYPE_CHECKING:
|
32 |
+
from gradio.blocks import Blocks
|
33 |
+
from gradio.interface import Interface
|
34 |
+
|
35 |
+
|
36 |
+
server_timeout = 600
|
37 |
+
|
38 |
+
|
39 |
+
@document()
|
40 |
+
def load(
|
41 |
+
name: str,
|
42 |
+
src: str | None = None,
|
43 |
+
hf_token: str | None = None,
|
44 |
+
alias: str | None = None,
|
45 |
+
**kwargs,
|
46 |
+
) -> Blocks:
|
47 |
+
"""
|
48 |
+
Constructs a demo from a Hugging Face repo. Can accept model repos (if src is "models") or Space repos (if src is "spaces"). The input
|
49 |
+
and output components are automatically loaded from the repo. Note that if a Space is loaded, certain high-level attributes of the Blocks (e.g.
|
50 |
+
custom `css`, `js`, and `head` attributes) will not be loaded.
|
51 |
+
Parameters:
|
52 |
+
name: the name of the model (e.g. "gpt2" or "facebook/bart-base") or space (e.g. "flax-community/spanish-gpt2"), can include the `src` as prefix (e.g. "models/facebook/bart-base")
|
53 |
+
src: the source of the model: `models` or `spaces` (or leave empty if source is provided as a prefix in `name`)
|
54 |
+
hf_token: optional access token for loading private Hugging Face Hub models or spaces. Find your token here: https://huggingface.co/settings/tokens. Warning: only provide this if you are loading a trusted private Space as it can be read by the Space you are loading.
|
55 |
+
alias: optional string used as the name of the loaded model instead of the default name (only applies if loading a Space running Gradio 2.x)
|
56 |
+
Returns:
|
57 |
+
a Gradio Blocks object for the given model
|
58 |
+
Example:
|
59 |
+
import gradio as gr
|
60 |
+
demo = gr.load("gradio/question-answering", src="spaces")
|
61 |
+
demo.launch()
|
62 |
+
"""
|
63 |
+
return load_blocks_from_repo(
|
64 |
+
name=name, src=src, hf_token=hf_token, alias=alias, **kwargs
|
65 |
+
)
|
66 |
+
|
67 |
+
|
68 |
+
def load_blocks_from_repo(
|
69 |
+
name: str,
|
70 |
+
src: str | None = None,
|
71 |
+
hf_token: str | None = None,
|
72 |
+
alias: str | None = None,
|
73 |
+
**kwargs,
|
74 |
+
) -> Blocks:
|
75 |
+
"""Creates and returns a Blocks instance from a Hugging Face model or Space repo."""
|
76 |
+
if src is None:
|
77 |
+
# Separate the repo type (e.g. "model") from repo name (e.g. "google/vit-base-patch16-224")
|
78 |
+
tokens = name.split("/")
|
79 |
+
if len(tokens) <= 1:
|
80 |
+
raise ValueError(
|
81 |
+
"Either `src` parameter must be provided, or `name` must be formatted as {src}/{repo name}"
|
82 |
+
)
|
83 |
+
src = tokens[0]
|
84 |
+
name = "/".join(tokens[1:])
|
85 |
+
|
86 |
+
factory_methods: dict[str, Callable] = {
|
87 |
+
# for each repo type, we have a method that returns the Interface given the model name & optionally an hf_token
|
88 |
+
"huggingface": from_model,
|
89 |
+
"models": from_model,
|
90 |
+
"spaces": from_spaces,
|
91 |
+
}
|
92 |
+
if src.lower() not in factory_methods:
|
93 |
+
raise ValueError(f"parameter: src must be one of {factory_methods.keys()}")
|
94 |
+
|
95 |
+
if hf_token is not None:
|
96 |
+
if Context.hf_token is not None and Context.hf_token != hf_token:
|
97 |
+
warnings.warn(
|
98 |
+
"""You are loading a model/Space with a different access token than the one you used to load a previous model/Space. This is not recommended, as it may cause unexpected behavior."""
|
99 |
+
)
|
100 |
+
Context.hf_token = hf_token
|
101 |
+
|
102 |
+
blocks: gradio.Blocks = factory_methods[src](name, hf_token, alias, **kwargs)
|
103 |
+
return blocks
|
104 |
+
|
105 |
+
|
106 |
+
def from_model(model_name: str, hf_token: str | None, alias: str | None, **kwargs):
|
107 |
+
model_url = f"https://huggingface.co/{model_name}"
|
108 |
+
api_url = f"https://api-inference.huggingface.co/models/{model_name}"
|
109 |
+
print(f"Fetching model from: {model_url}")
|
110 |
+
|
111 |
+
headers = {"Authorization": f"Bearer {hf_token}"} if hf_token is not None else {}
|
112 |
+
response = httpx.request("GET", api_url, headers=headers)
|
113 |
+
if response.status_code != 200:
|
114 |
+
raise ModelNotFoundError(
|
115 |
+
f"Could not find model: {model_name}. If it is a private or gated model, please provide your Hugging Face access token (https://huggingface.co/settings/tokens) as the argument for the `hf_token` parameter."
|
116 |
+
)
|
117 |
+
p = response.json().get("pipeline_tag")
|
118 |
+
|
119 |
+
headers["X-Wait-For-Model"] = "true"
|
120 |
+
client = huggingface_hub.InferenceClient(
|
121 |
+
model=model_name, headers=headers, token=hf_token, timeout=server_timeout,
|
122 |
+
)
|
123 |
+
|
124 |
+
# For tasks that are not yet supported by the InferenceClient
|
125 |
+
GRADIO_CACHE = os.environ.get("GRADIO_TEMP_DIR") or str( # noqa: N806
|
126 |
+
Path(tempfile.gettempdir()) / "gradio"
|
127 |
+
)
|
128 |
+
|
129 |
+
def custom_post_binary(data):
|
130 |
+
data = to_binary({"path": data})
|
131 |
+
response = httpx.request("POST", api_url, headers=headers, content=data)
|
132 |
+
return save_base64_to_cache(
|
133 |
+
external_utils.encode_to_base64(response), cache_dir=GRADIO_CACHE
|
134 |
+
)
|
135 |
+
|
136 |
+
preprocess = None
|
137 |
+
postprocess = None
|
138 |
+
examples = None
|
139 |
+
|
140 |
+
# example model: ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition
|
141 |
+
if p == "audio-classification":
|
142 |
+
inputs = components.Audio(type="filepath", label="Input")
|
143 |
+
outputs = components.Label(label="Class")
|
144 |
+
postprocess = external_utils.postprocess_label
|
145 |
+
examples = [
|
146 |
+
"https://gradio-builds.s3.amazonaws.com/demo-files/audio_sample.wav"
|
147 |
+
]
|
148 |
+
fn = client.audio_classification
|
149 |
+
# example model: facebook/xm_transformer_sm_all-en
|
150 |
+
elif p == "audio-to-audio":
|
151 |
+
inputs = components.Audio(type="filepath", label="Input")
|
152 |
+
outputs = components.Audio(label="Output")
|
153 |
+
examples = [
|
154 |
+
"https://gradio-builds.s3.amazonaws.com/demo-files/audio_sample.wav"
|
155 |
+
]
|
156 |
+
fn = custom_post_binary
|
157 |
+
# example model: facebook/wav2vec2-base-960h
|
158 |
+
elif p == "automatic-speech-recognition":
|
159 |
+
inputs = components.Audio(type="filepath", label="Input")
|
160 |
+
outputs = components.Textbox(label="Output")
|
161 |
+
examples = [
|
162 |
+
"https://gradio-builds.s3.amazonaws.com/demo-files/audio_sample.wav"
|
163 |
+
]
|
164 |
+
fn = client.automatic_speech_recognition
|
165 |
+
# example model: microsoft/DialoGPT-medium
|
166 |
+
elif p == "conversational":
|
167 |
+
inputs = [
|
168 |
+
components.Textbox(render=False),
|
169 |
+
components.State(render=False),
|
170 |
+
]
|
171 |
+
outputs = [
|
172 |
+
components.Chatbot(render=False),
|
173 |
+
components.State(render=False),
|
174 |
+
]
|
175 |
+
examples = [["Hello World"]]
|
176 |
+
preprocess = external_utils.chatbot_preprocess
|
177 |
+
postprocess = external_utils.chatbot_postprocess
|
178 |
+
fn = client.conversational
|
179 |
+
# example model: julien-c/distilbert-feature-extraction
|
180 |
+
elif p == "feature-extraction":
|
181 |
+
inputs = components.Textbox(label="Input")
|
182 |
+
outputs = components.Dataframe(label="Output")
|
183 |
+
fn = client.feature_extraction
|
184 |
+
postprocess = utils.resolve_singleton
|
185 |
+
# example model: distilbert/distilbert-base-uncased
|
186 |
+
elif p == "fill-mask":
|
187 |
+
inputs = components.Textbox(label="Input")
|
188 |
+
outputs = components.Label(label="Classification")
|
189 |
+
examples = [
|
190 |
+
"Hugging Face is the AI community, working together, to [MASK] the future."
|
191 |
+
]
|
192 |
+
postprocess = external_utils.postprocess_mask_tokens
|
193 |
+
fn = client.fill_mask
|
194 |
+
# Example: google/vit-base-patch16-224
|
195 |
+
elif p == "image-classification":
|
196 |
+
inputs = components.Image(type="filepath", label="Input Image")
|
197 |
+
outputs = components.Label(label="Classification")
|
198 |
+
postprocess = external_utils.postprocess_label
|
199 |
+
examples = ["https://gradio-builds.s3.amazonaws.com/demo-files/cheetah-002.jpg"]
|
200 |
+
fn = client.image_classification
|
201 |
+
# Example: deepset/xlm-roberta-base-squad2
|
202 |
+
elif p == "question-answering":
|
203 |
+
inputs = [
|
204 |
+
components.Textbox(label="Question"),
|
205 |
+
components.Textbox(lines=7, label="Context"),
|
206 |
+
]
|
207 |
+
outputs = [
|
208 |
+
components.Textbox(label="Answer"),
|
209 |
+
components.Label(label="Score"),
|
210 |
+
]
|
211 |
+
examples = [
|
212 |
+
[
|
213 |
+
"What entity was responsible for the Apollo program?",
|
214 |
+
"The Apollo program, also known as Project Apollo, was the third United States human spaceflight"
|
215 |
+
" program carried out by the National Aeronautics and Space Administration (NASA), which accomplished"
|
216 |
+
" landing the first humans on the Moon from 1969 to 1972.",
|
217 |
+
]
|
218 |
+
]
|
219 |
+
postprocess = external_utils.postprocess_question_answering
|
220 |
+
fn = client.question_answering
|
221 |
+
# Example: facebook/bart-large-cnn
|
222 |
+
elif p == "summarization":
|
223 |
+
inputs = components.Textbox(label="Input")
|
224 |
+
outputs = components.Textbox(label="Summary")
|
225 |
+
examples = [
|
226 |
+
[
|
227 |
+
"The tower is 324 metres (1,063 ft) tall, about the same height as an 81-storey building, and the tallest structure in Paris. Its base is square, measuring 125 metres (410 ft) on each side. During its construction, the Eiffel Tower surpassed the Washington Monument to become the tallest man-made structure in the world, a title it held for 41 years until the Chrysler Building in New York City was finished in 1930. It was the first structure to reach a height of 300 metres. Due to the addition of a broadcasting aerial at the top of the tower in 1957, it is now taller than the Chrysler Building by 5.2 metres (17 ft). Excluding transmitters, the Eiffel Tower is the second tallest free-standing structure in France after the Millau Viaduct."
|
228 |
+
]
|
229 |
+
]
|
230 |
+
fn = client.summarization
|
231 |
+
# Example: distilbert-base-uncased-finetuned-sst-2-english
|
232 |
+
elif p == "text-classification":
|
233 |
+
inputs = components.Textbox(label="Input")
|
234 |
+
outputs = components.Label(label="Classification")
|
235 |
+
examples = ["I feel great"]
|
236 |
+
postprocess = external_utils.postprocess_label
|
237 |
+
fn = client.text_classification
|
238 |
+
# Example: gpt2
|
239 |
+
elif p == "text-generation":
|
240 |
+
inputs = components.Textbox(label="Text")
|
241 |
+
outputs = inputs
|
242 |
+
examples = ["Once upon a time"]
|
243 |
+
fn = external_utils.text_generation_wrapper(client)
|
244 |
+
# Example: valhalla/t5-small-qa-qg-hl
|
245 |
+
elif p == "text2text-generation":
|
246 |
+
inputs = components.Textbox(label="Input")
|
247 |
+
outputs = components.Textbox(label="Generated Text")
|
248 |
+
examples = ["Translate English to Arabic: How are you?"]
|
249 |
+
fn = client.text_generation
|
250 |
+
# Example: Helsinki-NLP/opus-mt-en-ar
|
251 |
+
elif p == "translation":
|
252 |
+
inputs = components.Textbox(label="Input")
|
253 |
+
outputs = components.Textbox(label="Translation")
|
254 |
+
examples = ["Hello, how are you?"]
|
255 |
+
fn = client.translation
|
256 |
+
# Example: facebook/bart-large-mnli
|
257 |
+
elif p == "zero-shot-classification":
|
258 |
+
inputs = [
|
259 |
+
components.Textbox(label="Input"),
|
260 |
+
components.Textbox(label="Possible class names (" "comma-separated)"),
|
261 |
+
components.Checkbox(label="Allow multiple true classes"),
|
262 |
+
]
|
263 |
+
outputs = components.Label(label="Classification")
|
264 |
+
postprocess = external_utils.postprocess_label
|
265 |
+
examples = [["I feel great", "happy, sad", False]]
|
266 |
+
fn = external_utils.zero_shot_classification_wrapper(client)
|
267 |
+
# Example: sentence-transformers/distilbert-base-nli-stsb-mean-tokens
|
268 |
+
elif p == "sentence-similarity":
|
269 |
+
inputs = [
|
270 |
+
components.Textbox(
|
271 |
+
label="Source Sentence",
|
272 |
+
placeholder="Enter an original sentence",
|
273 |
+
),
|
274 |
+
components.Textbox(
|
275 |
+
lines=7,
|
276 |
+
placeholder="Sentences to compare to -- separate each sentence by a newline",
|
277 |
+
label="Sentences to compare to",
|
278 |
+
),
|
279 |
+
]
|
280 |
+
outputs = components.JSON(label="Similarity scores")
|
281 |
+
examples = [["That is a happy person", "That person is very happy"]]
|
282 |
+
fn = external_utils.sentence_similarity_wrapper(client)
|
283 |
+
# Example: julien-c/ljspeech_tts_train_tacotron2_raw_phn_tacotron_g2p_en_no_space_train
|
284 |
+
elif p == "text-to-speech":
|
285 |
+
inputs = components.Textbox(label="Input")
|
286 |
+
outputs = components.Audio(label="Audio")
|
287 |
+
examples = ["Hello, how are you?"]
|
288 |
+
fn = client.text_to_speech
|
289 |
+
# example model: osanseviero/BigGAN-deep-128
|
290 |
+
elif p == "text-to-image":
|
291 |
+
inputs = components.Textbox(label="Input")
|
292 |
+
outputs = components.Image(label="Output")
|
293 |
+
examples = ["A beautiful sunset"]
|
294 |
+
fn = client.text_to_image
|
295 |
+
# example model: huggingface-course/bert-finetuned-ner
|
296 |
+
elif p == "token-classification":
|
297 |
+
inputs = components.Textbox(label="Input")
|
298 |
+
outputs = components.HighlightedText(label="Output")
|
299 |
+
examples = [
|
300 |
+
"Hugging Face is a company based in Paris and New York City that acquired Gradio in 2021."
|
301 |
+
]
|
302 |
+
fn = external_utils.token_classification_wrapper(client)
|
303 |
+
# example model: impira/layoutlm-document-qa
|
304 |
+
elif p == "document-question-answering":
|
305 |
+
inputs = [
|
306 |
+
components.Image(type="filepath", label="Input Document"),
|
307 |
+
components.Textbox(label="Question"),
|
308 |
+
]
|
309 |
+
postprocess = external_utils.postprocess_label
|
310 |
+
outputs = components.Label(label="Label")
|
311 |
+
fn = client.document_question_answering
|
312 |
+
# example model: dandelin/vilt-b32-finetuned-vqa
|
313 |
+
elif p == "visual-question-answering":
|
314 |
+
inputs = [
|
315 |
+
components.Image(type="filepath", label="Input Image"),
|
316 |
+
components.Textbox(label="Question"),
|
317 |
+
]
|
318 |
+
outputs = components.Label(label="Label")
|
319 |
+
postprocess = external_utils.postprocess_visual_question_answering
|
320 |
+
examples = [
|
321 |
+
[
|
322 |
+
"https://gradio-builds.s3.amazonaws.com/demo-files/cheetah-002.jpg",
|
323 |
+
"What animal is in the image?",
|
324 |
+
]
|
325 |
+
]
|
326 |
+
fn = client.visual_question_answering
|
327 |
+
# example model: Salesforce/blip-image-captioning-base
|
328 |
+
elif p == "image-to-text":
|
329 |
+
inputs = components.Image(type="filepath", label="Input Image")
|
330 |
+
outputs = components.Textbox(label="Generated Text")
|
331 |
+
examples = ["https://gradio-builds.s3.amazonaws.com/demo-files/cheetah-002.jpg"]
|
332 |
+
fn = client.image_to_text
|
333 |
+
# example model: rajistics/autotrain-Adult-934630783
|
334 |
+
elif p in ["tabular-classification", "tabular-regression"]:
|
335 |
+
examples = external_utils.get_tabular_examples(model_name)
|
336 |
+
col_names, examples = external_utils.cols_to_rows(examples) # type: ignore
|
337 |
+
examples = [[examples]] if examples else None
|
338 |
+
inputs = components.Dataframe(
|
339 |
+
label="Input Rows",
|
340 |
+
type="pandas",
|
341 |
+
headers=col_names,
|
342 |
+
col_count=(len(col_names), "fixed"),
|
343 |
+
render=False,
|
344 |
+
)
|
345 |
+
outputs = components.Dataframe(
|
346 |
+
label="Predictions", type="array", headers=["prediction"]
|
347 |
+
)
|
348 |
+
fn = external_utils.tabular_wrapper
|
349 |
+
# example model: microsoft/table-transformer-detection
|
350 |
+
elif p == "object-detection":
|
351 |
+
inputs = components.Image(type="filepath", label="Input Image")
|
352 |
+
outputs = components.AnnotatedImage(label="Annotations")
|
353 |
+
fn = external_utils.object_detection_wrapper(client)
|
354 |
+
# example model: stabilityai/stable-diffusion-xl-refiner-1.0
|
355 |
+
elif p == "image-to-image":
|
356 |
+
inputs = [
|
357 |
+
components.Image(type="filepath", label="Input Image"),
|
358 |
+
components.Textbox(label="Input"),
|
359 |
+
]
|
360 |
+
outputs = components.Image(label="Output")
|
361 |
+
examples = [
|
362 |
+
[
|
363 |
+
"https://gradio-builds.s3.amazonaws.com/demo-files/cheetah-002.jpg",
|
364 |
+
"Photo of a cheetah with green eyes",
|
365 |
+
]
|
366 |
+
]
|
367 |
+
fn = client.image_to_image
|
368 |
+
else:
|
369 |
+
raise ValueError(f"Unsupported pipeline type: {p}")
|
370 |
+
|
371 |
+
def query_huggingface_inference_endpoints(*data, **kwargs):
|
372 |
+
if preprocess is not None:
|
373 |
+
data = preprocess(*data)
|
374 |
+
data = fn(*data, **kwargs) # type: ignore
|
375 |
+
if postprocess is not None:
|
376 |
+
data = postprocess(data) # type: ignore
|
377 |
+
return data
|
378 |
+
|
379 |
+
query_huggingface_inference_endpoints.__name__ = alias or model_name
|
380 |
+
|
381 |
+
interface_info = {
|
382 |
+
"fn": query_huggingface_inference_endpoints,
|
383 |
+
"inputs": inputs,
|
384 |
+
"outputs": outputs,
|
385 |
+
"title": model_name,
|
386 |
+
# "examples": examples,
|
387 |
+
}
|
388 |
+
|
389 |
+
kwargs = dict(interface_info, **kwargs)
|
390 |
+
interface = gradio.Interface(**kwargs)
|
391 |
+
return interface
|
392 |
+
|
393 |
+
|
394 |
+
def from_spaces(
|
395 |
+
space_name: str, hf_token: str | None, alias: str | None, **kwargs
|
396 |
+
) -> Blocks:
|
397 |
+
client = Client(
|
398 |
+
space_name,
|
399 |
+
hf_token=hf_token,
|
400 |
+
download_files=False,
|
401 |
+
_skip_components=False,
|
402 |
+
)
|
403 |
+
|
404 |
+
space_url = f"https://huggingface.co/spaces/{space_name}"
|
405 |
+
|
406 |
+
print(f"Fetching Space from: {space_url}")
|
407 |
+
|
408 |
+
headers = {}
|
409 |
+
if hf_token is not None:
|
410 |
+
headers["Authorization"] = f"Bearer {hf_token}"
|
411 |
+
|
412 |
+
iframe_url = (
|
413 |
+
httpx.get(
|
414 |
+
f"https://huggingface.co/api/spaces/{space_name}/host", headers=headers
|
415 |
+
)
|
416 |
+
.json()
|
417 |
+
.get("host")
|
418 |
+
)
|
419 |
+
|
420 |
+
if iframe_url is None:
|
421 |
+
raise ValueError(
|
422 |
+
f"Could not find Space: {space_name}. If it is a private or gated Space, please provide your Hugging Face access token (https://huggingface.co/settings/tokens) as the argument for the `hf_token` parameter."
|
423 |
+
)
|
424 |
+
|
425 |
+
r = httpx.get(iframe_url, headers=headers)
|
426 |
+
|
427 |
+
result = re.search(
|
428 |
+
r"window.gradio_config = (.*?);[\s]*</script>", r.text
|
429 |
+
) # some basic regex to extract the config
|
430 |
+
try:
|
431 |
+
config = json.loads(result.group(1)) # type: ignore
|
432 |
+
except AttributeError as ae:
|
433 |
+
raise ValueError(f"Could not load the Space: {space_name}") from ae
|
434 |
+
if "allow_flagging" in config: # Create an Interface for Gradio 2.x Spaces
|
435 |
+
return from_spaces_interface(
|
436 |
+
space_name, config, alias, hf_token, iframe_url, **kwargs
|
437 |
+
)
|
438 |
+
else: # Create a Blocks for Gradio 3.x Spaces
|
439 |
+
if kwargs:
|
440 |
+
warnings.warn(
|
441 |
+
"You cannot override parameters for this Space by passing in kwargs. "
|
442 |
+
"Instead, please load the Space as a function and use it to create a "
|
443 |
+
"Blocks or Interface locally. You may find this Guide helpful: "
|
444 |
+
"https://gradio.app/using_blocks_like_functions/"
|
445 |
+
)
|
446 |
+
if client.app_version < version.Version("4.0.0b14"):
|
447 |
+
return from_spaces_blocks(space=space_name, hf_token=hf_token)
|
448 |
+
|
449 |
+
|
450 |
+
def from_spaces_blocks(space: str, hf_token: str | None) -> Blocks:
|
451 |
+
client = Client(
|
452 |
+
space,
|
453 |
+
hf_token=hf_token,
|
454 |
+
download_files=False,
|
455 |
+
_skip_components=False,
|
456 |
+
)
|
457 |
+
# We set deserialize to False to avoid downloading output files from the server.
|
458 |
+
# Instead, we serve them as URLs using the /proxy/ endpoint directly from the server.
|
459 |
+
|
460 |
+
if client.app_version < version.Version("4.0.0b14"):
|
461 |
+
raise GradioVersionIncompatibleError(
|
462 |
+
f"Gradio version 4.x cannot load spaces with versions less than 4.x ({client.app_version})."
|
463 |
+
"Please downgrade to version 3 to load this space."
|
464 |
+
)
|
465 |
+
|
466 |
+
# Use end_to_end_fn here to properly upload/download all files
|
467 |
+
predict_fns = []
|
468 |
+
for fn_index, endpoint in client.endpoints.items():
|
469 |
+
if not isinstance(endpoint, Endpoint):
|
470 |
+
raise TypeError(
|
471 |
+
f"Expected endpoint to be an Endpoint, but got {type(endpoint)}"
|
472 |
+
)
|
473 |
+
helper = client.new_helper(fn_index)
|
474 |
+
if endpoint.backend_fn:
|
475 |
+
predict_fns.append(endpoint.make_end_to_end_fn(helper))
|
476 |
+
else:
|
477 |
+
predict_fns.append(None)
|
478 |
+
return gradio.Blocks.from_config(client.config, predict_fns, client.src) # type: ignore
|
479 |
+
|
480 |
+
|
481 |
+
def from_spaces_interface(
|
482 |
+
model_name: str,
|
483 |
+
config: dict,
|
484 |
+
alias: str | None,
|
485 |
+
hf_token: str | None,
|
486 |
+
iframe_url: str,
|
487 |
+
**kwargs,
|
488 |
+
) -> Interface:
|
489 |
+
config = external_utils.streamline_spaces_interface(config)
|
490 |
+
api_url = f"{iframe_url}/api/predict/"
|
491 |
+
headers = {"Content-Type": "application/json"}
|
492 |
+
if hf_token is not None:
|
493 |
+
headers["Authorization"] = f"Bearer {hf_token}"
|
494 |
+
|
495 |
+
# The function should call the API with preprocessed data
|
496 |
+
def fn(*data):
|
497 |
+
data = json.dumps({"data": data})
|
498 |
+
response = httpx.post(api_url, headers=headers, data=data) # type: ignore
|
499 |
+
result = json.loads(response.content.decode("utf-8"))
|
500 |
+
if "error" in result and "429" in result["error"]:
|
501 |
+
raise TooManyRequestsError("Too many requests to the Hugging Face API")
|
502 |
+
try:
|
503 |
+
output = result["data"]
|
504 |
+
except KeyError as ke:
|
505 |
+
raise KeyError(
|
506 |
+
f"Could not find 'data' key in response from external Space. Response received: {result}"
|
507 |
+
) from ke
|
508 |
+
if (
|
509 |
+
len(config["outputs"]) == 1
|
510 |
+
): # if the fn is supposed to return a single value, pop it
|
511 |
+
output = output[0]
|
512 |
+
if (
|
513 |
+
len(config["outputs"]) == 1 and isinstance(output, list)
|
514 |
+
): # Needed to support Output.Image() returning bounding boxes as well (TODO: handle different versions of gradio since they have slightly different APIs)
|
515 |
+
output = output[0]
|
516 |
+
return output
|
517 |
+
|
518 |
+
fn.__name__ = alias if (alias is not None) else model_name
|
519 |
+
config["fn"] = fn
|
520 |
+
|
521 |
+
kwargs = dict(config, **kwargs)
|
522 |
+
kwargs["_api_mode"] = True
|
523 |
+
interface = gradio.Interface(**kwargs)
|
524 |
+
return interface
|
525 |
+
|
526 |
+
|
527 |
+
def gr_Interface_load(
|
528 |
+
name: str,
|
529 |
+
src: str | None = None,
|
530 |
+
hf_token: str | None = None,
|
531 |
+
alias: str | None = None,
|
532 |
+
**kwargs,
|
533 |
+
) -> Blocks:
|
534 |
+
try:
|
535 |
+
return load_blocks_from_repo(name, src, hf_token, alias)
|
536 |
+
except Exception as e:
|
537 |
+
print(e)
|
538 |
+
return gradio.Interface(lambda: None, ['text'], ['image'])
|
539 |
+
|
540 |
+
|
541 |
+
def list_uniq(l):
|
542 |
+
return sorted(set(l), key=l.index)
|
543 |
+
|
544 |
+
|
545 |
+
def get_status(model_name: str):
|
546 |
+
from huggingface_hub import InferenceClient
|
547 |
+
client = InferenceClient(timeout=10)
|
548 |
+
return client.get_model_status(model_name)
|
549 |
+
|
550 |
+
|
551 |
+
def is_loadable(model_name: str, force_gpu: bool = False):
|
552 |
+
try:
|
553 |
+
status = get_status(model_name)
|
554 |
+
except Exception as e:
|
555 |
+
print(e)
|
556 |
+
print(f"Couldn't load {model_name}.")
|
557 |
+
return False
|
558 |
+
gpu_state = isinstance(status.compute_type, dict) and "gpu" in status.compute_type.keys()
|
559 |
+
if status is None or status.state not in ["Loadable", "Loaded"] or (force_gpu and not gpu_state):
|
560 |
+
print(f"Couldn't load {model_name}. Model state:'{status.state}', GPU:{gpu_state}")
|
561 |
+
return status is not None and status.state in ["Loadable", "Loaded"] and (not force_gpu or gpu_state)
|
562 |
+
|
563 |
+
|
564 |
+
def find_model_list(author: str="", tags: list[str]=[], not_tag="", sort: str="last_modified", limit: int=30, force_gpu=False, check_status=False):
|
565 |
+
from huggingface_hub import HfApi
|
566 |
+
api = HfApi()
|
567 |
+
default_tags = ["diffusers"]
|
568 |
+
if not sort: sort = "last_modified"
|
569 |
+
limit = limit * 20 if check_status and force_gpu else limit * 5
|
570 |
+
models = []
|
571 |
+
try:
|
572 |
+
model_infos = api.list_models(author=author, task="text-to-image",
|
573 |
+
tags=list_uniq(default_tags + tags), cardData=True, sort=sort, limit=limit)
|
574 |
+
except Exception as e:
|
575 |
+
print(f"Error: Failed to list models.")
|
576 |
+
print(e)
|
577 |
+
return models
|
578 |
+
for model in model_infos:
|
579 |
+
if not model.private and not model.gated:
|
580 |
+
loadable = is_loadable(model.id, force_gpu) if check_status else True
|
581 |
+
if not_tag and not_tag in model.tags or not loadable: continue
|
582 |
+
models.append(model.id)
|
583 |
+
if len(models) == limit: break
|
584 |
+
return models
|