Yntec commited on
Commit
6e252e1
1 Parent(s): c3f3a3e

Create externalmod.py

Browse files
Files changed (1) hide show
  1. externalmod.py +531 -0
externalmod.py ADDED
@@ -0,0 +1,531 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """This module should not be used directly as its API is subject to change. Instead,
2
+ use the `gr.Blocks.load()` or `gr.load()` functions."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import os
8
+ import re
9
+ import tempfile
10
+ import warnings
11
+ from pathlib import Path
12
+ from typing import TYPE_CHECKING, Callable
13
+
14
+ import httpx
15
+ import huggingface_hub
16
+ from gradio_client import Client
17
+ from gradio_client.client import Endpoint
18
+ from gradio_client.documentation import document
19
+ from packaging import version
20
+
21
+ import gradio
22
+ from gradio import components, external_utils, utils
23
+ from gradio.context import Context
24
+ from gradio.exceptions import (
25
+ GradioVersionIncompatibleError,
26
+ ModelNotFoundError,
27
+ TooManyRequestsError,
28
+ )
29
+ from gradio.processing_utils import save_base64_to_cache, to_binary
30
+
31
+ if TYPE_CHECKING:
32
+ from gradio.blocks import Blocks
33
+ from gradio.interface import Interface
34
+
35
+
36
+ @document()
37
+ def load(
38
+ name: str,
39
+ src: str | None = None,
40
+ hf_token: str | None = None,
41
+ alias: str | None = None,
42
+ **kwargs,
43
+ ) -> Blocks:
44
+ """
45
+ 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
46
+ 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.
47
+ custom `css`, `js`, and `head` attributes) will not be loaded.
48
+ Parameters:
49
+ 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")
50
+ src: the source of the model: `models` or `spaces` (or leave empty if source is provided as a prefix in `name`)
51
+ hf_token: optional access token for loading private Hugging Face Hub models or spaces. Find your token here: https://huggingface.co/settings/tokens. Warning: only provide this if you are loading a trusted private Space as it can be read by the Space you are loading.
52
+ 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)
53
+ Returns:
54
+ a Gradio Blocks object for the given model
55
+ Example:
56
+ import gradio as gr
57
+ demo = gr.load("gradio/question-answering", src="spaces")
58
+ demo.launch()
59
+ """
60
+ return load_blocks_from_repo(
61
+ name=name, src=src, hf_token=hf_token, alias=alias, **kwargs
62
+ )
63
+
64
+
65
+ def load_blocks_from_repo(
66
+ name: str,
67
+ src: str | None = None,
68
+ hf_token: str | None = None,
69
+ alias: str | None = None,
70
+ **kwargs,
71
+ ) -> Blocks:
72
+ """Creates and returns a Blocks instance from a Hugging Face model or Space repo."""
73
+ if src is None:
74
+ # Separate the repo type (e.g. "model") from repo name (e.g. "google/vit-base-patch16-224")
75
+ tokens = name.split("/")
76
+ if len(tokens) <= 1:
77
+ raise ValueError(
78
+ "Either `src` parameter must be provided, or `name` must be formatted as {src}/{repo name}"
79
+ )
80
+ src = tokens[0]
81
+ name = "/".join(tokens[1:])
82
+
83
+ factory_methods: dict[str, Callable] = {
84
+ # for each repo type, we have a method that returns the Interface given the model name & optionally an hf_token
85
+ "huggingface": from_model,
86
+ "models": from_model,
87
+ "spaces": from_spaces,
88
+ }
89
+ if src.lower() not in factory_methods:
90
+ raise ValueError(f"parameter: src must be one of {factory_methods.keys()}")
91
+
92
+ if hf_token is not None:
93
+ if Context.hf_token is not None and Context.hf_token != hf_token:
94
+ warnings.warn(
95
+ """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."""
96
+ )
97
+ Context.hf_token = hf_token
98
+
99
+ blocks: gradio.Blocks = factory_methods[src](name, hf_token, alias, **kwargs)
100
+ return blocks
101
+
102
+
103
+ def from_model(model_name: str, hf_token: str | None, alias: str | None, **kwargs):
104
+ model_url = f"https://huggingface.co/{model_name}"
105
+ api_url = f"https://api-inference.huggingface.co/models/{model_name}"
106
+ print(f"Fetching model from: {model_url}")
107
+
108
+ headers = {"Authorization": f"Bearer {hf_token}"} if hf_token is not None else {}
109
+ response = httpx.request("GET", api_url, headers=headers)
110
+ if response.status_code != 200:
111
+ raise ModelNotFoundError(
112
+ 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."
113
+ )
114
+ p = response.json().get("pipeline_tag")
115
+
116
+ headers["X-Wait-For-Model"] = "true"
117
+ client = huggingface_hub.InferenceClient(
118
+ model=model_name, headers=headers, token=hf_token
119
+ )
120
+
121
+ # For tasks that are not yet supported by the InferenceClient
122
+ GRADIO_CACHE = os.environ.get("GRADIO_TEMP_DIR") or str( # noqa: N806
123
+ Path(tempfile.gettempdir()) / "gradio"
124
+ )
125
+
126
+ def custom_post_binary(data):
127
+ data = to_binary({"path": data})
128
+ response = httpx.request("POST", api_url, headers=headers, content=data)
129
+ return save_base64_to_cache(
130
+ external_utils.encode_to_base64(response), cache_dir=GRADIO_CACHE
131
+ )
132
+
133
+ preprocess = None
134
+ postprocess = None
135
+ examples = None
136
+
137
+ # example model: ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition
138
+ if p == "audio-classification":
139
+ inputs = components.Audio(type="filepath", label="Input")
140
+ outputs = components.Label(label="Class")
141
+ postprocess = external_utils.postprocess_label
142
+ examples = [
143
+ "https://gradio-builds.s3.amazonaws.com/demo-files/audio_sample.wav"
144
+ ]
145
+ fn = client.audio_classification
146
+ # example model: facebook/xm_transformer_sm_all-en
147
+ elif p == "audio-to-audio":
148
+ inputs = components.Audio(type="filepath", label="Input")
149
+ outputs = components.Audio(label="Output")
150
+ examples = [
151
+ "https://gradio-builds.s3.amazonaws.com/demo-files/audio_sample.wav"
152
+ ]
153
+ fn = custom_post_binary
154
+ # example model: facebook/wav2vec2-base-960h
155
+ elif p == "automatic-speech-recognition":
156
+ inputs = components.Audio(type="filepath", label="Input")
157
+ outputs = components.Textbox(label="Output")
158
+ examples = [
159
+ "https://gradio-builds.s3.amazonaws.com/demo-files/audio_sample.wav"
160
+ ]
161
+ fn = client.automatic_speech_recognition
162
+ # example model: microsoft/DialoGPT-medium
163
+ elif p == "conversational":
164
+ inputs = [
165
+ components.Textbox(render=False),
166
+ components.State(render=False),
167
+ ]
168
+ outputs = [
169
+ components.Chatbot(render=False),
170
+ components.State(render=False),
171
+ ]
172
+ examples = [["Hello World"]]
173
+ preprocess = external_utils.chatbot_preprocess
174
+ postprocess = external_utils.chatbot_postprocess
175
+ fn = client.conversational
176
+ # example model: julien-c/distilbert-feature-extraction
177
+ elif p == "feature-extraction":
178
+ inputs = components.Textbox(label="Input")
179
+ outputs = components.Dataframe(label="Output")
180
+ fn = client.feature_extraction
181
+ postprocess = utils.resolve_singleton
182
+ # example model: distilbert/distilbert-base-uncased
183
+ elif p == "fill-mask":
184
+ inputs = components.Textbox(label="Input")
185
+ outputs = components.Label(label="Classification")
186
+ examples = [
187
+ "Hugging Face is the AI community, working together, to [MASK] the future."
188
+ ]
189
+ postprocess = external_utils.postprocess_mask_tokens
190
+ fn = client.fill_mask
191
+ # Example: google/vit-base-patch16-224
192
+ elif p == "image-classification":
193
+ inputs = components.Image(type="filepath", label="Input Image")
194
+ outputs = components.Label(label="Classification")
195
+ postprocess = external_utils.postprocess_label
196
+ examples = ["https://gradio-builds.s3.amazonaws.com/demo-files/cheetah-002.jpg"]
197
+ fn = client.image_classification
198
+ # Example: deepset/xlm-roberta-base-squad2
199
+ elif p == "question-answering":
200
+ inputs = [
201
+ components.Textbox(label="Question"),
202
+ components.Textbox(lines=7, label="Context"),
203
+ ]
204
+ outputs = [
205
+ components.Textbox(label="Answer"),
206
+ components.Label(label="Score"),
207
+ ]
208
+ examples = [
209
+ [
210
+ "What entity was responsible for the Apollo program?",
211
+ "The Apollo program, also known as Project Apollo, was the third United States human spaceflight"
212
+ " program carried out by the National Aeronautics and Space Administration (NASA), which accomplished"
213
+ " landing the first humans on the Moon from 1969 to 1972.",
214
+ ]
215
+ ]
216
+ postprocess = external_utils.postprocess_question_answering
217
+ fn = client.question_answering
218
+ # Example: facebook/bart-large-cnn
219
+ elif p == "summarization":
220
+ inputs = components.Textbox(label="Input")
221
+ outputs = components.Textbox(label="Summary")
222
+ examples = [
223
+ [
224
+ "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."
225
+ ]
226
+ ]
227
+ fn = client.summarization
228
+ # Example: distilbert-base-uncased-finetuned-sst-2-english
229
+ elif p == "text-classification":
230
+ inputs = components.Textbox(label="Input")
231
+ outputs = components.Label(label="Classification")
232
+ examples = ["I feel great"]
233
+ postprocess = external_utils.postprocess_label
234
+ fn = client.text_classification
235
+ # Example: gpt2
236
+ elif p == "text-generation":
237
+ inputs = components.Textbox(label="Text")
238
+ outputs = inputs
239
+ examples = ["Once upon a time"]
240
+ fn = external_utils.text_generation_wrapper(client)
241
+ # Example: valhalla/t5-small-qa-qg-hl
242
+ elif p == "text2text-generation":
243
+ inputs = components.Textbox(label="Input")
244
+ outputs = components.Textbox(label="Generated Text")
245
+ examples = ["Translate English to Arabic: How are you?"]
246
+ fn = client.text_generation
247
+ # Example: Helsinki-NLP/opus-mt-en-ar
248
+ elif p == "translation":
249
+ inputs = components.Textbox(label="Input")
250
+ outputs = components.Textbox(label="Translation")
251
+ examples = ["Hello, how are you?"]
252
+ fn = client.translation
253
+ # Example: facebook/bart-large-mnli
254
+ elif p == "zero-shot-classification":
255
+ inputs = [
256
+ components.Textbox(label="Input"),
257
+ components.Textbox(label="Possible class names (" "comma-separated)"),
258
+ components.Checkbox(label="Allow multiple true classes"),
259
+ ]
260
+ outputs = components.Label(label="Classification")
261
+ postprocess = external_utils.postprocess_label
262
+ examples = [["I feel great", "happy, sad", False]]
263
+ fn = external_utils.zero_shot_classification_wrapper(client)
264
+ # Example: sentence-transformers/distilbert-base-nli-stsb-mean-tokens
265
+ elif p == "sentence-similarity":
266
+ inputs = [
267
+ components.Textbox(
268
+ label="Source Sentence",
269
+ placeholder="Enter an original sentence",
270
+ ),
271
+ components.Textbox(
272
+ lines=7,
273
+ placeholder="Sentences to compare to -- separate each sentence by a newline",
274
+ label="Sentences to compare to",
275
+ ),
276
+ ]
277
+ outputs = components.JSON(label="Similarity scores")
278
+ examples = [["That is a happy person", "That person is very happy"]]
279
+ fn = external_utils.sentence_similarity_wrapper(client)
280
+ # Example: julien-c/ljspeech_tts_train_tacotron2_raw_phn_tacotron_g2p_en_no_space_train
281
+ elif p == "text-to-speech":
282
+ inputs = components.Textbox(label="Input")
283
+ outputs = components.Audio(label="Audio")
284
+ examples = ["Hello, how are you?"]
285
+ fn = client.text_to_speech
286
+ # example model: osanseviero/BigGAN-deep-128
287
+ elif p == "text-to-image":
288
+ inputs = components.Textbox(label="Input")
289
+ outputs = components.Image(label="Output")
290
+ examples = ["A beautiful sunset"]
291
+ fn = client.text_to_image
292
+ # example model: huggingface-course/bert-finetuned-ner
293
+ elif p == "token-classification":
294
+ inputs = components.Textbox(label="Input")
295
+ outputs = components.HighlightedText(label="Output")
296
+ examples = [
297
+ "Hugging Face is a company based in Paris and New York City that acquired Gradio in 2021."
298
+ ]
299
+ fn = external_utils.token_classification_wrapper(client)
300
+ # example model: impira/layoutlm-document-qa
301
+ elif p == "document-question-answering":
302
+ inputs = [
303
+ components.Image(type="filepath", label="Input Document"),
304
+ components.Textbox(label="Question"),
305
+ ]
306
+ postprocess = external_utils.postprocess_label
307
+ outputs = components.Label(label="Label")
308
+ fn = client.document_question_answering
309
+ # example model: dandelin/vilt-b32-finetuned-vqa
310
+ elif p == "visual-question-answering":
311
+ inputs = [
312
+ components.Image(type="filepath", label="Input Image"),
313
+ components.Textbox(label="Question"),
314
+ ]
315
+ outputs = components.Label(label="Label")
316
+ postprocess = external_utils.postprocess_visual_question_answering
317
+ examples = [
318
+ [
319
+ "https://gradio-builds.s3.amazonaws.com/demo-files/cheetah-002.jpg",
320
+ "What animal is in the image?",
321
+ ]
322
+ ]
323
+ fn = client.visual_question_answering
324
+ # example model: Salesforce/blip-image-captioning-base
325
+ elif p == "image-to-text":
326
+ inputs = components.Image(type="filepath", label="Input Image")
327
+ outputs = components.Textbox(label="Generated Text")
328
+ examples = ["https://gradio-builds.s3.amazonaws.com/demo-files/cheetah-002.jpg"]
329
+ fn = client.image_to_text
330
+ # example model: rajistics/autotrain-Adult-934630783
331
+ elif p in ["tabular-classification", "tabular-regression"]:
332
+ examples = external_utils.get_tabular_examples(model_name)
333
+ col_names, examples = external_utils.cols_to_rows(examples) # type: ignore
334
+ examples = [[examples]] if examples else None
335
+ inputs = components.Dataframe(
336
+ label="Input Rows",
337
+ type="pandas",
338
+ headers=col_names,
339
+ col_count=(len(col_names), "fixed"),
340
+ render=False,
341
+ )
342
+ outputs = components.Dataframe(
343
+ label="Predictions", type="array", headers=["prediction"]
344
+ )
345
+ fn = external_utils.tabular_wrapper
346
+ # example model: microsoft/table-transformer-detection
347
+ elif p == "object-detection":
348
+ inputs = components.Image(type="filepath", label="Input Image")
349
+ outputs = components.AnnotatedImage(label="Annotations")
350
+ fn = external_utils.object_detection_wrapper(client)
351
+ # example model: stabilityai/stable-diffusion-xl-refiner-1.0
352
+ elif p == "image-to-image":
353
+ inputs = [
354
+ components.Image(type="filepath", label="Input Image"),
355
+ components.Textbox(label="Input"),
356
+ ]
357
+ outputs = components.Image(label="Output")
358
+ examples = [
359
+ [
360
+ "https://gradio-builds.s3.amazonaws.com/demo-files/cheetah-002.jpg",
361
+ "Photo of a cheetah with green eyes",
362
+ ]
363
+ ]
364
+ fn = client.image_to_image
365
+ else:
366
+ raise ValueError(f"Unsupported pipeline type: {p}")
367
+
368
+ def query_huggingface_inference_endpoints(*data):
369
+ if preprocess is not None:
370
+ data = preprocess(*data)
371
+ data = fn(*data) # type: ignore
372
+ if postprocess is not None:
373
+ data = postprocess(data) # type: ignore
374
+ return data
375
+
376
+ query_huggingface_inference_endpoints.__name__ = alias or model_name
377
+
378
+ interface_info = {
379
+ "fn": query_huggingface_inference_endpoints,
380
+ "inputs": inputs,
381
+ "outputs": outputs,
382
+ "title": model_name,
383
+ # "examples": examples,
384
+ }
385
+
386
+ kwargs = dict(interface_info, **kwargs)
387
+ interface = gradio.Interface(**kwargs)
388
+ return interface
389
+
390
+
391
+ def from_spaces(
392
+ space_name: str, hf_token: str | None, alias: str | None, **kwargs
393
+ ) -> Blocks:
394
+ client = Client(
395
+ space_name,
396
+ hf_token=hf_token,
397
+ download_files=False,
398
+ _skip_components=False,
399
+ )
400
+
401
+ space_url = f"https://huggingface.co/spaces/{space_name}"
402
+
403
+ print(f"Fetching Space from: {space_url}")
404
+
405
+ headers = {}
406
+ if hf_token is not None:
407
+ headers["Authorization"] = f"Bearer {hf_token}"
408
+
409
+ iframe_url = (
410
+ httpx.get(
411
+ f"https://huggingface.co/api/spaces/{space_name}/host", headers=headers
412
+ )
413
+ .json()
414
+ .get("host")
415
+ )
416
+
417
+ if iframe_url is None:
418
+ raise ValueError(
419
+ 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."
420
+ )
421
+
422
+ r = httpx.get(iframe_url, headers=headers)
423
+
424
+ result = re.search(
425
+ r"window.gradio_config = (.*?);[\s]*</script>", r.text
426
+ ) # some basic regex to extract the config
427
+ try:
428
+ config = json.loads(result.group(1)) # type: ignore
429
+ except AttributeError as ae:
430
+ raise ValueError(f"Could not load the Space: {space_name}") from ae
431
+ if "allow_flagging" in config: # Create an Interface for Gradio 2.x Spaces
432
+ return from_spaces_interface(
433
+ space_name, config, alias, hf_token, iframe_url, **kwargs
434
+ )
435
+ else: # Create a Blocks for Gradio 3.x Spaces
436
+ if kwargs:
437
+ warnings.warn(
438
+ "You cannot override parameters for this Space by passing in kwargs. "
439
+ "Instead, please load the Space as a function and use it to create a "
440
+ "Blocks or Interface locally. You may find this Guide helpful: "
441
+ "https://gradio.app/using_blocks_like_functions/"
442
+ )
443
+ if client.app_version < version.Version("4.0.0b14"):
444
+ return from_spaces_blocks(space=space_name, hf_token=hf_token)
445
+
446
+
447
+ def from_spaces_blocks(space: str, hf_token: str | None) -> Blocks:
448
+ client = Client(
449
+ space,
450
+ hf_token=hf_token,
451
+ download_files=False,
452
+ _skip_components=False,
453
+ )
454
+ # We set deserialize to False to avoid downloading output files from the server.
455
+ # Instead, we serve them as URLs using the /proxy/ endpoint directly from the server.
456
+
457
+ if client.app_version < version.Version("4.0.0b14"):
458
+ raise GradioVersionIncompatibleError(
459
+ f"Gradio version 4.x cannot load spaces with versions less than 4.x ({client.app_version})."
460
+ "Please downgrade to version 3 to load this space."
461
+ )
462
+
463
+ # Use end_to_end_fn here to properly upload/download all files
464
+ predict_fns = []
465
+ for fn_index, endpoint in client.endpoints.items():
466
+ if not isinstance(endpoint, Endpoint):
467
+ raise TypeError(
468
+ f"Expected endpoint to be an Endpoint, but got {type(endpoint)}"
469
+ )
470
+ helper = client.new_helper(fn_index)
471
+ if endpoint.backend_fn:
472
+ predict_fns.append(endpoint.make_end_to_end_fn(helper))
473
+ else:
474
+ predict_fns.append(None)
475
+ return gradio.Blocks.from_config(client.config, predict_fns, client.src) # type: ignore
476
+
477
+
478
+ def from_spaces_interface(
479
+ model_name: str,
480
+ config: dict,
481
+ alias: str | None,
482
+ hf_token: str | None,
483
+ iframe_url: str,
484
+ **kwargs,
485
+ ) -> Interface:
486
+ config = external_utils.streamline_spaces_interface(config)
487
+ api_url = f"{iframe_url}/api/predict/"
488
+ headers = {"Content-Type": "application/json"}
489
+ if hf_token is not None:
490
+ headers["Authorization"] = f"Bearer {hf_token}"
491
+
492
+ # The function should call the API with preprocessed data
493
+ def fn(*data):
494
+ data = json.dumps({"data": data})
495
+ response = httpx.post(api_url, headers=headers, data=data) # type: ignore
496
+ result = json.loads(response.content.decode("utf-8"))
497
+ if "error" in result and "429" in result["error"]:
498
+ raise TooManyRequestsError("Too many requests to the Hugging Face API")
499
+ try:
500
+ output = result["data"]
501
+ except KeyError as ke:
502
+ raise KeyError(
503
+ f"Could not find 'data' key in response from external Space. Response received: {result}"
504
+ ) from ke
505
+ if (
506
+ len(config["outputs"]) == 1
507
+ ): # if the fn is supposed to return a single value, pop it
508
+ output = output[0]
509
+ if (
510
+ len(config["outputs"]) == 1 and isinstance(output, list)
511
+ ): # Needed to support Output.Image() returning bounding boxes as well (TODO: handle different versions of gradio since they have slightly different APIs)
512
+ output = output[0]
513
+ return output
514
+
515
+ fn.__name__ = alias if (alias is not None) else model_name
516
+ config["fn"] = fn
517
+
518
+ kwargs = dict(config, **kwargs)
519
+ kwargs["_api_mode"] = True
520
+ interface = gradio.Interface(**kwargs)
521
+ return interface
522
+
523
+
524
+ def gr_Interface_load(
525
+ name: str,
526
+ src: str | None = None,
527
+ hf_token: str | None = None,
528
+ alias: str | None = None,
529
+ **kwargs,
530
+ ) -> Blocks:
531
+ return load_blocks_from_repo(name, src, hf_token, alias)