huggingface-hub 0.36.0rc0__py3-none-any.whl → 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of huggingface-hub might be problematic. Click here for more details.

Files changed (132) hide show
  1. huggingface_hub/__init__.py +33 -45
  2. huggingface_hub/_commit_api.py +39 -43
  3. huggingface_hub/_commit_scheduler.py +11 -8
  4. huggingface_hub/_inference_endpoints.py +8 -8
  5. huggingface_hub/_jobs_api.py +20 -20
  6. huggingface_hub/_login.py +17 -43
  7. huggingface_hub/_oauth.py +8 -8
  8. huggingface_hub/_snapshot_download.py +135 -50
  9. huggingface_hub/_space_api.py +4 -4
  10. huggingface_hub/_tensorboard_logger.py +5 -5
  11. huggingface_hub/_upload_large_folder.py +18 -32
  12. huggingface_hub/_webhooks_payload.py +3 -3
  13. huggingface_hub/_webhooks_server.py +2 -2
  14. huggingface_hub/cli/__init__.py +0 -14
  15. huggingface_hub/cli/_cli_utils.py +143 -39
  16. huggingface_hub/cli/auth.py +105 -171
  17. huggingface_hub/cli/cache.py +594 -361
  18. huggingface_hub/cli/download.py +120 -112
  19. huggingface_hub/cli/hf.py +38 -41
  20. huggingface_hub/cli/jobs.py +689 -1017
  21. huggingface_hub/cli/lfs.py +120 -143
  22. huggingface_hub/cli/repo.py +282 -216
  23. huggingface_hub/cli/repo_files.py +50 -84
  24. huggingface_hub/cli/system.py +6 -25
  25. huggingface_hub/cli/upload.py +198 -220
  26. huggingface_hub/cli/upload_large_folder.py +91 -106
  27. huggingface_hub/community.py +5 -5
  28. huggingface_hub/constants.py +17 -52
  29. huggingface_hub/dataclasses.py +135 -21
  30. huggingface_hub/errors.py +47 -30
  31. huggingface_hub/fastai_utils.py +8 -9
  32. huggingface_hub/file_download.py +351 -303
  33. huggingface_hub/hf_api.py +398 -570
  34. huggingface_hub/hf_file_system.py +101 -66
  35. huggingface_hub/hub_mixin.py +32 -54
  36. huggingface_hub/inference/_client.py +177 -162
  37. huggingface_hub/inference/_common.py +38 -54
  38. huggingface_hub/inference/_generated/_async_client.py +218 -258
  39. huggingface_hub/inference/_generated/types/automatic_speech_recognition.py +3 -3
  40. huggingface_hub/inference/_generated/types/base.py +10 -7
  41. huggingface_hub/inference/_generated/types/chat_completion.py +16 -16
  42. huggingface_hub/inference/_generated/types/depth_estimation.py +2 -2
  43. huggingface_hub/inference/_generated/types/document_question_answering.py +2 -2
  44. huggingface_hub/inference/_generated/types/feature_extraction.py +2 -2
  45. huggingface_hub/inference/_generated/types/fill_mask.py +2 -2
  46. huggingface_hub/inference/_generated/types/sentence_similarity.py +3 -3
  47. huggingface_hub/inference/_generated/types/summarization.py +2 -2
  48. huggingface_hub/inference/_generated/types/table_question_answering.py +4 -4
  49. huggingface_hub/inference/_generated/types/text2text_generation.py +2 -2
  50. huggingface_hub/inference/_generated/types/text_generation.py +10 -10
  51. huggingface_hub/inference/_generated/types/text_to_video.py +2 -2
  52. huggingface_hub/inference/_generated/types/token_classification.py +2 -2
  53. huggingface_hub/inference/_generated/types/translation.py +2 -2
  54. huggingface_hub/inference/_generated/types/zero_shot_classification.py +2 -2
  55. huggingface_hub/inference/_generated/types/zero_shot_image_classification.py +2 -2
  56. huggingface_hub/inference/_generated/types/zero_shot_object_detection.py +1 -3
  57. huggingface_hub/inference/_mcp/agent.py +3 -3
  58. huggingface_hub/inference/_mcp/constants.py +1 -2
  59. huggingface_hub/inference/_mcp/mcp_client.py +33 -22
  60. huggingface_hub/inference/_mcp/types.py +10 -10
  61. huggingface_hub/inference/_mcp/utils.py +4 -4
  62. huggingface_hub/inference/_providers/__init__.py +12 -4
  63. huggingface_hub/inference/_providers/_common.py +62 -24
  64. huggingface_hub/inference/_providers/black_forest_labs.py +6 -6
  65. huggingface_hub/inference/_providers/cohere.py +3 -3
  66. huggingface_hub/inference/_providers/fal_ai.py +25 -25
  67. huggingface_hub/inference/_providers/featherless_ai.py +4 -4
  68. huggingface_hub/inference/_providers/fireworks_ai.py +3 -3
  69. huggingface_hub/inference/_providers/hf_inference.py +13 -13
  70. huggingface_hub/inference/_providers/hyperbolic.py +4 -4
  71. huggingface_hub/inference/_providers/nebius.py +10 -10
  72. huggingface_hub/inference/_providers/novita.py +5 -5
  73. huggingface_hub/inference/_providers/nscale.py +4 -4
  74. huggingface_hub/inference/_providers/replicate.py +15 -15
  75. huggingface_hub/inference/_providers/sambanova.py +6 -6
  76. huggingface_hub/inference/_providers/together.py +7 -7
  77. huggingface_hub/lfs.py +21 -94
  78. huggingface_hub/repocard.py +15 -16
  79. huggingface_hub/repocard_data.py +57 -57
  80. huggingface_hub/serialization/__init__.py +0 -1
  81. huggingface_hub/serialization/_base.py +9 -9
  82. huggingface_hub/serialization/_dduf.py +7 -7
  83. huggingface_hub/serialization/_torch.py +28 -28
  84. huggingface_hub/utils/__init__.py +11 -6
  85. huggingface_hub/utils/_auth.py +5 -5
  86. huggingface_hub/utils/_cache_manager.py +49 -74
  87. huggingface_hub/utils/_deprecation.py +1 -1
  88. huggingface_hub/utils/_dotenv.py +3 -3
  89. huggingface_hub/utils/_fixes.py +0 -10
  90. huggingface_hub/utils/_git_credential.py +3 -3
  91. huggingface_hub/utils/_headers.py +7 -29
  92. huggingface_hub/utils/_http.py +371 -208
  93. huggingface_hub/utils/_pagination.py +4 -4
  94. huggingface_hub/utils/_parsing.py +98 -0
  95. huggingface_hub/utils/_paths.py +5 -5
  96. huggingface_hub/utils/_runtime.py +59 -23
  97. huggingface_hub/utils/_safetensors.py +21 -21
  98. huggingface_hub/utils/_subprocess.py +9 -9
  99. huggingface_hub/utils/_telemetry.py +3 -3
  100. huggingface_hub/{commands/_cli_utils.py → utils/_terminal.py} +4 -9
  101. huggingface_hub/utils/_typing.py +3 -3
  102. huggingface_hub/utils/_validators.py +53 -72
  103. huggingface_hub/utils/_xet.py +16 -16
  104. huggingface_hub/utils/_xet_progress_reporting.py +1 -1
  105. huggingface_hub/utils/insecure_hashlib.py +3 -9
  106. huggingface_hub/utils/tqdm.py +3 -3
  107. {huggingface_hub-0.36.0rc0.dist-info → huggingface_hub-1.0.0.dist-info}/METADATA +16 -35
  108. huggingface_hub-1.0.0.dist-info/RECORD +152 -0
  109. {huggingface_hub-0.36.0rc0.dist-info → huggingface_hub-1.0.0.dist-info}/entry_points.txt +0 -1
  110. huggingface_hub/commands/__init__.py +0 -27
  111. huggingface_hub/commands/delete_cache.py +0 -476
  112. huggingface_hub/commands/download.py +0 -204
  113. huggingface_hub/commands/env.py +0 -39
  114. huggingface_hub/commands/huggingface_cli.py +0 -65
  115. huggingface_hub/commands/lfs.py +0 -200
  116. huggingface_hub/commands/repo.py +0 -151
  117. huggingface_hub/commands/repo_files.py +0 -132
  118. huggingface_hub/commands/scan_cache.py +0 -183
  119. huggingface_hub/commands/tag.py +0 -161
  120. huggingface_hub/commands/upload.py +0 -318
  121. huggingface_hub/commands/upload_large_folder.py +0 -131
  122. huggingface_hub/commands/user.py +0 -208
  123. huggingface_hub/commands/version.py +0 -40
  124. huggingface_hub/inference_api.py +0 -217
  125. huggingface_hub/keras_mixin.py +0 -497
  126. huggingface_hub/repository.py +0 -1471
  127. huggingface_hub/serialization/_tensorflow.py +0 -92
  128. huggingface_hub/utils/_hf_folder.py +0 -68
  129. huggingface_hub-0.36.0rc0.dist-info/RECORD +0 -170
  130. {huggingface_hub-0.36.0rc0.dist-info → huggingface_hub-1.0.0.dist-info}/LICENSE +0 -0
  131. {huggingface_hub-0.36.0rc0.dist-info → huggingface_hub-1.0.0.dist-info}/WHEEL +0 -0
  132. {huggingface_hub-0.36.0rc0.dist-info → huggingface_hub-1.0.0.dist-info}/top_level.txt +0 -0
@@ -1,497 +0,0 @@
1
- import collections.abc as collections
2
- import json
3
- import os
4
- import warnings
5
- from functools import wraps
6
- from pathlib import Path
7
- from shutil import copytree
8
- from typing import Any, Dict, List, Optional, Union
9
-
10
- from huggingface_hub import ModelHubMixin, snapshot_download
11
- from huggingface_hub.utils import (
12
- get_tf_version,
13
- is_graphviz_available,
14
- is_pydot_available,
15
- is_tf_available,
16
- yaml_dump,
17
- )
18
-
19
- from . import constants
20
- from .hf_api import HfApi
21
- from .utils import SoftTemporaryDirectory, logging, validate_hf_hub_args
22
- from .utils._typing import CallableT
23
-
24
-
25
- logger = logging.get_logger(__name__)
26
-
27
- keras = None
28
- if is_tf_available():
29
- # Depending on which version of TensorFlow is installed, we need to import
30
- # keras from the correct location.
31
- # See https://github.com/tensorflow/tensorflow/releases/tag/v2.16.1.
32
- # Note: saving a keras model only works with Keras<3.0.
33
- try:
34
- import tf_keras as keras # type: ignore
35
- except ImportError:
36
- import tensorflow as tf # type: ignore
37
-
38
- keras = tf.keras
39
-
40
-
41
- def _requires_keras_2_model(fn: CallableT) -> CallableT:
42
- # Wrapper to raise if user tries to save a Keras 3.x model
43
- @wraps(fn)
44
- def _inner(model, *args, **kwargs):
45
- if not hasattr(model, "history"): # hacky way to check if model is Keras 2.x
46
- raise NotImplementedError(
47
- f"Cannot use '{fn.__name__}': Keras 3.x is not supported."
48
- " Please save models manually and upload them using `upload_folder` or `hf upload`."
49
- )
50
- return fn(model, *args, **kwargs)
51
-
52
- return _inner # type: ignore [return-value]
53
-
54
-
55
- def _flatten_dict(dictionary, parent_key=""):
56
- """Flatten a nested dictionary.
57
- Reference: https://stackoverflow.com/a/6027615/10319735
58
-
59
- Args:
60
- dictionary (`dict`):
61
- The nested dictionary to be flattened.
62
- parent_key (`str`):
63
- The parent key to be prefixed to the children keys.
64
- Necessary for recursing over the nested dictionary.
65
-
66
- Returns:
67
- The flattened dictionary.
68
- """
69
- items = []
70
- for key, value in dictionary.items():
71
- new_key = f"{parent_key}.{key}" if parent_key else key
72
- if isinstance(value, collections.MutableMapping):
73
- items.extend(
74
- _flatten_dict(
75
- value,
76
- new_key,
77
- ).items()
78
- )
79
- else:
80
- items.append((new_key, value))
81
- return dict(items)
82
-
83
-
84
- def _create_hyperparameter_table(model):
85
- """Parse hyperparameter dictionary into a markdown table."""
86
- table = None
87
- if model.optimizer is not None:
88
- optimizer_params = model.optimizer.get_config()
89
- # flatten the configuration
90
- optimizer_params = _flatten_dict(optimizer_params)
91
- optimizer_params["training_precision"] = keras.mixed_precision.global_policy().name
92
- table = "| Hyperparameters | Value |\n| :-- | :-- |\n"
93
- for key, value in optimizer_params.items():
94
- table += f"| {key} | {value} |\n"
95
- return table
96
-
97
-
98
- def _plot_network(model, save_directory):
99
- keras.utils.plot_model(
100
- model,
101
- to_file=f"{save_directory}/model.png",
102
- show_shapes=False,
103
- show_dtype=False,
104
- show_layer_names=True,
105
- rankdir="TB",
106
- expand_nested=False,
107
- dpi=96,
108
- layer_range=None,
109
- )
110
-
111
-
112
- def _create_model_card(
113
- model,
114
- repo_dir: Path,
115
- plot_model: bool = True,
116
- metadata: Optional[dict] = None,
117
- ):
118
- """
119
- Creates a model card for the repository.
120
-
121
- Do not overwrite an existing README.md file.
122
- """
123
- readme_path = repo_dir / "README.md"
124
- if readme_path.exists():
125
- return
126
-
127
- hyperparameters = _create_hyperparameter_table(model)
128
- if plot_model and is_graphviz_available() and is_pydot_available():
129
- _plot_network(model, repo_dir)
130
- if metadata is None:
131
- metadata = {}
132
- metadata["library_name"] = "keras"
133
- model_card: str = "---\n"
134
- model_card += yaml_dump(metadata, default_flow_style=False)
135
- model_card += "---\n"
136
- model_card += "\n## Model description\n\nMore information needed\n"
137
- model_card += "\n## Intended uses & limitations\n\nMore information needed\n"
138
- model_card += "\n## Training and evaluation data\n\nMore information needed\n"
139
- if hyperparameters is not None:
140
- model_card += "\n## Training procedure\n"
141
- model_card += "\n### Training hyperparameters\n"
142
- model_card += "\nThe following hyperparameters were used during training:\n\n"
143
- model_card += hyperparameters
144
- model_card += "\n"
145
- if plot_model and os.path.exists(f"{repo_dir}/model.png"):
146
- model_card += "\n ## Model Plot\n"
147
- model_card += "\n<details>"
148
- model_card += "\n<summary>View Model Plot</summary>\n"
149
- path_to_plot = "./model.png"
150
- model_card += f"\n![Model Image]({path_to_plot})\n"
151
- model_card += "\n</details>"
152
-
153
- readme_path.write_text(model_card)
154
-
155
-
156
- @_requires_keras_2_model
157
- def save_pretrained_keras(
158
- model,
159
- save_directory: Union[str, Path],
160
- config: Optional[Dict[str, Any]] = None,
161
- include_optimizer: bool = False,
162
- plot_model: bool = True,
163
- tags: Optional[Union[list, str]] = None,
164
- **model_save_kwargs,
165
- ):
166
- """
167
- Saves a Keras model to save_directory in SavedModel format. Use this if
168
- you're using the Functional or Sequential APIs.
169
-
170
- Args:
171
- model (`Keras.Model`):
172
- The [Keras
173
- model](https://www.tensorflow.org/api_docs/python/tf/keras/Model)
174
- you'd like to save. The model must be compiled and built.
175
- save_directory (`str` or `Path`):
176
- Specify directory in which you want to save the Keras model.
177
- config (`dict`, *optional*):
178
- Configuration object to be saved alongside the model weights.
179
- include_optimizer(`bool`, *optional*, defaults to `False`):
180
- Whether or not to include optimizer in serialization.
181
- plot_model (`bool`, *optional*, defaults to `True`):
182
- Setting this to `True` will plot the model and put it in the model
183
- card. Requires graphviz and pydot to be installed.
184
- tags (Union[`str`,`list`], *optional*):
185
- List of tags that are related to model or string of a single tag. See example tags
186
- [here](https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1).
187
- model_save_kwargs(`dict`, *optional*):
188
- model_save_kwargs will be passed to
189
- [`tf.keras.models.save_model()`](https://www.tensorflow.org/api_docs/python/tf/keras/models/save_model).
190
- """
191
- if keras is None:
192
- raise ImportError("Called a Tensorflow-specific function but could not import it.")
193
-
194
- if not model.built:
195
- raise ValueError("Model should be built before trying to save")
196
-
197
- save_directory = Path(save_directory)
198
- save_directory.mkdir(parents=True, exist_ok=True)
199
-
200
- # saving config
201
- if config:
202
- if not isinstance(config, dict):
203
- raise RuntimeError(f"Provided config to save_pretrained_keras should be a dict. Got: '{type(config)}'")
204
-
205
- with (save_directory / constants.CONFIG_NAME).open("w") as f:
206
- json.dump(config, f)
207
-
208
- metadata = {}
209
- if isinstance(tags, list):
210
- metadata["tags"] = tags
211
- elif isinstance(tags, str):
212
- metadata["tags"] = [tags]
213
-
214
- task_name = model_save_kwargs.pop("task_name", None)
215
- if task_name is not None:
216
- warnings.warn(
217
- "`task_name` input argument is deprecated. Pass `tags` instead.",
218
- FutureWarning,
219
- )
220
- if "tags" in metadata:
221
- metadata["tags"].append(task_name)
222
- else:
223
- metadata["tags"] = [task_name]
224
-
225
- if model.history is not None:
226
- if model.history.history != {}:
227
- path = save_directory / "history.json"
228
- if path.exists():
229
- warnings.warn(
230
- "`history.json` file already exists, it will be overwritten by the history of this version.",
231
- UserWarning,
232
- )
233
- with path.open("w", encoding="utf-8") as f:
234
- json.dump(model.history.history, f, indent=2, sort_keys=True)
235
-
236
- _create_model_card(model, save_directory, plot_model, metadata)
237
- keras.models.save_model(model, save_directory, include_optimizer=include_optimizer, **model_save_kwargs)
238
-
239
-
240
- def from_pretrained_keras(*args, **kwargs) -> "KerasModelHubMixin":
241
- r"""
242
- Instantiate a pretrained Keras model from a pre-trained model from the Hub.
243
- The model is expected to be in `SavedModel` format.
244
-
245
- Args:
246
- pretrained_model_name_or_path (`str` or `os.PathLike`):
247
- Can be either:
248
- - A string, the `model id` of a pretrained model hosted inside a
249
- model repo on huggingface.co. Valid model ids can be located
250
- at the root-level, like `bert-base-uncased`, or namespaced
251
- under a user or organization name, like
252
- `dbmdz/bert-base-german-cased`.
253
- - You can add `revision` by appending `@` at the end of model_id
254
- simply like this: `dbmdz/bert-base-german-cased@main` Revision
255
- is the specific model version to use. It can be a branch name,
256
- a tag name, or a commit id, since we use a git-based system
257
- for storing models and other artifacts on huggingface.co, so
258
- `revision` can be any identifier allowed by git.
259
- - A path to a `directory` containing model weights saved using
260
- [`~transformers.PreTrainedModel.save_pretrained`], e.g.,
261
- `./my_model_directory/`.
262
- - `None` if you are both providing the configuration and state
263
- dictionary (resp. with keyword arguments `config` and
264
- `state_dict`).
265
- force_download (`bool`, *optional*, defaults to `False`):
266
- Whether to force the (re-)download of the model weights and
267
- configuration files, overriding the cached versions if they exist.
268
- proxies (`Dict[str, str]`, *optional*):
269
- A dictionary of proxy servers to use by protocol or endpoint, e.g.,
270
- `{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}`. The
271
- proxies are used on each request.
272
- token (`str` or `bool`, *optional*):
273
- The token to use as HTTP bearer authorization for remote files. If
274
- `True`, will use the token generated when running `transformers-cli
275
- login` (stored in `~/.huggingface`).
276
- cache_dir (`Union[str, os.PathLike]`, *optional*):
277
- Path to a directory in which a downloaded pretrained model
278
- configuration should be cached if the standard cache should not be
279
- used.
280
- local_files_only(`bool`, *optional*, defaults to `False`):
281
- Whether to only look at local files (i.e., do not try to download
282
- the model).
283
- model_kwargs (`Dict`, *optional*):
284
- model_kwargs will be passed to the model during initialization
285
-
286
- > [!TIP]
287
- > Passing `token=True` is required when you want to use a private
288
- > model.
289
- """
290
- return KerasModelHubMixin.from_pretrained(*args, **kwargs)
291
-
292
-
293
- @validate_hf_hub_args
294
- @_requires_keras_2_model
295
- def push_to_hub_keras(
296
- model,
297
- repo_id: str,
298
- *,
299
- config: Optional[dict] = None,
300
- commit_message: str = "Push Keras model using huggingface_hub.",
301
- private: Optional[bool] = None,
302
- api_endpoint: Optional[str] = None,
303
- token: Optional[str] = None,
304
- branch: Optional[str] = None,
305
- create_pr: Optional[bool] = None,
306
- allow_patterns: Optional[Union[List[str], str]] = None,
307
- ignore_patterns: Optional[Union[List[str], str]] = None,
308
- delete_patterns: Optional[Union[List[str], str]] = None,
309
- log_dir: Optional[str] = None,
310
- include_optimizer: bool = False,
311
- tags: Optional[Union[list, str]] = None,
312
- plot_model: bool = True,
313
- **model_save_kwargs,
314
- ):
315
- """
316
- Upload model checkpoint to the Hub.
317
-
318
- Use `allow_patterns` and `ignore_patterns` to precisely filter which files should be pushed to the hub. Use
319
- `delete_patterns` to delete existing remote files in the same commit. See [`upload_folder`] reference for more
320
- details.
321
-
322
- Args:
323
- model (`Keras.Model`):
324
- The [Keras model](`https://www.tensorflow.org/api_docs/python/tf/keras/Model`) you'd like to push to the
325
- Hub. The model must be compiled and built.
326
- repo_id (`str`):
327
- ID of the repository to push to (example: `"username/my-model"`).
328
- commit_message (`str`, *optional*, defaults to "Add Keras model"):
329
- Message to commit while pushing.
330
- private (`bool`, *optional*):
331
- Whether the repository created should be private.
332
- If `None` (default), the repo will be public unless the organization's default is private.
333
- api_endpoint (`str`, *optional*):
334
- The API endpoint to use when pushing the model to the hub.
335
- token (`str`, *optional*):
336
- The token to use as HTTP bearer authorization for remote files. If
337
- not set, will use the token set when logging in with
338
- `hf auth login` (stored in `~/.huggingface`).
339
- branch (`str`, *optional*):
340
- The git branch on which to push the model. This defaults to
341
- the default branch as specified in your repository, which
342
- defaults to `"main"`.
343
- create_pr (`boolean`, *optional*):
344
- Whether or not to create a Pull Request from `branch` with that commit.
345
- Defaults to `False`.
346
- config (`dict`, *optional*):
347
- Configuration object to be saved alongside the model weights.
348
- allow_patterns (`List[str]` or `str`, *optional*):
349
- If provided, only files matching at least one pattern are pushed.
350
- ignore_patterns (`List[str]` or `str`, *optional*):
351
- If provided, files matching any of the patterns are not pushed.
352
- delete_patterns (`List[str]` or `str`, *optional*):
353
- If provided, remote files matching any of the patterns will be deleted from the repo.
354
- log_dir (`str`, *optional*):
355
- TensorBoard logging directory to be pushed. The Hub automatically
356
- hosts and displays a TensorBoard instance if log files are included
357
- in the repository.
358
- include_optimizer (`bool`, *optional*, defaults to `False`):
359
- Whether or not to include optimizer during serialization.
360
- tags (Union[`list`, `str`], *optional*):
361
- List of tags that are related to model or string of a single tag. See example tags
362
- [here](https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1).
363
- plot_model (`bool`, *optional*, defaults to `True`):
364
- Setting this to `True` will plot the model and put it in the model
365
- card. Requires graphviz and pydot to be installed.
366
- model_save_kwargs(`dict`, *optional*):
367
- model_save_kwargs will be passed to
368
- [`tf.keras.models.save_model()`](https://www.tensorflow.org/api_docs/python/tf/keras/models/save_model).
369
-
370
- Returns:
371
- The url of the commit of your model in the given repository.
372
- """
373
- api = HfApi(endpoint=api_endpoint)
374
- repo_id = api.create_repo(repo_id=repo_id, token=token, private=private, exist_ok=True).repo_id
375
-
376
- # Push the files to the repo in a single commit
377
- with SoftTemporaryDirectory() as tmp:
378
- saved_path = Path(tmp) / repo_id
379
- save_pretrained_keras(
380
- model,
381
- saved_path,
382
- config=config,
383
- include_optimizer=include_optimizer,
384
- tags=tags,
385
- plot_model=plot_model,
386
- **model_save_kwargs,
387
- )
388
-
389
- # If `log_dir` provided, delete remote logs and upload new ones
390
- if log_dir is not None:
391
- delete_patterns = (
392
- []
393
- if delete_patterns is None
394
- else (
395
- [delete_patterns] # convert `delete_patterns` to a list
396
- if isinstance(delete_patterns, str)
397
- else delete_patterns
398
- )
399
- )
400
- delete_patterns.append("logs/*")
401
- copytree(log_dir, saved_path / "logs")
402
-
403
- return api.upload_folder(
404
- repo_type="model",
405
- repo_id=repo_id,
406
- folder_path=saved_path,
407
- commit_message=commit_message,
408
- token=token,
409
- revision=branch,
410
- create_pr=create_pr,
411
- allow_patterns=allow_patterns,
412
- ignore_patterns=ignore_patterns,
413
- delete_patterns=delete_patterns,
414
- )
415
-
416
-
417
- class KerasModelHubMixin(ModelHubMixin):
418
- """
419
- Implementation of [`ModelHubMixin`] to provide model Hub upload/download
420
- capabilities to Keras models.
421
-
422
-
423
- ```python
424
- >>> import tensorflow as tf
425
- >>> from huggingface_hub import KerasModelHubMixin
426
-
427
-
428
- >>> class MyModel(tf.keras.Model, KerasModelHubMixin):
429
- ... def __init__(self, **kwargs):
430
- ... super().__init__()
431
- ... self.config = kwargs.pop("config", None)
432
- ... self.dummy_inputs = ...
433
- ... self.layer = ...
434
-
435
- ... def call(self, *args):
436
- ... return ...
437
-
438
-
439
- >>> # Initialize and compile the model as you normally would
440
- >>> model = MyModel()
441
- >>> model.compile(...)
442
- >>> # Build the graph by training it or passing dummy inputs
443
- >>> _ = model(model.dummy_inputs)
444
- >>> # Save model weights to local directory
445
- >>> model.save_pretrained("my-awesome-model")
446
- >>> # Push model weights to the Hub
447
- >>> model.push_to_hub("my-awesome-model")
448
- >>> # Download and initialize weights from the Hub
449
- >>> model = MyModel.from_pretrained("username/super-cool-model")
450
- ```
451
- """
452
-
453
- def _save_pretrained(self, save_directory):
454
- save_pretrained_keras(self, save_directory)
455
-
456
- @classmethod
457
- def _from_pretrained(
458
- cls,
459
- model_id,
460
- revision,
461
- cache_dir,
462
- force_download,
463
- proxies,
464
- resume_download,
465
- local_files_only,
466
- token,
467
- config: Optional[Dict[str, Any]] = None,
468
- **model_kwargs,
469
- ):
470
- """Here we just call [`from_pretrained_keras`] function so both the mixin and
471
- functional APIs stay in sync.
472
-
473
- TODO - Some args above aren't used since we are calling
474
- snapshot_download instead of hf_hub_download.
475
- """
476
- if keras is None:
477
- raise ImportError("Called a TensorFlow-specific function but could not import it.")
478
-
479
- # Root is either a local filepath matching model_id or a cached snapshot
480
- if not os.path.isdir(model_id):
481
- storage_folder = snapshot_download(
482
- repo_id=model_id,
483
- revision=revision,
484
- cache_dir=cache_dir,
485
- library_name="keras",
486
- library_version=get_tf_version(),
487
- )
488
- else:
489
- storage_folder = model_id
490
-
491
- # TODO: change this in a future PR. We are not returning a KerasModelHubMixin instance here...
492
- model = keras.models.load_model(storage_folder)
493
-
494
- # For now, we add a new attribute, config, to store the config loaded from the hub/a local dir.
495
- model.config = config
496
-
497
- return model