licyk commited on
Commit
618817c
·
verified ·
1 Parent(s): 206bd6b

Upload upload_file_to_hf.py

Browse files
Files changed (1) hide show
  1. upload_file_to_hf.py +72 -28
upload_file_to_hf.py CHANGED
@@ -1,53 +1,98 @@
1
  import logging
2
  import os
 
3
  import argparse
 
4
  from tqdm import tqdm
5
  from huggingface_hub import HfApi, CommitOperationAdd
6
  from pathlib import Path
7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  def get_all_file(directory: str) -> list:
9
- logging.warning(f"获取 {directory} 中的所有文件绝对路径中")
10
  file_list = []
11
  for dirname, _, filenames in os.walk(directory):
12
  for filename in filenames:
13
  file_list.append(Path(os.path.join(dirname, filename)).as_posix())
14
- logging.warning(f"{directory} 已有的文件数量: {len(file_list)}")
15
  return file_list
16
 
17
 
18
  def filter_file(file_list: list, root_path) -> list:
19
- logging.warning("过滤文件中")
20
  file_list_ = []
21
  for file_path in file_list:
22
  rel_path = Path(os.path.relpath(file_path, root_path)).as_posix()
23
  if rel_path.startswith(".git") or rel_path.startswith(".huggingface"):
24
  continue
25
  file_list_.append(file_path)
26
- logging.warning(f"过滤后的文件数量: {len(file_list_)}")
27
  return file_list_
28
 
29
 
30
  def get_hf_repo_file_list(hf_access_token, repo, repo_type):
31
- logging.warning(f"获取 {repo} 中的所有文件路径中")
32
  api = HfApi()
33
  model_list = api.list_repo_files(
34
  repo_id = repo,
35
  repo_type = repo_type,
36
  token = hf_access_token
37
  )
38
- logging.warning(f"{repo} 已有的文件数量: {len(model_list)}")
39
  return model_list
40
 
41
 
42
  def get_upload_list(file_list: list, hf_file_list: list, root_path) -> list:
43
- logging.warning("计算需要上传的文件中")
44
  upload_list = []
45
  for file_path in file_list:
46
  file_rel_path = Path(os.path.relpath(file_path, root_path)).as_posix()
47
  if file_rel_path not in hf_file_list:
48
  upload_list.append(file_path)
49
 
50
- logging.warning(f"需要上传的文件数量: {len(upload_list)}")
51
  return upload_list
52
 
53
 
@@ -56,9 +101,9 @@ def upload_file_to_hf(hf_access_token: str, repo: str, repo_type: str, upload_fi
56
  api = HfApi()
57
  try:
58
  api.whoami(token = hf_access_token)
59
- logging.warning("HuggingFace Token 验证成功")
60
  except Exception as e:
61
- logging.warning("HuggingFace Token 验证失败: ", e)
62
 
63
  # 添加文件操作
64
  operations = []
@@ -67,17 +112,15 @@ def upload_file_to_hf(hf_access_token: str, repo: str, repo_type: str, upload_fi
67
 
68
  operations.append(CommitOperationAdd(path_in_repo = hf_file_path, path_or_fileobj = local_file_path))
69
 
70
- try:
71
- api.create_commit(
72
- repo_id = repo,
73
- operations = operations,
74
- commit_message = f"upload",
75
- repo_type = repo_type,
76
- token = hf_access_token
77
- )
78
- logging.warning("上传文件结束")
79
- except:
80
- logging.error("上传文件出错")
81
 
82
 
83
  def get_args():
@@ -96,19 +139,19 @@ def main():
96
  args = get_args()
97
 
98
  if args.hf_token is None:
99
- logging.error("缺失 HF Token")
100
  return
101
  else:
102
  hf_token = args.hf_token
103
 
104
  if args.repo is None:
105
- logging.error("未填写仓库名称")
106
  return
107
  else:
108
  repo = args.repo
109
 
110
  if args.repo_type is None:
111
- logging.error("缺少仓库种类")
112
  return
113
  else:
114
  repo_type = args.repo_type
@@ -118,9 +161,9 @@ def main():
118
  else:
119
  root_path = args.upload_path
120
 
121
- logging.warning(f"repo: {repo}")
122
- logging.warning(f"repo_type: {repo_type}")
123
- logging.warning(f"root_path: {root_path}")
124
 
125
  all_file_list = get_all_file(root_path) # 本地所有文件的绝对路径
126
  filtered_file_list = filter_file(all_file_list, root_path) # 除去不需要上传的文件
@@ -135,4 +178,5 @@ def main():
135
  root_path = root_path)
136
 
137
 
138
- main()
 
 
1
  import logging
2
  import os
3
+ import copy
4
  import argparse
5
+ import sys
6
  from tqdm import tqdm
7
  from huggingface_hub import HfApi, CommitOperationAdd
8
  from pathlib import Path
9
 
10
+
11
+
12
+ class ColoredFormatter(logging.Formatter):
13
+ COLORS = {
14
+ "DEBUG": "\033[0;36m", # CYAN
15
+ "INFO": "\033[0;32m", # GREEN
16
+ "WARNING": "\033[0;33m", # YELLOW
17
+ "ERROR": "\033[0;31m", # RED
18
+ "CRITICAL": "\033[0;37;41m", # WHITE ON RED
19
+ "RESET": "\033[0m", # RESET COLOR
20
+ }
21
+
22
+ def format(self, record):
23
+ colored_record = copy.copy(record)
24
+ levelname = colored_record.levelname
25
+ seq = self.COLORS.get(levelname, self.COLORS["RESET"])
26
+ colored_record.levelname = f"{seq}{levelname}{self.COLORS['RESET']}"
27
+ return super().format(colored_record)
28
+
29
+
30
+ def get_logger() -> logging.Logger:
31
+ logger = logging.getLogger("HF-Uploader")
32
+ logger.propagate = False
33
+
34
+ if not logger.handlers:
35
+ handler = logging.StreamHandler(sys.stdout)
36
+ handler.setFormatter(
37
+ ColoredFormatter(
38
+ "[%(name)s]-|%(asctime)s|-%(levelname)s: %(message)s", "%H:%M:%S"
39
+ )
40
+ )
41
+ logger.addHandler(handler)
42
+
43
+ logger.setLevel(logging.INFO)
44
+ logger.debug("Logger initialized.")
45
+
46
+ return logger
47
+
48
+
49
+
50
+ logger = get_logger()
51
+
52
+
53
  def get_all_file(directory: str) -> list:
54
+ logger.info(f"获取 {directory} 中的所有文件绝对路径中")
55
  file_list = []
56
  for dirname, _, filenames in os.walk(directory):
57
  for filename in filenames:
58
  file_list.append(Path(os.path.join(dirname, filename)).as_posix())
59
+ logger.info(f"{directory} 已有的文件数量: {len(file_list)}")
60
  return file_list
61
 
62
 
63
  def filter_file(file_list: list, root_path) -> list:
64
+ logger.info("过滤文件中")
65
  file_list_ = []
66
  for file_path in file_list:
67
  rel_path = Path(os.path.relpath(file_path, root_path)).as_posix()
68
  if rel_path.startswith(".git") or rel_path.startswith(".huggingface"):
69
  continue
70
  file_list_.append(file_path)
71
+ logger.info(f"过滤后的文件数量: {len(file_list_)}")
72
  return file_list_
73
 
74
 
75
  def get_hf_repo_file_list(hf_access_token, repo, repo_type):
76
+ logger.info(f"获取 {repo} 中的所有文件路径中")
77
  api = HfApi()
78
  model_list = api.list_repo_files(
79
  repo_id = repo,
80
  repo_type = repo_type,
81
  token = hf_access_token
82
  )
83
+ logger.info(f"{repo} 已有的文件数量: {len(model_list)}")
84
  return model_list
85
 
86
 
87
  def get_upload_list(file_list: list, hf_file_list: list, root_path) -> list:
88
+ logger.info("计算需要上传的文件中")
89
  upload_list = []
90
  for file_path in file_list:
91
  file_rel_path = Path(os.path.relpath(file_path, root_path)).as_posix()
92
  if file_rel_path not in hf_file_list:
93
  upload_list.append(file_path)
94
 
95
+ logger.info(f"需要上传的文件数量: {len(upload_list)}")
96
  return upload_list
97
 
98
 
 
101
  api = HfApi()
102
  try:
103
  api.whoami(token = hf_access_token)
104
+ logger.info("HuggingFace Token 验证成功")
105
  except Exception as e:
106
+ logger.info("HuggingFace Token 验证失败: ", e)
107
 
108
  # 添加文件操作
109
  operations = []
 
112
 
113
  operations.append(CommitOperationAdd(path_in_repo = hf_file_path, path_or_fileobj = local_file_path))
114
 
115
+ api.create_commit(
116
+ repo_id = repo,
117
+ operations = operations,
118
+ commit_message = f"upload",
119
+ repo_type = repo_type,
120
+ token = hf_access_token
121
+ )
122
+
123
+ logger.info("上传文件结束")
 
 
124
 
125
 
126
  def get_args():
 
139
  args = get_args()
140
 
141
  if args.hf_token is None:
142
+ logger.error("缺失 HF Token")
143
  return
144
  else:
145
  hf_token = args.hf_token
146
 
147
  if args.repo is None:
148
+ logger.error("未填写仓库名称")
149
  return
150
  else:
151
  repo = args.repo
152
 
153
  if args.repo_type is None:
154
+ logger.error("缺少仓库种类")
155
  return
156
  else:
157
  repo_type = args.repo_type
 
161
  else:
162
  root_path = args.upload_path
163
 
164
+ logger.info(f"repo: {repo}")
165
+ logger.info(f"repo_type: {repo_type}")
166
+ logger.info(f"root_path: {root_path}")
167
 
168
  all_file_list = get_all_file(root_path) # 本地所有文件的绝对路径
169
  filtered_file_list = filter_file(all_file_list, root_path) # 除去不需要上传的文件
 
178
  root_path = root_path)
179
 
180
 
181
+ if __name__ == "__main__":
182
+ main()