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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
|
| 3 |
+
# HF Token 从环境变量 HF_TOKEN 读取(由 modal_jupyter.py 通过 modal.Secret 注入)。
|
| 4 |
+
# 如果不在 Modal 环境中运行,请先设置:
|
| 5 |
+
# export HF_TOKEN="hf_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
|
| 6 |
+
|
| 7 |
+
import argparse
|
| 8 |
+
import os
|
| 9 |
+
import subprocess
|
| 10 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 11 |
+
from datetime import datetime
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
from huggingface_hub import HfApi, hf_hub_url, login
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
SCRIPT_DIR = Path(__file__).resolve().parent
|
| 18 |
+
UPLOAD_DIR = SCRIPT_DIR / "upload"
|
| 19 |
+
REPO_ID = "ACCC1380/private-model"
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def create_backup_archive(backup_dir: Path) -> Path:
|
| 23 |
+
backup_dir = backup_dir.expanduser().resolve()
|
| 24 |
+
|
| 25 |
+
if not backup_dir.exists():
|
| 26 |
+
raise FileNotFoundError(f"备份目录不存在: {backup_dir}")
|
| 27 |
+
if not backup_dir.is_dir():
|
| 28 |
+
raise NotADirectoryError(f"指定路径不是目录: {backup_dir}")
|
| 29 |
+
if backup_dir == backup_dir.parent:
|
| 30 |
+
raise ValueError("不支持直接打包文件系统根目录")
|
| 31 |
+
if backup_dir == UPLOAD_DIR.resolve():
|
| 32 |
+
raise ValueError("备份目录不能是脚本的 upload 输出目录")
|
| 33 |
+
|
| 34 |
+
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
|
| 35 |
+
|
| 36 |
+
timelapse = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 37 |
+
archive_path = UPLOAD_DIR / f"{backup_dir.name}_{timelapse}.tar"
|
| 38 |
+
|
| 39 |
+
print(f"开始打包目录: {backup_dir}")
|
| 40 |
+
print(f"归档文件: {archive_path}")
|
| 41 |
+
|
| 42 |
+
tar_command = ["tar", "-cvf", str(archive_path)]
|
| 43 |
+
|
| 44 |
+
# 如果备份目录包含脚本的 upload 目录,则排除它,避免归档包含自身。
|
| 45 |
+
try:
|
| 46 |
+
upload_relative_path = UPLOAD_DIR.resolve().relative_to(backup_dir)
|
| 47 |
+
except ValueError:
|
| 48 |
+
pass
|
| 49 |
+
else:
|
| 50 |
+
exclude_path = (Path(backup_dir.name) / upload_relative_path).as_posix()
|
| 51 |
+
tar_command.extend(["--exclude", exclude_path])
|
| 52 |
+
|
| 53 |
+
tar_command.extend(["-C", str(backup_dir.parent), backup_dir.name])
|
| 54 |
+
subprocess.run(tar_command, check=True)
|
| 55 |
+
|
| 56 |
+
print("目录打包完成")
|
| 57 |
+
return archive_path
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def collect_upload_files() -> list[Path]:
|
| 61 |
+
"""收集 upload 目录中已有的全部文件。"""
|
| 62 |
+
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
|
| 63 |
+
return sorted(path for path in UPLOAD_DIR.rglob("*") if path.is_file())
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def upload_file(api: HfApi, file_in_folder: Path, repo_id: str) -> str:
|
| 67 |
+
# 仓库路径和 URL 在 Windows/Linux 上均使用正斜杠。
|
| 68 |
+
path_in_repo = file_in_folder.relative_to(SCRIPT_DIR).as_posix()
|
| 69 |
+
|
| 70 |
+
try:
|
| 71 |
+
api.upload_file(
|
| 72 |
+
path_or_fileobj=file_in_folder,
|
| 73 |
+
path_in_repo=path_in_repo,
|
| 74 |
+
repo_id=repo_id,
|
| 75 |
+
repo_type="dataset",
|
| 76 |
+
)
|
| 77 |
+
except Exception as exc:
|
| 78 |
+
raise RuntimeError(f"文件 {file_in_folder} 上传失败: {exc}") from exc
|
| 79 |
+
|
| 80 |
+
return hf_hub_url(
|
| 81 |
+
repo_id=repo_id,
|
| 82 |
+
filename=path_in_repo,
|
| 83 |
+
repo_type="dataset",
|
| 84 |
+
revision="main",
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def huggingface_upload(local_files: list[Path], repo_id: str) -> bool:
|
| 89 |
+
hf_token = os.environ.get("HF_TOKEN", "")
|
| 90 |
+
if not hf_token:
|
| 91 |
+
print(
|
| 92 |
+
'Error: HF_TOKEN 环境变量未设置。请设置后重试:'
|
| 93 |
+
'export HF_TOKEN="hf_xxx"'
|
| 94 |
+
)
|
| 95 |
+
return False
|
| 96 |
+
|
| 97 |
+
login(token=hf_token)
|
| 98 |
+
api = HfApi()
|
| 99 |
+
print("HfApi 类已实例化")
|
| 100 |
+
print("开始上传文件...")
|
| 101 |
+
|
| 102 |
+
upload_tasks = []
|
| 103 |
+
upload_failed = False
|
| 104 |
+
|
| 105 |
+
with ThreadPoolExecutor(max_workers=15) as executor:
|
| 106 |
+
for local_file in local_files:
|
| 107 |
+
local_file = Path(local_file).resolve()
|
| 108 |
+
if not local_file.is_file():
|
| 109 |
+
print(f"Error: File {local_file} does not exist")
|
| 110 |
+
upload_failed = True
|
| 111 |
+
continue
|
| 112 |
+
|
| 113 |
+
upload_tasks.append(
|
| 114 |
+
executor.submit(upload_file, api, local_file, repo_id)
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
for task in as_completed(upload_tasks):
|
| 118 |
+
try:
|
| 119 |
+
direct_url = task.result()
|
| 120 |
+
print("文件上传完成")
|
| 121 |
+
print(f"响应:{direct_url}")
|
| 122 |
+
except Exception as exc:
|
| 123 |
+
upload_failed = True
|
| 124 |
+
print(f"上传失败: {exc}")
|
| 125 |
+
|
| 126 |
+
return not upload_failed
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def parse_args():
|
| 130 |
+
parser = argparse.ArgumentParser(
|
| 131 |
+
description="上传 upload 目录中的文件;也可选择先打包指定目录"
|
| 132 |
+
)
|
| 133 |
+
parser.add_argument(
|
| 134 |
+
"--backup-dir",
|
| 135 |
+
type=Path,
|
| 136 |
+
default=None,
|
| 137 |
+
help="可选:先使用 tar -cvf 打包该目录,再上传生成的归档",
|
| 138 |
+
)
|
| 139 |
+
return parser.parse_args()
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def main() -> int:
|
| 143 |
+
args = parse_args()
|
| 144 |
+
|
| 145 |
+
if args.backup_dir is not None:
|
| 146 |
+
try:
|
| 147 |
+
archive_path = create_backup_archive(args.backup_dir)
|
| 148 |
+
except (OSError, ValueError, subprocess.CalledProcessError) as exc:
|
| 149 |
+
print(f"打包失败: {exc}")
|
| 150 |
+
return 1
|
| 151 |
+
|
| 152 |
+
# 传入 --backup-dir 时,只上传本次生成的归档。
|
| 153 |
+
local_files = [archive_path]
|
| 154 |
+
else:
|
| 155 |
+
# 裸跑时不打包,直接上传 upload/ 中已有的文件。
|
| 156 |
+
local_files = collect_upload_files()
|
| 157 |
+
if not local_files:
|
| 158 |
+
print(f"没有可上传的文件: {UPLOAD_DIR}")
|
| 159 |
+
return 1
|
| 160 |
+
|
| 161 |
+
print(f"找到 {len(local_files)} 个待上传文件")
|
| 162 |
+
|
| 163 |
+
return 0 if huggingface_upload(local_files, REPO_ID) else 1
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
if __name__ == "__main__":
|
| 167 |
+
raise SystemExit(main())
|