code: def hf_hub_download(
      repo_id: str,
      filename: str,
      *,
      subfolder: Optional[str] = None,
      repo_type: Optional[str] = None,
      revision: Optional[str] = None,
      library_name: Optional[str] = None,
      library_version: Optional[str] = None,
      cache_dir: Union[str, Path, None] = None,
      local_dir: Union[str, Path, None] = None,
      local_dir_use_symlinks: Union[bool, Literal["auto"]] = "auto",
      user_agent: Union[Dict, str, None] = None,
      force_download: bool = False,
      force_filename: Optional[str] = None,
      proxies: Optional[Dict] = None,
      etag_timeout: float = DEFAULT_ETAG_TIMEOUT,
      resume_download: bool = False,
      token: Union[bool, str, None] = None,
      local_files_only: bool = False,
      legacy_cache_layout: bool = False,
      endpoint: Optional[str] = None,
  ) -> str:
      """Download a given file if it's not already present in the local cache.
  
      The new cache file layout looks like this:
      - The cache directory contains one subfolder per repo_id (namespaced by repo type)
      - inside each repo folder:
          - refs is a list of the latest known revision => commit_hash pairs
          - blobs contains the actual file blobs (identified by their git-sha or sha256, depending on
            whether they're LFS files or not)
          - snapshots contains one subfolder per commit, each "commit" contains the subset of the files
            that have been resolved at that particular commit. Each filename is a symlink to the blob
            at that particular commit.
  
      If `local_dir` is provided, the file structure from the repo will be replicated in this location. You can configure
      how you want to move those files:
        - If `local_dir_use_symlinks="auto"` (default), files are downloaded and stored in the cache directory as blob
          files. Small files (<5MB) are duplicated in `local_dir` while a symlink is created for bigger files. The goal
          is to be able to manually edit and save small files without corrupting the cache while saving disk space for
          binary files. The 5MB threshold can be configured with the `HF_HUB_LOCAL_DIR_AUTO_SYMLINK_THRESHOLD`
          environment variable.
        - If `local_dir_use_symlinks=True`, files are downloaded, stored in the cache directory and symlinked in `local_dir`.
          This is optimal in term of disk usage but files must not be manually edited.
        - If `local_dir_use_symlinks=False` and the blob files exist in the cache directory, they are duplicated in the
          local dir. This means disk usage is not optimized.
        - Finally, if `local_dir_use_symlinks=False` and the blob files do not exist in the cache directory, then the
          files are downloaded and directly placed under `local_dir`. This means if you need to download them again later,
          they will be re-downloaded entirely.
  
      ```
      [  96]  .
      └── [ 160]  models--julien-c--EsperBERTo-small
          ├── [ 160]  blobs
          │   ├── [321M]  403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
          │   ├── [ 398]  7cb18dc9bafbfcf74629a4b760af1b160957a83e
          │   └── [1.4K]  d7edf6bd2a681fb0175f7735299831ee1b22b812
          ├── [  96]  refs
          │   └── [  40]  main
          └── [ 128]  snapshots
              ├── [ 128]  2439f60ef33a0d46d85da5001d52aeda5b00ce9f
              │   ├── [  52]  README.md -> ../../blobs/d7edf6bd2a681fb0175f7735299831ee1b22b812
              │   └── [  76]  pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
              └── [ 128]  bbc77c8132af1cc5cf678da3f1ddf2de43606d48
                  ├── [  52]  README.md -> ../../blobs/7cb18dc9bafbfcf74629a4b760af1b160957a83e
                  └── [  76]  pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
      ```
  
      Args:
          repo_id (`str`):
              A user or an organization name and a repo name separated by a `/`.
          filename (`str`):
              The name of the file in the repo.
          subfolder (`str`, *optional*):
              An optional value corresponding to a folder inside the model repo.
          repo_type (`str`, *optional*):
              Set to `"dataset"` or `"space"` if downloading from a dataset or space,
              `None` or `"model"` if downloading from a model. Default is `None`.
          revision (`str`, *optional*):
              An optional Git revision id which can be a branch name, a tag, or a
              commit hash.
          library_name (`str`, *optional*):
              The name of the library to which the object corresponds.
          library_version (`str`, *optional*):
              The version of the library.
          cache_dir (`str`, `Path`, *optional*):
              Path to the folder where cached files are stored.
          local_dir (`str` or `Path`, *optional*):
              If provided, the downloaded file will be placed under this directory, either as a symlink (default) or
              a regular file (see description for more details).
          local_dir_use_symlinks (`"auto"` or `bool`, defaults to `"auto"`):
              To be used with `local_dir`. If set to "auto", the cache directory will be used and the file will be either
              duplicated or symlinked to the local directory depending on its size. It set to `True`, a symlink will be
              created, no matter the file size. If set to `False`, the file will either be duplicated from cache (if
              already exists) or downloaded from the Hub and not cached. See description for more details.
          user_agent (`dict`, `str`, *optional*):
              The user-agent info in the form of a dictionary or a string.
          force_download (`bool`, *optional*, defaults to `False`):
              Whether the file should be downloaded even if it already exists in
              the local cache.
          proxies (`dict`, *optional*):
              Dictionary mapping protocol to the URL of the proxy passed to
              `requests.request`.
          etag_timeout (`float`, *optional*, defaults to `10`):
              When fetching ETag, how many seconds to wait for the server to send
              data before giving up which is passed to `requests.request`.
          resume_download (`bool`, *optional*, defaults to `False`):
              If `True`, resume a previously interrupted download.
          token (`str`, `bool`, *optional*):
              A token to be used for the download.
                  - If `True`, the token is read from the HuggingFace config
                    folder.
                  - If a string, it's used as the authentication token.
          local_files_only (`bool`, *optional*, defaults to `False`):
              If `True`, avoid downloading the file and return the path to the
              local cached file if it exists.
          legacy_cache_layout (`bool`, *optional*, defaults to `False`):
              If `True`, uses the legacy file cache layout i.e. just call [`hf_hub_url`]
              then `cached_download`. This is deprecated as the new cache layout is
              more powerful.
  
      Returns:
          Local path (string) of file or if networking is off, last version of
          file cached on disk.
  
      <Tip>
  
      Raises the following errors:
  
          - [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
            if `token=True` and the token cannot be found.
          - [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError)
            if ETag cannot be determined.
          - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
            if some parameter value is invalid
          - [`~utils.RepositoryNotFoundError`]
            If the repository to download from cannot be found. This may be because it doesn't exist,
            or because it is set to `private` and you do not have access.
          - [`~utils.RevisionNotFoundError`]
            If the revision to download from cannot be found.
          - [`~utils.EntryNotFoundError`]
            If the file to download cannot be found.
          - [`~utils.LocalEntryNotFoundError`]
            If network is disabled or unavailable and file is not found in cache.
  
      </Tip>
      """
      if HF_HUB_ETAG_TIMEOUT != DEFAULT_ETAG_TIMEOUT:
          # Respect environment variable above user value
          etag_timeout = HF_HUB_ETAG_TIMEOUT
  
      if force_filename is not None:
          warnings.warn(
              "The `force_filename` parameter is deprecated as a new caching system, "
              "which keeps the filenames as they are on the Hub, is now in place.",
              FutureWarning,
          )
          legacy_cache_layout = True
  
      if legacy_cache_layout:
          url = hf_hub_url(
              repo_id,
              filename,
              subfolder=subfolder,
              repo_type=repo_type,
              revision=revision,
              endpoint=endpoint,
          )
  
          return cached_download(
              url,
              library_name=library_name,
              library_version=library_version,
              cache_dir=cache_dir,
              user_agent=user_agent,
              force_download=force_download,
              force_filename=force_filename,
              proxies=proxies,
              etag_timeout=etag_timeout,
              resume_download=resume_download,
              token=token,
              local_files_only=local_files_only,
              legacy_cache_layout=legacy_cache_layout,
          )
  
      if cache_dir is None:
          cache_dir = HF_HUB_CACHE
      if revision is None:
          revision = DEFAULT_REVISION
      if isinstance(cache_dir, Path):
          cache_dir = str(cache_dir)
      if isinstance(local_dir, Path):
          local_dir = str(local_dir)
      locks_dir = os.path.join(cache_dir, ".locks")
  
      if subfolder == "":
          subfolder = None
      if subfolder is not None:
          # This is used to create a URL, and not a local path, hence the forward slash.
          filename = f"{subfolder}/{filename}"
  
      if repo_type is None:
          repo_type = "model"
      if repo_type not in REPO_TYPES:
          raise ValueError(
              f"Invalid repo type: {repo_type}. Accepted repo types are: {str(REPO_TYPES)}"
          )
  
      storage_folder = os.path.join(
          cache_dir,
          repo_folder_name(repo_id=repo_id, repo_type=repo_type),
      )
      os.makedirs(storage_folder, exist_ok=True)
  
      # cross platform transcription of filename, to be used as a local file path.
      relative_filename = os.path.join(*filename.split("/"))
      if os.name == "nt":
          if (
              relative_filename.startswith("..\\")
              or "\\..\\" in relative_filename
          ):
              raise ValueError(
                  f"Invalid filename: cannot handle filename '{relative_filename}' on Windows. Please ask the repository"
                  " owner to rename this file."
              )
  
      # if user provides a commit_hash and they already have the file on disk,
      # shortcut everything.
      if REGEX_COMMIT_HASH.match(revision):
          pointer_path = _get_pointer_path(
              storage_folder, revision, relative_filename
          )
          if os.path.exists(pointer_path):
              if local_dir is not None:
                  return _to_local_dir(
                      pointer_path,
                      local_dir,
                      relative_filename,
                      use_symlinks=local_dir_use_symlinks,
                  )
              return pointer_path
  
      url = hf_hub_url(
          repo_id,
          filename,
          repo_type=repo_type,
          revision=revision,
          endpoint=endpoint,
      )
  
      headers = build_hf_headers(
          token=token,
          library_name=library_name,
          library_version=library_version,
          user_agent=user_agent,
      )
  
      url_to_download = url
      etag = None
      commit_hash = None
      expected_size = None
      head_call_error: Optional[Exception] = None
      if not local_files_only:
          try:
              try:
                  metadata = get_hf_file_metadata(
                      url=url,
                      token=token,
                      proxies=proxies,
                      timeout=etag_timeout,
                      library_name=library_name,
                      library_version=library_version,
                      user_agent=user_agent,
                  )
              except EntryNotFoundError as http_error:
                  # Cache the non-existence of the file and raise
                  commit_hash = http_error.response.headers.get(
                      HUGGINGFACE_HEADER_X_REPO_COMMIT
                  )
                  if (
                      commit_hash is not None
                      and not legacy_cache_layout
                  ):
                      no_exist_file_path = (
                          Path(storage_folder)
                          / ".no_exist"
                          / commit_hash
                          / relative_filename
                      )
                      no_exist_file_path.parent.mkdir(
                          parents=True, exist_ok=True
                      )
                      no_exist_file_path.touch()
                      _cache_commit_hash_for_specific_revision(
                          storage_folder, revision, commit_hash
                      )
                  raise
  
              # Commit hash must exist
              commit_hash = metadata.commit_hash
              if commit_hash is None:
                  raise FileMetadataError(
                      "Distant resource does not seem to be on huggingface.co. It is possible that a configuration issue"
                      " prevents you from downloading resources from https://huggingface.co. Please check your firewall"
                      " and proxy settings and make sure your SSL certificates are updated."
                  )
  
              # Etag must exist
              etag = metadata.etag
              # We favor a custom header indicating the etag of the linked resource, and
              # we fallback to the regular etag header.
              # If we don't have any of those, raise an error.
              if etag is None:
                  raise FileMetadataError(
                      "Distant resource does not have an ETag, we won't be able to reliably ensure reproducibility."
                  )
  
              # Expected (uncompressed) size
              expected_size = metadata.size
  
              # In case of a redirect, save an extra redirect on the request.get call,
              # and ensure we download the exact atomic version even if it changed
              # between the HEAD and the GET (unlikely, but hey).
              # Useful for lfs blobs that are stored on a CDN.
              if metadata.location != url:
                  url_to_download = metadata.location
                  # Remove authorization header when downloading a LFS blob
                  headers.pop("authorization", None)
          except (
              requests.exceptions.SSLError,
              requests.exceptions.ProxyError,
          ):
              # Actually raise for those subclasses of ConnectionError
              raise
          except (
              requests.exceptions.ConnectionError,
              requests.exceptions.Timeout,
              OfflineModeIsEnabled,
          ) as error:
              # Otherwise, our Internet connection is down.
              # etag is None
              head_call_error = error
              pass
          except (RevisionNotFoundError, EntryNotFoundError):
              # The repo was found but the revision or entry doesn't exist on the Hub (never existed or got deleted)
              raise
          except requests.HTTPError as error:
              # Multiple reasons for an http error:
              # - Repository is private and invalid/missing token sent
              # - Repository is gated and invalid/missing token sent
              # - Hub is down (error 500 or 504)
              # => let's switch to 'local_files_only=True' to check if the files are already cached.
              #    (if it's not the case, the error will be re-raised)
              head_call_error = error
              pass
          except FileMetadataError as error:
              # Multiple reasons for a FileMetadataError:
              # - Wrong network configuration (proxy, firewall, SSL certificates)
              # - Inconsistency on the Hub
              # => let's switch to 'local_files_only=True' to check if the files are already cached.
              #    (if it's not the case, the error will be re-raised)
              head_call_error = error
              pass
  
      # etag can be None for several reasons:
      # 1. we passed local_files_only.
      # 2. we don't have a connection
      # 3. Hub is down (HTTP 500 or 504)
      # 4. repo is not found -for example private or gated- and invalid/missing token sent
      # 5. Hub is blocked by a firewall or proxy is not set correctly.
      # => Try to get the last downloaded one from the specified revision.
      #
      # If the specified revision is a commit hash, look inside "snapshots".
      # If the specified revision is a branch or tag, look inside "refs".
      if etag is None:
          # In those cases, we cannot force download.
          if force_download:
              raise ValueError(
                  "We have no connection or you passed local_files_only, so force_download is not an accepted option."
              )
  
          # Try to get "commit_hash" from "revision"
          commit_hash = None
          if REGEX_COMMIT_HASH.match(revision):
              commit_hash = revision
          else:
              ref_path = os.path.join(storage_folder, "refs", revision)
              if os.path.isfile(ref_path):
                  with open(ref_path) as f:
                      commit_hash = f.read()
  
          # Return pointer file if exists
          if commit_hash is not None:
              pointer_path = _get_pointer_path(
                  storage_folder, commit_hash, relative_filename
              )
              if os.path.exists(pointer_path):
                  if local_dir is not None:
                      return _to_local_dir(
                          pointer_path,
                          local_dir,
                          relative_filename,
                          use_symlinks=local_dir_use_symlinks,
                      )
                  return pointer_path
  
          # If we couldn't find an appropriate file on disk, raise an error.
          # If files cannot be found and local_files_only=True,
          # the models might've been found if local_files_only=False
          # Notify the user about that
          if local_files_only:
              raise LocalEntryNotFoundError(
                  "Cannot find the requested files in the disk cache and outgoing traffic has been disabled. To enable"
                  " hf.co look-ups and downloads online, set 'local_files_only' to False."
              )
          elif isinstance(
              head_call_error, RepositoryNotFoundError
          ) or isinstance(head_call_error, GatedRepoError):
              # Repo not found => let's raise the actual error
              raise head_call_error
          else:
              # Otherwise: most likely a connection issue or Hub downtime => let's warn the user
              raise LocalEntryNotFoundError(
                  "An error happened while trying to locate the file on the Hub and we cannot find the requested files"
                  " in the local cache. Please check your connection and try again or make sure your Internet connection"
                  " is on."
              ) from head_call_error
  
      # From now on, etag and commit_hash are not None.
      assert (
          etag is not None
      ), "etag must have been retrieved from server"
      assert (
          commit_hash is not None
      ), "commit_hash must have been retrieved from server"
      blob_path = os.path.join(storage_folder, "blobs", etag)
      pointer_path = _get_pointer_path(
          storage_folder, commit_hash, relative_filename
      )
  
      os.makedirs(os.path.dirname(blob_path), exist_ok=True)
      os.makedirs(os.path.dirname(pointer_path), exist_ok=True)
      # if passed revision is not identical to commit_hash
      # then revision has to be a branch name or tag name.
      # In that case store a ref.
      _cache_commit_hash_for_specific_revision(
          storage_folder, revision, commit_hash
      )
  
      if os.path.exists(pointer_path) and not force_download:
          if local_dir is not None:
              return _to_local_dir(
                  pointer_path,
                  local_dir,
                  relative_filename,
                  use_symlinks=local_dir_use_symlinks,
              )
          return pointer_path
  
      if os.path.exists(blob_path) and not force_download:
          # we have the blob already, but not the pointer
          if local_dir is not None:  # to local dir
              return _to_local_dir(
                  blob_path,
                  local_dir,
                  relative_filename,
                  use_symlinks=local_dir_use_symlinks,
              )
          else:  # or in snapshot cache
              _create_symlink(blob_path, pointer_path, new_blob=False)
              return pointer_path
  
      # Prevent parallel downloads of the same file with a lock.
      # etag could be duplicated across repos,
      lock_path = os.path.join(
          locks_dir,
          repo_folder_name(repo_id=repo_id, repo_type=repo_type),
          f"{etag}.lock",
      )
  
      # Some Windows versions do not allow for paths longer than 255 characters.
      # In this case, we must specify it is an extended path by using the "\\?\" prefix.
      if os.name == "nt" and len(os.path.abspath(lock_path)) > 255:
          lock_path = "\\\\?\\" + os.path.abspath(lock_path)
  
      if os.name == "nt" and len(os.path.abspath(blob_path)) > 255:
          blob_path = "\\\\?\\" + os.path.abspath(blob_path)
  
      Path(lock_path).parent.mkdir(parents=True, exist_ok=True)
      with FileLock(lock_path):
          # If the download just completed while the lock was activated.
          if os.path.exists(pointer_path) and not force_download:
              # Even if returning early like here, the lock will be released.
              if local_dir is not None:
                  return _to_local_dir(
                      pointer_path,
                      local_dir,
                      relative_filename,
                      use_symlinks=local_dir_use_symlinks,
                  )
              return pointer_path
  
          if resume_download:
              incomplete_path = blob_path + ".incomplete"
  
              @contextmanager
              def _resumable_file_manager() -> (
                  Generator[io.BufferedWriter, None, None]
              ):
                  with open(incomplete_path, "ab") as f:
                      yield f
  
              temp_file_manager = _resumable_file_manager
              if os.path.exists(incomplete_path):
                  resume_size = os.stat(incomplete_path).st_size
              else:
                  resume_size = 0
          else:
              temp_file_manager = partial(  # type: ignore
                  tempfile.NamedTemporaryFile,
                  mode="wb",
                  dir=cache_dir,
                  delete=False,
              )
              resume_size = 0
  
          # Download to temporary file, then copy to cache dir once finished.
          # Otherwise you get corrupt cache entries if the download gets interrupted.
          with temp_file_manager() as temp_file:
              logger.info("downloading %s to %s", url, temp_file.name)
  
              if (
                  expected_size is not None
              ):  # might be None if HTTP header not set correctly
                  # Check tmp path
                  _check_disk_space(
                      expected_size, os.path.dirname(temp_file.name)
                  )
  
                  # Check destination
                  _check_disk_space(
                      expected_size, os.path.dirname(blob_path)
                  )
                  if local_dir is not None:
                      _check_disk_space(expected_size, local_dir)
  
              http_get(
                  url_to_download,
                  temp_file,
                  proxies=proxies,
                  resume_size=resume_size,
                  headers=headers,
                  expected_size=expected_size,
                  displayed_filename=filename,
              )
  
          if local_dir is None:
              logger.debug(f"Storing {url} in cache at {blob_path}")
              _chmod_and_replace(temp_file.name, blob_path)
              _create_symlink(blob_path, pointer_path, new_blob=True)
          else:
              local_dir_filepath = os.path.join(
                  local_dir, relative_filename
              )
              os.makedirs(
                  os.path.dirname(local_dir_filepath), exist_ok=True
              )
  
              # If "auto" (default) copy-paste small files to ease manual editing but symlink big files to save disk
              # In both cases, blob file is cached.
              is_big_file = (
                  os.stat(temp_file.name).st_size
                  > constants.HF_HUB_LOCAL_DIR_AUTO_SYMLINK_THRESHOLD
              )
              if local_dir_use_symlinks is True or (
                  local_dir_use_symlinks == "auto" and is_big_file
              ):
                  logger.debug(f"Storing {url} in cache at {blob_path}")
                  _chmod_and_replace(temp_file.name, blob_path)
                  logger.debug("Create symlink to local dir")
                  _create_symlink(
                      blob_path, local_dir_filepath, new_blob=False
                  )
              elif local_dir_use_symlinks == "auto" and not is_big_file:
                  logger.debug(f"Storing {url} in cache at {blob_path}")
                  _chmod_and_replace(temp_file.name, blob_path)
                  logger.debug(
                      "Duplicate in local dir (small file and use_symlink set to 'auto')"
                  )
                  shutil.copyfile(blob_path, local_dir_filepath)
              else:
                  logger.debug(
                      f"Storing {url} in local_dir at {local_dir_filepath} (not cached)."
                  )
                  _chmod_and_replace(temp_file.name, local_dir_filepath)
              pointer_path = local_dir_filepath  # for return value
  
      return pointer_path
  
imports: import copy
  import fnmatch
  import inspect
  import io
  import json
  import os
  import re
  import shutil
  import stat
  import tempfile
  import time
  import uuid
  import warnings
  from contextlib import contextmanager
  from dataclasses import dataclass
  from functools import partial
  from pathlib import Path
  from typing import Any, BinaryIO, Dict, Generator, Literal, Optional, Tuple, Union
  from urllib.parse import quote, urlparse
  import requests
  from filelock import FileLock
  from huggingface_hub import constants
  from .None import __version__
  from .constants import DEFAULT_ETAG_TIMEOUT, DEFAULT_REQUEST_TIMEOUT, DEFAULT_REVISION, DOWNLOAD_CHUNK_SIZE, ENDPOINT, HF_HUB_CACHE, HF_HUB_DISABLE_SYMLINKS_WARNING, HF_HUB_DOWNLOAD_TIMEOUT, HF_HUB_ENABLE_HF_TRANSFER, HF_HUB_ETAG_TIMEOUT, HF_TRANSFER_CONCURRENCY, HUGGINGFACE_CO_URL_TEMPLATE, HUGGINGFACE_HEADER_X_LINKED_ETAG, HUGGINGFACE_HEADER_X_LINKED_SIZE, HUGGINGFACE_HEADER_X_REPO_COMMIT, HUGGINGFACE_HUB_CACHE, REPO_ID_SEPARATOR, REPO_TYPES, REPO_TYPES_URL_PREFIXES
  from .utils import EntryNotFoundError, FileMetadataError, GatedRepoError, LocalEntryNotFoundError, OfflineModeIsEnabled, RepositoryNotFoundError, RevisionNotFoundError, SoftTemporaryDirectory, build_hf_headers, get_fastai_version, get_fastcore_version, get_graphviz_version, get_jinja_version, get_pydot_version, get_session, get_tf_version, get_torch_version, hf_raise_for_status, is_fastai_available, is_fastcore_available, is_graphviz_available, is_jinja_available, is_pydot_available, is_tf_available, is_torch_available, logging, reset_sessions, tqdm, validate_hf_hub_args
  from .utils._deprecation import _deprecate_method
  from .utils._headers import _http_user_agent
  from .utils._runtime import _PY_VERSION
  from .utils._typing import HTTP_METHOD_T
  from .utils.insecure_hashlib import sha256
label_desc: Use image node_id 15 for calling a global function with example usage: hf_hub_download(repo_id, filename) and returns: pointer_path, cached_download, pointer_path, pointer_path, _to_local_dir, _to_local_dir, pointer_path, pointer_path, _to_local_dir, pointer_path, _to_local_dir, _to_local_dir