[docs]defload_model_from_hf(repo_id,revision="main",verbose=True):""" Load the model from a given repo_id using the Hugging Face library. Will download to a `model_dir` directory and return the path to it. Need your own load model logic to load the model from the `model_dir`. Args: repo_id (str): The ID of the repository. revision (str): The revision to download. Can be a branch, tag, or commit hash. verbose (bool): Whether to print the download message. Default is True. Returns: model_dir (Path): The path to the downloaded model directory. """login(new_session=False)model_dir=snapshot_download(repo_id=repo_id,repo_type="model",revision=revision,)api=HfApi()commit=api.list_repo_commits(repo_id,revision=revision)[0]commit_message=commit.titlecommit_time=commit.created_at.strftime("%B %d, %Y at %I:%M %p %Z")ifverbose:log.info(log.yellow(f"Succesfully loaded model {commit_message} from "f"'https://huggingface.co/{repo_id}'. Last updated on {commit_time}."))returnPath(model_dir)
[docs]defupload_folder_to_hf(local_dir,repo_id,commit_message=None,revision="main",tag=None,verbose=True,):""" Upload a local directory to Hugging Face Hub. Args: local_dir (str or Path): Path to the local directory to upload. repo_id (str): The ID of the repository to upload to. commit_message (str, optional): Commit message. Defaults to "Upload files". revision (str): The revision to upload to. Defaults to "main". tag (str, optional): Tag to create. Defaults to None. verbose (bool): Whether to print the upload message. Default is True. Returns: str: URL of the uploaded repository. """login(new_session=False)api=HfApi()local_dir=Path(local_dir)ifnotcommit_message:commit_message=f"Upload files from {local_dir.name}"# create branch if it doesn't existapi.create_branch(repo_id,repo_type="model",branch=revision,exist_ok=True)api.upload_folder(folder_path=local_dir,repo_id=repo_id,repo_type="model",commit_message=commit_message,revision=revision,)iftag:api.create_tag(repo_id,repo_type="model",tag=tag)ifverbose:msg=f"Uploaded files from '{local_dir}' to 'https://huggingface.co/{repo_id}'."iftag:msg+=f" Tagged as {tag}."log.info(log.yellow(msg))returnf"https://huggingface.co/{repo_id}"
[docs]classHFPath(PurePosixPath):"""A path-like object that preserves the hf:// scheme and mimics Path API."""_scheme=HF_PREFIXdef__new__(cls,*args):# Strip "hf://" from all arguments and normalizeparts=[]forarginargs:s=str(arg)ifs.startswith(cls._scheme):s=s[len(cls._scheme):]parts.append(s.strip("/"))combined="/".join(parts)# Store path without schemeself=super().__new__(cls,combined)# Mark this as an HF path that needs a scheme when stringifiedself._needs_scheme=Truereturnselfdef__str__(self):# Get the raw path string without any schemepath_str=PurePosixPath.__str__(self)# Remove any hf:/ prefix if it somehow got includedifpath_str.startswith("hf:/"):path_str=path_str[len("hf:/"):]# Add our scheme prefix if this is meant to be an HF pathifgetattr(self,"_needs_scheme",True):returnf"{self._scheme}{path_str}"returnpath_strdef__truediv__(self,key):returnself.__class__(self,key)
[docs]defjoinpath(self,*args):"""Join paths like Path.joinpath but preserve the hf:// scheme."""returnself.__class__(self,*args)
@propertydefrepo_id(self):"""Extract the repo ID (e.g., zeahub/camus-sample)."""parts=[pforpinself.partsifpandp!="hf:"]iflen(parts)<2:raiseValueError("Invalid HFPath: cannot extract repo_id")returnf"{parts[0]}/{parts[1]}"@propertydefsubpath(self):"""Get path inside the repo."""return"/".join(self.parts[3:])
[docs]defis_file(self):"""Return True if this HFPath points to a file in the repo."""repo_id,subpath=_hf_parse_path(str(self))ifnotsubpath:returnFalsefiles=_hf_list_files(repo_id)returnany(f==subpathforfinfiles)
[docs]defis_dir(self):"""Return True if this HFPath points to a directory in the repo."""repo_id,subpath=_hf_parse_path(str(self))files=_hf_list_files(repo_id)# If subpath is empty, it's the repo root, which is a directoryifnotsubpath:returnTrue# If any file starts with subpath + '/', it's a directoryprefix=subpath.rstrip("/")+"/"returnany(f.startswith(prefix)forfinfiles)