_cache_assets.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  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. from pathlib import Path
  15. from ..constants import HF_ASSETS_CACHE
  16. def cached_assets_path(
  17. library_name: str,
  18. namespace: str = "default",
  19. subfolder: str = "default",
  20. *,
  21. assets_dir: str | Path | None = None,
  22. ) -> Path:
  23. """Return a folder path to cache arbitrary files.
  24. `huggingface_hub` provides a canonical folder path to store assets. This is the
  25. recommended way to integrate cache in a downstream library as it will benefit from
  26. the builtins tools to scan and delete the cache properly.
  27. The distinction is made between files cached from the Hub and assets. Files from the
  28. Hub are cached in a git-aware manner and entirely managed by `huggingface_hub`. See
  29. [related documentation](https://huggingface.co/docs/huggingface_hub/how-to-cache).
  30. All other files that a downstream library caches are considered to be "assets"
  31. (files downloaded from external sources, extracted from a .tar archive, preprocessed
  32. for training,...).
  33. Once the folder path is generated, it is guaranteed to exist and to be a directory.
  34. The path is based on 3 levels of depth: the library name, a namespace and a
  35. subfolder. Those 3 levels grants flexibility while allowing `huggingface_hub` to
  36. expect folders when scanning/deleting parts of the assets cache. Within a library,
  37. it is expected that all namespaces share the same subset of subfolder names but this
  38. is not a mandatory rule. The downstream library has then full control on which file
  39. structure to adopt within its cache. Namespace and subfolder are optional (would
  40. default to a `"default/"` subfolder) but library name is mandatory as we want every
  41. downstream library to manage its own cache.
  42. Expected tree:
  43. ```text
  44. assets/
  45. └── datasets/
  46. │ ├── SQuAD/
  47. │ │ ├── downloaded/
  48. │ │ ├── extracted/
  49. │ │ └── processed/
  50. │ ├── Helsinki-NLP--tatoeba_mt/
  51. │ ├── downloaded/
  52. │ ├── extracted/
  53. │ └── processed/
  54. └── transformers/
  55. ├── default/
  56. │ ├── something/
  57. ├── bert-base-cased/
  58. │ ├── default/
  59. │ └── training/
  60. hub/
  61. └── models--julien-c--EsperBERTo-small/
  62. ├── blobs/
  63. │ ├── (...)
  64. │ ├── (...)
  65. ├── refs/
  66. │ └── (...)
  67. └── [ 128] snapshots/
  68. ├── 2439f60ef33a0d46d85da5001d52aeda5b00ce9f/
  69. │ ├── (...)
  70. └── bbc77c8132af1cc5cf678da3f1ddf2de43606d48/
  71. └── (...)
  72. ```
  73. Args:
  74. library_name (`str`):
  75. Name of the library that will manage the cache folder. Example: `"dataset"`.
  76. namespace (`str`, *optional*, defaults to "default"):
  77. Namespace to which the data belongs. Example: `"SQuAD"`.
  78. subfolder (`str`, *optional*, defaults to "default"):
  79. Subfolder in which the data will be stored. Example: `extracted`.
  80. assets_dir (`str`, `Path`, *optional*):
  81. Path to the folder where assets are cached. This must not be the same folder
  82. where Hub files are cached. Defaults to `HF_HOME / "assets"` if not provided.
  83. Can also be set with `HF_ASSETS_CACHE` environment variable.
  84. Returns:
  85. Path to the cache folder (`Path`).
  86. Example:
  87. ```py
  88. >>> from huggingface_hub import cached_assets_path
  89. >>> cached_assets_path(library_name="datasets", namespace="SQuAD", subfolder="download")
  90. PosixPath('/home/wauplin/.cache/huggingface/extra/datasets/SQuAD/download')
  91. >>> cached_assets_path(library_name="datasets", namespace="SQuAD", subfolder="extracted")
  92. PosixPath('/home/wauplin/.cache/huggingface/extra/datasets/SQuAD/extracted')
  93. >>> cached_assets_path(library_name="datasets", namespace="Helsinki-NLP/tatoeba_mt")
  94. PosixPath('/home/wauplin/.cache/huggingface/extra/datasets/Helsinki-NLP--tatoeba_mt/default')
  95. >>> cached_assets_path(library_name="datasets", assets_dir="/tmp/tmp123456")
  96. PosixPath('/tmp/tmp123456/datasets/default/default')
  97. ```
  98. """
  99. # Resolve assets_dir
  100. if assets_dir is None:
  101. assets_dir = HF_ASSETS_CACHE
  102. assets_dir = Path(assets_dir).expanduser().resolve()
  103. # Avoid names that could create path issues
  104. for part in (" ", "/", "\\"):
  105. library_name = library_name.replace(part, "--")
  106. namespace = namespace.replace(part, "--")
  107. subfolder = subfolder.replace(part, "--")
  108. # Path to subfolder is created
  109. path = assets_dir / library_name / namespace / subfolder
  110. try:
  111. path.mkdir(exist_ok=True, parents=True)
  112. except (FileExistsError, NotADirectoryError):
  113. raise ValueError(f"Corrupted assets folder: cannot create directory because of an existing file ({path}).")
  114. # Return
  115. return path