Hub Python 库文档

仓库卡片

Hugging Face's logo
加入 Hugging Face 社区

并获取增强的文档体验

开始使用

仓库卡片

huggingface_hub 库提供了一个 Python 接口,用于创建、共享和更新模型/数据集卡片。访问专用文档页面,以深入了解 Hub 上的模型卡片是什么,以及它们在底层是如何工作的。您还可以查看我们的模型卡片指南,以了解如何在您自己的项目中使用这些实用程序。

Repo Card

RepoCard 对象是 ModelCardDatasetCardSpaceCard 的父类。

class huggingface_hub.RepoCard

< >

( content: str ignore_metadata_errors: bool = False )

__init__

< >

( content: str ignore_metadata_errors: bool = False )

参数

  • content (str) — Markdown 文件的内容。

从字符串内容初始化 RepoCard。内容应为 Markdown 文件,开头包含 YAML 块,主体为 Markdown。

示例

>>> from huggingface_hub.repocard import RepoCard
>>> text = '''
... ---
... language: en
... license: mit
... ---
...
... # My repo
... '''
>>> card = RepoCard(text)
>>> card.data.to_dict()
{'language': 'en', 'license': 'mit'}
>>> card.text
'\n# My repo\n'
引发以下错误
  • ValueError 当仓库卡片元数据的内容不是字典时。

from_template

< >

( card_data: CardData template_path: typing.Optional[str] = None template_str: typing.Optional[str] = None **template_kwargs ) huggingface_hub.repocard.RepoCard

参数

  • card_data (huggingface_hub.CardData) — 一个 huggingface_hub.CardData 实例,其中包含您想要包含在 Hugging Face Hub 上仓库卡片的 YAML 标头中的元数据。
  • template_path (str, optional) — 具有可选 Jinja 模板变量的 markdown 文件的路径,这些变量可以使用 template_kwargs 填充。默认为默认模板。

返回

huggingface_hub.repocard.RepoCard

具有指定卡片数据和模板内容的 RepoCard 实例。

从模板初始化 RepoCard。默认情况下,它使用默认模板。

模板是 Jinja2 模板,可以通过传递关键字参数进行自定义。

load

< >

( repo_id_or_path: typing.Union[str, pathlib.Path] repo_type: typing.Optional[str] = None token: typing.Optional[str] = None ignore_metadata_errors: bool = False ) huggingface_hub.repocard.RepoCard

参数

  • repo_id_or_path (Union[str, Path]) — 与 Hugging Face Hub 仓库或本地文件路径关联的仓库 ID。
  • repo_type (str, optional) — 要推送到的 Hugging Face 仓库的类型。默认为 None,将使用 “model”。其他选项为 “dataset” 和 “space”。从本地文件路径加载时未使用。如果从子类调用此方法,则默认值将为子类的 repo_type
  • token (str, optional) — 身份验证令牌,通过 huggingface_hub.HfApi.login 方法获得。将默认为存储的令牌。
  • ignore_metadata_errors (str) — 如果为 True,则解析元数据部分时发生的错误将被忽略。某些信息可能会在此过程中丢失。使用风险自负。

返回

huggingface_hub.repocard.RepoCard

从仓库的 README.md 文件或文件路径初始化的 RepoCard(或子类)。

从 Hugging Face Hub 仓库的 README.md 或本地文件路径初始化 RepoCard。

示例

>>> from huggingface_hub.repocard import RepoCard
>>> card = RepoCard.load("nateraw/food")
>>> assert card.data.tags == ["generated_from_trainer", "image-classification", "pytorch"]

push_to_hub

< >

( repo_id: str token: typing.Optional[str] = None repo_type: typing.Optional[str] = None commit_message: typing.Optional[str] = None commit_description: typing.Optional[str] = None revision: typing.Optional[str] = None create_pr: typing.Optional[bool] = None parent_commit: typing.Optional[str] = None ) str

参数

  • repo_id (str) — 要推送到的 Hugging Face Hub 仓库的仓库 ID。示例:“nateraw/food”。
  • token (str, optional) — 身份验证令牌,通过 huggingface_hub.HfApi.login 方法获得。将默认为存储的令牌。
  • repo_type (str, optional, 默认为 “model”) — 要推送到的 Hugging Face 仓库的类型。选项为 “model”、“dataset” 和 “space”。如果此函数由子类调用,它将默认为子类的 repo_type
  • commit_message (str, 可选) — 生成的提交的摘要 / 标题 / 首行。
  • commit_description (str, 可选) — 生成的提交的描述。
  • revision (str, 可选) — 要从中提交的 git 修订版本。默认为 "main" 分支的头部。
  • create_pr (bool, 可选) — 是否为此提交创建拉取请求(Pull Request)。默认为 False
  • parent_commit (str, 可选) — 父提交的 OID / SHA,为十六进制字符串。也支持简写(前 7 个字符)。如果指定且 create_prFalse,则当 revision 未指向 parent_commit 时,提交将失败。如果指定且 create_prTrue,则将从 parent_commit 创建拉取请求。指定 parent_commit 可确保在提交更改之前仓库未发生更改,如果仓库同时更新/提交,则此功能特别有用。

返回

str

更新了卡片元数据的提交的 URL。

将 RepoCard 推送到 Hugging Face Hub 仓库。

save

< >

( filepath: typing.Union[pathlib.Path, str] )

参数

  • filepath (Union[Path, str]) — 要保存到的 markdown 文件的文件路径。

将 RepoCard 保存到文件。

示例

>>> from huggingface_hub.repocard import RepoCard
>>> card = RepoCard("---\nlanguage: en\n---\n# This is a test repo card")
>>> card.save("/tmp/test.md")

validate

< >

( repo_type: typing.Optional[str] = None )

参数

  • repo_type (str, 可选, 默认为 “model”) — 要推送到的 Hugging Face 仓库的类型。选项包括 “model”、“dataset” 和 “space”。如果此函数是从子类调用的,则默认值将为子类的 repo_type

根据 Hugging Face Hub 的卡片验证逻辑验证卡片。使用此功能需要访问互联网,因此仅由 huggingface_hub.repocard.RepoCard.push_to_hub() 在内部调用。

引发以下错误
  • ValueError 如果卡片未通过验证检查。
  • HTTPError 如果由于任何其他原因导致 Hub API 请求失败。

卡片数据

CardData 对象是 ModelCardDataDatasetCardData 的父类。

class huggingface_hub.CardData

< >

( ignore_metadata_errors: bool = False **kwargs )

包含 RepoCard 元数据的结构。

CardDataModelCardDataDatasetCardData 的父类。

元数据可以导出为字典或 YAML。可以自定义导出以更改数据的表示形式(示例:展平评估结果)。CardData 的行为类似于字典(可以获取、弹出、设置值),但不继承自 dict 以允许此导出步骤。

get

< >

( key: str default: typing.Any = None )

获取给定元数据键的值。

pop

< >

( key: str default: typing.Any = None )

弹出给定元数据键的值。

to_dict

< >

( ) dict

返回

dict

CardData 表示为字典,可以转储到 YAML 块中,以便包含在 README.md 文件中。

将 CardData 转换为字典。

to_yaml

< >

( line_break = None original_order: typing.Optional[typing.List[str]] = None ) str

参数

  • line_break (str, 可选) — 转储为 yaml 时要使用的换行符。

返回

str

CardData 表示为 YAML 块。

将 CardData 转储到 YAML 块中,以便包含在 README.md 文件中。

模型卡片

ModelCard

class huggingface_hub.ModelCard

< >

( content: str ignore_metadata_errors: bool = False )

from_template

< >

( card_data: ModelCardData template_path: typing.Optional[str] = None template_str: typing.Optional[str] = None **template_kwargs ) huggingface_hub.ModelCard

参数

  • card_data (huggingface_hub.ModelCardData) — 一个 huggingface_hub.ModelCardData 实例,其中包含您要包含在 Hugging Face Hub 上模型卡片的 YAML 标头中的元数据。
  • template_path (str, 可选) — 具有可选 Jinja 模板变量的 markdown 文件的路径,可以使用 template_kwargs 填充这些变量。默认为默认模板。

返回

huggingface_hub.ModelCard

具有指定卡片数据和模板内容的 ModelCard 实例。

从模板初始化 ModelCard。默认情况下,它使用默认模板,可以在此处找到:https://github.com/huggingface/huggingface_hub/blob/main/src/huggingface_hub/templates/modelcard_template.md

模板是 Jinja2 模板,可以通过传递关键字参数进行自定义。

示例

>>> from huggingface_hub import ModelCard, ModelCardData, EvalResult

>>> # Using the Default Template
>>> card_data = ModelCardData(
...     language='en',
...     license='mit',
...     library_name='timm',
...     tags=['image-classification', 'resnet'],
...     datasets=['beans'],
...     metrics=['accuracy'],
... )
>>> card = ModelCard.from_template(
...     card_data,
...     model_description='This model does x + y...'
... )

>>> # Including Evaluation Results
>>> card_data = ModelCardData(
...     language='en',
...     tags=['image-classification', 'resnet'],
...     eval_results=[
...         EvalResult(
...             task_type='image-classification',
...             dataset_type='beans',
...             dataset_name='Beans',
...             metric_type='accuracy',
...             metric_value=0.9,
...         ),
...     ],
...     model_name='my-cool-model',
... )
>>> card = ModelCard.from_template(card_data)

>>> # Using a Custom Template
>>> card_data = ModelCardData(
...     language='en',
...     tags=['image-classification', 'resnet']
... )
>>> card = ModelCard.from_template(
...     card_data=card_data,
...     template_path='./src/huggingface_hub/templates/modelcard_template.md',
...     custom_template_var='custom value',  # will be replaced in template if it exists
... )

ModelCardData

class huggingface_hub.ModelCardData

< >

( base_model: typing.Union[typing.List[str], str, NoneType] = None datasets: typing.Union[typing.List[str], str, NoneType] = None eval_results: typing.Optional[typing.List[huggingface_hub.repocard_data.EvalResult]] = None language: typing.Union[typing.List[str], str, NoneType] = None library_name: typing.Optional[str] = None license: typing.Optional[str] = None license_name: typing.Optional[str] = None license_link: typing.Optional[str] = None metrics: typing.Optional[typing.List[str]] = None model_name: typing.Optional[str] = None pipeline_tag: typing.Optional[str] = None tags: typing.Optional[typing.List[str]] = None ignore_metadata_errors: bool = False **kwargs )

参数

  • base_model (strList[str], 可选) — 模型所派生的基础模型的标识符。例如,如果您的模型是现有模型的微调或适配器,则适用。该值必须是 Hub 上的模型 ID(如果您的模型派生自多个模型,则为 ID 列表)。默认为 None。
  • datasets (Union[str, List[str]], 可选) — 用于训练此模型的数据集或数据集列表。应为在 https://huggingface.co/datasets 上找到的数据集 ID。默认为 None。
  • eval_results (Union[List[EvalResult], EvalResult], 可选) — 定义模型评估结果的 huggingface_hub.EvalResult 列表。如果提供,model_name 将用作 PapersWithCode 排行榜上的名称。默认为 None
  • language (Union[str, List[str]], 可选) — 模型训练数据或元数据的语言。它必须是 ISO 639-1、639-2 或 639-3 代码(两个/三个字母),或像 “code”、“multilingual” 这样的特殊值。默认为 None
  • library_name (str, 可选) — 此模型使用的库的名称。示例:keras 或来自 https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/src/model-libraries.ts 的任何库。默认为 None。
  • license (str, 可选) — 此模型的许可证。示例:apache-2.0 或来自 https://huggingface.co/docs/hub/repositories-licenses 的任何许可证。默认为 None。
  • license_name (str, 可选) — 此许可证的名称。默认为 None。与 license_link 结合使用。常见许可证(Apache-2.0、MIT、CC-BY-SA-4.0)不需要名称。在这种情况下,请改用 license
  • license_link (str, 可选) — 此模型许可证的链接。默认为 None。与 license_name 结合使用。常见许可证(Apache-2.0、MIT、CC-BY-SA-4.0)不需要链接。在这种情况下,请改用 license
  • metrics (List[str], 可选) — 用于评估此模型的指标列表。应为可在 https://huggingface.co/metrics 找到的指标名称。示例:“accuracy”。默认为 None。
  • model_name (str, 可选) — 此模型的名称。它与 eval_results 一起用于构建卡片元数据中的 model-index。您在此处提供的名称将用于 PapersWithCode 排行榜。如果未提供,则仓库名称将用作默认名称。默认为 None。
  • pipeline_tag (str, 可选) — 与模型关联的 pipeline 标签。示例:“text-classification”。
  • tags (List[str], 可选) — 要添加到模型的标签列表,这些标签可在 Hugging Face Hub 上进行筛选时使用。默认为 None。
  • ignore_metadata_errors (str) — 如果为 True,则在解析元数据部分时将忽略错误。在此过程中可能会丢失一些信息。使用风险自负。
  • kwargs (dict, 可选) — 将添加到模型卡的附加元数据。默认为 None。

模型卡元数据,当包含在您的 README.md 顶部时,会被 Hugging Face Hub 使用。

示例

>>> 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']}

数据集卡片

数据集卡片在 ML 社区中也称为数据卡片。

DatasetCard

class huggingface_hub.DatasetCard

< >

( content: str ignore_metadata_errors: bool = False )

from_template

< >

( card_data: DatasetCardData template_path: typing.Optional[str] = None template_str: typing.Optional[str] = None **template_kwargs ) huggingface_hub.DatasetCard

参数

  • card_data (huggingface_hub.DatasetCardData) — 一个 huggingface_hub.DatasetCardData 实例,其中包含您想要包含在 Hugging Face Hub 上数据集卡片的 YAML 标头中的元数据。
  • template_path (str, 可选) — 具有可选 Jinja 模板变量的 markdown 文件的路径,可以使用 template_kwargs 填充这些变量。默认为默认模板。

返回

huggingface_hub.DatasetCard

具有指定卡片数据和来自模板内容的 DatasetCard 实例。

从模板初始化 DatasetCard。默认情况下,它使用默认模板,该模板可以在这里找到: https://github.com/huggingface/huggingface_hub/blob/main/src/huggingface_hub/templates/datasetcard_template.md

模板是 Jinja2 模板,可以通过传递关键字参数进行自定义。

示例

>>> from huggingface_hub import DatasetCard, DatasetCardData

>>> # Using the Default Template
>>> card_data = DatasetCardData(
...     language='en',
...     license='mit',
...     annotations_creators='crowdsourced',
...     task_categories=['text-classification'],
...     task_ids=['sentiment-classification', 'text-scoring'],
...     multilinguality='monolingual',
...     pretty_name='My Text Classification Dataset',
... )
>>> card = DatasetCard.from_template(
...     card_data,
...     pretty_name=card_data.pretty_name,
... )

>>> # Using a Custom Template
>>> card_data = DatasetCardData(
...     language='en',
...     license='mit',
... )
>>> card = DatasetCard.from_template(
...     card_data=card_data,
...     template_path='./src/huggingface_hub/templates/datasetcard_template.md',
...     custom_template_var='custom value',  # will be replaced in template if it exists
... )

DatasetCardData

class huggingface_hub.DatasetCardData

< >

( language: typing.Union[typing.List[str], str, NoneType] = None license: typing.Union[typing.List[str], str, NoneType] = None annotations_creators: typing.Union[typing.List[str], str, NoneType] = None language_creators: typing.Union[typing.List[str], str, NoneType] = None multilinguality: typing.Union[typing.List[str], str, NoneType] = None size_categories: typing.Union[typing.List[str], str, NoneType] = None source_datasets: typing.Optional[typing.List[str]] = None task_categories: typing.Union[typing.List[str], str, NoneType] = None task_ids: typing.Union[typing.List[str], str, NoneType] = None paperswithcode_id: typing.Optional[str] = None pretty_name: typing.Optional[str] = None train_eval_index: typing.Optional[typing.Dict] = None config_names: typing.Union[typing.List[str], str, NoneType] = None ignore_metadata_errors: bool = False **kwargs )

参数

  • language (List[str], 可选) — 数据集的数据或元数据的语言。它必须是 ISO 639-1、639-2 或 639-3 代码(两个/三个字母),或像 “code”、“multilingual” 这样的特殊值。
  • license (Union[str, List[str]], 可选) — 此数据集的许可证。示例:apache-2.0 或来自 https://huggingface.co/docs/hub/repositories-licenses 的任何许可证。
  • annotations_creators (Union[str, List[str]], 可选) — 数据集的标注是如何创建的。选项包括:‘found’、‘crowdsourced’、‘expert-generated’、‘machine-generated’、‘no-annotation’、‘other’。
  • language_creators (Union[str, List[str]], 可选) — 数据集中基于文本的数据是如何创建的。选项包括:‘found’、‘crowdsourced’、‘expert-generated’、‘machine-generated’、‘other’
  • multilinguality (Union[str, List[str]], 可选) — 数据集是否为多语言。选项包括:‘monolingual’、‘multilingual’、‘translation’、‘other’。
  • size_categories (Union[str, List[str]], 可选) — 数据集中示例的数量。选项包括:‘n<1K’、‘1K1T’和 ‘other’。
  • source_datasets (List[str]], 可选) — 指示数据集是原始数据集还是从另一个现有数据集扩展而来。选项包括:‘original’ 和 ‘extended’。
  • task_categories (Union[str, List[str]], 可选) — 数据集支持的任务类别是什么?
  • task_ids (Union[str, List[str]], 可选) — 数据集支持的具体任务是什么?
  • paperswithcode_id (str, 可选) — PapersWithCode 上数据集的 ID。
  • pretty_name (str, 可选) — 数据集更易读的名称。(例如,“猫 vs. 狗”)
  • train_eval_index (Dict, 可选) — 一个字典,描述了在 Hub 上进行评估的必要规范。如果未提供,将从 kwargs 的 ‘train-eval-index’ 键中收集。
  • config_names (Union[str, List[str]], 可选) — 数据集可用的数据集配置列表。

Dataset Card 元数据,当包含在您的 README.md 顶部时,Hugging Face Hub 会使用它

Space Cards

SpaceCard

class huggingface_hub.SpaceCard

< >

( content: str ignore_metadata_errors: bool = False )

SpaceCardData

class huggingface_hub.SpaceCardData

< >

( title: typing.Optional[str] = None sdk: typing.Optional[str] = None sdk_version: typing.Optional[str] = None python_version: typing.Optional[str] = None app_file: typing.Optional[str] = None app_port: typing.Optional[int] = None license: typing.Optional[str] = None duplicated_from: typing.Optional[str] = None models: typing.Optional[typing.List[str]] = None datasets: typing.Optional[typing.List[str]] = None tags: typing.Optional[typing.List[str]] = None ignore_metadata_errors: bool = False **kwargs )

参数

  • title (str, 可选) — Space 的标题。
  • sdk (str, 可选) — Space 的 SDK(为 gradiostreamlitdockerstatic 之一)。
  • sdk_version (str, 可选) — 使用的 SDK 的版本(如果为 Gradio/Streamlit sdk)。
  • python_version (str, 可选) — Space 中使用的 Python 版本(如果为 Gradio/Streamlit sdk)。
  • app_file (str, 可选) — 您的主应用程序文件的路径(其中包含 gradio 或 streamlit Python 代码,或静态 html 代码)。路径是相对于仓库的根目录。
  • app_port (str, 可选) — 您的应用程序正在运行的端口。仅当 sdk 为 docker 时使用。
  • license (str, 可选) — 此模型的许可证。示例:apache-2.0 或 https://huggingface.co/docs/hub/repositories-licenses 中的任何许可证。
  • duplicated_from (str, 可选) — 如果这是一个复制的 Space,则为原始 Space 的 ID。
  • models (Liststr, 可选) — 与此 Space 相关的模型列表。应为在 https://huggingface.co/models 上找到的数据集 ID。
  • datasets (List[str], 可选) — 与此 Space 相关的数据集列表。应为在 https://huggingface.co/datasets 上找到的数据集 ID。
  • tags (List[str], 可选) — 要添加到您的 Space 的标签列表,这些标签可在 Hub 上进行筛选时使用。
  • ignore_metadata_errors (str) — 如果为 True,则解析元数据部分时出现的错误将被忽略。在此过程中可能会丢失一些信息。请自行承担使用风险。
  • kwargs (dict, 可选) — 将添加到 space card 的其他元数据。

Space Card 元数据,当包含在您的 README.md 顶部时,Hugging Face Hub 会使用它

要获取 Spaces 配置的详尽参考,请访问 https://huggingface.co/docs/hub/spaces-config-reference#spaces-configuration-reference

示例

>>> 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'}

实用工具

EvalResult

class huggingface_hub.EvalResult

< >

( task_type: str dataset_type: str dataset_name: str metric_type: str metric_value: typing.Any task_name: typing.Optional[str] = None dataset_config: typing.Optional[str] = None dataset_split: typing.Optional[str] = None dataset_revision: typing.Optional[str] = None dataset_args: typing.Optional[typing.Dict[str, typing.Any]] = None metric_name: typing.Optional[str] = None metric_config: typing.Optional[str] = None metric_args: typing.Optional[typing.Dict[str, typing.Any]] = None verified: typing.Optional[bool] = None verify_token: typing.Optional[str] = None source_name: typing.Optional[str] = None source_url: typing.Optional[str] = None )

参数

  • task_type (str) — 任务标识符。 例如:“image-classification”。
  • dataset_type (str) — 数据集标识符。 例如:“common_voice”。 使用来自 https://huggingface.co/datasets 的数据集 ID。
  • dataset_name (str) — 数据集的易读名称。 例如:“Common Voice (French)”。
  • metric_type (str) — 指标标识符。 例如:“wer”。 使用来自 https://huggingface.co/metrics 的指标 ID。
  • metric_value (Any) — 指标值。 例如:0.9 或 “20.0 ± 1.2”。
  • task_name (str, optional) — 任务的易读名称。 例如:“语音识别”。
  • dataset_config (str, optional) — 在 load_dataset() 中使用的数据集配置的名称。 例如:在 load_dataset("common_voice", "fr") 中的 fr。 有关更多信息,请参阅 datasets 文档: https://huggingface.co/docs/datasets/package_reference/loading_methods#datasets.load_dataset.name
  • dataset_split (str, optional) — 在 load_dataset() 中使用的拆分。 例如:“test”。
  • dataset_revision (str, optional) — 在 load_dataset() 中使用的数据集修订版本(又名 Git Sha)。 例如:5503434ddd753f426f4b38109466949a1217c2bb
  • dataset_args (Dict[str, Any], optional) — 在 Metric.compute() 期间传递的参数。 bleu 的示例:{"max_order": 4}
  • metric_name (str, optional) — 指标的易读名称。 例如:“Test WER”。
  • metric_config (str, optional) — 在 load_metric() 中使用的指标配置的名称。 例如:在 load_metric("bleurt", "bleurt-large-512") 中的 bleurt-large-512。 有关更多信息,请参阅 datasets 文档: https://huggingface.co/docs/datasets/v2.1.0/en/loading#load-configurations
  • metric_args (Dict[str, Any], optional) — 在 Metric.compute() 期间传递的参数。 bleu 的示例:max_order: 4
  • verified (bool, optional) — 指示指标是否来自 Hugging Face 的 评估服务。 由 Hugging Face 自动计算,请勿设置。
  • verify_token (str, optional) — 用于验证指标是否来自 Hugging Face 的 评估服务 的 JSON Web 令牌。
  • source_name (str, optional) — 评估结果来源的名称。 例如:“Open LLM Leaderboard”。
  • source_url (str, optional) — 评估结果来源的 URL。 例如:”https://huggingface.co/spaces/open-llm-leaderboard/open_llm_leaderboard”

模型卡的 model-index 中找到的各个评估结果的扁平化表示形式。

有关 model-index 规范的更多信息,请参阅 https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1

is_equal_except_value

< >

( other: EvalResult )

如果 selfother 描述的是完全相同的指标,但值不同,则返回 True。

model_index_to_eval_results

huggingface_hub.repocard_data.model_index_to_eval_results

< >

( model_index: typing.List[typing.Dict[str, typing.Any]] ) model_name (str)

参数

  • model_index (List[Dict[str, Any]]) — 模型索引数据结构,可能来自 Hugging Face Hub 上的 README.md 文件。

返回

model_name (str)

模型名称,如模型索引中所找到。 这用作 PapersWithCode 等排行榜上模型的标识符。 eval_results (List[EvalResult]): 包含在提供的 model_index 中报告的指标的 huggingface_hub.EvalResult 对象列表。

接收模型索引并返回模型名称和 huggingface_hub.EvalResult 对象列表。

模型索引的详细规范可以在这里找到: https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1

示例

>>> 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_to_model_index

huggingface_hub.repocard_data.eval_results_to_model_index

< >

( model_name: str eval_results: typing.List[huggingface_hub.repocard_data.EvalResult] ) model_index (List[Dict[str, Any]])

参数

  • model_name (str) — 模型名称(例如,“my-cool-model”)。这用作模型在 PapersWithCode 等排行榜上的标识符。
  • eval_results (List[EvalResult]) — 包含要在模型索引中报告的指标的 huggingface_hub.EvalResult 对象列表。

返回

model_index (List[Dict[str, Any]])

转换为模型索引的 eval_results。

接收给定的模型名称和 huggingface_hub.EvalResult 列表,并返回一个有效的模型索引,该索引将与 Hugging Face Hub 期望的格式兼容。

示例

>>> 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}]}]}]

metadata_eval_result

huggingface_hub.metadata_eval_result

< >

( model_pretty_name: str task_pretty_name: str task_id: str metrics_pretty_name: str metrics_id: str metrics_value: typing.Any dataset_pretty_name: str dataset_id: str metrics_config: typing.Optional[str] = None metrics_verified: bool = False dataset_config: typing.Optional[str] = None dataset_split: typing.Optional[str] = None dataset_revision: typing.Optional[str] = None metrics_verification_token: typing.Optional[str] = None ) dict

参数

  • model_pretty_name (str) — 模型在自然语言中的名称。
  • task_pretty_name (str) — 任务在自然语言中的名称。
  • task_id (str) — 示例:automatic-speech-recognition。任务 ID。
  • metrics_pretty_name (str) — 指标在自然语言中的名称。示例:Test WER。
  • metrics_id (str) — 示例:wer。来自 https://huggingface.co/metrics 的指标 ID。
  • metrics_value (Any) — 来自指标的值。示例:20.0 或 “20.0 ± 1.2”。
  • dataset_pretty_name (str) — 数据集在自然语言中的名称。
  • dataset_id (str) — 示例:common_voice。来自 https://huggingface.co/datasets 的数据集 ID。
  • metrics_config (str, optional) — 在 load_metric() 中使用的指标配置的名称。示例:load_metric("bleurt", "bleurt-large-512") 中的 bleurt-large-512。
  • metrics_verified (bool, optional, defaults to False) — 指示指标是否来自 Hugging Face 的 评估服务。由 Hugging Face 自动计算,请勿设置。
  • dataset_config (str, optional) — 示例:fr。在 load_dataset() 中使用的数据集配置的名称。
  • dataset_split (str, optional) — 示例:test。在 load_dataset() 中使用的数据集拆分的名称。
  • dataset_revision (str, optional) — 示例:5503434ddd753f426f4b38109466949a1217c2bb。在 load_dataset() 中使用的数据集修订版本的名称。
  • metrics_verification_token (bool, optional) — 用于验证指标是否来自 Hugging Face 的 评估服务 的 JSON Web 令牌。

返回

dict

包含在数据集上评估的模型结果的元数据字典。

创建一个包含在数据集上评估的模型结果的元数据字典。

示例

>>> from huggingface_hub import metadata_eval_result
>>> results = metadata_eval_result(
...         model_pretty_name="RoBERTa fine-tuned on ReactionGIF",
...         task_pretty_name="Text Classification",
...         task_id="text-classification",
...         metrics_pretty_name="Accuracy",
...         metrics_id="accuracy",
...         metrics_value=0.2662102282047272,
...         dataset_pretty_name="ReactionJPEG",
...         dataset_id="julien-c/reactionjpeg",
...         dataset_config="default",
...         dataset_split="test",
... )
>>> results == {
...     'model-index': [
...         {
...             'name': 'RoBERTa fine-tuned on ReactionGIF',
...             'results': [
...                 {
...                     'task': {
...                         'type': 'text-classification',
...                         'name': 'Text Classification'
...                     },
...                     'dataset': {
...                         'name': 'ReactionJPEG',
...                         'type': 'julien-c/reactionjpeg',
...                         'config': 'default',
...                         'split': 'test'
...                     },
...                     'metrics': [
...                         {
...                             'type': 'accuracy',
...                             'value': 0.2662102282047272,
...                             'name': 'Accuracy',
...                             'verified': False
...                         }
...                     ]
...                 }
...             ]
...         }
...     ]
... }
True

metadata_update

huggingface_hub.metadata_update

< >

( repo_id: str metadata: typing.Dict repo_type: typing.Optional[str] = None overwrite: bool = False token: typing.Optional[str] = None commit_message: typing.Optional[str] = None commit_description: typing.Optional[str] = None revision: typing.Optional[str] = None create_pr: bool = False parent_commit: typing.Optional[str] = None ) str

参数

  • repo_id (str) — 仓库的名称。
  • metadata (dict) — 包含要更新的元数据的字典。
  • repo_type (str, optional) — 如果更新到数据集或 Space,则设置为 "dataset""space";如果更新到模型,则设置为 None"model"。默认为 None
  • overwrite (bool, optional, defaults to False) — 如果设置为 True,则可以覆盖现有字段;否则,尝试覆盖现有字段将导致错误。
  • token (str, optional) — Hugging Face 身份验证令牌。
  • commit_message (str, optional) — 生成的提交的摘要/标题/第一行。默认为 f"使用 huggingface_hub 更新元数据"
  • commit_description (str optional) — 生成的提交的描述
  • revision (str, 可选) — 从中提交的 git 修订版本。默认为 "main" 分支的头部。
  • create_pr (boolean, 可选) — 是否从此提交的 revision 创建拉取请求。默认为 False
  • parent_commit (str, 可选) — 父提交的 OID / SHA,以十六进制字符串表示。也支持简写形式(前 7 个字符)。如果指定且 create_prFalse,则当 revision 未指向 parent_commit 时,提交将失败。如果指定且 create_prTrue,则将从 parent_commit 创建拉取请求。指定 parent_commit 可确保在提交更改之前仓库未发生更改,并且当仓库同时更新/提交时,此功能尤其有用。

返回

str

更新了卡片元数据的提交的 URL。

更新 Hugging Face Hub 上仓库的 README.md 文件中的元数据。如果 README.md 文件尚不存在,则将创建一个新的文件,其中包含元数据以及默认的 ModelCard 或 DatasetCard 模板。对于 space 仓库,由于 Space 在没有 README.md 文件的情况下无法存在,因此会抛出错误。

示例

>>> from huggingface_hub import metadata_update
>>> metadata = {'model-index': [{'name': 'RoBERTa fine-tuned on ReactionGIF',
...             'results': [{'dataset': {'name': 'ReactionGIF',
...                                      'type': 'julien-c/reactiongif'},
...                           'metrics': [{'name': 'Recall',
...                                        'type': 'recall',
...                                        'value': 0.7762102282047272}],
...                          'task': {'name': 'Text Classification',
...                                   'type': 'text-classification'}}]}]}
>>> url = metadata_update("hf-internal-testing/reactiongif-roberta-card", metadata)
< > 在 GitHub 上更新