cache_manager.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. """Contains utilities to manage the ModelScope cache directory."""
  2. import os
  3. from dataclasses import dataclass
  4. from pathlib import Path
  5. from typing import Dict, FrozenSet, List, Literal, Optional, Set, Union
  6. from modelscope.hub.errors import CacheNotFound, CorruptedCacheException
  7. from modelscope.hub.utils.caching import ModelFileSystemCache
  8. from modelscope.hub.utils.utils import (convert_readable_size,
  9. format_timesince, tabulate)
  10. from modelscope.utils.constant import REPO_TYPE_DATASET, REPO_TYPE_MODEL
  11. from modelscope.utils.file_utils import get_modelscope_cache_dir
  12. from modelscope.utils.logger import get_logger
  13. logger = get_logger()
  14. # List of OS-created helper files that need to be ignored
  15. FILES_TO_IGNORE = ['.DS_Store', '._____temp']
  16. @dataclass(frozen=True)
  17. class CachedFileInfo:
  18. """Frozen data structure holding information about a single cached file.
  19. Args:
  20. file_name (`str`):
  21. Name of the file. Example: `config.json`.
  22. file_path (`Path`):
  23. Path of the file in the `snapshots` directory. The file path is a symlink
  24. referring to a blob in the `blobs` folder.
  25. blob_path (`Path`):
  26. Path of the blob file. This is equivalent to `file_path.resolve()`.
  27. size_on_disk (`int`):
  28. Size of the blob file in bytes.
  29. blob_last_accessed (`float`):
  30. Timestamp of the last time the blob file has been accessed (from any
  31. revision).
  32. blob_last_modified (`float`):
  33. Timestamp of the last time the blob file has been modified/created.
  34. """
  35. file_name: str
  36. file_path: Path
  37. file_revision_hash: str
  38. blob_path: Path
  39. size_on_disk: int
  40. blob_last_accessed: float
  41. blob_last_modified: float
  42. @property
  43. def blob_last_accessed_str(self) -> str:
  44. """
  45. (property) Timestamp of the last time the blob file has been accessed (from any
  46. revision), returned as a human-readable string.
  47. Example: "2 weeks ago".
  48. """
  49. return format_timesince(self.blob_last_accessed)
  50. @property
  51. def blob_last_modified_str(self) -> str:
  52. """
  53. (property) Timestamp of the last time the blob file has been modified, returned
  54. as a human-readable string.
  55. Example: "2 weeks ago".
  56. """
  57. return format_timesince(self.blob_last_modified)
  58. @property
  59. def size_on_disk_str(self) -> str:
  60. """
  61. (property) Size of the blob file as a human-readable string.
  62. Example: "42.2K".
  63. """
  64. return convert_readable_size(self.size_on_disk)
  65. @dataclass(frozen=True)
  66. class CachedRevisionInfo:
  67. """Frozen data structure holding information about a revision.
  68. Args:
  69. commit_hash (`str`):
  70. Hash of the revision (unique).
  71. Example: `"9338f7b671827df886678df2bdd7cc7b4f36dffd"`.
  72. snapshot_path (`Path`):
  73. Path to the revision directory in the `snapshots` folder. It contains the
  74. exact tree structure as the repo on the Hub.
  75. files: (`FrozenSet[CachedFileInfo]`):
  76. Set of [`~CachedFileInfo`] describing all files contained in the snapshot.
  77. size_on_disk (`int`):
  78. Sum of the blob file sizes that are symlink-ed by the revision.
  79. last_modified (`float`):
  80. Timestamp of the last time the revision has been created/modified.
  81. """
  82. commit_hash: str
  83. snapshot_path: Path
  84. size_on_disk: int
  85. files: FrozenSet[CachedFileInfo]
  86. last_modified: float
  87. @property
  88. def last_modified_str(self) -> str:
  89. """
  90. (property) Timestamp of the last time the revision has been modified, returned
  91. as a human-readable string.
  92. Example: "2 weeks ago".
  93. """
  94. return format_timesince(self.last_modified)
  95. @property
  96. def size_on_disk_str(self) -> str:
  97. """
  98. (property) Sum of the blob file sizes as a human-readable string.
  99. Example: "42.2K".
  100. """
  101. return convert_readable_size(self.size_on_disk)
  102. @property
  103. def nb_files(self) -> int:
  104. """
  105. (property) Total number of files in the revision.
  106. """
  107. return len(self.files)
  108. @dataclass(frozen=True)
  109. class CachedRepoInfo:
  110. """Frozen data structure holding information about a cached repository.
  111. Args:
  112. repo_id (`str`):
  113. Repo id of the repo on the Hub. Example: `"damo/bert-base-chinese"`.
  114. repo_type (`Literal["dataset", "model"]`):
  115. Type of the cached repo.
  116. repo_path (`Path`):
  117. Local path to the cached repo.
  118. size_on_disk (`int`):
  119. Sum of the blob file sizes in the cached repo.
  120. nb_files (`int`):
  121. Total number of blob files in the cached repo.
  122. revisions (`FrozenSet[CachedRevisionInfo]`):
  123. Set of [`~CachedRevisionInfo`] describing all revisions cached in the repo.
  124. last_accessed (`float`):
  125. Timestamp of the last time a blob file of the repo has been accessed.
  126. last_modified (`float`):
  127. Timestamp of the last time a blob file of the repo has been modified/created.
  128. """
  129. repo_id: str
  130. repo_type: str
  131. repo_path: Path
  132. size_on_disk: int
  133. nb_files: int
  134. revisions: FrozenSet[CachedRevisionInfo]
  135. last_accessed: float
  136. last_modified: float
  137. @property
  138. def last_accessed_str(self) -> str:
  139. """
  140. (property) Last time a blob file of the repo has been accessed, returned as a
  141. human-readable string.
  142. Example: "2 weeks ago".
  143. """
  144. return format_timesince(self.last_accessed)
  145. @property
  146. def last_modified_str(self) -> str:
  147. """
  148. (property) Last time a blob file of the repo has been modified, returned as a
  149. human-readable string.
  150. Example: "2 weeks ago".
  151. """
  152. return format_timesince(self.last_modified)
  153. @property
  154. def size_on_disk_str(self) -> str:
  155. """
  156. (property) Sum of the blob file sizes as a human-readable string.
  157. Example: "42.2K".
  158. """
  159. return convert_readable_size(self.size_on_disk)
  160. @dataclass(frozen=True)
  161. class ModelScopeCacheInfo:
  162. """Frozen data structure holding information about the entire cache-system.
  163. This data structure is returned by [`scan_cache_dir`] and is immutable.
  164. Args:
  165. size_on_disk (`int`):
  166. Sum of all valid repo sizes in the cache-system.
  167. repos (`FrozenSet[CachedRepoInfo]`):
  168. Set of [`~CachedRepoInfo`] describing all valid cached repos found on the
  169. cache-system while scanning.
  170. warnings (`List[CorruptedCacheException]`):
  171. List of [`~CorruptedCacheException`] that occurred while scanning the cache.
  172. Those exceptions are captured so that the scan can continue. Corrupted repos
  173. are skipped from the scan.
  174. """
  175. size_on_disk: int
  176. repos: FrozenSet[CachedRepoInfo]
  177. warnings: List[CorruptedCacheException]
  178. @property
  179. def size_on_disk_str(self) -> str:
  180. """
  181. (property) Sum of all valid repo sizes in the cache-system as a human-readable
  182. string.
  183. """
  184. return convert_readable_size(self.size_on_disk)
  185. def export_as_table(self) -> str:
  186. """Generate a detailed table from the [`ModelScopeCacheInfo`] object.
  187. Returns a table with a row per repo and revision (thus multiple rows can appear for a single repo), with columns
  188. "repo_id", "repo_type", "revision", "size_on_disk", "nb_files", "last_modified", "local_path".
  189. Example:
  190. ```py
  191. >>> from modelscope.hub.cache_manager import scan_cache_dir
  192. >>> ms_cache_info = scan_cache_dir()
  193. ModelScopeCacheInfo(...)
  194. >>> print(ms_cache_info.export_as_table())
  195. REPO ID REPO TYPE REVISION SIZE ON DISK NB FILES LAST_MODIFIED LOCAL PATH
  196. ---------------------- --------- ---------- ------------ -------- ------------- -------------------------------------------------------------
  197. damo/bert-base-chinese model master 2.7M 5 1 week ago ~/.cache/modelscope/hub/models--damo--bert-base-chinese/...
  198. damo/structured-bert model master 8.8K 1 1 week ago ~/.cache/modelscope/hub/models--damo--structured-bert/...
  199. damo/t5-base model master 893.8M 4 7 months ago ~/.cache/modelscope/hub/models--damo--t5-base/...
  200. ```
  201. Returns:
  202. `str`: The table as a string.
  203. """ # noqa: E501
  204. def format_repo_revision(repo: CachedRepoInfo,
  205. revision: CachedRevisionInfo) -> List[str]:
  206. """Format a single repo and revision into a list of strings for tabulation."""
  207. return [
  208. repo.repo_id,
  209. repo.repo_type,
  210. revision.commit_hash,
  211. '{:>12}'.format(repo.size_on_disk_str),
  212. repo.nb_files,
  213. repo.last_accessed_str,
  214. repo.last_modified_str,
  215. str(repo.repo_path),
  216. ]
  217. column_headers = [
  218. 'REPO ID',
  219. 'REPO TYPE',
  220. 'REVISION',
  221. 'SIZE ON DISK',
  222. 'NB FILES',
  223. 'LAST_ACCESSED',
  224. 'LAST_MODIFIED',
  225. 'LOCAL PATH',
  226. ]
  227. table_data = [
  228. format_repo_revision(repo, revision)
  229. for repo in sorted(self.repos, key=lambda repo: repo.repo_id)
  230. for revision in sorted(
  231. repo.revisions, key=lambda revision: revision.commit_hash)
  232. ]
  233. return tabulate(
  234. rows=table_data,
  235. headers=column_headers,
  236. )
  237. def scan_cache_dir(
  238. cache_dir: Optional[Union[str, Path]] = None) -> ModelScopeCacheInfo:
  239. """Scan the entire ModelScope cache-system and return a [`ModelScopeCacheInfo`] structure.
  240. Use `scan_cache_dir` to programmatically scan your cache-system. The cache
  241. will be scanned repo by repo. If a repo is corrupted, a [`~CorruptedCacheException`]
  242. will be thrown internally but captured and returned in the [`~ModelScopeCacheInfo`]
  243. structure. Only valid repos get a proper report.
  244. ```py
  245. >>> from modelscope.hub.utils import scan_cache_dir
  246. >>> ms_cache_info = scan_cache_dir()
  247. ModelScopeCacheInfo(
  248. size_on_disk=3398085269,
  249. repos=frozenset({
  250. CachedRepoInfo(
  251. repo_id='damo/t5-small',
  252. repo_type='model',
  253. repo_path=PosixPath(...),
  254. size_on_disk=970726914,
  255. nb_files=11,
  256. revisions=frozenset({
  257. CachedRevisionInfo(
  258. commit_hash='master',
  259. size_on_disk=970726339,
  260. snapshot_path=PosixPath(...),
  261. files=frozenset({
  262. CachedFileInfo(
  263. file_name='config.json',
  264. size_on_disk=1197
  265. file_path=PosixPath(...),
  266. blob_path=PosixPath(...),
  267. ),
  268. CachedFileInfo(...),
  269. ...
  270. }),
  271. ),
  272. CachedRevisionInfo(...),
  273. ...
  274. }),
  275. ),
  276. CachedRepoInfo(...),
  277. ...
  278. }),
  279. warnings=[
  280. CorruptedCacheException("Snapshots dir doesn't exist in cached repo: ..."),
  281. CorruptedCacheException(...),
  282. ...
  283. ],
  284. )
  285. ```
  286. Args:
  287. cache_dir (`str` or `Path`, `optional`):
  288. Cache directory to scan. Defaults to the default ModelScope cache directory.
  289. Raises:
  290. `CacheNotFound`: If the cache directory does not exist.
  291. `ValueError`: If the cache directory is a file, instead of a directory.
  292. Returns: a [`ModelScopeCacheInfo`] object.
  293. """
  294. if cache_dir is None:
  295. cache_dir = get_modelscope_cache_dir()
  296. cache_dir = Path(cache_dir).expanduser().resolve()
  297. if not cache_dir.exists():
  298. raise CacheNotFound(
  299. f'Cache directory not found: {cache_dir}. Please use `cache_dir` argument or set `MODELSCOPE_CACHE` environment variable.', # noqa: E501
  300. cache_dir=cache_dir,
  301. )
  302. if cache_dir.is_file():
  303. raise ValueError(
  304. f'Scan cache expects a directory but found a file: {cache_dir}. Please use `cache_dir` argument or set `MODELSCOPE_CACHE` environment variable.' # noqa: E501
  305. )
  306. repos: Set[CachedRepoInfo] = set()
  307. warnings: List[CorruptedCacheException] = []
  308. # ModelScope structure is different - we need to look in models/ and datasets/ directories
  309. model_dir = cache_dir / 'models'
  310. dataset_dir = cache_dir / 'datasets'
  311. # Check models directory
  312. if model_dir.exists() and model_dir.is_dir():
  313. # First level directories are owners/organizations
  314. model_repos, model_warnings = _scan_dir(
  315. model_dir, repo_type=REPO_TYPE_MODEL)
  316. repos.update(model_repos)
  317. warnings.extend(model_warnings)
  318. # Check datasets directory
  319. if dataset_dir.exists() and dataset_dir.is_dir():
  320. # First level directories are owners/organizations
  321. dataset_repos, dataset_warnings = _scan_dir(
  322. dataset_dir, repo_type=REPO_TYPE_DATASET)
  323. repos.update(dataset_repos)
  324. warnings.extend(dataset_warnings)
  325. # Also check for repos directly in cache_dir (older structure)
  326. # If the repo is not in models/ or datasets/, assume it's a model repo
  327. other_repos, other_warnings = _scan_dir(
  328. cache_dir, repo_type=REPO_TYPE_MODEL, inplace=True)
  329. repos.update(other_repos)
  330. warnings.extend(other_warnings)
  331. return ModelScopeCacheInfo(
  332. repos=frozenset(repos),
  333. size_on_disk=sum(repo.size_on_disk for repo in repos),
  334. warnings=warnings,
  335. )
  336. def _is_valid_dir(dir: Path) -> bool:
  337. """Check if a directory is valid for scanning."""
  338. if not dir.exists():
  339. return False
  340. if not dir.is_dir():
  341. return False
  342. if dir.is_symlink():
  343. return False
  344. if dir.name in FILES_TO_IGNORE:
  345. return False
  346. return True
  347. def _scan_dir(dir: Path, repo_type: str, inplace: bool = False):
  348. """Scan a directory for cached repos and return a set of [`~CachedRepoInfo`] and warnings."""
  349. repos = set()
  350. warnings = []
  351. for owner_dir in dir.iterdir():
  352. # not extend scan the following dirs when scan current dir
  353. if inplace and owner_dir.name in ['models', 'datasets', 'hub']:
  354. continue
  355. if not _is_valid_dir(owner_dir):
  356. continue
  357. # Second level directories are repo names
  358. for name_dir in owner_dir.iterdir():
  359. if not _is_valid_dir(name_dir):
  360. continue
  361. try:
  362. info = _scan_cached_repo(name_dir, repo_type=repo_type)
  363. if info is not None:
  364. repos.add(info)
  365. except CorruptedCacheException as e:
  366. warnings.append(e)
  367. return repos, warnings
  368. def _scan_cached_repo(repo_path: Path,
  369. repo_type: str) -> Optional[CachedRepoInfo]:
  370. """Scan a single cache repo and return information about it.
  371. Any unexpected behavior will raise a [`~CorruptedCacheException`].
  372. """
  373. if not repo_path.is_dir():
  374. raise CorruptedCacheException(
  375. f'Repo path is not a directory: {repo_path}')
  376. # Use ModelFileSystemCache to get cached files information
  377. try:
  378. cache = ModelFileSystemCache(str(repo_path))
  379. cached_files = cache.cached_files
  380. cached_model_revision = cache.cached_model_revision
  381. repo_id = cache.get_model_id().replace('___', '.')
  382. if repo_id == 'unknown':
  383. return None # Skip if repo_id is unknown
  384. except Exception as e:
  385. raise CorruptedCacheException(f'Failed to load cache information: {e}')
  386. # Collect file stats and information
  387. blob_stats = {} # Track blob file stats
  388. cached_files_info = set()
  389. # Process all cached files
  390. for cached_file in cached_files:
  391. file_path = os.path.join(repo_path, cached_file['Path'])
  392. file_revision_hash = cached_file.get('Revision', '')
  393. if not os.path.exists(file_path):
  394. continue
  395. blob_path = Path(file_path)
  396. blob_stats[blob_path] = blob_path.stat()
  397. # Create CachedFileInfo for this file
  398. cached_files_info.add(
  399. CachedFileInfo(
  400. file_name=os.path.basename(cached_file['Path']),
  401. file_path=blob_path,
  402. file_revision_hash=file_revision_hash,
  403. size_on_disk=blob_stats[blob_path].st_size,
  404. blob_path=blob_path,
  405. blob_last_accessed=blob_stats[blob_path].st_atime,
  406. blob_last_modified=blob_stats[blob_path].st_mtime,
  407. ))
  408. # Create a single revision from cached files
  409. revision_hash = 'master' # Default revision name
  410. if cached_model_revision:
  411. # Extract revision hash from cached_model_revision if available
  412. if 'Revision:' in cached_model_revision:
  413. revision_hash = cached_model_revision.split('Revision:')[1].split(
  414. ',')[0]
  415. # Calculate revision metadata
  416. if cached_files_info:
  417. revision_last_modified = max(blob_stats[file.blob_path].st_mtime
  418. for file in cached_files_info)
  419. else:
  420. revision_last_modified = repo_path.stat().st_mtime
  421. # Create a CachedRevisionInfo for the repository
  422. cached_revision = CachedRevisionInfo(
  423. commit_hash=revision_hash,
  424. files=frozenset(cached_files_info),
  425. size_on_disk=sum(blob_stats[file.blob_path].st_size
  426. for file in cached_files_info),
  427. snapshot_path=repo_path,
  428. last_modified=revision_last_modified,
  429. )
  430. # Calculate repository-wide statistics
  431. if blob_stats:
  432. repo_last_accessed = max(stat.st_atime for stat in blob_stats.values())
  433. repo_last_modified = max(stat.st_mtime for stat in blob_stats.values())
  434. else:
  435. repo_stats = repo_path.stat()
  436. repo_last_accessed = repo_stats.st_atime
  437. repo_last_modified = repo_stats.st_mtime
  438. # Build and return frozen structure
  439. return CachedRepoInfo(
  440. nb_files=len(blob_stats),
  441. repo_id=repo_id,
  442. repo_path=repo_path,
  443. repo_type=repo_type,
  444. revisions=frozenset([cached_revision]),
  445. size_on_disk=sum(stat.st_size for stat in blob_stats.values()),
  446. last_accessed=repo_last_accessed,
  447. last_modified=repo_last_modified,
  448. )