John6666 commited on
Commit
08c6266
·
verified ·
1 Parent(s): c164ddd

Upload externalmod.py

Browse files
Files changed (1) hide show
  1. externalmod.py +21 -21
externalmod.py CHANGED
@@ -9,7 +9,7 @@ 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
@@ -41,7 +41,7 @@ server_timeout = 600
41
  def load(
42
  name: str,
43
  src: str | None = None,
44
- hf_token: str | None = None,
45
  alias: str | None = None,
46
  **kwargs,
47
  ) -> Blocks:
@@ -52,7 +52,7 @@ def load(
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. 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.
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
@@ -69,7 +69,7 @@ def load(
69
  def load_blocks_from_repo(
70
  name: str,
71
  src: str | None = None,
72
- hf_token: str | None = None,
73
  alias: str | None = None,
74
  **kwargs,
75
  ) -> Blocks:
@@ -93,7 +93,7 @@ def load_blocks_from_repo(
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:
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."""
@@ -104,12 +104,16 @@ def load_blocks_from_repo(
104
  return blocks
105
 
106
 
107
- def from_model(model_name: str, hf_token: str | None, alias: str | None, **kwargs):
 
 
108
  model_url = f"https://huggingface.co/{model_name}"
109
  api_url = f"https://api-inference.huggingface.co/models/{model_name}"
110
  print(f"Fetching model from: {model_url}")
111
 
112
- headers = {"Authorization": f"Bearer {hf_token}"} if hf_token is not None else {}
 
 
113
  response = httpx.request("GET", api_url, headers=headers)
114
  if response.status_code != 200:
115
  raise ModelNotFoundError(
@@ -372,7 +376,11 @@ def from_model(model_name: str, hf_token: str | None, alias: str | None, **kwarg
372
  def query_huggingface_inference_endpoints(*data, **kwargs):
373
  if preprocess is not None:
374
  data = preprocess(*data)
375
- data = fn(*data, **kwargs) # type: ignore
 
 
 
 
376
  if postprocess is not None:
377
  data = postprocess(data) # type: ignore
378
  return data
@@ -384,7 +392,7 @@ def from_model(model_name: str, hf_token: str | None, alias: str | None, **kwarg
384
  "inputs": inputs,
385
  "outputs": outputs,
386
  "title": model_name,
387
- # "examples": examples,
388
  }
389
 
390
  kwargs = dict(interface_info, **kwargs)
@@ -395,19 +403,12 @@ def from_model(model_name: str, hf_token: str | None, alias: str | None, **kwarg
395
  def from_spaces(
396
  space_name: str, hf_token: str | None, alias: str | None, **kwargs
397
  ) -> Blocks:
398
- client = Client(
399
- space_name,
400
- hf_token=hf_token,
401
- download_files=False,
402
- _skip_components=False,
403
- )
404
-
405
  space_url = f"https://huggingface.co/spaces/{space_name}"
406
 
407
  print(f"Fetching Space from: {space_url}")
408
 
409
  headers = {}
410
- if hf_token is not None:
411
  headers["Authorization"] = f"Bearer {hf_token}"
412
 
413
  iframe_url = (
@@ -444,8 +445,7 @@ def from_spaces(
444
  "Blocks or Interface locally. You may find this Guide helpful: "
445
  "https://gradio.app/using_blocks_like_functions/"
446
  )
447
- if client.app_version < version.Version("4.0.0b14"):
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:
@@ -490,7 +490,7 @@ def from_spaces_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 is not None:
494
  headers["Authorization"] = f"Bearer {hf_token}"
495
 
496
  # The function should call the API with preprocessed data
@@ -530,7 +530,7 @@ def gr_Interface_load(
530
  src: str | None = None,
531
  hf_token: str | None = None,
532
  alias: str | None = None,
533
- **kwargs,
534
  ) -> Blocks:
535
  try:
536
  return load_blocks_from_repo(name, src, hf_token, alias)
 
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
 
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:
 
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
 
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:
 
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."""
 
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(
 
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
 
392
  "inputs": inputs,
393
  "outputs": outputs,
394
  "title": model_name,
395
+ #"examples": examples,
396
  }
397
 
398
  kwargs = dict(interface_info, **kwargs)
 
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 = (
 
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:
 
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
 
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)