huggingface-hub 0.34.4__py3-none-any.whl → 1.0.0rc0__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 (125) hide show
  1. huggingface_hub/__init__.py +46 -45
  2. huggingface_hub/_commit_api.py +28 -28
  3. huggingface_hub/_commit_scheduler.py +11 -8
  4. huggingface_hub/_inference_endpoints.py +8 -8
  5. huggingface_hub/_jobs_api.py +167 -10
  6. huggingface_hub/_login.py +13 -39
  7. huggingface_hub/_oauth.py +8 -8
  8. huggingface_hub/_snapshot_download.py +14 -28
  9. huggingface_hub/_space_api.py +4 -4
  10. huggingface_hub/_tensorboard_logger.py +13 -14
  11. huggingface_hub/_upload_large_folder.py +15 -15
  12. huggingface_hub/_webhooks_payload.py +3 -3
  13. huggingface_hub/_webhooks_server.py +2 -2
  14. huggingface_hub/cli/_cli_utils.py +2 -2
  15. huggingface_hub/cli/auth.py +5 -6
  16. huggingface_hub/cli/cache.py +14 -20
  17. huggingface_hub/cli/download.py +4 -4
  18. huggingface_hub/cli/jobs.py +560 -11
  19. huggingface_hub/cli/lfs.py +4 -4
  20. huggingface_hub/cli/repo.py +7 -7
  21. huggingface_hub/cli/repo_files.py +2 -2
  22. huggingface_hub/cli/upload.py +4 -4
  23. huggingface_hub/cli/upload_large_folder.py +3 -3
  24. huggingface_hub/commands/_cli_utils.py +2 -2
  25. huggingface_hub/commands/delete_cache.py +13 -13
  26. huggingface_hub/commands/download.py +4 -13
  27. huggingface_hub/commands/lfs.py +4 -4
  28. huggingface_hub/commands/repo_files.py +2 -2
  29. huggingface_hub/commands/scan_cache.py +1 -1
  30. huggingface_hub/commands/tag.py +1 -3
  31. huggingface_hub/commands/upload.py +4 -4
  32. huggingface_hub/commands/upload_large_folder.py +3 -3
  33. huggingface_hub/commands/user.py +5 -6
  34. huggingface_hub/community.py +5 -5
  35. huggingface_hub/constants.py +3 -41
  36. huggingface_hub/dataclasses.py +16 -19
  37. huggingface_hub/errors.py +42 -29
  38. huggingface_hub/fastai_utils.py +8 -9
  39. huggingface_hub/file_download.py +153 -252
  40. huggingface_hub/hf_api.py +815 -600
  41. huggingface_hub/hf_file_system.py +98 -62
  42. huggingface_hub/hub_mixin.py +37 -57
  43. huggingface_hub/inference/_client.py +177 -325
  44. huggingface_hub/inference/_common.py +110 -124
  45. huggingface_hub/inference/_generated/_async_client.py +226 -432
  46. huggingface_hub/inference/_generated/types/automatic_speech_recognition.py +3 -3
  47. huggingface_hub/inference/_generated/types/base.py +10 -7
  48. huggingface_hub/inference/_generated/types/chat_completion.py +18 -16
  49. huggingface_hub/inference/_generated/types/depth_estimation.py +2 -2
  50. huggingface_hub/inference/_generated/types/document_question_answering.py +2 -2
  51. huggingface_hub/inference/_generated/types/feature_extraction.py +2 -2
  52. huggingface_hub/inference/_generated/types/fill_mask.py +2 -2
  53. huggingface_hub/inference/_generated/types/sentence_similarity.py +3 -3
  54. huggingface_hub/inference/_generated/types/summarization.py +2 -2
  55. huggingface_hub/inference/_generated/types/table_question_answering.py +4 -4
  56. huggingface_hub/inference/_generated/types/text2text_generation.py +2 -2
  57. huggingface_hub/inference/_generated/types/text_generation.py +10 -10
  58. huggingface_hub/inference/_generated/types/text_to_video.py +2 -2
  59. huggingface_hub/inference/_generated/types/token_classification.py +2 -2
  60. huggingface_hub/inference/_generated/types/translation.py +2 -2
  61. huggingface_hub/inference/_generated/types/zero_shot_classification.py +2 -2
  62. huggingface_hub/inference/_generated/types/zero_shot_image_classification.py +2 -2
  63. huggingface_hub/inference/_generated/types/zero_shot_object_detection.py +1 -3
  64. huggingface_hub/inference/_mcp/_cli_hacks.py +3 -3
  65. huggingface_hub/inference/_mcp/agent.py +3 -3
  66. huggingface_hub/inference/_mcp/cli.py +1 -1
  67. huggingface_hub/inference/_mcp/constants.py +2 -3
  68. huggingface_hub/inference/_mcp/mcp_client.py +58 -30
  69. huggingface_hub/inference/_mcp/types.py +10 -7
  70. huggingface_hub/inference/_mcp/utils.py +11 -7
  71. huggingface_hub/inference/_providers/__init__.py +2 -2
  72. huggingface_hub/inference/_providers/_common.py +49 -25
  73. huggingface_hub/inference/_providers/black_forest_labs.py +6 -6
  74. huggingface_hub/inference/_providers/cohere.py +3 -3
  75. huggingface_hub/inference/_providers/fal_ai.py +25 -25
  76. huggingface_hub/inference/_providers/featherless_ai.py +4 -4
  77. huggingface_hub/inference/_providers/fireworks_ai.py +3 -3
  78. huggingface_hub/inference/_providers/hf_inference.py +28 -20
  79. huggingface_hub/inference/_providers/hyperbolic.py +4 -4
  80. huggingface_hub/inference/_providers/nebius.py +10 -10
  81. huggingface_hub/inference/_providers/novita.py +5 -5
  82. huggingface_hub/inference/_providers/nscale.py +4 -4
  83. huggingface_hub/inference/_providers/replicate.py +15 -15
  84. huggingface_hub/inference/_providers/sambanova.py +6 -6
  85. huggingface_hub/inference/_providers/together.py +7 -7
  86. huggingface_hub/lfs.py +20 -31
  87. huggingface_hub/repocard.py +18 -18
  88. huggingface_hub/repocard_data.py +56 -56
  89. huggingface_hub/serialization/__init__.py +0 -1
  90. huggingface_hub/serialization/_base.py +9 -9
  91. huggingface_hub/serialization/_dduf.py +7 -7
  92. huggingface_hub/serialization/_torch.py +28 -28
  93. huggingface_hub/utils/__init__.py +10 -4
  94. huggingface_hub/utils/_auth.py +5 -5
  95. huggingface_hub/utils/_cache_manager.py +31 -31
  96. huggingface_hub/utils/_deprecation.py +1 -1
  97. huggingface_hub/utils/_dotenv.py +3 -3
  98. huggingface_hub/utils/_fixes.py +0 -10
  99. huggingface_hub/utils/_git_credential.py +4 -4
  100. huggingface_hub/utils/_headers.py +7 -29
  101. huggingface_hub/utils/_http.py +366 -208
  102. huggingface_hub/utils/_pagination.py +4 -4
  103. huggingface_hub/utils/_paths.py +5 -5
  104. huggingface_hub/utils/_runtime.py +15 -13
  105. huggingface_hub/utils/_safetensors.py +21 -21
  106. huggingface_hub/utils/_subprocess.py +9 -9
  107. huggingface_hub/utils/_telemetry.py +3 -3
  108. huggingface_hub/utils/_typing.py +25 -5
  109. huggingface_hub/utils/_validators.py +53 -72
  110. huggingface_hub/utils/_xet.py +16 -16
  111. huggingface_hub/utils/_xet_progress_reporting.py +32 -11
  112. huggingface_hub/utils/insecure_hashlib.py +3 -9
  113. huggingface_hub/utils/tqdm.py +3 -3
  114. {huggingface_hub-0.34.4.dist-info → huggingface_hub-1.0.0rc0.dist-info}/METADATA +18 -29
  115. huggingface_hub-1.0.0rc0.dist-info/RECORD +161 -0
  116. huggingface_hub/inference_api.py +0 -217
  117. huggingface_hub/keras_mixin.py +0 -500
  118. huggingface_hub/repository.py +0 -1477
  119. huggingface_hub/serialization/_tensorflow.py +0 -95
  120. huggingface_hub/utils/_hf_folder.py +0 -68
  121. huggingface_hub-0.34.4.dist-info/RECORD +0 -166
  122. {huggingface_hub-0.34.4.dist-info → huggingface_hub-1.0.0rc0.dist-info}/LICENSE +0 -0
  123. {huggingface_hub-0.34.4.dist-info → huggingface_hub-1.0.0rc0.dist-info}/WHEEL +0 -0
  124. {huggingface_hub-0.34.4.dist-info → huggingface_hub-1.0.0rc0.dist-info}/entry_points.txt +0 -0
  125. {huggingface_hub-0.34.4.dist-info → huggingface_hub-1.0.0rc0.dist-info}/top_level.txt +0 -0
@@ -1,500 +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
-
288
- Passing `token=True` is required when you want to use a private
289
- model.
290
-
291
- </Tip>
292
- """
293
- return KerasModelHubMixin.from_pretrained(*args, **kwargs)
294
-
295
-
296
- @validate_hf_hub_args
297
- @_requires_keras_2_model
298
- def push_to_hub_keras(
299
- model,
300
- repo_id: str,
301
- *,
302
- config: Optional[dict] = None,
303
- commit_message: str = "Push Keras model using huggingface_hub.",
304
- private: Optional[bool] = None,
305
- api_endpoint: Optional[str] = None,
306
- token: Optional[str] = None,
307
- branch: Optional[str] = None,
308
- create_pr: Optional[bool] = None,
309
- allow_patterns: Optional[Union[List[str], str]] = None,
310
- ignore_patterns: Optional[Union[List[str], str]] = None,
311
- delete_patterns: Optional[Union[List[str], str]] = None,
312
- log_dir: Optional[str] = None,
313
- include_optimizer: bool = False,
314
- tags: Optional[Union[list, str]] = None,
315
- plot_model: bool = True,
316
- **model_save_kwargs,
317
- ):
318
- """
319
- Upload model checkpoint to the Hub.
320
-
321
- Use `allow_patterns` and `ignore_patterns` to precisely filter which files should be pushed to the hub. Use
322
- `delete_patterns` to delete existing remote files in the same commit. See [`upload_folder`] reference for more
323
- details.
324
-
325
- Args:
326
- model (`Keras.Model`):
327
- The [Keras model](`https://www.tensorflow.org/api_docs/python/tf/keras/Model`) you'd like to push to the
328
- Hub. The model must be compiled and built.
329
- repo_id (`str`):
330
- ID of the repository to push to (example: `"username/my-model"`).
331
- commit_message (`str`, *optional*, defaults to "Add Keras model"):
332
- Message to commit while pushing.
333
- private (`bool`, *optional*):
334
- Whether the repository created should be private.
335
- If `None` (default), the repo will be public unless the organization's default is private.
336
- api_endpoint (`str`, *optional*):
337
- The API endpoint to use when pushing the model to the hub.
338
- token (`str`, *optional*):
339
- The token to use as HTTP bearer authorization for remote files. If
340
- not set, will use the token set when logging in with
341
- `hf auth login` (stored in `~/.huggingface`).
342
- branch (`str`, *optional*):
343
- The git branch on which to push the model. This defaults to
344
- the default branch as specified in your repository, which
345
- defaults to `"main"`.
346
- create_pr (`boolean`, *optional*):
347
- Whether or not to create a Pull Request from `branch` with that commit.
348
- Defaults to `False`.
349
- config (`dict`, *optional*):
350
- Configuration object to be saved alongside the model weights.
351
- allow_patterns (`List[str]` or `str`, *optional*):
352
- If provided, only files matching at least one pattern are pushed.
353
- ignore_patterns (`List[str]` or `str`, *optional*):
354
- If provided, files matching any of the patterns are not pushed.
355
- delete_patterns (`List[str]` or `str`, *optional*):
356
- If provided, remote files matching any of the patterns will be deleted from the repo.
357
- log_dir (`str`, *optional*):
358
- TensorBoard logging directory to be pushed. The Hub automatically
359
- hosts and displays a TensorBoard instance if log files are included
360
- in the repository.
361
- include_optimizer (`bool`, *optional*, defaults to `False`):
362
- Whether or not to include optimizer during serialization.
363
- tags (Union[`list`, `str`], *optional*):
364
- List of tags that are related to model or string of a single tag. See example tags
365
- [here](https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1).
366
- plot_model (`bool`, *optional*, defaults to `True`):
367
- Setting this to `True` will plot the model and put it in the model
368
- card. Requires graphviz and pydot to be installed.
369
- model_save_kwargs(`dict`, *optional*):
370
- model_save_kwargs will be passed to
371
- [`tf.keras.models.save_model()`](https://www.tensorflow.org/api_docs/python/tf/keras/models/save_model).
372
-
373
- Returns:
374
- The url of the commit of your model in the given repository.
375
- """
376
- api = HfApi(endpoint=api_endpoint)
377
- repo_id = api.create_repo(repo_id=repo_id, token=token, private=private, exist_ok=True).repo_id
378
-
379
- # Push the files to the repo in a single commit
380
- with SoftTemporaryDirectory() as tmp:
381
- saved_path = Path(tmp) / repo_id
382
- save_pretrained_keras(
383
- model,
384
- saved_path,
385
- config=config,
386
- include_optimizer=include_optimizer,
387
- tags=tags,
388
- plot_model=plot_model,
389
- **model_save_kwargs,
390
- )
391
-
392
- # If `log_dir` provided, delete remote logs and upload new ones
393
- if log_dir is not None:
394
- delete_patterns = (
395
- []
396
- if delete_patterns is None
397
- else (
398
- [delete_patterns] # convert `delete_patterns` to a list
399
- if isinstance(delete_patterns, str)
400
- else delete_patterns
401
- )
402
- )
403
- delete_patterns.append("logs/*")
404
- copytree(log_dir, saved_path / "logs")
405
-
406
- return api.upload_folder(
407
- repo_type="model",
408
- repo_id=repo_id,
409
- folder_path=saved_path,
410
- commit_message=commit_message,
411
- token=token,
412
- revision=branch,
413
- create_pr=create_pr,
414
- allow_patterns=allow_patterns,
415
- ignore_patterns=ignore_patterns,
416
- delete_patterns=delete_patterns,
417
- )
418
-
419
-
420
- class KerasModelHubMixin(ModelHubMixin):
421
- """
422
- Implementation of [`ModelHubMixin`] to provide model Hub upload/download
423
- capabilities to Keras models.
424
-
425
-
426
- ```python
427
- >>> import tensorflow as tf
428
- >>> from huggingface_hub import KerasModelHubMixin
429
-
430
-
431
- >>> class MyModel(tf.keras.Model, KerasModelHubMixin):
432
- ... def __init__(self, **kwargs):
433
- ... super().__init__()
434
- ... self.config = kwargs.pop("config", None)
435
- ... self.dummy_inputs = ...
436
- ... self.layer = ...
437
-
438
- ... def call(self, *args):
439
- ... return ...
440
-
441
-
442
- >>> # Initialize and compile the model as you normally would
443
- >>> model = MyModel()
444
- >>> model.compile(...)
445
- >>> # Build the graph by training it or passing dummy inputs
446
- >>> _ = model(model.dummy_inputs)
447
- >>> # Save model weights to local directory
448
- >>> model.save_pretrained("my-awesome-model")
449
- >>> # Push model weights to the Hub
450
- >>> model.push_to_hub("my-awesome-model")
451
- >>> # Download and initialize weights from the Hub
452
- >>> model = MyModel.from_pretrained("username/super-cool-model")
453
- ```
454
- """
455
-
456
- def _save_pretrained(self, save_directory):
457
- save_pretrained_keras(self, save_directory)
458
-
459
- @classmethod
460
- def _from_pretrained(
461
- cls,
462
- model_id,
463
- revision,
464
- cache_dir,
465
- force_download,
466
- proxies,
467
- resume_download,
468
- local_files_only,
469
- token,
470
- config: Optional[Dict[str, Any]] = None,
471
- **model_kwargs,
472
- ):
473
- """Here we just call [`from_pretrained_keras`] function so both the mixin and
474
- functional APIs stay in sync.
475
-
476
- TODO - Some args above aren't used since we are calling
477
- snapshot_download instead of hf_hub_download.
478
- """
479
- if keras is None:
480
- raise ImportError("Called a TensorFlow-specific function but could not import it.")
481
-
482
- # Root is either a local filepath matching model_id or a cached snapshot
483
- if not os.path.isdir(model_id):
484
- storage_folder = snapshot_download(
485
- repo_id=model_id,
486
- revision=revision,
487
- cache_dir=cache_dir,
488
- library_name="keras",
489
- library_version=get_tf_version(),
490
- )
491
- else:
492
- storage_folder = model_id
493
-
494
- # TODO: change this in a future PR. We are not returning a KerasModelHubMixin instance here...
495
- model = keras.models.load_model(storage_folder)
496
-
497
- # For now, we add a new attribute, config, to store the config loaded from the hub/a local dir.
498
- model.config = config
499
-
500
- return model