File size: 5,512 Bytes
a6c64ec 14ba72f a6c64ec 1481d6f a6c64ec 14ba72f a6c64ec 14ba72f a6c64ec | 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 | #!/usr/bin/env python
"""
Simple script to upload (large) files to Hugging Face Hub.
Usage example:
HF_TOKEN=hf_xxx python upload_to_hf.py \
--repo-id your-username/your-repo \
--file /path/to/large_file.bin \
--repo-type model \
--create \
--private
Install dependency:
pip install huggingface_hub
"""
import argparse
import os
import sys
from pathlib import Path
import io
from huggingface_hub import HfApi
try:
# Newer huggingface_hub versions
from huggingface_hub.utils import HfHubHTTPError # type: ignore[attr-defined]
except Exception: # pragma: no cover
# Fallback for older / different versions
from huggingface_hub import HfHubError as HfHubHTTPError # type: ignore[assignment]
def _format_size(num_bytes: int) -> str:
"""Return human-readable size with automatic units."""
units = ["B", "KB", "MB", "GB", "TB"]
size = float(num_bytes)
for unit in units:
if size < 1024.0 or unit == units[-1]:
return f"{size:.2f} {unit}"
size /= 1024.0
class ProgressFile(io.BufferedReader):
"""BufferedReader subclass that prints upload progress based on bytes read."""
def __init__(self, path: Path, total_size: int) -> None:
raw = path.open("rb")
super().__init__(raw)
self._total_size = max(total_size, 1)
self._seen = 0
self._last_percent = -1
def read(self, size: int = -1) -> bytes: # type: ignore[override]
chunk = super().read(size)
if not chunk:
return chunk
# Clamp seen bytes so progress never exceeds 100%.
self._seen = min(self._seen + len(chunk), self._total_size)
percent = int(self._seen * 100 / self._total_size)
if percent != self._last_percent:
self._last_percent = percent
seen_str = _format_size(self._seen)
total_str = _format_size(self._total_size)
print(
f"\rProgress: {percent:3d}% ({seen_str} / {total_str})",
end="",
flush=True,
)
return chunk
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Upload (large) files to Hugging Face Hub using huggingface_hub."
)
parser.add_argument(
"--repo-id",
required=True,
help="Target repo on Hugging Face, e.g. 'username/my-model' or 'org/my-dataset'.",
)
parser.add_argument(
"--file",
required=True,
help="Local path to the file to upload.",
)
parser.add_argument(
"--path-in-repo",
default=None,
help="Destination path inside the repo (default: basename of --file).",
)
parser.add_argument(
"--repo-type",
default="model",
choices=["model", "dataset", "space"],
help="Type of repo to upload to (default: model).",
)
parser.add_argument(
"--branch",
default="main",
help="Branch/revision to upload to (default: main).",
)
parser.add_argument(
"--message",
default="Upload file",
help="Commit message for the upload.",
)
parser.add_argument(
"--token",
default=os.getenv("HF_TOKEN"),
help="Hugging Face token. If not set, uses HF_TOKEN env var.",
)
parser.add_argument(
"--create",
action="store_true",
help="Create the repo if it doesn't exist.",
)
parser.add_argument(
"--private",
action="store_true",
help="If creating a repo, make it private.",
)
return parser.parse_args()
def main() -> None:
args = parse_args()
if not args.token:
print(
"Error: Hugging Face token not provided. "
"Pass --token or set HF_TOKEN environment variable.",
file=sys.stderr,
)
sys.exit(1)
file_path = Path(args.file).expanduser().resolve()
if not file_path.is_file():
print(f"Error: file not found: {file_path}", file=sys.stderr)
sys.exit(1)
path_in_repo = args.path_in_repo or file_path.name
file_size = file_path.stat().st_size
api = HfApi(token=args.token)
if args.create:
try:
api.create_repo(
repo_id=args.repo_id,
repo_type=args.repo_type,
private=bool(args.private),
exist_ok=True,
)
print(
f"Ensured repo '{args.repo_id}' (type={args.repo_type}, private={args.private})."
)
except HfHubHTTPError as e:
print(f"Error while creating/ensuring repo: {e}", file=sys.stderr)
sys.exit(1)
print(
f"Uploading '{file_path}' to repo '{args.repo_id}' "
f"as '{path_in_repo}' (type={args.repo_type}, branch={args.branch})..."
)
progress_file = ProgressFile(file_path, file_size)
try:
api.upload_file(
path_or_fileobj=progress_file,
path_in_repo=path_in_repo,
repo_id=args.repo_id,
repo_type=args.repo_type,
commit_message=args.message,
revision=args.branch,
)
except HfHubHTTPError as e:
print(f"Upload failed: {e}", file=sys.stderr)
sys.exit(1)
finally:
progress_file.close()
# Ensure the progress line is finished
print()
print("Upload completed successfully.")
if __name__ == "__main__":
main()
|