Skip to content

Commit 45ee3e2

Browse files
Wauplinosanseviero
andauthored
Add user agent to all requests with huggingface_hub version (and other) (#1075)
* Add user agent in http header * fix tests * docstring * docstring * ensure BC * bc * Apply suggestions from code review Co-authored-by: Omar Sanseviero <[email protected]> Co-authored-by: Omar Sanseviero <[email protected]>
1 parent dac13ac commit 45ee3e2

File tree

13 files changed

+386
-197
lines changed

13 files changed

+386
-197
lines changed

src/huggingface_hub/fastai_utils.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,16 @@
99

1010
from huggingface_hub import snapshot_download
1111
from huggingface_hub.constants import CONFIG_NAME
12-
from huggingface_hub.file_download import (
13-
_PY_VERSION,
12+
from huggingface_hub.hf_api import HfApi
13+
from huggingface_hub.utils import (
1414
get_fastai_version,
1515
get_fastcore_version,
16+
get_python_version,
1617
)
17-
from huggingface_hub.hf_api import HfApi
1818

1919
from .utils import logging, validate_hf_hub_args
2020
from .utils._deprecation import _deprecate_arguments, _deprecate_positional_args
21+
from .utils._runtime import _PY_VERSION # noqa: F401 # for backward compatibility...
2122

2223

2324
logger = logging.get_logger(__name__)
@@ -214,7 +215,7 @@ def _check_fastai_fastcore_pyproject_versions(
214215
"""
215216

216217
PYPROJECT_TEMPLATE = f"""[build-system]
217-
requires = ["setuptools>=40.8.0", "wheel", "python={_PY_VERSION}", "fastai={get_fastai_version()}", "fastcore={get_fastcore_version()}"]
218+
requires = ["setuptools>=40.8.0", "wheel", "python={get_python_version()}", "fastai={get_fastai_version()}", "fastcore={get_fastcore_version()}"]
218219
build-backend = "setuptools.build_meta:__legacy__"
219220
"""
220221

src/huggingface_hub/file_download.py

Lines changed: 27 additions & 163 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
import os
66
import re
77
import shutil
8-
import sys
98
import tempfile
109
import warnings
1110
from contextlib import contextmanager
@@ -16,14 +15,12 @@
1615
from typing import BinaryIO, Dict, Optional, Tuple, Union
1716
from urllib.parse import quote, urlparse
1817

19-
import packaging.version
20-
2118
import requests
2219
from filelock import FileLock
2320
from huggingface_hub import constants
2421
from requests.exceptions import ConnectTimeout, ProxyError
2522

26-
from . import __version__
23+
from . import __version__ # noqa: F401 # for backward compatibility
2724
from .constants import (
2825
DEFAULT_REVISION,
2926
HUGGINGFACE_CO_URL_TEMPLATE,
@@ -34,6 +31,20 @@
3431
REPO_TYPES,
3532
REPO_TYPES_URL_PREFIXES,
3633
)
34+
from .utils import get_fastai_version # noqa: F401 # for backward compatibility
35+
from .utils import get_fastcore_version # noqa: F401 # for backward compatibility
36+
from .utils import get_graphviz_version # noqa: F401 # for backward compatibility
37+
from .utils import get_jinja_version # noqa: F401 # for backward compatibility
38+
from .utils import get_pydot_version # noqa: F401 # for backward compatibility
39+
from .utils import get_tf_version # noqa: F401 # for backward compatibility
40+
from .utils import get_torch_version # noqa: F401 # for backward compatibility
41+
from .utils import is_fastai_available # noqa: F401 # for backward compatibility
42+
from .utils import is_fastcore_available # noqa: F401 # for backward compatibility
43+
from .utils import is_graphviz_available # noqa: F401 # for backward compatibility
44+
from .utils import is_jinja_available # noqa: F401 # for backward compatibility
45+
from .utils import is_pydot_available # noqa: F401 # for backward compatibility
46+
from .utils import is_tf_available # noqa: F401 # for backward compatibility
47+
from .utils import is_torch_available # noqa: F401 # for backward compatibility
3748
from .utils import (
3849
EntryNotFoundError,
3950
LocalEntryNotFoundError,
@@ -44,133 +55,12 @@
4455
tqdm,
4556
validate_hf_hub_args,
4657
)
58+
from .utils._headers import _http_user_agent
59+
from .utils._runtime import _PY_VERSION # noqa: F401 # for backward compatibility
4760

4861

4962
logger = logging.get_logger(__name__)
5063

51-
_PY_VERSION: str = sys.version.split()[0].rstrip("+")
52-
53-
if packaging.version.Version(_PY_VERSION) < packaging.version.Version("3.8.0"):
54-
import importlib_metadata
55-
else:
56-
import importlib.metadata as importlib_metadata
57-
58-
_torch_version = "N/A"
59-
_torch_available = False
60-
try:
61-
_torch_version = importlib_metadata.version("torch")
62-
_torch_available = True
63-
except importlib_metadata.PackageNotFoundError:
64-
pass
65-
66-
_pydot_available = False
67-
68-
try:
69-
_pydot_version = importlib_metadata.version("pydot")
70-
_pydot_available = True
71-
except importlib_metadata.PackageNotFoundError:
72-
pass
73-
74-
75-
def is_pydot_available():
76-
return _pydot_available
77-
78-
79-
_graphviz_available = False
80-
81-
try:
82-
_graphviz_version = importlib_metadata.version("graphviz")
83-
_graphviz_available = True
84-
except importlib_metadata.PackageNotFoundError:
85-
pass
86-
87-
88-
def is_graphviz_available():
89-
return _graphviz_available
90-
91-
92-
_tf_version = "N/A"
93-
_tf_available = False
94-
_tf_candidates = (
95-
"tensorflow",
96-
"tensorflow-cpu",
97-
"tensorflow-gpu",
98-
"tf-nightly",
99-
"tf-nightly-cpu",
100-
"tf-nightly-gpu",
101-
"intel-tensorflow",
102-
"intel-tensorflow-avx512",
103-
"tensorflow-rocm",
104-
"tensorflow-macos",
105-
)
106-
for package_name in _tf_candidates:
107-
try:
108-
_tf_version = importlib_metadata.version(package_name)
109-
_tf_available = True
110-
break
111-
except importlib_metadata.PackageNotFoundError:
112-
pass
113-
114-
_fastai_version = "N/A"
115-
_fastai_available = False
116-
try:
117-
_fastai_version: str = importlib_metadata.version("fastai")
118-
_fastai_available = True
119-
except importlib_metadata.PackageNotFoundError:
120-
pass
121-
122-
_fastcore_version = "N/A"
123-
_fastcore_available = False
124-
try:
125-
_fastcore_version: str = importlib_metadata.version("fastcore")
126-
_fastcore_available = True
127-
except importlib_metadata.PackageNotFoundError:
128-
pass
129-
130-
_jinja_version = "N/A"
131-
_jinja_available = False
132-
try:
133-
_jinja_version: str = importlib_metadata.version("Jinja2")
134-
_jinja_available = True
135-
except importlib_metadata.PackageNotFoundError:
136-
pass
137-
138-
139-
def is_torch_available():
140-
return _torch_available
141-
142-
143-
def is_tf_available():
144-
return _tf_available
145-
146-
147-
def get_tf_version():
148-
return _tf_version
149-
150-
151-
def is_fastai_available():
152-
return _fastai_available
153-
154-
155-
def get_fastai_version():
156-
return _fastai_version
157-
158-
159-
def is_fastcore_available():
160-
return _fastcore_available
161-
162-
163-
def get_fastcore_version():
164-
return _fastcore_version
165-
166-
167-
def is_jinja_available():
168-
return _jinja_available
169-
170-
171-
def get_jinja_version():
172-
return _jinja_version
173-
17464

17565
_are_symlinks_supported_in_dir: Dict[str, bool] = {}
17666

@@ -432,38 +322,12 @@ def http_user_agent(
432322
library_version: Optional[str] = None,
433323
user_agent: Union[Dict, str, None] = None,
434324
) -> str:
435-
"""Formats a user-agent string with basic info about a request.
436-
437-
Args:
438-
library_name (`str`, *optional*):
439-
The name of the library to which the object corresponds.
440-
library_version (`str`, *optional*):
441-
The version of the library.
442-
user_agent (`str`, `dict`, *optional*):
443-
The user agent info in the form of a dictionary or a single string.
444-
445-
Returns:
446-
The formatted user-agent string.
447-
"""
448-
if library_name is not None:
449-
ua = f"{library_name}/{library_version}"
450-
else:
451-
ua = "unknown/None"
452-
ua += f"; hf_hub/{__version__}"
453-
ua += f"; python/{_PY_VERSION}"
454-
if is_torch_available():
455-
ua += f"; torch/{_torch_version}"
456-
if is_tf_available():
457-
ua += f"; tensorflow/{_tf_version}"
458-
if is_fastai_available():
459-
ua += f"; fastai/{_fastai_version}"
460-
if is_fastcore_available():
461-
ua += f"; fastcore/{_fastcore_version}"
462-
if isinstance(user_agent, dict):
463-
ua += "; " + "; ".join(f"{k}/{v}" for k, v in user_agent.items())
464-
elif isinstance(user_agent, str):
465-
ua += "; " + user_agent
466-
return ua
325+
"""Deprecated in favor of [`build_hf_headers`]."""
326+
return _http_user_agent(
327+
library_name=library_name,
328+
library_version=library_version,
329+
user_agent=user_agent,
330+
)
467331

468332

469333
class OfflineModeIsEnabled(ConnectionError):
@@ -733,8 +597,8 @@ def cached_download(
733597

734598
os.makedirs(cache_dir, exist_ok=True)
735599

736-
headers = build_hf_headers(use_auth_token=use_auth_token)
737-
headers["user-agent"] = http_user_agent(
600+
headers = build_hf_headers(
601+
use_auth_token=use_auth_token,
738602
library_name=library_name,
739603
library_version=library_version,
740604
user_agent=user_agent,
@@ -1172,8 +1036,8 @@ def hf_hub_download(
11721036

11731037
url = hf_hub_url(repo_id, filename, repo_type=repo_type, revision=revision)
11741038

1175-
headers = build_hf_headers(use_auth_token=use_auth_token)
1176-
headers["user-agent"] = http_user_agent(
1039+
headers = build_hf_headers(
1040+
use_auth_token=use_auth_token,
11771041
library_name=library_name,
11781042
library_version=library_version,
11791043
user_agent=user_agent,

src/huggingface_hub/keras_mixin.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,13 @@
99
from urllib.parse import quote
1010

1111
from huggingface_hub import CommitOperationDelete, ModelHubMixin, snapshot_download
12-
from huggingface_hub.file_download import (
12+
from huggingface_hub.utils import (
1313
get_tf_version,
1414
is_graphviz_available,
1515
is_pydot_available,
1616
is_tf_available,
17+
yaml_dump,
1718
)
18-
from huggingface_hub.utils import yaml_dump
1919

2020
from .constants import CONFIG_NAME, DEFAULT_REVISION
2121
from .hf_api import HfApi, _parse_revision_from_pr_url, _prepare_upload_folder_commit

src/huggingface_hub/repocard.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313

1414
import requests
1515
import yaml
16-
from huggingface_hub.file_download import hf_hub_download, is_jinja_available
16+
from huggingface_hub.file_download import hf_hub_download
1717
from huggingface_hub.hf_api import upload_file
1818
from huggingface_hub.repocard_data import (
1919
CardData,
@@ -23,7 +23,7 @@
2323
eval_results_to_model_index,
2424
model_index_to_eval_results,
2525
)
26-
from huggingface_hub.utils import yaml_dump
26+
from huggingface_hub.utils import is_jinja_available, yaml_dump
2727

2828
from .constants import REPOCARD_NAME
2929
from .utils import EntryNotFoundError, validate_hf_hub_args

src/huggingface_hub/utils/__init__.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,24 @@
4040
from ._hf_folder import HfFolder
4141
from ._http import http_backoff
4242
from ._paths import filter_repo_objects
43+
from ._runtime import (
44+
get_fastai_version,
45+
get_fastcore_version,
46+
get_graphviz_version,
47+
get_hf_hub_version,
48+
get_jinja_version,
49+
get_pydot_version,
50+
get_python_version,
51+
get_tf_version,
52+
get_torch_version,
53+
is_fastai_available,
54+
is_fastcore_available,
55+
is_graphviz_available,
56+
is_jinja_available,
57+
is_pydot_available,
58+
is_tf_available,
59+
is_torch_available,
60+
)
4361
from ._subprocess import run_subprocess
4462
from ._validators import HFValidationError, validate_hf_hub_args, validate_repo_id
4563
from .tqdm import (

0 commit comments

Comments
 (0)