File size: 9,393 Bytes
407171b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ff39e1
407171b
 
e00c89e
407171b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
"""
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()