EridanusQ commited on
Commit
407171b
·
1 Parent(s): f12c3ea
UnitCommitment_Trajectory_Test/test/case2383wp-2017-07-27/case2383wp-2017-07-27-part1.json ADDED
The diff for this file is too large to render. See raw diff
 
upload_to_hf.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ upload_to_hf.py
3
+ ===============
4
+ 将 UnitCommitment_Trajectory_Dataset 中的 MPS 文件上传到 Hugging Face Dataset 仓库。
5
+
6
+ 依赖安装:
7
+ pip install huggingface_hub tqdm
8
+
9
+ 使用前配置:
10
+ 1. 修改下方 CONFIG 中的 REPO_ID 为您自己的仓库地址
11
+ 2. 确保已通过 `huggingface-cli login` 登录,或设置环境变量 HF_TOKEN
12
+
13
+ 运行:
14
+ python upload_to_hf.py
15
+ """
16
+
17
+ import os
18
+ import sys
19
+ from pathlib import Path
20
+ from huggingface_hub import HfApi, CommitOperationAdd
21
+ from tqdm import tqdm
22
+
23
+ # ============================================================
24
+ # 配置区 — 根据您的情况修改以下参数
25
+ # ============================================================
26
+ CONFIG = {
27
+ # 您的 Hugging Face Dataset 仓库地址,格式: "用户名/仓库名"
28
+ "REPO_ID": "EridanusQ/UnitCommitment__Trajectory",
29
+
30
+ # 本地数据集根目录(相对于本脚本的路径)
31
+ "LOCAL_DATASET_DIR": "./UnitCommitment_Trajectory_Dataset",
32
+
33
+ # 上传到仓库中的目标路径前缀(留空则上传到根目录)
34
+ "REPO_BASE_PATH": "data",
35
+
36
+ # 每批次提交的文件数量(过大会导致单次 commit 超时,建议 50~200)
37
+ "BATCH_SIZE": 100,
38
+
39
+ # 默认上传的目标分支(留空则在运行时交互选择)
40
+ # 例如: "main", "dev", "case14" 等
41
+ "BRANCH": "",
42
+
43
+ # 代理配置(如果需要)—— 留空则不使用代理
44
+ "HTTP_PROXY": "http://127.0.0.1:7897",
45
+ "HTTPS_PROXY": "http://127.0.0.1:7897",
46
+ }
47
+ # ============================================================
48
+
49
+
50
+ def setup_proxy():
51
+ """配置系统代理环境变量"""
52
+ if CONFIG["HTTP_PROXY"]:
53
+ os.environ["HTTP_PROXY"] = CONFIG["HTTP_PROXY"]
54
+ os.environ["http_proxy"] = CONFIG["HTTP_PROXY"]
55
+ if CONFIG["HTTPS_PROXY"]:
56
+ os.environ["HTTPS_PROXY"] = CONFIG["HTTPS_PROXY"]
57
+ os.environ["https_proxy"] = CONFIG["HTTPS_PROXY"]
58
+ if CONFIG["HTTP_PROXY"] or CONFIG["HTTPS_PROXY"]:
59
+ print(f"✅ 代理已配置: {CONFIG['HTTPS_PROXY']}")
60
+
61
+
62
+ def collect_files(local_dir: Path) -> list[tuple[Path, str]]:
63
+ """
64
+ 遍历本地目录,收集所有文件及其对应的仓库路径。
65
+
66
+ Returns:
67
+ list of (local_path, repo_path) tuples
68
+ """
69
+ files = []
70
+ for local_path in sorted(local_dir.rglob("*")):
71
+ if local_path.is_file():
72
+ # 计算相对路径,构建仓库内的目标路径
73
+ relative = local_path.relative_to(local_dir)
74
+ repo_path = (
75
+ f"{CONFIG['REPO_BASE_PATH']}/{relative.as_posix()}"
76
+ if CONFIG["REPO_BASE_PATH"]
77
+ else relative.as_posix()
78
+ )
79
+ files.append((local_path, repo_path))
80
+ return files
81
+
82
+
83
+ def select_branch(api: HfApi) -> str:
84
+ """
85
+ 交互式选择上传分支。
86
+ 若 CONFIG["BRANCH"] 已填写则直接使用,否则列出仓库现有分支供用户选择或新建。
87
+ """
88
+ # 如果配置文件中已指定分支,直接使用
89
+ if CONFIG["BRANCH"].strip():
90
+ branch = CONFIG["BRANCH"].strip()
91
+ print(f"📌 使用配置文件中指定的分支: {branch}")
92
+ return branch
93
+
94
+ # 获取仓库现有分支列表
95
+ try:
96
+ refs = api.list_repo_refs(
97
+ repo_id=CONFIG["REPO_ID"],
98
+ repo_type="dataset",
99
+ )
100
+ existing_branches = [b.name for b in refs.branches]
101
+ except Exception:
102
+ existing_branches = []
103
+
104
+ print("\n📋 仓库现有分支:")
105
+ if existing_branches:
106
+ for i, name in enumerate(existing_branches, 1):
107
+ print(f" [{i}] {name}")
108
+ else:
109
+ print(" (暂无分支)")
110
+ print(f" [n] 输入新分支名")
111
+
112
+ while True:
113
+ choice = input("\n请选择分支编号,或输入 'n' 新建分支: ").strip()
114
+ if choice.lower() == "n":
115
+ new_branch = input("请输入新分支名称: ").strip()
116
+ if not new_branch:
117
+ print(" ⚠️ 分支名不能为空,请重新输入。")
118
+ continue
119
+ return new_branch
120
+ elif choice.isdigit() and 1 <= int(choice) <= len(existing_branches):
121
+ return existing_branches[int(choice) - 1]
122
+ else:
123
+ print(" ⚠️ 无效输入,请重试。")
124
+
125
+
126
+ def ensure_branch_exists(api: HfApi, branch: str):
127
+ """
128
+ 检查分支是否存在,若不存在则从 main 分支创建。
129
+ """
130
+ try:
131
+ refs = api.list_repo_refs(
132
+ repo_id=CONFIG["REPO_ID"],
133
+ repo_type="dataset",
134
+ )
135
+ existing = [b.name for b in refs.branches]
136
+ except Exception:
137
+ existing = []
138
+
139
+ if branch not in existing:
140
+ print(f" 🌿 分支 '{branch}' 不存在,正在从 main 创建...")
141
+ try:
142
+ api.create_branch(
143
+ repo_id=CONFIG["REPO_ID"],
144
+ repo_type="dataset",
145
+ branch=branch,
146
+ )
147
+ print(f" ✅ 分支 '{branch}' 创建成功!")
148
+ except Exception as e:
149
+ print(f" ❌ 分支创建失败: {e}")
150
+ import sys; sys.exit(1)
151
+ else:
152
+ print(f" ✅ 分支 '{branch}' 已存在。")
153
+
154
+
155
+ def upload_in_batches(api: HfApi, files: list[tuple[Path, str]], branch: str):
156
+ """
157
+ 将文件分批次提交到 Hugging Face 指定分支,每批次显示进度条。
158
+ """
159
+ total_files = len(files)
160
+ batch_size = CONFIG["BATCH_SIZE"]
161
+ total_batches = (total_files + batch_size - 1) // batch_size
162
+
163
+ print(f"\n📦 共 {total_files} 个文件,分 {total_batches} 批次上传(每批 {batch_size} 个)\n")
164
+
165
+ for batch_idx in range(total_batches):
166
+ start = batch_idx * batch_size
167
+ end = min(start + batch_size, total_files)
168
+ batch = files[start:end]
169
+
170
+ print(f"── 批次 [{batch_idx + 1}/{total_batches}],共 {len(batch)} 个文件 ──")
171
+
172
+ # 构建 CommitOperation 列表,并显示进度条
173
+ operations = []
174
+ with tqdm(batch, desc=" 准备文件", unit="file", ncols=80) as pbar:
175
+ for local_path, repo_path in pbar:
176
+ pbar.set_postfix_str(local_path.name[:30])
177
+ operations.append(
178
+ CommitOperationAdd(
179
+ path_in_repo=repo_path,
180
+ path_or_fileobj=str(local_path),
181
+ )
182
+ )
183
+
184
+ # 提交本批次
185
+ print(f" ⬆️ 正在上传到分支 '{branch}'...")
186
+ try:
187
+ api.create_commit(
188
+ repo_id=CONFIG["REPO_ID"],
189
+ repo_type="dataset",
190
+ operations=operations,
191
+ commit_message=f"upload: batch {batch_idx + 1}/{total_batches} ({len(batch)} files)",
192
+ revision=branch,
193
+ )
194
+ print(f" ✅ 批次 {batch_idx + 1} 上传成功!({start + 1}~{end} / {total_files})\n")
195
+ except Exception as e:
196
+ print(f" ❌ 批次 {batch_idx + 1} 上传失败: {e}")
197
+ print(" ⚠️ 您可以修改脚本的 start_from_batch 变量后重新运行以跳过已上传的批次。")
198
+ sys.exit(1)
199
+
200
+
201
+ def main():
202
+ setup_proxy()
203
+
204
+ local_dir = Path(CONFIG["LOCAL_DATASET_DIR"]).resolve()
205
+ if not local_dir.exists():
206
+ print(f"❌ 本地数据集目录不存在: {local_dir}")
207
+ sys.exit(1)
208
+
209
+ print(f"📂 本地目录: {local_dir}")
210
+ print(f"🎯 目标仓库: https://huggingface.co/datasets/{CONFIG['REPO_ID']}")
211
+
212
+ # 收集文件列表
213
+ print("\n🔍 正在扫描文件...")
214
+ files = collect_files(local_dir)
215
+ if not files:
216
+ print("⚠️ 未找到任何文件,请检查目录路径。")
217
+ sys.exit(0)
218
+
219
+ # 按文件大小统计
220
+ total_size = sum(p.stat().st_size for p, _ in files)
221
+ print(f"📊 找到 {len(files)} 个文件,总大小: {total_size / 1024 / 1024:.1f} MB")
222
+
223
+ # 显示文件类型分布
224
+ suffixes = {}
225
+ for p, _ in files:
226
+ ext = p.suffix.lower() or "(无后缀)"
227
+ suffixes[ext] = suffixes.get(ext, 0) + 1
228
+ for ext, cnt in sorted(suffixes.items(), key=lambda x: -x[1]):
229
+ print(f" {ext:12s} × {cnt}")
230
+
231
+ # 确认上传
232
+ print()
233
+ confirm = input("确认开始上传?(y/n): ").strip().lower()
234
+ if confirm != "y":
235
+ print("已取消。")
236
+ sys.exit(0)
237
+
238
+ # 初始化 API
239
+ api = HfApi()
240
+
241
+ # 确保仓库存在(不存在则自动创建)
242
+ try:
243
+ api.repo_info(repo_id=CONFIG["REPO_ID"], repo_type="dataset")
244
+ print(f"\n✅ 仓库已存在。")
245
+ except Exception:
246
+ print(f"\n⚠️ 仓库不存在,正在创建: {CONFIG['REPO_ID']}")
247
+ api.create_repo(
248
+ repo_id=CONFIG["REPO_ID"],
249
+ repo_type="dataset",
250
+ private=False,
251
+ )
252
+
253
+ # 选择上传分支
254
+ branch = select_branch(api)
255
+ ensure_branch_exists(api, branch)
256
+ print(f"\n🚀 准备上传至分支: [{branch}]")
257
+
258
+ # 确认上传
259
+ print()
260
+ confirm = input("确认开始上传?(y/n): ").strip().lower()
261
+ if confirm != "y":
262
+ print("已取消。")
263
+ sys.exit(0)
264
+
265
+ # 分批上传
266
+ upload_in_batches(api, files, branch)
267
+
268
+ print("=" * 60)
269
+ print(f"🎉 所有文件上传完成!")
270
+ print(f"🔗 访问地址: https://huggingface.co/datasets/{CONFIG['REPO_ID']}/tree/{branch}")
271
+ print("=" * 60)
272
+
273
+
274
+ if __name__ == "__main__":
275
+ main()