John6666 commited on
Commit
c317a40
β€’
1 Parent(s): 8ffb119

Upload 6 files

Browse files
Files changed (4) hide show
  1. README.md +14 -14
  2. app.py +83 -165
  3. externalmod.py +612 -0
  4. requirements.txt +2 -3
README.md CHANGED
@@ -1,14 +1,14 @@
1
- ---
2
- title: 899 Models Blitz Diffusion
3
- emoji: πŸ‘©β€πŸŽ¨πŸ‘¨β€πŸŽ¨
4
- colorFrom: red
5
- colorTo: blue
6
- sdk: gradio
7
- sdk_version: 3.15.0
8
- app_file: app.py
9
- pinned: false
10
- duplicated_from: classic_maximum_multiplier_places
11
- short_description: Classic ToyWorld UI with prompt enhancer!
12
- ---
13
-
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
+ ---
2
+ title: 899 Models Blitz Diffusion (Gradio 5.x)
3
+ emoji: πŸ‘©β€πŸŽ¨πŸ‘¨β€πŸŽ¨
4
+ colorFrom: red
5
+ colorTo: blue
6
+ sdk: gradio
7
+ sdk_version: 5.0.1
8
+ app_file: app.py
9
+ pinned: false
10
+ duplicated_from: classic_maximum_multiplier_places
11
+ short_description: Classic ToyWorld UI with prompt enhancer!
12
+ ---
13
+
14
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py CHANGED
@@ -1,11 +1,8 @@
1
  import gradio as gr
2
- import os
3
- import sys
4
- from pathlib import Path
5
  from all_models import models
6
- from externalmod3 import gr_Interface_load
7
  from prompt_extend import extend_prompt
8
- from random import randint
9
  import asyncio
10
  from threading import RLock
11
  lock = RLock()
@@ -13,39 +10,14 @@ HF_TOKEN = os.environ.get("HF_TOKEN") if os.environ.get("HF_TOKEN") else None #
13
 
14
  inference_timeout = 300
15
  MAX_SEED = 2**32-1
16
-
17
- """models = [ # for debugging
18
- "nicky007/stable-diffusion-logo-fine-tuned",
19
- "stablediffusionapi/three-delicacy", #233
20
- "stablediffusionapi/three-delicacy-wonto", #234
21
- "naclbit/trinart_stable_diffusion_v2",
22
- "dallinmackay/Tron-Legacy-diffusion",
23
- "digiplay/unstableDiffusersYamerMIX_v3",
24
- "dallinmackay/Van-Gogh-diffusion",
25
- "ItsJayQz/Valorant_Diffusion",
26
- "Fictiverse/Stable_Diffusion_VoxelArt_Model", #204
27
- "wavymulder/wavyfusion",
28
- ]"""
29
-
30
  current_model = models[0]
31
-
32
- #text_gen1=gr.Interface.load("spaces/phenomenon1981/MagicPrompt-Stable-Diffusion")
33
- #text_gen1=gr.Interface.load("spaces/Yntec/prompt-extend")
34
  text_gen1 = extend_prompt
35
- #text_gen1=gr.Interface.load("spaces/daspartho/prompt-extend")
36
- #text_gen1=gr.Interface.load("spaces/Omnibus/MagicPrompt-Stable-Diffusion_link")
37
 
38
- models2 = []
39
- for m in models:
40
- try:
41
- models2.append(gr_Interface_load(f"models/{m}", hf_token=HF_TOKEN))
42
- except Exception as e:
43
- print(e)
44
- models2.append(gr.Interface(lambda: None, ['text'], ['image']))
45
 
46
  def text_it1(inputs, text_gen1=text_gen1):
47
  go_t1 = text_gen1(inputs)
48
- return (go_t1)
49
 
50
  def set_model(current_model):
51
  current_model = models[current_model]
@@ -57,180 +29,126 @@ def send_it1(inputs, model_choice, neg_input, height, width, steps, cfg, seed):
57
 
58
  # https://huggingface.co/docs/api-inference/detailed_parameters
59
  # https://huggingface.co/docs/huggingface_hub/package_reference/inference_client
60
- async def infer(model_index, prompt, nprompt="", height=None, width=None, steps=None, cfg=None, seed=-1, timeout=inference_timeout):
61
- from pathlib import Path
62
  kwargs = {}
63
- if height is not None and height >= 256: kwargs["height"] = height
64
- if width is not None and width >= 256: kwargs["width"] = width
65
- if steps is not None and steps >= 1: kwargs["num_inference_steps"] = steps
66
- if cfg is not None and cfg > 0: cfg = kwargs["guidance_scale"] = cfg
67
- noise = ""
68
- if seed >= 0: kwargs["seed"] = seed
69
- else:
70
- rand = randint(1, 500)
71
- for i in range(rand):
72
- noise += " "
73
  task = asyncio.create_task(asyncio.to_thread(models2[model_index].fn,
74
- f'{prompt} {noise}', negative_prompt=nprompt, **kwargs, token=HF_TOKEN))
75
  await asyncio.sleep(0)
76
  try:
77
  result = await asyncio.wait_for(task, timeout=timeout)
78
- except (Exception, asyncio.TimeoutError) as e:
 
 
 
 
 
 
79
  print(e)
80
- print(f"Task timed out: {models2[model_index]}")
81
  if not task.done(): task.cancel()
82
  result = None
83
- if task.done() and result is not None:
 
84
  with lock:
85
  png_path = "image.png"
86
- result.save(png_path)
87
- image = str(Path(png_path).resolve())
88
  return image
89
  return None
90
 
91
- def gen_fn(model_index, prompt, nprompt="", height=None, width=None, steps=None, cfg=None, seed=-1):
92
  try:
93
  loop = asyncio.new_event_loop()
94
  result = loop.run_until_complete(infer(model_index, prompt, nprompt,
95
  height, width, steps, cfg, seed, inference_timeout))
96
  except (Exception, asyncio.CancelledError) as e:
97
  print(e)
98
- print(f"Task aborted: {models2[model_index]}")
99
  result = None
 
100
  finally:
101
  loop.close()
102
  return result
103
 
104
- css=""""""
 
 
 
 
 
 
 
 
 
 
 
 
 
105
 
106
- with gr.Blocks(css=css) as myface:
107
  gr.HTML(f"""
108
- <div style="text-align: center; max-width: 1200px; margin: 0 auto;">
109
- <div>
110
- <style>
111
- h1 {{
112
- font-size: 6em;
113
- color: #ffc99f;
114
- margin-top: 30px;
115
- margin-bottom: 30px;
116
- text-shadow: 3px 3px 0 rgba(0, 0, 0, 1) !important;
117
- }}
118
- h3 {{
119
- color: #ffc99f; !important;
120
- }}
121
- h4 {{
122
- display: inline-block;
123
- color: #ffffff !important;
124
- }}
125
- .wrapper img {{
126
- font-size: 98% !important;
127
- white-space: nowrap !important;
128
- text-align: center !important;
129
- display: inline-block !important;
130
- color: #ffffff !important;
131
- }}
132
- .wrapper {{
133
- color: #ffffff !important;
134
- }}
135
- .gradio-container {{
136
- background-image: linear-gradient(#254150, #1e2f40, #182634) !important;
137
- color: #ffaa66 !important;
138
- font-family: 'IBM Plex Sans', sans-serif !important;
139
- }}
140
- .text-gray-500 {{
141
- color: #ffc99f !important;
142
- }}
143
- .gr-box {{
144
- background-image: linear-gradient(#182634, #1e2f40, #254150) !important;
145
- border-top-color: #000000 !important;
146
- border-right-color: #ffffff !important;
147
- border-bottom-color: #ffffff !important;
148
- border-left-color: #000000 !important;
149
- }}
150
- .gr-input {{
151
- color: #ffc99f; !important;
152
- background-color: #254150 !important;
153
- }}
154
- :root {{
155
- --neutral-100: #000000 !important;
156
- }}
157
- </style>
158
- <body>
159
- <div class="center"><h1>Blitz Diffusion</h1>
160
- </div>
161
- </body>
162
- </div>
163
- <p style="margin-bottom: 1px; color: #ffaa66;">
164
- <h3>{int(len(models))} Stable Diffusion models, but why? For your enjoyment!</h3></p>
165
- <br><div class="wrapper">9.3 <img src="https://huggingface.co/Yntec/DucHaitenLofi/resolve/main/NEW.webp" alt="NEW!" style="width:32px;height:16px;">This has become a legacy backup copy of old <u><a href="https://huggingface.co/spaces/Yntec/ToyWorld">ToyWorld</a></u>'s UI! Newer models added dailty over there! 25 new models since last update!</div>
166
- <p style="margin-bottom: 1px; font-size: 98%">
167
- <br><h4>If a model is already loaded each new image takes less than <b>10</b> seconds to generate!</h4></p>
168
- <p style="margin-bottom: 1px; color: #ffffff;">
169
- <br><div class="wrapper">Generate 6 images from 1 prompt at the <u><a href="https://huggingface.co/spaces/Yntec/PrintingPress">PrintingPress</a></u>, and use 6 different models at <u><a href="https://huggingface.co/spaces/Yntec/diffusion80xx">Huggingface Diffusion!</a></u>!
170
- </p></p>
171
- </div>
172
- """)
173
  with gr.Row():
174
  with gr.Column(scale=100):
175
- #Model selection dropdown
176
- model_name1 = gr.Dropdown(label="Select Model", choices=[m for m in models], type="index", value=current_model, interactive=True)
 
177
  with gr.Row():
178
  with gr.Column(scale=100):
179
- with gr.Group():
180
- magic1 = gr.Textbox(label="Your Prompt", lines=4) #Positive
181
  with gr.Accordion("Advanced", open=False, visible=True):
182
- neg_input = gr.Textbox(label='Negative prompt', lines=1)
183
  with gr.Row():
184
- width = gr.Slider(label="Width", maximum=1216, step=32, value=0)
185
- height = gr.Slider(label="Height", maximum=1216, step=32, value=0)
186
  with gr.Row():
187
- steps = gr.Slider(label="Number of inference steps", maximum=100, step=1, value=0)
188
- cfg = gr.Slider(label="Guidance scale", maximum=30.0, step=0.1, value=0)
189
- seed = gr.Slider(label="Seed", minimum=-1, maximum=MAX_SEED, step=1, value=-1)
 
 
190
 
191
- gr.HTML("""<style> .gr-button {
192
- color: #ffffff !important;
193
- text-shadow: 1px 1px 0 rgba(0, 0, 0, 1) !important;
194
- background-image: linear-gradient(#76635a, #d2a489) !important;
195
- border-radius: 24px !important;
196
- border: solid 1px !important;
197
- border-top-color: #ffc99f !important;
198
- border-right-color: #000000 !important;
199
- border-bottom-color: #000000 !important;
200
- border-left-color: #ffc99f !important;
201
- padding: 6px 30px;
202
- }
203
- .gr-button:active {
204
- color: #ffc99f !important;
205
- font-size: 98% !important;
206
- text-shadow: 0px 0px 0 rgba(0, 0, 0, 1) !important;
207
- background-image: linear-gradient(#d2a489, #76635a) !important;
208
- border-top-color: #000000 !important;
209
- border-right-color: #ffffff !important;
210
- border-bottom-color: #ffffff !important;
211
- border-left-color: #000000 !important;
212
- }
213
- .gr-button:hover {
214
- filter: brightness(130%);
215
- }
216
- </style>""")
217
- run = gr.Button("Generate Image")
218
  with gr.Row():
219
  with gr.Column():
220
- output1 = gr.Image(label=(f"{current_model}"))
221
-
 
222
  with gr.Row():
223
  with gr.Column(scale=50):
224
- input_text = gr.Textbox(label="Use this box to extend an idea automagically, by typing some words and clicking Extend Idea", lines=2)
225
- see_prompts = gr.Button("Extend Idea -> overwrite the contents of the `Your PromptΒ΄ box above")
226
- use_short = gr.Button("Copy the contents of this box to the `Your PromptΒ΄ box above")
227
  def short_prompt(inputs):
228
- return(inputs)
229
 
230
  model_name1.change(set_model, inputs=model_name1, outputs=[output1])
231
- run.click(send_it1, inputs=[magic1, model_name1, neg_input, height, width, steps, cfg, seed], outputs=[output1])
 
 
 
 
 
 
 
232
  use_short.click(short_prompt, inputs=[input_text], outputs=magic1)
233
  see_prompts.click(text_it1, inputs=[input_text], outputs=magic1)
 
234
 
235
- myface.queue(concurrency_count=200)
236
- myface.launch(inline=True, show_api=False, max_threads=400)
 
 
1
  import gradio as gr
2
+ import os
 
 
3
  from all_models import models
4
+ from externalmod import gr_Interface_load, save_image, randomize_seed
5
  from prompt_extend import extend_prompt
 
6
  import asyncio
7
  from threading import RLock
8
  lock = RLock()
 
10
 
11
  inference_timeout = 300
12
  MAX_SEED = 2**32-1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  current_model = models[0]
 
 
 
14
  text_gen1 = extend_prompt
 
 
15
 
16
+ models2 = [gr_Interface_load(f"models/{m}", live=False, preprocess=True, postprocess=False, hf_token=HF_TOKEN) for m in models]
 
 
 
 
 
 
17
 
18
  def text_it1(inputs, text_gen1=text_gen1):
19
  go_t1 = text_gen1(inputs)
20
+ return(go_t1)
21
 
22
  def set_model(current_model):
23
  current_model = models[current_model]
 
29
 
30
  # https://huggingface.co/docs/api-inference/detailed_parameters
31
  # https://huggingface.co/docs/huggingface_hub/package_reference/inference_client
32
+ async def infer(model_index, prompt, nprompt="", height=0, width=0, steps=0, cfg=0, seed=-1, timeout=inference_timeout):
 
33
  kwargs = {}
34
+ if height > 0: kwargs["height"] = height
35
+ if width > 0: kwargs["width"] = width
36
+ if steps > 0: kwargs["num_inference_steps"] = steps
37
+ if cfg > 0: cfg = kwargs["guidance_scale"] = cfg
38
+ if seed == -1: kwargs["seed"] = randomize_seed()
39
+ else: kwargs["seed"] = seed
 
 
 
 
40
  task = asyncio.create_task(asyncio.to_thread(models2[model_index].fn,
41
+ prompt=prompt, negative_prompt=nprompt, **kwargs, token=HF_TOKEN))
42
  await asyncio.sleep(0)
43
  try:
44
  result = await asyncio.wait_for(task, timeout=timeout)
45
+ except asyncio.TimeoutError as e:
46
+ print(e)
47
+ print(f"Task timed out: {models[model_index]}")
48
+ if not task.done(): task.cancel()
49
+ result = None
50
+ raise Exception(f"Task timed out: {models[model_index]}") from e
51
+ except Exception as e:
52
  print(e)
 
53
  if not task.done(): task.cancel()
54
  result = None
55
+ raise Exception() from e
56
+ if task.done() and result is not None and not isinstance(result, tuple):
57
  with lock:
58
  png_path = "image.png"
59
+ image = save_image(result, png_path, models[model_index], prompt, nprompt, height, width, steps, cfg, seed)
 
60
  return image
61
  return None
62
 
63
+ def gen_fn(model_index, prompt, nprompt="", height=0, width=0, steps=0, cfg=0, seed=-1):
64
  try:
65
  loop = asyncio.new_event_loop()
66
  result = loop.run_until_complete(infer(model_index, prompt, nprompt,
67
  height, width, steps, cfg, seed, inference_timeout))
68
  except (Exception, asyncio.CancelledError) as e:
69
  print(e)
70
+ print(f"Task aborted: {models[model_index]}")
71
  result = None
72
+ raise gr.Error(f"Task aborted: {models[model_index]}, Error: {e}")
73
  finally:
74
  loop.close()
75
  return result
76
 
77
+ css="""
78
+ .gradio-container {background-image: linear-gradient(#254150, #1e2f40, #182634) !important;
79
+ color: #ffaa66 !important; font-family: 'IBM Plex Sans', sans-serif !important;}
80
+ h1 {font-size: 6em; color: #ffc99f; margin-top: 30px; margin-bottom: 30px;
81
+ text-shadow: 3px 3px 0 rgba(0, 0, 0, 1) !important;}
82
+ h3 {color: #ffc99f; !important;}
83
+ h4 {display: inline-block; color: #ffffff !important;}
84
+ .wrapper img {font-size: 98% !important; white-space: nowrap !important; text-align: center !important;
85
+ display: inline-block !important; color: #ffffff !important;}
86
+ .wrapper {color: #ffffff !important;}
87
+ .gr-box {background-image: linear-gradient(#182634, #1e2f40, #254150) !important;
88
+ border-top-color: #000000 !important; border-right-color: #ffffff !important;
89
+ border-bottom-color: #ffffff !important; border-left-color: #000000 !important;}
90
+ """
91
 
92
+ with gr.Blocks(theme='John6666/YntecDark', fill_width=True, css=css) as myface:
93
  gr.HTML(f"""
94
+ <div style="text-align: center; max-width: 1200px; margin: 0 auto;">
95
+ <div class="center"><h1>Blitz Diffusion</h1></div>
96
+ <p style="margin-bottom: 1px; color: #ffaa66;">
97
+ <h3>{int(len(models))} Stable Diffusion models, but why? For your enjoyment!</h3></p>
98
+ <br><div class="wrapper">9.3 <img src="https://huggingface.co/Yntec/DucHaitenLofi/resolve/main/NEW.webp" alt="NEW!" style="width:32px;height:16px;">This has become a legacy backup copy of old <u><a href="https://huggingface.co/spaces/Yntec/ToyWorld">ToyWorld</a></u>'s UI! Newer models added dailty over there! 25 new models since last update!</div>
99
+ <p style="margin-bottom: 1px; font-size: 98%">
100
+ <br><h4>If a model is already loaded each new image takes less than <b>10</b> seconds to generate!</h4></p>
101
+ <p style="margin-bottom: 1px; color: #ffffff;">
102
+ <br><div class="wrapper">Generate 6 images from 1 prompt at the <u><a href="https://huggingface.co/spaces/Yntec/PrintingPress">PrintingPress</a></u>, and use 6 different models at <u><a href="https://huggingface.co/spaces/Yntec/diffusion80xx">Huggingface Diffusion!</a></u>!
103
+ </p></p></div>
104
+ """, elem_classes="gr-box")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  with gr.Row():
106
  with gr.Column(scale=100):
107
+ # Model selection dropdown
108
+ model_name1 = gr.Dropdown(label="Select Model", choices=[m for m in models], type="index",
109
+ value=current_model, interactive=True, elem_classes=["gr-box", "gr-input"])
110
  with gr.Row():
111
  with gr.Column(scale=100):
112
+ with gr.Group():
113
+ magic1 = gr.Textbox(label="Your Prompt", lines=4, elem_classes=["gr-box", "gr-input"]) #Positive
114
  with gr.Accordion("Advanced", open=False, visible=True):
115
+ neg_input = gr.Textbox(label='Negative prompt', lines=1, elem_classes=["gr-box", "gr-input"])
116
  with gr.Row():
117
+ width = gr.Slider(label="Width", info="If 0, the default value is used.", maximum=1216, step=32, value=0, elem_classes=["gr-box", "gr-input"])
118
+ height = gr.Slider(label="Height", info="If 0, the default value is used.", maximum=1216, step=32, value=0, elem_classes=["gr-box", "gr-input"])
119
  with gr.Row():
120
+ steps = gr.Slider(label="Number of inference steps", info="If 0, the default value is used.", maximum=100, step=1, value=0, elem_classes=["gr-box", "gr-input"])
121
+ cfg = gr.Slider(label="Guidance scale", info="If 0, the default value is used.", maximum=30.0, step=0.1, value=-1, elem_classes=["gr-box", "gr-input"])
122
+ seed = gr.Slider(label="Seed", info="Randomize Seed if -1.", minimum=-1, maximum=MAX_SEED, step=1, value=-1, elem_classes=["gr-box", "gr-input"])
123
+ seed_rand = gr.Button("Randomize Seed 🎲", size="sm", variant="secondary")
124
+ run = gr.Button("Generate Image", variant="primary", elem_classes="gr-button")
125
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  with gr.Row():
127
  with gr.Column():
128
+ output1 = gr.Image(label=(f"{current_model}"), show_download_button=True,
129
+ interactive=False, show_share_button=False, format=".png", elem_classes="gr-box")
130
+
131
  with gr.Row():
132
  with gr.Column(scale=50):
133
+ input_text=gr.Textbox(label="Use this box to extend an idea automagically, by typing some words and clicking Extend Idea", lines=2, elem_classes=["gr-box", "gr-input"])
134
+ see_prompts=gr.Button("Extend Idea -> overwrite the contents of the `Your PromptΒ΄ box above", variant="primary", elem_classes="gr-button")
135
+ use_short=gr.Button("Copy the contents of this box to the `Your PromptΒ΄ box above", variant="primary", elem_classes="gr-button")
136
  def short_prompt(inputs):
137
+ return (inputs)
138
 
139
  model_name1.change(set_model, inputs=model_name1, outputs=[output1])
140
+ gr.on(
141
+ triggers=[run.click, magic1.submit],
142
+ fn=send_it1,
143
+ inputs=[magic1, model_name1, neg_input, height, width, steps, cfg, seed],
144
+ outputs=[output1],
145
+ concurrency_limit=None,
146
+ queue=False,
147
+ )
148
  use_short.click(short_prompt, inputs=[input_text], outputs=magic1)
149
  see_prompts.click(text_it1, inputs=[input_text], outputs=magic1)
150
+ seed_rand.click(randomize_seed, None, [seed], queue=False)
151
 
152
+ #myface.queue(default_concurrency_limit=200, max_size=200)
153
+ myface.launch(show_api=False, max_threads=400)
154
+ # https://github.com/gradio-app/gradio/issues/6339
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
requirements.txt CHANGED
@@ -1,4 +1,3 @@
1
- transformers
2
  numpy<2
3
- torch==2.2.0
4
- fastapi==0.112.2
 
1
+ transformers==4.44.0
2
  numpy<2
3
+ torch==2.2.0