text
stringlengths
1
1.02k
class_index
int64
0
305
source
stringclasses
77 values
auth_parser = parser.add_parser("auth", help="Other authentication related commands") auth_subparsers = auth_parser.add_subparsers(help="Authentication subcommands") auth_switch_parser = auth_subparsers.add_parser("switch", help="Switch between access tokens") auth_switch_parser.add_argument( "--token-name", type=str, help="Optional: Name of the access token to switch to.", ) auth_switch_parser.add_argument( "--add-to-git-credential", action="store_true", help="Optional: Save token to git credential helper.", ) auth_switch_parser.set_defaults(func=lambda args: AuthSwitchCommand(args)) auth_list_parser = auth_subparsers.add_parser("list", help="List all stored access tokens") auth_list_parser.set_defaults(func=lambda args: AuthListCommand(args)) # new system: git-based repo system
279
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/user.py
repo_parser = parser.add_parser("repo", help="{create} Commands to interact with your huggingface.co repos.") repo_subparsers = repo_parser.add_subparsers(help="huggingface.co repos related commands") repo_create_parser = repo_subparsers.add_parser("create", help="Create a new repo on huggingface.co") repo_create_parser.add_argument( "name", type=str, help="Name for your repo. Will be namespaced under your username to build the repo id.", ) repo_create_parser.add_argument( "--type", type=str, help='Optional: repo_type: set to "dataset" or "space" if creating a dataset or space, default is model.', ) repo_create_parser.add_argument("--organization", type=str, help="Optional: organization namespace.") repo_create_parser.add_argument( "--space_sdk", type=str,
279
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/user.py
help='Optional: Hugging Face Spaces SDK type. Required when --type is set to "space".', choices=SPACES_SDK_TYPES, ) repo_create_parser.add_argument( "-y", "--yes", action="store_true", help="Optional: answer Yes to the prompt", ) repo_create_parser.set_defaults(func=lambda args: RepoCreateCommand(args))
279
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/user.py
class BaseUserCommand: def __init__(self, args): self.args = args self._api = HfApi()
280
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/user.py
class LoginCommand(BaseUserCommand): def run(self): logging.set_verbosity_info() login( token=self.args.token, add_to_git_credential=self.args.add_to_git_credential, )
281
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/user.py
class LogoutCommand(BaseUserCommand): def run(self): logging.set_verbosity_info() logout(token_name=self.args.token_name)
282
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/user.py
class AuthSwitchCommand(BaseUserCommand): def run(self): logging.set_verbosity_info() token_name = self.args.token_name if token_name is None: token_name = self._select_token_name() if token_name is None: print("No token name provided. Aborting.") exit() auth_switch(token_name, add_to_git_credential=self.args.add_to_git_credential) def _select_token_name(self) -> Optional[str]: token_names = list(get_stored_tokens().keys()) if not token_names: logger.error("No stored tokens found. Please login first.") return None
283
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/user.py
if _inquirer_py_available: return self._select_token_name_tui(token_names) # if inquirer is not available, use a simpler terminal UI print("Available stored tokens:") for i, token_name in enumerate(token_names, 1): print(f"{i}. {token_name}") while True: try: choice = input("Enter the number of the token to switch to (or 'q' to quit): ") if choice.lower() == "q": return None index = int(choice) - 1 if 0 <= index < len(token_names): return token_names[index] else: print("Invalid selection. Please try again.") except ValueError: print("Invalid input. Please enter a number or 'q' to quit.")
283
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/user.py
def _select_token_name_tui(self, token_names: List[str]) -> Optional[str]: choices = [Choice(token_name, name=token_name) for token_name in token_names] try: return inquirer.select( message="Select a token to switch to:", choices=choices, default=None, ).execute() except KeyboardInterrupt: logger.info("Token selection cancelled.") return None
283
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/user.py
class AuthListCommand(BaseUserCommand): def run(self): logging.set_verbosity_info() auth_list()
284
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/user.py
class WhoamiCommand(BaseUserCommand): def run(self): token = get_token() if token is None: print("Not logged in") exit() try: info = self._api.whoami(token) print(info["name"]) orgs = [org["name"] for org in info["orgs"]] if orgs: print(ANSI.bold("orgs: "), ",".join(orgs)) if ENDPOINT != "https://huggingface.co": print(f"Authenticated through private endpoint: {ENDPOINT}") except HTTPError as e: print(e) print(ANSI.red(e.response.text)) exit(1)
285
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/user.py
class RepoCreateCommand(BaseUserCommand): def run(self): token = get_token() if token is None: print("Not logged in") exit(1) try: stdout = subprocess.check_output(["git", "--version"]).decode("utf-8") print(ANSI.gray(stdout.strip())) except FileNotFoundError: print("Looks like you do not have git installed, please install.") try: stdout = subprocess.check_output(["git-lfs", "--version"]).decode("utf-8") print(ANSI.gray(stdout.strip())) except FileNotFoundError: print( ANSI.red( "Looks like you do not have git-lfs installed, please install." " You can install from https://git-lfs.github.com/." " Then run `git lfs install` (you only have to do this once)." ) ) print("")
286
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/user.py
user = self._api.whoami(token)["name"] namespace = self.args.organization if self.args.organization is not None else user repo_id = f"{namespace}/{self.args.name}" if self.args.type not in REPO_TYPES: print("Invalid repo --type") exit(1) if self.args.type in REPO_TYPES_URL_PREFIXES: prefixed_repo_id = REPO_TYPES_URL_PREFIXES[self.args.type] + repo_id else: prefixed_repo_id = repo_id print(f"You are about to create {ANSI.bold(prefixed_repo_id)}")
286
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/user.py
if not self.args.yes: choice = input("Proceed? [Y/n] ").lower() if not (choice == "" or choice == "y" or choice == "yes"): print("Abort") exit() try: url = self._api.create_repo( repo_id=repo_id, token=token, repo_type=self.args.type, space_sdk=self.args.space_sdk, ) except HTTPError as e: print(e) print(ANSI.red(e.response.text)) exit(1) print("\nYour repo now lives at:") print(f" {ANSI.bold(url)}") print("\nYou can clone it locally with the command below, and commit/push as usual.") print(f"\n git clone {url}") print("")
286
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/user.py
class VersionCommand(BaseHuggingfaceCLICommand): def __init__(self, args): self.args = args @staticmethod def register_subcommand(parser: _SubParsersAction): version_parser = parser.add_parser("version", help="Print information about the huggingface-cli version.") version_parser.set_defaults(func=VersionCommand) def run(self) -> None: print(f"huggingface_hub version: {__version__}")
287
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/version.py
class EnvironmentCommand(BaseHuggingfaceCLICommand): def __init__(self, args): self.args = args @staticmethod def register_subcommand(parser: _SubParsersAction): env_parser = parser.add_parser("env", help="Print information about the environment.") env_parser.set_defaults(func=EnvironmentCommand) def run(self) -> None: dump_environment_info()
288
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/env.py
class UploadCommand(BaseHuggingfaceCLICommand): @staticmethod def register_subcommand(parser: _SubParsersAction): upload_parser = parser.add_parser("upload", help="Upload a file or a folder to a repo on the Hub") upload_parser.add_argument( "repo_id", type=str, help="The ID of the repo to upload to (e.g. `username/repo-name`)." ) upload_parser.add_argument( "local_path", nargs="?", help="Local path to the file or folder to upload. Defaults to current directory." ) upload_parser.add_argument( "path_in_repo", nargs="?", help="Path of the file or folder in the repo. Defaults to the relative path of the file or folder.", ) upload_parser.add_argument( "--repo-type", choices=["model", "dataset", "space"], default="model", help="Type of the repo to upload to (e.g. `dataset`).", ) upload_parser.add_argument(
289
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/upload.py
"--revision", type=str, help=( "An optional Git revision to push to. It can be a branch name or a PR reference. If revision does not" " exist and `--create-pr` is not set, a branch will be automatically created." ), ) upload_parser.add_argument( "--private", action="store_true", help=( "Whether to create a private repo if repo doesn't exist on the Hub. Ignored if the repo already" " exists." ), ) upload_parser.add_argument("--include", nargs="*", type=str, help="Glob patterns to match files to upload.") upload_parser.add_argument( "--exclude", nargs="*", type=str, help="Glob patterns to exclude from files to upload." ) upload_parser.add_argument( "--delete", nargs="*", type=str,
289
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/upload.py
help="Glob patterns for file to be deleted from the repo while committing.", ) upload_parser.add_argument( "--commit-message", type=str, help="The summary / title / first line of the generated commit." ) upload_parser.add_argument("--commit-description", type=str, help="The description of the generated commit.") upload_parser.add_argument( "--create-pr", action="store_true", help="Whether to upload content as a new Pull Request." ) upload_parser.add_argument( "--every", type=float, help="If set, a background job is scheduled to create commits every `every` minutes.", ) upload_parser.add_argument( "--token", type=str, help="A User Access Token generated from https://huggingface.co/settings/tokens" ) upload_parser.add_argument( "--quiet", action="store_true",
289
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/upload.py
help="If True, progress bars are disabled and only the path to the uploaded files is printed.", ) upload_parser.set_defaults(func=UploadCommand)
289
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/upload.py
def __init__(self, args: Namespace) -> None: self.repo_id: str = args.repo_id self.repo_type: Optional[str] = args.repo_type self.revision: Optional[str] = args.revision self.private: bool = args.private self.include: Optional[List[str]] = args.include self.exclude: Optional[List[str]] = args.exclude self.delete: Optional[List[str]] = args.delete self.commit_message: Optional[str] = args.commit_message self.commit_description: Optional[str] = args.commit_description self.create_pr: bool = args.create_pr self.api: HfApi = HfApi(token=args.token, library_name="huggingface-cli") self.quiet: bool = args.quiet # disable warnings and progress bars # Check `--every` is valid if args.every is not None and args.every <= 0: raise ValueError(f"`every` must be a positive value (got '{args.every}')") self.every: Optional[float] = args.every
289
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/upload.py
# Resolve `local_path` and `path_in_repo` repo_name: str = args.repo_id.split("/")[-1] # e.g. "Wauplin/my-cool-model" => "my-cool-model" self.local_path: str self.path_in_repo: str if args.local_path is None and os.path.isfile(repo_name): # Implicit case 1: user provided only a repo_id which happen to be a local file as well => upload it with same name self.local_path = repo_name self.path_in_repo = repo_name elif args.local_path is None and os.path.isdir(repo_name): # Implicit case 2: user provided only a repo_id which happen to be a local folder as well => upload it at root self.local_path = repo_name self.path_in_repo = "." elif args.local_path is None: # Implicit case 3: user provided only a repo_id that does not match a local file or folder # => the user must explicitly provide a local_path => raise exception
289
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/upload.py
raise ValueError(f"'{repo_name}' is not a local file or folder. Please set `local_path` explicitly.") elif args.path_in_repo is None and os.path.isfile(args.local_path): # Explicit local path to file, no path in repo => upload it at root with same name self.local_path = args.local_path self.path_in_repo = os.path.basename(args.local_path) elif args.path_in_repo is None: # Explicit local path to folder, no path in repo => upload at root self.local_path = args.local_path self.path_in_repo = "." else: # Finally, if both paths are explicit self.local_path = args.local_path self.path_in_repo = args.path_in_repo
289
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/upload.py
def run(self) -> None: if self.quiet: disable_progress_bars() with warnings.catch_warnings(): warnings.simplefilter("ignore") print(self._upload()) enable_progress_bars() else: logging.set_verbosity_info() print(self._upload()) logging.set_verbosity_warning() def _upload(self) -> str: if os.path.isfile(self.local_path): if self.include is not None and len(self.include) > 0: warnings.warn("Ignoring `--include` since a single file is uploaded.") if self.exclude is not None and len(self.exclude) > 0: warnings.warn("Ignoring `--exclude` since a single file is uploaded.") if self.delete is not None and len(self.delete) > 0: warnings.warn("Ignoring `--delete` since a single file is uploaded.")
289
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/upload.py
if not HF_HUB_ENABLE_HF_TRANSFER: logger.info( "Consider using `hf_transfer` for faster uploads. This solution comes with some limitations. See" " https://huggingface.co/docs/huggingface_hub/hf_transfer for more details." )
289
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/upload.py
# Schedule commits if `every` is set if self.every is not None: if os.path.isfile(self.local_path): # If file => watch entire folder + use allow_patterns folder_path = os.path.dirname(self.local_path) path_in_repo = ( self.path_in_repo[: -len(self.local_path)] # remove filename from path_in_repo if self.path_in_repo.endswith(self.local_path) else self.path_in_repo ) allow_patterns = [self.local_path] ignore_patterns = [] else: folder_path = self.local_path path_in_repo = self.path_in_repo allow_patterns = self.include or [] ignore_patterns = self.exclude or [] if self.delete is not None and len(self.delete) > 0: warnings.warn("Ignoring `--delete` when uploading with scheduled commits.")
289
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/upload.py
scheduler = CommitScheduler( folder_path=folder_path, repo_id=self.repo_id, repo_type=self.repo_type, revision=self.revision, allow_patterns=allow_patterns, ignore_patterns=ignore_patterns, path_in_repo=path_in_repo, private=self.private, every=self.every, hf_api=self.api, ) print(f"Scheduling commits every {self.every} minutes to {scheduler.repo_id}.") try: # Block main thread until KeyboardInterrupt while True: time.sleep(100) except KeyboardInterrupt: scheduler.stop() return "Stopped scheduled commits."
289
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/upload.py
# Otherwise, create repo and proceed with the upload if not os.path.isfile(self.local_path) and not os.path.isdir(self.local_path): raise FileNotFoundError(f"No such file or directory: '{self.local_path}'.") repo_id = self.api.create_repo( repo_id=self.repo_id, repo_type=self.repo_type, exist_ok=True, private=self.private, space_sdk="gradio" if self.repo_type == "space" else None, # ^ We don't want it to fail when uploading to a Space => let's set Gradio by default. # ^ I'd rather not add CLI args to set it explicitly as we already have `huggingface-cli repo create` for that. ).repo_id
289
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/upload.py
# Check if branch already exists and if not, create it if self.revision is not None and not self.create_pr: try: self.api.repo_info(repo_id=repo_id, repo_type=self.repo_type, revision=self.revision) except RevisionNotFoundError: logger.info(f"Branch '{self.revision}' not found. Creating it...") self.api.create_branch(repo_id=repo_id, repo_type=self.repo_type, branch=self.revision, exist_ok=True) # ^ `exist_ok=True` to avoid race concurrency issues
289
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/upload.py
# File-based upload if os.path.isfile(self.local_path): return self.api.upload_file( path_or_fileobj=self.local_path, path_in_repo=self.path_in_repo, repo_id=repo_id, repo_type=self.repo_type, revision=self.revision, commit_message=self.commit_message, commit_description=self.commit_description, create_pr=self.create_pr, )
289
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/upload.py
# Folder-based upload else: return self.api.upload_folder( folder_path=self.local_path, path_in_repo=self.path_in_repo, repo_id=repo_id, repo_type=self.repo_type, revision=self.revision, commit_message=self.commit_message, commit_description=self.commit_description, create_pr=self.create_pr, allow_patterns=self.include, ignore_patterns=self.exclude, delete_patterns=self.delete, )
289
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/upload.py
class DeleteCacheCommand(BaseHuggingfaceCLICommand): @staticmethod def register_subcommand(parser: _SubParsersAction): delete_cache_parser = parser.add_parser("delete-cache", help="Delete revisions from the cache directory.") delete_cache_parser.add_argument( "--dir", type=str, default=None, help="cache directory (optional). Default to the default HuggingFace cache.", ) delete_cache_parser.add_argument( "--disable-tui", action="store_true", help=( "Disable Terminal User Interface (TUI) mode. Useful if your" " platform/terminal doesn't support the multiselect menu." ), ) delete_cache_parser.set_defaults(func=DeleteCacheCommand) def __init__(self, args: Namespace) -> None: self.cache_dir: Optional[str] = args.dir self.disable_tui: bool = args.disable_tui
290
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/delete_cache.py
def run(self): """Run `delete-cache` command with or without TUI.""" # Scan cache directory hf_cache_info = scan_cache_dir(self.cache_dir) # Manual review from the user if self.disable_tui: selected_hashes = _manual_review_no_tui(hf_cache_info, preselected=[]) else: selected_hashes = _manual_review_tui(hf_cache_info, preselected=[]) # If deletion is not cancelled if len(selected_hashes) > 0 and _CANCEL_DELETION_STR not in selected_hashes: confirm_message = _get_expectations_str(hf_cache_info, selected_hashes) + " Confirm deletion ?" # Confirm deletion if self.disable_tui: confirmed = _ask_for_confirmation_no_tui(confirm_message) else: confirmed = _ask_for_confirmation_tui(confirm_message)
290
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/delete_cache.py
# Deletion is confirmed if confirmed: strategy = hf_cache_info.delete_revisions(*selected_hashes) print("Start deletion.") strategy.execute() print( f"Done. Deleted {len(strategy.repos)} repo(s) and" f" {len(strategy.snapshots)} revision(s) for a total of" f" {strategy.expected_freed_size_str}." ) return # Deletion is cancelled print("Deletion is cancelled. Do nothing.")
290
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/delete_cache.py
class ANSI: """ Helper for en.wikipedia.org/wiki/ANSI_escape_code """ _bold = "\u001b[1m" _gray = "\u001b[90m" _red = "\u001b[31m" _reset = "\u001b[0m" _yellow = "\u001b[33m" @classmethod def bold(cls, s: str) -> str: return cls._format(s, cls._bold) @classmethod def gray(cls, s: str) -> str: return cls._format(s, cls._gray) @classmethod def red(cls, s: str) -> str: return cls._format(s, cls._bold + cls._red) @classmethod def yellow(cls, s: str) -> str: return cls._format(s, cls._yellow) @classmethod def _format(cls, s: str, code: str) -> str: if os.environ.get("NO_COLOR"): # See https://no-color.org/ return s return f"{code}{s}{cls._reset}"
291
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/_cli_utils.py
class ScanCacheCommand(BaseHuggingfaceCLICommand): @staticmethod def register_subcommand(parser: _SubParsersAction): scan_cache_parser = parser.add_parser("scan-cache", help="Scan cache directory.") scan_cache_parser.add_argument( "--dir", type=str, default=None, help="cache directory to scan (optional). Default to the default HuggingFace cache.", ) scan_cache_parser.add_argument( "-v", "--verbose", action="count", default=0, help="show a more verbose output", ) scan_cache_parser.set_defaults(func=ScanCacheCommand) def __init__(self, args: Namespace) -> None: self.verbosity: int = args.verbose self.cache_dir: Optional[str] = args.dir
292
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/scan_cache.py
def run(self): try: t0 = time.time() hf_cache_info = scan_cache_dir(self.cache_dir) t1 = time.time() except CacheNotFound as exc: cache_dir = exc.cache_dir print(f"Cache directory not found: {cache_dir}") return self._print_hf_cache_info_as_table(hf_cache_info) print( f"\nDone in {round(t1-t0,1)}s. Scanned {len(hf_cache_info.repos)} repo(s)" f" for a total of {ANSI.red(hf_cache_info.size_on_disk_str)}." ) if len(hf_cache_info.warnings) > 0: message = f"Got {len(hf_cache_info.warnings)} warning(s) while scanning." if self.verbosity >= 3: print(ANSI.gray(message)) for warning in hf_cache_info.warnings: print(ANSI.gray(warning)) else: print(ANSI.gray(message + " Use -vvv to print details."))
292
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/scan_cache.py
def _print_hf_cache_info_as_table(self, hf_cache_info: HFCacheInfo) -> None: print(get_table(hf_cache_info, verbosity=self.verbosity))
292
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/scan_cache.py
class DownloadCommand(BaseHuggingfaceCLICommand): @staticmethod def register_subcommand(parser: _SubParsersAction): download_parser = parser.add_parser("download", help="Download files from the Hub") download_parser.add_argument( "repo_id", type=str, help="ID of the repo to download from (e.g. `username/repo-name`)." ) download_parser.add_argument( "filenames", type=str, nargs="*", help="Files to download (e.g. `config.json`, `data/metadata.jsonl`)." ) download_parser.add_argument( "--repo-type", choices=["model", "dataset", "space"], default="model", help="Type of repo to download from (defaults to 'model').", ) download_parser.add_argument( "--revision", type=str, help="An optional Git revision id which can be a branch name, a tag, or a commit hash.", ) download_parser.add_argument(
293
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/download.py
"--include", nargs="*", type=str, help="Glob patterns to match files to download." ) download_parser.add_argument( "--exclude", nargs="*", type=str, help="Glob patterns to exclude from files to download." ) download_parser.add_argument( "--cache-dir", type=str, help="Path to the directory where to save the downloaded files." ) download_parser.add_argument( "--local-dir", type=str, help=( "If set, the downloaded file will be placed under this directory. Check out" " https://huggingface.co/docs/huggingface_hub/guides/download#download-files-to-local-folder for more" " details." ), ) download_parser.add_argument( "--local-dir-use-symlinks", choices=["auto", "True", "False"], help=("Deprecated and ignored. Downloading to a local directory does not use symlinks anymore."), )
293
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/download.py
download_parser.add_argument( "--force-download", action="store_true", help="If True, the files will be downloaded even if they are already cached.", ) download_parser.add_argument( "--resume-download", action="store_true", help="Deprecated and ignored. Downloading a file to local dir always attempts to resume previously interrupted downloads (unless hf-transfer is enabled).", ) download_parser.add_argument( "--token", type=str, help="A User Access Token generated from https://huggingface.co/settings/tokens" ) download_parser.add_argument( "--quiet", action="store_true", help="If True, progress bars are disabled and only the path to the download files is printed.", ) download_parser.add_argument( "--max-workers", type=int, default=8,
293
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/download.py
help="Maximum number of workers to use for downloading files. Default is 8.", ) download_parser.set_defaults(func=DownloadCommand)
293
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/download.py
def __init__(self, args: Namespace) -> None: self.token = args.token self.repo_id: str = args.repo_id self.filenames: List[str] = args.filenames self.repo_type: str = args.repo_type self.revision: Optional[str] = args.revision self.include: Optional[List[str]] = args.include self.exclude: Optional[List[str]] = args.exclude self.cache_dir: Optional[str] = args.cache_dir self.local_dir: Optional[str] = args.local_dir self.force_download: bool = args.force_download self.resume_download: Optional[bool] = args.resume_download or None self.quiet: bool = args.quiet self.max_workers: int = args.max_workers if args.local_dir_use_symlinks is not None: warnings.warn( "Ignoring --local-dir-use-symlinks. Downloading to a local directory does not use symlinks anymore.", FutureWarning, )
293
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/download.py
def run(self) -> None: if self.quiet: disable_progress_bars() with warnings.catch_warnings(): warnings.simplefilter("ignore") print(self._download()) # Print path to downloaded files enable_progress_bars() else: logging.set_verbosity_info() print(self._download()) # Print path to downloaded files logging.set_verbosity_warning() def _download(self) -> str: # Warn user if patterns are ignored if len(self.filenames) > 0: if self.include is not None and len(self.include) > 0: warnings.warn("Ignoring `--include` since filenames have being explicitly set.") if self.exclude is not None and len(self.exclude) > 0: warnings.warn("Ignoring `--exclude` since filenames have being explicitly set.")
293
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/download.py
# Single file to download: use `hf_hub_download` if len(self.filenames) == 1: return hf_hub_download( repo_id=self.repo_id, repo_type=self.repo_type, revision=self.revision, filename=self.filenames[0], cache_dir=self.cache_dir, resume_download=self.resume_download, force_download=self.force_download, token=self.token, local_dir=self.local_dir, library_name="huggingface-cli", ) # Otherwise: use `snapshot_download` to ensure all files comes from same revision elif len(self.filenames) == 0: allow_patterns = self.include ignore_patterns = self.exclude else: allow_patterns = self.filenames ignore_patterns = None
293
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/download.py
return snapshot_download( repo_id=self.repo_id, repo_type=self.repo_type, revision=self.revision, allow_patterns=allow_patterns, ignore_patterns=ignore_patterns, resume_download=self.resume_download, force_download=self.force_download, cache_dir=self.cache_dir, token=self.token, local_dir=self.local_dir, library_name="huggingface-cli", max_workers=self.max_workers, )
293
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/download.py
class BaseHuggingfaceCLICommand(ABC): @staticmethod @abstractmethod def register_subcommand(parser: _SubParsersAction): raise NotImplementedError() @abstractmethod def run(self): raise NotImplementedError()
294
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/__init__.py
class LfsCommands(BaseHuggingfaceCLICommand): """ Implementation of a custom transfer agent for the transfer type "multipart" for git-lfs. This lets users upload large files >5GB 🔥. Spec for LFS custom transfer agent is: https://github.com/git-lfs/git-lfs/blob/master/docs/custom-transfers.md This introduces two commands to the CLI: 1. $ huggingface-cli lfs-enable-largefiles This should be executed once for each model repo that contains a model file >5GB. It's documented in the error message you get if you just try to git push a 5GB file without having enabled it before. 2. $ huggingface-cli lfs-multipart-upload This command is called by lfs directly and is not meant to be called by the user. """
295
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/lfs.py
@staticmethod def register_subcommand(parser: _SubParsersAction): enable_parser = parser.add_parser( "lfs-enable-largefiles", help="Configure your repository to enable upload of files > 5GB." ) enable_parser.add_argument("path", type=str, help="Local path to repository you want to configure.") enable_parser.set_defaults(func=lambda args: LfsEnableCommand(args)) # Command will get called by git-lfs, do not call it directly. upload_parser = parser.add_parser(LFS_MULTIPART_UPLOAD_COMMAND, add_help=False) upload_parser.set_defaults(func=lambda args: LfsUploadCommand(args))
295
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/lfs.py
class LfsEnableCommand: def __init__(self, args): self.args = args def run(self): local_path = os.path.abspath(self.args.path) if not os.path.isdir(local_path): print("This does not look like a valid git repo.") exit(1) subprocess.run( "git config lfs.customtransfer.multipart.path huggingface-cli".split(), check=True, cwd=local_path, ) subprocess.run( f"git config lfs.customtransfer.multipart.args {LFS_MULTIPART_UPLOAD_COMMAND}".split(), check=True, cwd=local_path, ) print("Local repo set up for largefiles")
296
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/lfs.py
class LfsUploadCommand: def __init__(self, args) -> None: self.args = args def run(self) -> None: # Immediately after invoking a custom transfer process, git-lfs # sends initiation data to the process over stdin. # This tells the process useful information about the configuration. init_msg = json.loads(sys.stdin.readline().strip()) if not (init_msg.get("event") == "init" and init_msg.get("operation") == "upload"): write_msg({"error": {"code": 32, "message": "Wrong lfs init operation"}}) sys.exit(1) # The transfer process should use the information it needs from the # initiation structure, and also perform any one-off setup tasks it # needs to do. It should then respond on stdout with a simple empty # confirmation structure, as follows: write_msg({})
297
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/lfs.py
# After the initiation exchange, git-lfs will send any number of # transfer requests to the stdin of the transfer process, in a serial sequence. while True: msg = read_msg() if msg is None: # When all transfers have been processed, git-lfs will send # a terminate event to the stdin of the transfer process. # On receiving this message the transfer process should # clean up and terminate. No response is expected. sys.exit(0) oid = msg["oid"] filepath = msg["path"] completion_url = msg["action"]["href"] header = msg["action"]["header"] chunk_size = int(header.pop("chunk_size")) presigned_urls: List[str] = list(header.values())
297
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/lfs.py
# Send a "started" progress event to allow other workers to start. # Otherwise they're delayed until first "progress" event is reported, # i.e. after the first 5GB by default (!) write_msg( { "event": "progress", "oid": oid, "bytesSoFar": 1, "bytesSinceLast": 0, } )
297
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/lfs.py
parts = [] with open(filepath, "rb") as file: for i, presigned_url in enumerate(presigned_urls): with SliceFileObj( file, seek_from=i * chunk_size, read_limit=chunk_size, ) as data: r = get_session().put(presigned_url, data=data) hf_raise_for_status(r) parts.append( { "etag": r.headers.get("etag"), "partNumber": i + 1, } ) # In order to support progress reporting while data is uploading / downloading, # the transfer process should post messages to stdout write_msg( { "event": "progress",
297
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/lfs.py
"oid": oid, "bytesSoFar": (i + 1) * chunk_size, "bytesSinceLast": chunk_size, } ) # Not precise but that's ok.
297
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/lfs.py
r = get_session().post( completion_url, json={ "oid": oid, "parts": parts, }, ) hf_raise_for_status(r) write_msg({"event": "complete", "oid": oid})
297
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/lfs.py
class UploadLargeFolderCommand(BaseHuggingfaceCLICommand): @staticmethod def register_subcommand(parser: _SubParsersAction): subparser = parser.add_parser("upload-large-folder", help="Upload a large folder to a repo on the Hub") subparser.add_argument( "repo_id", type=str, help="The ID of the repo to upload to (e.g. `username/repo-name`)." ) subparser.add_argument("local_path", type=str, help="Local path to the file or folder to upload.") subparser.add_argument( "--repo-type", choices=["model", "dataset", "space"], help="Type of the repo to upload to (e.g. `dataset`).", ) subparser.add_argument( "--revision", type=str, help=("An optional Git revision to push to. It can be a branch name or a PR reference."), ) subparser.add_argument( "--private", action="store_true", help=(
298
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/upload_large_folder.py
"Whether to create a private repo if repo doesn't exist on the Hub. Ignored if the repo already exists." ), ) subparser.add_argument("--include", nargs="*", type=str, help="Glob patterns to match files to upload.") subparser.add_argument("--exclude", nargs="*", type=str, help="Glob patterns to exclude from files to upload.") subparser.add_argument( "--token", type=str, help="A User Access Token generated from https://huggingface.co/settings/tokens" ) subparser.add_argument( "--num-workers", type=int, help="Number of workers to use to hash, upload and commit files." ) subparser.add_argument("--no-report", action="store_true", help="Whether to disable regular status report.") subparser.add_argument("--no-bars", action="store_true", help="Whether to disable progress bars.") subparser.set_defaults(func=UploadLargeFolderCommand)
298
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/upload_large_folder.py
def __init__(self, args: Namespace) -> None: self.repo_id: str = args.repo_id self.local_path: str = args.local_path self.repo_type: str = args.repo_type self.revision: Optional[str] = args.revision self.private: bool = args.private self.include: Optional[List[str]] = args.include self.exclude: Optional[List[str]] = args.exclude self.api: HfApi = HfApi(token=args.token, library_name="huggingface-cli") self.num_workers: Optional[int] = args.num_workers self.no_report: bool = args.no_report self.no_bars: bool = args.no_bars if not os.path.isdir(self.local_path): raise ValueError("Large upload is only supported for folders.") def run(self) -> None: logging.set_verbosity_info()
298
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/upload_large_folder.py
print( ANSI.yellow( "You are about to upload a large folder to the Hub using `huggingface-cli upload-large-folder`. " "This is a new feature so feedback is very welcome!\n" "\n" "A few things to keep in mind:\n" " - Repository limits still apply: https://huggingface.co/docs/hub/repositories-recommendations\n" " - Do not start several processes in parallel.\n" " - You can interrupt and resume the process at any time. " "The script will pick up where it left off except for partially uploaded files that would have to be entirely reuploaded.\n" " - Do not upload the same folder to several repositories. If you need to do so, you must delete the `./.cache/huggingface/` folder first.\n" "\n" f"Some temporary metadata will be stored under `{self.local_path}/.cache/huggingface`.\n"
298
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/upload_large_folder.py
" - You must not modify those files manually.\n" " - You must not delete the `./.cache/huggingface/` folder while a process is running.\n" " - You can delete the `./.cache/huggingface/` folder to reinitialize the upload state when process is not running. Files will have to be hashed and preuploaded again, except for already committed files.\n" "\n" "If the process output is to verbose, you can disable the progress bars with `--no-bars`. " "You can also entirely disable the status report with `--no-report`.\n" "\n" "For more details, run `huggingface-cli upload-large-folder --help` or check the documentation at " "https://huggingface.co/docs/huggingface_hub/guides/upload#upload-a-large-folder." ) )
298
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/upload_large_folder.py
if self.no_bars: disable_progress_bars() self.api.upload_large_folder( repo_id=self.repo_id, folder_path=self.local_path, repo_type=self.repo_type, revision=self.revision, private=self.private, allow_patterns=self.include, ignore_patterns=self.exclude, num_workers=self.num_workers, print_report=not self.no_report, )
298
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/upload_large_folder.py
class TagCommands(BaseHuggingfaceCLICommand): @staticmethod def register_subcommand(parser: _SubParsersAction): tag_parser = parser.add_parser("tag", help="(create, list, delete) tags for a repo in the hub")
299
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/tag.py
tag_parser.add_argument("repo_id", type=str, help="The ID of the repo to tag (e.g. `username/repo-name`).") tag_parser.add_argument("tag", nargs="?", type=str, help="The name of the tag for creation or deletion.") tag_parser.add_argument("-m", "--message", type=str, help="The description of the tag to create.") tag_parser.add_argument("--revision", type=str, help="The git revision to tag.") tag_parser.add_argument( "--token", type=str, help="A User Access Token generated from https://huggingface.co/settings/tokens." ) tag_parser.add_argument( "--repo-type", choices=["model", "dataset", "space"], default="model", help="Set the type of repository (model, dataset, or space).", ) tag_parser.add_argument("-y", "--yes", action="store_true", help="Answer Yes to prompts automatically.")
299
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/tag.py
tag_parser.add_argument("-l", "--list", action="store_true", help="List tags for a repository.") tag_parser.add_argument("-d", "--delete", action="store_true", help="Delete a tag for a repository.") tag_parser.set_defaults(func=lambda args: handle_commands(args))
299
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/tag.py
class TagCommand: def __init__(self, args: Namespace): self.args = args self.api = HfApi(token=self.args.token) self.repo_id = self.args.repo_id self.repo_type = self.args.repo_type if self.repo_type not in REPO_TYPES: print("Invalid repo --repo-type") exit(1)
300
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/tag.py
class TagCreateCommand(TagCommand): def run(self): print(f"You are about to create tag {ANSI.bold(self.args.tag)} on {self.repo_type} {ANSI.bold(self.repo_id)}") try: self.api.create_tag( repo_id=self.repo_id, tag=self.args.tag, tag_message=self.args.message, revision=self.args.revision, repo_type=self.repo_type, ) except RepositoryNotFoundError: print(f"{self.repo_type.capitalize()} {ANSI.bold(self.repo_id)} not found.") exit(1) except RevisionNotFoundError: print(f"Revision {ANSI.bold(self.args.revision)} not found.") exit(1) except HfHubHTTPError as e: if e.response.status_code == 409: print(f"Tag {ANSI.bold(self.args.tag)} already exists on {ANSI.bold(self.repo_id)}") exit(1) raise e
301
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/tag.py
print(f"Tag {ANSI.bold(self.args.tag)} created on {ANSI.bold(self.repo_id)}")
301
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/tag.py
class TagListCommand(TagCommand): def run(self): try: refs = self.api.list_repo_refs( repo_id=self.repo_id, repo_type=self.repo_type, ) except RepositoryNotFoundError: print(f"{self.repo_type.capitalize()} {ANSI.bold(self.repo_id)} not found.") exit(1) except HTTPError as e: print(e) print(ANSI.red(e.response.text)) exit(1) if len(refs.tags) == 0: print("No tags found") exit(0) print(f"Tags for {self.repo_type} {ANSI.bold(self.repo_id)}:") for tag in refs.tags: print(tag.name)
302
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/tag.py
class TagDeleteCommand(TagCommand): def run(self): print(f"You are about to delete tag {ANSI.bold(self.args.tag)} on {self.repo_type} {ANSI.bold(self.repo_id)}") if not self.args.yes: choice = input("Proceed? [Y/n] ").lower() if choice not in ("", "y", "yes"): print("Abort") exit() try: self.api.delete_tag(repo_id=self.repo_id, tag=self.args.tag, repo_type=self.repo_type) except RepositoryNotFoundError: print(f"{self.repo_type.capitalize()} {ANSI.bold(self.repo_id)} not found.") exit(1) except RevisionNotFoundError: print(f"Tag {ANSI.bold(self.args.tag)} not found on {ANSI.bold(self.repo_id)}") exit(1) print(f"Tag {ANSI.bold(self.args.tag)} deleted on {ANSI.bold(self.repo_id)}")
303
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/tag.py
class DeleteFilesSubCommand: def __init__(self, args) -> None: self.args = args self.repo_id: str = args.repo_id self.repo_type: Optional[str] = args.repo_type self.revision: Optional[str] = args.revision self.api: HfApi = HfApi(token=args.token, library_name="huggingface-cli") self.patterns: List[str] = args.patterns self.commit_message: Optional[str] = args.commit_message self.commit_description: Optional[str] = args.commit_description self.create_pr: bool = args.create_pr self.token: Optional[str] = args.token
304
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/repo_files.py
def run(self) -> None: logging.set_verbosity_info() url = self.api.delete_files( delete_patterns=self.patterns, repo_id=self.repo_id, repo_type=self.repo_type, revision=self.revision, commit_message=self.commit_message, commit_description=self.commit_description, create_pr=self.create_pr, ) print(f"Files correctly deleted from repo. Commit: {url}.") logging.set_verbosity_warning()
304
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/repo_files.py
class RepoFilesCommand(BaseHuggingfaceCLICommand): @staticmethod def register_subcommand(parser: _SubParsersAction): repo_files_parser = parser.add_parser("repo-files", help="Manage files in a repo on the Hub") repo_files_parser.add_argument( "repo_id", type=str, help="The ID of the repo to manage (e.g. `username/repo-name`)." ) repo_files_subparsers = repo_files_parser.add_subparsers( help="Action to execute against the files.", required=True, ) delete_subparser = repo_files_subparsers.add_parser( "delete", help="Delete files from a repo on the Hub", ) delete_subparser.set_defaults(func=lambda args: DeleteFilesSubCommand(args)) delete_subparser.add_argument( "patterns", nargs="+", type=str, help="Glob patterns to match files to delete.", ) delete_subparser.add_argument( "--repo-type",
305
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/repo_files.py
choices=["model", "dataset", "space"], default="model", help="Type of the repo to upload to (e.g. `dataset`).", ) delete_subparser.add_argument( "--revision", type=str, help=( "An optional Git revision to push to. It can be a branch name " "or a PR reference. If revision does not" " exist and `--create-pr` is not set, a branch will be automatically created." ), ) delete_subparser.add_argument( "--commit-message", type=str, help="The summary / title / first line of the generated commit." ) delete_subparser.add_argument( "--commit-description", type=str, help="The description of the generated commit." ) delete_subparser.add_argument( "--create-pr", action="store_true", help="Whether to create a new Pull Request for these changes." ) repo_files_parser.add_argument(
305
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/repo_files.py
"--token", type=str, help="A User Access Token generated from https://huggingface.co/settings/tokens", )
305
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/repo_files.py
repo_files_parser.set_defaults(func=RepoFilesCommand)
305
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/commands/repo_files.py