file_utils.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. # Copyright (c) Alibaba, Inc. and its affiliates.
  2. import hashlib
  3. import inspect
  4. import io
  5. import os
  6. from pathlib import Path
  7. from shutil import Error, copy2, copystat
  8. from typing import BinaryIO, Optional, Union
  9. # TODO: remove this api, unify to flattened args
  10. def func_receive_dict_inputs(func):
  11. """to decide if a func could receive dict inputs or not
  12. Args:
  13. func (class): the target function to be inspected
  14. Returns:
  15. bool: if func only has one arg ``input`` or ``inputs``, return True, else return False
  16. """
  17. full_args_spec = inspect.getfullargspec(func)
  18. varargs = full_args_spec.varargs
  19. varkw = full_args_spec.varkw
  20. if not (varargs is None and varkw is None):
  21. return False
  22. args = [] if not full_args_spec.args else full_args_spec.args
  23. args.pop(0) if (args and args[0] in ['self', 'cls']) else args
  24. if len(args) == 1 and args[0] in ['input', 'inputs']:
  25. return True
  26. return False
  27. def get_default_modelscope_cache_dir():
  28. """
  29. default base dir: '~/.cache/modelscope'
  30. """
  31. default_cache_dir = os.path.expanduser(Path.home().joinpath(
  32. '.cache', 'modelscope', 'hub'))
  33. return default_cache_dir
  34. def get_modelscope_cache_dir() -> str:
  35. """Get modelscope cache dir, default location or
  36. setting with MODELSCOPE_CACHE
  37. Returns:
  38. str: the modelscope cache root.
  39. """
  40. return os.path.expanduser(
  41. os.getenv('MODELSCOPE_CACHE', get_default_modelscope_cache_dir()))
  42. def get_model_cache_root() -> str:
  43. """Get model cache root path.
  44. Returns:
  45. str: the modelscope model cache root.
  46. """
  47. return os.path.join(get_modelscope_cache_dir(), 'models')
  48. def get_dataset_cache_root() -> str:
  49. """Get dataset raw file cache root path.
  50. if `MODELSCOPE_CACHE` is set, return `MODELSCOPE_CACHE/datasets`,
  51. else return `~/.cache/modelscope/hub/datasets`
  52. Returns:
  53. str: the modelscope dataset raw file cache root.
  54. """
  55. return os.path.join(get_modelscope_cache_dir(), 'datasets')
  56. def get_dataset_cache_dir(dataset_id: str) -> str:
  57. """Get the dataset_id's path.
  58. dataset_cache_root/dataset_id.
  59. Args:
  60. dataset_id (str): The dataset id.
  61. Returns:
  62. str: The dataset_id's cache root path.
  63. """
  64. dataset_root = get_dataset_cache_root()
  65. return dataset_root if dataset_id is None else os.path.join(
  66. dataset_root, dataset_id + '/')
  67. def get_model_cache_dir(model_id: str) -> str:
  68. """cache dir precedence:
  69. function parameter > environment > ~/.cache/modelscope/hub/model_id
  70. Args:
  71. model_id (str, optional): The model id.
  72. Returns:
  73. str: the model_id dir if model_id not None, otherwise cache root dir.
  74. """
  75. root_path = get_model_cache_root()
  76. return root_path if model_id is None else os.path.join(
  77. root_path, model_id + '/')
  78. def read_file(path):
  79. with open(path, 'r') as f:
  80. text = f.read()
  81. return text
  82. def copytree_py37(src,
  83. dst,
  84. symlinks=False,
  85. ignore=None,
  86. copy_function=copy2,
  87. ignore_dangling_symlinks=False,
  88. dirs_exist_ok=False):
  89. """copy from py37 shutil. add the parameter dirs_exist_ok."""
  90. names = os.listdir(src)
  91. if ignore is not None:
  92. ignored_names = ignore(src, names)
  93. else:
  94. ignored_names = set()
  95. os.makedirs(dst, exist_ok=dirs_exist_ok)
  96. errors = []
  97. for name in names:
  98. if name in ignored_names:
  99. continue
  100. srcname = os.path.join(src, name)
  101. dstname = os.path.join(dst, name)
  102. try:
  103. if os.path.islink(srcname):
  104. linkto = os.readlink(srcname)
  105. if symlinks:
  106. # We can't just leave it to `copy_function` because legacy
  107. # code with a custom `copy_function` may rely on copytree
  108. # doing the right thing.
  109. os.symlink(linkto, dstname)
  110. copystat(srcname, dstname, follow_symlinks=not symlinks)
  111. else:
  112. # ignore dangling symlink if the flag is on
  113. if not os.path.exists(linkto) and ignore_dangling_symlinks:
  114. continue
  115. # otherwise let the copy occurs. copy2 will raise an error
  116. if os.path.isdir(srcname):
  117. copytree_py37(
  118. srcname,
  119. dstname,
  120. symlinks,
  121. ignore,
  122. copy_function,
  123. dirs_exist_ok=dirs_exist_ok)
  124. else:
  125. copy_function(srcname, dstname)
  126. elif os.path.isdir(srcname):
  127. copytree_py37(
  128. srcname,
  129. dstname,
  130. symlinks,
  131. ignore,
  132. copy_function,
  133. dirs_exist_ok=dirs_exist_ok)
  134. else:
  135. # Will raise a SpecialFileError for unsupported file types
  136. copy_function(srcname, dstname)
  137. # catch the Error from the recursive copytree so that we can
  138. # continue with other files
  139. except Error as err:
  140. errors.extend(err.args[0])
  141. except OSError as why:
  142. errors.append((srcname, dstname, str(why)))
  143. try:
  144. copystat(src, dst)
  145. except OSError as why:
  146. # Copying file access times may fail on Windows
  147. if getattr(why, 'winerror', None) is None:
  148. errors.append((src, dst, str(why)))
  149. if errors:
  150. raise Error(errors)
  151. return dst
  152. def get_file_size(file_path_or_obj: Union[str, Path, bytes, BinaryIO]) -> int:
  153. if isinstance(file_path_or_obj, (str, Path)):
  154. file_path = Path(file_path_or_obj)
  155. return file_path.stat().st_size
  156. elif isinstance(file_path_or_obj, bytes):
  157. return len(file_path_or_obj)
  158. elif isinstance(file_path_or_obj, io.BufferedIOBase):
  159. current_position = file_path_or_obj.tell()
  160. file_path_or_obj.seek(0, os.SEEK_END)
  161. size = file_path_or_obj.tell()
  162. file_path_or_obj.seek(current_position)
  163. return size
  164. else:
  165. raise TypeError(
  166. 'Unsupported type: must be string, Path, bytes, or io.BufferedIOBase'
  167. )
  168. def get_file_hash(
  169. file_path_or_obj: Union[str, Path, bytes, BinaryIO],
  170. buffer_size_mb: Optional[int] = 1,
  171. tqdm_desc: Optional[str] = '[Calculating]',
  172. disable_tqdm: Optional[bool] = True,
  173. ) -> dict:
  174. from tqdm.auto import tqdm
  175. file_size = get_file_size(file_path_or_obj)
  176. if file_size > 1024 * 1024 * 1024: # 1GB
  177. disable_tqdm = False
  178. name = 'Large File'
  179. if isinstance(file_path_or_obj, (str, Path)):
  180. path = file_path_or_obj if isinstance(
  181. file_path_or_obj, Path) else Path(file_path_or_obj)
  182. name = path.name
  183. tqdm_desc = f'[Validating Hash for {name}]'
  184. buffer_size = buffer_size_mb * 1024 * 1024
  185. file_hash = hashlib.sha256()
  186. chunk_hash_list = []
  187. progress = tqdm(
  188. total=file_size,
  189. initial=0,
  190. unit_scale=True,
  191. dynamic_ncols=True,
  192. unit='B',
  193. desc=tqdm_desc,
  194. disable=disable_tqdm,
  195. )
  196. if isinstance(file_path_or_obj, (str, Path)):
  197. with open(file_path_or_obj, 'rb') as f:
  198. while byte_chunk := f.read(buffer_size):
  199. chunk_hash_list.append(hashlib.sha256(byte_chunk).hexdigest())
  200. file_hash.update(byte_chunk)
  201. progress.update(len(byte_chunk))
  202. file_hash = file_hash.hexdigest()
  203. final_chunk_size = buffer_size
  204. elif isinstance(file_path_or_obj, bytes):
  205. file_hash.update(file_path_or_obj)
  206. file_hash = file_hash.hexdigest()
  207. chunk_hash_list.append(file_hash)
  208. final_chunk_size = len(file_path_or_obj)
  209. progress.update(final_chunk_size)
  210. elif isinstance(file_path_or_obj, io.BufferedIOBase):
  211. file_path_or_obj.seek(0, os.SEEK_SET)
  212. while byte_chunk := file_path_or_obj.read(buffer_size):
  213. chunk_hash_list.append(hashlib.sha256(byte_chunk).hexdigest())
  214. file_hash.update(byte_chunk)
  215. progress.update(len(byte_chunk))
  216. file_hash = file_hash.hexdigest()
  217. final_chunk_size = buffer_size
  218. file_path_or_obj.seek(0, os.SEEK_SET)
  219. else:
  220. progress.close()
  221. raise ValueError(
  222. 'Input must be str, Path, bytes or a io.BufferedIOBase')
  223. progress.close()
  224. return {
  225. 'file_path_or_obj': file_path_or_obj,
  226. 'file_hash': file_hash,
  227. 'file_size': file_size,
  228. 'chunk_size': final_chunk_size,
  229. 'chunk_nums': len(chunk_hash_list),
  230. 'chunk_hash_list': chunk_hash_list,
  231. }