hf_file_system.py 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150
  1. import os
  2. import re
  3. import tempfile
  4. from collections import deque
  5. from dataclasses import dataclass, field
  6. from datetime import datetime
  7. from itertools import chain
  8. from pathlib import Path
  9. from typing import Any, Dict, Iterator, List, NoReturn, Optional, Tuple, Union
  10. from urllib.parse import quote, unquote
  11. import fsspec
  12. from fsspec.callbacks import _DEFAULT_CALLBACK, NoOpCallback, TqdmCallback
  13. from fsspec.utils import isfilelike
  14. from requests import Response
  15. from . import constants
  16. from ._commit_api import CommitOperationCopy, CommitOperationDelete
  17. from .errors import EntryNotFoundError, RepositoryNotFoundError, RevisionNotFoundError
  18. from .file_download import hf_hub_url, http_get
  19. from .hf_api import HfApi, LastCommitInfo, RepoFile
  20. from .utils import HFValidationError, hf_raise_for_status, http_backoff
  21. # Regex used to match special revisions with "/" in them (see #1710)
  22. SPECIAL_REFS_REVISION_REGEX = re.compile(
  23. r"""
  24. (^refs\/convert\/\w+) # `refs/convert/parquet` revisions
  25. |
  26. (^refs\/pr\/\d+) # PR revisions
  27. """,
  28. re.VERBOSE,
  29. )
  30. @dataclass
  31. class HfFileSystemResolvedPath:
  32. """Data structure containing information about a resolved Hugging Face file system path."""
  33. repo_type: str
  34. repo_id: str
  35. revision: str
  36. path_in_repo: str
  37. # The part placed after '@' in the initial path. It can be a quoted or unquoted refs revision.
  38. # Used to reconstruct the unresolved path to return to the user.
  39. _raw_revision: Optional[str] = field(default=None, repr=False)
  40. def unresolve(self) -> str:
  41. repo_path = constants.REPO_TYPES_URL_PREFIXES.get(self.repo_type, "") + self.repo_id
  42. if self._raw_revision:
  43. return f"{repo_path}@{self._raw_revision}/{self.path_in_repo}".rstrip("/")
  44. elif self.revision != constants.DEFAULT_REVISION:
  45. return f"{repo_path}@{safe_revision(self.revision)}/{self.path_in_repo}".rstrip("/")
  46. else:
  47. return f"{repo_path}/{self.path_in_repo}".rstrip("/")
  48. class HfFileSystem(fsspec.AbstractFileSystem):
  49. """
  50. Access a remote Hugging Face Hub repository as if were a local file system.
  51. > [!WARNING]
  52. > [`HfFileSystem`] provides fsspec compatibility, which is useful for libraries that require it (e.g., reading
  53. > Hugging Face datasets directly with `pandas`). However, it introduces additional overhead due to this compatibility
  54. > layer. For better performance and reliability, it's recommended to use `HfApi` methods when possible.
  55. Args:
  56. token (`str` or `bool`, *optional*):
  57. A valid user access token (string). Defaults to the locally saved
  58. token, which is the recommended method for authentication (see
  59. https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
  60. To disable authentication, pass `False`.
  61. endpoint (`str`, *optional*):
  62. Endpoint of the Hub. Defaults to <https://huggingface.co>.
  63. Usage:
  64. ```python
  65. >>> from huggingface_hub import HfFileSystem
  66. >>> fs = HfFileSystem()
  67. >>> # List files
  68. >>> fs.glob("my-username/my-model/*.bin")
  69. ['my-username/my-model/pytorch_model.bin']
  70. >>> fs.ls("datasets/my-username/my-dataset", detail=False)
  71. ['datasets/my-username/my-dataset/.gitattributes', 'datasets/my-username/my-dataset/README.md', 'datasets/my-username/my-dataset/data.json']
  72. >>> # Read/write files
  73. >>> with fs.open("my-username/my-model/pytorch_model.bin") as f:
  74. ... data = f.read()
  75. >>> with fs.open("my-username/my-model/pytorch_model.bin", "wb") as f:
  76. ... f.write(data)
  77. ```
  78. """
  79. root_marker = ""
  80. protocol = "hf"
  81. def __init__(
  82. self,
  83. *args,
  84. endpoint: Optional[str] = None,
  85. token: Union[bool, str, None] = None,
  86. block_size: Optional[int] = None,
  87. **storage_options,
  88. ):
  89. super().__init__(*args, **storage_options)
  90. self.endpoint = endpoint or constants.ENDPOINT
  91. self.token = token
  92. self._api = HfApi(endpoint=endpoint, token=token)
  93. self.block_size = block_size
  94. # Maps (repo_type, repo_id, revision) to a 2-tuple with:
  95. # * the 1st element indicating whether the repositoy and the revision exist
  96. # * the 2nd element being the exception raised if the repository or revision doesn't exist
  97. self._repo_and_revision_exists_cache: Dict[
  98. Tuple[str, str, Optional[str]], Tuple[bool, Optional[Exception]]
  99. ] = {}
  100. # Maps parent directory path to path infos
  101. self.dircache: Dict[str, List[Dict[str, Any]]] = {}
  102. def _repo_and_revision_exist(
  103. self, repo_type: str, repo_id: str, revision: Optional[str]
  104. ) -> Tuple[bool, Optional[Exception]]:
  105. if (repo_type, repo_id, revision) not in self._repo_and_revision_exists_cache:
  106. try:
  107. self._api.repo_info(
  108. repo_id, revision=revision, repo_type=repo_type, timeout=constants.HF_HUB_ETAG_TIMEOUT
  109. )
  110. except (RepositoryNotFoundError, HFValidationError) as e:
  111. self._repo_and_revision_exists_cache[(repo_type, repo_id, revision)] = False, e
  112. self._repo_and_revision_exists_cache[(repo_type, repo_id, None)] = False, e
  113. except RevisionNotFoundError as e:
  114. self._repo_and_revision_exists_cache[(repo_type, repo_id, revision)] = False, e
  115. self._repo_and_revision_exists_cache[(repo_type, repo_id, None)] = True, None
  116. else:
  117. self._repo_and_revision_exists_cache[(repo_type, repo_id, revision)] = True, None
  118. self._repo_and_revision_exists_cache[(repo_type, repo_id, None)] = True, None
  119. return self._repo_and_revision_exists_cache[(repo_type, repo_id, revision)]
  120. def resolve_path(self, path: str, revision: Optional[str] = None) -> HfFileSystemResolvedPath:
  121. """
  122. Resolve a Hugging Face file system path into its components.
  123. Args:
  124. path (`str`):
  125. Path to resolve.
  126. revision (`str`, *optional*):
  127. The revision of the repo to resolve. Defaults to the revision specified in the path.
  128. Returns:
  129. [`HfFileSystemResolvedPath`]: Resolved path information containing `repo_type`, `repo_id`, `revision` and `path_in_repo`.
  130. Raises:
  131. `ValueError`:
  132. If path contains conflicting revision information.
  133. `NotImplementedError`:
  134. If trying to list repositories.
  135. """
  136. def _align_revision_in_path_with_revision(
  137. revision_in_path: Optional[str], revision: Optional[str]
  138. ) -> Optional[str]:
  139. if revision is not None:
  140. if revision_in_path is not None and revision_in_path != revision:
  141. raise ValueError(
  142. f'Revision specified in path ("{revision_in_path}") and in `revision` argument ("{revision}")'
  143. " are not the same."
  144. )
  145. else:
  146. revision = revision_in_path
  147. return revision
  148. path = self._strip_protocol(path)
  149. if not path:
  150. # can't list repositories at root
  151. raise NotImplementedError("Access to repositories lists is not implemented.")
  152. elif path.split("/")[0] + "/" in constants.REPO_TYPES_URL_PREFIXES.values():
  153. if "/" not in path:
  154. # can't list repositories at the repository type level
  155. raise NotImplementedError("Access to repositories lists is not implemented.")
  156. repo_type, path = path.split("/", 1)
  157. repo_type = constants.REPO_TYPES_MAPPING[repo_type]
  158. else:
  159. repo_type = constants.REPO_TYPE_MODEL
  160. if path.count("/") > 0:
  161. if "@" in path:
  162. repo_id, revision_in_path = path.split("@", 1)
  163. if "/" in revision_in_path:
  164. match = SPECIAL_REFS_REVISION_REGEX.search(revision_in_path)
  165. if match is not None and revision in (None, match.group()):
  166. # Handle `refs/convert/parquet` and PR revisions separately
  167. path_in_repo = SPECIAL_REFS_REVISION_REGEX.sub("", revision_in_path).lstrip("/")
  168. revision_in_path = match.group()
  169. else:
  170. revision_in_path, path_in_repo = revision_in_path.split("/", 1)
  171. else:
  172. path_in_repo = ""
  173. revision = _align_revision_in_path_with_revision(unquote(revision_in_path), revision)
  174. repo_and_revision_exist, err = self._repo_and_revision_exist(repo_type, repo_id, revision)
  175. if not repo_and_revision_exist:
  176. _raise_file_not_found(path, err)
  177. else:
  178. revision_in_path = None
  179. repo_id_with_namespace = "/".join(path.split("/")[:2])
  180. path_in_repo_with_namespace = "/".join(path.split("/")[2:])
  181. repo_id_without_namespace = path.split("/")[0]
  182. path_in_repo_without_namespace = "/".join(path.split("/")[1:])
  183. repo_id = repo_id_with_namespace
  184. path_in_repo = path_in_repo_with_namespace
  185. repo_and_revision_exist, err = self._repo_and_revision_exist(repo_type, repo_id, revision)
  186. if not repo_and_revision_exist:
  187. if isinstance(err, (RepositoryNotFoundError, HFValidationError)):
  188. repo_id = repo_id_without_namespace
  189. path_in_repo = path_in_repo_without_namespace
  190. repo_and_revision_exist, _ = self._repo_and_revision_exist(repo_type, repo_id, revision)
  191. if not repo_and_revision_exist:
  192. _raise_file_not_found(path, err)
  193. else:
  194. _raise_file_not_found(path, err)
  195. else:
  196. repo_id = path
  197. path_in_repo = ""
  198. if "@" in path:
  199. repo_id, revision_in_path = path.split("@", 1)
  200. revision = _align_revision_in_path_with_revision(unquote(revision_in_path), revision)
  201. else:
  202. revision_in_path = None
  203. repo_and_revision_exist, _ = self._repo_and_revision_exist(repo_type, repo_id, revision)
  204. if not repo_and_revision_exist:
  205. raise NotImplementedError("Access to repositories lists is not implemented.")
  206. revision = revision if revision is not None else constants.DEFAULT_REVISION
  207. return HfFileSystemResolvedPath(repo_type, repo_id, revision, path_in_repo, _raw_revision=revision_in_path)
  208. def invalidate_cache(self, path: Optional[str] = None) -> None:
  209. """
  210. Clear the cache for a given path.
  211. For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.invalidate_cache).
  212. Args:
  213. path (`str`, *optional*):
  214. Path to clear from cache. If not provided, clear the entire cache.
  215. """
  216. if not path:
  217. self.dircache.clear()
  218. self._repo_and_revision_exists_cache.clear()
  219. else:
  220. resolved_path = self.resolve_path(path)
  221. path = resolved_path.unresolve()
  222. while path:
  223. self.dircache.pop(path, None)
  224. path = self._parent(path)
  225. # Only clear repo cache if path is to repo root
  226. if not resolved_path.path_in_repo:
  227. self._repo_and_revision_exists_cache.pop((resolved_path.repo_type, resolved_path.repo_id, None), None)
  228. self._repo_and_revision_exists_cache.pop(
  229. (resolved_path.repo_type, resolved_path.repo_id, resolved_path.revision), None
  230. )
  231. def _open(
  232. self,
  233. path: str,
  234. mode: str = "rb",
  235. revision: Optional[str] = None,
  236. block_size: Optional[int] = None,
  237. **kwargs,
  238. ) -> "HfFileSystemFile":
  239. block_size = block_size if block_size is not None else self.block_size
  240. if block_size is not None:
  241. kwargs["block_size"] = block_size
  242. if "a" in mode:
  243. raise NotImplementedError("Appending to remote files is not yet supported.")
  244. if block_size == 0:
  245. return HfFileSystemStreamFile(self, path, mode=mode, revision=revision, **kwargs)
  246. else:
  247. return HfFileSystemFile(self, path, mode=mode, revision=revision, **kwargs)
  248. def _rm(self, path: str, revision: Optional[str] = None, **kwargs) -> None:
  249. resolved_path = self.resolve_path(path, revision=revision)
  250. self._api.delete_file(
  251. path_in_repo=resolved_path.path_in_repo,
  252. repo_id=resolved_path.repo_id,
  253. token=self.token,
  254. repo_type=resolved_path.repo_type,
  255. revision=resolved_path.revision,
  256. commit_message=kwargs.get("commit_message"),
  257. commit_description=kwargs.get("commit_description"),
  258. )
  259. self.invalidate_cache(path=resolved_path.unresolve())
  260. def rm(
  261. self,
  262. path: str,
  263. recursive: bool = False,
  264. maxdepth: Optional[int] = None,
  265. revision: Optional[str] = None,
  266. **kwargs,
  267. ) -> None:
  268. """
  269. Delete files from a repository.
  270. For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.rm).
  271. > [!WARNING]
  272. > Note: When possible, use `HfApi.delete_file()` for better performance.
  273. Args:
  274. path (`str`):
  275. Path to delete.
  276. recursive (`bool`, *optional*):
  277. If True, delete directory and all its contents. Defaults to False.
  278. maxdepth (`int`, *optional*):
  279. Maximum number of subdirectories to visit when deleting recursively.
  280. revision (`str`, *optional*):
  281. The git revision to delete from.
  282. """
  283. resolved_path = self.resolve_path(path, revision=revision)
  284. paths = self.expand_path(path, recursive=recursive, maxdepth=maxdepth, revision=revision)
  285. paths_in_repo = [self.resolve_path(path).path_in_repo for path in paths if not self.isdir(path)]
  286. operations = [CommitOperationDelete(path_in_repo=path_in_repo) for path_in_repo in paths_in_repo]
  287. commit_message = f"Delete {path} "
  288. commit_message += "recursively " if recursive else ""
  289. commit_message += f"up to depth {maxdepth} " if maxdepth is not None else ""
  290. # TODO: use `commit_description` to list all the deleted paths?
  291. self._api.create_commit(
  292. repo_id=resolved_path.repo_id,
  293. repo_type=resolved_path.repo_type,
  294. token=self.token,
  295. operations=operations,
  296. revision=resolved_path.revision,
  297. commit_message=kwargs.get("commit_message", commit_message),
  298. commit_description=kwargs.get("commit_description"),
  299. )
  300. self.invalidate_cache(path=resolved_path.unresolve())
  301. def ls(
  302. self, path: str, detail: bool = True, refresh: bool = False, revision: Optional[str] = None, **kwargs
  303. ) -> List[Union[str, Dict[str, Any]]]:
  304. """
  305. List the contents of a directory.
  306. For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.ls).
  307. > [!WARNING]
  308. > Note: When possible, use `HfApi.list_repo_tree()` for better performance.
  309. Args:
  310. path (`str`):
  311. Path to the directory.
  312. detail (`bool`, *optional*):
  313. If True, returns a list of dictionaries containing file information. If False,
  314. returns a list of file paths. Defaults to True.
  315. refresh (`bool`, *optional*):
  316. If True, bypass the cache and fetch the latest data. Defaults to False.
  317. revision (`str`, *optional*):
  318. The git revision to list from.
  319. Returns:
  320. `List[Union[str, Dict[str, Any]]]`: List of file paths (if detail=False) or list of file information
  321. dictionaries (if detail=True).
  322. """
  323. resolved_path = self.resolve_path(path, revision=revision)
  324. path = resolved_path.unresolve()
  325. try:
  326. out = self._ls_tree(path, refresh=refresh, revision=revision, **kwargs)
  327. except EntryNotFoundError:
  328. # Path could be a file
  329. if not resolved_path.path_in_repo:
  330. _raise_file_not_found(path, None)
  331. out = self._ls_tree(self._parent(path), refresh=refresh, revision=revision, **kwargs)
  332. out = [o for o in out if o["name"] == path]
  333. if len(out) == 0:
  334. _raise_file_not_found(path, None)
  335. return out if detail else [o["name"] for o in out]
  336. def _ls_tree(
  337. self,
  338. path: str,
  339. recursive: bool = False,
  340. refresh: bool = False,
  341. revision: Optional[str] = None,
  342. expand_info: bool = False,
  343. maxdepth: Optional[int] = None,
  344. ):
  345. resolved_path = self.resolve_path(path, revision=revision)
  346. path = resolved_path.unresolve()
  347. root_path = HfFileSystemResolvedPath(
  348. resolved_path.repo_type,
  349. resolved_path.repo_id,
  350. resolved_path.revision,
  351. path_in_repo="",
  352. _raw_revision=resolved_path._raw_revision,
  353. ).unresolve()
  354. out = []
  355. if path in self.dircache and not refresh:
  356. cached_path_infos = self.dircache[path]
  357. out.extend(cached_path_infos)
  358. dirs_not_in_dircache = []
  359. if recursive:
  360. # Use BFS to traverse the cache and build the "recursive "output
  361. # (The Hub uses a so-called "tree first" strategy for the tree endpoint but we sort the output to follow the spec so the result is (eventually) the same)
  362. depth = 2
  363. dirs_to_visit = deque(
  364. [(depth, path_info) for path_info in cached_path_infos if path_info["type"] == "directory"]
  365. )
  366. while dirs_to_visit:
  367. depth, dir_info = dirs_to_visit.popleft()
  368. if maxdepth is None or depth <= maxdepth:
  369. if dir_info["name"] not in self.dircache:
  370. dirs_not_in_dircache.append(dir_info["name"])
  371. else:
  372. cached_path_infos = self.dircache[dir_info["name"]]
  373. out.extend(cached_path_infos)
  374. dirs_to_visit.extend(
  375. [
  376. (depth + 1, path_info)
  377. for path_info in cached_path_infos
  378. if path_info["type"] == "directory"
  379. ]
  380. )
  381. dirs_not_expanded = []
  382. if expand_info:
  383. # Check if there are directories with non-expanded entries
  384. dirs_not_expanded = [self._parent(o["name"]) for o in out if o["last_commit"] is None]
  385. if (recursive and dirs_not_in_dircache) or (expand_info and dirs_not_expanded):
  386. # If the dircache is incomplete, find the common path of the missing and non-expanded entries
  387. # and extend the output with the result of `_ls_tree(common_path, recursive=True)`
  388. common_prefix = os.path.commonprefix(dirs_not_in_dircache + dirs_not_expanded)
  389. # Get the parent directory if the common prefix itself is not a directory
  390. common_path = (
  391. common_prefix.rstrip("/")
  392. if common_prefix.endswith("/")
  393. or common_prefix == root_path
  394. or common_prefix in chain(dirs_not_in_dircache, dirs_not_expanded)
  395. else self._parent(common_prefix)
  396. )
  397. if maxdepth is not None:
  398. common_path_depth = common_path[len(path) :].count("/")
  399. maxdepth -= common_path_depth
  400. out = [o for o in out if not o["name"].startswith(common_path + "/")]
  401. for cached_path in list(self.dircache):
  402. if cached_path.startswith(common_path + "/"):
  403. self.dircache.pop(cached_path, None)
  404. self.dircache.pop(common_path, None)
  405. out.extend(
  406. self._ls_tree(
  407. common_path,
  408. recursive=recursive,
  409. refresh=True,
  410. revision=revision,
  411. expand_info=expand_info,
  412. maxdepth=maxdepth,
  413. )
  414. )
  415. else:
  416. tree = self._api.list_repo_tree(
  417. resolved_path.repo_id,
  418. resolved_path.path_in_repo,
  419. recursive=recursive,
  420. expand=expand_info,
  421. revision=resolved_path.revision,
  422. repo_type=resolved_path.repo_type,
  423. )
  424. for path_info in tree:
  425. cache_path = root_path + "/" + path_info.path
  426. if isinstance(path_info, RepoFile):
  427. cache_path_info = {
  428. "name": cache_path,
  429. "size": path_info.size,
  430. "type": "file",
  431. "blob_id": path_info.blob_id,
  432. "lfs": path_info.lfs,
  433. "last_commit": path_info.last_commit,
  434. "security": path_info.security,
  435. }
  436. else:
  437. cache_path_info = {
  438. "name": cache_path,
  439. "size": 0,
  440. "type": "directory",
  441. "tree_id": path_info.tree_id,
  442. "last_commit": path_info.last_commit,
  443. }
  444. parent_path = self._parent(cache_path_info["name"])
  445. self.dircache.setdefault(parent_path, []).append(cache_path_info)
  446. depth = cache_path[len(path) :].count("/")
  447. if maxdepth is None or depth <= maxdepth:
  448. out.append(cache_path_info)
  449. return out
  450. def walk(self, path: str, *args, **kwargs) -> Iterator[Tuple[str, List[str], List[str]]]:
  451. """
  452. Return all files below the given path.
  453. For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.walk).
  454. Args:
  455. path (`str`):
  456. Root path to list files from.
  457. Returns:
  458. `Iterator[Tuple[str, List[str], List[str]]]`: An iterator of (path, list of directory names, list of file names) tuples.
  459. """
  460. path = self.resolve_path(path, revision=kwargs.get("revision")).unresolve()
  461. yield from super().walk(path, *args, **kwargs)
  462. def glob(self, path: str, **kwargs) -> List[str]:
  463. """
  464. Find files by glob-matching.
  465. For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.glob).
  466. Args:
  467. path (`str`):
  468. Path pattern to match.
  469. Returns:
  470. `List[str]`: List of paths matching the pattern.
  471. """
  472. path = self.resolve_path(path, revision=kwargs.get("revision")).unresolve()
  473. return super().glob(path, **kwargs)
  474. def find(
  475. self,
  476. path: str,
  477. maxdepth: Optional[int] = None,
  478. withdirs: bool = False,
  479. detail: bool = False,
  480. refresh: bool = False,
  481. revision: Optional[str] = None,
  482. **kwargs,
  483. ) -> Union[List[str], Dict[str, Dict[str, Any]]]:
  484. """
  485. List all files below path.
  486. For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.find).
  487. Args:
  488. path (`str`):
  489. Root path to list files from.
  490. maxdepth (`int`, *optional*):
  491. Maximum depth to descend into subdirectories.
  492. withdirs (`bool`, *optional*):
  493. Include directory paths in the output. Defaults to False.
  494. detail (`bool`, *optional*):
  495. If True, returns a dict mapping paths to file information. Defaults to False.
  496. refresh (`bool`, *optional*):
  497. If True, bypass the cache and fetch the latest data. Defaults to False.
  498. revision (`str`, *optional*):
  499. The git revision to list from.
  500. Returns:
  501. `Union[List[str], Dict[str, Dict[str, Any]]]`: List of paths or dict of file information.
  502. """
  503. if maxdepth is not None and maxdepth < 1:
  504. raise ValueError("maxdepth must be at least 1")
  505. resolved_path = self.resolve_path(path, revision=revision)
  506. path = resolved_path.unresolve()
  507. try:
  508. out = self._ls_tree(
  509. path, recursive=True, refresh=refresh, revision=resolved_path.revision, maxdepth=maxdepth, **kwargs
  510. )
  511. except EntryNotFoundError:
  512. # Path could be a file
  513. try:
  514. if self.info(path, revision=revision, **kwargs)["type"] == "file":
  515. out = {path: {}}
  516. else:
  517. out = {}
  518. except FileNotFoundError:
  519. out = {}
  520. else:
  521. if not withdirs:
  522. out = [o for o in out if o["type"] != "directory"]
  523. else:
  524. # If `withdirs=True`, include the directory itself to be consistent with the spec
  525. path_info = self.info(path, revision=resolved_path.revision, **kwargs)
  526. out = [path_info] + out if path_info["type"] == "directory" else out
  527. out = {o["name"]: o for o in out}
  528. names = sorted(out)
  529. if not detail:
  530. return names
  531. else:
  532. return {name: out[name] for name in names}
  533. def cp_file(self, path1: str, path2: str, revision: Optional[str] = None, **kwargs) -> None:
  534. """
  535. Copy a file within or between repositories.
  536. > [!WARNING]
  537. > Note: When possible, use `HfApi.upload_file()` for better performance.
  538. Args:
  539. path1 (`str`):
  540. Source path to copy from.
  541. path2 (`str`):
  542. Destination path to copy to.
  543. revision (`str`, *optional*):
  544. The git revision to copy from.
  545. """
  546. resolved_path1 = self.resolve_path(path1, revision=revision)
  547. resolved_path2 = self.resolve_path(path2, revision=revision)
  548. same_repo = (
  549. resolved_path1.repo_type == resolved_path2.repo_type and resolved_path1.repo_id == resolved_path2.repo_id
  550. )
  551. if same_repo:
  552. commit_message = f"Copy {path1} to {path2}"
  553. self._api.create_commit(
  554. repo_id=resolved_path1.repo_id,
  555. repo_type=resolved_path1.repo_type,
  556. revision=resolved_path2.revision,
  557. commit_message=kwargs.get("commit_message", commit_message),
  558. commit_description=kwargs.get("commit_description", ""),
  559. operations=[
  560. CommitOperationCopy(
  561. src_path_in_repo=resolved_path1.path_in_repo,
  562. path_in_repo=resolved_path2.path_in_repo,
  563. src_revision=resolved_path1.revision,
  564. )
  565. ],
  566. )
  567. else:
  568. with self.open(path1, "rb", revision=resolved_path1.revision) as f:
  569. content = f.read()
  570. commit_message = f"Copy {path1} to {path2}"
  571. self._api.upload_file(
  572. path_or_fileobj=content,
  573. path_in_repo=resolved_path2.path_in_repo,
  574. repo_id=resolved_path2.repo_id,
  575. token=self.token,
  576. repo_type=resolved_path2.repo_type,
  577. revision=resolved_path2.revision,
  578. commit_message=kwargs.get("commit_message", commit_message),
  579. commit_description=kwargs.get("commit_description"),
  580. )
  581. self.invalidate_cache(path=resolved_path1.unresolve())
  582. self.invalidate_cache(path=resolved_path2.unresolve())
  583. def modified(self, path: str, **kwargs) -> datetime:
  584. """
  585. Get the last modified time of a file.
  586. For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.modified).
  587. Args:
  588. path (`str`):
  589. Path to the file.
  590. Returns:
  591. `datetime`: Last commit date of the file.
  592. """
  593. info = self.info(path, **{**kwargs, "expand_info": True})
  594. return info["last_commit"]["date"]
  595. def info(self, path: str, refresh: bool = False, revision: Optional[str] = None, **kwargs) -> Dict[str, Any]:
  596. """
  597. Get information about a file or directory.
  598. For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.info).
  599. > [!WARNING]
  600. > Note: When possible, use `HfApi.get_paths_info()` or `HfApi.repo_info()` for better performance.
  601. Args:
  602. path (`str`):
  603. Path to get info for.
  604. refresh (`bool`, *optional*):
  605. If True, bypass the cache and fetch the latest data. Defaults to False.
  606. revision (`str`, *optional*):
  607. The git revision to get info from.
  608. Returns:
  609. `Dict[str, Any]`: Dictionary containing file information (type, size, commit info, etc.).
  610. """
  611. resolved_path = self.resolve_path(path, revision=revision)
  612. path = resolved_path.unresolve()
  613. expand_info = kwargs.get(
  614. "expand_info", False
  615. ) # don't expose it as a parameter in the public API to follow the spec
  616. if not resolved_path.path_in_repo:
  617. # Path is the root directory
  618. out = {
  619. "name": path,
  620. "size": 0,
  621. "type": "directory",
  622. "last_commit": None,
  623. }
  624. if expand_info:
  625. last_commit = self._api.list_repo_commits(
  626. resolved_path.repo_id, repo_type=resolved_path.repo_type, revision=resolved_path.revision
  627. )[-1]
  628. out = {
  629. **out,
  630. "tree_id": None, # TODO: tree_id of the root directory?
  631. "last_commit": LastCommitInfo(
  632. oid=last_commit.commit_id, title=last_commit.title, date=last_commit.created_at
  633. ),
  634. }
  635. else:
  636. out = None
  637. parent_path = self._parent(path)
  638. if not expand_info and parent_path not in self.dircache:
  639. # Fill the cache with cheap call
  640. self.ls(parent_path)
  641. if parent_path in self.dircache:
  642. # Check if the path is in the cache
  643. out1 = [o for o in self.dircache[parent_path] if o["name"] == path]
  644. if not out1:
  645. _raise_file_not_found(path, None)
  646. out = out1[0]
  647. if refresh or out is None or (expand_info and out and out["last_commit"] is None):
  648. paths_info = self._api.get_paths_info(
  649. resolved_path.repo_id,
  650. resolved_path.path_in_repo,
  651. expand=expand_info,
  652. revision=resolved_path.revision,
  653. repo_type=resolved_path.repo_type,
  654. )
  655. if not paths_info:
  656. _raise_file_not_found(path, None)
  657. path_info = paths_info[0]
  658. root_path = HfFileSystemResolvedPath(
  659. resolved_path.repo_type,
  660. resolved_path.repo_id,
  661. resolved_path.revision,
  662. path_in_repo="",
  663. _raw_revision=resolved_path._raw_revision,
  664. ).unresolve()
  665. if isinstance(path_info, RepoFile):
  666. out = {
  667. "name": root_path + "/" + path_info.path,
  668. "size": path_info.size,
  669. "type": "file",
  670. "blob_id": path_info.blob_id,
  671. "lfs": path_info.lfs,
  672. "last_commit": path_info.last_commit,
  673. "security": path_info.security,
  674. }
  675. else:
  676. out = {
  677. "name": root_path + "/" + path_info.path,
  678. "size": 0,
  679. "type": "directory",
  680. "tree_id": path_info.tree_id,
  681. "last_commit": path_info.last_commit,
  682. }
  683. if not expand_info:
  684. out = {k: out[k] for k in ["name", "size", "type"]}
  685. assert out is not None
  686. return out
  687. def exists(self, path, **kwargs):
  688. """
  689. Check if a file exists.
  690. For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.exists).
  691. > [!WARNING]
  692. > Note: When possible, use `HfApi.file_exists()` for better performance.
  693. Args:
  694. path (`str`):
  695. Path to check.
  696. Returns:
  697. `bool`: True if file exists, False otherwise.
  698. """
  699. try:
  700. if kwargs.get("refresh", False):
  701. self.invalidate_cache(path)
  702. self.info(path, **kwargs)
  703. return True
  704. except: # noqa: E722
  705. return False
  706. def isdir(self, path):
  707. """
  708. Check if a path is a directory.
  709. For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.isdir).
  710. Args:
  711. path (`str`):
  712. Path to check.
  713. Returns:
  714. `bool`: True if path is a directory, False otherwise.
  715. """
  716. try:
  717. return self.info(path)["type"] == "directory"
  718. except OSError:
  719. return False
  720. def isfile(self, path):
  721. """
  722. Check if a path is a file.
  723. For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.isfile).
  724. Args:
  725. path (`str`):
  726. Path to check.
  727. Returns:
  728. `bool`: True if path is a file, False otherwise.
  729. """
  730. try:
  731. return self.info(path)["type"] == "file"
  732. except: # noqa: E722
  733. return False
  734. def url(self, path: str) -> str:
  735. """
  736. Get the HTTP URL of the given path.
  737. Args:
  738. path (`str`):
  739. Path to get URL for.
  740. Returns:
  741. `str`: HTTP URL to access the file or directory on the Hub.
  742. """
  743. resolved_path = self.resolve_path(path)
  744. url = hf_hub_url(
  745. resolved_path.repo_id,
  746. resolved_path.path_in_repo,
  747. repo_type=resolved_path.repo_type,
  748. revision=resolved_path.revision,
  749. endpoint=self.endpoint,
  750. )
  751. if self.isdir(path):
  752. url = url.replace("/resolve/", "/tree/", 1)
  753. return url
  754. def get_file(self, rpath, lpath, callback=_DEFAULT_CALLBACK, outfile=None, **kwargs) -> None:
  755. """
  756. Copy single remote file to local.
  757. > [!WARNING]
  758. > Note: When possible, use `HfApi.hf_hub_download()` for better performance.
  759. Args:
  760. rpath (`str`):
  761. Remote path to download from.
  762. lpath (`str`):
  763. Local path to download to.
  764. callback (`Callback`, *optional*):
  765. Optional callback to track download progress. Defaults to no callback.
  766. outfile (`IO`, *optional*):
  767. Optional file-like object to write to. If provided, `lpath` is ignored.
  768. """
  769. revision = kwargs.get("revision")
  770. unhandled_kwargs = set(kwargs.keys()) - {"revision"}
  771. if not isinstance(callback, (NoOpCallback, TqdmCallback)) or len(unhandled_kwargs) > 0:
  772. # for now, let's not handle custom callbacks
  773. # and let's not handle custom kwargs
  774. return super().get_file(rpath, lpath, callback=callback, outfile=outfile, **kwargs)
  775. # Taken from https://github.com/fsspec/filesystem_spec/blob/47b445ae4c284a82dd15e0287b1ffc410e8fc470/fsspec/spec.py#L883
  776. if isfilelike(lpath):
  777. outfile = lpath
  778. elif self.isdir(rpath):
  779. os.makedirs(lpath, exist_ok=True)
  780. return None
  781. if isinstance(lpath, (str, Path)): # otherwise, let's assume it's a file-like object
  782. os.makedirs(os.path.dirname(lpath), exist_ok=True)
  783. # Open file if not already open
  784. close_file = False
  785. if outfile is None:
  786. outfile = open(lpath, "wb")
  787. close_file = True
  788. initial_pos = outfile.tell()
  789. # Custom implementation of `get_file` to use `http_get`.
  790. resolve_remote_path = self.resolve_path(rpath, revision=revision)
  791. expected_size = self.info(rpath, revision=revision)["size"]
  792. callback.set_size(expected_size)
  793. try:
  794. http_get(
  795. url=hf_hub_url(
  796. repo_id=resolve_remote_path.repo_id,
  797. revision=resolve_remote_path.revision,
  798. filename=resolve_remote_path.path_in_repo,
  799. repo_type=resolve_remote_path.repo_type,
  800. endpoint=self.endpoint,
  801. ),
  802. temp_file=outfile, # type: ignore[arg-type]
  803. displayed_filename=rpath,
  804. expected_size=expected_size,
  805. resume_size=0,
  806. headers=self._api._build_hf_headers(),
  807. _tqdm_bar=callback.tqdm if isinstance(callback, TqdmCallback) else None,
  808. )
  809. outfile.seek(initial_pos)
  810. finally:
  811. # Close file only if we opened it ourselves
  812. if close_file:
  813. outfile.close()
  814. @property
  815. def transaction(self):
  816. """A context within which files are committed together upon exit
  817. Requires the file class to implement `.commit()` and `.discard()`
  818. for the normal and exception cases.
  819. """
  820. # Taken from https://github.com/fsspec/filesystem_spec/blob/3fbb6fee33b46cccb015607630843dea049d3243/fsspec/spec.py#L231
  821. # See https://github.com/huggingface/huggingface_hub/issues/1733
  822. raise NotImplementedError("Transactional commits are not supported.")
  823. def start_transaction(self):
  824. """Begin write transaction for deferring files, non-context version"""
  825. # Taken from https://github.com/fsspec/filesystem_spec/blob/3fbb6fee33b46cccb015607630843dea049d3243/fsspec/spec.py#L241
  826. # See https://github.com/huggingface/huggingface_hub/issues/1733
  827. raise NotImplementedError("Transactional commits are not supported.")
  828. def __reduce__(self):
  829. # re-populate the instance cache at HfFileSystem._cache and re-populate the cache attributes of every instance
  830. return make_instance, (
  831. type(self),
  832. self.storage_args,
  833. self.storage_options,
  834. {
  835. "dircache": self.dircache,
  836. "_repo_and_revision_exists_cache": self._repo_and_revision_exists_cache,
  837. },
  838. )
  839. class HfFileSystemFile(fsspec.spec.AbstractBufferedFile):
  840. def __init__(self, fs: HfFileSystem, path: str, revision: Optional[str] = None, **kwargs):
  841. try:
  842. self.resolved_path = fs.resolve_path(path, revision=revision)
  843. except FileNotFoundError as e:
  844. if "w" in kwargs.get("mode", ""):
  845. raise FileNotFoundError(
  846. f"{e}.\nMake sure the repository and revision exist before writing data."
  847. ) from e
  848. raise
  849. super().__init__(fs, self.resolved_path.unresolve(), **kwargs)
  850. self.fs: HfFileSystem
  851. def __del__(self):
  852. if not hasattr(self, "resolved_path"):
  853. # Means that the constructor failed. Nothing to do.
  854. return
  855. return super().__del__()
  856. def _fetch_range(self, start: int, end: int) -> bytes:
  857. headers = {
  858. "range": f"bytes={start}-{end - 1}",
  859. **self.fs._api._build_hf_headers(),
  860. }
  861. url = hf_hub_url(
  862. repo_id=self.resolved_path.repo_id,
  863. revision=self.resolved_path.revision,
  864. filename=self.resolved_path.path_in_repo,
  865. repo_type=self.resolved_path.repo_type,
  866. endpoint=self.fs.endpoint,
  867. )
  868. r = http_backoff("GET", url, headers=headers, timeout=constants.HF_HUB_DOWNLOAD_TIMEOUT)
  869. hf_raise_for_status(r)
  870. return r.content
  871. def _initiate_upload(self) -> None:
  872. self.temp_file = tempfile.NamedTemporaryFile(prefix="hffs-", delete=False)
  873. def _upload_chunk(self, final: bool = False) -> None:
  874. self.buffer.seek(0)
  875. block = self.buffer.read()
  876. self.temp_file.write(block)
  877. if final:
  878. self.temp_file.close()
  879. self.fs._api.upload_file(
  880. path_or_fileobj=self.temp_file.name,
  881. path_in_repo=self.resolved_path.path_in_repo,
  882. repo_id=self.resolved_path.repo_id,
  883. token=self.fs.token,
  884. repo_type=self.resolved_path.repo_type,
  885. revision=self.resolved_path.revision,
  886. commit_message=self.kwargs.get("commit_message"),
  887. commit_description=self.kwargs.get("commit_description"),
  888. )
  889. os.remove(self.temp_file.name)
  890. self.fs.invalidate_cache(
  891. path=self.resolved_path.unresolve(),
  892. )
  893. def read(self, length=-1):
  894. """Read remote file.
  895. If `length` is not provided or is -1, the entire file is downloaded and read. On POSIX systems and if
  896. `hf_transfer` is not enabled, the file is loaded in memory directly. Otherwise, the file is downloaded to a
  897. temporary file and read from there.
  898. """
  899. if self.mode == "rb" and (length is None or length == -1) and self.loc == 0:
  900. with self.fs.open(self.path, "rb", block_size=0) as f: # block_size=0 enables fast streaming
  901. out = f.read()
  902. self.loc += len(out)
  903. return out
  904. return super().read(length)
  905. def url(self) -> str:
  906. return self.fs.url(self.path)
  907. class HfFileSystemStreamFile(fsspec.spec.AbstractBufferedFile):
  908. def __init__(
  909. self,
  910. fs: HfFileSystem,
  911. path: str,
  912. mode: str = "rb",
  913. revision: Optional[str] = None,
  914. block_size: int = 0,
  915. cache_type: str = "none",
  916. **kwargs,
  917. ):
  918. if block_size != 0:
  919. raise ValueError(f"HfFileSystemStreamFile only supports block_size=0 but got {block_size}")
  920. if cache_type != "none":
  921. raise ValueError(f"HfFileSystemStreamFile only supports cache_type='none' but got {cache_type}")
  922. if "w" in mode:
  923. raise ValueError(f"HfFileSystemStreamFile only supports reading but got mode='{mode}'")
  924. try:
  925. self.resolved_path = fs.resolve_path(path, revision=revision)
  926. except FileNotFoundError as e:
  927. if "w" in kwargs.get("mode", ""):
  928. raise FileNotFoundError(
  929. f"{e}.\nMake sure the repository and revision exist before writing data."
  930. ) from e
  931. # avoid an unnecessary .info() call to instantiate .details
  932. self.details = {"name": self.resolved_path.unresolve(), "size": None}
  933. super().__init__(
  934. fs, self.resolved_path.unresolve(), mode=mode, block_size=block_size, cache_type=cache_type, **kwargs
  935. )
  936. self.response: Optional[Response] = None
  937. self.fs: HfFileSystem
  938. def seek(self, loc: int, whence: int = 0):
  939. if loc == 0 and whence == 1:
  940. return
  941. if loc == self.loc and whence == 0:
  942. return
  943. raise ValueError("Cannot seek streaming HF file")
  944. def read(self, length: int = -1):
  945. read_args = (length,) if length >= 0 else ()
  946. if self.response is None:
  947. url = hf_hub_url(
  948. repo_id=self.resolved_path.repo_id,
  949. revision=self.resolved_path.revision,
  950. filename=self.resolved_path.path_in_repo,
  951. repo_type=self.resolved_path.repo_type,
  952. endpoint=self.fs.endpoint,
  953. )
  954. self.response = http_backoff(
  955. "GET",
  956. url,
  957. headers=self.fs._api._build_hf_headers(),
  958. stream=True,
  959. timeout=constants.HF_HUB_DOWNLOAD_TIMEOUT,
  960. )
  961. hf_raise_for_status(self.response)
  962. try:
  963. self.response.raw.decode_content = True
  964. out = self.response.raw.read(*read_args)
  965. except Exception:
  966. self.response.close()
  967. # Retry by recreating the connection
  968. url = hf_hub_url(
  969. repo_id=self.resolved_path.repo_id,
  970. revision=self.resolved_path.revision,
  971. filename=self.resolved_path.path_in_repo,
  972. repo_type=self.resolved_path.repo_type,
  973. endpoint=self.fs.endpoint,
  974. )
  975. self.response = http_backoff(
  976. "GET",
  977. url,
  978. headers={"Range": "bytes=%d-" % self.loc, **self.fs._api._build_hf_headers()},
  979. stream=True,
  980. timeout=constants.HF_HUB_DOWNLOAD_TIMEOUT,
  981. )
  982. hf_raise_for_status(self.response)
  983. try:
  984. self.response.raw.decode_content = True
  985. out = self.response.raw.read(*read_args)
  986. except Exception:
  987. self.response.close()
  988. raise
  989. self.loc += len(out)
  990. return out
  991. def url(self) -> str:
  992. return self.fs.url(self.path)
  993. def __del__(self):
  994. if not hasattr(self, "resolved_path"):
  995. # Means that the constructor failed. Nothing to do.
  996. return
  997. return super().__del__()
  998. def __reduce__(self):
  999. return reopen, (self.fs, self.path, self.mode, self.blocksize, self.cache.name)
  1000. def safe_revision(revision: str) -> str:
  1001. return revision if SPECIAL_REFS_REVISION_REGEX.match(revision) else safe_quote(revision)
  1002. def safe_quote(s: str) -> str:
  1003. return quote(s, safe="")
  1004. def _raise_file_not_found(path: str, err: Optional[Exception]) -> NoReturn:
  1005. msg = path
  1006. if isinstance(err, RepositoryNotFoundError):
  1007. msg = f"{path} (repository not found)"
  1008. elif isinstance(err, RevisionNotFoundError):
  1009. msg = f"{path} (revision not found)"
  1010. elif isinstance(err, HFValidationError):
  1011. msg = f"{path} (invalid repository id)"
  1012. raise FileNotFoundError(msg) from err
  1013. def reopen(fs: HfFileSystem, path: str, mode: str, block_size: int, cache_type: str):
  1014. return fs.open(path, mode=mode, block_size=block_size, cache_type=cache_type)
  1015. def make_instance(cls, args, kwargs, instance_cache_attributes_dict):
  1016. fs = cls(*args, **kwargs)
  1017. for attr, cached_value in instance_cache_attributes_dict.items():
  1018. setattr(fs, attr, cached_value)
  1019. return fs