xjyplayer commited on
Commit
261aa6b
·
verified ·
1 Parent(s): 0f4e2dd

Delete test4

Browse files
Files changed (1) hide show
  1. test4/huggingface.py +0 -434
test4/huggingface.py DELETED
@@ -1,434 +0,0 @@
1
- import subprocess
2
- import json
3
- from huggingface_hub import HfApi, list_models
4
- from huggingface_hub.utils import HfHubHTTPError, RepositoryNotFoundError, RevisionNotFoundError
5
- from huggingface_hub.hf_api import RepoFile, RepoFolder
6
- import os
7
- os.environ['NO_PROXY'] = 'localhost, 127.0.0.1, ::1, ip.cn, chinaz.com, 192.168.0.0/16, mirrors.cloud.aliyuncs.com, hf-mirror.com, s3.us-east-1.amazonaws.com, lfs.huggingface.co'
8
-
9
- import re
10
- import json
11
- from datetime import datetime
12
-
13
- # Specify the mirror URL
14
- mirror_url = "https://hf-mirror.com"
15
-
16
- raw_url = "https://huggingface.co"
17
- user=""
18
- user_id=""
19
- api=None
20
- model_list = {}
21
- commit_message = ""
22
-
23
- def save_access_token(access_token):
24
- """保存 AccessToken 到文件中."""
25
- with open("access_token.json", "w") as f:
26
- json.dump({"access_token": access_token}, f)
27
-
28
- def load_access_token():
29
- """加载保存的 AccessToken."""
30
- try:
31
- with open("access_token.json", "r") as f:
32
- return json.load(f)["access_token"]
33
- except FileNotFoundError:
34
- return None
35
-
36
- def login(init=False):
37
-
38
- """登录到 Hugging Face 账户. 只有初始化的时候才可以略过登录,直接读取本地文件,其他情况代表手动调用"""
39
- access_token = load_access_token()
40
- if not (access_token and init):
41
- access_token = input("请输入您的 AccessToken: ")
42
- save_access_token(access_token)
43
- os.environ['HF_ENDPOINT'] = mirror_url
44
- subprocess.run(["huggingface-cli", "login", "--token", access_token], capture_output=True, text=True)
45
-
46
- os.environ['HF_ENDPOINT'] = ''
47
-
48
- return access_token
49
-
50
- def makesure_login(init=False):
51
- global user, api, user_id
52
-
53
- if init:
54
- login(init)
55
-
56
- """确保登录成功."""
57
- while True:
58
- status, res = check_login()
59
- if status:
60
- print(f"登录成功,用户名为: {res}")
61
- if api == None:
62
- api = HfApi(endpoint=mirror_url, token=load_access_token())
63
- user=res
64
- user_id = user
65
- break
66
- else:
67
- print(f"登录失败,请重新登录, {res}")
68
- login(init)
69
-
70
-
71
- def check_login():
72
- os.environ['HF_ENDPOINT'] = mirror_url
73
- result = subprocess.run(["huggingface-cli", "whoami"], capture_output=True, text=True)
74
- os.environ['HF_ENDPOINT'] = ""
75
-
76
- if result.returncode == 0:
77
- return True, result.stdout.split("\n")[0]
78
- else:
79
- return False, result.stderr
80
-
81
-
82
- def list_projects():
83
- global user, api, model_list
84
- """列出用户的项目列表."""
85
- makesure_login()
86
- # List models
87
- models = api.list_models(author=user, token=load_access_token())
88
- # Print table header
89
- print("\nProjects:")
90
- print("| {:<5} | {:<40} | {:<30} | {:<10} |".format("ID", "Model ID", "Created At", "Private"))
91
- print("| {:<5} | {:<40} | {:<30} | {:<10} |".format("-"*5, "-"*40, "-"*30, "-"*10))
92
- start_num = 99
93
- end_num = 99
94
- for i, model in enumerate(models, start=100):
95
- end_num += 1
96
- model_list[i] = model.id
97
- print(f"| {i:<5} | {model.id.ljust(40)} | {str(model.created_at).ljust(30)} | {str(model.private).ljust(10)} |")
98
- # # List datasets
99
- # print("\nDatasets:")
100
- # datasets = api.list_datasets()
101
- # # List spaces
102
- # print("\nSpaces:")
103
- # spaces = api.list_spaces()
104
-
105
- while True:
106
- print("\n请选择操作:")
107
- print("1. 添加一个新项目")
108
- print("2. 下载某个项目")
109
- print("3. 选择一个项目为当前项目")
110
- print("4. 返回上一级")
111
- choice = input("请输入操作编号: ")
112
- if choice == "1":
113
- repo_name = input("请输入存储库名称, 直接回车取消: ")
114
- if repo_name == "":
115
- continue
116
- private = input("是否为私有库, 请输入 y 或 n: ") == "y"
117
- repo_id = create_repository(repo_name, private= private)
118
-
119
- elif choice == "2":
120
- download_project()
121
- elif choice == "3":
122
- select_current_project(start_num + 1, end_num)
123
- elif choice == "4":
124
- return # Return to the previous level
125
- else:
126
- print("无效的操作编号,请重新输入")
127
-
128
-
129
- def select_current_project(start_num, end_num):
130
- """选择一个项目为当前项目."""
131
- global current_project, model_list
132
- while True:
133
- selected_id = input(f"请在 {str(start_num)} - {str(end_num)} 之中选择一个项目编号,或直接输入repo_id作为当前选择的项目: ")
134
- if selected_id.isdigit() and start_num <= int(selected_id) <= end_num:
135
- current_project = model_list[int(selected_id)]
136
- print(f"当前项目: {current_project}")
137
- show_project_details()
138
- break
139
- elif "/" in selected_id:
140
- current_project = selected_id
141
- print(f"当前项目: {current_project}")
142
- show_project_details()
143
- break
144
- else:
145
- print("无效的项目编号,请重新选择。")
146
-
147
- def show_project_details():
148
- """显示项目的具体内容,并提供下载和上传文件的选项."""
149
- global current_project, api
150
- makesure_login()
151
- if current_project:
152
- try:
153
- # Get project details
154
- info = api.repo_info(current_project)
155
- print(f"项目信息:")
156
- print(f"ID: {info.id}")
157
- print(f"Author: {info.author}")
158
- print(f"Created At: {info.created_at}")
159
- print(f"Last Modified: {info.last_modified}")
160
- print(f"Private: {info.private}")
161
-
162
- print_tree(current_project)
163
- # Display project content using tree structure
164
- print("\n项目内容:")
165
-
166
- # Provide options for downloading or uploading files
167
- while True:
168
- print("\n请选择操作:")
169
- print("1. 下载一个或多个项目文件")
170
- print("2. 上传一个或多个项目文件")
171
- print("3. 返回上一级")
172
- choice = input("请输入操作编号: ")
173
- if choice == "1":
174
- download_files(current_project)
175
- elif choice == "2":
176
- upload_files(current_project)
177
- elif choice == "3":
178
- return # Return to the previous level
179
- else:
180
- print("无效的操作编号,请重新输入。")
181
- except HfHubHTTPError as e:
182
- print(f"获取项目详情失败: {e}")
183
- else:
184
- print("未选择任何项目。")
185
-
186
-
187
-
188
- def format_size(size):
189
- """将文件大小格式化为更易读的形式."""
190
- power = 2**10
191
- n = 0
192
- power_labels = {0: '', 1: 'K', 2: 'M', 3: 'G', 4: 'T'}
193
- while size > power:
194
- size /= power
195
- n += 1
196
- return f"{size:.2f} {power_labels[n]}B"
197
-
198
- def print_tree(repo_id, path=None, expand=False, revision=None, repo_type=None, indent=""):
199
- """以树状形式打印项目文件结构."""
200
- global api
201
- if path is None:
202
- path = ''
203
- repo_tree = api.list_repo_tree(repo_id, path)
204
- for item in repo_tree:
205
- if isinstance(item, RepoFile):
206
- file_size = format_size(item.size) if item.size else "0 B"
207
- print(indent + f"📄 {item.path} (Size: {file_size})")
208
- elif isinstance(item, RepoFolder):
209
- print(indent + f"📁 {item.path}/")
210
- print_tree(repo_id, path=f"{item.path}", expand=expand, indent=indent + " ")
211
-
212
- def save_last_folder(folder_path):
213
- """
214
- Save the last used folder path to a configuration file.
215
- If the folder does not exist, create it.
216
-
217
- Args:
218
- - folder_path (str): The folder path to save.
219
- """
220
- if not os.path.exists(folder_path):
221
- os.makedirs(folder_path, exist_ok=True)
222
- print(f"文件夹 '{folder_path}' 不存在,已创建。")
223
-
224
- config = {"last_folder": folder_path}
225
- with open("config.json", "w") as f:
226
- json.dump(config, f)
227
-
228
- def get_default_folder():
229
- default_folder = os.getcwd() # 默认文件夹为当前工作目录
230
- config_file = "config.json"
231
- if os.path.exists(config_file):
232
- with open(config_file, "r") as f:
233
- config = json.load(f)
234
- if "last_folder" in config and os.path.exists(config["last_folder"]):
235
- default_folder = config["last_folder"]
236
- return default_folder
237
-
238
- def download_files(repo_id):
239
- total_files = 0
240
- successful_downloads = 0
241
- failed_downloads = 0
242
-
243
- default_folder = get_default_folder()
244
-
245
- while True:
246
- print("\n请输入要下载的文件路径,多个文件请使用逗号分隔, 回车返回上一级")
247
- file_paths_input = input("请输入文件路径: ")
248
- if len(file_paths_input) == 0:
249
- return
250
-
251
- folder_path = input(f"请输入文件夹路径,按回车使用{default_folder}:")
252
-
253
- if folder_path == "":
254
- folder_path = default_folder
255
-
256
- save_last_folder(folder_path)
257
-
258
- file_paths = [file_path.strip() for file_path in file_paths_input.split(",")]
259
- total_files += len(file_paths)
260
-
261
- # Prompt user to place downloaded files in corresponding folders
262
- user_choice = input("是否把下载的文件放到对应的文件夹?(Y/n):")
263
- if user_choice.lower() != 'n':
264
- dir_obj = True
265
-
266
- for file_path in file_paths:
267
- # Extract filename and subfolder from file_path
268
- if "/" in file_path:
269
- parts = file_path.rsplit("/", 1)
270
- filename = parts[-1]
271
- subfolder = parts[0]
272
- else:
273
- filename = file_path
274
- subfolder = ""
275
-
276
- try:
277
- path_input = folder_path
278
- if dir_obj:
279
- path_input = folder_path + "/" + subfolder
280
- print(f'downloading {filename} to {path_input}...')
281
- api.hf_hub_download(repo_id=repo_id, filename=filename, subfolder=subfolder, local_dir=path_input, local_dir_use_symlinks=False)
282
- successful_downloads += 1
283
- except Exception as e:
284
- print(f"下载文件 '{filename}' 时出错:{e}")
285
- failed_downloads += 1
286
-
287
- print(f"\n总共下载文件数: {total_files}")
288
- print(f"成功下载文件数: {successful_downloads}")
289
- print(f"失败下载文件数: {failed_downloads}")
290
-
291
- import os
292
-
293
- def upload_files(repo_id):
294
- """上传一个或多个项目文件."""
295
- global api
296
- makesure_login()
297
- if not is_own_project(repo_id):
298
- print("检测到当前项目不是本人的项目,故而没有上传权限")
299
- return
300
- while True:
301
- file_paths_input = input("请输入要上传的文件路径(多个文件请用逗号分隔), 回车返回上一级: ")
302
- if len(file_paths_input) == 0:
303
- return
304
- file_paths = [path.strip() for path in file_paths_input.split(",")]
305
-
306
- relative_paths_input = input("请输入要上传的文件相对路径, 没有会自动创建,不填全部上传到根目录(多个路径请用逗号分隔): ")
307
- if len(relative_paths_input) == 0:
308
- relative_paths = [""]
309
- else:
310
- relative_paths = [path.strip() for path in relative_paths_input.split(",")]
311
-
312
- if len(relative_paths) < len(file_paths):
313
- fill_choice = input("文件路径数目大于相对路径数目,请选择填充方式:\n1. 使用根目录填充\n2. 根据最后一个路径填充\n请选择(1/2): ")
314
- if fill_choice == "1":
315
- relative_paths += ["" for _ in range(len(file_paths) - len(relative_paths))]
316
- elif fill_choice == "2":
317
- last_path = relative_paths[-1] if relative_paths else ""
318
- relative_paths += [last_path for _ in range(len(file_paths) - len(relative_paths))]
319
- elif len(relative_paths) > len(file_paths):
320
- ignored_paths = relative_paths[len(file_paths):]
321
- print(f"文件路径数目小于相对路径数目,以下相对路径将被忽略: {', '.join(ignored_paths)}")
322
- relative_paths = relative_paths[:len(file_paths)]
323
-
324
- # 获取当前时间
325
- now = datetime.now()
326
- current_time = now.strftime("%Y-%m-%d %H:%M:%S")
327
- default_message = f"{user_id} uploaded at {current_time}"
328
- commit_message = input(f"请输入本次提交的目的,(回车默认填写:{default_message}):")
329
-
330
- for file_path, relative_path in zip(file_paths, relative_paths):
331
- # Convert relative path to absolute path
332
- absolute_path = os.path.abspath(file_path)
333
- if not os.path.exists(file_path):
334
- print(f"文件 '{file_path}' 不存在,跳过上传。")
335
- continue
336
-
337
- try:
338
-
339
- # 构造 commit_message
340
- if len(commit_message) == 0:
341
- commit_message = default_message
342
- else:
343
- commit_message = f"{user_id}: " + commit_message
344
- file_name = os.path.basename(file_path)
345
- print(f'uploading {absolute_path} to {repo_id}/{relative_path}/{file_name}...')
346
-
347
- api.upload_file(repo_id=repo_id, path_or_fileobj=absolute_path, path_in_repo=relative_path + "/" + file_name, commit_message=commit_message)
348
- print(f"文件 {file_path} 上传成功。")
349
- except HfHubHTTPError as e:
350
- print(f"文件 {file_path} 上传失败: {e}")
351
- except ValueError as e:
352
- print(f"文件 {file_path} 上传失败: {e}")
353
- except RepositoryNotFoundError as e:
354
- print(f"文件 {file_path} 上传失败: {e}")
355
- except RevisionNotFoundError as e:
356
- print(f"文件 {file_path} 上传失败: {e}")
357
-
358
- break
359
-
360
- def is_own_project(repo_id):
361
- """检查给定的 repo_id 是否为当前用户的项目."""
362
- return repo_id in model_list.values()
363
-
364
- def create_repository(repo_name, private = False):
365
- global user, api
366
- makesure_login()
367
- try:
368
- # 创建存储库
369
- api.create_repo(repo_name, private=private)
370
- except HfHubHTTPError as e:
371
- error_code = extract_first_three_digits(str(e))
372
- if error_code == 403:
373
- print("HTTPError 403: You don't have write permissions to the repository.")
374
- elif error_code == 404:
375
- print("HTTPError 404: The repository or project doesn't exist on the Hub.")
376
- elif error_code == 409:
377
- print("HTTPError 409: The project already exists in the collection and _ok=False.")
378
- else:
379
- print(f"HTTPError {e.server_message}")
380
-
381
- except ValueError as e:
382
- """bug"""
383
- print("warning:" + str(e))
384
-
385
- repo_id = user + '/' + repo_name
386
- if not private:
387
- url = mirror_url + "/" + repo_id
388
- else:
389
- url = "https://huggingface.co" + + "/" + repo_id
390
- # 检查是否成功创建存储库
391
- if url:
392
- print(f"存储库 {repo_id} 创建成功!地址为:" + url)
393
- else:
394
- print("存储库创建失败,请检查权限或存储库是否已存在。")
395
- return repo_id
396
-
397
- def extract_first_three_digits(s):
398
- match = re.search(r'\d{3}', s)
399
- if match:
400
- return int(match.group())
401
- return 0
402
-
403
- def getrepoid_from_url(url):
404
- parts = url.split('/')
405
- repo_id = parts[-2] + "/" + parts[-1]
406
- return repo_id
407
-
408
- def download_project():
409
- """下载某个项目."""
410
- # Your code to download a project goes here
411
- pass
412
-
413
- def switch_account():
414
- """切换账户."""
415
- access_token = input("请输入您的新 AccessToken: ")
416
- save_access_token(access_token)
417
- makesure_login() # 切换账户后立即登录
418
-
419
- def main():
420
- makesure_login(True)
421
- while True:
422
- print("\n请选择操作:")
423
- print("1. 查看项目列表")
424
- print("2. 切换账户")
425
- choice = input("请输入操作编号: ")
426
- if choice == "1":
427
- list_projects()
428
- elif choice == "2":
429
- switch_account()
430
- else:
431
- print("无效的操作编号,请重新输入")
432
-
433
- if __name__ == "__main__":
434
- main()