""" upload_to_hf.py =============== 将 UnitCommitment_Trajectory_Dataset 中的 MPS 文件上传到 Hugging Face Dataset 仓库。 依赖安装: pip install huggingface_hub tqdm 使用前配置: 1. 修改下方 CONFIG 中的 REPO_ID 为您自己的仓库地址 2. 确保已通过 `huggingface-cli login` 登录,或设置环境变量 HF_TOKEN 运行: python upload_to_hf.py """ import os import sys from pathlib import Path from huggingface_hub import HfApi, CommitOperationAdd from tqdm import tqdm # ============================================================ # 配置区 — 根据您的情况修改以下参数 # ============================================================ CONFIG = { # 您的 Hugging Face Dataset 仓库地址,格式: "用户名/仓库名" "REPO_ID": "EridanusQ/UnitCommitment__Trajectory", # 本地数据集根目录(相对于本脚本的路径) "LOCAL_DATASET_DIR": "./UnitCommitment_Trajectory_Dataset", # 上传到仓库中的目标路径前缀(留空则上传到根目录) "REPO_BASE_PATH": "UnitCommitment_Trajectory_Dataset", # 每批次提交的文件数量(过大会导致单次 commit 超时,建议 50~200) "BATCH_SIZE": 1000, # 默认上传的目标分支(留空则在运行时交互选择) # 例如: "main", "dev", "case14" 等 "BRANCH": "", # 代理配置(如果需要)—— 留空则不使用代理 "HTTP_PROXY": "http://127.0.0.1:7897", "HTTPS_PROXY": "http://127.0.0.1:7897", } # ============================================================ def setup_proxy(): """配置系统代理环境变量""" if CONFIG["HTTP_PROXY"]: os.environ["HTTP_PROXY"] = CONFIG["HTTP_PROXY"] os.environ["http_proxy"] = CONFIG["HTTP_PROXY"] if CONFIG["HTTPS_PROXY"]: os.environ["HTTPS_PROXY"] = CONFIG["HTTPS_PROXY"] os.environ["https_proxy"] = CONFIG["HTTPS_PROXY"] if CONFIG["HTTP_PROXY"] or CONFIG["HTTPS_PROXY"]: print(f"✅ 代理已配置: {CONFIG['HTTPS_PROXY']}") def collect_files(local_dir: Path) -> list[tuple[Path, str]]: """ 遍历本地目录,收集所有文件及其对应的仓库路径。 Returns: list of (local_path, repo_path) tuples """ files = [] for local_path in sorted(local_dir.rglob("*")): if local_path.is_file(): # 计算相对路径,构建仓库内的目标路径 relative = local_path.relative_to(local_dir) repo_path = ( f"{CONFIG['REPO_BASE_PATH']}/{relative.as_posix()}" if CONFIG["REPO_BASE_PATH"] else relative.as_posix() ) files.append((local_path, repo_path)) return files def select_branch(api: HfApi) -> str: """ 交互式选择上传分支。 若 CONFIG["BRANCH"] 已填写则直接使用,否则列出仓库现有分支供用户选择或新建。 """ # 如果配置文件中已指定分支,直接使用 if CONFIG["BRANCH"].strip(): branch = CONFIG["BRANCH"].strip() print(f"📌 使用配置文件中指定的分支: {branch}") return branch # 获取仓库现有分支列表 try: refs = api.list_repo_refs( repo_id=CONFIG["REPO_ID"], repo_type="dataset", ) existing_branches = [b.name for b in refs.branches] except Exception: existing_branches = [] print("\n📋 仓库现有分支:") if existing_branches: for i, name in enumerate(existing_branches, 1): print(f" [{i}] {name}") else: print(" (暂无分支)") print(f" [n] 输入新分支名") while True: choice = input("\n请选择分支编号,或输入 'n' 新建分支: ").strip() if choice.lower() == "n": new_branch = input("请输入新分支名称: ").strip() if not new_branch: print(" ⚠️ 分支名不能为空,请重新输入。") continue return new_branch elif choice.isdigit() and 1 <= int(choice) <= len(existing_branches): return existing_branches[int(choice) - 1] else: print(" ⚠️ 无效输入,请重试。") def ensure_branch_exists(api: HfApi, branch: str): """ 检查分支是否存在,若不存在则从 main 分支创建。 """ try: refs = api.list_repo_refs( repo_id=CONFIG["REPO_ID"], repo_type="dataset", ) existing = [b.name for b in refs.branches] except Exception: existing = [] if branch not in existing: print(f" 🌿 分支 '{branch}' 不存在,正在从 main 创建...") try: api.create_branch( repo_id=CONFIG["REPO_ID"], repo_type="dataset", branch=branch, ) print(f" ✅ 分支 '{branch}' 创建成功!") except Exception as e: print(f" ❌ 分支创建失败: {e}") import sys; sys.exit(1) else: print(f" ✅ 分支 '{branch}' 已存在。") def upload_in_batches(api: HfApi, files: list[tuple[Path, str]], branch: str): """ 将文件分批次提交到 Hugging Face 指定分支,每批次显示进度条。 """ total_files = len(files) batch_size = CONFIG["BATCH_SIZE"] total_batches = (total_files + batch_size - 1) // batch_size print(f"\n📦 共 {total_files} 个文件,分 {total_batches} 批次上传(每批 {batch_size} 个)\n") for batch_idx in range(total_batches): start = batch_idx * batch_size end = min(start + batch_size, total_files) batch = files[start:end] print(f"── 批次 [{batch_idx + 1}/{total_batches}],共 {len(batch)} 个文件 ──") # 构建 CommitOperation 列表,并显示进度条 operations = [] with tqdm(batch, desc=" 准备文件", unit="file", ncols=80) as pbar: for local_path, repo_path in pbar: pbar.set_postfix_str(local_path.name[:30]) operations.append( CommitOperationAdd( path_in_repo=repo_path, path_or_fileobj=str(local_path), ) ) # 提交本批次 print(f" ⬆️ 正在上传到分支 '{branch}'...") try: api.create_commit( repo_id=CONFIG["REPO_ID"], repo_type="dataset", operations=operations, commit_message=f"upload: batch {batch_idx + 1}/{total_batches} ({len(batch)} files)", revision=branch, ) print(f" ✅ 批次 {batch_idx + 1} 上传成功!({start + 1}~{end} / {total_files})\n") except Exception as e: print(f" ❌ 批次 {batch_idx + 1} 上传失败: {e}") print(" ⚠️ 您可以修改脚本的 start_from_batch 变量后重新运行以跳过已上传的批次。") sys.exit(1) def main(): setup_proxy() local_dir = Path(CONFIG["LOCAL_DATASET_DIR"]).resolve() if not local_dir.exists(): print(f"❌ 本地数据集目录不存在: {local_dir}") sys.exit(1) print(f"📂 本地目录: {local_dir}") print(f"🎯 目标仓库: https://huggingface.co/datasets/{CONFIG['REPO_ID']}") # 收集文件列表 print("\n🔍 正在扫描文件...") files = collect_files(local_dir) if not files: print("⚠️ 未找到任何文件,请检查目录路径。") sys.exit(0) # 按文件大小统计 total_size = sum(p.stat().st_size for p, _ in files) print(f"📊 找到 {len(files)} 个文件,总大小: {total_size / 1024 / 1024:.1f} MB") # 显示文件类型分布 suffixes = {} for p, _ in files: ext = p.suffix.lower() or "(无后缀)" suffixes[ext] = suffixes.get(ext, 0) + 1 for ext, cnt in sorted(suffixes.items(), key=lambda x: -x[1]): print(f" {ext:12s} × {cnt}") # 确认上传 print() confirm = input("确认开始上传?(y/n): ").strip().lower() if confirm != "y": print("已取消。") sys.exit(0) # 初始化 API api = HfApi() # 确保仓库存在(不存在则自动创建) try: api.repo_info(repo_id=CONFIG["REPO_ID"], repo_type="dataset") print(f"\n✅ 仓库已存在。") except Exception: print(f"\n⚠️ 仓库不存在,正在创建: {CONFIG['REPO_ID']}") api.create_repo( repo_id=CONFIG["REPO_ID"], repo_type="dataset", private=False, ) # 选择上传分支 branch = select_branch(api) ensure_branch_exists(api, branch) print(f"\n🚀 准备上传至分支: [{branch}]") # 确认上传 print() confirm = input("确认开始上传?(y/n): ").strip().lower() if confirm != "y": print("已取消。") sys.exit(0) # 分批上传 upload_in_batches(api, files, branch) print("=" * 60) print(f"🎉 所有文件上传完成!") print(f"🔗 访问地址: https://huggingface.co/datasets/{CONFIG['REPO_ID']}/tree/{branch}") print("=" * 60) if __name__ == "__main__": main()