Datasets:

Modalities:
Image
Languages:
English
ArXiv:
Tags:
code
License:
yueyin27 commited on
Commit
a6c64ec
·
verified ·
1 Parent(s): f11672a

Upload file

Browse files
Files changed (1) hide show
  1. upload_to_hf.py +180 -0
upload_to_hf.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """
3
+ Simple script to upload (large) files to Hugging Face Hub.
4
+
5
+ Usage example:
6
+ HF_TOKEN=hf_xxx python upload_to_hf.py \
7
+ --repo-id your-username/your-repo \
8
+ --file /path/to/large_file.bin \
9
+ --repo-type model \
10
+ --create \
11
+ --private
12
+
13
+ Install dependency:
14
+ pip install huggingface_hub
15
+ """
16
+
17
+ import argparse
18
+ import os
19
+ import sys
20
+ from pathlib import Path
21
+ import io
22
+
23
+ from huggingface_hub import HfApi
24
+
25
+ try:
26
+ # Newer huggingface_hub versions
27
+ from huggingface_hub.utils import HfHubHTTPError # type: ignore[attr-defined]
28
+ except Exception: # pragma: no cover
29
+ # Fallback for older / different versions
30
+ from huggingface_hub import HfHubError as HfHubHTTPError # type: ignore[assignment]
31
+
32
+
33
+ class ProgressFile(io.BufferedReader):
34
+ """BufferedReader subclass that prints upload progress based on bytes read."""
35
+
36
+ def __init__(self, path: Path, total_size: int) -> None:
37
+ raw = path.open("rb")
38
+ super().__init__(raw)
39
+ self._total_size = max(total_size, 1)
40
+ self._seen = 0
41
+ self._last_percent = -1
42
+
43
+ def read(self, size: int = -1) -> bytes: # type: ignore[override]
44
+ chunk = super().read(size)
45
+ if not chunk:
46
+ return chunk
47
+
48
+ self._seen += len(chunk)
49
+ percent = int(self._seen * 100 / self._total_size)
50
+ if percent != self._last_percent:
51
+ self._last_percent = percent
52
+ gb_seen = self._seen / (1024**3)
53
+ gb_total = self._total_size / (1024**3)
54
+ print(
55
+ f"\rProgress: {percent:3d}% ({gb_seen:.2f} / {gb_total:.2f} GB)",
56
+ end="",
57
+ flush=True,
58
+ )
59
+ return chunk
60
+
61
+
62
+ def parse_args() -> argparse.Namespace:
63
+ parser = argparse.ArgumentParser(
64
+ description="Upload (large) files to Hugging Face Hub using huggingface_hub."
65
+ )
66
+ parser.add_argument(
67
+ "--repo-id",
68
+ required=True,
69
+ help="Target repo on Hugging Face, e.g. 'username/my-model' or 'org/my-dataset'.",
70
+ )
71
+ parser.add_argument(
72
+ "--file",
73
+ required=True,
74
+ help="Local path to the file to upload.",
75
+ )
76
+ parser.add_argument(
77
+ "--path-in-repo",
78
+ default=None,
79
+ help="Destination path inside the repo (default: basename of --file).",
80
+ )
81
+ parser.add_argument(
82
+ "--repo-type",
83
+ default="model",
84
+ choices=["model", "dataset", "space"],
85
+ help="Type of repo to upload to (default: model).",
86
+ )
87
+ parser.add_argument(
88
+ "--branch",
89
+ default="main",
90
+ help="Branch/revision to upload to (default: main).",
91
+ )
92
+ parser.add_argument(
93
+ "--message",
94
+ default="Upload file",
95
+ help="Commit message for the upload.",
96
+ )
97
+ parser.add_argument(
98
+ "--token",
99
+ default=os.getenv("HF_TOKEN"),
100
+ help="Hugging Face token. If not set, uses HF_TOKEN env var.",
101
+ )
102
+ parser.add_argument(
103
+ "--create",
104
+ action="store_true",
105
+ help="Create the repo if it doesn't exist.",
106
+ )
107
+ parser.add_argument(
108
+ "--private",
109
+ action="store_true",
110
+ help="If creating a repo, make it private.",
111
+ )
112
+ return parser.parse_args()
113
+
114
+
115
+ def main() -> None:
116
+ args = parse_args()
117
+
118
+ if not args.token:
119
+ print(
120
+ "Error: Hugging Face token not provided. "
121
+ "Pass --token or set HF_TOKEN environment variable.",
122
+ file=sys.stderr,
123
+ )
124
+ sys.exit(1)
125
+
126
+ file_path = Path(args.file).expanduser().resolve()
127
+ if not file_path.is_file():
128
+ print(f"Error: file not found: {file_path}", file=sys.stderr)
129
+ sys.exit(1)
130
+
131
+ path_in_repo = args.path_in_repo or file_path.name
132
+ file_size = file_path.stat().st_size
133
+
134
+ api = HfApi(token=args.token)
135
+
136
+ if args.create:
137
+ try:
138
+ api.create_repo(
139
+ repo_id=args.repo_id,
140
+ repo_type=args.repo_type,
141
+ private=bool(args.private),
142
+ exist_ok=True,
143
+ )
144
+ print(
145
+ f"Ensured repo '{args.repo_id}' (type={args.repo_type}, private={args.private})."
146
+ )
147
+ except HfHubHTTPError as e:
148
+ print(f"Error while creating/ensuring repo: {e}", file=sys.stderr)
149
+ sys.exit(1)
150
+
151
+ print(
152
+ f"Uploading '{file_path}' to repo '{args.repo_id}' "
153
+ f"as '{path_in_repo}' (type={args.repo_type}, branch={args.branch})..."
154
+ )
155
+
156
+ progress_file = ProgressFile(file_path, file_size)
157
+
158
+ try:
159
+ api.upload_file(
160
+ path_or_fileobj=progress_file,
161
+ path_in_repo=path_in_repo,
162
+ repo_id=args.repo_id,
163
+ repo_type=args.repo_type,
164
+ commit_message=args.message,
165
+ revision=args.branch,
166
+ )
167
+ except HfHubHTTPError as e:
168
+ print(f"Upload failed: {e}", file=sys.stderr)
169
+ sys.exit(1)
170
+ finally:
171
+ progress_file.close()
172
+ # Ensure the progress line is finished
173
+ print()
174
+
175
+ print("Upload completed successfully.")
176
+
177
+
178
+ if __name__ == "__main__":
179
+ main()
180
+