| |
| """ |
| 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: |
| |
| from huggingface_hub.utils import HfHubHTTPError |
| except Exception: |
| |
| from huggingface_hub import HfHubError as HfHubHTTPError |
|
|
|
|
| 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: |
| chunk = super().read(size) |
| if not chunk: |
| return chunk |
|
|
| |
| 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() |
| |
| print() |
|
|
| print("Upload completed successfully.") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|
|
|