huggingface-hub 0.36.0__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.0.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.0.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.0.dist-info/RECORD +0 -170
  130. {huggingface_hub-0.36.0.dist-info → huggingface_hub-1.0.0.dist-info}/LICENSE +0 -0
  131. {huggingface_hub-0.36.0.dist-info → huggingface_hub-1.0.0.dist-info}/WHEEL +0 -0
  132. {huggingface_hub-0.36.0.dist-info → huggingface_hub-1.0.0.dist-info}/top_level.txt +0 -0
@@ -1,1471 +0,0 @@
1
- import atexit
2
- import os
3
- import re
4
- import subprocess
5
- import threading
6
- import time
7
- from contextlib import contextmanager
8
- from pathlib import Path
9
- from typing import Callable, Dict, Iterator, List, Optional, Tuple, TypedDict, Union
10
- from urllib.parse import urlparse
11
-
12
- from huggingface_hub import constants
13
- from huggingface_hub.repocard import metadata_load, metadata_save
14
-
15
- from .hf_api import HfApi, repo_type_and_id_from_hf_id
16
- from .lfs import LFS_MULTIPART_UPLOAD_COMMAND
17
- from .utils import (
18
- SoftTemporaryDirectory,
19
- get_token,
20
- logging,
21
- run_subprocess,
22
- tqdm,
23
- validate_hf_hub_args,
24
- )
25
- from .utils._deprecation import _deprecate_method
26
-
27
-
28
- logger = logging.get_logger(__name__)
29
-
30
-
31
- class CommandInProgress:
32
- """
33
- Utility to follow commands launched asynchronously.
34
- """
35
-
36
- def __init__(
37
- self,
38
- title: str,
39
- is_done_method: Callable,
40
- status_method: Callable,
41
- process: subprocess.Popen,
42
- post_method: Optional[Callable] = None,
43
- ):
44
- self.title = title
45
- self._is_done = is_done_method
46
- self._status = status_method
47
- self._process = process
48
- self._stderr = ""
49
- self._stdout = ""
50
- self._post_method = post_method
51
-
52
- @property
53
- def is_done(self) -> bool:
54
- """
55
- Whether the process is done.
56
- """
57
- result = self._is_done()
58
-
59
- if result and self._post_method is not None:
60
- self._post_method()
61
- self._post_method = None
62
-
63
- return result
64
-
65
- @property
66
- def status(self) -> int:
67
- """
68
- The exit code/status of the current action. Will return `0` if the
69
- command has completed successfully, and a number between 1 and 255 if
70
- the process errored-out.
71
-
72
- Will return -1 if the command is still ongoing.
73
- """
74
- return self._status()
75
-
76
- @property
77
- def failed(self) -> bool:
78
- """
79
- Whether the process errored-out.
80
- """
81
- return self.status > 0
82
-
83
- @property
84
- def stderr(self) -> str:
85
- """
86
- The current output message on the standard error.
87
- """
88
- if self._process.stderr is not None:
89
- self._stderr += self._process.stderr.read()
90
- return self._stderr
91
-
92
- @property
93
- def stdout(self) -> str:
94
- """
95
- The current output message on the standard output.
96
- """
97
- if self._process.stdout is not None:
98
- self._stdout += self._process.stdout.read()
99
- return self._stdout
100
-
101
- def __repr__(self):
102
- status = self.status
103
-
104
- if status == -1:
105
- status = "running"
106
-
107
- return (
108
- f"[{self.title} command, status code: {status},"
109
- f" {'in progress.' if not self.is_done else 'finished.'} PID:"
110
- f" {self._process.pid}]"
111
- )
112
-
113
-
114
- def is_git_repo(folder: Union[str, Path]) -> bool:
115
- """
116
- Check if the folder is the root or part of a git repository
117
-
118
- Args:
119
- folder (`str`):
120
- The folder in which to run the command.
121
-
122
- Returns:
123
- `bool`: `True` if the repository is part of a repository, `False`
124
- otherwise.
125
- """
126
- folder_exists = os.path.exists(os.path.join(folder, ".git"))
127
- git_branch = subprocess.run("git branch".split(), cwd=folder, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
128
- return folder_exists and git_branch.returncode == 0
129
-
130
-
131
- def is_local_clone(folder: Union[str, Path], remote_url: str) -> bool:
132
- """
133
- Check if the folder is a local clone of the remote_url
134
-
135
- Args:
136
- folder (`str` or `Path`):
137
- The folder in which to run the command.
138
- remote_url (`str`):
139
- The url of a git repository.
140
-
141
- Returns:
142
- `bool`: `True` if the repository is a local clone of the remote
143
- repository specified, `False` otherwise.
144
- """
145
- if not is_git_repo(folder):
146
- return False
147
-
148
- remotes = run_subprocess("git remote -v", folder).stdout
149
-
150
- # Remove token for the test with remotes.
151
- remote_url = re.sub(r"https://.*@", "https://", remote_url)
152
- remotes = [re.sub(r"https://.*@", "https://", remote) for remote in remotes.split()]
153
- return remote_url in remotes
154
-
155
-
156
- def is_tracked_with_lfs(filename: Union[str, Path]) -> bool:
157
- """
158
- Check if the file passed is tracked with git-lfs.
159
-
160
- Args:
161
- filename (`str` or `Path`):
162
- The filename to check.
163
-
164
- Returns:
165
- `bool`: `True` if the file passed is tracked with git-lfs, `False`
166
- otherwise.
167
- """
168
- folder = Path(filename).parent
169
- filename = Path(filename).name
170
-
171
- try:
172
- p = run_subprocess("git check-attr -a".split() + [filename], folder)
173
- attributes = p.stdout.strip()
174
- except subprocess.CalledProcessError as exc:
175
- if not is_git_repo(folder):
176
- return False
177
- else:
178
- raise OSError(exc.stderr)
179
-
180
- if len(attributes) == 0:
181
- return False
182
-
183
- found_lfs_tag = {"diff": False, "merge": False, "filter": False}
184
-
185
- for attribute in attributes.split("\n"):
186
- for tag in found_lfs_tag.keys():
187
- if tag in attribute and "lfs" in attribute:
188
- found_lfs_tag[tag] = True
189
-
190
- return all(found_lfs_tag.values())
191
-
192
-
193
- def is_git_ignored(filename: Union[str, Path]) -> bool:
194
- """
195
- Check if file is git-ignored. Supports nested .gitignore files.
196
-
197
- Args:
198
- filename (`str` or `Path`):
199
- The filename to check.
200
-
201
- Returns:
202
- `bool`: `True` if the file passed is ignored by `git`, `False`
203
- otherwise.
204
- """
205
- folder = Path(filename).parent
206
- filename = Path(filename).name
207
-
208
- try:
209
- p = run_subprocess("git check-ignore".split() + [filename], folder, check=False)
210
- # Will return exit code 1 if not gitignored
211
- is_ignored = not bool(p.returncode)
212
- except subprocess.CalledProcessError as exc:
213
- raise OSError(exc.stderr)
214
-
215
- return is_ignored
216
-
217
-
218
- def is_binary_file(filename: Union[str, Path]) -> bool:
219
- """
220
- Check if file is a binary file.
221
-
222
- Args:
223
- filename (`str` or `Path`):
224
- The filename to check.
225
-
226
- Returns:
227
- `bool`: `True` if the file passed is a binary file, `False` otherwise.
228
- """
229
- try:
230
- with open(filename, "rb") as f:
231
- content = f.read(10 * (1024**2)) # Read a maximum of 10MB
232
-
233
- # Code sample taken from the following stack overflow thread
234
- # https://stackoverflow.com/questions/898669/how-can-i-detect-if-a-file-is-binary-non-text-in-python/7392391#7392391
235
- text_chars = bytearray({7, 8, 9, 10, 12, 13, 27} | set(range(0x20, 0x100)) - {0x7F})
236
- return bool(content.translate(None, text_chars))
237
- except UnicodeDecodeError:
238
- return True
239
-
240
-
241
- def files_to_be_staged(pattern: str = ".", folder: Union[str, Path, None] = None) -> List[str]:
242
- """
243
- Returns a list of filenames that are to be staged.
244
-
245
- Args:
246
- pattern (`str` or `Path`):
247
- The pattern of filenames to check. Put `.` to get all files.
248
- folder (`str` or `Path`):
249
- The folder in which to run the command.
250
-
251
- Returns:
252
- `List[str]`: List of files that are to be staged.
253
- """
254
- try:
255
- p = run_subprocess("git ls-files --exclude-standard -mo".split() + [pattern], folder)
256
- if len(p.stdout.strip()):
257
- files = p.stdout.strip().split("\n")
258
- else:
259
- files = []
260
- except subprocess.CalledProcessError as exc:
261
- raise EnvironmentError(exc.stderr)
262
-
263
- return files
264
-
265
-
266
- def is_tracked_upstream(folder: Union[str, Path]) -> bool:
267
- """
268
- Check if the current checked-out branch is tracked upstream.
269
-
270
- Args:
271
- folder (`str` or `Path`):
272
- The folder in which to run the command.
273
-
274
- Returns:
275
- `bool`: `True` if the current checked-out branch is tracked upstream,
276
- `False` otherwise.
277
- """
278
- try:
279
- run_subprocess("git rev-parse --symbolic-full-name --abbrev-ref @{u}", folder)
280
- return True
281
- except subprocess.CalledProcessError as exc:
282
- if "HEAD" in exc.stderr:
283
- raise OSError("No branch checked out")
284
-
285
- return False
286
-
287
-
288
- def commits_to_push(folder: Union[str, Path], upstream: Optional[str] = None) -> int:
289
- """
290
- Check the number of commits that would be pushed upstream
291
-
292
- Args:
293
- folder (`str` or `Path`):
294
- The folder in which to run the command.
295
- upstream (`str`, *optional*):
296
- The name of the upstream repository with which the comparison should be
297
- made.
298
-
299
- Returns:
300
- `int`: Number of commits that would be pushed upstream were a `git
301
- push` to proceed.
302
- """
303
- try:
304
- result = run_subprocess(f"git cherry -v {upstream or ''}", folder)
305
- return len(result.stdout.split("\n")) - 1
306
- except subprocess.CalledProcessError as exc:
307
- raise EnvironmentError(exc.stderr)
308
-
309
-
310
- class PbarT(TypedDict):
311
- # Used to store an opened progress bar in `_lfs_log_progress`
312
- bar: tqdm
313
- past_bytes: int
314
-
315
-
316
- @contextmanager
317
- def _lfs_log_progress():
318
- """
319
- This is a context manager that will log the Git LFS progress of cleaning,
320
- smudging, pulling and pushing.
321
- """
322
-
323
- if logger.getEffectiveLevel() >= logging.ERROR:
324
- try:
325
- yield
326
- except Exception:
327
- pass
328
- return
329
-
330
- def output_progress(stopping_event: threading.Event):
331
- """
332
- To be launched as a separate thread with an event meaning it should stop
333
- the tail.
334
- """
335
- # Key is tuple(state, filename), value is a dict(tqdm bar and a previous value)
336
- pbars: Dict[Tuple[str, str], PbarT] = {}
337
-
338
- def close_pbars():
339
- for pbar in pbars.values():
340
- pbar["bar"].update(pbar["bar"].total - pbar["past_bytes"])
341
- pbar["bar"].refresh()
342
- pbar["bar"].close()
343
-
344
- def tail_file(filename) -> Iterator[str]:
345
- """
346
- Creates a generator to be iterated through, which will return each
347
- line one by one. Will stop tailing the file if the stopping_event is
348
- set.
349
- """
350
- with open(filename, "r") as file:
351
- current_line = ""
352
- while True:
353
- if stopping_event.is_set():
354
- close_pbars()
355
- break
356
-
357
- line_bit = file.readline()
358
- if line_bit is not None and not len(line_bit.strip()) == 0:
359
- current_line += line_bit
360
- if current_line.endswith("\n"):
361
- yield current_line
362
- current_line = ""
363
- else:
364
- time.sleep(1)
365
-
366
- # If the file isn't created yet, wait for a few seconds before trying again.
367
- # Can be interrupted with the stopping_event.
368
- while not os.path.exists(os.environ["GIT_LFS_PROGRESS"]):
369
- if stopping_event.is_set():
370
- close_pbars()
371
- return
372
-
373
- time.sleep(2)
374
-
375
- for line in tail_file(os.environ["GIT_LFS_PROGRESS"]):
376
- try:
377
- state, file_progress, byte_progress, filename = line.split()
378
- except ValueError as error:
379
- # Try/except to ease debugging. See https://github.com/huggingface/huggingface_hub/issues/1373.
380
- raise ValueError(f"Cannot unpack LFS progress line:\n{line}") from error
381
- description = f"{state.capitalize()} file {filename}"
382
-
383
- current_bytes, total_bytes = byte_progress.split("/")
384
- current_bytes_int = int(current_bytes)
385
- total_bytes_int = int(total_bytes)
386
-
387
- pbar = pbars.get((state, filename))
388
- if pbar is None:
389
- # Initialize progress bar
390
- pbars[(state, filename)] = {
391
- "bar": tqdm(
392
- desc=description,
393
- initial=current_bytes_int,
394
- total=total_bytes_int,
395
- unit="B",
396
- unit_scale=True,
397
- unit_divisor=1024,
398
- name="huggingface_hub.lfs_upload",
399
- ),
400
- "past_bytes": int(current_bytes),
401
- }
402
- else:
403
- # Update progress bar
404
- pbar["bar"].update(current_bytes_int - pbar["past_bytes"])
405
- pbar["past_bytes"] = current_bytes_int
406
-
407
- current_lfs_progress_value = os.environ.get("GIT_LFS_PROGRESS", "")
408
-
409
- with SoftTemporaryDirectory() as tmpdir:
410
- os.environ["GIT_LFS_PROGRESS"] = os.path.join(tmpdir, "lfs_progress")
411
- logger.debug(f"Following progress in {os.environ['GIT_LFS_PROGRESS']}")
412
-
413
- exit_event = threading.Event()
414
- x = threading.Thread(target=output_progress, args=(exit_event,), daemon=True)
415
- x.start()
416
-
417
- try:
418
- yield
419
- finally:
420
- exit_event.set()
421
- x.join()
422
-
423
- os.environ["GIT_LFS_PROGRESS"] = current_lfs_progress_value
424
-
425
-
426
- class Repository:
427
- """
428
- Helper class to wrap the git and git-lfs commands.
429
-
430
- The aim is to facilitate interacting with huggingface.co hosted model or
431
- dataset repos, though not a lot here (if any) is actually specific to
432
- huggingface.co.
433
-
434
- > [!WARNING]
435
- > [`Repository`] is deprecated in favor of the http-based alternatives implemented in
436
- > [`HfApi`]. Given its large adoption in legacy code, the complete removal of
437
- > [`Repository`] will only happen in release `v1.0`. For more details, please read
438
- > https://huggingface.co/docs/huggingface_hub/concepts/git_vs_http.
439
- """
440
-
441
- command_queue: List[CommandInProgress]
442
-
443
- @validate_hf_hub_args
444
- @_deprecate_method(
445
- version="1.0",
446
- message=(
447
- "Please prefer the http-based alternatives instead. Given its large adoption in legacy code, the complete"
448
- " removal is only planned on next major release.\nFor more details, please read"
449
- " https://huggingface.co/docs/huggingface_hub/concepts/git_vs_http."
450
- ),
451
- )
452
- def __init__(
453
- self,
454
- local_dir: Union[str, Path],
455
- clone_from: Optional[str] = None,
456
- repo_type: Optional[str] = None,
457
- token: Union[bool, str] = True,
458
- git_user: Optional[str] = None,
459
- git_email: Optional[str] = None,
460
- revision: Optional[str] = None,
461
- skip_lfs_files: bool = False,
462
- client: Optional[HfApi] = None,
463
- ):
464
- """
465
- Instantiate a local clone of a git repo.
466
-
467
- If `clone_from` is set, the repo will be cloned from an existing remote repository.
468
- If the remote repo does not exist, a `EnvironmentError` exception will be thrown.
469
- Please create the remote repo first using [`create_repo`].
470
-
471
- `Repository` uses the local git credentials by default. If explicitly set, the `token`
472
- or the `git_user`/`git_email` pair will be used instead.
473
-
474
- Args:
475
- local_dir (`str` or `Path`):
476
- path (e.g. `'my_trained_model/'`) to the local directory, where
477
- the `Repository` will be initialized.
478
- clone_from (`str`, *optional*):
479
- Either a repository url or `repo_id`.
480
- Example:
481
- - `"https://huggingface.co/philschmid/playground-tests"`
482
- - `"philschmid/playground-tests"`
483
- repo_type (`str`, *optional*):
484
- To set when cloning a repo from a repo_id. Default is model.
485
- token (`bool` or `str`, *optional*):
486
- A valid authentication token (see https://huggingface.co/settings/token).
487
- If `None` or `True` and machine is logged in (through `hf auth login`
488
- or [`~huggingface_hub.login`]), token will be retrieved from the cache.
489
- If `False`, token is not sent in the request header.
490
- git_user (`str`, *optional*):
491
- will override the `git config user.name` for committing and
492
- pushing files to the hub.
493
- git_email (`str`, *optional*):
494
- will override the `git config user.email` for committing and
495
- pushing files to the hub.
496
- revision (`str`, *optional*):
497
- Revision to checkout after initializing the repository. If the
498
- revision doesn't exist, a branch will be created with that
499
- revision name from the default branch's current HEAD.
500
- skip_lfs_files (`bool`, *optional*, defaults to `False`):
501
- whether to skip git-LFS files or not.
502
- client (`HfApi`, *optional*):
503
- Instance of [`HfApi`] to use when calling the HF Hub API. A new
504
- instance will be created if this is left to `None`.
505
-
506
- Raises:
507
- [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
508
- If the remote repository set in `clone_from` does not exist.
509
- """
510
- if isinstance(local_dir, Path):
511
- local_dir = str(local_dir)
512
- os.makedirs(local_dir, exist_ok=True)
513
- self.local_dir = os.path.join(os.getcwd(), local_dir)
514
- self._repo_type = repo_type
515
- self.command_queue = []
516
- self.skip_lfs_files = skip_lfs_files
517
- self.client = client if client is not None else HfApi()
518
-
519
- self.check_git_versions()
520
-
521
- if isinstance(token, str):
522
- self.huggingface_token: Optional[str] = token
523
- elif token is False:
524
- self.huggingface_token = None
525
- else:
526
- # if `True` -> explicit use of the cached token
527
- # if `None` -> implicit use of the cached token
528
- self.huggingface_token = get_token()
529
-
530
- if clone_from is not None:
531
- self.clone_from(repo_url=clone_from)
532
- else:
533
- if is_git_repo(self.local_dir):
534
- logger.debug("[Repository] is a valid git repo")
535
- else:
536
- raise ValueError("If not specifying `clone_from`, you need to pass Repository a valid git clone.")
537
-
538
- if self.huggingface_token is not None and (git_email is None or git_user is None):
539
- user = self.client.whoami(self.huggingface_token)
540
-
541
- if git_email is None:
542
- git_email = user.get("email")
543
-
544
- if git_user is None:
545
- git_user = user.get("fullname")
546
-
547
- if git_user is not None or git_email is not None:
548
- self.git_config_username_and_email(git_user, git_email)
549
-
550
- self.lfs_enable_largefiles()
551
- self.git_credential_helper_store()
552
-
553
- if revision is not None:
554
- self.git_checkout(revision, create_branch_ok=True)
555
-
556
- # This ensures that all commands exit before exiting the Python runtime.
557
- # This will ensure all pushes register on the hub, even if other errors happen in subsequent operations.
558
- atexit.register(self.wait_for_commands)
559
-
560
- @property
561
- def current_branch(self) -> str:
562
- """
563
- Returns the current checked out branch.
564
-
565
- Returns:
566
- `str`: Current checked out branch.
567
- """
568
- try:
569
- result = run_subprocess("git rev-parse --abbrev-ref HEAD", self.local_dir).stdout.strip()
570
- except subprocess.CalledProcessError as exc:
571
- raise EnvironmentError(exc.stderr)
572
-
573
- return result
574
-
575
- def check_git_versions(self):
576
- """
577
- Checks that `git` and `git-lfs` can be run.
578
-
579
- Raises:
580
- [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
581
- If `git` or `git-lfs` are not installed.
582
- """
583
- try:
584
- git_version = run_subprocess("git --version", self.local_dir).stdout.strip()
585
- except FileNotFoundError:
586
- raise EnvironmentError("Looks like you do not have git installed, please install.")
587
-
588
- try:
589
- lfs_version = run_subprocess("git-lfs --version", self.local_dir).stdout.strip()
590
- except FileNotFoundError:
591
- raise EnvironmentError(
592
- "Looks like you do not have git-lfs installed, please install."
593
- " You can install from https://git-lfs.github.com/."
594
- " Then run `git lfs install` (you only have to do this once)."
595
- )
596
- logger.info(git_version + "\n" + lfs_version)
597
-
598
- @validate_hf_hub_args
599
- def clone_from(self, repo_url: str, token: Union[bool, str, None] = None):
600
- """
601
- Clone from a remote. If the folder already exists, will try to clone the
602
- repository within it.
603
-
604
- If this folder is a git repository with linked history, will try to
605
- update the repository.
606
-
607
- Args:
608
- repo_url (`str`):
609
- The URL from which to clone the repository
610
- token (`Union[str, bool]`, *optional*):
611
- Whether to use the authentication token. It can be:
612
- - a string which is the token itself
613
- - `False`, which would not use the authentication token
614
- - `True`, which would fetch the authentication token from the
615
- local folder and use it (you should be logged in for this to
616
- work).
617
- - `None`, which would retrieve the value of
618
- `self.huggingface_token`.
619
-
620
- > [!TIP]
621
- > Raises the following error:
622
- >
623
- > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
624
- > if an organization token (starts with "api_org") is passed. Use must use
625
- > your own personal access token (see https://hf.co/settings/tokens).
626
- >
627
- > - [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
628
- > if you are trying to clone the repository in a non-empty folder, or if the
629
- > `git` operations raise errors.
630
- """
631
- token = (
632
- token # str -> use it
633
- if isinstance(token, str)
634
- else (
635
- None # `False` -> explicit no token
636
- if token is False
637
- else self.huggingface_token # `None` or `True` -> use default
638
- )
639
- )
640
- if token is not None and token.startswith("api_org"):
641
- raise ValueError(
642
- "You must use your personal access token, not an Organization token"
643
- " (see https://hf.co/settings/tokens)."
644
- )
645
-
646
- hub_url = self.client.endpoint
647
- if hub_url in repo_url or ("http" not in repo_url and len(repo_url.split("/")) <= 2):
648
- repo_type, namespace, repo_name = repo_type_and_id_from_hf_id(repo_url, hub_url=hub_url)
649
- repo_id = f"{namespace}/{repo_name}" if namespace is not None else repo_name
650
-
651
- if repo_type is not None:
652
- self._repo_type = repo_type
653
-
654
- repo_url = hub_url + "/"
655
-
656
- if self._repo_type in constants.REPO_TYPES_URL_PREFIXES:
657
- repo_url += constants.REPO_TYPES_URL_PREFIXES[self._repo_type]
658
-
659
- if token is not None:
660
- # Add token in git url when provided
661
- scheme = urlparse(repo_url).scheme
662
- repo_url = repo_url.replace(f"{scheme}://", f"{scheme}://user:{token}@")
663
-
664
- repo_url += repo_id
665
-
666
- # For error messages, it's cleaner to show the repo url without the token.
667
- clean_repo_url = re.sub(r"(https?)://.*@", r"\1://", repo_url)
668
- try:
669
- run_subprocess("git lfs install", self.local_dir)
670
-
671
- # checks if repository is initialized in a empty repository or in one with files
672
- if len(os.listdir(self.local_dir)) == 0:
673
- logger.warning(f"Cloning {clean_repo_url} into local empty directory.")
674
-
675
- with _lfs_log_progress():
676
- env = os.environ.copy()
677
-
678
- if self.skip_lfs_files:
679
- env.update({"GIT_LFS_SKIP_SMUDGE": "1"})
680
-
681
- run_subprocess(
682
- # 'git lfs clone' is deprecated (will display a warning in the terminal)
683
- # but we still use it as it provides a nicer UX when downloading large
684
- # files (shows progress).
685
- f"{'git clone' if self.skip_lfs_files else 'git lfs clone'} {repo_url} .",
686
- self.local_dir,
687
- env=env,
688
- )
689
- else:
690
- # Check if the folder is the root of a git repository
691
- if not is_git_repo(self.local_dir):
692
- raise EnvironmentError(
693
- "Tried to clone a repository in a non-empty folder that isn't"
694
- f" a git repository ('{self.local_dir}'). If you really want to"
695
- f" do this, do it manually:\n cd {self.local_dir} && git init"
696
- " && git remote add origin && git pull origin main\n or clone"
697
- " repo to a new folder and move your existing files there"
698
- " afterwards."
699
- )
700
-
701
- if is_local_clone(self.local_dir, repo_url):
702
- logger.warning(
703
- f"{self.local_dir} is already a clone of {clean_repo_url}."
704
- " Make sure you pull the latest changes with"
705
- " `repo.git_pull()`."
706
- )
707
- else:
708
- output = run_subprocess("git remote get-url origin", self.local_dir, check=False)
709
-
710
- error_msg = (
711
- f"Tried to clone {clean_repo_url} in an unrelated git"
712
- " repository.\nIf you believe this is an error, please add"
713
- f" a remote with the following URL: {clean_repo_url}."
714
- )
715
- if output.returncode == 0:
716
- clean_local_remote_url = re.sub(r"https://.*@", "https://", output.stdout)
717
- error_msg += f"\nLocal path has its origin defined as: {clean_local_remote_url}"
718
- raise EnvironmentError(error_msg)
719
-
720
- except subprocess.CalledProcessError as exc:
721
- raise EnvironmentError(exc.stderr)
722
-
723
- def git_config_username_and_email(self, git_user: Optional[str] = None, git_email: Optional[str] = None):
724
- """
725
- Sets git username and email (only in the current repo).
726
-
727
- Args:
728
- git_user (`str`, *optional*):
729
- The username to register through `git`.
730
- git_email (`str`, *optional*):
731
- The email to register through `git`.
732
- """
733
- try:
734
- if git_user is not None:
735
- run_subprocess("git config user.name".split() + [git_user], self.local_dir)
736
-
737
- if git_email is not None:
738
- run_subprocess(f"git config user.email {git_email}".split(), self.local_dir)
739
- except subprocess.CalledProcessError as exc:
740
- raise EnvironmentError(exc.stderr)
741
-
742
- def git_credential_helper_store(self):
743
- """
744
- Sets the git credential helper to `store`
745
- """
746
- try:
747
- run_subprocess("git config credential.helper store", self.local_dir)
748
- except subprocess.CalledProcessError as exc:
749
- raise EnvironmentError(exc.stderr)
750
-
751
- def git_head_hash(self) -> str:
752
- """
753
- Get commit sha on top of HEAD.
754
-
755
- Returns:
756
- `str`: The current checked out commit SHA.
757
- """
758
- try:
759
- p = run_subprocess("git rev-parse HEAD", self.local_dir)
760
- return p.stdout.strip()
761
- except subprocess.CalledProcessError as exc:
762
- raise EnvironmentError(exc.stderr)
763
-
764
- def git_remote_url(self) -> str:
765
- """
766
- Get URL to origin remote.
767
-
768
- Returns:
769
- `str`: The URL of the `origin` remote.
770
- """
771
- try:
772
- p = run_subprocess("git config --get remote.origin.url", self.local_dir)
773
- url = p.stdout.strip()
774
- # Strip basic auth info.
775
- return re.sub(r"https://.*@", "https://", url)
776
- except subprocess.CalledProcessError as exc:
777
- raise EnvironmentError(exc.stderr)
778
-
779
- def git_head_commit_url(self) -> str:
780
- """
781
- Get URL to last commit on HEAD. We assume it's been pushed, and the url
782
- scheme is the same one as for GitHub or HuggingFace.
783
-
784
- Returns:
785
- `str`: The URL to the current checked-out commit.
786
- """
787
- sha = self.git_head_hash()
788
- url = self.git_remote_url()
789
- if url.endswith("/"):
790
- url = url[:-1]
791
- return f"{url}/commit/{sha}"
792
-
793
- def list_deleted_files(self) -> List[str]:
794
- """
795
- Returns a list of the files that are deleted in the working directory or
796
- index.
797
-
798
- Returns:
799
- `List[str]`: A list of files that have been deleted in the working
800
- directory or index.
801
- """
802
- try:
803
- git_status = run_subprocess("git status -s", self.local_dir).stdout.strip()
804
- except subprocess.CalledProcessError as exc:
805
- raise EnvironmentError(exc.stderr)
806
-
807
- if len(git_status) == 0:
808
- return []
809
-
810
- # Receives a status like the following
811
- # D .gitignore
812
- # D new_file.json
813
- # AD new_file1.json
814
- # ?? new_file2.json
815
- # ?? new_file4.json
816
-
817
- # Strip each line of whitespaces
818
- modified_files_statuses = [status.strip() for status in git_status.split("\n")]
819
-
820
- # Only keep files that are deleted using the D prefix
821
- deleted_files_statuses = [status for status in modified_files_statuses if "D" in status.split()[0]]
822
-
823
- # Remove the D prefix and strip to keep only the relevant filename
824
- deleted_files = [status.split()[-1].strip() for status in deleted_files_statuses]
825
-
826
- return deleted_files
827
-
828
- def lfs_track(self, patterns: Union[str, List[str]], filename: bool = False):
829
- """
830
- Tell git-lfs to track files according to a pattern.
831
-
832
- Setting the `filename` argument to `True` will treat the arguments as
833
- literal filenames, not as patterns. Any special glob characters in the
834
- filename will be escaped when writing to the `.gitattributes` file.
835
-
836
- Args:
837
- patterns (`Union[str, List[str]]`):
838
- The pattern, or list of patterns, to track with git-lfs.
839
- filename (`bool`, *optional*, defaults to `False`):
840
- Whether to use the patterns as literal filenames.
841
- """
842
- if isinstance(patterns, str):
843
- patterns = [patterns]
844
- try:
845
- for pattern in patterns:
846
- run_subprocess(
847
- f"git lfs track {'--filename' if filename else ''} {pattern}",
848
- self.local_dir,
849
- )
850
- except subprocess.CalledProcessError as exc:
851
- raise EnvironmentError(exc.stderr)
852
-
853
- def lfs_untrack(self, patterns: Union[str, List[str]]):
854
- """
855
- Tell git-lfs to untrack those files.
856
-
857
- Args:
858
- patterns (`Union[str, List[str]]`):
859
- The pattern, or list of patterns, to untrack with git-lfs.
860
- """
861
- if isinstance(patterns, str):
862
- patterns = [patterns]
863
- try:
864
- for pattern in patterns:
865
- run_subprocess("git lfs untrack".split() + [pattern], self.local_dir)
866
- except subprocess.CalledProcessError as exc:
867
- raise EnvironmentError(exc.stderr)
868
-
869
- def lfs_enable_largefiles(self):
870
- """
871
- HF-specific. This enables upload support of files >5GB.
872
- """
873
- try:
874
- lfs_config = "git config lfs.customtransfer.multipart"
875
- run_subprocess(f"{lfs_config}.path hf", self.local_dir)
876
- run_subprocess(
877
- f"{lfs_config}.args {LFS_MULTIPART_UPLOAD_COMMAND}",
878
- self.local_dir,
879
- )
880
- except subprocess.CalledProcessError as exc:
881
- raise EnvironmentError(exc.stderr)
882
-
883
- def auto_track_binary_files(self, pattern: str = ".") -> List[str]:
884
- """
885
- Automatically track binary files with git-lfs.
886
-
887
- Args:
888
- pattern (`str`, *optional*, defaults to "."):
889
- The pattern with which to track files that are binary.
890
-
891
- Returns:
892
- `List[str]`: List of filenames that are now tracked due to being
893
- binary files
894
- """
895
- files_to_be_tracked_with_lfs = []
896
-
897
- deleted_files = self.list_deleted_files()
898
-
899
- for filename in files_to_be_staged(pattern, folder=self.local_dir):
900
- if filename in deleted_files:
901
- continue
902
-
903
- path_to_file = os.path.join(os.getcwd(), self.local_dir, filename)
904
-
905
- if not (is_tracked_with_lfs(path_to_file) or is_git_ignored(path_to_file)):
906
- size_in_mb = os.path.getsize(path_to_file) / (1024 * 1024)
907
-
908
- if size_in_mb >= 10:
909
- logger.warning(
910
- "Parsing a large file to check if binary or not. Tracking large"
911
- " files using `repository.auto_track_large_files` is"
912
- " recommended so as to not load the full file in memory."
913
- )
914
-
915
- is_binary = is_binary_file(path_to_file)
916
-
917
- if is_binary:
918
- self.lfs_track(filename)
919
- files_to_be_tracked_with_lfs.append(filename)
920
-
921
- # Cleanup the .gitattributes if files were deleted
922
- self.lfs_untrack(deleted_files)
923
-
924
- return files_to_be_tracked_with_lfs
925
-
926
- def auto_track_large_files(self, pattern: str = ".") -> List[str]:
927
- """
928
- Automatically track large files (files that weigh more than 10MBs) with
929
- git-lfs.
930
-
931
- Args:
932
- pattern (`str`, *optional*, defaults to "."):
933
- The pattern with which to track files that are above 10MBs.
934
-
935
- Returns:
936
- `List[str]`: List of filenames that are now tracked due to their
937
- size.
938
- """
939
- files_to_be_tracked_with_lfs = []
940
-
941
- deleted_files = self.list_deleted_files()
942
-
943
- for filename in files_to_be_staged(pattern, folder=self.local_dir):
944
- if filename in deleted_files:
945
- continue
946
-
947
- path_to_file = os.path.join(os.getcwd(), self.local_dir, filename)
948
- size_in_mb = os.path.getsize(path_to_file) / (1024 * 1024)
949
-
950
- if size_in_mb >= 10 and not is_tracked_with_lfs(path_to_file) and not is_git_ignored(path_to_file):
951
- self.lfs_track(filename)
952
- files_to_be_tracked_with_lfs.append(filename)
953
-
954
- # Cleanup the .gitattributes if files were deleted
955
- self.lfs_untrack(deleted_files)
956
-
957
- return files_to_be_tracked_with_lfs
958
-
959
- def lfs_prune(self, recent=False):
960
- """
961
- git lfs prune
962
-
963
- Args:
964
- recent (`bool`, *optional*, defaults to `False`):
965
- Whether to prune files even if they were referenced by recent
966
- commits. See the following
967
- [link](https://github.com/git-lfs/git-lfs/blob/f3d43f0428a84fc4f1e5405b76b5a73ec2437e65/docs/man/git-lfs-prune.1.ronn#recent-files)
968
- for more information.
969
- """
970
- try:
971
- with _lfs_log_progress():
972
- result = run_subprocess(f"git lfs prune {'--recent' if recent else ''}", self.local_dir)
973
- logger.info(result.stdout)
974
- except subprocess.CalledProcessError as exc:
975
- raise EnvironmentError(exc.stderr)
976
-
977
- def git_pull(self, rebase: bool = False, lfs: bool = False):
978
- """
979
- git pull
980
-
981
- Args:
982
- rebase (`bool`, *optional*, defaults to `False`):
983
- Whether to rebase the current branch on top of the upstream
984
- branch after fetching.
985
- lfs (`bool`, *optional*, defaults to `False`):
986
- Whether to fetch the LFS files too. This option only changes the
987
- behavior when a repository was cloned without fetching the LFS
988
- files; calling `repo.git_pull(lfs=True)` will then fetch the LFS
989
- file from the remote repository.
990
- """
991
- command = "git pull" if not lfs else "git lfs pull"
992
- if rebase:
993
- command += " --rebase"
994
- try:
995
- with _lfs_log_progress():
996
- result = run_subprocess(command, self.local_dir)
997
- logger.info(result.stdout)
998
- except subprocess.CalledProcessError as exc:
999
- raise EnvironmentError(exc.stderr)
1000
-
1001
- def git_add(self, pattern: str = ".", auto_lfs_track: bool = False):
1002
- """
1003
- git add
1004
-
1005
- Setting the `auto_lfs_track` parameter to `True` will automatically
1006
- track files that are larger than 10MB with `git-lfs`.
1007
-
1008
- Args:
1009
- pattern (`str`, *optional*, defaults to "."):
1010
- The pattern with which to add files to staging.
1011
- auto_lfs_track (`bool`, *optional*, defaults to `False`):
1012
- Whether to automatically track large and binary files with
1013
- git-lfs. Any file over 10MB in size, or in binary format, will
1014
- be automatically tracked.
1015
- """
1016
- if auto_lfs_track:
1017
- # Track files according to their size (>=10MB)
1018
- tracked_files = self.auto_track_large_files(pattern)
1019
-
1020
- # Read the remaining files and track them if they're binary
1021
- tracked_files.extend(self.auto_track_binary_files(pattern))
1022
-
1023
- if tracked_files:
1024
- logger.warning(
1025
- f"Adding files tracked by Git LFS: {tracked_files}. This may take a"
1026
- " bit of time if the files are large."
1027
- )
1028
-
1029
- try:
1030
- result = run_subprocess("git add -v".split() + [pattern], self.local_dir)
1031
- logger.info(f"Adding to index:\n{result.stdout}\n")
1032
- except subprocess.CalledProcessError as exc:
1033
- raise EnvironmentError(exc.stderr)
1034
-
1035
- def git_commit(self, commit_message: str = "commit files to HF hub"):
1036
- """
1037
- git commit
1038
-
1039
- Args:
1040
- commit_message (`str`, *optional*, defaults to "commit files to HF hub"):
1041
- The message attributed to the commit.
1042
- """
1043
- try:
1044
- result = run_subprocess("git commit -v -m".split() + [commit_message], self.local_dir)
1045
- logger.info(f"Committed:\n{result.stdout}\n")
1046
- except subprocess.CalledProcessError as exc:
1047
- if len(exc.stderr) > 0:
1048
- raise EnvironmentError(exc.stderr)
1049
- else:
1050
- raise EnvironmentError(exc.stdout)
1051
-
1052
- def git_push(
1053
- self,
1054
- upstream: Optional[str] = None,
1055
- blocking: bool = True,
1056
- auto_lfs_prune: bool = False,
1057
- ) -> Union[str, Tuple[str, CommandInProgress]]:
1058
- """
1059
- git push
1060
-
1061
- If used without setting `blocking`, will return url to commit on remote
1062
- repo. If used with `blocking=True`, will return a tuple containing the
1063
- url to commit and the command object to follow for information about the
1064
- process.
1065
-
1066
- Args:
1067
- upstream (`str`, *optional*):
1068
- Upstream to which this should push. If not specified, will push
1069
- to the lastly defined upstream or to the default one (`origin
1070
- main`).
1071
- blocking (`bool`, *optional*, defaults to `True`):
1072
- Whether the function should return only when the push has
1073
- finished. Setting this to `False` will return an
1074
- `CommandInProgress` object which has an `is_done` property. This
1075
- property will be set to `True` when the push is finished.
1076
- auto_lfs_prune (`bool`, *optional*, defaults to `False`):
1077
- Whether to automatically prune files once they have been pushed
1078
- to the remote.
1079
- """
1080
- command = "git push"
1081
-
1082
- if upstream:
1083
- command += f" --set-upstream {upstream}"
1084
-
1085
- number_of_commits = commits_to_push(self.local_dir, upstream)
1086
-
1087
- if number_of_commits > 1:
1088
- logger.warning(f"Several commits ({number_of_commits}) will be pushed upstream.")
1089
- if blocking:
1090
- logger.warning("The progress bars may be unreliable.")
1091
-
1092
- try:
1093
- with _lfs_log_progress():
1094
- process = subprocess.Popen(
1095
- command.split(),
1096
- stderr=subprocess.PIPE,
1097
- stdout=subprocess.PIPE,
1098
- encoding="utf-8",
1099
- cwd=self.local_dir,
1100
- )
1101
-
1102
- if blocking:
1103
- stdout, stderr = process.communicate()
1104
- return_code = process.poll()
1105
- process.kill()
1106
-
1107
- if len(stderr):
1108
- logger.warning(stderr)
1109
-
1110
- if return_code:
1111
- raise subprocess.CalledProcessError(return_code, process.args, output=stdout, stderr=stderr)
1112
-
1113
- except subprocess.CalledProcessError as exc:
1114
- raise EnvironmentError(exc.stderr)
1115
-
1116
- if not blocking:
1117
-
1118
- def status_method():
1119
- status = process.poll()
1120
- if status is None:
1121
- return -1
1122
- else:
1123
- return status
1124
-
1125
- command_in_progress = CommandInProgress(
1126
- "push",
1127
- is_done_method=lambda: process.poll() is not None,
1128
- status_method=status_method,
1129
- process=process,
1130
- post_method=self.lfs_prune if auto_lfs_prune else None,
1131
- )
1132
-
1133
- self.command_queue.append(command_in_progress)
1134
-
1135
- return self.git_head_commit_url(), command_in_progress
1136
-
1137
- if auto_lfs_prune:
1138
- self.lfs_prune()
1139
-
1140
- return self.git_head_commit_url()
1141
-
1142
- def git_checkout(self, revision: str, create_branch_ok: bool = False):
1143
- """
1144
- git checkout a given revision
1145
-
1146
- Specifying `create_branch_ok` to `True` will create the branch to the
1147
- given revision if that revision doesn't exist.
1148
-
1149
- Args:
1150
- revision (`str`):
1151
- The revision to checkout.
1152
- create_branch_ok (`str`, *optional*, defaults to `False`):
1153
- Whether creating a branch named with the `revision` passed at
1154
- the current checked-out reference if `revision` isn't an
1155
- existing revision is allowed.
1156
- """
1157
- try:
1158
- result = run_subprocess(f"git checkout {revision}", self.local_dir)
1159
- logger.warning(f"Checked out {revision} from {self.current_branch}.")
1160
- logger.warning(result.stdout)
1161
- except subprocess.CalledProcessError as exc:
1162
- if not create_branch_ok:
1163
- raise EnvironmentError(exc.stderr)
1164
- else:
1165
- try:
1166
- result = run_subprocess(f"git checkout -b {revision}", self.local_dir)
1167
- logger.warning(
1168
- f"Revision `{revision}` does not exist. Created and checked out branch `{revision}`."
1169
- )
1170
- logger.warning(result.stdout)
1171
- except subprocess.CalledProcessError as exc:
1172
- raise EnvironmentError(exc.stderr)
1173
-
1174
- def tag_exists(self, tag_name: str, remote: Optional[str] = None) -> bool:
1175
- """
1176
- Check if a tag exists or not.
1177
-
1178
- Args:
1179
- tag_name (`str`):
1180
- The name of the tag to check.
1181
- remote (`str`, *optional*):
1182
- Whether to check if the tag exists on a remote. This parameter
1183
- should be the identifier of the remote.
1184
-
1185
- Returns:
1186
- `bool`: Whether the tag exists.
1187
- """
1188
- if remote:
1189
- try:
1190
- result = run_subprocess(f"git ls-remote origin refs/tags/{tag_name}", self.local_dir).stdout.strip()
1191
- except subprocess.CalledProcessError as exc:
1192
- raise EnvironmentError(exc.stderr)
1193
-
1194
- return len(result) != 0
1195
- else:
1196
- try:
1197
- git_tags = run_subprocess("git tag", self.local_dir).stdout.strip()
1198
- except subprocess.CalledProcessError as exc:
1199
- raise EnvironmentError(exc.stderr)
1200
-
1201
- git_tags = git_tags.split("\n")
1202
- return tag_name in git_tags
1203
-
1204
- def delete_tag(self, tag_name: str, remote: Optional[str] = None) -> bool:
1205
- """
1206
- Delete a tag, both local and remote, if it exists
1207
-
1208
- Args:
1209
- tag_name (`str`):
1210
- The tag name to delete.
1211
- remote (`str`, *optional*):
1212
- The remote on which to delete the tag.
1213
-
1214
- Returns:
1215
- `bool`: `True` if deleted, `False` if the tag didn't exist.
1216
- If remote is not passed, will just be updated locally
1217
- """
1218
- delete_locally = True
1219
- delete_remotely = True
1220
-
1221
- if not self.tag_exists(tag_name):
1222
- delete_locally = False
1223
-
1224
- if not self.tag_exists(tag_name, remote=remote):
1225
- delete_remotely = False
1226
-
1227
- if delete_locally:
1228
- try:
1229
- run_subprocess(["git", "tag", "-d", tag_name], self.local_dir).stdout.strip()
1230
- except subprocess.CalledProcessError as exc:
1231
- raise EnvironmentError(exc.stderr)
1232
-
1233
- if remote and delete_remotely:
1234
- try:
1235
- run_subprocess(f"git push {remote} --delete {tag_name}", self.local_dir).stdout.strip()
1236
- except subprocess.CalledProcessError as exc:
1237
- raise EnvironmentError(exc.stderr)
1238
-
1239
- return True
1240
-
1241
- def add_tag(self, tag_name: str, message: Optional[str] = None, remote: Optional[str] = None):
1242
- """
1243
- Add a tag at the current head and push it
1244
-
1245
- If remote is None, will just be updated locally
1246
-
1247
- If no message is provided, the tag will be lightweight. if a message is
1248
- provided, the tag will be annotated.
1249
-
1250
- Args:
1251
- tag_name (`str`):
1252
- The name of the tag to be added.
1253
- message (`str`, *optional*):
1254
- The message that accompanies the tag. The tag will turn into an
1255
- annotated tag if a message is passed.
1256
- remote (`str`, *optional*):
1257
- The remote on which to add the tag.
1258
- """
1259
- if message:
1260
- tag_args = ["git", "tag", "-a", tag_name, "-m", message]
1261
- else:
1262
- tag_args = ["git", "tag", tag_name]
1263
-
1264
- try:
1265
- run_subprocess(tag_args, self.local_dir).stdout.strip()
1266
- except subprocess.CalledProcessError as exc:
1267
- raise EnvironmentError(exc.stderr)
1268
-
1269
- if remote:
1270
- try:
1271
- run_subprocess(f"git push {remote} {tag_name}", self.local_dir).stdout.strip()
1272
- except subprocess.CalledProcessError as exc:
1273
- raise EnvironmentError(exc.stderr)
1274
-
1275
- def is_repo_clean(self) -> bool:
1276
- """
1277
- Return whether or not the git status is clean or not
1278
-
1279
- Returns:
1280
- `bool`: `True` if the git status is clean, `False` otherwise.
1281
- """
1282
- try:
1283
- git_status = run_subprocess("git status --porcelain", self.local_dir).stdout.strip()
1284
- except subprocess.CalledProcessError as exc:
1285
- raise EnvironmentError(exc.stderr)
1286
-
1287
- return len(git_status) == 0
1288
-
1289
- def push_to_hub(
1290
- self,
1291
- commit_message: str = "commit files to HF hub",
1292
- blocking: bool = True,
1293
- clean_ok: bool = True,
1294
- auto_lfs_prune: bool = False,
1295
- ) -> Union[None, str, Tuple[str, CommandInProgress]]:
1296
- """
1297
- Helper to add, commit, and push files to remote repository on the
1298
- HuggingFace Hub. Will automatically track large files (>10MB).
1299
-
1300
- Args:
1301
- commit_message (`str`):
1302
- Message to use for the commit.
1303
- blocking (`bool`, *optional*, defaults to `True`):
1304
- Whether the function should return only when the `git push` has
1305
- finished.
1306
- clean_ok (`bool`, *optional*, defaults to `True`):
1307
- If True, this function will return None if the repo is
1308
- untouched. Default behavior is to fail because the git command
1309
- fails.
1310
- auto_lfs_prune (`bool`, *optional*, defaults to `False`):
1311
- Whether to automatically prune files once they have been pushed
1312
- to the remote.
1313
- """
1314
- if clean_ok and self.is_repo_clean():
1315
- logger.info("Repo currently clean. Ignoring push_to_hub")
1316
- return None
1317
- self.git_add(auto_lfs_track=True)
1318
- self.git_commit(commit_message)
1319
- return self.git_push(
1320
- upstream=f"origin {self.current_branch}",
1321
- blocking=blocking,
1322
- auto_lfs_prune=auto_lfs_prune,
1323
- )
1324
-
1325
- @contextmanager
1326
- def commit(
1327
- self,
1328
- commit_message: str,
1329
- branch: Optional[str] = None,
1330
- track_large_files: bool = True,
1331
- blocking: bool = True,
1332
- auto_lfs_prune: bool = False,
1333
- ):
1334
- """
1335
- Context manager utility to handle committing to a repository. This
1336
- automatically tracks large files (>10Mb) with git-lfs. Set the
1337
- `track_large_files` argument to `False` if you wish to ignore that
1338
- behavior.
1339
-
1340
- Args:
1341
- commit_message (`str`):
1342
- Message to use for the commit.
1343
- branch (`str`, *optional*):
1344
- The branch on which the commit will appear. This branch will be
1345
- checked-out before any operation.
1346
- track_large_files (`bool`, *optional*, defaults to `True`):
1347
- Whether to automatically track large files or not. Will do so by
1348
- default.
1349
- blocking (`bool`, *optional*, defaults to `True`):
1350
- Whether the function should return only when the `git push` has
1351
- finished.
1352
- auto_lfs_prune (`bool`, defaults to `True`):
1353
- Whether to automatically prune files once they have been pushed
1354
- to the remote.
1355
-
1356
- Examples:
1357
-
1358
- ```python
1359
- >>> with Repository(
1360
- ... "text-files",
1361
- ... clone_from="<user>/text-files",
1362
- ... token=True,
1363
- >>> ).commit("My first file :)"):
1364
- ... with open("file.txt", "w+") as f:
1365
- ... f.write(json.dumps({"hey": 8}))
1366
-
1367
- >>> import torch
1368
-
1369
- >>> model = torch.nn.Transformer()
1370
- >>> with Repository(
1371
- ... "torch-model",
1372
- ... clone_from="<user>/torch-model",
1373
- ... token=True,
1374
- >>> ).commit("My cool model :)"):
1375
- ... torch.save(model.state_dict(), "model.pt")
1376
- ```
1377
-
1378
- """
1379
-
1380
- files_to_stage = files_to_be_staged(".", folder=self.local_dir)
1381
-
1382
- if len(files_to_stage):
1383
- files_in_msg = str(files_to_stage[:5])[:-1] + ", ...]" if len(files_to_stage) > 5 else str(files_to_stage)
1384
- logger.error(
1385
- "There exists some updated files in the local repository that are not"
1386
- f" committed: {files_in_msg}. This may lead to errors if checking out"
1387
- " a branch. These files and their modifications will be added to the"
1388
- " current commit."
1389
- )
1390
-
1391
- if branch is not None:
1392
- self.git_checkout(branch, create_branch_ok=True)
1393
-
1394
- if is_tracked_upstream(self.local_dir):
1395
- logger.warning("Pulling changes ...")
1396
- self.git_pull(rebase=True)
1397
- else:
1398
- logger.warning(f"The current branch has no upstream branch. Will push to 'origin {self.current_branch}'")
1399
-
1400
- current_working_directory = os.getcwd()
1401
- os.chdir(os.path.join(current_working_directory, self.local_dir))
1402
-
1403
- try:
1404
- yield self
1405
- finally:
1406
- self.git_add(auto_lfs_track=track_large_files)
1407
-
1408
- try:
1409
- self.git_commit(commit_message)
1410
- except OSError as e:
1411
- # If no changes are detected, there is nothing to commit.
1412
- if "nothing to commit" not in str(e):
1413
- raise e
1414
-
1415
- try:
1416
- self.git_push(
1417
- upstream=f"origin {self.current_branch}",
1418
- blocking=blocking,
1419
- auto_lfs_prune=auto_lfs_prune,
1420
- )
1421
- except OSError as e:
1422
- # If no changes are detected, there is nothing to commit.
1423
- if "could not read Username" in str(e):
1424
- raise OSError("Couldn't authenticate user for push. Did you set `token` to `True`?") from e
1425
- else:
1426
- raise e
1427
-
1428
- os.chdir(current_working_directory)
1429
-
1430
- def repocard_metadata_load(self) -> Optional[Dict]:
1431
- filepath = os.path.join(self.local_dir, constants.REPOCARD_NAME)
1432
- if os.path.isfile(filepath):
1433
- return metadata_load(filepath)
1434
- return None
1435
-
1436
- def repocard_metadata_save(self, data: Dict) -> None:
1437
- return metadata_save(os.path.join(self.local_dir, constants.REPOCARD_NAME), data)
1438
-
1439
- @property
1440
- def commands_failed(self):
1441
- """
1442
- Returns the asynchronous commands that failed.
1443
- """
1444
- return [c for c in self.command_queue if c.status > 0]
1445
-
1446
- @property
1447
- def commands_in_progress(self):
1448
- """
1449
- Returns the asynchronous commands that are currently in progress.
1450
- """
1451
- return [c for c in self.command_queue if not c.is_done]
1452
-
1453
- def wait_for_commands(self):
1454
- """
1455
- Blocking method: blocks all subsequent execution until all commands have
1456
- been processed.
1457
- """
1458
- index = 0
1459
- for command_failed in self.commands_failed:
1460
- logger.error(f"The {command_failed.title} command with PID {command_failed._process.pid} failed.")
1461
- logger.error(command_failed.stderr)
1462
-
1463
- while self.commands_in_progress:
1464
- if index % 10 == 0:
1465
- logger.warning(
1466
- f"Waiting for the following commands to finish before shutting down: {self.commands_in_progress}."
1467
- )
1468
-
1469
- index += 1
1470
-
1471
- time.sleep(1)