Files changed (2) hide show
  1. app.py +176 -174
  2. externalmod.py +617 -585
app.py CHANGED
@@ -1,175 +1,177 @@
1
- import gradio as gr
2
- from random import randint
3
- from all_models import models
4
-
5
- from externalmod import gr_Interface_load
6
-
7
- import asyncio
8
- import os
9
- from threading import RLock
10
- lock = RLock()
11
- 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.
12
-
13
-
14
- def load_fn(models):
15
- global models_load
16
- models_load = {}
17
-
18
- for model in models:
19
- if model not in models_load.keys():
20
- try:
21
- m = gr_Interface_load(f'models/{model}', hf_token=HF_TOKEN)
22
- except Exception as error:
23
- print(error)
24
- m = gr.Interface(lambda: None, ['text'], ['image'])
25
- models_load.update({model: m})
26
-
27
-
28
- load_fn(models)
29
-
30
-
31
- num_models = 6
32
- MAX_SEED = 3999999999
33
- default_models = models[:num_models]
34
- inference_timeout = 600
35
- starting_seed = randint(1941, 2024)
36
-
37
- def extend_choices(choices):
38
- return choices[:num_models] + (num_models - len(choices[:num_models])) * ['NA']
39
-
40
-
41
- def update_imgbox(choices):
42
- choices_plus = extend_choices(choices[:num_models])
43
- return [gr.Image(None, label=m, visible=(m!='NA')) for m in choices_plus]
44
-
45
- def gen_fn(model_str, prompt):
46
- if model_str == 'NA':
47
- return None
48
- noise = str('') #str(randint(0, 99999999999))
49
- return models_load[model_str](f'{prompt} {noise}')
50
-
51
- async def infer(model_str, prompt, seed=1, timeout=inference_timeout):
52
- from pathlib import Path
53
- kwargs = {}
54
- noise = ""
55
- kwargs["seed"] = seed
56
- task = asyncio.create_task(asyncio.to_thread(models_load[model_str].fn,
57
- prompt=f'{prompt} {noise}', **kwargs, token=HF_TOKEN))
58
- await asyncio.sleep(0)
59
- try:
60
- result = await asyncio.wait_for(task, timeout=timeout)
61
- except (Exception, asyncio.TimeoutError) as e:
62
- print(e)
63
- print(f"Task timed out: {model_str}")
64
- if not task.done(): task.cancel()
65
- result = None
66
- if task.done() and result is not None:
67
- with lock:
68
- png_path = "image.png"
69
- result.save(png_path)
70
- image = str(Path(png_path).resolve())
71
- return image
72
- return None
73
-
74
- def gen_fnseed(model_str, prompt, seed=1):
75
- if model_str == 'NA':
76
- return None
77
- try:
78
- loop = asyncio.new_event_loop()
79
- result = loop.run_until_complete(infer(model_str, prompt, seed, inference_timeout))
80
- except (Exception, asyncio.CancelledError) as e:
81
- print(e)
82
- result = None
83
- with lock:
84
- image = "https://huggingface.co/spaces/Yntec/ToyWorld/resolve/main/error.png"
85
- result = image
86
- finally:
87
- loop.close()
88
- return result
89
-
90
- css="""
91
- .wrapper img {font-size: 98% !important; white-space: nowrap !important; text-align: center !important;
92
- display: inline-block !important;}
93
- """
94
-
95
- with gr.Blocks(css=css) as demo:
96
- with gr.Tab('Mini Toy World'):
97
- txt_input = gr.Textbox(label='Your prompt:', lines=4)
98
- gen_button = gr.Button('Generate up to 6 images in up to 3 minutes total')
99
- #stop_button = gr.Button('Stop', variant = 'secondary', interactive = False)
100
- gen_button.click(lambda s: gr.update(interactive = True), None)
101
- gr.HTML(
102
- """
103
- <div style="text-align: center; max-width: 1200px; margin: 0 auto;">
104
- <div>
105
- <body>
106
- <div class="center"><p style="margin-bottom: 10px; color: #000000;">Scroll down to see more images and select models.</p>
107
- </div>
108
- </body>
109
- </div>
110
- </div>
111
- """
112
- )
113
- with gr.Row():
114
- output = [gr.Image(label = m, min_width=480) for m in default_models]
115
- current_models = [gr.Textbox(m, visible = False) for m in default_models]
116
-
117
- for m, o in zip(current_models, output):
118
- gen_event = gr.on(triggers=[gen_button.click, txt_input.submit], fn=gen_fn,
119
- inputs=[m, txt_input], outputs=[o], concurrency_limit=None, queue=False)
120
- #stop_button.click(lambda s: gr.update(interactive = False), None, stop_button, cancels = [gen_event])
121
- with gr.Accordion('Model selection'):
122
- 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)
123
- #model_choice = gr.CheckboxGroup(models, label = f'Choose up to {num_models} different models from the 2 available! Untick them to only use one!', value = default_models, multiselect = True, max_choices = num_models, interactive = True, filterable = False)
124
- model_choice.change(update_imgbox, model_choice, output)
125
- model_choice.change(extend_choices, model_choice, current_models)
126
- with gr.Row():
127
- gr.HTML(
128
- """
129
- <div class="footer">
130
- <p> Based on the <a href="https://huggingface.co/spaces/John6666/hfd_test_nostopbutton">Huggingface NoStopButton</a> Space by John6666, <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! For 6 images with the same model check out the <a href="https://huggingface.co/spaces/Yntec/PrintingPress">Printing Press</a>, for the classic UI with prompt enhancer try <a href="https://huggingface.co/spaces/Yntec/blitz_diffusion">Blitz Diffusion!</a>
131
- </p>
132
- """
133
- )
134
- with gr.Tab('🌱 Use seeds!'):
135
- txt_inputseed = gr.Textbox(label='Your prompt:', lines=4)
136
- gen_buttonseed = gr.Button('Generate up to 6 images with the same seed in up to 3 minutes total')
137
- seed = gr.Slider(label="Use a seed to replicate the same image later (maximum 3999999999)", minimum=0, maximum=MAX_SEED, step=1, value=starting_seed, scale=3)
138
- #stop_button = gr.Button('Stop', variant = 'secondary', interactive = False)
139
- gen_buttonseed.click(lambda s: gr.update(interactive = True), None)
140
- gr.HTML(
141
- """
142
- <div style="text-align: center; max-width: 1200px; margin: 0 auto;">
143
- <div>
144
- <body>
145
- <div class="center"><p style="margin-bottom: 10px; color: #000000;">Scroll down to see more images and select models.</p>
146
- </div>
147
- </body>
148
- </div>
149
- </div>
150
- """
151
- )
152
- with gr.Row():
153
- output = [gr.Image(label = m, min_width=480) for m in default_models]
154
- current_models = [gr.Textbox(m, visible = False) for m in default_models]
155
-
156
- for m, o in zip(current_models, output):
157
- gen_eventseed = gr.on(triggers=[gen_buttonseed.click, txt_inputseed.submit], fn=gen_fnseed,
158
- inputs=[m, txt_inputseed, seed], outputs=[o], concurrency_limit=None, queue=False)
159
- #stop_button.click(lambda s: gr.update(interactive = False), None, stop_button, cancels = [gen_event])
160
- with gr.Accordion('Model selection'):
161
- 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)
162
- #model_choice = gr.CheckboxGroup(models, label = f'Choose up to {num_models} different models from the 2 available! Untick them to only use one!', value = default_models, multiselect = True, max_choices = num_models, interactive = True, filterable = False)
163
- model_choice.change(update_imgbox, model_choice, output)
164
- model_choice.change(extend_choices, model_choice, current_models)
165
- with gr.Row():
166
- gr.HTML(
167
- """
168
- <div class="footer">
169
- <p> Based on the <a href="https://huggingface.co/spaces/John6666/hfd_test_nostopbutton">Huggingface NoStopButton</a> Space by John6666, <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! For 6 images with the same model check out the <a href="https://huggingface.co/spaces/Yntec/PrintingPress">Printing Press</a>, for the classic UI with prompt enhancer try <a href="https://huggingface.co/spaces/Yntec/blitz_diffusion">Blitz Diffusion!</a>
170
- </p>
171
- """
172
- )
173
-
174
- demo.queue(default_concurrency_limit=200, max_size=200)
 
 
175
  demo.launch(show_api=False, max_threads=400)
 
1
+ import gradio as gr
2
+ from random import randint
3
+ from all_models import models
4
+
5
+ from externalmod import gr_Interface_load
6
+
7
+ import asyncio
8
+ import os
9
+ from threading import RLock
10
+ lock = RLock()
11
+ HF_TOKEN = os.getenv("HF_TOKEN", None)
12
+
13
+
14
+ def load_fn(models):
15
+ global models_load
16
+ models_load = {}
17
+
18
+ for model in models:
19
+ if model not in models_load.keys():
20
+ try:
21
+ kwargs = {}
22
+ if HF_TOKEN: kwargs["hf_token"] = HF_TOKEN
23
+ m = gr_Interface_load(f'models/{model}', **kwargs)
24
+ except Exception as error:
25
+ print(error)
26
+ m = gr.Interface(lambda: None, ['text'], ['image'])
27
+ models_load.update({model: m})
28
+
29
+
30
+ load_fn(models)
31
+
32
+
33
+ num_models = 6
34
+ MAX_SEED = 3999999999
35
+ default_models = models[:num_models]
36
+ inference_timeout = 600
37
+ starting_seed = randint(1941, 2024)
38
+
39
+ def extend_choices(choices):
40
+ return choices[:num_models] + (num_models - len(choices[:num_models])) * ['NA']
41
+
42
+
43
+ def update_imgbox(choices):
44
+ choices_plus = extend_choices(choices[:num_models])
45
+ return [gr.Image(None, label=m, visible=(m!='NA')) for m in choices_plus]
46
+
47
+ def gen_fn(model_str, prompt):
48
+ if model_str == 'NA':
49
+ return None
50
+ noise = str('') #str(randint(0, 99999999999))
51
+ return models_load[model_str](f'{prompt} {noise}')
52
+
53
+ async def infer(model_str, prompt, seed=1, timeout=inference_timeout):
54
+ from pathlib import Path
55
+ kwargs = {}
56
+ noise = ""
57
+ kwargs["seed"] = seed
58
+ task = asyncio.create_task(asyncio.to_thread(models_load[model_str].fn,
59
+ prompt=f'{prompt} {noise}', **kwargs))
60
+ await asyncio.sleep(0)
61
+ try:
62
+ result = await asyncio.wait_for(task, timeout=timeout)
63
+ except (Exception, asyncio.TimeoutError) as e:
64
+ print(e)
65
+ print(f"Task timed out: {model_str}")
66
+ if not task.done(): task.cancel()
67
+ result = None
68
+ if task.done() and result is not None:
69
+ with lock:
70
+ png_path = "image.png"
71
+ result.save(png_path)
72
+ image = str(Path(png_path).resolve())
73
+ return image
74
+ return None
75
+
76
+ def gen_fnseed(model_str, prompt, seed=1):
77
+ if model_str == 'NA':
78
+ return None
79
+ try:
80
+ loop = asyncio.new_event_loop()
81
+ result = loop.run_until_complete(infer(model_str, prompt, seed, inference_timeout))
82
+ except (Exception, asyncio.CancelledError) as e:
83
+ print(e)
84
+ result = None
85
+ with lock:
86
+ image = "https://huggingface.co/spaces/Yntec/ToyWorld/resolve/main/error.png"
87
+ result = image
88
+ finally:
89
+ loop.close()
90
+ return result
91
+
92
+ css="""
93
+ .wrapper img {font-size: 98% !important; white-space: nowrap !important; text-align: center !important;
94
+ display: inline-block !important;}
95
+ """
96
+
97
+ with gr.Blocks(css=css) as demo:
98
+ with gr.Tab('Mini Toy World'):
99
+ txt_input = gr.Textbox(label='Your prompt:', lines=4)
100
+ gen_button = gr.Button('Generate up to 6 images in up to 3 minutes total')
101
+ #stop_button = gr.Button('Stop', variant = 'secondary', interactive = False)
102
+ gen_button.click(lambda s: gr.update(interactive = True), None)
103
+ gr.HTML(
104
+ """
105
+ <div style="text-align: center; max-width: 1200px; margin: 0 auto;">
106
+ <div>
107
+ <body>
108
+ <div class="center"><p style="margin-bottom: 10px; color: #000000;">Scroll down to see more images and select models.</p>
109
+ </div>
110
+ </body>
111
+ </div>
112
+ </div>
113
+ """
114
+ )
115
+ with gr.Row():
116
+ output = [gr.Image(label = m, min_width=480) for m in default_models]
117
+ current_models = [gr.Textbox(m, visible = False) for m in default_models]
118
+
119
+ for m, o in zip(current_models, output):
120
+ gen_event = gr.on(triggers=[gen_button.click, txt_input.submit], fn=gen_fn,
121
+ inputs=[m, txt_input], outputs=[o], concurrency_limit=None, queue=False)
122
+ #stop_button.click(lambda s: gr.update(interactive = False), None, stop_button, cancels = [gen_event])
123
+ with gr.Accordion('Model selection'):
124
+ 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)
125
+ #model_choice = gr.CheckboxGroup(models, label = f'Choose up to {num_models} different models from the 2 available! Untick them to only use one!', value = default_models, multiselect = True, max_choices = num_models, interactive = True, filterable = False)
126
+ model_choice.change(update_imgbox, model_choice, output)
127
+ model_choice.change(extend_choices, model_choice, current_models)
128
+ with gr.Row():
129
+ gr.HTML(
130
+ """
131
+ <div class="footer">
132
+ <p> Based on the <a href="https://huggingface.co/spaces/John6666/hfd_test_nostopbutton">Huggingface NoStopButton</a> Space by John6666, <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! For 6 images with the same model check out the <a href="https://huggingface.co/spaces/Yntec/PrintingPress">Printing Press</a>, for the classic UI with prompt enhancer try <a href="https://huggingface.co/spaces/Yntec/blitz_diffusion">Blitz Diffusion!</a>
133
+ </p>
134
+ """
135
+ )
136
+ with gr.Tab('🌱 Use seeds!'):
137
+ txt_inputseed = gr.Textbox(label='Your prompt:', lines=4)
138
+ gen_buttonseed = gr.Button('Generate up to 6 images with the same seed in up to 3 minutes total')
139
+ seed = gr.Slider(label="Use a seed to replicate the same image later (maximum 3999999999)", minimum=0, maximum=MAX_SEED, step=1, value=starting_seed, scale=3)
140
+ #stop_button = gr.Button('Stop', variant = 'secondary', interactive = False)
141
+ gen_buttonseed.click(lambda s: gr.update(interactive = True), None)
142
+ gr.HTML(
143
+ """
144
+ <div style="text-align: center; max-width: 1200px; margin: 0 auto;">
145
+ <div>
146
+ <body>
147
+ <div class="center"><p style="margin-bottom: 10px; color: #000000;">Scroll down to see more images and select models.</p>
148
+ </div>
149
+ </body>
150
+ </div>
151
+ </div>
152
+ """
153
+ )
154
+ with gr.Row():
155
+ output = [gr.Image(label = m, min_width=480) for m in default_models]
156
+ current_models = [gr.Textbox(m, visible = False) for m in default_models]
157
+
158
+ for m, o in zip(current_models, output):
159
+ gen_eventseed = gr.on(triggers=[gen_buttonseed.click, txt_inputseed.submit], fn=gen_fnseed,
160
+ inputs=[m, txt_inputseed, seed], outputs=[o], concurrency_limit=None, queue=False)
161
+ #stop_button.click(lambda s: gr.update(interactive = False), None, stop_button, cancels = [gen_event])
162
+ with gr.Accordion('Model selection'):
163
+ 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)
164
+ #model_choice = gr.CheckboxGroup(models, label = f'Choose up to {num_models} different models from the 2 available! Untick them to only use one!', value = default_models, multiselect = True, max_choices = num_models, interactive = True, filterable = False)
165
+ model_choice.change(update_imgbox, model_choice, output)
166
+ model_choice.change(extend_choices, model_choice, current_models)
167
+ with gr.Row():
168
+ gr.HTML(
169
+ """
170
+ <div class="footer">
171
+ <p> Based on the <a href="https://huggingface.co/spaces/John6666/hfd_test_nostopbutton">Huggingface NoStopButton</a> Space by John6666, <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! For 6 images with the same model check out the <a href="https://huggingface.co/spaces/Yntec/PrintingPress">Printing Press</a>, for the classic UI with prompt enhancer try <a href="https://huggingface.co/spaces/Yntec/blitz_diffusion">Blitz Diffusion!</a>
172
+ </p>
173
+ """
174
+ )
175
+
176
+ demo.queue(default_concurrency_limit=200, max_size=200)
177
  demo.launch(show_api=False, max_threads=400)
externalmod.py CHANGED
@@ -1,585 +1,617 @@
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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.getenv("HF_TOKEN", None)
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
+ p = "text-to-image"
116
+ #headers = (
117
+ # {} if hf_token in [False, None] else {"Authorization": f"Bearer {hf_token}"}
118
+ #)
119
+ #response = httpx.request("GET", api_url, headers=headers)
120
+ #if response.status_code != 200:
121
+ # raise ModelNotFoundError(
122
+ # 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."
123
+ # )
124
+ #p = response.json().get("pipeline_tag")
125
+
126
+ headers["X-Wait-For-Model"] = "true"
127
+ client_kwargs = {}
128
+ if hf_token: client_kwargs["token"] = hf_token
129
+ client = huggingface_hub.InferenceClient(
130
+ model=model_name, headers=headers, timeout=server_timeout, **client_kwargs,
131
+ )
132
+
133
+ # For tasks that are not yet supported by the InferenceClient
134
+ GRADIO_CACHE = os.environ.get("GRADIO_TEMP_DIR") or str( # noqa: N806
135
+ Path(tempfile.gettempdir()) / "gradio"
136
+ )
137
+
138
+ def custom_post_binary(data):
139
+ data = to_binary({"path": data})
140
+ response = httpx.request("POST", api_url, headers=headers, content=data)
141
+ return save_base64_to_cache(
142
+ external_utils.encode_to_base64(response), cache_dir=GRADIO_CACHE
143
+ )
144
+
145
+ preprocess = None
146
+ postprocess = None
147
+ examples = None
148
+
149
+ # example model: ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition
150
+ if p == "audio-classification":
151
+ inputs = components.Audio(type="filepath", label="Input")
152
+ outputs = components.Label(label="Class")
153
+ postprocess = external_utils.postprocess_label
154
+ examples = [
155
+ "https://gradio-builds.s3.amazonaws.com/demo-files/audio_sample.wav"
156
+ ]
157
+ fn = client.audio_classification
158
+ # example model: facebook/xm_transformer_sm_all-en
159
+ elif p == "audio-to-audio":
160
+ inputs = components.Audio(type="filepath", label="Input")
161
+ outputs = components.Audio(label="Output")
162
+ examples = [
163
+ "https://gradio-builds.s3.amazonaws.com/demo-files/audio_sample.wav"
164
+ ]
165
+ fn = custom_post_binary
166
+ # example model: facebook/wav2vec2-base-960h
167
+ elif p == "automatic-speech-recognition":
168
+ inputs = components.Audio(type="filepath", label="Input")
169
+ outputs = components.Textbox(label="Output")
170
+ examples = [
171
+ "https://gradio-builds.s3.amazonaws.com/demo-files/audio_sample.wav"
172
+ ]
173
+ fn = client.automatic_speech_recognition
174
+ # example model: microsoft/DialoGPT-medium
175
+ elif p == "conversational":
176
+ inputs = [
177
+ components.Textbox(render=False),
178
+ components.State(render=False),
179
+ ]
180
+ outputs = [
181
+ components.Chatbot(render=False),
182
+ components.State(render=False),
183
+ ]
184
+ examples = [["Hello World"]]
185
+ preprocess = external_utils.chatbot_preprocess
186
+ postprocess = external_utils.chatbot_postprocess
187
+ fn = client.conversational
188
+ # example model: julien-c/distilbert-feature-extraction
189
+ elif p == "feature-extraction":
190
+ inputs = components.Textbox(label="Input")
191
+ outputs = components.Dataframe(label="Output")
192
+ fn = client.feature_extraction
193
+ postprocess = utils.resolve_singleton
194
+ # example model: distilbert/distilbert-base-uncased
195
+ elif p == "fill-mask":
196
+ inputs = components.Textbox(label="Input")
197
+ outputs = components.Label(label="Classification")
198
+ examples = [
199
+ "Hugging Face is the AI community, working together, to [MASK] the future."
200
+ ]
201
+ postprocess = external_utils.postprocess_mask_tokens
202
+ fn = client.fill_mask
203
+ # Example: google/vit-base-patch16-224
204
+ elif p == "image-classification":
205
+ inputs = components.Image(type="filepath", label="Input Image")
206
+ outputs = components.Label(label="Classification")
207
+ postprocess = external_utils.postprocess_label
208
+ examples = ["https://gradio-builds.s3.amazonaws.com/demo-files/cheetah-002.jpg"]
209
+ fn = client.image_classification
210
+ # Example: deepset/xlm-roberta-base-squad2
211
+ elif p == "question-answering":
212
+ inputs = [
213
+ components.Textbox(label="Question"),
214
+ components.Textbox(lines=7, label="Context"),
215
+ ]
216
+ outputs = [
217
+ components.Textbox(label="Answer"),
218
+ components.Label(label="Score"),
219
+ ]
220
+ examples = [
221
+ [
222
+ "What entity was responsible for the Apollo program?",
223
+ "The Apollo program, also known as Project Apollo, was the third United States human spaceflight"
224
+ " program carried out by the National Aeronautics and Space Administration (NASA), which accomplished"
225
+ " landing the first humans on the Moon from 1969 to 1972.",
226
+ ]
227
+ ]
228
+ postprocess = external_utils.postprocess_question_answering
229
+ fn = client.question_answering
230
+ # Example: facebook/bart-large-cnn
231
+ elif p == "summarization":
232
+ inputs = components.Textbox(label="Input")
233
+ outputs = components.Textbox(label="Summary")
234
+ examples = [
235
+ [
236
+ "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."
237
+ ]
238
+ ]
239
+ fn = client.summarization
240
+ # Example: distilbert-base-uncased-finetuned-sst-2-english
241
+ elif p == "text-classification":
242
+ inputs = components.Textbox(label="Input")
243
+ outputs = components.Label(label="Classification")
244
+ examples = ["I feel great"]
245
+ postprocess = external_utils.postprocess_label
246
+ fn = client.text_classification
247
+ # Example: gpt2
248
+ elif p == "text-generation":
249
+ inputs = components.Textbox(label="Text")
250
+ outputs = inputs
251
+ examples = ["Once upon a time"]
252
+ fn = external_utils.text_generation_wrapper(client)
253
+ # Example: valhalla/t5-small-qa-qg-hl
254
+ elif p == "text2text-generation":
255
+ inputs = components.Textbox(label="Input")
256
+ outputs = components.Textbox(label="Generated Text")
257
+ examples = ["Translate English to Arabic: How are you?"]
258
+ fn = client.text_generation
259
+ # Example: Helsinki-NLP/opus-mt-en-ar
260
+ elif p == "translation":
261
+ inputs = components.Textbox(label="Input")
262
+ outputs = components.Textbox(label="Translation")
263
+ examples = ["Hello, how are you?"]
264
+ fn = client.translation
265
+ # Example: facebook/bart-large-mnli
266
+ elif p == "zero-shot-classification":
267
+ inputs = [
268
+ components.Textbox(label="Input"),
269
+ components.Textbox(label="Possible class names (" "comma-separated)"),
270
+ components.Checkbox(label="Allow multiple true classes"),
271
+ ]
272
+ outputs = components.Label(label="Classification")
273
+ postprocess = external_utils.postprocess_label
274
+ examples = [["I feel great", "happy, sad", False]]
275
+ fn = external_utils.zero_shot_classification_wrapper(client)
276
+ # Example: sentence-transformers/distilbert-base-nli-stsb-mean-tokens
277
+ elif p == "sentence-similarity":
278
+ inputs = [
279
+ components.Textbox(
280
+ label="Source Sentence",
281
+ placeholder="Enter an original sentence",
282
+ ),
283
+ components.Textbox(
284
+ lines=7,
285
+ placeholder="Sentences to compare to -- separate each sentence by a newline",
286
+ label="Sentences to compare to",
287
+ ),
288
+ ]
289
+ outputs = components.JSON(label="Similarity scores")
290
+ examples = [["That is a happy person", "That person is very happy"]]
291
+ fn = external_utils.sentence_similarity_wrapper(client)
292
+ # Example: julien-c/ljspeech_tts_train_tacotron2_raw_phn_tacotron_g2p_en_no_space_train
293
+ elif p == "text-to-speech":
294
+ inputs = components.Textbox(label="Input")
295
+ outputs = components.Audio(label="Audio")
296
+ examples = ["Hello, how are you?"]
297
+ fn = client.text_to_speech
298
+ # example model: osanseviero/BigGAN-deep-128
299
+ elif p == "text-to-image":
300
+ inputs = components.Textbox(label="Input")
301
+ outputs = components.Image(label="Output")
302
+ examples = ["A beautiful sunset"]
303
+ fn = client.text_to_image
304
+ # example model: huggingface-course/bert-finetuned-ner
305
+ elif p == "token-classification":
306
+ inputs = components.Textbox(label="Input")
307
+ outputs = components.HighlightedText(label="Output")
308
+ examples = [
309
+ "Hugging Face is a company based in Paris and New York City that acquired Gradio in 2021."
310
+ ]
311
+ fn = external_utils.token_classification_wrapper(client)
312
+ # example model: impira/layoutlm-document-qa
313
+ elif p == "document-question-answering":
314
+ inputs = [
315
+ components.Image(type="filepath", label="Input Document"),
316
+ components.Textbox(label="Question"),
317
+ ]
318
+ postprocess = external_utils.postprocess_label
319
+ outputs = components.Label(label="Label")
320
+ fn = client.document_question_answering
321
+ # example model: dandelin/vilt-b32-finetuned-vqa
322
+ elif p == "visual-question-answering":
323
+ inputs = [
324
+ components.Image(type="filepath", label="Input Image"),
325
+ components.Textbox(label="Question"),
326
+ ]
327
+ outputs = components.Label(label="Label")
328
+ postprocess = external_utils.postprocess_visual_question_answering
329
+ examples = [
330
+ [
331
+ "https://gradio-builds.s3.amazonaws.com/demo-files/cheetah-002.jpg",
332
+ "What animal is in the image?",
333
+ ]
334
+ ]
335
+ fn = client.visual_question_answering
336
+ # example model: Salesforce/blip-image-captioning-base
337
+ elif p == "image-to-text":
338
+ inputs = components.Image(type="filepath", label="Input Image")
339
+ outputs = components.Textbox(label="Generated Text")
340
+ examples = ["https://gradio-builds.s3.amazonaws.com/demo-files/cheetah-002.jpg"]
341
+ fn = client.image_to_text
342
+ # example model: rajistics/autotrain-Adult-934630783
343
+ elif p in ["tabular-classification", "tabular-regression"]:
344
+ examples = external_utils.get_tabular_examples(model_name)
345
+ col_names, examples = external_utils.cols_to_rows(examples) # type: ignore
346
+ examples = [[examples]] if examples else None
347
+ inputs = components.Dataframe(
348
+ label="Input Rows",
349
+ type="pandas",
350
+ headers=col_names,
351
+ col_count=(len(col_names), "fixed"),
352
+ render=False,
353
+ )
354
+ outputs = components.Dataframe(
355
+ label="Predictions", type="array", headers=["prediction"]
356
+ )
357
+ fn = external_utils.tabular_wrapper
358
+ # example model: microsoft/table-transformer-detection
359
+ elif p == "object-detection":
360
+ inputs = components.Image(type="filepath", label="Input Image")
361
+ outputs = components.AnnotatedImage(label="Annotations")
362
+ fn = external_utils.object_detection_wrapper(client)
363
+ # example model: stabilityai/stable-diffusion-xl-refiner-1.0
364
+ elif p == "image-to-image":
365
+ inputs = [
366
+ components.Image(type="filepath", label="Input Image"),
367
+ components.Textbox(label="Input"),
368
+ ]
369
+ outputs = components.Image(label="Output")
370
+ examples = [
371
+ [
372
+ "https://gradio-builds.s3.amazonaws.com/demo-files/cheetah-002.jpg",
373
+ "Photo of a cheetah with green eyes",
374
+ ]
375
+ ]
376
+ fn = client.image_to_image
377
+ else:
378
+ raise ValueError(f"Unsupported pipeline type: {p}")
379
+
380
+ def query_huggingface_inference_endpoints(*data, **kwargs):
381
+ if preprocess is not None:
382
+ data = preprocess(*data)
383
+ try:
384
+ data = fn(*data, **kwargs) # type: ignore
385
+ except huggingface_hub.utils.HfHubHTTPError as e:
386
+ if "429" in str(e):
387
+ raise TooManyRequestsError() from e
388
+ print(e)
389
+ if postprocess is not None:
390
+ data = postprocess(data) # type: ignore
391
+ return data
392
+
393
+ query_huggingface_inference_endpoints.__name__ = alias or model_name
394
+
395
+ interface_info = {
396
+ "fn": query_huggingface_inference_endpoints,
397
+ "inputs": inputs,
398
+ "outputs": outputs,
399
+ "title": model_name,
400
+ #"examples": examples,
401
+ }
402
+
403
+ kwargs = dict(interface_info, **kwargs)
404
+ interface = gradio.Interface(**kwargs)
405
+ return interface
406
+
407
+
408
+ def from_spaces(
409
+ space_name: str, hf_token: str | None, alias: str | None, **kwargs
410
+ ) -> Blocks:
411
+ space_url = f"https://huggingface.co/spaces/{space_name}"
412
+
413
+ print(f"Fetching Space from: {space_url}")
414
+
415
+ headers = {}
416
+ if hf_token not in [False, None]:
417
+ headers["Authorization"] = f"Bearer {hf_token}"
418
+
419
+ iframe_url = (
420
+ httpx.get(
421
+ f"https://huggingface.co/api/spaces/{space_name}/host", headers=headers
422
+ )
423
+ .json()
424
+ .get("host")
425
+ )
426
+
427
+ if iframe_url is None:
428
+ raise ValueError(
429
+ 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."
430
+ )
431
+
432
+ r = httpx.get(iframe_url, headers=headers)
433
+
434
+ result = re.search(
435
+ r"window.gradio_config = (.*?);[\s]*</script>", r.text
436
+ ) # some basic regex to extract the config
437
+ try:
438
+ config = json.loads(result.group(1)) # type: ignore
439
+ except AttributeError as ae:
440
+ raise ValueError(f"Could not load the Space: {space_name}") from ae
441
+ if "allow_flagging" in config: # Create an Interface for Gradio 2.x Spaces
442
+ return from_spaces_interface(
443
+ space_name, config, alias, hf_token, iframe_url, **kwargs
444
+ )
445
+ else: # Create a Blocks for Gradio 3.x Spaces
446
+ if kwargs:
447
+ warnings.warn(
448
+ "You cannot override parameters for this Space by passing in kwargs. "
449
+ "Instead, please load the Space as a function and use it to create a "
450
+ "Blocks or Interface locally. You may find this Guide helpful: "
451
+ "https://gradio.app/using_blocks_like_functions/"
452
+ )
453
+ return from_spaces_blocks(space=space_name, hf_token=hf_token)
454
+
455
+
456
+ def from_spaces_blocks(space: str, hf_token: str | None) -> Blocks:
457
+ client = Client(
458
+ space,
459
+ hf_token=hf_token,
460
+ download_files=False,
461
+ _skip_components=False,
462
+ )
463
+ # We set deserialize to False to avoid downloading output files from the server.
464
+ # Instead, we serve them as URLs using the /proxy/ endpoint directly from the server.
465
+
466
+ if client.app_version < version.Version("4.0.0b14"):
467
+ raise GradioVersionIncompatibleError(
468
+ f"Gradio version 4.x cannot load spaces with versions less than 4.x ({client.app_version})."
469
+ "Please downgrade to version 3 to load this space."
470
+ )
471
+
472
+ # Use end_to_end_fn here to properly upload/download all files
473
+ predict_fns = []
474
+ for fn_index, endpoint in client.endpoints.items():
475
+ if not isinstance(endpoint, Endpoint):
476
+ raise TypeError(
477
+ f"Expected endpoint to be an Endpoint, but got {type(endpoint)}"
478
+ )
479
+ helper = client.new_helper(fn_index)
480
+ if endpoint.backend_fn:
481
+ predict_fns.append(endpoint.make_end_to_end_fn(helper))
482
+ else:
483
+ predict_fns.append(None)
484
+ return gradio.Blocks.from_config(client.config, predict_fns, client.src) # type: ignore
485
+
486
+
487
+ def from_spaces_interface(
488
+ model_name: str,
489
+ config: dict,
490
+ alias: str | None,
491
+ hf_token: str | None,
492
+ iframe_url: str,
493
+ **kwargs,
494
+ ) -> Interface:
495
+ config = external_utils.streamline_spaces_interface(config)
496
+ api_url = f"{iframe_url}/api/predict/"
497
+ headers = {"Content-Type": "application/json"}
498
+ if hf_token not in [False, None]:
499
+ headers["Authorization"] = f"Bearer {hf_token}"
500
+
501
+ # The function should call the API with preprocessed data
502
+ def fn(*data):
503
+ data = json.dumps({"data": data})
504
+ response = httpx.post(api_url, headers=headers, data=data) # type: ignore
505
+ result = json.loads(response.content.decode("utf-8"))
506
+ if "error" in result and "429" in result["error"]:
507
+ raise TooManyRequestsError("Too many requests to the Hugging Face API")
508
+ try:
509
+ output = result["data"]
510
+ except KeyError as ke:
511
+ raise KeyError(
512
+ f"Could not find 'data' key in response from external Space. Response received: {result}"
513
+ ) from ke
514
+ if (
515
+ len(config["outputs"]) == 1
516
+ ): # if the fn is supposed to return a single value, pop it
517
+ output = output[0]
518
+ if (
519
+ len(config["outputs"]) == 1 and isinstance(output, list)
520
+ ): # Needed to support Output.Image() returning bounding boxes as well (TODO: handle different versions of gradio since they have slightly different APIs)
521
+ output = output[0]
522
+ return output
523
+
524
+ fn.__name__ = alias if (alias is not None) else model_name
525
+ config["fn"] = fn
526
+
527
+ kwargs = dict(config, **kwargs)
528
+ kwargs["_api_mode"] = True
529
+ interface = gradio.Interface(**kwargs)
530
+ return interface
531
+
532
+
533
+ def gr_Interface_load(
534
+ name: str,
535
+ src: str | None = None,
536
+ hf_token: str | None = None,
537
+ alias: str | None = None,
538
+ **kwargs, # ignore
539
+ ) -> Blocks:
540
+ try:
541
+ return load_blocks_from_repo(name, src, hf_token, alias)
542
+ except Exception as e:
543
+ print(e)
544
+ return gradio.Interface(lambda: None, ['text'], ['image'])
545
+
546
+
547
+ def list_uniq(l):
548
+ return sorted(set(l), key=l.index)
549
+
550
+
551
+ def get_status(model_name: str):
552
+ from huggingface_hub import AsyncInferenceClient
553
+ client = AsyncInferenceClient(token=HF_TOKEN, timeout=10)
554
+ return client.get_model_status(model_name)
555
+
556
+
557
+ def is_loadable(model_name: str, force_gpu: bool = False):
558
+ try:
559
+ status = get_status(model_name)
560
+ except Exception as e:
561
+ print(e)
562
+ print(f"Couldn't load {model_name}.")
563
+ return False
564
+ gpu_state = isinstance(status.compute_type, dict) and "gpu" in status.compute_type.keys()
565
+ if status is None or status.state not in ["Loadable", "Loaded"] or (force_gpu and not gpu_state):
566
+ print(f"Couldn't load {model_name}. Model state:'{status.state}', GPU:{gpu_state}")
567
+ return status is not None and status.state in ["Loadable", "Loaded"] and (not force_gpu or gpu_state)
568
+
569
+
570
+ def find_model_list(author: str="", tags: list[str]=[], not_tag="", sort: str="last_modified", limit: int=30, force_gpu=False, check_status=False):
571
+ from huggingface_hub import HfApi
572
+ api = HfApi(token=HF_TOKEN)
573
+ default_tags = ["diffusers"]
574
+ if not sort: sort = "last_modified"
575
+ limit = limit * 20 if check_status and force_gpu else limit * 5
576
+ models = []
577
+ try:
578
+ model_infos = api.list_models(author=author, #task="text-to-image",
579
+ tags=list_uniq(default_tags + tags), cardData=True, sort=sort, limit=limit)
580
+ except Exception as e:
581
+ print(f"Error: Failed to list models.")
582
+ print(e)
583
+ return models
584
+ for model in model_infos:
585
+ if not model.private and not model.gated or HF_TOKEN is not None:
586
+ loadable = is_loadable(model.id, force_gpu) if check_status else True
587
+ if not_tag and not_tag in model.tags or not loadable: continue
588
+ models.append(model.id)
589
+ if len(models) == limit: break
590
+ return models
591
+
592
+
593
+ def save_image(image, savefile, modelname, prompt, nprompt, height=0, width=0, steps=0, cfg=0, seed=-1):
594
+ from PIL import Image, PngImagePlugin
595
+ import json
596
+ try:
597
+ metadata = {"prompt": prompt, "negative_prompt": nprompt, "Model": {"Model": modelname.split("/")[-1]}}
598
+ if steps > 0: metadata["num_inference_steps"] = steps
599
+ if cfg > 0: metadata["guidance_scale"] = cfg
600
+ if seed != -1: metadata["seed"] = seed
601
+ if width > 0 and height > 0: metadata["resolution"] = f"{width} x {height}"
602
+ metadata_str = json.dumps(metadata)
603
+ info = PngImagePlugin.PngInfo()
604
+ info.add_text("metadata", metadata_str)
605
+ image.save(savefile, "PNG", pnginfo=info)
606
+ return str(Path(savefile).resolve())
607
+ except Exception as e:
608
+ print(f"Failed to save image file: {e}")
609
+ raise Exception(f"Failed to save image file:") from e
610
+
611
+
612
+ def randomize_seed():
613
+ from random import seed, randint
614
+ MAX_SEED = 2**32-1
615
+ seed()
616
+ rseed = randint(0, MAX_SEED)
617
+ return rseed