File size: 3,337 Bytes
5b7e9c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Upload the current repo to a fresh HuggingFace dataset via the Hub HTTP API.
Uploads only git-tracked files — raw SLTrans language folders are ignored.

Usage:
    python upload_to_hub.py
    python upload_to_hub.py --repo nlpscu/Multilingual-Code-Generator --private
"""

import argparse
import subprocess
import sys
from pathlib import Path

from huggingface_hub import HfApi


def git_tracked_files() -> list[str]:
    result = subprocess.run(
        ["git", "ls-files"],
        capture_output=True, text=True, cwd=Path(__file__).parent,
    )
    if result.returncode != 0:
        print("ERROR: not inside a git repo or git not found", file=sys.stderr)
        sys.exit(1)
    return [f for f in result.stdout.strip().splitlines() if f]


def main():
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--repo",    default="st-taro/csen346_temp",
                    help="HuggingFace dataset repo id  (default: st-taro/csen346_temp)")
    ap.add_argument("--private", action="store_true", default=False,
                    help="Create as private repo (note: private repos have a 10 GB LFS limit)")
    ap.add_argument("--dry-run", action="store_true",
                    help="Print files that would be uploaded without uploading")
    args = ap.parse_args()

    root = Path(__file__).parent
    files = git_tracked_files()

    print(f"Repo   : {args.repo}")
    print(f"Private: {args.private}")
    print(f"Files  : {len(files)}")
    for f in files:
        size = (root / f).stat().st_size if (root / f).exists() else 0
        print(f"  {f}  ({size / 1e6:.1f} MB)")

    if args.dry_run:
        print("\nDry run — nothing uploaded.")
        return

    api = HfApi()

    # Create repo (no-op if already exists)
    try:
        api.create_repo(
            repo_id=args.repo,
            repo_type="dataset",
            private=args.private,
            exist_ok=True,
        )
        print(f"\nRepo ready: https://huggingface.co/datasets/{args.repo}")
    except Exception as e:
        print(f"ERROR creating repo: {e}", file=sys.stderr)
        sys.exit(1)

    # Upload files one at a time so progress is visible and failures are isolated
    failed = []
    for i, filepath in enumerate(files, 1):
        local = root / filepath
        if not local.exists():
            print(f"[{i}/{len(files)}] SKIP (not on disk): {filepath}")
            continue
        size_mb = local.stat().st_size / 1e6
        print(f"[{i}/{len(files)}] {filepath}  ({size_mb:.1f} MB) ... ", end="", flush=True)
        try:
            api.upload_file(
                path_or_fileobj=str(local),
                path_in_repo=filepath,
                repo_id=args.repo,
                repo_type="dataset",
            )
            print("done")
        except Exception as e:
            print(f"FAILED: {e}")
            failed.append((filepath, str(e)))

    print()
    if failed:
        print(f"Upload finished with {len(failed)} failure(s):")
        for f, err in failed:
            print(f"  {f}: {err}")
        sys.exit(1)
    else:
        print(f"All {len(files)} files uploaded.")
        print(f"Dataset: https://huggingface.co/datasets/{args.repo}")


if __name__ == "__main__":
    main()