text
stringlengths
31
361k
type
stringclasses
6 values
start
int64
125
418k
end
int64
325
418k
depth
int64
0
8
filepath
stringclasses
103 values
parent_class
stringclasses
106 values
class EvalResult: """ Flattened representation of individual evaluation results found in model-index of Model Cards. For more information on the model-index spec, see https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1. Args: task_type (`str`): The task identifier. Example: "image-classification". dataset_type (`str`): The dataset identifier. Example: "common_voice". Use dataset id from https://hf.co/datasets. dataset_name (`str`): A pretty name for the dataset. Example: "Common Voice (French)". metric_type (`str`): The metric identifier. Example: "wer". Use metric id from https://hf.co/metrics. metric_value (`Any`): The metric value. Example: 0.9 or "20.0 ± 1.2". task_name (`str`, *optional*): A pretty name for the task. Example: "Speech Recognition". dataset_config (`str`, *optional*): The name of the dataset configuration used in `load_dataset()`. Example: fr in `load_dataset("common_voice", "fr")`. See the `datasets` docs for more info: https://hf.co/docs/datasets/package_reference/loading_methods#datasets.load_dataset.name dataset_split (`str`, *optional*): The split used in `load_dataset()`. Example: "test". dataset_revision (`str`, *optional*): The revision (AKA Git Sha) of the dataset used in `load_dataset()`. Example: 5503434ddd753f426f4b38109466949a1217c2bb dataset_args (`Dict[str, Any]`, *optional*): The arguments passed during `Metric.compute()`. Example for `bleu`: `{"max_order": 4}` metric_name (`str`, *optional*): A pretty name for the metric. Example: "Test WER". metric_config (`str`, *optional*): The name of the metric configuration used in `load_metric()`. Example: bleurt-large-512 in `load_metric("bleurt", "bleurt-large-512")`. See the `datasets` docs for more info: https://huggingface.co/docs/datasets/v2.1.0/en/loading#load-configurations metric_args (`Dict[str, Any]`, *optional*): The arguments passed during `Metric.compute()`. Example for `bleu`: max_order: 4 verified (`bool`, *optional*): Indicates whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not. Automatically computed by Hugging Face, do not set. verify_token (`str`, *optional*): A JSON Web Token that is used to verify whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not. source_name (`str`, *optional*): The name of the source of the evaluation result. Example: "Open LLM Leaderboard". source_url (`str`, *optional*): The URL of the source of the evaluation result. Example: "https://huggingface.co/spaces/open-llm-leaderboard/open_llm_leaderboard". """ # Required # The task identifier # Example: automatic-speech-recognition task_type: str # The dataset identifier # Example: common_voice. Use dataset id from https://hf.co/datasets dataset_type: str # A pretty name for the dataset. # Example: Common Voice (French) dataset_name: str # The metric identifier # Example: wer. Use metric id from https://hf.co/metrics metric_type: str # Value of the metric. # Example: 20.0 or "20.0 ± 1.2" metric_value: Any # Optional # A pretty name for the task. # Example: Speech Recognition task_name: Optional[str] = None # The name of the dataset configuration used in `load_dataset()`. # Example: fr in `load_dataset("common_voice", "fr")`. # See the `datasets` docs for more info: # https://huggingface.co/docs/datasets/package_reference/loading_methods#datasets.load_dataset.name dataset_config: Optional[str] = None # The split used in `load_dataset()`. # Example: test dataset_split: Optional[str] = None # The revision (AKA Git Sha) of the dataset used in `load_dataset()`. # Example: 5503434ddd753f426f4b38109466949a1217c2bb dataset_revision: Optional[str] = None # The arguments passed during `Metric.compute()`. # Example for `bleu`: max_order: 4 dataset_args: Optional[Dict[str, Any]] = None # A pretty name for the metric. # Example: Test WER metric_name: Optional[str] = None # The name of the metric configuration used in `load_metric()`. # Example: bleurt-large-512 in `load_metric("bleurt", "bleurt-large-512")`. # See the `datasets` docs for more info: https://huggingface.co/docs/datasets/v2.1.0/en/loading#load-configurations metric_config: Optional[str] = None # The arguments passed during `Metric.compute()`. # Example for `bleu`: max_order: 4 metric_args: Optional[Dict[str, Any]] = None # Indicates whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not. Automatically computed by Hugging Face, do not set. verified: Optional[bool] = None # A JSON Web Token that is used to verify whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not. verify_token: Optional[str] = None # The name of the source of the evaluation result. # Example: Open LLM Leaderboard source_name: Optional[str] = None # The URL of the source of the evaluation result. # Example: https://huggingface.co/spaces/open-llm-leaderboard/open_llm_leaderboard source_url: Optional[str] = None @property def unique_identifier(self) -> tuple: """Returns a tuple that uniquely identifies this evaluation.""" return ( self.task_type, self.dataset_type, self.dataset_config, self.dataset_split, self.dataset_revision, ) def is_equal_except_value(self, other: "EvalResult") -> bool: """ Return True if `self` and `other` describe exactly the same metric but with a different value. """ for key, _ in self.__dict__.items(): if key == "metric_value": continue # For metrics computed by Hugging Face's evaluation service, `verify_token` is derived from `metric_value`, # so we exclude it here in the comparison. if key != "verify_token" and getattr(self, key) != getattr(other, key): return False return True def __post_init__(self) -> None: if self.source_name is not None and self.source_url is None: raise ValueError("If `source_name` is provided, `source_url` must also be provided.")
class_definition
248
7,185
0
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
null
def unique_identifier(self) -> tuple: """Returns a tuple that uniquely identifies this evaluation.""" return ( self.task_type, self.dataset_type, self.dataset_config, self.dataset_split, self.dataset_revision, )
function_definition
6,067
6,362
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
EvalResult
def is_equal_except_value(self, other: "EvalResult") -> bool: """ Return True if `self` and `other` describe exactly the same metric but with a different value. """ for key, _ in self.__dict__.items(): if key == "metric_value": continue # For metrics computed by Hugging Face's evaluation service, `verify_token` is derived from `metric_value`, # so we exclude it here in the comparison. if key != "verify_token" and getattr(self, key) != getattr(other, key): return False return True
function_definition
6,368
6,980
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
EvalResult
for key, _ in self.__dict__.items(): if key == "metric_value": continue # For metrics computed by Hugging Face's evaluation service, `verify_token` is derived from `metric_value`, # so we exclude it here in the comparison. if key != "verify_token" and getattr(self, key) != getattr(other, key): return False
for_statement
6,573
6,960
2
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
EvalResult
if key == "metric_value": continue
if_statement
6,622
6,672
3
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
EvalResult
if key != "verify_token" and getattr(self, key) != getattr(other, key): return False
if_statement
6,860
6,960
3
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
EvalResult
def __post_init__(self) -> None: if self.source_name is not None and self.source_url is None: raise ValueError("If `source_name` is provided, `source_url` must also be provided.")
function_definition
6,986
7,185
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
EvalResult
if self.source_name is not None and self.source_url is None: raise ValueError("If `source_name` is provided, `source_url` must also be provided.")
if_statement
7,027
7,185
2
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
EvalResult
class CardData: """Structure containing metadata from a RepoCard. [`CardData`] is the parent class of [`ModelCardData`] and [`DatasetCardData`]. Metadata can be exported as a dictionary or YAML. Export can be customized to alter the representation of the data (example: flatten evaluation results). `CardData` behaves as a dictionary (can get, pop, set values) but do not inherit from `dict` to allow this export step. """ def __init__(self, ignore_metadata_errors: bool = False, **kwargs): self.__dict__.update(kwargs) def to_dict(self): """Converts CardData to a dict. Returns: `dict`: CardData represented as a dictionary ready to be dumped to a YAML block for inclusion in a README.md file. """ data_dict = copy.deepcopy(self.__dict__) self._to_dict(data_dict) return {key: value for key, value in data_dict.items() if value is not None} def _to_dict(self, data_dict): """Use this method in child classes to alter the dict representation of the data. Alter the dict in-place. Args: data_dict (`dict`): The raw dict representation of the card data. """ pass def to_yaml(self, line_break=None, original_order: Optional[List[str]] = None) -> str: """Dumps CardData to a YAML block for inclusion in a README.md file. Args: line_break (str, *optional*): The line break to use when dumping to yaml. Returns: `str`: CardData represented as a YAML block. """ if original_order: self.__dict__ = { k: self.__dict__[k] for k in original_order + list(set(self.__dict__.keys()) - set(original_order)) if k in self.__dict__ } return yaml_dump(self.to_dict(), sort_keys=False, line_break=line_break).strip() def __repr__(self): return repr(self.__dict__) def __str__(self): return self.to_yaml() def get(self, key: str, default: Any = None) -> Any: """Get value for a given metadata key.""" return self.__dict__.get(key, default) def pop(self, key: str, default: Any = None) -> Any: """Pop value for a given metadata key.""" return self.__dict__.pop(key, default) def __getitem__(self, key: str) -> Any: """Get value for a given metadata key.""" return self.__dict__[key] def __setitem__(self, key: str, value: Any) -> None: """Set value for a given metadata key.""" self.__dict__[key] = value def __contains__(self, key: str) -> bool: """Check if a given metadata key is set.""" return key in self.__dict__ def __len__(self) -> int: """Return the number of metadata keys set.""" return len(self.__dict__)
class_definition
7,199
10,080
0
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
null
def __init__(self, ignore_metadata_errors: bool = False, **kwargs): self.__dict__.update(kwargs)
function_definition
7,653
7,757
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
CardData
def to_dict(self): """Converts CardData to a dict. Returns: `dict`: CardData represented as a dictionary ready to be dumped to a YAML block for inclusion in a README.md file. """ data_dict = copy.deepcopy(self.__dict__) self._to_dict(data_dict) return {key: value for key, value in data_dict.items() if value is not None}
function_definition
7,763
8,158
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
CardData
def _to_dict(self, data_dict): """Use this method in child classes to alter the dict representation of the data. Alter the dict in-place. Args: data_dict (`dict`): The raw dict representation of the card data. """ pass
function_definition
8,164
8,427
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
CardData
def to_yaml(self, line_break=None, original_order: Optional[List[str]] = None) -> str: """Dumps CardData to a YAML block for inclusion in a README.md file. Args: line_break (str, *optional*): The line break to use when dumping to yaml. Returns: `str`: CardData represented as a YAML block. """ if original_order: self.__dict__ = { k: self.__dict__[k] for k in original_order + list(set(self.__dict__.keys()) - set(original_order)) if k in self.__dict__ } return yaml_dump(self.to_dict(), sort_keys=False, line_break=line_break).strip()
function_definition
8,433
9,130
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
CardData
if original_order: self.__dict__ = { k: self.__dict__[k] for k in original_order + list(set(self.__dict__.keys()) - set(original_order)) if k in self.__dict__ }
if_statement
8,809
9,041
2
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
CardData
def __repr__(self): return repr(self.__dict__)
function_definition
9,136
9,190
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
CardData
def __str__(self): return self.to_yaml()
function_definition
9,196
9,244
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
CardData
def get(self, key: str, default: Any = None) -> Any: """Get value for a given metadata key.""" return self.__dict__.get(key, default)
function_definition
9,250
9,399
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
CardData
def pop(self, key: str, default: Any = None) -> Any: """Pop value for a given metadata key.""" return self.__dict__.pop(key, default)
function_definition
9,405
9,554
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
CardData
def __getitem__(self, key: str) -> Any: """Get value for a given metadata key.""" return self.__dict__[key]
function_definition
9,560
9,683
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
CardData
def __setitem__(self, key: str, value: Any) -> None: """Set value for a given metadata key.""" self.__dict__[key] = value
function_definition
9,689
9,826
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
CardData
def __contains__(self, key: str) -> bool: """Check if a given metadata key is set.""" return key in self.__dict__
function_definition
9,832
9,961
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
CardData
def __len__(self) -> int: """Return the number of metadata keys set.""" return len(self.__dict__)
function_definition
9,967
10,080
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
CardData
class ModelCardData(CardData): """Model Card Metadata that is used by Hugging Face Hub when included at the top of your README.md Args: base_model (`str` or `List[str]`, *optional*): The identifier of the base model from which the model derives. This is applicable for example if your model is a fine-tune or adapter of an existing model. The value must be the ID of a model on the Hub (or a list of IDs if your model derives from multiple models). Defaults to None. datasets (`Union[str, List[str]]`, *optional*): Dataset or list of datasets that were used to train this model. Should be a dataset ID found on https://hf.co/datasets. Defaults to None. eval_results (`Union[List[EvalResult], EvalResult]`, *optional*): List of `huggingface_hub.EvalResult` that define evaluation results of the model. If provided, `model_name` is used to as a name on PapersWithCode's leaderboards. Defaults to `None`. language (`Union[str, List[str]]`, *optional*): Language of model's training data or metadata. It must be an ISO 639-1, 639-2 or 639-3 code (two/three letters), or a special value like "code", "multilingual". Defaults to `None`. library_name (`str`, *optional*): Name of library used by this model. Example: keras or any library from https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/src/model-libraries.ts. Defaults to None. license (`str`, *optional*): License of this model. Example: apache-2.0 or any license from https://huggingface.co/docs/hub/repositories-licenses. Defaults to None. license_name (`str`, *optional*): Name of the license of this model. Defaults to None. To be used in conjunction with `license_link`. Common licenses (Apache-2.0, MIT, CC-BY-SA-4.0) do not need a name. In that case, use `license` instead. license_link (`str`, *optional*): Link to the license of this model. Defaults to None. To be used in conjunction with `license_name`. Common licenses (Apache-2.0, MIT, CC-BY-SA-4.0) do not need a link. In that case, use `license` instead. metrics (`List[str]`, *optional*): List of metrics used to evaluate this model. Should be a metric name that can be found at https://hf.co/metrics. Example: 'accuracy'. Defaults to None. model_name (`str`, *optional*): A name for this model. It is used along with `eval_results` to construct the `model-index` within the card's metadata. The name you supply here is what will be used on PapersWithCode's leaderboards. If None is provided then the repo name is used as a default. Defaults to None. pipeline_tag (`str`, *optional*): The pipeline tag associated with the model. Example: "text-classification". tags (`List[str]`, *optional*): List of tags to add to your model that can be used when filtering on the Hugging Face Hub. Defaults to None. ignore_metadata_errors (`str`): If True, errors while parsing the metadata section will be ignored. Some information might be lost during the process. Use it at your own risk. kwargs (`dict`, *optional*): Additional metadata that will be added to the model card. Defaults to None. Example: ```python >>> from huggingface_hub import ModelCardData >>> card_data = ModelCardData( ... language="en", ... license="mit", ... library_name="timm", ... tags=['image-classification', 'resnet'], ... ) >>> card_data.to_dict() {'language': 'en', 'license': 'mit', 'library_name': 'timm', 'tags': ['image-classification', 'resnet']} ``` """ def __init__( self, *, base_model: Optional[Union[str, List[str]]] = None, datasets: Optional[Union[str, List[str]]] = None, eval_results: Optional[List[EvalResult]] = None, language: Optional[Union[str, List[str]]] = None, library_name: Optional[str] = None, license: Optional[str] = None, license_name: Optional[str] = None, license_link: Optional[str] = None, metrics: Optional[List[str]] = None, model_name: Optional[str] = None, pipeline_tag: Optional[str] = None, tags: Optional[List[str]] = None, ignore_metadata_errors: bool = False, **kwargs, ): self.base_model = base_model self.datasets = datasets self.eval_results = eval_results self.language = language self.library_name = library_name self.license = license self.license_name = license_name self.license_link = license_link self.metrics = metrics self.model_name = model_name self.pipeline_tag = pipeline_tag self.tags = _to_unique_list(tags) model_index = kwargs.pop("model-index", None) if model_index: try: model_name, eval_results = model_index_to_eval_results(model_index) self.model_name = model_name self.eval_results = eval_results except (KeyError, TypeError) as error: if ignore_metadata_errors: logger.warning("Invalid model-index. Not loading eval results into CardData.") else: raise ValueError( f"Invalid `model_index` in metadata cannot be parsed: {error.__class__} {error}. Pass" " `ignore_metadata_errors=True` to ignore this error while loading a Model Card. Warning:" " some information will be lost. Use it at your own risk." ) super().__init__(**kwargs) if self.eval_results: if isinstance(self.eval_results, EvalResult): self.eval_results = [self.eval_results] if self.model_name is None: raise ValueError("Passing `eval_results` requires `model_name` to be set.") def _to_dict(self, data_dict): """Format the internal data dict. In this case, we convert eval results to a valid model index""" if self.eval_results is not None: data_dict["model-index"] = eval_results_to_model_index(self.model_name, self.eval_results) del data_dict["eval_results"], data_dict["model_name"]
class_definition
10,083
16,711
0
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
null
def __init__( self, *, base_model: Optional[Union[str, List[str]]] = None, datasets: Optional[Union[str, List[str]]] = None, eval_results: Optional[List[EvalResult]] = None, language: Optional[Union[str, List[str]]] = None, library_name: Optional[str] = None, license: Optional[str] = None, license_name: Optional[str] = None, license_link: Optional[str] = None, metrics: Optional[List[str]] = None, model_name: Optional[str] = None, pipeline_tag: Optional[str] = None, tags: Optional[List[str]] = None, ignore_metadata_errors: bool = False, **kwargs, ): self.base_model = base_model self.datasets = datasets self.eval_results = eval_results self.language = language self.library_name = library_name self.license = license self.license_name = license_name self.license_link = license_link self.metrics = metrics self.model_name = model_name self.pipeline_tag = pipeline_tag self.tags = _to_unique_list(tags) model_index = kwargs.pop("model-index", None) if model_index: try: model_name, eval_results = model_index_to_eval_results(model_index) self.model_name = model_name self.eval_results = eval_results except (KeyError, TypeError) as error: if ignore_metadata_errors: logger.warning("Invalid model-index. Not loading eval results into CardData.") else: raise ValueError( f"Invalid `model_index` in metadata cannot be parsed: {error.__class__} {error}. Pass" " `ignore_metadata_errors=True` to ignore this error while loading a Model Card. Warning:" " some information will be lost. Use it at your own risk." ) super().__init__(**kwargs) if self.eval_results: if isinstance(self.eval_results, EvalResult): self.eval_results = [self.eval_results] if self.model_name is None: raise ValueError("Passing `eval_results` requires `model_name` to be set.")
function_definition
14,051
16,357
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
ModelCardData
if model_index: try: model_name, eval_results = model_index_to_eval_results(model_index) self.model_name = model_name self.eval_results = eval_results except (KeyError, TypeError) as error: if ignore_metadata_errors: logger.warning("Invalid model-index. Not loading eval results into CardData.") else: raise ValueError( f"Invalid `model_index` in metadata cannot be parsed: {error.__class__} {error}. Pass" " `ignore_metadata_errors=True` to ignore this error while loading a Model Card. Warning:" " some information will be lost. Use it at your own risk." )
if_statement
15,250
16,044
2
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
ModelCardData
try: model_name, eval_results = model_index_to_eval_results(model_index) self.model_name = model_name self.eval_results = eval_results except (KeyError, TypeError) as error: if ignore_metadata_errors: logger.warning("Invalid model-index. Not loading eval results into CardData.") else: raise ValueError( f"Invalid `model_index` in metadata cannot be parsed: {error.__class__} {error}. Pass" " `ignore_metadata_errors=True` to ignore this error while loading a Model Card. Warning:" " some information will be lost. Use it at your own risk." )
try_statement
15,278
16,044
3
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
ModelCardData
if ignore_metadata_errors: logger.warning("Invalid model-index. Not loading eval results into CardData.") else: raise ValueError( f"Invalid `model_index` in metadata cannot be parsed: {error.__class__} {error}. Pass" " `ignore_metadata_errors=True` to ignore this error while loading a Model Card. Warning:" " some information will be lost. Use it at your own risk." )
if_statement
15,528
16,044
4
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
ModelCardData
if self.eval_results: if isinstance(self.eval_results, EvalResult): self.eval_results = [self.eval_results] if self.model_name is None: raise ValueError("Passing `eval_results` requires `model_name` to be set.")
if_statement
16,090
16,357
2
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
ModelCardData
if isinstance(self.eval_results, EvalResult): self.eval_results = [self.eval_results]
if_statement
16,124
16,225
3
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
ModelCardData
if self.model_name is None: raise ValueError("Passing `eval_results` requires `model_name` to be set.")
if_statement
16,238
16,357
3
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
ModelCardData
def _to_dict(self, data_dict): """Format the internal data dict. In this case, we convert eval results to a valid model index""" if self.eval_results is not None: data_dict["model-index"] = eval_results_to_model_index(self.model_name, self.eval_results) del data_dict["eval_results"], data_dict["model_name"]
function_definition
16,363
16,711
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
ModelCardData
if self.eval_results is not None: data_dict["model-index"] = eval_results_to_model_index(self.model_name, self.eval_results) del data_dict["eval_results"], data_dict["model_name"]
if_statement
16,508
16,711
2
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
ModelCardData
class DatasetCardData(CardData): """Dataset Card Metadata that is used by Hugging Face Hub when included at the top of your README.md Args: language (`List[str]`, *optional*): Language of dataset's data or metadata. It must be an ISO 639-1, 639-2 or 639-3 code (two/three letters), or a special value like "code", "multilingual". license (`Union[str, List[str]]`, *optional*): License(s) of this dataset. Example: apache-2.0 or any license from https://huggingface.co/docs/hub/repositories-licenses. annotations_creators (`Union[str, List[str]]`, *optional*): How the annotations for the dataset were created. Options are: 'found', 'crowdsourced', 'expert-generated', 'machine-generated', 'no-annotation', 'other'. language_creators (`Union[str, List[str]]`, *optional*): How the text-based data in the dataset was created. Options are: 'found', 'crowdsourced', 'expert-generated', 'machine-generated', 'other' multilinguality (`Union[str, List[str]]`, *optional*): Whether the dataset is multilingual. Options are: 'monolingual', 'multilingual', 'translation', 'other'. size_categories (`Union[str, List[str]]`, *optional*): The number of examples in the dataset. Options are: 'n<1K', '1K<n<10K', '10K<n<100K', '100K<n<1M', '1M<n<10M', '10M<n<100M', '100M<n<1B', '1B<n<10B', '10B<n<100B', '100B<n<1T', 'n>1T', and 'other'. source_datasets (`List[str]]`, *optional*): Indicates whether the dataset is an original dataset or extended from another existing dataset. Options are: 'original' and 'extended'. task_categories (`Union[str, List[str]]`, *optional*): What categories of task does the dataset support? task_ids (`Union[str, List[str]]`, *optional*): What specific tasks does the dataset support? paperswithcode_id (`str`, *optional*): ID of the dataset on PapersWithCode. pretty_name (`str`, *optional*): A more human-readable name for the dataset. (ex. "Cats vs. Dogs") train_eval_index (`Dict`, *optional*): A dictionary that describes the necessary spec for doing evaluation on the Hub. If not provided, it will be gathered from the 'train-eval-index' key of the kwargs. config_names (`Union[str, List[str]]`, *optional*): A list of the available dataset configs for the dataset. """ def __init__( self, *, language: Optional[Union[str, List[str]]] = None, license: Optional[Union[str, List[str]]] = None, annotations_creators: Optional[Union[str, List[str]]] = None, language_creators: Optional[Union[str, List[str]]] = None, multilinguality: Optional[Union[str, List[str]]] = None, size_categories: Optional[Union[str, List[str]]] = None, source_datasets: Optional[List[str]] = None, task_categories: Optional[Union[str, List[str]]] = None, task_ids: Optional[Union[str, List[str]]] = None, paperswithcode_id: Optional[str] = None, pretty_name: Optional[str] = None, train_eval_index: Optional[Dict] = None, config_names: Optional[Union[str, List[str]]] = None, ignore_metadata_errors: bool = False, **kwargs, ): self.annotations_creators = annotations_creators self.language_creators = language_creators self.language = language self.license = license self.multilinguality = multilinguality self.size_categories = size_categories self.source_datasets = source_datasets self.task_categories = task_categories self.task_ids = task_ids self.paperswithcode_id = paperswithcode_id self.pretty_name = pretty_name self.config_names = config_names # TODO - maybe handle this similarly to EvalResult? self.train_eval_index = train_eval_index or kwargs.pop("train-eval-index", None) super().__init__(**kwargs) def _to_dict(self, data_dict): data_dict["train-eval-index"] = data_dict.pop("train_eval_index")
class_definition
16,714
20,971
0
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
null
def __init__( self, *, language: Optional[Union[str, List[str]]] = None, license: Optional[Union[str, List[str]]] = None, annotations_creators: Optional[Union[str, List[str]]] = None, language_creators: Optional[Union[str, List[str]]] = None, multilinguality: Optional[Union[str, List[str]]] = None, size_categories: Optional[Union[str, List[str]]] = None, source_datasets: Optional[List[str]] = None, task_categories: Optional[Union[str, List[str]]] = None, task_ids: Optional[Union[str, List[str]]] = None, paperswithcode_id: Optional[str] = None, pretty_name: Optional[str] = None, train_eval_index: Optional[Dict] = None, config_names: Optional[Union[str, List[str]]] = None, ignore_metadata_errors: bool = False, **kwargs, ): self.annotations_creators = annotations_creators self.language_creators = language_creators self.language = language self.license = license self.multilinguality = multilinguality self.size_categories = size_categories self.source_datasets = source_datasets self.task_categories = task_categories self.task_ids = task_ids self.paperswithcode_id = paperswithcode_id self.pretty_name = pretty_name self.config_names = config_names # TODO - maybe handle this similarly to EvalResult? self.train_eval_index = train_eval_index or kwargs.pop("train-eval-index", None) super().__init__(**kwargs)
function_definition
19,282
20,861
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
DatasetCardData
def _to_dict(self, data_dict): data_dict["train-eval-index"] = data_dict.pop("train_eval_index")
function_definition
20,867
20,971
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
DatasetCardData
class SpaceCardData(CardData): """Space Card Metadata that is used by Hugging Face Hub when included at the top of your README.md To get an exhaustive reference of Spaces configuration, please visit https://huggingface.co/docs/hub/spaces-config-reference#spaces-configuration-reference. Args: title (`str`, *optional*) Title of the Space. sdk (`str`, *optional*) SDK of the Space (one of `gradio`, `streamlit`, `docker`, or `static`). sdk_version (`str`, *optional*) Version of the used SDK (if Gradio/Streamlit sdk). python_version (`str`, *optional*) Python version used in the Space (if Gradio/Streamlit sdk). app_file (`str`, *optional*) Path to your main application file (which contains either gradio or streamlit Python code, or static html code). Path is relative to the root of the repository. app_port (`str`, *optional*) Port on which your application is running. Used only if sdk is `docker`. license (`str`, *optional*) License of this model. Example: apache-2.0 or any license from https://huggingface.co/docs/hub/repositories-licenses. duplicated_from (`str`, *optional*) ID of the original Space if this is a duplicated Space. models (List[`str`], *optional*) List of models related to this Space. Should be a dataset ID found on https://hf.co/models. datasets (`List[str]`, *optional*) List of datasets related to this Space. Should be a dataset ID found on https://hf.co/datasets. tags (`List[str]`, *optional*) List of tags to add to your Space that can be used when filtering on the Hub. ignore_metadata_errors (`str`): If True, errors while parsing the metadata section will be ignored. Some information might be lost during the process. Use it at your own risk. kwargs (`dict`, *optional*): Additional metadata that will be added to the space card. Example: ```python >>> from huggingface_hub import SpaceCardData >>> card_data = SpaceCardData( ... title="Dreambooth Training", ... license="mit", ... sdk="gradio", ... duplicated_from="multimodalart/dreambooth-training" ... ) >>> card_data.to_dict() {'title': 'Dreambooth Training', 'sdk': 'gradio', 'license': 'mit', 'duplicated_from': 'multimodalart/dreambooth-training'} ``` """ def __init__( self, *, title: Optional[str] = None, sdk: Optional[str] = None, sdk_version: Optional[str] = None, python_version: Optional[str] = None, app_file: Optional[str] = None, app_port: Optional[int] = None, license: Optional[str] = None, duplicated_from: Optional[str] = None, models: Optional[List[str]] = None, datasets: Optional[List[str]] = None, tags: Optional[List[str]] = None, ignore_metadata_errors: bool = False, **kwargs, ): self.title = title self.sdk = sdk self.sdk_version = sdk_version self.python_version = python_version self.app_file = app_file self.app_port = app_port self.license = license self.duplicated_from = duplicated_from self.models = models self.datasets = datasets self.tags = _to_unique_list(tags) super().__init__(**kwargs)
class_definition
20,974
24,542
0
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
null
def __init__( self, *, title: Optional[str] = None, sdk: Optional[str] = None, sdk_version: Optional[str] = None, python_version: Optional[str] = None, app_file: Optional[str] = None, app_port: Optional[int] = None, license: Optional[str] = None, duplicated_from: Optional[str] = None, models: Optional[List[str]] = None, datasets: Optional[List[str]] = None, tags: Optional[List[str]] = None, ignore_metadata_errors: bool = False, **kwargs, ): self.title = title self.sdk = sdk self.sdk_version = sdk_version self.python_version = python_version self.app_file = app_file self.app_port = app_port self.license = license self.duplicated_from = duplicated_from self.models = models self.datasets = datasets self.tags = _to_unique_list(tags) super().__init__(**kwargs)
function_definition
23,557
24,542
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
SpaceCardData
def model_index_to_eval_results(model_index: List[Dict[str, Any]]) -> Tuple[str, List[EvalResult]]: """Takes in a model index and returns the model name and a list of `huggingface_hub.EvalResult` objects. A detailed spec of the model index can be found here: https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1 Args: model_index (`List[Dict[str, Any]]`): A model index data structure, likely coming from a README.md file on the Hugging Face Hub. Returns: model_name (`str`): The name of the model as found in the model index. This is used as the identifier for the model on leaderboards like PapersWithCode. eval_results (`List[EvalResult]`): A list of `huggingface_hub.EvalResult` objects containing the metrics reported in the provided model_index. Example: ```python >>> from huggingface_hub.repocard_data import model_index_to_eval_results >>> # Define a minimal model index >>> model_index = [ ... { ... "name": "my-cool-model", ... "results": [ ... { ... "task": { ... "type": "image-classification" ... }, ... "dataset": { ... "type": "beans", ... "name": "Beans" ... }, ... "metrics": [ ... { ... "type": "accuracy", ... "value": 0.9 ... } ... ] ... } ... ] ... } ... ] >>> model_name, eval_results = model_index_to_eval_results(model_index) >>> model_name 'my-cool-model' >>> eval_results[0].task_type 'image-classification' >>> eval_results[0].metric_type 'accuracy' ``` """ eval_results = [] for elem in model_index: name = elem["name"] results = elem["results"] for result in results: task_type = result["task"]["type"] task_name = result["task"].get("name") dataset_type = result["dataset"]["type"] dataset_name = result["dataset"]["name"] dataset_config = result["dataset"].get("config") dataset_split = result["dataset"].get("split") dataset_revision = result["dataset"].get("revision") dataset_args = result["dataset"].get("args") source_name = result.get("source", {}).get("name") source_url = result.get("source", {}).get("url") for metric in result["metrics"]: metric_type = metric["type"] metric_value = metric["value"] metric_name = metric.get("name") metric_args = metric.get("args") metric_config = metric.get("config") verified = metric.get("verified") verify_token = metric.get("verifyToken") eval_result = EvalResult( task_type=task_type, # Required dataset_type=dataset_type, # Required dataset_name=dataset_name, # Required metric_type=metric_type, # Required metric_value=metric_value, # Required task_name=task_name, dataset_config=dataset_config, dataset_split=dataset_split, dataset_revision=dataset_revision, dataset_args=dataset_args, metric_name=metric_name, metric_args=metric_args, metric_config=metric_config, verified=verified, verify_token=verify_token, source_name=source_name, source_url=source_url, ) eval_results.append(eval_result) return name, eval_results
function_definition
24,545
28,735
0
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
null
for elem in model_index: name = elem["name"] results = elem["results"] for result in results: task_type = result["task"]["type"] task_name = result["task"].get("name") dataset_type = result["dataset"]["type"] dataset_name = result["dataset"]["name"] dataset_config = result["dataset"].get("config") dataset_split = result["dataset"].get("split") dataset_revision = result["dataset"].get("revision") dataset_args = result["dataset"].get("args") source_name = result.get("source", {}).get("name") source_url = result.get("source", {}).get("url") for metric in result["metrics"]: metric_type = metric["type"] metric_value = metric["value"] metric_name = metric.get("name") metric_args = metric.get("args") metric_config = metric.get("config") verified = metric.get("verified") verify_token = metric.get("verifyToken") eval_result = EvalResult( task_type=task_type, # Required dataset_type=dataset_type, # Required dataset_name=dataset_name, # Required metric_type=metric_type, # Required metric_value=metric_value, # Required task_name=task_name, dataset_config=dataset_config, dataset_split=dataset_split, dataset_revision=dataset_revision, dataset_args=dataset_args, metric_name=metric_name, metric_args=metric_args, metric_config=metric_config, verified=verified, verify_token=verify_token, source_name=source_name, source_url=source_url, ) eval_results.append(eval_result)
for_statement
26,669
28,705
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
null
for result in results: task_type = result["task"]["type"] task_name = result["task"].get("name") dataset_type = result["dataset"]["type"] dataset_name = result["dataset"]["name"] dataset_config = result["dataset"].get("config") dataset_split = result["dataset"].get("split") dataset_revision = result["dataset"].get("revision") dataset_args = result["dataset"].get("args") source_name = result.get("source", {}).get("name") source_url = result.get("source", {}).get("url") for metric in result["metrics"]: metric_type = metric["type"] metric_value = metric["value"] metric_name = metric.get("name") metric_args = metric.get("args") metric_config = metric.get("config") verified = metric.get("verified") verify_token = metric.get("verifyToken") eval_result = EvalResult( task_type=task_type, # Required dataset_type=dataset_type, # Required dataset_name=dataset_name, # Required metric_type=metric_type, # Required metric_value=metric_value, # Required task_name=task_name, dataset_config=dataset_config, dataset_split=dataset_split, dataset_revision=dataset_revision, dataset_args=dataset_args, metric_name=metric_name, metric_args=metric_args, metric_config=metric_config, verified=verified, verify_token=verify_token, source_name=source_name, source_url=source_url, ) eval_results.append(eval_result)
for_statement
26,764
28,705
2
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
null
for metric in result["metrics"]: metric_type = metric["type"] metric_value = metric["value"] metric_name = metric.get("name") metric_args = metric.get("args") metric_config = metric.get("config") verified = metric.get("verified") verify_token = metric.get("verifyToken") eval_result = EvalResult( task_type=task_type, # Required dataset_type=dataset_type, # Required dataset_name=dataset_name, # Required metric_type=metric_type, # Required metric_value=metric_value, # Required task_name=task_name, dataset_config=dataset_config, dataset_split=dataset_split, dataset_revision=dataset_revision, dataset_args=dataset_args, metric_name=metric_name, metric_args=metric_args, metric_config=metric_config, verified=verified, verify_token=verify_token, source_name=source_name, source_url=source_url, ) eval_results.append(eval_result)
for_statement
27,370
28,705
3
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
null
def _remove_none(obj): """ Recursively remove `None` values from a dict. Borrowed from: https://stackoverflow.com/a/20558778 """ if isinstance(obj, (list, tuple, set)): return type(obj)(_remove_none(x) for x in obj if x is not None) elif isinstance(obj, dict): return type(obj)((_remove_none(k), _remove_none(v)) for k, v in obj.items() if k is not None and v is not None) else: return obj
function_definition
28,738
29,175
0
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
null
if isinstance(obj, (list, tuple, set)): return type(obj)(_remove_none(x) for x in obj if x is not None) elif isinstance(obj, dict): return type(obj)((_remove_none(k), _remove_none(v)) for k, v in obj.items() if k is not None and v is not None) else: return obj
if_statement
28,883
29,175
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
null
def eval_results_to_model_index(model_name: str, eval_results: List[EvalResult]) -> List[Dict[str, Any]]: """Takes in given model name and list of `huggingface_hub.EvalResult` and returns a valid model-index that will be compatible with the format expected by the Hugging Face Hub. Args: model_name (`str`): Name of the model (ex. "my-cool-model"). This is used as the identifier for the model on leaderboards like PapersWithCode. eval_results (`List[EvalResult]`): List of `huggingface_hub.EvalResult` objects containing the metrics to be reported in the model-index. Returns: model_index (`List[Dict[str, Any]]`): The eval_results converted to a model-index. Example: ```python >>> from huggingface_hub.repocard_data import eval_results_to_model_index, EvalResult >>> # Define minimal eval_results >>> eval_results = [ ... EvalResult( ... task_type="image-classification", # Required ... dataset_type="beans", # Required ... dataset_name="Beans", # Required ... metric_type="accuracy", # Required ... metric_value=0.9, # Required ... ) ... ] >>> eval_results_to_model_index("my-cool-model", eval_results) [{'name': 'my-cool-model', 'results': [{'task': {'type': 'image-classification'}, 'dataset': {'name': 'Beans', 'type': 'beans'}, 'metrics': [{'type': 'accuracy', 'value': 0.9}]}]}] ``` """ # Metrics are reported on a unique task-and-dataset basis. # Here, we make a map of those pairs and the associated EvalResults. task_and_ds_types_map: Dict[Any, List[EvalResult]] = defaultdict(list) for eval_result in eval_results: task_and_ds_types_map[eval_result.unique_identifier].append(eval_result) # Use the map from above to generate the model index data. model_index_data = [] for results in task_and_ds_types_map.values(): # All items from `results` share same metadata sample_result = results[0] data = { "task": { "type": sample_result.task_type, "name": sample_result.task_name, }, "dataset": { "name": sample_result.dataset_name, "type": sample_result.dataset_type, "config": sample_result.dataset_config, "split": sample_result.dataset_split, "revision": sample_result.dataset_revision, "args": sample_result.dataset_args, }, "metrics": [ { "type": result.metric_type, "value": result.metric_value, "name": result.metric_name, "config": result.metric_config, "args": result.metric_args, "verified": result.verified, "verifyToken": result.verify_token, } for result in results ], } if sample_result.source_url is not None: source = { "url": sample_result.source_url, } if sample_result.source_name is not None: source["name"] = sample_result.source_name data["source"] = source model_index_data.append(data) # TODO - Check if there cases where this list is longer than one? # Finally, the model index itself is list of dicts. model_index = [ { "name": model_name, "results": model_index_data, } ] return _remove_none(model_index)
function_definition
29,178
32,909
0
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
null
for eval_result in eval_results: task_and_ds_types_map[eval_result.unique_identifier].append(eval_result)
for_statement
30,967
31,080
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
null
for results in task_and_ds_types_map.values(): # All items from `results` share same metadata sample_result = results[0] data = { "task": { "type": sample_result.task_type, "name": sample_result.task_name, }, "dataset": { "name": sample_result.dataset_name, "type": sample_result.dataset_type, "config": sample_result.dataset_config, "split": sample_result.dataset_split, "revision": sample_result.dataset_revision, "args": sample_result.dataset_args, }, "metrics": [ { "type": result.metric_type, "value": result.metric_value, "name": result.metric_name, "config": result.metric_config, "args": result.metric_args, "verified": result.verified, "verifyToken": result.verify_token, } for result in results ], } if sample_result.source_url is not None: source = { "url": sample_result.source_url, } if sample_result.source_name is not None: source["name"] = sample_result.source_name data["source"] = source model_index_data.append(data)
for_statement
31,175
32,626
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
null
if sample_result.source_url is not None: source = { "url": sample_result.source_url, } if sample_result.source_name is not None: source["name"] = sample_result.source_name data["source"] = source
if_statement
32,313
32,588
2
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
null
if sample_result.source_name is not None: source["name"] = sample_result.source_name
if_statement
32,452
32,552
3
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
null
def _to_unique_list(tags: Optional[List[str]]) -> Optional[List[str]]: if tags is None: return tags unique_tags = [] # make tags unique + keep order explicitly for tag in tags: if tag not in unique_tags: unique_tags.append(tag) return unique_tags
function_definition
32,912
33,203
0
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
null
if tags is None: return tags
if_statement
32,987
33,023
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
null
for tag in tags: if tag not in unique_tags: unique_tags.append(tag)
for_statement
33,093
33,180
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
null
if tag not in unique_tags: unique_tags.append(tag)
if_statement
33,118
33,180
2
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/repocard_data.py
null
if is_pydantic_available(): from pydantic import BaseModel else: # Define a dummy BaseModel to avoid import errors when pydantic is not installed # Import error will be raised when trying to use the class class BaseModel: # type: ignore [no-redef] def __init__(self, *args, **kwargs) -> None: raise ImportError( "You must have `pydantic` installed to use `WebhookPayload`. This is an optional dependency that" " should be installed separately. Please run `pip install --upgrade pydantic` and retry." )
if_statement
764
1,347
0
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_payload.py
null
class BaseModel: # type: ignore [no-redef] def __init__(self, *args, **kwargs) -> None: raise ImportError( "You must have `pydantic` installed to use `WebhookPayload`. This is an optional dependency that" " should be installed separately. Please run `pip install --upgrade pydantic` and retry." )
class_definition
986
1,347
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_payload.py
null
def __init__(self, *args, **kwargs) -> None: raise ImportError( "You must have `pydantic` installed to use `WebhookPayload`. This is an optional dependency that" " should be installed separately. Please run `pip install --upgrade pydantic` and retry." )
function_definition
1,038
1,347
2
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_payload.py
BaseModel
class ObjectId(BaseModel): id: str
class_definition
1,991
2,029
0
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_payload.py
null
class WebhookPayloadUrl(BaseModel): web: str api: Optional[str] = None
class_definition
2,032
2,110
0
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_payload.py
null
class WebhookPayloadMovedTo(BaseModel): name: str owner: ObjectId
class_definition
2,113
2,186
0
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_payload.py
null
class WebhookPayloadWebhook(ObjectId): version: SupportedWebhookVersion
class_definition
2,189
2,264
0
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_payload.py
null
class WebhookPayloadEvent(BaseModel): action: WebhookEvent_T scope: str
class_definition
2,267
2,346
0
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_payload.py
null
class WebhookPayloadDiscussionChanges(BaseModel): base: str mergeCommitId: Optional[str] = None
class_definition
2,349
2,452
0
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_payload.py
null
class WebhookPayloadComment(ObjectId): author: ObjectId hidden: bool content: Optional[str] = None url: WebhookPayloadUrl
class_definition
2,455
2,592
0
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_payload.py
null
class WebhookPayloadDiscussion(ObjectId): num: int author: ObjectId url: WebhookPayloadUrl title: str isPullRequest: bool status: DiscussionStatus_T changes: Optional[WebhookPayloadDiscussionChanges] = None pinned: Optional[bool] = None
class_definition
2,595
2,863
0
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_payload.py
null
class WebhookPayloadRepo(ObjectId): owner: ObjectId head_sha: Optional[str] = None name: str private: bool subdomain: Optional[str] = None tags: Optional[List[str]] = None type: Literal["dataset", "model", "space"] url: WebhookPayloadUrl
class_definition
2,866
3,135
0
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_payload.py
null
class WebhookPayloadUpdatedRef(BaseModel): ref: str oldSha: Optional[str] = None newSha: Optional[str] = None
class_definition
3,138
3,259
0
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_payload.py
null
class WebhookPayload(BaseModel): event: WebhookPayloadEvent repo: WebhookPayloadRepo discussion: Optional[WebhookPayloadDiscussion] = None comment: Optional[WebhookPayloadComment] = None webhook: WebhookPayloadWebhook movedTo: Optional[WebhookPayloadMovedTo] = None updatedRefs: Optional[List[WebhookPayloadUpdatedRef]] = None
class_definition
3,262
3,616
0
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/_webhooks_payload.py
null
if TYPE_CHECKING: from _typeshed import DataclassInstance
if_statement
664
725
0
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
null
if is_torch_available(): import torch # type: ignore
if_statement
727
784
0
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
null
if is_safetensors_available(): import safetensors from safetensors.torch import load_model as load_model_as_safetensor from safetensors.torch import save_model as save_model_as_safetensor
if_statement
786
985
0
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
null
class MixinInfo: model_card_template: str model_card_data: ModelCardData repo_url: Optional[str] = None docs_url: Optional[str] = None
class_definition
1,902
2,052
0
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
null
class ModelHubMixin: """ A generic mixin to integrate ANY machine learning framework with the Hub. To integrate your framework, your model class must inherit from this class. Custom logic for saving/loading models have to be overwritten in [`_from_pretrained`] and [`_save_pretrained`]. [`PyTorchModelHubMixin`] is a good example of mixin integration with the Hub. Check out our [integration guide](../guides/integrations) for more instructions. When inheriting from [`ModelHubMixin`], you can define class-level attributes. These attributes are not passed to `__init__` but to the class definition itself. This is useful to define metadata about the library integrating [`ModelHubMixin`]. For more details on how to integrate the mixin with your library, checkout the [integration guide](../guides/integrations). Args: repo_url (`str`, *optional*): URL of the library repository. Used to generate model card. docs_url (`str`, *optional*): URL of the library documentation. Used to generate model card. model_card_template (`str`, *optional*): Template of the model card. Used to generate model card. Defaults to a generic template. language (`str` or `List[str]`, *optional*): Language supported by the library. Used to generate model card. library_name (`str`, *optional*): Name of the library integrating ModelHubMixin. Used to generate model card. license (`str`, *optional*): License of the library integrating ModelHubMixin. Used to generate model card. E.g: "apache-2.0" license_name (`str`, *optional*): Name of the library integrating ModelHubMixin. Used to generate model card. Only used if `license` is set to `other`. E.g: "coqui-public-model-license". license_link (`str`, *optional*): URL to the license of the library integrating ModelHubMixin. Used to generate model card. Only used if `license` is set to `other` and `license_name` is set. E.g: "https://coqui.ai/cpml". pipeline_tag (`str`, *optional*): Tag of the pipeline. Used to generate model card. E.g. "text-classification". tags (`List[str]`, *optional*): Tags to be added to the model card. Used to generate model card. E.g. ["x-custom-tag", "arxiv:2304.12244"] coders (`Dict[Type, Tuple[Callable, Callable]]`, *optional*): Dictionary of custom types and their encoders/decoders. Used to encode/decode arguments that are not jsonable by default. E.g dataclasses, argparse.Namespace, OmegaConf, etc. Example: ```python >>> from huggingface_hub import ModelHubMixin # Inherit from ModelHubMixin >>> class MyCustomModel( ... ModelHubMixin, ... library_name="my-library", ... tags=["x-custom-tag", "arxiv:2304.12244"], ... repo_url="https://github.com/huggingface/my-cool-library", ... docs_url="https://huggingface.co/docs/my-cool-library", ... # ^ optional metadata to generate model card ... ): ... def __init__(self, size: int = 512, device: str = "cpu"): ... # define how to initialize your model ... super().__init__() ... ... ... ... def _save_pretrained(self, save_directory: Path) -> None: ... # define how to serialize your model ... ... ... ... @classmethod ... def from_pretrained( ... cls: Type[T], ... pretrained_model_name_or_path: Union[str, Path], ... *, ... force_download: bool = False, ... resume_download: Optional[bool] = None, ... proxies: Optional[Dict] = None, ... token: Optional[Union[str, bool]] = None, ... cache_dir: Optional[Union[str, Path]] = None, ... local_files_only: bool = False, ... revision: Optional[str] = None, ... **model_kwargs, ... ) -> T: ... # define how to deserialize your model ... ... >>> model = MyCustomModel(size=256, device="gpu") # Save model weights to local directory >>> model.save_pretrained("my-awesome-model") # Push model weights to the Hub >>> model.push_to_hub("my-awesome-model") # Download and initialize weights from the Hub >>> reloaded_model = MyCustomModel.from_pretrained("username/my-awesome-model") >>> reloaded_model.size 256 # Model card has been correctly populated >>> from huggingface_hub import ModelCard >>> card = ModelCard.load("username/my-awesome-model") >>> card.data.tags ["x-custom-tag", "pytorch_model_hub_mixin", "model_hub_mixin"] >>> card.data.library_name "my-library" ``` """ _hub_mixin_config: Optional[Union[dict, "DataclassInstance"]] = None # ^ optional config attribute automatically set in `from_pretrained` _hub_mixin_info: MixinInfo # ^ information about the library integrating ModelHubMixin (used to generate model card) _hub_mixin_inject_config: bool # whether `_from_pretrained` expects `config` or not _hub_mixin_init_parameters: Dict[str, inspect.Parameter] # __init__ parameters _hub_mixin_jsonable_default_values: Dict[str, Any] # default values for __init__ parameters _hub_mixin_jsonable_custom_types: Tuple[Type, ...] # custom types that can be encoded/decoded _hub_mixin_coders: Dict[Type, CODER_T] # encoders/decoders for custom types # ^ internal values to handle config def __init_subclass__( cls, *, # Generic info for model card repo_url: Optional[str] = None, docs_url: Optional[str] = None, # Model card template model_card_template: str = DEFAULT_MODEL_CARD, # Model card metadata language: Optional[List[str]] = None, library_name: Optional[str] = None, license: Optional[str] = None, license_name: Optional[str] = None, license_link: Optional[str] = None, pipeline_tag: Optional[str] = None, tags: Optional[List[str]] = None, # How to encode/decode arguments with custom type into a JSON config? coders: Optional[ Dict[Type, CODER_T] # Key is a type. # Value is a tuple (encoder, decoder). # Example: {MyCustomType: (lambda x: x.value, lambda data: MyCustomType(data))} ] = None, ) -> None: """Inspect __init__ signature only once when subclassing + handle modelcard.""" super().__init_subclass__() # Will be reused when creating modelcard tags = tags or [] tags.append("model_hub_mixin") # Initialize MixinInfo if not existent info = MixinInfo(model_card_template=model_card_template, model_card_data=ModelCardData()) # If parent class has a MixinInfo, inherit from it as a copy if hasattr(cls, "_hub_mixin_info"): # Inherit model card template from parent class if not explicitly set if model_card_template == DEFAULT_MODEL_CARD: info.model_card_template = cls._hub_mixin_info.model_card_template # Inherit from parent model card data info.model_card_data = ModelCardData(**cls._hub_mixin_info.model_card_data.to_dict()) # Inherit other info info.docs_url = cls._hub_mixin_info.docs_url info.repo_url = cls._hub_mixin_info.repo_url cls._hub_mixin_info = info # Update MixinInfo with metadata if model_card_template is not None and model_card_template != DEFAULT_MODEL_CARD: info.model_card_template = model_card_template if repo_url is not None: info.repo_url = repo_url if docs_url is not None: info.docs_url = docs_url if language is not None: info.model_card_data.language = language if library_name is not None: info.model_card_data.library_name = library_name if license is not None: info.model_card_data.license = license if license_name is not None: info.model_card_data.license_name = license_name if license_link is not None: info.model_card_data.license_link = license_link if pipeline_tag is not None: info.model_card_data.pipeline_tag = pipeline_tag if tags is not None: if info.model_card_data.tags is not None: info.model_card_data.tags.extend(tags) else: info.model_card_data.tags = tags info.model_card_data.tags = sorted(set(info.model_card_data.tags)) # Handle encoders/decoders for args cls._hub_mixin_coders = coders or {} cls._hub_mixin_jsonable_custom_types = tuple(cls._hub_mixin_coders.keys()) # Inspect __init__ signature to handle config cls._hub_mixin_init_parameters = dict(inspect.signature(cls.__init__).parameters) cls._hub_mixin_jsonable_default_values = { param.name: cls._encode_arg(param.default) for param in cls._hub_mixin_init_parameters.values() if param.default is not inspect.Parameter.empty and cls._is_jsonable(param.default) } cls._hub_mixin_inject_config = "config" in inspect.signature(cls._from_pretrained).parameters def __new__(cls: Type[T], *args, **kwargs) -> T: """Create a new instance of the class and handle config. 3 cases: - If `self._hub_mixin_config` is already set, do nothing. - If `config` is passed as a dataclass, set it as `self._hub_mixin_config`. - Otherwise, build `self._hub_mixin_config` from default values and passed values. """ instance = super().__new__(cls) # If `config` is already set, return early if instance._hub_mixin_config is not None: return instance # Infer passed values passed_values = { **{ key: value for key, value in zip( # [1:] to skip `self` parameter list(cls._hub_mixin_init_parameters)[1:], args, ) }, **kwargs, } # If config passed as dataclass => set it and return early if is_dataclass(passed_values.get("config")): instance._hub_mixin_config = passed_values["config"] return instance # Otherwise, build config from default + passed values init_config = { # default values **cls._hub_mixin_jsonable_default_values, # passed values **{ key: cls._encode_arg(value) # Encode custom types as jsonable value for key, value in passed_values.items() if instance._is_jsonable(value) # Only if jsonable or we have a custom encoder }, } passed_config = init_config.pop("config", {}) # Populate `init_config` with provided config if isinstance(passed_config, dict): init_config.update(passed_config) # Set `config` attribute and return if init_config != {}: instance._hub_mixin_config = init_config return instance @classmethod def _is_jsonable(cls, value: Any) -> bool: """Check if a value is JSON serializable.""" if isinstance(value, cls._hub_mixin_jsonable_custom_types): return True return is_jsonable(value) @classmethod def _encode_arg(cls, arg: Any) -> Any: """Encode an argument into a JSON serializable format.""" for type_, (encoder, _) in cls._hub_mixin_coders.items(): if isinstance(arg, type_): if arg is None: return None return encoder(arg) return arg @classmethod def _decode_arg(cls, expected_type: Type[ARGS_T], value: Any) -> Optional[ARGS_T]: """Decode a JSON serializable value into an argument.""" if is_simple_optional_type(expected_type): if value is None: return None expected_type = unwrap_simple_optional_type(expected_type) # Dataclass => handle it if is_dataclass(expected_type): return _load_dataclass(expected_type, value) # type: ignore[return-value] # Otherwise => check custom decoders for type_, (_, decoder) in cls._hub_mixin_coders.items(): if inspect.isclass(expected_type) and issubclass(expected_type, type_): return decoder(value) # Otherwise => don't decode return value def save_pretrained( self, save_directory: Union[str, Path], *, config: Optional[Union[dict, "DataclassInstance"]] = None, repo_id: Optional[str] = None, push_to_hub: bool = False, model_card_kwargs: Optional[Dict[str, Any]] = None, **push_to_hub_kwargs, ) -> Optional[str]: """ Save weights in local directory. Args: save_directory (`str` or `Path`): Path to directory in which the model weights and configuration will be saved. config (`dict` or `DataclassInstance`, *optional*): Model configuration specified as a key/value dictionary or a dataclass instance. push_to_hub (`bool`, *optional*, defaults to `False`): Whether or not to push your model to the Huggingface Hub after saving it. repo_id (`str`, *optional*): ID of your repository on the Hub. Used only if `push_to_hub=True`. Will default to the folder name if not provided. model_card_kwargs (`Dict[str, Any]`, *optional*): Additional arguments passed to the model card template to customize the model card. push_to_hub_kwargs: Additional key word arguments passed along to the [`~ModelHubMixin.push_to_hub`] method. Returns: `str` or `None`: url of the commit on the Hub if `push_to_hub=True`, `None` otherwise. """ save_directory = Path(save_directory) save_directory.mkdir(parents=True, exist_ok=True) # Remove config.json if already exists. After `_save_pretrained` we don't want to overwrite config.json # as it might have been saved by the custom `_save_pretrained` already. However we do want to overwrite # an existing config.json if it was not saved by `_save_pretrained`. config_path = save_directory / constants.CONFIG_NAME config_path.unlink(missing_ok=True) # save model weights/files (framework-specific) self._save_pretrained(save_directory) # save config (if provided and if not serialized yet in `_save_pretrained`) if config is None: config = self._hub_mixin_config if config is not None: if is_dataclass(config): config = asdict(config) # type: ignore[arg-type] if not config_path.exists(): config_str = json.dumps(config, sort_keys=True, indent=2) config_path.write_text(config_str) # save model card model_card_path = save_directory / "README.md" model_card_kwargs = model_card_kwargs if model_card_kwargs is not None else {} if not model_card_path.exists(): # do not overwrite if already exists self.generate_model_card(**model_card_kwargs).save(save_directory / "README.md") # push to the Hub if required if push_to_hub: kwargs = push_to_hub_kwargs.copy() # soft-copy to avoid mutating input if config is not None: # kwarg for `push_to_hub` kwargs["config"] = config if repo_id is None: repo_id = save_directory.name # Defaults to `save_directory` name return self.push_to_hub(repo_id=repo_id, model_card_kwargs=model_card_kwargs, **kwargs) return None def _save_pretrained(self, save_directory: Path) -> None: """ Overwrite this method in subclass to define how to save your model. Check out our [integration guide](../guides/integrations) for instructions. Args: save_directory (`str` or `Path`): Path to directory in which the model weights and configuration will be saved. """ raise NotImplementedError @classmethod @validate_hf_hub_args def from_pretrained( cls: Type[T], pretrained_model_name_or_path: Union[str, Path], *, force_download: bool = False, resume_download: Optional[bool] = None, proxies: Optional[Dict] = None, token: Optional[Union[str, bool]] = None, cache_dir: Optional[Union[str, Path]] = None, local_files_only: bool = False, revision: Optional[str] = None, **model_kwargs, ) -> T: """ Download a model from the Huggingface Hub and instantiate it. Args: pretrained_model_name_or_path (`str`, `Path`): - Either the `model_id` (string) of a model hosted on the Hub, e.g. `bigscience/bloom`. - Or a path to a `directory` containing model weights saved using [`~transformers.PreTrainedModel.save_pretrained`], e.g., `../path/to/my_model_directory/`. revision (`str`, *optional*): Revision of the model on the Hub. Can be a branch name, a git tag or any commit id. Defaults to the latest commit on `main` branch. force_download (`bool`, *optional*, defaults to `False`): Whether to force (re-)downloading the model weights and configuration files from the Hub, overriding the existing cache. proxies (`Dict[str, str]`, *optional*): A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}`. The proxies are used on every request. token (`str` or `bool`, *optional*): The token to use as HTTP bearer authorization for remote files. By default, it will use the token cached when running `huggingface-cli login`. cache_dir (`str`, `Path`, *optional*): Path to the folder where cached files are stored. 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. model_kwargs (`Dict`, *optional*): Additional kwargs to pass to the model during initialization. """ model_id = str(pretrained_model_name_or_path) config_file: Optional[str] = None if os.path.isdir(model_id): if constants.CONFIG_NAME in os.listdir(model_id): config_file = os.path.join(model_id, constants.CONFIG_NAME) else: logger.warning(f"{constants.CONFIG_NAME} not found in {Path(model_id).resolve()}") else: try: config_file = hf_hub_download( repo_id=model_id, filename=constants.CONFIG_NAME, revision=revision, cache_dir=cache_dir, force_download=force_download, proxies=proxies, resume_download=resume_download, token=token, local_files_only=local_files_only, ) except HfHubHTTPError as e: logger.info(f"{constants.CONFIG_NAME} not found on the HuggingFace Hub: {str(e)}") # Read config config = None if config_file is not None: with open(config_file, "r", encoding="utf-8") as f: config = json.load(f) # Decode custom types in config for key, value in config.items(): if key in cls._hub_mixin_init_parameters: expected_type = cls._hub_mixin_init_parameters[key].annotation if expected_type is not inspect.Parameter.empty: config[key] = cls._decode_arg(expected_type, value) # Populate model_kwargs from config for param in cls._hub_mixin_init_parameters.values(): if param.name not in model_kwargs and param.name in config: model_kwargs[param.name] = config[param.name] # Check if `config` argument was passed at init if "config" in cls._hub_mixin_init_parameters and "config" not in model_kwargs: # Decode `config` argument if it was passed config_annotation = cls._hub_mixin_init_parameters["config"].annotation config = cls._decode_arg(config_annotation, config) # Forward config to model initialization model_kwargs["config"] = config # Inject config if `**kwargs` are expected if is_dataclass(cls): for key in cls.__dataclass_fields__: if key not in model_kwargs and key in config: model_kwargs[key] = config[key] elif any(param.kind == inspect.Parameter.VAR_KEYWORD for param in cls._hub_mixin_init_parameters.values()): for key, value in config.items(): if key not in model_kwargs: model_kwargs[key] = value # Finally, also inject if `_from_pretrained` expects it if cls._hub_mixin_inject_config and "config" not in model_kwargs: model_kwargs["config"] = config instance = cls._from_pretrained( model_id=str(model_id), revision=revision, cache_dir=cache_dir, force_download=force_download, proxies=proxies, resume_download=resume_download, local_files_only=local_files_only, token=token, **model_kwargs, ) # Implicitly set the config as instance attribute if not already set by the class # This way `config` will be available when calling `save_pretrained` or `push_to_hub`. if config is not None and (getattr(instance, "_hub_mixin_config", None) in (None, {})): instance._hub_mixin_config = config return instance @classmethod def _from_pretrained( cls: Type[T], *, model_id: str, revision: Optional[str], cache_dir: Optional[Union[str, Path]], force_download: bool, proxies: Optional[Dict], resume_download: Optional[bool], local_files_only: bool, token: Optional[Union[str, bool]], **model_kwargs, ) -> T: """Overwrite this method in subclass to define how to load your model from pretrained. Use [`hf_hub_download`] or [`snapshot_download`] to download files from the Hub before loading them. Most args taken as input can be directly passed to those 2 methods. If needed, you can add more arguments to this method using "model_kwargs". For example [`PyTorchModelHubMixin._from_pretrained`] takes as input a `map_location` parameter to set on which device the model should be loaded. Check out our [integration guide](../guides/integrations) for more instructions. Args: model_id (`str`): ID of the model to load from the Huggingface Hub (e.g. `bigscience/bloom`). revision (`str`, *optional*): Revision of the model on the Hub. Can be a branch name, a git tag or any commit id. Defaults to the latest commit on `main` branch. force_download (`bool`, *optional*, defaults to `False`): Whether to force (re-)downloading the model weights and configuration files from the Hub, overriding the existing cache. proxies (`Dict[str, str]`, *optional*): A dictionary of proxy servers to use by protocol or endpoint (e.g., `{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}`). token (`str` or `bool`, *optional*): The token to use as HTTP bearer authorization for remote files. By default, it will use the token cached when running `huggingface-cli login`. cache_dir (`str`, `Path`, *optional*): Path to the folder where cached files are stored. 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. model_kwargs: Additional keyword arguments passed along to the [`~ModelHubMixin._from_pretrained`] method. """ raise NotImplementedError @validate_hf_hub_args def push_to_hub( self, repo_id: str, *, config: Optional[Union[dict, "DataclassInstance"]] = None, commit_message: str = "Push model using huggingface_hub.", private: Optional[bool] = None, token: Optional[str] = None, branch: Optional[str] = None, create_pr: Optional[bool] = None, allow_patterns: Optional[Union[List[str], str]] = None, ignore_patterns: Optional[Union[List[str], str]] = None, delete_patterns: Optional[Union[List[str], str]] = None, model_card_kwargs: Optional[Dict[str, Any]] = None, ) -> str: """ Upload model checkpoint to the Hub. Use `allow_patterns` and `ignore_patterns` to precisely filter which files should be pushed to the hub. Use `delete_patterns` to delete existing remote files in the same commit. See [`upload_folder`] reference for more details. Args: repo_id (`str`): ID of the repository to push to (example: `"username/my-model"`). config (`dict` or `DataclassInstance`, *optional*): Model configuration specified as a key/value dictionary or a dataclass instance. commit_message (`str`, *optional*): Message to commit while pushing. private (`bool`, *optional*): Whether the repository created should be private. If `None` (default), the repo will be public unless the organization's default is private. token (`str`, *optional*): The token to use as HTTP bearer authorization for remote files. By default, it will use the token cached when running `huggingface-cli login`. branch (`str`, *optional*): The git branch on which to push the model. This defaults to `"main"`. create_pr (`boolean`, *optional*): Whether or not to create a Pull Request from `branch` with that commit. Defaults to `False`. allow_patterns (`List[str]` or `str`, *optional*): If provided, only files matching at least one pattern are pushed. ignore_patterns (`List[str]` or `str`, *optional*): If provided, files matching any of the patterns are not pushed. delete_patterns (`List[str]` or `str`, *optional*): If provided, remote files matching any of the patterns will be deleted from the repo. model_card_kwargs (`Dict[str, Any]`, *optional*): Additional arguments passed to the model card template to customize the model card. Returns: The url of the commit of your model in the given repository. """ api = HfApi(token=token) repo_id = api.create_repo(repo_id=repo_id, private=private, exist_ok=True).repo_id # Push the files to the repo in a single commit with SoftTemporaryDirectory() as tmp: saved_path = Path(tmp) / repo_id self.save_pretrained(saved_path, config=config, model_card_kwargs=model_card_kwargs) return api.upload_folder( repo_id=repo_id, repo_type="model", folder_path=saved_path, commit_message=commit_message, revision=branch, create_pr=create_pr, allow_patterns=allow_patterns, ignore_patterns=ignore_patterns, delete_patterns=delete_patterns, ) def generate_model_card(self, *args, **kwargs) -> ModelCard: card = ModelCard.from_template( card_data=self._hub_mixin_info.model_card_data, template_str=self._hub_mixin_info.model_card_template, repo_url=self._hub_mixin_info.repo_url, docs_url=self._hub_mixin_info.docs_url, **kwargs, ) return card
class_definition
2,055
31,281
0
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
null
def __init_subclass__( cls, *, # Generic info for model card repo_url: Optional[str] = None, docs_url: Optional[str] = None, # Model card template model_card_template: str = DEFAULT_MODEL_CARD, # Model card metadata language: Optional[List[str]] = None, library_name: Optional[str] = None, license: Optional[str] = None, license_name: Optional[str] = None, license_link: Optional[str] = None, pipeline_tag: Optional[str] = None, tags: Optional[List[str]] = None, # How to encode/decode arguments with custom type into a JSON config? coders: Optional[ Dict[Type, CODER_T] # Key is a type. # Value is a tuple (encoder, decoder). # Example: {MyCustomType: (lambda x: x.value, lambda data: MyCustomType(data))} ] = None, ) -> None: """Inspect __init__ signature only once when subclassing + handle modelcard.""" super().__init_subclass__() # Will be reused when creating modelcard tags = tags or [] tags.append("model_hub_mixin") # Initialize MixinInfo if not existent info = MixinInfo(model_card_template=model_card_template, model_card_data=ModelCardData()) # If parent class has a MixinInfo, inherit from it as a copy if hasattr(cls, "_hub_mixin_info"): # Inherit model card template from parent class if not explicitly set if model_card_template == DEFAULT_MODEL_CARD: info.model_card_template = cls._hub_mixin_info.model_card_template # Inherit from parent model card data info.model_card_data = ModelCardData(**cls._hub_mixin_info.model_card_data.to_dict()) # Inherit other info info.docs_url = cls._hub_mixin_info.docs_url info.repo_url = cls._hub_mixin_info.repo_url cls._hub_mixin_info = info # Update MixinInfo with metadata if model_card_template is not None and model_card_template != DEFAULT_MODEL_CARD: info.model_card_template = model_card_template if repo_url is not None: info.repo_url = repo_url if docs_url is not None: info.docs_url = docs_url if language is not None: info.model_card_data.language = language if library_name is not None: info.model_card_data.library_name = library_name if license is not None: info.model_card_data.license = license if license_name is not None: info.model_card_data.license_name = license_name if license_link is not None: info.model_card_data.license_link = license_link if pipeline_tag is not None: info.model_card_data.pipeline_tag = pipeline_tag if tags is not None: if info.model_card_data.tags is not None: info.model_card_data.tags.extend(tags) else: info.model_card_data.tags = tags info.model_card_data.tags = sorted(set(info.model_card_data.tags)) # Handle encoders/decoders for args cls._hub_mixin_coders = coders or {} cls._hub_mixin_jsonable_custom_types = tuple(cls._hub_mixin_coders.keys()) # Inspect __init__ signature to handle config cls._hub_mixin_init_parameters = dict(inspect.signature(cls.__init__).parameters) cls._hub_mixin_jsonable_default_values = { param.name: cls._encode_arg(param.default) for param in cls._hub_mixin_init_parameters.values() if param.default is not inspect.Parameter.empty and cls._is_jsonable(param.default) } cls._hub_mixin_inject_config = "config" in inspect.signature(cls._from_pretrained).parameters
function_definition
7,747
11,595
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
ModelHubMixin
if hasattr(cls, "_hub_mixin_info"): # Inherit model card template from parent class if not explicitly set if model_card_template == DEFAULT_MODEL_CARD: info.model_card_template = cls._hub_mixin_info.model_card_template # Inherit from parent model card data info.model_card_data = ModelCardData(**cls._hub_mixin_info.model_card_data.to_dict()) # Inherit other info info.docs_url = cls._hub_mixin_info.docs_url info.repo_url = cls._hub_mixin_info.repo_url
if_statement
9,135
9,690
2
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
ModelHubMixin
if model_card_template == DEFAULT_MODEL_CARD: info.model_card_template = cls._hub_mixin_info.model_card_template
if_statement
9,265
9,393
3
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
ModelHubMixin
if model_card_template is not None and model_card_template != DEFAULT_MODEL_CARD: info.model_card_template = model_card_template
if_statement
9,776
9,916
2
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
ModelHubMixin
if repo_url is not None: info.repo_url = repo_url
if_statement
9,925
9,986
2
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
ModelHubMixin
if docs_url is not None: info.docs_url = docs_url
if_statement
9,995
10,056
2
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
ModelHubMixin
if language is not None: info.model_card_data.language = language
if_statement
10,065
10,142
2
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
ModelHubMixin
if library_name is not None: info.model_card_data.library_name = library_name
if_statement
10,151
10,240
2
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
ModelHubMixin
if license is not None: info.model_card_data.license = license
if_statement
10,249
10,323
2
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
ModelHubMixin
if license_name is not None: info.model_card_data.license_name = license_name
if_statement
10,332
10,421
2
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
ModelHubMixin
if license_link is not None: info.model_card_data.license_link = license_link
if_statement
10,430
10,519
2
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
ModelHubMixin
if pipeline_tag is not None: info.model_card_data.pipeline_tag = pipeline_tag
if_statement
10,528
10,617
2
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
ModelHubMixin
if tags is not None: if info.model_card_data.tags is not None: info.model_card_data.tags.extend(tags) else: info.model_card_data.tags = tags
if_statement
10,626
10,822
2
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
ModelHubMixin
if info.model_card_data.tags is not None: info.model_card_data.tags.extend(tags) else: info.model_card_data.tags = tags
if_statement
10,659
10,822
3
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
ModelHubMixin
def __new__(cls: Type[T], *args, **kwargs) -> T: """Create a new instance of the class and handle config. 3 cases: - If `self._hub_mixin_config` is already set, do nothing. - If `config` is passed as a dataclass, set it as `self._hub_mixin_config`. - Otherwise, build `self._hub_mixin_config` from default values and passed values. """ instance = super().__new__(cls) # If `config` is already set, return early if instance._hub_mixin_config is not None: return instance # Infer passed values passed_values = { **{ key: value for key, value in zip( # [1:] to skip `self` parameter list(cls._hub_mixin_init_parameters)[1:], args, ) }, **kwargs, } # If config passed as dataclass => set it and return early if is_dataclass(passed_values.get("config")): instance._hub_mixin_config = passed_values["config"] return instance # Otherwise, build config from default + passed values init_config = { # default values **cls._hub_mixin_jsonable_default_values, # passed values **{ key: cls._encode_arg(value) # Encode custom types as jsonable value for key, value in passed_values.items() if instance._is_jsonable(value) # Only if jsonable or we have a custom encoder }, } passed_config = init_config.pop("config", {}) # Populate `init_config` with provided config if isinstance(passed_config, dict): init_config.update(passed_config) # Set `config` attribute and return if init_config != {}: instance._hub_mixin_config = init_config return instance
function_definition
11,601
13,543
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
ModelHubMixin
if instance._hub_mixin_config is not None: return instance
if_statement
12,086
12,156
2
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
ModelHubMixin
if is_dataclass(passed_values.get("config")): instance._hub_mixin_config = passed_values["config"] return instance
if_statement
12,577
12,715
2
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
ModelHubMixin
if isinstance(passed_config, dict): init_config.update(passed_config)
if_statement
13,310
13,391
2
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
ModelHubMixin
if init_config != {}: instance._hub_mixin_config = init_config
if_statement
13,445
13,519
2
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
ModelHubMixin
def _is_jsonable(cls, value: Any) -> bool: """Check if a value is JSON serializable.""" if isinstance(value, cls._hub_mixin_jsonable_custom_types): return True return is_jsonable(value)
function_definition
13,566
13,787
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
ModelHubMixin
if isinstance(value, cls._hub_mixin_jsonable_custom_types): return True
if_statement
13,670
13,753
2
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
ModelHubMixin
def _encode_arg(cls, arg: Any) -> Any: """Encode an argument into a JSON serializable format.""" for type_, (encoder, _) in cls._hub_mixin_coders.items(): if isinstance(arg, type_): if arg is None: return None return encoder(arg) return arg
function_definition
13,810
14,138
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
ModelHubMixin
for type_, (encoder, _) in cls._hub_mixin_coders.items(): if isinstance(arg, type_): if arg is None: return None return encoder(arg)
for_statement
13,923
14,119
2
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
ModelHubMixin
if isinstance(arg, type_): if arg is None: return None return encoder(arg)
if_statement
13,993
14,119
3
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
ModelHubMixin
if arg is None: return None
if_statement
14,036
14,083
4
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
ModelHubMixin
def _decode_arg(cls, expected_type: Type[ARGS_T], value: Any) -> Optional[ARGS_T]: """Decode a JSON serializable value into an argument.""" if is_simple_optional_type(expected_type): if value is None: return None expected_type = unwrap_simple_optional_type(expected_type) # Dataclass => handle it if is_dataclass(expected_type): return _load_dataclass(expected_type, value) # type: ignore[return-value] # Otherwise => check custom decoders for type_, (_, decoder) in cls._hub_mixin_coders.items(): if inspect.isclass(expected_type) and issubclass(expected_type, type_): return decoder(value) # Otherwise => don't decode return value
function_definition
14,161
14,938
1
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
ModelHubMixin
if is_simple_optional_type(expected_type): if value is None: return None expected_type = unwrap_simple_optional_type(expected_type)
if_statement
14,317
14,488
2
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
ModelHubMixin
if value is None: return None
if_statement
14,372
14,417
3
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
ModelHubMixin
if is_dataclass(expected_type): return _load_dataclass(expected_type, value) # type: ignore[return-value]
if_statement
14,530
14,648
2
/Users/nielsrogge/Documents/python_projecten/huggingface_hub/src/huggingface_hub/hub_mixin.py
ModelHubMixin
README.md exists but content is empty.
Downloads last month
12