lfs.py 14 KB

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