ZTWHHH commited on
Commit
8f62728
Β·
verified Β·
1 Parent(s): 3803939

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes. Β  See raw diff
Files changed (50) hide show
  1. evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/__pycache__/_commit_api.cpython-310.pyc +0 -0
  2. evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/__pycache__/_inference_endpoints.cpython-310.pyc +0 -0
  3. evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/__pycache__/_snapshot_download.cpython-310.pyc +0 -0
  4. evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/__pycache__/_upload_large_folder.cpython-310.pyc +0 -0
  5. evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/__pycache__/_webhooks_payload.cpython-310.pyc +0 -0
  6. evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/__pycache__/hub_mixin.cpython-310.pyc +0 -0
  7. evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/__pycache__/inference_api.cpython-310.pyc +0 -0
  8. evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/__pycache__/lfs.cpython-310.pyc +0 -0
  9. evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/__pycache__/repocard.cpython-310.pyc +0 -0
  10. evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/__pycache__/repository.cpython-310.pyc +0 -0
  11. evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/commands/__pycache__/_cli_utils.cpython-310.pyc +0 -0
  12. evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/commands/__pycache__/user.cpython-310.pyc +0 -0
  13. evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/chat_completion.cpython-310.pyc +0 -0
  14. evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/document_question_answering.cpython-310.pyc +0 -0
  15. evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/text2text_generation.cpython-310.pyc +0 -0
  16. evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/utils/__init__.py +110 -0
  17. evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/utils/_datetime.py +62 -0
  18. evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/utils/_experimental.py +66 -0
  19. evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/utils/_headers.py +239 -0
  20. evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/utils/_hf_folder.py +96 -0
  21. evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/utils/_pagination.py +52 -0
  22. evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/utils/_telemetry.py +126 -0
  23. evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/utils/_typing.py +75 -0
  24. evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/utils/_validators.py +226 -0
  25. evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/utils/endpoint_helpers.py +66 -0
  26. evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/utils/insecure_hashlib.py +34 -0
  27. evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/utils/logging.py +182 -0
  28. evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/utils/tqdm.py +264 -0
  29. evalkit_tf449/share/terminfo/q/qansi-t +0 -0
  30. evalkit_tf449/share/terminfo/q/qnx +0 -0
  31. evalkit_tf449/share/terminfo/q/qume +0 -0
  32. evalkit_tf449/share/terminfo/q/qvt119+-w +0 -0
  33. evalkit_tf449/share/terminfo/q/qvt119-25-w +0 -0
  34. evalkit_tf449/share/terminfo/q/qvt119-w +0 -0
  35. evalkit_tf449/share/terminfo/q/qvt203+ +0 -0
  36. evalkit_tf449/share/terminfo/q/qvt203-25-w +0 -0
  37. evalkit_tf449/share/terminfo/x/x1720 +0 -0
  38. evalkit_tf449/share/terminfo/x/xerox +0 -0
  39. evalkit_tf449/share/terminfo/x/xerox820 +0 -0
  40. evalkit_tf449/share/terminfo/x/xiterm +0 -0
  41. evalkit_tf449/share/terminfo/x/xl83 +0 -0
  42. evalkit_tf449/share/terminfo/x/xnuppc+144x48 +0 -0
  43. evalkit_tf449/share/terminfo/x/xnuppc+200x75 +0 -0
  44. evalkit_tf449/share/terminfo/x/xnuppc+b +0 -0
  45. evalkit_tf449/share/terminfo/x/xnuppc+f +0 -0
  46. evalkit_tf449/share/terminfo/x/xnuppc-100x37-m +0 -0
  47. evalkit_tf449/share/terminfo/x/xnuppc-160x64-m +0 -0
  48. evalkit_tf449/share/terminfo/x/xnuppc-200x64 +0 -0
  49. evalkit_tf449/share/terminfo/x/xnuppc-256x96-m +0 -0
  50. evalkit_tf449/share/terminfo/x/xnuppc-80x30 +0 -0
evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/__pycache__/_commit_api.cpython-310.pyc ADDED
Binary file (24.2 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/__pycache__/_inference_endpoints.cpython-310.pyc ADDED
Binary file (15.5 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/__pycache__/_snapshot_download.cpython-310.pyc ADDED
Binary file (10.4 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/__pycache__/_upload_large_folder.cpython-310.pyc ADDED
Binary file (16.2 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/__pycache__/_webhooks_payload.cpython-310.pyc ADDED
Binary file (3.93 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/__pycache__/hub_mixin.cpython-310.pyc ADDED
Binary file (28.7 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/__pycache__/inference_api.cpython-310.pyc ADDED
Binary file (7.58 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/__pycache__/lfs.cpython-310.pyc ADDED
Binary file (13.8 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/__pycache__/repocard.cpython-310.pyc ADDED
Binary file (29.6 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/__pycache__/repository.cpython-310.pyc ADDED
Binary file (45.6 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/commands/__pycache__/_cli_utils.cpython-310.pyc ADDED
Binary file (2.36 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/commands/__pycache__/user.cpython-310.pyc ADDED
Binary file (10.1 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/chat_completion.cpython-310.pyc ADDED
Binary file (8.18 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/document_question_answering.cpython-310.pyc ADDED
Binary file (2.07 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/text2text_generation.cpython-310.pyc ADDED
Binary file (1.64 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/utils/__init__.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License
15
+
16
+ # ruff: noqa: F401
17
+
18
+ from huggingface_hub.errors import (
19
+ BadRequestError,
20
+ CacheNotFound,
21
+ CorruptedCacheException,
22
+ DisabledRepoError,
23
+ EntryNotFoundError,
24
+ FileMetadataError,
25
+ GatedRepoError,
26
+ HfHubHTTPError,
27
+ HFValidationError,
28
+ LocalEntryNotFoundError,
29
+ LocalTokenNotFoundError,
30
+ NotASafetensorsRepoError,
31
+ OfflineModeIsEnabled,
32
+ RepositoryNotFoundError,
33
+ RevisionNotFoundError,
34
+ SafetensorsParsingError,
35
+ )
36
+
37
+ from . import tqdm as _tqdm # _tqdm is the module
38
+ from ._auth import get_stored_tokens, get_token
39
+ from ._cache_assets import cached_assets_path
40
+ from ._cache_manager import (
41
+ CachedFileInfo,
42
+ CachedRepoInfo,
43
+ CachedRevisionInfo,
44
+ DeleteCacheStrategy,
45
+ HFCacheInfo,
46
+ scan_cache_dir,
47
+ )
48
+ from ._chunk_utils import chunk_iterable
49
+ from ._datetime import parse_datetime
50
+ from ._experimental import experimental
51
+ from ._fixes import SoftTemporaryDirectory, WeakFileLock, yaml_dump
52
+ from ._git_credential import list_credential_helpers, set_git_credential, unset_git_credential
53
+ from ._headers import build_hf_headers, get_token_to_send
54
+ from ._hf_folder import HfFolder
55
+ from ._http import (
56
+ configure_http_backend,
57
+ fix_hf_endpoint_in_url,
58
+ get_session,
59
+ hf_raise_for_status,
60
+ http_backoff,
61
+ reset_sessions,
62
+ )
63
+ from ._pagination import paginate
64
+ from ._paths import DEFAULT_IGNORE_PATTERNS, FORBIDDEN_FOLDERS, filter_repo_objects
65
+ from ._runtime import (
66
+ dump_environment_info,
67
+ get_aiohttp_version,
68
+ get_fastai_version,
69
+ get_fastapi_version,
70
+ get_fastcore_version,
71
+ get_gradio_version,
72
+ get_graphviz_version,
73
+ get_hf_hub_version,
74
+ get_hf_transfer_version,
75
+ get_jinja_version,
76
+ get_numpy_version,
77
+ get_pillow_version,
78
+ get_pydantic_version,
79
+ get_pydot_version,
80
+ get_python_version,
81
+ get_tensorboard_version,
82
+ get_tf_version,
83
+ get_torch_version,
84
+ is_aiohttp_available,
85
+ is_colab_enterprise,
86
+ is_fastai_available,
87
+ is_fastapi_available,
88
+ is_fastcore_available,
89
+ is_google_colab,
90
+ is_gradio_available,
91
+ is_graphviz_available,
92
+ is_hf_transfer_available,
93
+ is_jinja_available,
94
+ is_notebook,
95
+ is_numpy_available,
96
+ is_package_available,
97
+ is_pillow_available,
98
+ is_pydantic_available,
99
+ is_pydot_available,
100
+ is_safetensors_available,
101
+ is_tensorboard_available,
102
+ is_tf_available,
103
+ is_torch_available,
104
+ )
105
+ from ._safetensors import SafetensorsFileMetadata, SafetensorsRepoMetadata, TensorInfo
106
+ from ._subprocess import capture_output, run_interactive_subprocess, run_subprocess
107
+ from ._telemetry import send_telemetry
108
+ from ._typing import is_jsonable, is_simple_optional_type, unwrap_simple_optional_type
109
+ from ._validators import smoothly_deprecate_use_auth_token, validate_hf_hub_args, validate_repo_id
110
+ from .tqdm import are_progress_bars_disabled, disable_progress_bars, enable_progress_bars, tqdm, tqdm_stream_file
evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/utils/_datetime.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022-present, the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Contains utilities to handle datetimes in Huggingface Hub."""
16
+
17
+ from datetime import datetime, timezone
18
+
19
+
20
+ def parse_datetime(date_string: str) -> datetime:
21
+ """
22
+ Parses a date_string returned from the server to a datetime object.
23
+
24
+ This parser is a weak-parser is the sense that it handles only a single format of
25
+ date_string. It is expected that the server format will never change. The
26
+ implementation depends only on the standard lib to avoid an external dependency
27
+ (python-dateutil). See full discussion about this decision on PR:
28
+ https://github.com/huggingface/huggingface_hub/pull/999.
29
+
30
+ Example:
31
+ ```py
32
+ > parse_datetime('2022-08-19T07:19:38.123Z')
33
+ datetime.datetime(2022, 8, 19, 7, 19, 38, 123000, tzinfo=timezone.utc)
34
+ ```
35
+
36
+ Args:
37
+ date_string (`str`):
38
+ A string representing a datetime returned by the Hub server.
39
+ String is expected to follow '%Y-%m-%dT%H:%M:%S.%fZ' pattern.
40
+
41
+ Returns:
42
+ A python datetime object.
43
+
44
+ Raises:
45
+ :class:`ValueError`:
46
+ If `date_string` cannot be parsed.
47
+ """
48
+ try:
49
+ # Datetime ending with a Z means "UTC". We parse the date and then explicitly
50
+ # set the timezone to UTC.
51
+ # See https://en.wikipedia.org/wiki/ISO_8601#Coordinated_Universal_Time_(UTC)
52
+ # Taken from https://stackoverflow.com/a/3168394.
53
+ if len(date_string) == 30:
54
+ # Means timezoned-timestamp with nanoseconds precision. We need to truncate the last 3 digits.
55
+ date_string = date_string[:-4] + "Z"
56
+ dt = datetime.strptime(date_string, "%Y-%m-%dT%H:%M:%S.%fZ")
57
+ return dt.replace(tzinfo=timezone.utc) # Set explicit timezone
58
+ except ValueError as e:
59
+ raise ValueError(
60
+ f"Cannot parse '{date_string}' as a datetime. Date string is expected to"
61
+ " follow '%Y-%m-%dT%H:%M:%S.%fZ' pattern."
62
+ ) from e
evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/utils/_experimental.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023-present, the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Contains utilities to flag a feature as "experimental" in Huggingface Hub."""
16
+
17
+ import warnings
18
+ from functools import wraps
19
+ from typing import Callable
20
+
21
+ from .. import constants
22
+
23
+
24
+ def experimental(fn: Callable) -> Callable:
25
+ """Decorator to flag a feature as experimental.
26
+
27
+ An experimental feature trigger a warning when used as it might be subject to breaking changes in the future.
28
+ Warnings can be disabled by setting the environment variable `HF_EXPERIMENTAL_WARNING` to `0`.
29
+
30
+ Args:
31
+ fn (`Callable`):
32
+ The function to flag as experimental.
33
+
34
+ Returns:
35
+ `Callable`: The decorated function.
36
+
37
+ Example:
38
+
39
+ ```python
40
+ >>> from huggingface_hub.utils import experimental
41
+
42
+ >>> @experimental
43
+ ... def my_function():
44
+ ... print("Hello world!")
45
+
46
+ >>> my_function()
47
+ UserWarning: 'my_function' is experimental and might be subject to breaking changes in the future. You can disable
48
+ this warning by setting `HF_HUB_DISABLE_EXPERIMENTAL_WARNING=1` as environment variable.
49
+ Hello world!
50
+ ```
51
+ """
52
+ # For classes, put the "experimental" around the "__new__" method => __new__ will be removed in warning message
53
+ name = fn.__qualname__[: -len(".__new__")] if fn.__qualname__.endswith(".__new__") else fn.__qualname__
54
+
55
+ @wraps(fn)
56
+ def _inner_fn(*args, **kwargs):
57
+ if not constants.HF_HUB_DISABLE_EXPERIMENTAL_WARNING:
58
+ warnings.warn(
59
+ f"'{name}' is experimental and might be subject to breaking changes in the future."
60
+ " You can disable this warning by setting `HF_HUB_DISABLE_EXPERIMENTAL_WARNING=1` as environment"
61
+ " variable.",
62
+ UserWarning,
63
+ )
64
+ return fn(*args, **kwargs)
65
+
66
+ return _inner_fn
evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/utils/_headers.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022-present, the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Contains utilities to handle headers to send in calls to Huggingface Hub."""
16
+
17
+ from typing import Dict, Optional, Union
18
+
19
+ from huggingface_hub.errors import LocalTokenNotFoundError
20
+
21
+ from .. import constants
22
+ from ._auth import get_token
23
+ from ._runtime import (
24
+ get_fastai_version,
25
+ get_fastcore_version,
26
+ get_hf_hub_version,
27
+ get_python_version,
28
+ get_tf_version,
29
+ get_torch_version,
30
+ is_fastai_available,
31
+ is_fastcore_available,
32
+ is_tf_available,
33
+ is_torch_available,
34
+ )
35
+ from ._validators import validate_hf_hub_args
36
+
37
+
38
+ @validate_hf_hub_args
39
+ def build_hf_headers(
40
+ *,
41
+ token: Optional[Union[bool, str]] = None,
42
+ is_write_action: bool = False,
43
+ library_name: Optional[str] = None,
44
+ library_version: Optional[str] = None,
45
+ user_agent: Union[Dict, str, None] = None,
46
+ headers: Optional[Dict[str, str]] = None,
47
+ ) -> Dict[str, str]:
48
+ """
49
+ Build headers dictionary to send in a HF Hub call.
50
+
51
+ By default, authorization token is always provided either from argument (explicit
52
+ use) or retrieved from the cache (implicit use). To explicitly avoid sending the
53
+ token to the Hub, set `token=False` or set the `HF_HUB_DISABLE_IMPLICIT_TOKEN`
54
+ environment variable.
55
+
56
+ In case of an API call that requires write access, an error is thrown if token is
57
+ `None` or token is an organization token (starting with `"api_org***"`).
58
+
59
+ In addition to the auth header, a user-agent is added to provide information about
60
+ the installed packages (versions of python, huggingface_hub, torch, tensorflow,
61
+ fastai and fastcore).
62
+
63
+ Args:
64
+ token (`str`, `bool`, *optional*):
65
+ The token to be sent in authorization header for the Hub call:
66
+ - if a string, it is used as the Hugging Face token
67
+ - if `True`, the token is read from the machine (cache or env variable)
68
+ - if `False`, authorization header is not set
69
+ - if `None`, the token is read from the machine only except if
70
+ `HF_HUB_DISABLE_IMPLICIT_TOKEN` env variable is set.
71
+ is_write_action (`bool`, default to `False`):
72
+ Set to True if the API call requires a write access. If `True`, the token
73
+ will be validated (cannot be `None`, cannot start by `"api_org***"`).
74
+ library_name (`str`, *optional*):
75
+ The name of the library that is making the HTTP request. Will be added to
76
+ the user-agent header.
77
+ library_version (`str`, *optional*):
78
+ The version of the library that is making the HTTP request. Will be added
79
+ to the user-agent header.
80
+ user_agent (`str`, `dict`, *optional*):
81
+ The user agent info in the form of a dictionary or a single string. It will
82
+ be completed with information about the installed packages.
83
+ headers (`dict`, *optional*):
84
+ Additional headers to include in the request. Those headers take precedence
85
+ over the ones generated by this function.
86
+
87
+ Returns:
88
+ A `Dict` of headers to pass in your API call.
89
+
90
+ Example:
91
+ ```py
92
+ >>> build_hf_headers(token="hf_***") # explicit token
93
+ {"authorization": "Bearer hf_***", "user-agent": ""}
94
+
95
+ >>> build_hf_headers(token=True) # explicitly use cached token
96
+ {"authorization": "Bearer hf_***",...}
97
+
98
+ >>> build_hf_headers(token=False) # explicitly don't use cached token
99
+ {"user-agent": ...}
100
+
101
+ >>> build_hf_headers() # implicit use of the cached token
102
+ {"authorization": "Bearer hf_***",...}
103
+
104
+ # HF_HUB_DISABLE_IMPLICIT_TOKEN=True # to set as env variable
105
+ >>> build_hf_headers() # token is not sent
106
+ {"user-agent": ...}
107
+
108
+ >>> build_hf_headers(token="api_org_***", is_write_action=True)
109
+ ValueError: You must use your personal account token for write-access methods.
110
+
111
+ >>> build_hf_headers(library_name="transformers", library_version="1.2.3")
112
+ {"authorization": ..., "user-agent": "transformers/1.2.3; hf_hub/0.10.2; python/3.10.4; tensorflow/1.55"}
113
+ ```
114
+
115
+ Raises:
116
+ [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
117
+ If organization token is passed and "write" access is required.
118
+ [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
119
+ If "write" access is required but token is not passed and not saved locally.
120
+ [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
121
+ If `token=True` but token is not saved locally.
122
+ """
123
+ # Get auth token to send
124
+ token_to_send = get_token_to_send(token)
125
+ _validate_token_to_send(token_to_send, is_write_action=is_write_action)
126
+
127
+ # Combine headers
128
+ hf_headers = {
129
+ "user-agent": _http_user_agent(
130
+ library_name=library_name,
131
+ library_version=library_version,
132
+ user_agent=user_agent,
133
+ )
134
+ }
135
+ if token_to_send is not None:
136
+ hf_headers["authorization"] = f"Bearer {token_to_send}"
137
+ if headers is not None:
138
+ hf_headers.update(headers)
139
+ return hf_headers
140
+
141
+
142
+ def get_token_to_send(token: Optional[Union[bool, str]]) -> Optional[str]:
143
+ """Select the token to send from either `token` or the cache."""
144
+ # Case token is explicitly provided
145
+ if isinstance(token, str):
146
+ return token
147
+
148
+ # Case token is explicitly forbidden
149
+ if token is False:
150
+ return None
151
+
152
+ # Token is not provided: we get it from local cache
153
+ cached_token = get_token()
154
+
155
+ # Case token is explicitly required
156
+ if token is True:
157
+ if cached_token is None:
158
+ raise LocalTokenNotFoundError(
159
+ "Token is required (`token=True`), but no token found. You"
160
+ " need to provide a token or be logged in to Hugging Face with"
161
+ " `huggingface-cli login` or `huggingface_hub.login`. See"
162
+ " https://huggingface.co/settings/tokens."
163
+ )
164
+ return cached_token
165
+
166
+ # Case implicit use of the token is forbidden by env variable
167
+ if constants.HF_HUB_DISABLE_IMPLICIT_TOKEN:
168
+ return None
169
+
170
+ # Otherwise: we use the cached token as the user has not explicitly forbidden it
171
+ return cached_token
172
+
173
+
174
+ def _validate_token_to_send(token: Optional[str], is_write_action: bool) -> None:
175
+ if is_write_action:
176
+ if token is None:
177
+ raise ValueError(
178
+ "Token is required (write-access action) but no token found. You need"
179
+ " to provide a token or be logged in to Hugging Face with"
180
+ " `huggingface-cli login` or `huggingface_hub.login`. See"
181
+ " https://huggingface.co/settings/tokens."
182
+ )
183
+ if token.startswith("api_org"):
184
+ raise ValueError(
185
+ "You must use your personal account token for write-access methods. To"
186
+ " generate a write-access token, go to"
187
+ " https://huggingface.co/settings/tokens"
188
+ )
189
+
190
+
191
+ def _http_user_agent(
192
+ *,
193
+ library_name: Optional[str] = None,
194
+ library_version: Optional[str] = None,
195
+ user_agent: Union[Dict, str, None] = None,
196
+ ) -> str:
197
+ """Format a user-agent string containing information about the installed packages.
198
+
199
+ Args:
200
+ library_name (`str`, *optional*):
201
+ The name of the library that is making the HTTP request.
202
+ library_version (`str`, *optional*):
203
+ The version of the library that is making the HTTP request.
204
+ user_agent (`str`, `dict`, *optional*):
205
+ The user agent info in the form of a dictionary or a single string.
206
+
207
+ Returns:
208
+ The formatted user-agent string.
209
+ """
210
+ if library_name is not None:
211
+ ua = f"{library_name}/{library_version}"
212
+ else:
213
+ ua = "unknown/None"
214
+ ua += f"; hf_hub/{get_hf_hub_version()}"
215
+ ua += f"; python/{get_python_version()}"
216
+
217
+ if not constants.HF_HUB_DISABLE_TELEMETRY:
218
+ if is_torch_available():
219
+ ua += f"; torch/{get_torch_version()}"
220
+ if is_tf_available():
221
+ ua += f"; tensorflow/{get_tf_version()}"
222
+ if is_fastai_available():
223
+ ua += f"; fastai/{get_fastai_version()}"
224
+ if is_fastcore_available():
225
+ ua += f"; fastcore/{get_fastcore_version()}"
226
+
227
+ if isinstance(user_agent, dict):
228
+ ua += "; " + "; ".join(f"{k}/{v}" for k, v in user_agent.items())
229
+ elif isinstance(user_agent, str):
230
+ ua += "; " + user_agent
231
+
232
+ return _deduplicate_user_agent(ua)
233
+
234
+
235
+ def _deduplicate_user_agent(user_agent: str) -> str:
236
+ """Deduplicate redundant information in the generated user-agent."""
237
+ # Split around ";" > Strip whitespaces > Store as dict keys (ensure unicity) > format back as string
238
+ # Order is implicitly preserved by dictionary structure (see https://stackoverflow.com/a/53657523).
239
+ return "; ".join({key.strip(): None for key in user_agent.split(";")}.keys())
evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/utils/_hf_folder.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022-present, the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Contain helper class to retrieve/store token from/to local cache."""
16
+
17
+ import warnings
18
+ from pathlib import Path
19
+ from typing import Optional
20
+
21
+ from .. import constants
22
+ from ._auth import get_token
23
+
24
+
25
+ class HfFolder:
26
+ path_token = Path(constants.HF_TOKEN_PATH)
27
+ # Private attribute. Will be removed in v0.15
28
+ _old_path_token = Path(constants._OLD_HF_TOKEN_PATH)
29
+
30
+ # TODO: deprecate when adapted in transformers/datasets/gradio
31
+ # @_deprecate_method(version="1.0", message="Use `huggingface_hub.login` instead.")
32
+ @classmethod
33
+ def save_token(cls, token: str) -> None:
34
+ """
35
+ Save token, creating folder as needed.
36
+
37
+ Token is saved in the huggingface home folder. You can configure it by setting
38
+ the `HF_HOME` environment variable.
39
+
40
+ Args:
41
+ token (`str`):
42
+ The token to save to the [`HfFolder`]
43
+ """
44
+ cls.path_token.parent.mkdir(parents=True, exist_ok=True)
45
+ cls.path_token.write_text(token)
46
+
47
+ # TODO: deprecate when adapted in transformers/datasets/gradio
48
+ # @_deprecate_method(version="1.0", message="Use `huggingface_hub.get_token` instead.")
49
+ @classmethod
50
+ def get_token(cls) -> Optional[str]:
51
+ """
52
+ Get token or None if not existent.
53
+
54
+ This method is deprecated in favor of [`huggingface_hub.get_token`] but is kept for backward compatibility.
55
+ Its behavior is the same as [`huggingface_hub.get_token`].
56
+
57
+ Returns:
58
+ `str` or `None`: The token, `None` if it doesn't exist.
59
+ """
60
+ # 0. Check if token exist in old path but not new location
61
+ try:
62
+ cls._copy_to_new_path_and_warn()
63
+ except Exception: # if not possible (e.g. PermissionError), do not raise
64
+ pass
65
+
66
+ return get_token()
67
+
68
+ # TODO: deprecate when adapted in transformers/datasets/gradio
69
+ # @_deprecate_method(version="1.0", message="Use `huggingface_hub.logout` instead.")
70
+ @classmethod
71
+ def delete_token(cls) -> None:
72
+ """
73
+ Deletes the token from storage. Does not fail if token does not exist.
74
+ """
75
+ try:
76
+ cls.path_token.unlink()
77
+ except FileNotFoundError:
78
+ pass
79
+
80
+ try:
81
+ cls._old_path_token.unlink()
82
+ except FileNotFoundError:
83
+ pass
84
+
85
+ @classmethod
86
+ def _copy_to_new_path_and_warn(cls):
87
+ if cls._old_path_token.exists() and not cls.path_token.exists():
88
+ cls.save_token(cls._old_path_token.read_text())
89
+ warnings.warn(
90
+ f"A token has been found in `{cls._old_path_token}`. This is the old"
91
+ " path where tokens were stored. The new location is"
92
+ f" `{cls.path_token}` which is configurable using `HF_HOME` environment"
93
+ " variable. Your token has been copied to this new location. You can"
94
+ " now safely delete the old token file manually or use"
95
+ " `huggingface-cli logout`."
96
+ )
evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/utils/_pagination.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022-present, the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Contains utilities to handle pagination on Huggingface Hub."""
16
+
17
+ from typing import Dict, Iterable, Optional
18
+
19
+ import requests
20
+
21
+ from . import get_session, hf_raise_for_status, logging
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ def paginate(path: str, params: Dict, headers: Dict) -> Iterable:
28
+ """Fetch a list of models/datasets/spaces and paginate through results.
29
+
30
+ This is using the same "Link" header format as GitHub.
31
+ See:
32
+ - https://requests.readthedocs.io/en/latest/api/#requests.Response.links
33
+ - https://docs.github.com/en/rest/guides/traversing-with-pagination#link-header
34
+ """
35
+ session = get_session()
36
+ r = session.get(path, params=params, headers=headers)
37
+ hf_raise_for_status(r)
38
+ yield from r.json()
39
+
40
+ # Follow pages
41
+ # Next link already contains query params
42
+ next_page = _get_next_page(r)
43
+ while next_page is not None:
44
+ logger.debug(f"Pagination detected. Requesting next page: {next_page}")
45
+ r = session.get(next_page, headers=headers)
46
+ hf_raise_for_status(r)
47
+ yield from r.json()
48
+ next_page = _get_next_page(r)
49
+
50
+
51
+ def _get_next_page(response: requests.Response) -> Optional[str]:
52
+ return response.links.get("next", {}).get("url")
evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/utils/_telemetry.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from queue import Queue
2
+ from threading import Lock, Thread
3
+ from typing import Dict, Optional, Union
4
+ from urllib.parse import quote
5
+
6
+ from .. import constants, logging
7
+ from . import build_hf_headers, get_session, hf_raise_for_status
8
+
9
+
10
+ logger = logging.get_logger(__name__)
11
+
12
+ # Telemetry is sent by a separate thread to avoid blocking the main thread.
13
+ # A daemon thread is started once and consume tasks from the _TELEMETRY_QUEUE.
14
+ # If the thread stops for some reason -shouldn't happen-, we restart a new one.
15
+ _TELEMETRY_THREAD: Optional[Thread] = None
16
+ _TELEMETRY_THREAD_LOCK = Lock() # Lock to avoid starting multiple threads in parallel
17
+ _TELEMETRY_QUEUE: Queue = Queue()
18
+
19
+
20
+ def send_telemetry(
21
+ topic: str,
22
+ *,
23
+ library_name: Optional[str] = None,
24
+ library_version: Optional[str] = None,
25
+ user_agent: Union[Dict, str, None] = None,
26
+ ) -> None:
27
+ """
28
+ Sends telemetry that helps tracking usage of different HF libraries.
29
+
30
+ This usage data helps us debug issues and prioritize new features. However, we understand that not everyone wants
31
+ to share additional information, and we respect your privacy. You can disable telemetry collection by setting the
32
+ `HF_HUB_DISABLE_TELEMETRY=1` as environment variable. Telemetry is also disabled in offline mode (i.e. when setting
33
+ `HF_HUB_OFFLINE=1`).
34
+
35
+ Telemetry collection is run in a separate thread to minimize impact for the user.
36
+
37
+ Args:
38
+ topic (`str`):
39
+ Name of the topic that is monitored. The topic is directly used to build the URL. If you want to monitor
40
+ subtopics, just use "/" separation. Examples: "gradio", "transformers/examples",...
41
+ library_name (`str`, *optional*):
42
+ The name of the library that is making the HTTP request. Will be added to the user-agent header.
43
+ library_version (`str`, *optional*):
44
+ The version of the library that is making the HTTP request. Will be added to the user-agent header.
45
+ user_agent (`str`, `dict`, *optional*):
46
+ The user agent info in the form of a dictionary or a single string. It will be completed with information about the installed packages.
47
+
48
+ Example:
49
+ ```py
50
+ >>> from huggingface_hub.utils import send_telemetry
51
+
52
+ # Send telemetry without library information
53
+ >>> send_telemetry("ping")
54
+
55
+ # Send telemetry to subtopic with library information
56
+ >>> send_telemetry("gradio/local_link", library_name="gradio", library_version="3.22.1")
57
+
58
+ # Send telemetry with additional data
59
+ >>> send_telemetry(
60
+ ... topic="examples",
61
+ ... library_name="transformers",
62
+ ... library_version="4.26.0",
63
+ ... user_agent={"pipeline": "text_classification", "framework": "flax"},
64
+ ... )
65
+ ```
66
+ """
67
+ if constants.HF_HUB_OFFLINE or constants.HF_HUB_DISABLE_TELEMETRY:
68
+ return
69
+
70
+ _start_telemetry_thread() # starts thread only if doesn't exist yet
71
+ _TELEMETRY_QUEUE.put(
72
+ {"topic": topic, "library_name": library_name, "library_version": library_version, "user_agent": user_agent}
73
+ )
74
+
75
+
76
+ def _start_telemetry_thread():
77
+ """Start a daemon thread to consume tasks from the telemetry queue.
78
+
79
+ If the thread is interrupted, start a new one.
80
+ """
81
+ with _TELEMETRY_THREAD_LOCK: # avoid to start multiple threads if called concurrently
82
+ global _TELEMETRY_THREAD
83
+ if _TELEMETRY_THREAD is None or not _TELEMETRY_THREAD.is_alive():
84
+ _TELEMETRY_THREAD = Thread(target=_telemetry_worker, daemon=True)
85
+ _TELEMETRY_THREAD.start()
86
+
87
+
88
+ def _telemetry_worker():
89
+ """Wait for a task and consume it."""
90
+ while True:
91
+ kwargs = _TELEMETRY_QUEUE.get()
92
+ _send_telemetry_in_thread(**kwargs)
93
+ _TELEMETRY_QUEUE.task_done()
94
+
95
+
96
+ def _send_telemetry_in_thread(
97
+ topic: str,
98
+ *,
99
+ library_name: Optional[str] = None,
100
+ library_version: Optional[str] = None,
101
+ user_agent: Union[Dict, str, None] = None,
102
+ ) -> None:
103
+ """Contains the actual data sending data to the Hub.
104
+
105
+ This function is called directly in gradio's analytics because
106
+ it is not possible to send telemetry from a daemon thread.
107
+
108
+ See here: https://github.com/gradio-app/gradio/pull/8180
109
+
110
+ Please do not rename or remove this function.
111
+ """
112
+ path = "/".join(quote(part) for part in topic.split("/") if len(part) > 0)
113
+ try:
114
+ r = get_session().head(
115
+ f"{constants.ENDPOINT}/api/telemetry/{path}",
116
+ headers=build_hf_headers(
117
+ token=False, # no need to send a token for telemetry
118
+ library_name=library_name,
119
+ library_version=library_version,
120
+ user_agent=user_agent,
121
+ ),
122
+ )
123
+ hf_raise_for_status(r)
124
+ except Exception as e:
125
+ # We don't want to error in case of connection errors of any kind.
126
+ logger.debug(f"Error while sending telemetry: {e}")
evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/utils/_typing.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022-present, the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Handle typing imports based on system compatibility."""
16
+
17
+ import sys
18
+ from typing import Any, Callable, List, Literal, Type, TypeVar, Union, get_args, get_origin
19
+
20
+
21
+ UNION_TYPES: List[Any] = [Union]
22
+ if sys.version_info >= (3, 10):
23
+ from types import UnionType
24
+
25
+ UNION_TYPES += [UnionType]
26
+
27
+
28
+ HTTP_METHOD_T = Literal["GET", "OPTIONS", "HEAD", "POST", "PUT", "PATCH", "DELETE"]
29
+
30
+ # type hint meaning "function signature not changed by decorator"
31
+ CallableT = TypeVar("CallableT", bound=Callable)
32
+
33
+ _JSON_SERIALIZABLE_TYPES = (int, float, str, bool, type(None))
34
+
35
+
36
+ def is_jsonable(obj: Any) -> bool:
37
+ """Check if an object is JSON serializable.
38
+
39
+ This is a weak check, as it does not check for the actual JSON serialization, but only for the types of the object.
40
+ It works correctly for basic use cases but do not guarantee an exhaustive check.
41
+
42
+ Object is considered to be recursively json serializable if:
43
+ - it is an instance of int, float, str, bool, or NoneType
44
+ - it is a list or tuple and all its items are json serializable
45
+ - it is a dict and all its keys are strings and all its values are json serializable
46
+ """
47
+ try:
48
+ if isinstance(obj, _JSON_SERIALIZABLE_TYPES):
49
+ return True
50
+ if isinstance(obj, (list, tuple)):
51
+ return all(is_jsonable(item) for item in obj)
52
+ if isinstance(obj, dict):
53
+ return all(isinstance(key, str) and is_jsonable(value) for key, value in obj.items())
54
+ if hasattr(obj, "__json__"):
55
+ return True
56
+ return False
57
+ except RecursionError:
58
+ return False
59
+
60
+
61
+ def is_simple_optional_type(type_: Type) -> bool:
62
+ """Check if a type is optional, i.e. Optional[Type] or Union[Type, None] or Type | None, where Type is a non-composite type."""
63
+ if get_origin(type_) in UNION_TYPES:
64
+ union_args = get_args(type_)
65
+ if len(union_args) == 2 and type(None) in union_args:
66
+ return True
67
+ return False
68
+
69
+
70
+ def unwrap_simple_optional_type(optional_type: Type) -> Type:
71
+ """Unwraps a simple optional type, i.e. returns Type from Optional[Type]."""
72
+ for arg in get_args(optional_type):
73
+ if arg is not type(None):
74
+ return arg
75
+ raise ValueError(f"'{optional_type}' is not an optional type")
evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/utils/_validators.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022-present, the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Contains utilities to validate argument values in `huggingface_hub`."""
16
+
17
+ import inspect
18
+ import re
19
+ import warnings
20
+ from functools import wraps
21
+ from itertools import chain
22
+ from typing import Any, Dict
23
+
24
+ from huggingface_hub.errors import HFValidationError
25
+
26
+ from ._typing import CallableT
27
+
28
+
29
+ REPO_ID_REGEX = re.compile(
30
+ r"""
31
+ ^
32
+ (\b[\w\-.]+\b/)? # optional namespace (username or organization)
33
+ \b # starts with a word boundary
34
+ [\w\-.]{1,96} # repo_name: alphanumeric + . _ -
35
+ \b # ends with a word boundary
36
+ $
37
+ """,
38
+ flags=re.VERBOSE,
39
+ )
40
+
41
+
42
+ def validate_hf_hub_args(fn: CallableT) -> CallableT:
43
+ """Validate values received as argument for any public method of `huggingface_hub`.
44
+
45
+ The goal of this decorator is to harmonize validation of arguments reused
46
+ everywhere. By default, all defined validators are tested.
47
+
48
+ Validators:
49
+ - [`~utils.validate_repo_id`]: `repo_id` must be `"repo_name"`
50
+ or `"namespace/repo_name"`. Namespace is a username or an organization.
51
+ - [`~utils.smoothly_deprecate_use_auth_token`]: Use `token` instead of
52
+ `use_auth_token` (only if `use_auth_token` is not expected by the decorated
53
+ function - in practice, always the case in `huggingface_hub`).
54
+
55
+ Example:
56
+ ```py
57
+ >>> from huggingface_hub.utils import validate_hf_hub_args
58
+
59
+ >>> @validate_hf_hub_args
60
+ ... def my_cool_method(repo_id: str):
61
+ ... print(repo_id)
62
+
63
+ >>> my_cool_method(repo_id="valid_repo_id")
64
+ valid_repo_id
65
+
66
+ >>> my_cool_method("other..repo..id")
67
+ huggingface_hub.utils._validators.HFValidationError: Cannot have -- or .. in repo_id: 'other..repo..id'.
68
+
69
+ >>> my_cool_method(repo_id="other..repo..id")
70
+ huggingface_hub.utils._validators.HFValidationError: Cannot have -- or .. in repo_id: 'other..repo..id'.
71
+
72
+ >>> @validate_hf_hub_args
73
+ ... def my_cool_auth_method(token: str):
74
+ ... print(token)
75
+
76
+ >>> my_cool_auth_method(token="a token")
77
+ "a token"
78
+
79
+ >>> my_cool_auth_method(use_auth_token="a use_auth_token")
80
+ "a use_auth_token"
81
+
82
+ >>> my_cool_auth_method(token="a token", use_auth_token="a use_auth_token")
83
+ UserWarning: Both `token` and `use_auth_token` are passed (...)
84
+ "a token"
85
+ ```
86
+
87
+ Raises:
88
+ [`~utils.HFValidationError`]:
89
+ If an input is not valid.
90
+ """
91
+ # TODO: add an argument to opt-out validation for specific argument?
92
+ signature = inspect.signature(fn)
93
+
94
+ # Should the validator switch `use_auth_token` values to `token`? In practice, always
95
+ # True in `huggingface_hub`. Might not be the case in a downstream library.
96
+ check_use_auth_token = "use_auth_token" not in signature.parameters and "token" in signature.parameters
97
+
98
+ @wraps(fn)
99
+ def _inner_fn(*args, **kwargs):
100
+ has_token = False
101
+ for arg_name, arg_value in chain(
102
+ zip(signature.parameters, args), # Args values
103
+ kwargs.items(), # Kwargs values
104
+ ):
105
+ if arg_name in ["repo_id", "from_id", "to_id"]:
106
+ validate_repo_id(arg_value)
107
+
108
+ elif arg_name == "token" and arg_value is not None:
109
+ has_token = True
110
+
111
+ if check_use_auth_token:
112
+ kwargs = smoothly_deprecate_use_auth_token(fn_name=fn.__name__, has_token=has_token, kwargs=kwargs)
113
+
114
+ return fn(*args, **kwargs)
115
+
116
+ return _inner_fn # type: ignore
117
+
118
+
119
+ def validate_repo_id(repo_id: str) -> None:
120
+ """Validate `repo_id` is valid.
121
+
122
+ This is not meant to replace the proper validation made on the Hub but rather to
123
+ avoid local inconsistencies whenever possible (example: passing `repo_type` in the
124
+ `repo_id` is forbidden).
125
+
126
+ Rules:
127
+ - Between 1 and 96 characters.
128
+ - Either "repo_name" or "namespace/repo_name"
129
+ - [a-zA-Z0-9] or "-", "_", "."
130
+ - "--" and ".." are forbidden
131
+
132
+ Valid: `"foo"`, `"foo/bar"`, `"123"`, `"Foo-BAR_foo.bar123"`
133
+
134
+ Not valid: `"datasets/foo/bar"`, `".repo_id"`, `"foo--bar"`, `"foo.git"`
135
+
136
+ Example:
137
+ ```py
138
+ >>> from huggingface_hub.utils import validate_repo_id
139
+ >>> validate_repo_id(repo_id="valid_repo_id")
140
+ >>> validate_repo_id(repo_id="other..repo..id")
141
+ huggingface_hub.utils._validators.HFValidationError: Cannot have -- or .. in repo_id: 'other..repo..id'.
142
+ ```
143
+
144
+ Discussed in https://github.com/huggingface/huggingface_hub/issues/1008.
145
+ In moon-landing (internal repository):
146
+ - https://github.com/huggingface/moon-landing/blob/main/server/lib/Names.ts#L27
147
+ - https://github.com/huggingface/moon-landing/blob/main/server/views/components/NewRepoForm/NewRepoForm.svelte#L138
148
+ """
149
+ if not isinstance(repo_id, str):
150
+ # Typically, a Path is not a repo_id
151
+ raise HFValidationError(f"Repo id must be a string, not {type(repo_id)}: '{repo_id}'.")
152
+
153
+ if repo_id.count("/") > 1:
154
+ raise HFValidationError(
155
+ "Repo id must be in the form 'repo_name' or 'namespace/repo_name':"
156
+ f" '{repo_id}'. Use `repo_type` argument if needed."
157
+ )
158
+
159
+ if not REPO_ID_REGEX.match(repo_id):
160
+ raise HFValidationError(
161
+ "Repo id must use alphanumeric chars or '-', '_', '.', '--' and '..' are"
162
+ " forbidden, '-' and '.' cannot start or end the name, max length is 96:"
163
+ f" '{repo_id}'."
164
+ )
165
+
166
+ if "--" in repo_id or ".." in repo_id:
167
+ raise HFValidationError(f"Cannot have -- or .. in repo_id: '{repo_id}'.")
168
+
169
+ if repo_id.endswith(".git"):
170
+ raise HFValidationError(f"Repo_id cannot end by '.git': '{repo_id}'.")
171
+
172
+
173
+ def smoothly_deprecate_use_auth_token(fn_name: str, has_token: bool, kwargs: Dict[str, Any]) -> Dict[str, Any]:
174
+ """Smoothly deprecate `use_auth_token` in the `huggingface_hub` codebase.
175
+
176
+ The long-term goal is to remove any mention of `use_auth_token` in the codebase in
177
+ favor of a unique and less verbose `token` argument. This will be done a few steps:
178
+
179
+ 0. Step 0: methods that require a read-access to the Hub use the `use_auth_token`
180
+ argument (`str`, `bool` or `None`). Methods requiring write-access have a `token`
181
+ argument (`str`, `None`). This implicit rule exists to be able to not send the
182
+ token when not necessary (`use_auth_token=False`) even if logged in.
183
+
184
+ 1. Step 1: we want to harmonize everything and use `token` everywhere (supporting
185
+ `token=False` for read-only methods). In order not to break existing code, if
186
+ `use_auth_token` is passed to a function, the `use_auth_token` value is passed
187
+ as `token` instead, without any warning.
188
+ a. Corner case: if both `use_auth_token` and `token` values are passed, a warning
189
+ is thrown and the `use_auth_token` value is ignored.
190
+
191
+ 2. Step 2: Once it is release, we should push downstream libraries to switch from
192
+ `use_auth_token` to `token` as much as possible, but without throwing a warning
193
+ (e.g. manually create issues on the corresponding repos).
194
+
195
+ 3. Step 3: After a transitional period (6 months e.g. until April 2023?), we update
196
+ `huggingface_hub` to throw a warning on `use_auth_token`. Hopefully, very few
197
+ users will be impacted as it would have already been fixed.
198
+ In addition, unit tests in `huggingface_hub` must be adapted to expect warnings
199
+ to be thrown (but still use `use_auth_token` as before).
200
+
201
+ 4. Step 4: After a normal deprecation cycle (3 releases ?), remove this validator.
202
+ `use_auth_token` will definitely not be supported.
203
+ In addition, we update unit tests in `huggingface_hub` to use `token` everywhere.
204
+
205
+ This has been discussed in:
206
+ - https://github.com/huggingface/huggingface_hub/issues/1094.
207
+ - https://github.com/huggingface/huggingface_hub/pull/928
208
+ - (related) https://github.com/huggingface/huggingface_hub/pull/1064
209
+ """
210
+ new_kwargs = kwargs.copy() # do not mutate input !
211
+
212
+ use_auth_token = new_kwargs.pop("use_auth_token", None) # remove from kwargs
213
+ if use_auth_token is not None:
214
+ if has_token:
215
+ warnings.warn(
216
+ "Both `token` and `use_auth_token` are passed to"
217
+ f" `{fn_name}` with non-None values. `token` is now the"
218
+ " preferred argument to pass a User Access Token."
219
+ " `use_auth_token` value will be ignored."
220
+ )
221
+ else:
222
+ # `token` argument is not passed and a non-None value is passed in
223
+ # `use_auth_token` => use `use_auth_token` value as `token` kwarg.
224
+ new_kwargs["token"] = use_auth_token
225
+
226
+ return new_kwargs
evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/utils/endpoint_helpers.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under the Apache License, Version 2.0 (the "License");
2
+ # you may not use this file except in compliance with the License.
3
+ # You may obtain a copy of the License at
4
+ #
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ #
7
+ # Unless required by applicable law or agreed to in writing, software
8
+ # distributed under the License is distributed on an "AS IS" BASIS,
9
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+ # See the License for the specific language governing permissions and
11
+ # limitations under the License.
12
+ """
13
+ Helpful utility functions and classes in relation to exploring API endpoints
14
+ with the aim for a user-friendly interface.
15
+ """
16
+
17
+ import math
18
+ import re
19
+ from typing import TYPE_CHECKING
20
+
21
+ from ..repocard_data import ModelCardData
22
+
23
+
24
+ if TYPE_CHECKING:
25
+ from ..hf_api import ModelInfo
26
+
27
+
28
+ def _is_emission_within_threshold(model_info: "ModelInfo", minimum_threshold: float, maximum_threshold: float) -> bool:
29
+ """Checks if a model's emission is within a given threshold.
30
+
31
+ Args:
32
+ model_info (`ModelInfo`):
33
+ A model info object containing the model's emission information.
34
+ minimum_threshold (`float`):
35
+ A minimum carbon threshold to filter by, such as 1.
36
+ maximum_threshold (`float`):
37
+ A maximum carbon threshold to filter by, such as 10.
38
+
39
+ Returns:
40
+ `bool`: Whether the model's emission is within the given threshold.
41
+ """
42
+ if minimum_threshold is None and maximum_threshold is None:
43
+ raise ValueError("Both `minimum_threshold` and `maximum_threshold` cannot both be `None`")
44
+ if minimum_threshold is None:
45
+ minimum_threshold = -1
46
+ if maximum_threshold is None:
47
+ maximum_threshold = math.inf
48
+
49
+ card_data = getattr(model_info, "card_data", None)
50
+ if card_data is None or not isinstance(card_data, (dict, ModelCardData)):
51
+ return False
52
+
53
+ # Get CO2 emission metadata
54
+ emission = card_data.get("co2_eq_emissions", None)
55
+ if isinstance(emission, dict):
56
+ emission = emission["emissions"]
57
+ if not emission:
58
+ return False
59
+
60
+ # Filter out if value is missing or out of range
61
+ matched = re.search(r"\d+\.\d+|\d+", str(emission))
62
+ if matched is None:
63
+ return False
64
+
65
+ emission_value = float(matched.group(0))
66
+ return minimum_threshold <= emission_value <= maximum_threshold
evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/utils/insecure_hashlib.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Taken from https://github.com/mlflow/mlflow/pull/10119
2
+ #
3
+ # DO NOT use this function for security purposes (e.g., password hashing).
4
+ #
5
+ # In Python >= 3.9, insecure hashing algorithms such as MD5 fail in FIPS-compliant
6
+ # environments unless `usedforsecurity=False` is explicitly passed.
7
+ #
8
+ # References:
9
+ # - https://github.com/mlflow/mlflow/issues/9905
10
+ # - https://github.com/mlflow/mlflow/pull/10119
11
+ # - https://docs.python.org/3/library/hashlib.html
12
+ # - https://github.com/huggingface/transformers/pull/27038
13
+ #
14
+ # Usage:
15
+ # ```python
16
+ # # Use
17
+ # from huggingface_hub.utils.insecure_hashlib import sha256
18
+ # # instead of
19
+ # from hashlib import sha256
20
+ #
21
+ # # Use
22
+ # from huggingface_hub.utils import insecure_hashlib
23
+ # # instead of
24
+ # import hashlib
25
+ # ```
26
+ import functools
27
+ import hashlib
28
+ import sys
29
+
30
+
31
+ _kwargs = {"usedforsecurity": False} if sys.version_info >= (3, 9) else {}
32
+ md5 = functools.partial(hashlib.md5, **_kwargs)
33
+ sha1 = functools.partial(hashlib.sha1, **_kwargs)
34
+ sha256 = functools.partial(hashlib.sha256, **_kwargs)
evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/utils/logging.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 Optuna, Hugging Face
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Logging utilities."""
16
+
17
+ import logging
18
+ import os
19
+ from logging import (
20
+ CRITICAL, # NOQA
21
+ DEBUG, # NOQA
22
+ ERROR, # NOQA
23
+ FATAL, # NOQA
24
+ INFO, # NOQA
25
+ NOTSET, # NOQA
26
+ WARN, # NOQA
27
+ WARNING, # NOQA
28
+ )
29
+ from typing import Optional
30
+
31
+
32
+ log_levels = {
33
+ "debug": logging.DEBUG,
34
+ "info": logging.INFO,
35
+ "warning": logging.WARNING,
36
+ "error": logging.ERROR,
37
+ "critical": logging.CRITICAL,
38
+ }
39
+
40
+ _default_log_level = logging.WARNING
41
+
42
+
43
+ def _get_library_name() -> str:
44
+ return __name__.split(".")[0]
45
+
46
+
47
+ def _get_library_root_logger() -> logging.Logger:
48
+ return logging.getLogger(_get_library_name())
49
+
50
+
51
+ def _get_default_logging_level():
52
+ """
53
+ If `HF_HUB_VERBOSITY` env var is set to one of the valid choices return that as the new default level. If it is not
54
+ - fall back to `_default_log_level`
55
+ """
56
+ env_level_str = os.getenv("HF_HUB_VERBOSITY", None)
57
+ if env_level_str:
58
+ if env_level_str in log_levels:
59
+ return log_levels[env_level_str]
60
+ else:
61
+ logging.getLogger().warning(
62
+ f"Unknown option HF_HUB_VERBOSITY={env_level_str}, has to be one of: { ', '.join(log_levels.keys()) }"
63
+ )
64
+ return _default_log_level
65
+
66
+
67
+ def _configure_library_root_logger() -> None:
68
+ library_root_logger = _get_library_root_logger()
69
+ library_root_logger.addHandler(logging.StreamHandler())
70
+ library_root_logger.setLevel(_get_default_logging_level())
71
+
72
+
73
+ def _reset_library_root_logger() -> None:
74
+ library_root_logger = _get_library_root_logger()
75
+ library_root_logger.setLevel(logging.NOTSET)
76
+
77
+
78
+ def get_logger(name: Optional[str] = None) -> logging.Logger:
79
+ """
80
+ Returns a logger with the specified name. This function is not supposed
81
+ to be directly accessed by library users.
82
+
83
+ Args:
84
+ name (`str`, *optional*):
85
+ The name of the logger to get, usually the filename
86
+
87
+ Example:
88
+
89
+ ```python
90
+ >>> from huggingface_hub import get_logger
91
+
92
+ >>> logger = get_logger(__file__)
93
+ >>> logger.set_verbosity_info()
94
+ ```
95
+ """
96
+
97
+ if name is None:
98
+ name = _get_library_name()
99
+
100
+ return logging.getLogger(name)
101
+
102
+
103
+ def get_verbosity() -> int:
104
+ """Return the current level for the HuggingFace Hub's root logger.
105
+
106
+ Returns:
107
+ Logging level, e.g., `huggingface_hub.logging.DEBUG` and
108
+ `huggingface_hub.logging.INFO`.
109
+
110
+ <Tip>
111
+
112
+ HuggingFace Hub has following logging levels:
113
+
114
+ - `huggingface_hub.logging.CRITICAL`, `huggingface_hub.logging.FATAL`
115
+ - `huggingface_hub.logging.ERROR`
116
+ - `huggingface_hub.logging.WARNING`, `huggingface_hub.logging.WARN`
117
+ - `huggingface_hub.logging.INFO`
118
+ - `huggingface_hub.logging.DEBUG`
119
+
120
+ </Tip>
121
+ """
122
+ return _get_library_root_logger().getEffectiveLevel()
123
+
124
+
125
+ def set_verbosity(verbosity: int) -> None:
126
+ """
127
+ Sets the level for the HuggingFace Hub's root logger.
128
+
129
+ Args:
130
+ verbosity (`int`):
131
+ Logging level, e.g., `huggingface_hub.logging.DEBUG` and
132
+ `huggingface_hub.logging.INFO`.
133
+ """
134
+ _get_library_root_logger().setLevel(verbosity)
135
+
136
+
137
+ def set_verbosity_info():
138
+ """
139
+ Sets the verbosity to `logging.INFO`.
140
+ """
141
+ return set_verbosity(INFO)
142
+
143
+
144
+ def set_verbosity_warning():
145
+ """
146
+ Sets the verbosity to `logging.WARNING`.
147
+ """
148
+ return set_verbosity(WARNING)
149
+
150
+
151
+ def set_verbosity_debug():
152
+ """
153
+ Sets the verbosity to `logging.DEBUG`.
154
+ """
155
+ return set_verbosity(DEBUG)
156
+
157
+
158
+ def set_verbosity_error():
159
+ """
160
+ Sets the verbosity to `logging.ERROR`.
161
+ """
162
+ return set_verbosity(ERROR)
163
+
164
+
165
+ def disable_propagation() -> None:
166
+ """
167
+ Disable propagation of the library log outputs. Note that log propagation is
168
+ disabled by default.
169
+ """
170
+ _get_library_root_logger().propagate = False
171
+
172
+
173
+ def enable_propagation() -> None:
174
+ """
175
+ Enable propagation of the library log outputs. Please disable the
176
+ HuggingFace Hub's default handler to prevent double logging if the root
177
+ logger has been configured.
178
+ """
179
+ _get_library_root_logger().propagate = True
180
+
181
+
182
+ _configure_library_root_logger()
evalkit_tf437/lib/python3.10/site-packages/huggingface_hub/utils/tqdm.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License
15
+ """Utility helpers to handle progress bars in `huggingface_hub`.
16
+
17
+ Example:
18
+ 1. Use `huggingface_hub.utils.tqdm` as you would use `tqdm.tqdm` or `tqdm.auto.tqdm`.
19
+ 2. To disable progress bars, either use `disable_progress_bars()` helper or set the
20
+ environment variable `HF_HUB_DISABLE_PROGRESS_BARS` to 1.
21
+ 3. To re-enable progress bars, use `enable_progress_bars()`.
22
+ 4. To check whether progress bars are disabled, use `are_progress_bars_disabled()`.
23
+
24
+ NOTE: Environment variable `HF_HUB_DISABLE_PROGRESS_BARS` has the priority.
25
+
26
+ Example:
27
+ ```py
28
+ >>> from huggingface_hub.utils import are_progress_bars_disabled, disable_progress_bars, enable_progress_bars, tqdm
29
+
30
+ # Disable progress bars globally
31
+ >>> disable_progress_bars()
32
+
33
+ # Use as normal `tqdm`
34
+ >>> for _ in tqdm(range(5)):
35
+ ... pass
36
+
37
+ # Still not showing progress bars, as `disable=False` is overwritten to `True`.
38
+ >>> for _ in tqdm(range(5), disable=False):
39
+ ... pass
40
+
41
+ >>> are_progress_bars_disabled()
42
+ True
43
+
44
+ # Re-enable progress bars globally
45
+ >>> enable_progress_bars()
46
+
47
+ # Progress bar will be shown !
48
+ >>> for _ in tqdm(range(5)):
49
+ ... pass
50
+ 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 5/5 [00:00<00:00, 117817.53it/s]
51
+ ```
52
+
53
+ Group-based control:
54
+ ```python
55
+ # Disable progress bars for a specific group
56
+ >>> disable_progress_bars("peft.foo")
57
+
58
+ # Check state of different groups
59
+ >>> assert not are_progress_bars_disabled("peft"))
60
+ >>> assert not are_progress_bars_disabled("peft.something")
61
+ >>> assert are_progress_bars_disabled("peft.foo"))
62
+ >>> assert are_progress_bars_disabled("peft.foo.bar"))
63
+
64
+ # Enable progress bars for a subgroup
65
+ >>> enable_progress_bars("peft.foo.bar")
66
+
67
+ # Check if enabling a subgroup affects the parent group
68
+ >>> assert are_progress_bars_disabled("peft.foo"))
69
+ >>> assert not are_progress_bars_disabled("peft.foo.bar"))
70
+
71
+ # No progress bar for `name="peft.foo"`
72
+ >>> for _ in tqdm(range(5), name="peft.foo"):
73
+ ... pass
74
+
75
+ # Progress bar will be shown for `name="peft.foo.bar"`
76
+ >>> for _ in tqdm(range(5), name="peft.foo.bar"):
77
+ ... pass
78
+ 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 5/5 [00:00<00:00, 117817.53it/s]
79
+
80
+ ```
81
+ """
82
+
83
+ import io
84
+ import warnings
85
+ from contextlib import contextmanager
86
+ from pathlib import Path
87
+ from typing import Dict, Iterator, Optional, Union
88
+
89
+ from tqdm.auto import tqdm as old_tqdm
90
+
91
+ from ..constants import HF_HUB_DISABLE_PROGRESS_BARS
92
+
93
+
94
+ # The `HF_HUB_DISABLE_PROGRESS_BARS` environment variable can be True, False, or not set (None),
95
+ # allowing for control over progress bar visibility. When set, this variable takes precedence
96
+ # over programmatic settings, dictating whether progress bars should be shown or hidden globally.
97
+ # Essentially, the environment variable's setting overrides any code-based configurations.
98
+ #
99
+ # If `HF_HUB_DISABLE_PROGRESS_BARS` is not defined (None), it implies that users can manage
100
+ # progress bar visibility through code. By default, progress bars are turned on.
101
+
102
+
103
+ progress_bar_states: Dict[str, bool] = {}
104
+
105
+
106
+ def disable_progress_bars(name: Optional[str] = None) -> None:
107
+ """
108
+ Disable progress bars either globally or for a specified group.
109
+
110
+ This function updates the state of progress bars based on a group name.
111
+ If no group name is provided, all progress bars are disabled. The operation
112
+ respects the `HF_HUB_DISABLE_PROGRESS_BARS` environment variable's setting.
113
+
114
+ Args:
115
+ name (`str`, *optional*):
116
+ The name of the group for which to disable the progress bars. If None,
117
+ progress bars are disabled globally.
118
+
119
+ Raises:
120
+ Warning: If the environment variable precludes changes.
121
+ """
122
+ if HF_HUB_DISABLE_PROGRESS_BARS is False:
123
+ warnings.warn(
124
+ "Cannot disable progress bars: environment variable `HF_HUB_DISABLE_PROGRESS_BARS=0` is set and has priority."
125
+ )
126
+ return
127
+
128
+ if name is None:
129
+ progress_bar_states.clear()
130
+ progress_bar_states["_global"] = False
131
+ else:
132
+ keys_to_remove = [key for key in progress_bar_states if key.startswith(f"{name}.")]
133
+ for key in keys_to_remove:
134
+ del progress_bar_states[key]
135
+ progress_bar_states[name] = False
136
+
137
+
138
+ def enable_progress_bars(name: Optional[str] = None) -> None:
139
+ """
140
+ Enable progress bars either globally or for a specified group.
141
+
142
+ This function sets the progress bars to enabled for the specified group or globally
143
+ if no group is specified. The operation is subject to the `HF_HUB_DISABLE_PROGRESS_BARS`
144
+ environment setting.
145
+
146
+ Args:
147
+ name (`str`, *optional*):
148
+ The name of the group for which to enable the progress bars. If None,
149
+ progress bars are enabled globally.
150
+
151
+ Raises:
152
+ Warning: If the environment variable precludes changes.
153
+ """
154
+ if HF_HUB_DISABLE_PROGRESS_BARS is True:
155
+ warnings.warn(
156
+ "Cannot enable progress bars: environment variable `HF_HUB_DISABLE_PROGRESS_BARS=1` is set and has priority."
157
+ )
158
+ return
159
+
160
+ if name is None:
161
+ progress_bar_states.clear()
162
+ progress_bar_states["_global"] = True
163
+ else:
164
+ keys_to_remove = [key for key in progress_bar_states if key.startswith(f"{name}.")]
165
+ for key in keys_to_remove:
166
+ del progress_bar_states[key]
167
+ progress_bar_states[name] = True
168
+
169
+
170
+ def are_progress_bars_disabled(name: Optional[str] = None) -> bool:
171
+ """
172
+ Check if progress bars are disabled globally or for a specific group.
173
+
174
+ This function returns whether progress bars are disabled for a given group or globally.
175
+ It checks the `HF_HUB_DISABLE_PROGRESS_BARS` environment variable first, then the programmatic
176
+ settings.
177
+
178
+ Args:
179
+ name (`str`, *optional*):
180
+ The group name to check; if None, checks the global setting.
181
+
182
+ Returns:
183
+ `bool`: True if progress bars are disabled, False otherwise.
184
+ """
185
+ if HF_HUB_DISABLE_PROGRESS_BARS is True:
186
+ return True
187
+
188
+ if name is None:
189
+ return not progress_bar_states.get("_global", True)
190
+
191
+ while name:
192
+ if name in progress_bar_states:
193
+ return not progress_bar_states[name]
194
+ name = ".".join(name.split(".")[:-1])
195
+
196
+ return not progress_bar_states.get("_global", True)
197
+
198
+
199
+ class tqdm(old_tqdm):
200
+ """
201
+ Class to override `disable` argument in case progress bars are globally disabled.
202
+
203
+ Taken from https://github.com/tqdm/tqdm/issues/619#issuecomment-619639324.
204
+ """
205
+
206
+ def __init__(self, *args, **kwargs):
207
+ name = kwargs.pop("name", None) # do not pass `name` to `tqdm`
208
+ if are_progress_bars_disabled(name):
209
+ kwargs["disable"] = True
210
+ super().__init__(*args, **kwargs)
211
+
212
+ def __delattr__(self, attr: str) -> None:
213
+ """Fix for https://github.com/huggingface/huggingface_hub/issues/1603"""
214
+ try:
215
+ super().__delattr__(attr)
216
+ except AttributeError:
217
+ if attr != "_lock":
218
+ raise
219
+
220
+
221
+ @contextmanager
222
+ def tqdm_stream_file(path: Union[Path, str]) -> Iterator[io.BufferedReader]:
223
+ """
224
+ Open a file as binary and wrap the `read` method to display a progress bar when it's streamed.
225
+
226
+ First implemented in `transformers` in 2019 but removed when switched to git-lfs. Used in `huggingface_hub` to show
227
+ progress bar when uploading an LFS file to the Hub. See github.com/huggingface/transformers/pull/2078#discussion_r354739608
228
+ for implementation details.
229
+
230
+ Note: currently implementation handles only files stored on disk as it is the most common use case. Could be
231
+ extended to stream any `BinaryIO` object but we might have to debug some corner cases.
232
+
233
+ Example:
234
+ ```py
235
+ >>> with tqdm_stream_file("config.json") as f:
236
+ >>> requests.put(url, data=f)
237
+ config.json: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 8.19k/8.19k [00:02<00:00, 3.72kB/s]
238
+ ```
239
+ """
240
+ if isinstance(path, str):
241
+ path = Path(path)
242
+
243
+ with path.open("rb") as f:
244
+ total_size = path.stat().st_size
245
+ pbar = tqdm(
246
+ unit="B",
247
+ unit_scale=True,
248
+ total=total_size,
249
+ initial=0,
250
+ desc=path.name,
251
+ )
252
+
253
+ f_read = f.read
254
+
255
+ def _inner_read(size: Optional[int] = -1) -> bytes:
256
+ data = f_read(size)
257
+ pbar.update(len(data))
258
+ return data
259
+
260
+ f.read = _inner_read # type: ignore
261
+
262
+ yield f
263
+
264
+ pbar.close()
evalkit_tf449/share/terminfo/q/qansi-t ADDED
Binary file (2.01 kB). View file
 
evalkit_tf449/share/terminfo/q/qnx ADDED
Binary file (1.37 kB). View file
 
evalkit_tf449/share/terminfo/q/qume ADDED
Binary file (364 Bytes). View file
 
evalkit_tf449/share/terminfo/q/qvt119+-w ADDED
Binary file (598 Bytes). View file
 
evalkit_tf449/share/terminfo/q/qvt119-25-w ADDED
Binary file (595 Bytes). View file
 
evalkit_tf449/share/terminfo/q/qvt119-w ADDED
Binary file (598 Bytes). View file
 
evalkit_tf449/share/terminfo/q/qvt203+ ADDED
Binary file (855 Bytes). View file
 
evalkit_tf449/share/terminfo/q/qvt203-25-w ADDED
Binary file (855 Bytes). View file
 
evalkit_tf449/share/terminfo/x/x1720 ADDED
Binary file (356 Bytes). View file
 
evalkit_tf449/share/terminfo/x/xerox ADDED
Binary file (429 Bytes). View file
 
evalkit_tf449/share/terminfo/x/xerox820 ADDED
Binary file (355 Bytes). View file
 
evalkit_tf449/share/terminfo/x/xiterm ADDED
Binary file (1.57 kB). View file
 
evalkit_tf449/share/terminfo/x/xl83 ADDED
Binary file (414 Bytes). View file
 
evalkit_tf449/share/terminfo/x/xnuppc+144x48 ADDED
Binary file (88 Bytes). View file
 
evalkit_tf449/share/terminfo/x/xnuppc+200x75 ADDED
Binary file (90 Bytes). View file
 
evalkit_tf449/share/terminfo/x/xnuppc+b ADDED
Binary file (991 Bytes). View file
 
evalkit_tf449/share/terminfo/x/xnuppc+f ADDED
Binary file (1.01 kB). View file
 
evalkit_tf449/share/terminfo/x/xnuppc-100x37-m ADDED
Binary file (987 Bytes). View file
 
evalkit_tf449/share/terminfo/x/xnuppc-160x64-m ADDED
Binary file (987 Bytes). View file
 
evalkit_tf449/share/terminfo/x/xnuppc-200x64 ADDED
Binary file (1.22 kB). View file
 
evalkit_tf449/share/terminfo/x/xnuppc-256x96-m ADDED
Binary file (987 Bytes). View file
 
evalkit_tf449/share/terminfo/x/xnuppc-80x30 ADDED
Binary file (1.21 kB). View file