gunship999 commited on
Commit
209a6bd
1 Parent(s): f400a23

Upload 3 files

Browse files
Files changed (3) hide show
  1. all_models.py +107 -0
  2. app (28).py +265 -0
  3. externalmod.py +612 -0
all_models.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ models = [ # Sexy Reality
2
+ "John6666/ultra-v4-sdxl",
3
+ "John6666/ultra-v5-sdxl",
4
+ "wrenth04/pornworks-sexy-beauty-v04-sdxl",
5
+ "John6666/pornworks-sexy-beauty-v04-sdxl",
6
+ "John6666/stallion-dreams-pony-realistic-v1-sdxl",
7
+ "John6666/stoiqo-raffaello-xl-xl2-sdxl",
8
+
9
+ "digiplay/AnalogMadness-realistic-model-v4",
10
+ "digiplay/AnalogMadness-realistic-model-v5",
11
+ "digiplay/AnalogMadness-realistic-model-v6",
12
+ "digiplay/AnalogMadness-realistic-model-v7",
13
+
14
+ "digiplay/Photon_v1",
15
+ "John6666/ultrium-v81-nsfwsfw-sdxl",
16
+ "John6666/mklan-aio-nsfw-aio-nextgen-xlv2-sdxl",
17
+ "John6666/ultrium-v82-nsfwsfw-sdxl",
18
+
19
+ "John6666/stoiqo-afrodite-fluxxl-f1dalpha-fp8-flux",
20
+ "John6666/stoiqo-afrodite-xl-xl31-sdxl",
21
+ "John6666/stoiqo-new-reality-sdxl-xlpro-sdxl",
22
+ "John6666/stoiqo-newreality-sdxl-xl4-sdxl",
23
+
24
+ "John6666/ultimate-realistic-mix-v2-sdxl",
25
+ "John6666/ultimate-realistic-mix-v1-sdxl",
26
+ "John6666/fennfoto-pony-v3-sdxl",
27
+ "digiplay/NextPhoto_v1",
28
+ "digiplay/AbsoluteReality_v1.0_diffusers",
29
+ "digiplay/VoidnoiseCore_R0829",
30
+ ]
31
+
32
+ theRest = [
33
+ "John6666/pretty-pony-v10-sdxl",
34
+ "John6666/lewdify-v80-sdxl",
35
+ "John6666/realism-illustrious-by-stable-yogi-v11dmd2-sdxl",
36
+ "John6666/babes-by-stable-yogi-xlv4-sdxl",
37
+ "John6666/zukiillustrious-cyberfixitercomp-cutev10cyberfixitercomp-sdxl",
38
+ "John6666/purerealism-mix-xl-v10-sdxl",
39
+ "John6666/dramaxl-v10-sdxl",
40
+ "John6666/sevenof9-pony-real-mix-thebest-sdxl",
41
+
42
+
43
+ # "xey/sldr_flux_nsfw_v2-studio",
44
+ # "digiplay/BeenReal_diffusers",
45
+
46
+ "digiplay/AI-infinity-V1-fp16",
47
+
48
+
49
+
50
+ # "John6666/pornworks-anime-desire-nsfw-v02-sdxl",
51
+ # "UnfilteredAI/NSFW-gen-v2.1",
52
+ # "digiplay/VoidnoiseCore_R0829",
53
+ # "digiplay/fantasticmix_k1",
54
+ # "digiplay/WhiteDreamyHillMix_v1_VAE",
55
+
56
+
57
+ "digiplay/chrysanthemumMix_v1",
58
+ "digiplay/majicMIX_realistic_v5",
59
+ "digiplay/majicMIX_realistic_v6",
60
+ "digiplay/majicMIX_realistic_v7",
61
+ "digiplay/PolyMorphMix",
62
+ "digiplay/ya3_xt",
63
+ "digiplay/CleanLinearMix_nsfw",
64
+ "digiplay/Perfect_Gap_Blend_v1",
65
+ "digiplay/MengX_Mix_Real_v3",
66
+
67
+ "stablediffusionapi/newrealityxl-global-nsfw",
68
+ "stablediffusionapi/omnigenxl-nsfw-sfw",
69
+ "stablediffusionapi/mklan-xxx-nsfw-pony",
70
+
71
+ "John6666/unlimited-porn-xreal-sdxl",
72
+ "John6666/wai-real-mix-v8-sdxl-spo",
73
+ "John6666/wai-real-mix-v11-sdxl",
74
+ "John6666/jib-mix-pony-realistic-v2-sdxl",
75
+ "John6666/pony-realism-v21main-sdxl",
76
+ "digiplay/AstrAnime_v6",
77
+ ]
78
+
79
+ yntec_dead = [
80
+ "Yntec/MGM",
81
+ "Yntec/IdleFancy",
82
+ "Yntec/AbsoluteReality",
83
+ "Yntec/Dreamlike",
84
+ "Yntec/theallysMixIV-verisimilar",
85
+ "Yntec/Photosphere",
86
+ "Yntec/BeenYou",
87
+ "Yntec/TheWonderMix",
88
+ "Yntec/Luma",
89
+ "Yntec/DucHaiten-Retro-Diffusers",
90
+ "Yntec/aMovieX",
91
+ "Yntec/CutesyAnime",
92
+ "Yntec/DreamWorks",
93
+ "Yntec/DucHaitenNiji",
94
+
95
+ ]
96
+
97
+ from externalmod import find_model_list
98
+
99
+ #models = find_model_list("Yntec", [], "", "last_modified", 20)
100
+
101
+ # Examples:
102
+ #models = ['yodayo-ai/kivotos-xl-2.0', 'yodayo-ai/holodayo-xl-2.1'] # specific models
103
+ #models = find_model_list("Yntec", [], "", "last_modified", 20) # Yntec's latest 20 models
104
+ #models = find_model_list("Yntec", ["anime"], "", "last_modified", 20) # Yntec's latest 20 models with 'anime' tag
105
+ #models = find_model_list("Yntec", [], "anime", "last_modified", 20) # Yntec's latest 20 models without 'anime' tag
106
+ #models = find_model_list("", [], "", "last_modified", 20) # latest 20 text-to-image models of huggingface
107
+ #models = find_model_list("", [], "", "downloads", 20) # monthly most downloaded 20 text-to-image models of huggingface
app (28).py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from all_models import models
3
+ from externalmod import gr_Interface_load, save_image, randomize_seed
4
+ import asyncio
5
+ import os
6
+ from threading import RLock
7
+ from datetime import datetime
8
+
9
+ preSetPrompt = "cute tall slender athletic 20+ caucasian woman. gorgeous face. perky tits. sensual expression. lifting shirt. photorealistic. cinematic. f1.4"
10
+ # preSetPrompt = "cute tall slender athletic 20+ nude caucasian woman. gorgeous face. perky tits. gaping outie pussy. pussy juice. sly smile. explicit pose. artistic. photorealistic. cinematic. f1.4"
11
+
12
+ # H. R. Giger prompt:
13
+ # preSetPrompt = "a tall slender athletic caucasian nude 18+ female cyborg. gorgeous face. perky tits. wet skin. sensual expression. she is entangled in rusty chains, rusty barbed wire and electric cables. old dark dusty decaying spaceship designed by h.r. giger. rusty metal dildos. wet tubes and wet plastic hoses. dark, gloomy teal cinematic light. photorealistic."
14
+
15
+ negPreSetPrompt = "[deformed | disfigured], poorly drawn, [bad : wrong] anatomy, [extra | missing | floating | disconnected] limb, (mutated hands and fingers), blurry, text, fuzziness"
16
+
17
+ lock = RLock()
18
+ 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.
19
+
20
+ def get_current_time():
21
+ now = datetime.now()
22
+ now2 = now
23
+ current_time = now2.strftime("%y-%m-%d %H:%M:%S")
24
+ return current_time
25
+
26
+ def load_fn(models):
27
+ global models_load
28
+ models_load = {}
29
+ for model in models:
30
+ if model not in models_load.keys():
31
+ try:
32
+ m = gr_Interface_load(f'models/{model}', hf_token=HF_TOKEN)
33
+ except Exception as error:
34
+ print(error)
35
+ m = gr.Interface(lambda: None, ['text'], ['image'])
36
+ models_load.update({model: m})
37
+
38
+
39
+ load_fn(models)
40
+
41
+
42
+ num_models = 6
43
+ max_images = 6
44
+ inference_timeout = 400
45
+ default_models = models[:num_models]
46
+ MAX_SEED = 2**32-1
47
+
48
+
49
+ def extend_choices(choices):
50
+ return choices[:num_models] + (num_models - len(choices[:num_models])) * ['NA']
51
+
52
+
53
+ def update_imgbox(choices):
54
+ choices_plus = extend_choices(choices[:num_models])
55
+ return [gr.Image(None, label=m, visible=(m!='NA')) for m in choices_plus]
56
+
57
+
58
+ def random_choices():
59
+ import random
60
+ random.seed()
61
+ return random.choices(models, k=num_models)
62
+
63
+
64
+ # https://huggingface.co/docs/api-inference/detailed_parameters
65
+ # https://huggingface.co/docs/huggingface_hub/package_reference/inference_client
66
+ async def infer(model_str, prompt, nprompt="", height=0, width=0, steps=0, cfg=0, seed=-1, timeout=inference_timeout):
67
+ kwargs = {}
68
+ if height > 0: kwargs["height"] = height
69
+ if width > 0: kwargs["width"] = width
70
+ if steps > 0: kwargs["num_inference_steps"] = steps
71
+ if cfg > 0: cfg = kwargs["guidance_scale"] = cfg
72
+
73
+ if seed == -1:
74
+ theSeed = randomize_seed()
75
+ kwargs["seed"] = theSeed
76
+ else:
77
+ kwargs["seed"] = seed
78
+ theSeed = seed
79
+
80
+ task = asyncio.create_task(asyncio.to_thread(models_load[model_str].fn, prompt=prompt, negative_prompt=nprompt, **kwargs, token=HF_TOKEN))
81
+ await asyncio.sleep(0)
82
+ try:
83
+ result = await asyncio.wait_for(task, timeout=timeout)
84
+ except asyncio.TimeoutError as e:
85
+ print(e)
86
+ print(f"Task timed out: {model_str}")
87
+ if not task.done(): task.cancel()
88
+ result = None
89
+ raise Exception(f"Task timed out: {model_str}") from e
90
+ except Exception as e:
91
+ print(e)
92
+ if not task.done(): task.cancel()
93
+ result = None
94
+ raise Exception() from e
95
+ if task.done() and result is not None and not isinstance(result, tuple):
96
+ with lock:
97
+ # png_path = "img.png"
98
+ # png_path = get_current_time() + "_" + model_str.replace("/", "_") + ".png"
99
+ # png_path = model_str.replace("/", "_") + " - " + prompt + " - " + get_current_time() + ".png"
100
+ png_path = model_str.replace("/", "_") + " - " + get_current_time() + "_" + str(theSeed) + ".png"
101
+ image = save_image(result, png_path, model_str, prompt, nprompt, height, width, steps, cfg, seed)
102
+ return image
103
+ return None
104
+
105
+
106
+ def gen_fn(model_str, prompt, nprompt="", height=0, width=0, steps=0, cfg=0, seed=-1):
107
+ try:
108
+ loop = asyncio.new_event_loop()
109
+ result = loop.run_until_complete(infer(model_str, prompt, nprompt,
110
+ height, width, steps, cfg, seed, inference_timeout))
111
+ except (Exception, asyncio.CancelledError) as e:
112
+ print(e)
113
+ print(f"Task aborted: {model_str}")
114
+ result = None
115
+ raise gr.Error(f"Task aborted: {model_str}, Error: {e}")
116
+ finally:
117
+ loop.close()
118
+ return result
119
+
120
+
121
+ def add_gallery(image, model_str, gallery):
122
+ if gallery is None: gallery = []
123
+ with lock:
124
+ if image is not None: gallery.insert(0, (image, model_str))
125
+ return gallery
126
+
127
+
128
+ CSS="""
129
+ .gradio-container { max-width: 1200px; margin: 0 auto; !important; }
130
+ .output { width=112px; height=112px; max_width=112px; max_height=112px; !important; }
131
+ .gallery { min_width=512px; min_height=512px; max_height=512px; !important; }
132
+ .guide { text-align: center; !important; }
133
+ """
134
+
135
+ js_func = """
136
+ function refresh() {
137
+ const url = new URL(window.location);
138
+ if (url.searchParams.get('__theme') !== 'dark') {
139
+ url.searchParams.set('__theme', 'dark');
140
+ window.location.href = url.href;
141
+ }
142
+ }
143
+ """
144
+
145
+ js_AutoSave="""
146
+ console.log("Yo");
147
+
148
+ var img1 = document.querySelector("div#component-355 .svelte-1kpcxni button.svelte-1kpcxni .svelte-1kpcxni img"),
149
+ observer = new MutationObserver((changes) => {
150
+ changes.forEach(change => {
151
+ if(change.attributeName.includes('src')){
152
+ console.log(img1.src);
153
+ document.querySelector("div#component-355 .svelte-1kpcxni .svelte-sr71km a.svelte-1s8vnbx button").click();
154
+ }
155
+ });
156
+ });
157
+ observer.observe(img1, {attributes : true});
158
+
159
+ """
160
+
161
+ with gr.Blocks(theme='NoCrypt/miku@>=1.2.2', fill_width=True, css=CSS) as demo:
162
+ # with gr.Blocks(theme='JohnSmith9982/small_and_pretty', fill_width=True, css=CSS, js=js_func) as demo:
163
+ gr.HTML("")
164
+ with gr.Tab('6 Models'):
165
+ with gr.Column(scale=2):
166
+ with gr.Group():
167
+ txt_input = gr.Textbox(label='Your prompt:', value=preSetPrompt, lines=3, autofocus=1)
168
+ neg_input = gr.Textbox(label='Negative prompt:', value=negPreSetPrompt, lines=1)
169
+ with gr.Accordion("Advanced", open=False, visible=True):
170
+ with gr.Row():
171
+ width = gr.Slider(label="Width", info="If 0, the default value is used.", maximum=1216, step=32, value=0)
172
+ height = gr.Slider(label="Height", info="If 0, the default value is used.", maximum=1216, step=32, value=0)
173
+ with gr.Row():
174
+ steps = gr.Slider(label="Number of inference steps", info="If 0, the default value is used.", maximum=100, step=1, value=0)
175
+ cfg = gr.Slider(label="Guidance scale", info="If 0, the default value is used.", maximum=30.0, step=0.1, value=0)
176
+ seed = gr.Slider(label="Seed", info="Randomize Seed if -1.", minimum=-1, maximum=MAX_SEED, step=1, value=-1)
177
+ seed_rand = gr.Button("Randomize Seed 🎲", size="sm", variant="secondary")
178
+ seed_rand.click(randomize_seed, None, [seed], queue=False)
179
+ with gr.Row():
180
+ gen_button = gr.Button(f'Generate up to {int(num_models)} images', variant='primary', scale=3)
181
+ random_button = gr.Button(f'Randomize Models', variant='secondary', scale=1)
182
+ #stop_button = gr.Button('Stop', variant='stop', interactive=False, scale=1)
183
+ #gen_button.click(lambda: gr.update(interactive=True), None, stop_button)
184
+ gr.Markdown("", elem_classes="guide")
185
+
186
+ with gr.Column(scale=1):
187
+ with gr.Group():
188
+ with gr.Row():
189
+ output = [gr.Image(label=m, show_download_button=True, elem_classes="output",
190
+ interactive=False, width=112, height=112, show_share_button=False, format="png",
191
+ visible=True) for m in default_models]
192
+ current_models = [gr.Textbox(m, visible=False) for m in default_models]
193
+
194
+ with gr.Column(scale=2):
195
+ gallery = gr.Gallery(label="Output", show_download_button=True, elem_classes="gallery",
196
+ interactive=False, show_share_button=False, container=True, format="png",
197
+ preview=True, object_fit="cover", columns=2, rows=2)
198
+
199
+ for m, o in zip(current_models, output):
200
+ gen_event = gr.on(triggers=[gen_button.click, txt_input.submit], fn=gen_fn,
201
+ inputs=[m, txt_input, neg_input, height, width, steps, cfg, seed], outputs=[o],
202
+ concurrency_limit=None, queue=False) # Be sure to delete ", queue=False" when activating the stop button
203
+ o.change(add_gallery, [o, m, gallery], [gallery])
204
+ #stop_button.click(lambda: gr.update(interactive=False), None, stop_button, cancels=[gen_event])
205
+
206
+ with gr.Column(scale=4):
207
+ with gr.Accordion('Model selection'):
208
+ model_choice = gr.CheckboxGroup(models, label = f'Choose up to {int(num_models)} different models from the {len(models)} available!', value=default_models, interactive=True)
209
+ model_choice.change(update_imgbox, model_choice, output)
210
+ model_choice.change(extend_choices, model_choice, current_models)
211
+ random_button.click(random_choices, None, model_choice)
212
+
213
+ with gr.Tab('Single model'):
214
+ with gr.Column(scale=2):
215
+ model_choice2 = gr.Dropdown(models, label='Choose model', value=models[0])
216
+ with gr.Group():
217
+ # global preSetPrompt
218
+ # global negPreSetPrompt
219
+ txt_input2 = gr.Textbox(label='Your prompt:', value = preSetPrompt, lines=3, autofocus=1)
220
+ neg_input2 = gr.Textbox(label='Negative prompt:', value=negPreSetPrompt, lines=1)
221
+ with gr.Accordion("Advanced", open=False, visible=True):
222
+ with gr.Row():
223
+ width2 = gr.Slider(label="Width", info="If 0, the default value is used.", maximum=1216, step=32, value=0)
224
+ height2 = gr.Slider(label="Height", info="If 0, the default value is used.", maximum=1216, step=32, value=0)
225
+ with gr.Row():
226
+ steps2 = gr.Slider(label="Number of inference steps", info="If 0, the default value is used.", maximum=100, step=1, value=0)
227
+ cfg2 = gr.Slider(label="Guidance scale", info="If 0, the default value is used.", maximum=30.0, step=0.1, value=0)
228
+ seed2 = gr.Slider(label="Seed", info="Randomize Seed if -1.", minimum=-1, maximum=MAX_SEED, step=1, value=-1)
229
+ seed_rand2 = gr.Button("Randomize Seed", size="sm", variant="secondary")
230
+ seed_rand2.click(randomize_seed, None, [seed2], queue=False)
231
+ num_images = gr.Slider(1, max_images, value=max_images, step=1, label='Number of images')
232
+ with gr.Row():
233
+ gen_button2 = gr.Button('Let the machine halucinate', variant='primary', scale=2)
234
+ #stop_button2 = gr.Button('Stop', variant='stop', interactive=False, scale=1)
235
+ #gen_button2.click(lambda: gr.update(interactive=True), None, stop_button2)
236
+
237
+ with gr.Column(scale=1):
238
+ with gr.Group():
239
+ with gr.Row():
240
+ output2 = [gr.Image(label='', show_download_button=True, elem_classes="output",
241
+ interactive=False, width=112, height=112, visible=True, format="png",
242
+ show_share_button=False, show_label=False) for _ in range(max_images)]
243
+
244
+ with gr.Column(scale=2):
245
+ gallery2 = gr.Gallery(label="Output", show_download_button=True, elem_classes="gallery",
246
+ interactive=False, show_share_button=True, container=True, format="png",
247
+ preview=True, object_fit="cover", columns=2, rows=2)
248
+
249
+ for i, o in enumerate(output2):
250
+ img_i = gr.Number(i, visible=False)
251
+ num_images.change(lambda i, n: gr.update(visible = (i < n)), [img_i, num_images], o, queue=False)
252
+ gen_event2 = gr.on(triggers=[gen_button2.click, txt_input2.submit],
253
+ fn=lambda i, n, m, t1, t2, n1, n2, n3, n4, n5: gen_fn(m, t1, t2, n1, n2, n3, n4, n5) if (i < n) else None,
254
+ inputs=[img_i, num_images, model_choice2, txt_input2, neg_input2,
255
+ height2, width2, steps2, cfg2, seed2], outputs=[o],
256
+ concurrency_limit=None, queue=False) # Be sure to delete ", queue=False" when activating the stop button
257
+ o.change(add_gallery, [o, model_choice2, gallery2], [gallery2])
258
+ #stop_button2.click(lambda: gr.update(interactive=False), None, stop_button2, cancels=[gen_event2])
259
+
260
+ # gr.Markdown(js_AutoSave)
261
+ gr.Markdown("")
262
+
263
+ # demo.queue(default_concurrency_limit=200, max_size=200)
264
+ demo.launch(show_api=False, max_threads=400)
265
+ # demo.launch(show_api=False, max_threads=400, js=js_AutoSave)
externalmod.py ADDED
@@ -0,0 +1,612 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, Literal
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
+ 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.
37
+ server_timeout = 600
38
+
39
+
40
+ @document()
41
+ def load(
42
+ name: str,
43
+ src: str | None = None,
44
+ hf_token: str | Literal[False] | None = None,
45
+ alias: str | None = None,
46
+ **kwargs,
47
+ ) -> Blocks:
48
+ """
49
+ 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
50
+ 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.
51
+ custom `css`, `js`, and `head` attributes) will not be loaded.
52
+ Parameters:
53
+ 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")
54
+ src: the source of the model: `models` or `spaces` (or leave empty if source is provided as a prefix in `name`)
55
+ hf_token: optional access token for loading private Hugging Face Hub models or spaces. Will default to the locally saved token if not provided. Pass `token=False` if you don't want to send your token to the server. Find your token here: https://huggingface.co/settings/tokens. Warning: only provide a token if you are loading a trusted private Space as it can be read by the Space you are loading.
56
+ 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)
57
+ Returns:
58
+ a Gradio Blocks object for the given model
59
+ Example:
60
+ import gradio as gr
61
+ demo = gr.load("gradio/question-answering", src="spaces")
62
+ demo.launch()
63
+ """
64
+ return load_blocks_from_repo(
65
+ name=name, src=src, hf_token=hf_token, alias=alias, **kwargs
66
+ )
67
+
68
+
69
+ def load_blocks_from_repo(
70
+ name: str,
71
+ src: str | None = None,
72
+ hf_token: str | Literal[False] | None = None,
73
+ alias: str | None = None,
74
+ **kwargs,
75
+ ) -> Blocks:
76
+ """Creates and returns a Blocks instance from a Hugging Face model or Space repo."""
77
+ if src is None:
78
+ # Separate the repo type (e.g. "model") from repo name (e.g. "google/vit-base-patch16-224")
79
+ tokens = name.split("/")
80
+ if len(tokens) <= 1:
81
+ raise ValueError(
82
+ "Either `src` parameter must be provided, or `name` must be formatted as {src}/{repo name}"
83
+ )
84
+ src = tokens[0]
85
+ name = "/".join(tokens[1:])
86
+
87
+ factory_methods: dict[str, Callable] = {
88
+ # for each repo type, we have a method that returns the Interface given the model name & optionally an hf_token
89
+ "huggingface": from_model,
90
+ "models": from_model,
91
+ "spaces": from_spaces,
92
+ }
93
+ if src.lower() not in factory_methods:
94
+ raise ValueError(f"parameter: src must be one of {factory_methods.keys()}")
95
+
96
+ if hf_token is not None and hf_token is not False:
97
+ if Context.hf_token is not None and Context.hf_token != hf_token:
98
+ warnings.warn(
99
+ """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."""
100
+ )
101
+ Context.hf_token = hf_token
102
+
103
+ blocks: gradio.Blocks = factory_methods[src](name, hf_token, alias, **kwargs)
104
+ return blocks
105
+
106
+
107
+ def from_model(
108
+ model_name: str, hf_token: str | Literal[False] | None, alias: str | None, **kwargs
109
+ ):
110
+ model_url = f"https://huggingface.co/{model_name}"
111
+ api_url = f"https://api-inference.huggingface.co/models/{model_name}"
112
+ print(f"Fetching model from: {model_url}")
113
+
114
+ headers = (
115
+ {} if hf_token in [False, None] else {"Authorization": f"Bearer {hf_token}"}
116
+ )
117
+ response = httpx.request("GET", api_url, headers=headers)
118
+ if response.status_code != 200:
119
+ raise ModelNotFoundError(
120
+ 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."
121
+ )
122
+ p = response.json().get("pipeline_tag")
123
+
124
+ headers["X-Wait-For-Model"] = "true"
125
+ client = huggingface_hub.InferenceClient(
126
+ model=model_name, headers=headers, token=hf_token, timeout=server_timeout,
127
+ )
128
+
129
+ # For tasks that are not yet supported by the InferenceClient
130
+ GRADIO_CACHE = os.environ.get("GRADIO_TEMP_DIR") or str( # noqa: N806
131
+ Path(tempfile.gettempdir()) / "gradio"
132
+ )
133
+
134
+ def custom_post_binary(data):
135
+ data = to_binary({"path": data})
136
+ response = httpx.request("POST", api_url, headers=headers, content=data)
137
+ return save_base64_to_cache(
138
+ external_utils.encode_to_base64(response), cache_dir=GRADIO_CACHE
139
+ )
140
+
141
+ preprocess = None
142
+ postprocess = None
143
+ examples = None
144
+
145
+ # example model: ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition
146
+ if p == "audio-classification":
147
+ inputs = components.Audio(type="filepath", label="Input")
148
+ outputs = components.Label(label="Class")
149
+ postprocess = external_utils.postprocess_label
150
+ examples = [
151
+ "https://gradio-builds.s3.amazonaws.com/demo-files/audio_sample.wav"
152
+ ]
153
+ fn = client.audio_classification
154
+ # example model: facebook/xm_transformer_sm_all-en
155
+ elif p == "audio-to-audio":
156
+ inputs = components.Audio(type="filepath", label="Input")
157
+ outputs = components.Audio(label="Output")
158
+ examples = [
159
+ "https://gradio-builds.s3.amazonaws.com/demo-files/audio_sample.wav"
160
+ ]
161
+ fn = custom_post_binary
162
+ # example model: facebook/wav2vec2-base-960h
163
+ elif p == "automatic-speech-recognition":
164
+ inputs = components.Audio(type="filepath", label="Input")
165
+ outputs = components.Textbox(label="Output")
166
+ examples = [
167
+ "https://gradio-builds.s3.amazonaws.com/demo-files/audio_sample.wav"
168
+ ]
169
+ fn = client.automatic_speech_recognition
170
+ # example model: microsoft/DialoGPT-medium
171
+ elif p == "conversational":
172
+ inputs = [
173
+ components.Textbox(render=False),
174
+ components.State(render=False),
175
+ ]
176
+ outputs = [
177
+ components.Chatbot(render=False),
178
+ components.State(render=False),
179
+ ]
180
+ examples = [["Hello World"]]
181
+ preprocess = external_utils.chatbot_preprocess
182
+ postprocess = external_utils.chatbot_postprocess
183
+ fn = client.conversational
184
+ # example model: julien-c/distilbert-feature-extraction
185
+ elif p == "feature-extraction":
186
+ inputs = components.Textbox(label="Input")
187
+ outputs = components.Dataframe(label="Output")
188
+ fn = client.feature_extraction
189
+ postprocess = utils.resolve_singleton
190
+ # example model: distilbert/distilbert-base-uncased
191
+ elif p == "fill-mask":
192
+ inputs = components.Textbox(label="Input")
193
+ outputs = components.Label(label="Classification")
194
+ examples = [
195
+ "Hugging Face is the AI community, working together, to [MASK] the future."
196
+ ]
197
+ postprocess = external_utils.postprocess_mask_tokens
198
+ fn = client.fill_mask
199
+ # Example: google/vit-base-patch16-224
200
+ elif p == "image-classification":
201
+ inputs = components.Image(type="filepath", label="Input Image")
202
+ outputs = components.Label(label="Classification")
203
+ postprocess = external_utils.postprocess_label
204
+ examples = ["https://gradio-builds.s3.amazonaws.com/demo-files/cheetah-002.jpg"]
205
+ fn = client.image_classification
206
+ # Example: deepset/xlm-roberta-base-squad2
207
+ elif p == "question-answering":
208
+ inputs = [
209
+ components.Textbox(label="Question"),
210
+ components.Textbox(lines=7, label="Context"),
211
+ ]
212
+ outputs = [
213
+ components.Textbox(label="Answer"),
214
+ components.Label(label="Score"),
215
+ ]
216
+ examples = [
217
+ [
218
+ "What entity was responsible for the Apollo program?",
219
+ "The Apollo program, also known as Project Apollo, was the third United States human spaceflight"
220
+ " program carried out by the National Aeronautics and Space Administration (NASA), which accomplished"
221
+ " landing the first humans on the Moon from 1969 to 1972.",
222
+ ]
223
+ ]
224
+ postprocess = external_utils.postprocess_question_answering
225
+ fn = client.question_answering
226
+ # Example: facebook/bart-large-cnn
227
+ elif p == "summarization":
228
+ inputs = components.Textbox(label="Input")
229
+ outputs = components.Textbox(label="Summary")
230
+ examples = [
231
+ [
232
+ "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."
233
+ ]
234
+ ]
235
+ fn = client.summarization
236
+ # Example: distilbert-base-uncased-finetuned-sst-2-english
237
+ elif p == "text-classification":
238
+ inputs = components.Textbox(label="Input")
239
+ outputs = components.Label(label="Classification")
240
+ examples = ["I feel great"]
241
+ postprocess = external_utils.postprocess_label
242
+ fn = client.text_classification
243
+ # Example: gpt2
244
+ elif p == "text-generation":
245
+ inputs = components.Textbox(label="Text")
246
+ outputs = inputs
247
+ examples = ["Once upon a time"]
248
+ fn = external_utils.text_generation_wrapper(client)
249
+ # Example: valhalla/t5-small-qa-qg-hl
250
+ elif p == "text2text-generation":
251
+ inputs = components.Textbox(label="Input")
252
+ outputs = components.Textbox(label="Generated Text")
253
+ examples = ["Translate English to Arabic: How are you?"]
254
+ fn = client.text_generation
255
+ # Example: Helsinki-NLP/opus-mt-en-ar
256
+ elif p == "translation":
257
+ inputs = components.Textbox(label="Input")
258
+ outputs = components.Textbox(label="Translation")
259
+ examples = ["Hello, how are you?"]
260
+ fn = client.translation
261
+ # Example: facebook/bart-large-mnli
262
+ elif p == "zero-shot-classification":
263
+ inputs = [
264
+ components.Textbox(label="Input"),
265
+ components.Textbox(label="Possible class names (" "comma-separated)"),
266
+ components.Checkbox(label="Allow multiple true classes"),
267
+ ]
268
+ outputs = components.Label(label="Classification")
269
+ postprocess = external_utils.postprocess_label
270
+ examples = [["I feel great", "happy, sad", False]]
271
+ fn = external_utils.zero_shot_classification_wrapper(client)
272
+ # Example: sentence-transformers/distilbert-base-nli-stsb-mean-tokens
273
+ elif p == "sentence-similarity":
274
+ inputs = [
275
+ components.Textbox(
276
+ label="Source Sentence",
277
+ placeholder="Enter an original sentence",
278
+ ),
279
+ components.Textbox(
280
+ lines=7,
281
+ placeholder="Sentences to compare to -- separate each sentence by a newline",
282
+ label="Sentences to compare to",
283
+ ),
284
+ ]
285
+ outputs = components.JSON(label="Similarity scores")
286
+ examples = [["That is a happy person", "That person is very happy"]]
287
+ fn = external_utils.sentence_similarity_wrapper(client)
288
+ # Example: julien-c/ljspeech_tts_train_tacotron2_raw_phn_tacotron_g2p_en_no_space_train
289
+ elif p == "text-to-speech":
290
+ inputs = components.Textbox(label="Input")
291
+ outputs = components.Audio(label="Audio")
292
+ examples = ["Hello, how are you?"]
293
+ fn = client.text_to_speech
294
+ # example model: osanseviero/BigGAN-deep-128
295
+ elif p == "text-to-image":
296
+ inputs = components.Textbox(label="Input")
297
+ outputs = components.Image(label="Output")
298
+ examples = ["A beautiful sunset"]
299
+ fn = client.text_to_image
300
+ # example model: huggingface-course/bert-finetuned-ner
301
+ elif p == "token-classification":
302
+ inputs = components.Textbox(label="Input")
303
+ outputs = components.HighlightedText(label="Output")
304
+ examples = [
305
+ "Hugging Face is a company based in Paris and New York City that acquired Gradio in 2021."
306
+ ]
307
+ fn = external_utils.token_classification_wrapper(client)
308
+ # example model: impira/layoutlm-document-qa
309
+ elif p == "document-question-answering":
310
+ inputs = [
311
+ components.Image(type="filepath", label="Input Document"),
312
+ components.Textbox(label="Question"),
313
+ ]
314
+ postprocess = external_utils.postprocess_label
315
+ outputs = components.Label(label="Label")
316
+ fn = client.document_question_answering
317
+ # example model: dandelin/vilt-b32-finetuned-vqa
318
+ elif p == "visual-question-answering":
319
+ inputs = [
320
+ components.Image(type="filepath", label="Input Image"),
321
+ components.Textbox(label="Question"),
322
+ ]
323
+ outputs = components.Label(label="Label")
324
+ postprocess = external_utils.postprocess_visual_question_answering
325
+ examples = [
326
+ [
327
+ "https://gradio-builds.s3.amazonaws.com/demo-files/cheetah-002.jpg",
328
+ "What animal is in the image?",
329
+ ]
330
+ ]
331
+ fn = client.visual_question_answering
332
+ # example model: Salesforce/blip-image-captioning-base
333
+ elif p == "image-to-text":
334
+ inputs = components.Image(type="filepath", label="Input Image")
335
+ outputs = components.Textbox(label="Generated Text")
336
+ examples = ["https://gradio-builds.s3.amazonaws.com/demo-files/cheetah-002.jpg"]
337
+ fn = client.image_to_text
338
+ # example model: rajistics/autotrain-Adult-934630783
339
+ elif p in ["tabular-classification", "tabular-regression"]:
340
+ examples = external_utils.get_tabular_examples(model_name)
341
+ col_names, examples = external_utils.cols_to_rows(examples) # type: ignore
342
+ examples = [[examples]] if examples else None
343
+ inputs = components.Dataframe(
344
+ label="Input Rows",
345
+ type="pandas",
346
+ headers=col_names,
347
+ col_count=(len(col_names), "fixed"),
348
+ render=False,
349
+ )
350
+ outputs = components.Dataframe(
351
+ label="Predictions", type="array", headers=["prediction"]
352
+ )
353
+ fn = external_utils.tabular_wrapper
354
+ # example model: microsoft/table-transformer-detection
355
+ elif p == "object-detection":
356
+ inputs = components.Image(type="filepath", label="Input Image")
357
+ outputs = components.AnnotatedImage(label="Annotations")
358
+ fn = external_utils.object_detection_wrapper(client)
359
+ # example model: stabilityai/stable-diffusion-xl-refiner-1.0
360
+ elif p == "image-to-image":
361
+ inputs = [
362
+ components.Image(type="filepath", label="Input Image"),
363
+ components.Textbox(label="Input"),
364
+ ]
365
+ outputs = components.Image(label="Output")
366
+ examples = [
367
+ [
368
+ "https://gradio-builds.s3.amazonaws.com/demo-files/cheetah-002.jpg",
369
+ "Photo of a cheetah with green eyes",
370
+ ]
371
+ ]
372
+ fn = client.image_to_image
373
+ else:
374
+ raise ValueError(f"Unsupported pipeline type: {p}")
375
+
376
+ def query_huggingface_inference_endpoints(*data, **kwargs):
377
+ if preprocess is not None:
378
+ data = preprocess(*data)
379
+ try:
380
+ data = fn(*data, **kwargs) # type: ignore
381
+ except huggingface_hub.utils.HfHubHTTPError as e:
382
+ if "429" in str(e):
383
+ raise TooManyRequestsError() from e
384
+ if postprocess is not None:
385
+ data = postprocess(data) # type: ignore
386
+ return data
387
+
388
+ query_huggingface_inference_endpoints.__name__ = alias or model_name
389
+
390
+ interface_info = {
391
+ "fn": query_huggingface_inference_endpoints,
392
+ "inputs": inputs,
393
+ "outputs": outputs,
394
+ "title": model_name,
395
+ #"examples": examples,
396
+ }
397
+
398
+ kwargs = dict(interface_info, **kwargs)
399
+ interface = gradio.Interface(**kwargs)
400
+ return interface
401
+
402
+
403
+ def from_spaces(
404
+ space_name: str, hf_token: str | None, alias: str | None, **kwargs
405
+ ) -> Blocks:
406
+ space_url = f"https://huggingface.co/spaces/{space_name}"
407
+
408
+ print(f"Fetching Space from: {space_url}")
409
+
410
+ headers = {}
411
+ if hf_token not in [False, None]:
412
+ headers["Authorization"] = f"Bearer {hf_token}"
413
+
414
+ iframe_url = (
415
+ httpx.get(
416
+ f"https://huggingface.co/api/spaces/{space_name}/host", headers=headers
417
+ )
418
+ .json()
419
+ .get("host")
420
+ )
421
+
422
+ if iframe_url is None:
423
+ raise ValueError(
424
+ 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."
425
+ )
426
+
427
+ r = httpx.get(iframe_url, headers=headers)
428
+
429
+ result = re.search(
430
+ r"window.gradio_config = (.*?);[\s]*</script>", r.text
431
+ ) # some basic regex to extract the config
432
+ try:
433
+ config = json.loads(result.group(1)) # type: ignore
434
+ except AttributeError as ae:
435
+ raise ValueError(f"Could not load the Space: {space_name}") from ae
436
+ if "allow_flagging" in config: # Create an Interface for Gradio 2.x Spaces
437
+ return from_spaces_interface(
438
+ space_name, config, alias, hf_token, iframe_url, **kwargs
439
+ )
440
+ else: # Create a Blocks for Gradio 3.x Spaces
441
+ if kwargs:
442
+ warnings.warn(
443
+ "You cannot override parameters for this Space by passing in kwargs. "
444
+ "Instead, please load the Space as a function and use it to create a "
445
+ "Blocks or Interface locally. You may find this Guide helpful: "
446
+ "https://gradio.app/using_blocks_like_functions/"
447
+ )
448
+ return from_spaces_blocks(space=space_name, hf_token=hf_token)
449
+
450
+
451
+ def from_spaces_blocks(space: str, hf_token: str | None) -> Blocks:
452
+ client = Client(
453
+ space,
454
+ hf_token=hf_token,
455
+ download_files=False,
456
+ _skip_components=False,
457
+ )
458
+ # We set deserialize to False to avoid downloading output files from the server.
459
+ # Instead, we serve them as URLs using the /proxy/ endpoint directly from the server.
460
+
461
+ if client.app_version < version.Version("4.0.0b14"):
462
+ raise GradioVersionIncompatibleError(
463
+ f"Gradio version 4.x cannot load spaces with versions less than 4.x ({client.app_version})."
464
+ "Please downgrade to version 3 to load this space."
465
+ )
466
+
467
+ # Use end_to_end_fn here to properly upload/download all files
468
+ predict_fns = []
469
+ for fn_index, endpoint in client.endpoints.items():
470
+ if not isinstance(endpoint, Endpoint):
471
+ raise TypeError(
472
+ f"Expected endpoint to be an Endpoint, but got {type(endpoint)}"
473
+ )
474
+ helper = client.new_helper(fn_index)
475
+ if endpoint.backend_fn:
476
+ predict_fns.append(endpoint.make_end_to_end_fn(helper))
477
+ else:
478
+ predict_fns.append(None)
479
+ return gradio.Blocks.from_config(client.config, predict_fns, client.src) # type: ignore
480
+
481
+
482
+ def from_spaces_interface(
483
+ model_name: str,
484
+ config: dict,
485
+ alias: str | None,
486
+ hf_token: str | None,
487
+ iframe_url: str,
488
+ **kwargs,
489
+ ) -> Interface:
490
+ config = external_utils.streamline_spaces_interface(config)
491
+ api_url = f"{iframe_url}/api/predict/"
492
+ headers = {"Content-Type": "application/json"}
493
+ if hf_token not in [False, None]:
494
+ headers["Authorization"] = f"Bearer {hf_token}"
495
+
496
+ # The function should call the API with preprocessed data
497
+ def fn(*data):
498
+ data = json.dumps({"data": data})
499
+ response = httpx.post(api_url, headers=headers, data=data) # type: ignore
500
+ result = json.loads(response.content.decode("utf-8"))
501
+ if "error" in result and "429" in result["error"]:
502
+ raise TooManyRequestsError("Too many requests to the Hugging Face API")
503
+ try:
504
+ output = result["data"]
505
+ except KeyError as ke:
506
+ raise KeyError(
507
+ f"Could not find 'data' key in response from external Space. Response received: {result}"
508
+ ) from ke
509
+ if (
510
+ len(config["outputs"]) == 1
511
+ ): # if the fn is supposed to return a single value, pop it
512
+ output = output[0]
513
+ if (
514
+ len(config["outputs"]) == 1 and isinstance(output, list)
515
+ ): # Needed to support Output.Image() returning bounding boxes as well (TODO: handle different versions of gradio since they have slightly different APIs)
516
+ output = output[0]
517
+ return output
518
+
519
+ fn.__name__ = alias if (alias is not None) else model_name
520
+ config["fn"] = fn
521
+
522
+ kwargs = dict(config, **kwargs)
523
+ kwargs["_api_mode"] = True
524
+ interface = gradio.Interface(**kwargs)
525
+ return interface
526
+
527
+
528
+ def gr_Interface_load(
529
+ name: str,
530
+ src: str | None = None,
531
+ hf_token: str | None = None,
532
+ alias: str | None = None,
533
+ **kwargs, # ignore
534
+ ) -> Blocks:
535
+ try:
536
+ return load_blocks_from_repo(name, src, hf_token, alias)
537
+ except Exception as e:
538
+ print(e)
539
+ return gradio.Interface(lambda: None, ['text'], ['image'])
540
+
541
+
542
+ def list_uniq(l):
543
+ return sorted(set(l), key=l.index)
544
+
545
+
546
+ def get_status(model_name: str):
547
+ from huggingface_hub import AsyncInferenceClient
548
+ client = AsyncInferenceClient(token=HF_TOKEN, timeout=10)
549
+ return client.get_model_status(model_name)
550
+
551
+
552
+ def is_loadable(model_name: str, force_gpu: bool = False):
553
+ try:
554
+ status = get_status(model_name)
555
+ except Exception as e:
556
+ print(e)
557
+ print(f"Couldn't load {model_name}.")
558
+ return False
559
+ gpu_state = isinstance(status.compute_type, dict) and "gpu" in status.compute_type.keys()
560
+ if status is None or status.state not in ["Loadable", "Loaded"] or (force_gpu and not gpu_state):
561
+ print(f"Couldn't load {model_name}. Model state:'{status.state}', GPU:{gpu_state}")
562
+ return status is not None and status.state in ["Loadable", "Loaded"] and (not force_gpu or gpu_state)
563
+
564
+
565
+ def find_model_list(author: str="", tags: list[str]=[], not_tag="", sort: str="last_modified", limit: int=30, force_gpu=False, check_status=False):
566
+ from huggingface_hub import HfApi
567
+ api = HfApi(token=HF_TOKEN)
568
+ default_tags = ["diffusers"]
569
+ if not sort: sort = "last_modified"
570
+ limit = limit * 20 if check_status and force_gpu else limit * 5
571
+ models = []
572
+ try:
573
+ model_infos = api.list_models(author=author, #task="text-to-image",
574
+ tags=list_uniq(default_tags + tags), cardData=True, sort=sort, limit=limit)
575
+ except Exception as e:
576
+ print(f"Error: Failed to list models.")
577
+ print(e)
578
+ return models
579
+ for model in model_infos:
580
+ if not model.private and not model.gated or HF_TOKEN is not None:
581
+ loadable = is_loadable(model.id, force_gpu) if check_status else True
582
+ if not_tag and not_tag in model.tags or not loadable: continue
583
+ models.append(model.id)
584
+ if len(models) == limit: break
585
+ return models
586
+
587
+
588
+ def save_image(image, savefile, modelname, prompt, nprompt, height=0, width=0, steps=0, cfg=0, seed=-1):
589
+ from PIL import Image, PngImagePlugin
590
+ import json
591
+ try:
592
+ metadata = {"prompt": prompt, "negative_prompt": nprompt, "Model": {"Model": modelname.split("/")[-1]}}
593
+ if steps > 0: metadata["num_inference_steps"] = steps
594
+ if cfg > 0: metadata["guidance_scale"] = cfg
595
+ if seed != -1: metadata["seed"] = seed
596
+ if width > 0 and height > 0: metadata["resolution"] = f"{width} x {height}"
597
+ metadata_str = json.dumps(metadata)
598
+ info = PngImagePlugin.PngInfo()
599
+ info.add_text("metadata", metadata_str)
600
+ image.save(savefile, "PNG", pnginfo=info)
601
+ return str(Path(savefile).resolve())
602
+ except Exception as e:
603
+ print(f"Failed to save image file: {e}")
604
+ raise Exception(f"Failed to save image file:") from e
605
+
606
+
607
+ def randomize_seed():
608
+ from random import seed, randint
609
+ MAX_SEED = 2**32-1
610
+ seed()
611
+ rseed = randint(0, MAX_SEED)
612
+ return rseed