lfs.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. # coding=utf-8
  2. # Copyright 2019-present, the HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Git LFS related type definitions and utilities"""
  16. import inspect
  17. import io
  18. import re
  19. import warnings
  20. from dataclasses import dataclass
  21. from math import ceil
  22. from os.path import getsize
  23. from pathlib import Path
  24. from typing import TYPE_CHECKING, BinaryIO, Dict, Iterable, List, Optional, Tuple, TypedDict
  25. from urllib.parse import unquote
  26. from huggingface_hub import constants
  27. from .utils import (
  28. build_hf_headers,
  29. fix_hf_endpoint_in_url,
  30. get_session,
  31. hf_raise_for_status,
  32. http_backoff,
  33. logging,
  34. tqdm,
  35. validate_hf_hub_args,
  36. )
  37. from .utils._lfs import SliceFileObj
  38. from .utils.sha import sha256, sha_fileobj
  39. from .utils.tqdm import is_tqdm_disabled
  40. if TYPE_CHECKING:
  41. from ._commit_api import CommitOperationAdd
  42. logger = logging.get_logger(__name__)
  43. OID_REGEX = re.compile(r"^[0-9a-f]{40}$")
  44. LFS_MULTIPART_UPLOAD_COMMAND = "lfs-multipart-upload"
  45. LFS_HEADERS = {
  46. "Accept": "application/vnd.git-lfs+json",
  47. "Content-Type": "application/vnd.git-lfs+json",
  48. }
  49. @dataclass
  50. class UploadInfo:
  51. """
  52. Dataclass holding required information to determine whether a blob
  53. should be uploaded to the hub using the LFS protocol or the regular protocol
  54. Args:
  55. sha256 (`bytes`):
  56. SHA256 hash of the blob
  57. size (`int`):
  58. Size in bytes of the blob
  59. sample (`bytes`):
  60. First 512 bytes of the blob
  61. """
  62. sha256: bytes
  63. size: int
  64. sample: bytes
  65. @classmethod
  66. def from_path(cls, path: str):
  67. size = getsize(path)
  68. with io.open(path, "rb") as file:
  69. sample = file.peek(512)[:512]
  70. sha = sha_fileobj(file)
  71. return cls(size=size, sha256=sha, sample=sample)
  72. @classmethod
  73. def from_bytes(cls, data: bytes):
  74. sha = sha256(data).digest()
  75. return cls(size=len(data), sample=data[:512], sha256=sha)
  76. @classmethod
  77. def from_fileobj(cls, fileobj: BinaryIO):
  78. sample = fileobj.read(512)
  79. fileobj.seek(0, io.SEEK_SET)
  80. sha = sha_fileobj(fileobj)
  81. size = fileobj.tell()
  82. fileobj.seek(0, io.SEEK_SET)
  83. return cls(size=size, sha256=sha, sample=sample)
  84. @validate_hf_hub_args
  85. def post_lfs_batch_info(
  86. upload_infos: Iterable[UploadInfo],
  87. token: Optional[str],
  88. repo_type: str,
  89. repo_id: str,
  90. revision: Optional[str] = None,
  91. endpoint: Optional[str] = None,
  92. headers: Optional[Dict[str, str]] = None,
  93. transfers: Optional[List[str]] = None,
  94. ) -> Tuple[List[dict], List[dict], Optional[str]]:
  95. """
  96. Requests the LFS batch endpoint to retrieve upload instructions
  97. Learn more: https://github.com/git-lfs/git-lfs/blob/main/docs/api/batch.md
  98. Args:
  99. upload_infos (`Iterable` of `UploadInfo`):
  100. `UploadInfo` for the files that are being uploaded, typically obtained
  101. from `CommitOperationAdd.upload_info`
  102. repo_type (`str`):
  103. Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`.
  104. repo_id (`str`):
  105. A namespace (user or an organization) and a repo name separated
  106. by a `/`.
  107. revision (`str`, *optional*):
  108. The git revision to upload to.
  109. headers (`dict`, *optional*):
  110. Additional headers to include in the request
  111. transfers (`list`, *optional*):
  112. List of transfer methods to use. Defaults to ["basic", "multipart"].
  113. Returns:
  114. `LfsBatchInfo`: 3-tuple:
  115. - First element is the list of upload instructions from the server
  116. - Second element is a list of errors, if any
  117. - Third element is the chosen transfer adapter if provided by the server (e.g. "basic", "multipart", "xet")
  118. Raises:
  119. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  120. If an argument is invalid or the server response is malformed.
  121. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  122. If the server returned an error.
  123. """
  124. endpoint = endpoint if endpoint is not None else constants.ENDPOINT
  125. url_prefix = ""
  126. if repo_type in constants.REPO_TYPES_URL_PREFIXES:
  127. url_prefix = constants.REPO_TYPES_URL_PREFIXES[repo_type]
  128. batch_url = f"{endpoint}/{url_prefix}{repo_id}.git/info/lfs/objects/batch"
  129. payload: Dict = {
  130. "operation": "upload",
  131. "transfers": transfers if transfers is not None else ["basic", "multipart"],
  132. "objects": [
  133. {
  134. "oid": upload.sha256.hex(),
  135. "size": upload.size,
  136. }
  137. for upload in upload_infos
  138. ],
  139. "hash_algo": "sha256",
  140. }
  141. if revision is not None:
  142. payload["ref"] = {"name": unquote(revision)} # revision has been previously 'quoted'
  143. headers = {
  144. **LFS_HEADERS,
  145. **build_hf_headers(token=token),
  146. **(headers or {}),
  147. }
  148. resp = get_session().post(batch_url, headers=headers, json=payload)
  149. hf_raise_for_status(resp)
  150. batch_info = resp.json()
  151. objects = batch_info.get("objects", None)
  152. if not isinstance(objects, list):
  153. raise ValueError("Malformed response from server")
  154. chosen_transfer = batch_info.get("transfer")
  155. chosen_transfer = chosen_transfer if isinstance(chosen_transfer, str) else None
  156. return (
  157. [_validate_batch_actions(obj) for obj in objects if "error" not in obj],
  158. [_validate_batch_error(obj) for obj in objects if "error" in obj],
  159. chosen_transfer,
  160. )
  161. class PayloadPartT(TypedDict):
  162. partNumber: int
  163. etag: str
  164. class CompletionPayloadT(TypedDict):
  165. """Payload that will be sent to the Hub when uploading multi-part."""
  166. oid: str
  167. parts: List[PayloadPartT]
  168. def lfs_upload(
  169. operation: "CommitOperationAdd",
  170. lfs_batch_action: Dict,
  171. token: Optional[str] = None,
  172. headers: Optional[Dict[str, str]] = None,
  173. endpoint: Optional[str] = None,
  174. ) -> None:
  175. """
  176. Handles uploading a given object to the Hub with the LFS protocol.
  177. Can be a No-op if the content of the file is already present on the hub large file storage.
  178. Args:
  179. operation (`CommitOperationAdd`):
  180. The add operation triggering this upload.
  181. lfs_batch_action (`dict`):
  182. Upload instructions from the LFS batch endpoint for this object. See [`~utils.lfs.post_lfs_batch_info`] for
  183. more details.
  184. headers (`dict`, *optional*):
  185. Headers to include in the request, including authentication and user agent headers.
  186. Raises:
  187. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  188. If `lfs_batch_action` is improperly formatted
  189. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  190. If the upload resulted in an error
  191. """
  192. # 0. If LFS file is already present, skip upload
  193. _validate_batch_actions(lfs_batch_action)
  194. actions = lfs_batch_action.get("actions")
  195. if actions is None:
  196. # The file was already uploaded
  197. logger.debug(f"Content of file {operation.path_in_repo} is already present upstream - skipping upload")
  198. return
  199. # 1. Validate server response (check required keys in dict)
  200. upload_action = lfs_batch_action["actions"]["upload"]
  201. _validate_lfs_action(upload_action)
  202. verify_action = lfs_batch_action["actions"].get("verify")
  203. if verify_action is not None:
  204. _validate_lfs_action(verify_action)
  205. # 2. Upload file (either single part or multi-part)
  206. header = upload_action.get("header", {})
  207. chunk_size = header.get("chunk_size")
  208. upload_url = fix_hf_endpoint_in_url(upload_action["href"], endpoint=endpoint)
  209. if chunk_size is not None:
  210. try:
  211. chunk_size = int(chunk_size)
  212. except (ValueError, TypeError):
  213. raise ValueError(
  214. f"Malformed response from LFS batch endpoint: `chunk_size` should be an integer. Got '{chunk_size}'."
  215. )
  216. _upload_multi_part(operation=operation, header=header, chunk_size=chunk_size, upload_url=upload_url)
  217. else:
  218. _upload_single_part(operation=operation, upload_url=upload_url)
  219. # 3. Verify upload went well
  220. if verify_action is not None:
  221. _validate_lfs_action(verify_action)
  222. verify_url = fix_hf_endpoint_in_url(verify_action["href"], endpoint)
  223. verify_resp = get_session().post(
  224. verify_url,
  225. headers=build_hf_headers(token=token, headers=headers),
  226. json={"oid": operation.upload_info.sha256.hex(), "size": operation.upload_info.size},
  227. )
  228. hf_raise_for_status(verify_resp)
  229. logger.debug(f"{operation.path_in_repo}: Upload successful")
  230. def _validate_lfs_action(lfs_action: dict):
  231. """validates response from the LFS batch endpoint"""
  232. if not (
  233. isinstance(lfs_action.get("href"), str)
  234. and (lfs_action.get("header") is None or isinstance(lfs_action.get("header"), dict))
  235. ):
  236. raise ValueError("lfs_action is improperly formatted")
  237. return lfs_action
  238. def _validate_batch_actions(lfs_batch_actions: dict):
  239. """validates response from the LFS batch endpoint"""
  240. if not (isinstance(lfs_batch_actions.get("oid"), str) and isinstance(lfs_batch_actions.get("size"), int)):
  241. raise ValueError("lfs_batch_actions is improperly formatted")
  242. upload_action = lfs_batch_actions.get("actions", {}).get("upload")
  243. verify_action = lfs_batch_actions.get("actions", {}).get("verify")
  244. if upload_action is not None:
  245. _validate_lfs_action(upload_action)
  246. if verify_action is not None:
  247. _validate_lfs_action(verify_action)
  248. return lfs_batch_actions
  249. def _validate_batch_error(lfs_batch_error: dict):
  250. """validates response from the LFS batch endpoint"""
  251. if not (isinstance(lfs_batch_error.get("oid"), str) and isinstance(lfs_batch_error.get("size"), int)):
  252. raise ValueError("lfs_batch_error is improperly formatted")
  253. error_info = lfs_batch_error.get("error")
  254. if not (
  255. isinstance(error_info, dict)
  256. and isinstance(error_info.get("message"), str)
  257. and isinstance(error_info.get("code"), int)
  258. ):
  259. raise ValueError("lfs_batch_error is improperly formatted")
  260. return lfs_batch_error
  261. def _upload_single_part(operation: "CommitOperationAdd", upload_url: str) -> None:
  262. """
  263. Uploads `fileobj` as a single PUT HTTP request (basic LFS transfer protocol)
  264. Args:
  265. upload_url (`str`):
  266. The URL to PUT the file to.
  267. fileobj:
  268. The file-like object holding the data to upload.
  269. Returns: `requests.Response`
  270. Raises:
  271. [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  272. If the upload resulted in an error.
  273. """
  274. with operation.as_file(with_tqdm=True) as fileobj:
  275. # S3 might raise a transient 500 error -> let's retry if that happens
  276. response = http_backoff("PUT", upload_url, data=fileobj)
  277. hf_raise_for_status(response)
  278. def _upload_multi_part(operation: "CommitOperationAdd", header: Dict, chunk_size: int, upload_url: str) -> None:
  279. """
  280. Uploads file using HF multipart LFS transfer protocol.
  281. """
  282. # 1. Get upload URLs for each part
  283. sorted_parts_urls = _get_sorted_parts_urls(header=header, upload_info=operation.upload_info, chunk_size=chunk_size)
  284. # 2. Upload parts (either with hf_transfer or in pure Python)
  285. use_hf_transfer = constants.HF_HUB_ENABLE_HF_TRANSFER
  286. if (
  287. constants.HF_HUB_ENABLE_HF_TRANSFER
  288. and not isinstance(operation.path_or_fileobj, str)
  289. and not isinstance(operation.path_or_fileobj, Path)
  290. ):
  291. warnings.warn(
  292. "hf_transfer is enabled but does not support uploading from bytes or BinaryIO, falling back to regular"
  293. " upload"
  294. )
  295. use_hf_transfer = False
  296. response_headers = (
  297. _upload_parts_hf_transfer(operation=operation, sorted_parts_urls=sorted_parts_urls, chunk_size=chunk_size)
  298. if use_hf_transfer
  299. else _upload_parts_iteratively(operation=operation, sorted_parts_urls=sorted_parts_urls, chunk_size=chunk_size)
  300. )
  301. # 3. Send completion request
  302. completion_res = get_session().post(
  303. upload_url,
  304. json=_get_completion_payload(response_headers, operation.upload_info.sha256.hex()),
  305. headers=LFS_HEADERS,
  306. )
  307. hf_raise_for_status(completion_res)
  308. def _get_sorted_parts_urls(header: Dict, upload_info: UploadInfo, chunk_size: int) -> List[str]:
  309. sorted_part_upload_urls = [
  310. upload_url
  311. for _, upload_url in sorted(
  312. [
  313. (int(part_num, 10), upload_url)
  314. for part_num, upload_url in header.items()
  315. if part_num.isdigit() and len(part_num) > 0
  316. ],
  317. key=lambda t: t[0],
  318. )
  319. ]
  320. num_parts = len(sorted_part_upload_urls)
  321. if num_parts != ceil(upload_info.size / chunk_size):
  322. raise ValueError("Invalid server response to upload large LFS file")
  323. return sorted_part_upload_urls
  324. def _get_completion_payload(response_headers: List[Dict], oid: str) -> CompletionPayloadT:
  325. parts: List[PayloadPartT] = []
  326. for part_number, header in enumerate(response_headers):
  327. etag = header.get("etag")
  328. if etag is None or etag == "":
  329. raise ValueError(f"Invalid etag (`{etag}`) returned for part {part_number + 1}")
  330. parts.append(
  331. {
  332. "partNumber": part_number + 1,
  333. "etag": etag,
  334. }
  335. )
  336. return {"oid": oid, "parts": parts}
  337. def _upload_parts_iteratively(
  338. operation: "CommitOperationAdd", sorted_parts_urls: List[str], chunk_size: int
  339. ) -> List[Dict]:
  340. headers = []
  341. with operation.as_file(with_tqdm=True) as fileobj:
  342. for part_idx, part_upload_url in enumerate(sorted_parts_urls):
  343. with SliceFileObj(
  344. fileobj,
  345. seek_from=chunk_size * part_idx,
  346. read_limit=chunk_size,
  347. ) as fileobj_slice:
  348. # S3 might raise a transient 500 error -> let's retry if that happens
  349. part_upload_res = http_backoff("PUT", part_upload_url, data=fileobj_slice)
  350. hf_raise_for_status(part_upload_res)
  351. headers.append(part_upload_res.headers)
  352. return headers # type: ignore
  353. def _upload_parts_hf_transfer(
  354. operation: "CommitOperationAdd", sorted_parts_urls: List[str], chunk_size: int
  355. ) -> List[Dict]:
  356. # Upload file using an external Rust-based package. Upload is faster but support less features (no progress bars).
  357. try:
  358. from hf_transfer import multipart_upload
  359. except ImportError:
  360. raise ValueError(
  361. "Fast uploading using 'hf_transfer' is enabled (HF_HUB_ENABLE_HF_TRANSFER=1) but 'hf_transfer' package is"
  362. " not available in your environment. Try `pip install hf_transfer`."
  363. )
  364. supports_callback = "callback" in inspect.signature(multipart_upload).parameters
  365. if not supports_callback:
  366. warnings.warn(
  367. "You are using an outdated version of `hf_transfer`. Consider upgrading to latest version to enable progress bars using `pip install -U hf_transfer`."
  368. )
  369. total = operation.upload_info.size
  370. desc = operation.path_in_repo
  371. if len(desc) > 40:
  372. desc = f"(…){desc[-40:]}"
  373. with tqdm(
  374. unit="B",
  375. unit_scale=True,
  376. total=total,
  377. initial=0,
  378. desc=desc,
  379. disable=is_tqdm_disabled(logger.getEffectiveLevel()),
  380. name="huggingface_hub.lfs_upload",
  381. ) as progress:
  382. try:
  383. output = multipart_upload(
  384. file_path=operation.path_or_fileobj,
  385. parts_urls=sorted_parts_urls,
  386. chunk_size=chunk_size,
  387. max_files=128,
  388. parallel_failures=127, # could be removed
  389. max_retries=5,
  390. **({"callback": progress.update} if supports_callback else {}),
  391. )
  392. except Exception as e:
  393. raise RuntimeError(
  394. "An error occurred while uploading using `hf_transfer`. Consider disabling HF_HUB_ENABLE_HF_TRANSFER for"
  395. " better error handling."
  396. ) from e
  397. if not supports_callback:
  398. progress.update(total)
  399. return output