# 仓库卡片

huggingface_hub 库提供了一个 Python 接口，用于创建、共享和更新模型/数据集卡片。请访问[专用文档页面](https://huggingface.co/docs/hub/models-cards)，深入了解 Hub 上的模型卡片是什么以及其底层工作原理。您还可以查看我们的[模型卡片指南](../how-to-model-cards)，了解如何在自己的项目中使用这些实用工具。

## 仓库卡片[[huggingface_hub.RepoCard]]

`RepoCard` 对象是 [ModelCard](/docs/huggingface_hub/v2.4.0/zh/package_reference/cards#huggingface_hub.ModelCard)、[DatasetCard](/docs/huggingface_hub/v2.4.0/zh/package_reference/cards#huggingface_hub.DatasetCard) 和 `SpaceCard` 的父类。

#### huggingface_hub.RepoCard[[huggingface_hub.RepoCard]]

```python
huggingface_hub.RepoCard(content: str, ignore_metadata_errors: bool = False)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/repocard.py#L37)

#### __init__[[huggingface_hub.RepoCard.__init__]]

```python
__init__(content: str, ignore_metadata_errors: bool = False)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/repocard.py#L42)

**参数：**

content (`str`) : Markdown 文件的内容。

从字符串内容初始化一个 RepoCard。内容应为一个 Markdown 文件，开头包含一个 YAML 块，后接 Markdown 正文。

示例：
```python
>>> 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'

```

> [!TIP]
> 引发以下错误：
>
> - 当仓库卡片元数据的内容不是字典时，抛出 [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)。

#### from_template[[huggingface_hub.RepoCard.from_template]]

```python
from_template(card_data: CardData, template_path: str | None = None, template_str: str | None = None, **template_kwargs)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/repocard.py#L289)

**参数：**

card_data (`huggingface_hub.CardData`)：一个 huggingface_hub.CardData 实例，包含您希望添加到 Hugging Face Hub 上仓库卡片 YAML 头部的元数据。

template_path (`str`, *可选*) : 指向 Markdown 文件的路径，该文件可包含可选的 Jinja 模板变量，这些变量可通过 `template_kwargs` 进行填充。默认使用默认模板。

template_str (`str`, *可选*) : 一个带有可选变量的原始 Jinja 模板字符串。当 `template_path` 和默认模板都不适用时使用。如果同时提供了 `template_path`，则此参数会被忽略。

**返回：** [huggingface_hub.repocard.RepoCard](/docs/huggingface_hub/v2.4.0/zh/package_reference/cards#huggingface_hub.RepoCard)

一个包含指定卡片数据和模板内容的 RepoCard 实例。

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

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

#### load[[huggingface_hub.RepoCard.load]]

```python
load(repo_id_or_path: str | pathlib.Path, repo_type: str | None = None, token: str | None = None, ignore_metadata_errors: bool = False)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/repocard.py#L135)

**参数：**

repo_id_or_path (`Union[str, Path]`) : 与 Hugging Face Hub 仓库关联的仓库 ID 或本地文件路径。

repo_type (`str`, *可选*) : 要推送到的 Hugging Face 仓库的类型。默认为 None，此时将使用 "model"。其他选项包括 "dataset" 和 "space"。从本地文件路径加载时不使用此参数。如果从子类调用，默认值将是该子类的 `repo_type`。

token (`str`, *可选*) : 身份验证令牌，通过 `huggingface_hub.HfApi.login` 方法获取。默认使用已存储的令牌。

ignore_metadata_errors (`str`) : 如果为 True，解析元数据部分时出现的错误将被忽略。在此过程中可能会丢失一些信息。请谨慎使用。

**返回：** [huggingface_hub.repocard.RepoCard](/docs/huggingface_hub/v2.4.0/zh/package_reference/cards#huggingface_hub.RepoCard)

从仓库的 README.md 文件或文件路径初始化的 RepoCard（或其子类）。

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

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

```

#### push_to_hub[[huggingface_hub.RepoCard.push_to_hub]]

```python
push_to_hub(repo_id: str, token: str | None = None, repo_type: str | None = None, commit_message: str | None = None, commit_description: str | None = None, revision: str | None = None, create_pr: bool | None = None, parent_commit: str | None = None)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/repocard.py#L226)

**参数：**

repo_id (`str`) : 要推送到的 Hugging Face Hub 仓库的仓库 ID。示例："nateraw/food"。

token (`str`, *可选*) : 身份验证令牌，通过 `huggingface_hub.HfApi.login` 方法获取。默认使用已存储的令牌。

repo_type (`str`，*可选*，默认为 "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_pr` 为 `False`，当 `revision` 不指向 `parent_commit` 时，提交将失败。如果指定了该参数且 `create_pr` 为 `True`，拉取请求将从 `parent_commit` 创建。指定 `parent_commit` 可确保在提交更改之前仓库未发生变化，这在仓库被并发更新 / 提交时尤其有用。

**返回：** `str`

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

将 RepoCard 推送到 Hugging Face Hub 仓库。

#### 保存[[huggingface_hub.RepoCard.save]]

```python
save(filepath: pathlib.Path | str)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/repocard.py#L115)

**参数：**

filepath (`Union[Path, str]`) : 要保存的 Markdown 文件的路径。

将 RepoCard 保存到文件。

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

```

#### validate[[huggingface_hub.RepoCard.validate]]

```python
validate(repo_type: str | None = None)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/repocard.py#L189)

**参数：**

repo_type (`str`，*可选*，默认为 "model")：要推送到的 Hugging Face 仓库类型。可选值为 "model"、"dataset" 和 "space"。如果此函数从子类中调用，默认值将为该子类的 `repo_type`。

根据 Hugging Face Hub 的卡片验证逻辑验证卡片。使用此函数需要访问互联网，因此它仅由 [huggingface_hub.repocard.RepoCard.push_to_hub()](/docs/huggingface_hub/v2.4.0/zh/package_reference/cards#huggingface_hub.RepoCard.push_to_hub) 内部调用。

> [!TIP]
> 引发以下错误：
>
> - 如果卡片未通过验证检查，则抛出 [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)。 - 如果向 Hub API 的请求因其他任何原因失败，则抛出 [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)。

## 卡片数据[[huggingface_hub.CardData]]

[CardData](/docs/huggingface_hub/v2.4.0/zh/package_reference/cards#huggingface_hub.CardData) 对象是 [ModelCardData](/docs/huggingface_hub/v2.4.0/zh/package_reference/cards#huggingface_hub.ModelCardData) 和 [DatasetCardData](/docs/huggingface_hub/v2.4.0/zh/package_reference/cards#huggingface_hub.DatasetCardData) 的父类。

#### huggingface_hub.CardData[[huggingface_hub.CardData]]

```python
huggingface_hub.CardData(ignore_metadata_errors: bool = False, **kwargs)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/repocard_data.py#L165)

包含来自 RepoCard 的元数据的结构。

[CardData](/docs/huggingface_hub/v2.4.0/zh/package_reference/cards#huggingface_hub.CardData) 是 [ModelCardData](/docs/huggingface_hub/v2.4.0/zh/package_reference/cards#huggingface_hub.ModelCardData) 和 [DatasetCardData](/docs/huggingface_hub/v2.4.0/zh/package_reference/cards#huggingface_hub.DatasetCardData) 的父类。

元数据可以导出为字典或 YAML 格式。可以自定义导出过程以更改数据的表示方式（例如：展平评估结果）。`CardData` 的行为类似于字典（可以获取、弹出和设置值），但它不继承自 `dict`，以便允许此导出步骤。

#### get[[huggingface_hub.CardData.get]]

```python
get(key: str, default: typing.Any = None)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/repocard_data.py#L228)

获取给定元数据键的值。

#### pop[[huggingface_hub.CardData.pop]]

```python
pop(key: str, default: typing.Any = None)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/repocard_data.py#L233)

获取给定元数据键的值。

#### to_dict[[huggingface_hub.CardData.to_dict]]

```python
to_dict()
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/repocard_data.py#L178)

**返回：** `dict`

以字典形式表示的 CardData，可直接转储为 YAML 代码块，以便包含在 README.md 文件中。

将 CardData 转换为字典。

#### to_yaml[[huggingface_hub.CardData.to_yaml]]

```python
to_yaml(line_break = None, original_order: list[str] | None = None)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/repocard_data.py#L198)

**参数：**

line_break (str, *可选*) : 转储到 yaml 时使用的换行符。

original_order (`list[str]`, *可选*) : 如果提供，则在转储前重新排序元数据字段以匹配此列表。`original_order` 中未包含的任何键都会追加在列出的键之后，并保持其现有的相对顺序。适用于在不打乱键顺序的情况下往返处理 YAML 块。

**返回：** `str`

以 YAML 块表示的 CardData。

将 CardData 转储为 YAML 代码块，以便包含在 README.md 文件中。

## 模型卡片

### ModelCard[[huggingface_hub.ModelCard]]

#### huggingface_hub.ModelCard[[huggingface_hub.ModelCard]]

```python
huggingface_hub.ModelCard(content: str, ignore_metadata_errors: bool = False)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/repocard.py#L336)

#### from_template[[huggingface_hub.ModelCard.from_template]]

```python
from_template(card_data: ModelCardData, template_path: str | None = None, template_str: str | None = None, **template_kwargs)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/repocard.py#L341)

**参数：**

card_data (`huggingface_hub.ModelCardData`)：一个 huggingface_hub.ModelCardData 实例，包含您希望添加到 Hugging Face Hub 上模型卡片 YAML 头部的元数据。

template_path (`str`, *可选*) : 指向 Markdown 文件的路径，该文件可包含可选的 Jinja 模板变量，这些变量可通过 `template_kwargs` 进行填充。默认使用默认模板。

template_str (`str`, *可选*) : 一个带有可选变量的原始 Jinja 模板字符串。当 `template_path` 和默认模板都不适用时使用。如果同时提供了 `template_path`，则此参数会被忽略。

**返回：** [huggingface_hub.ModelCard](/docs/huggingface_hub/v2.4.0/zh/package_reference/cards#huggingface_hub.ModelCard)

一个 ModelCard 实例，包含指定的卡片数据和来自模板的内容。

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

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

示例：
```python
>>> 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[[huggingface_hub.ModelCardData]]

#### huggingface_hub.ModelCardData[[huggingface_hub.ModelCardData]]

```python
huggingface_hub.ModelCardData(base_model: str | list[str] | None = None, datasets: str | list[str] | None = None, eval_results: list[huggingface_hub.repocard_data.EvalResult] | None = None, language: str | list[str] | None = None, library_name: str | None = None, license: str | None = None, license_name: str | None = None, license_link: str | None = None, metrics: list[str] | None = None, model_name: str | None = None, pipeline_tag: str | None = None, tags: list[str] | None = None, ignore_metadata_errors: bool = False, **kwargs)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/repocard_data.py#L271)

**参数：**

base_model (`str` 或 `list[str]`，*可选*) : 模型所派生的基础模型的标识符。例如，如果您的模型是现有模型的微调版本或适配器，则适用此参数。该值必须是 Hub 上模型的 ID（如果您的模型派生自多个模型，则可以是 ID 列表）。默认为 None。

datasets (`Union[str, list[str]]`，*可选*)：用于训练此模型的数据集或数据集列表。应为在 https://hf.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`, *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]`, *可选*) : 用于评估此模型的指标列表。应为可在 https://hf.co/metrics 中找到的指标名称。示例：'accuracy'。默认为 None。

model_name (`str`, *可选*) : 此模型的名称。它与 `eval_results` 一起用于在卡片的元数据中构建 `model-index`。您在此处提供的名称将用于 PapersWithCode 的排行榜。如果提供 None，则默认使用仓库名称。默认为 None。

pipeline_tag (`str`, *可选*) : 与模型关联的流水线标签。示例："text-classification"。

tags (`list[str]`, *可选*) : 要添加到模型中的标签列表，可用于在 Hugging Face Hub 上进行筛选。默认为 None。

ignore_metadata_errors (`str`) : 如果为 True，解析元数据部分时出现的错误将被忽略。在此过程中可能会丢失一些信息。请谨慎使用。

kwargs (`dict`, *可选*) : 将添加到模型卡中的附加元数据。默认为 None。

在 README.md 文件顶部包含时，Hugging Face Hub 使用的模型卡元数据

示例：
```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']}

```

## 数据集卡片

数据集卡片在机器学习社区中也被称为数据卡片。

### DatasetCard[[huggingface_hub.DatasetCard]]

#### huggingface_hub.DatasetCard[[huggingface_hub.DatasetCard]]

```python
huggingface_hub.DatasetCard(content: str, ignore_metadata_errors: bool = False)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/repocard.py#L420)

#### from_template[[huggingface_hub.DatasetCard.from_template]]

```python
from_template(card_data: DatasetCardData, template_path: str | None = None, template_str: str | None = None, **template_kwargs)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/repocard.py#L425)

**参数：**

card_data (`huggingface_hub.DatasetCardData`)：一个 huggingface_hub.DatasetCardData 实例，包含您希望添加到 Hugging Face Hub 上数据集卡片 YAML 头部的元数据。

template_path (`str`, *可选*) : 指向 Markdown 文件的路径，该文件可包含可选的 Jinja 模板变量，这些变量可通过 `template_kwargs` 进行填充。默认使用默认模板。

template_str (`str`, *可选*) : 一个带有可选变量的原始 Jinja 模板字符串。当 `template_path` 和默认模板都不适用时使用。如果同时提供了 `template_path`，则此参数会被忽略。

**返回：** [huggingface_hub.DatasetCard](/docs/huggingface_hub/v2.4.0/zh/package_reference/cards#huggingface_hub.DatasetCard)

一个 DatasetCard 实例，包含指定的卡片数据和来自模板的内容。

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

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

示例：
```python
>>> 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[[huggingface_hub.DatasetCardData]]

#### huggingface_hub.DatasetCardData[[huggingface_hub.DatasetCardData]]

```python
huggingface_hub.DatasetCardData(language: str | list[str] | None = None, license: str | list[str] | None = None, annotations_creators: str | list[str] | None = None, language_creators: str | list[str] | None = None, multilinguality: str | list[str] | None = None, size_categories: str | list[str] | None = None, source_datasets: list[str] | None = None, task_categories: str | list[str] | None = None, task_ids: str | list[str] | None = None, paperswithcode_id: str | None = None, pretty_name: str | None = None, train_eval_index: dict | None = None, config_names: str | list[str] | None = None, ignore_metadata_errors: bool = False, **kwargs)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/repocard_data.py#L400)

**参数：**

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`, *可选*) : 数据集更易于人类阅读的名称。（例如 "Cats vs. Dogs"）

train_eval_index (`dict`, *可选*) : 一个字典，用于描述在 Hub 上执行评估所需的规范。如果未提供，将从 kwargs 的 'train-eval-index' 键中获取。

config_names (`Union[str, list[str]]`，*可选*)：该数据集可用的数据集配置列表。

在 README.md 文件顶部包含时，Hugging Face Hub 使用的数据集卡片元数据

## 空间卡片

### SpaceCard[[huggingface_hub.SpaceCard]]

#### huggingface_hub.SpaceCard[[huggingface_hub.SpaceCard]]

```python
huggingface_hub.SpaceCard(content: str, ignore_metadata_errors: bool = False)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/repocard.py#L488)

### SpaceCardData[[huggingface_hub.SpaceCardData]]

#### huggingface_hub.SpaceCardData[[huggingface_hub.SpaceCardData]]

```python
huggingface_hub.SpaceCardData(title: str | None = None, sdk: str | None = None, sdk_version: str | None = None, python_version: str | None = None, app_file: str | None = None, app_port: int | None = None, license: str | None = None, duplicated_from: str | None = None, models: list[str] | None = None, datasets: list[str] | None = None, tags: list[str] | None = None, ignore_metadata_errors: bool = False, **kwargs)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/repocard_data.py#L480)

**参数：**

title (`str`, *可选*) : Space 的标题。

sdk (`str`, *可选*) : Space 的 SDK（`gradio`、`streamlit`、`docker` 或 `static` 之一）。

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 (`list[str]`, *可选*) : 与此 Space 相关的模型列表。应为在 https://hf.co/models 上找到的数据集 ID。

datasets (`list[str]`, *可选*) : 与此 Space 相关的数据集列表。应为在 https://hf.co/datasets 上找到的数据集 ID。

tags (`list[str]`, *可选*) : 要添加到您的 Space 的标签列表，可用于在 Hub 上进行筛选。

ignore_metadata_errors (`str`) : 如果为 True，解析元数据部分时出现的错误将被忽略。在此过程中可能会丢失一些信息。请谨慎使用。

kwargs (`dict`, *可选*) : 将添加到空间卡片中的附加元数据。

在 README.md 文件顶部包含时，Hugging Face Hub 使用的 Space 卡片元数据

如需获取 Spaces 配置的完整参考，请访问 https://huggingface.co/docs/hub/spaces-config-reference#spaces-configuration-reference。

示例：
```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'}
```

## 实用工具

### EvalResult[[huggingface_hub.EvalResult]]

#### huggingface_hub.EvalResult[[huggingface_hub.EvalResult]]

```python
huggingface_hub.EvalResult(task_type: str, dataset_type: str, dataset_name: str, metric_type: str, metric_value: typing.Any, task_name: str | None = None, dataset_config: str | None = None, dataset_split: str | None = None, dataset_revision: str | None = None, dataset_args: dict[str, typing.Any] | None = None, metric_name: str | None = None, metric_config: str | None = None, metric_args: dict[str, typing.Any] | None = None, verified: bool | None = None, verify_token: str | None = None, source_name: str | None = None, source_url: str | None = None)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/repocard_data.py#L13)

**参数：**

task_type (`str`) : 任务标识符。示例："image-classification"。

dataset_type (`str`) : 数据集标识符。示例："common_voice"。请使用 https://hf.co/datasets 中的数据集 id。

dataset_name (`str`) : 数据集的显示名称。示例："Common Voice (French)"。

metric_type (`str`) : 指标标识符。示例："wer"。请使用 https://hf.co/metrics 中的指标 id。

metric_value (`Any`)：指标值。示例：0.9 或 "20.0 ± 1.2"。

task_name (`str`, *可选*) : 任务的显示名称。示例："Speech Recognition"。

dataset_config (`str`, *可选*) : 在 `load_dataset()` 中使用的数据集配置名称。示例：`load_dataset("common_voice", "fr")` 中的 fr。有关更多信息，请参阅 `datasets` 文档：https://hf.co/docs/datasets/package_reference/loading_methods#datasets.load_dataset.name

dataset_split (`str`, *可选*) : 在 `load_dataset()` 中使用的 split。示例："test"。

dataset_revision (`str`, *可选*) : 在 `load_dataset()` 中使用的数据集的版本（也称为 Git Sha）。示例：5503434ddd753f426f4b38109466949a1217c2bb

dataset_args (`dict[str, Any]`, *可选*) : 在调用 `Metric.compute()` 时传入的参数。`bleu` 的示例：`{"max_order": 4}`

metric_name (`str`, *可选*) : 指标的显示名称。示例："Test WER"。

metric_config (`str`, *可选*) : 在 `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]`, *可选*) : 在调用 `Metric.compute()` 时传入的参数。`bleu` 的示例：max_order: 4

verified (`bool`, *可选*) : 指示指标是否来自 Hugging Face 的 [评估服务](https://huggingface.co/spaces/autoevaluate/model-evaluator)。由 Hugging Face 自动计算，请勿设置。

verify_token (`str`, *可选*) : 用于验证指标是否源自 Hugging Face [评估服务](https://huggingface.co/spaces/autoevaluate/model-evaluator) 的 JSON Web Token。

source_name (`str`, *可选*) : 评估结果来源的名称。示例："Open LLM Leaderboard"。

source_url (`str`, *可选*) : 评估结果来源的 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[[huggingface_hub.EvalResult.is_equal_except_value]]

```python
is_equal_except_value(other: EvalResult)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/repocard_data.py#L145)

如果 `self` 和 `other` 描述的是完全相同的指标但值不同，则返回 True。

### model_index_to_eval_results[[huggingface_hub.repocard_data.model_index_to_eval_results]]

#### huggingface_hub.repocard_data.model_index_to_eval_results[[huggingface_hub.repocard_data.model_index_to_eval_results]]

```python
huggingface_hub.repocard_data.model_index_to_eval_results(model_index: list)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/repocard_data.py#L561)

**参数：**

model_index (`list[dict[str, Any]]`) : 模型索引数据结构，通常来自 Hugging Face Hub 上的 README.md 文件。

**返回：** model_name (`str`)

在模型索引中找到的模型名称。此名称用作模型在 PapersWithCode 等排行榜上的标识符。eval_results (`list[EvalResult]`)：一个 `huggingface_hub.EvalResult` 对象列表，包含在提供的 model_index 中报告的指标。

接收模型索引，并返回模型名称以及一个`huggingface_hub.EvalResult`对象列表。

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

示例：
```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_to_model_index[[huggingface_hub.repocard_data.eval_results_to_model_index]]

#### huggingface_hub.repocard_data.eval_results_to_model_index[[huggingface_hub.repocard_data.eval_results_to_model_index]]

```python
huggingface_hub.repocard_data.eval_results_to_model_index(model_name: str, eval_results: list)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/repocard_data.py#L681)

**参数：**

model_name (`str`) : 模型的名称（例如 "my-cool-model"）。此名称用作模型在 PapersWithCode 等排行榜上的标识符。

eval_results (`list[EvalResult]`) : 包含要在 model-index 中报告的指标的 `huggingface_hub.EvalResult` 对象列表。

**返回：** model_index (`list[dict[str, Any]]`)

转换为模型索引的 eval_results。

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

示例：
```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}]}]}]

```

### metadata_eval_result[[huggingface_hub.metadata_eval_result]]

#### huggingface_hub.metadata_eval_result[[huggingface_hub.metadata_eval_result]]

```python
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: str | None = None, metrics_verified: bool = False, dataset_config: str | None = None, dataset_split: str | None = None, dataset_revision: str | None = None, metrics_verification_token: str | None = None)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/repocard.py#L560)

**参数：**

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://hf.co/metrics 的指标 ID。

metrics_value (`Any`)：来自指标的值。示例：20.0 或 "20.0 ± 1.2"。

dataset_pretty_name (`str`) : 数据集的自然语言名称。

dataset_id (`str`) : 示例：common_voice。来自 https://hf.co/datasets 的数据集 ID。

metrics_config (`str`, *可选*) : 在 `load_metric()` 中使用的指标配置名称。示例：`load_metric("bleurt", "bleurt-large-512")` 中的 bleurt-large-512。

metrics_verified (`bool`，*可选*，默认为 `False`)：指示指标是否来自 Hugging Face 的 [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator)。由 Hugging Face 自动计算，请勿设置。

dataset_config (`str`, *可选*) : 示例：fr。在 `load_dataset()` 中使用的数据集配置的名称。

dataset_split (`str`，*可选*)：示例：test。在 `load_dataset()` 中使用的数据集拆分名称。

dataset_revision (`str`，*可选*)：示例：5503434ddd753f426f4b38109466949a1217c2bb。在 `load_dataset()` 中使用的数据集修订版本的名称。

metrics_verification_token (`bool`, *可选*) : 用于验证指标是否源自 Hugging Face 的 [评估服务](https://huggingface.co/spaces/autoevaluate/model-evaluator) 的 JSON Web Token。

**返回：** `dict`

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

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

示例：
```python
>>> 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]]

#### huggingface_hub.metadata_update[[huggingface_hub.metadata_update]]

```python
huggingface_hub.metadata_update(repo_id: str, metadata: dict, repo_type: str | None = None, overwrite: bool = False, token: str | None = None, commit_message: str | None = None, commit_description: str | None = None, revision: str | None = None, create_pr: bool = False, parent_commit: str | None = None)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/repocard.py#L688)

**参数：**

repo_id (`str`) : 仓库的名称。

metadata (`dict`) : 包含要更新的元数据的字典。

repo_type (`str`, *可选*) : 如果更新为数据集或空间，请设置为 `"dataset"` 或 `"space"`；如果更新为模型，请设置为 `None` 或 `"model"`。默认值为 `None`。

overwrite (`bool`，*可选*，默认为 `False`)：如果设置为 `True`，则可以覆盖现有字段；否则，尝试覆盖现有字段将导致错误。

token (`str`, *可选*) : Hugging Face 身份验证令牌。

commit_message (`str`, *可选*) : 生成的提交的摘要 / 标题 / 第一行。默认为 `f"Update metadata with huggingface_hub"`

commit_description (`str`, *可选*) : 生成的提交的描述

revision (`str`, *可选*) : 要从中提交内容的 git 版本。默认为 `"main"` 分支的头部。

create_pr (`boolean`, *可选*) : 是否从 `revision` 创建包含该提交的 Pull Request。默认为 `False`。

parent_commit (`str`, *可选*) : 父提交的 OID / SHA，以十六进制字符串表示。也支持简写形式（前 7 个字符）。如果指定了该参数且 `create_pr` 为 `False`，当 `revision` 不指向 `parent_commit` 时，提交将失败。如果指定了该参数且 `create_pr` 为 `True`，拉取请求将从 `parent_commit` 创建。指定 `parent_commit` 可确保在提交更改之前仓库未发生变化，这在仓库被并发更新 / 提交时尤其有用。

**返回：** `str`

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

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

示例：
```python
>>> 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)

```

