# 创建并共享模型卡片

`huggingface_hub` 库提供了一个 Python 接口，用于创建、共享和更新 Model Cards。请访问[专用文档页面](https://huggingface.co/docs/hub/models-cards)，深入了解 Hub 上的 Model Cards 是什么，以及其底层工作原理。

## 从 Hub 加载模型卡

要从 Hub 加载现有的卡片，可以使用 [ModelCard.load()](/docs/huggingface_hub/v2.5.0/zh/package_reference/cards#huggingface_hub.RepoCard.load) 函数。在这里，我们将加载 [`nateraw/vit-base-beans`](https://huggingface.co/nateraw/vit-base-beans) 的卡片。

```python
from huggingface_hub import ModelCard

card = ModelCard.load('nateraw/vit-base-beans')
```

此卡片包含一些您可能想要访问或利用的有用属性：
  - `card.data`：返回一个包含模型卡片元数据的 [ModelCardData](/docs/huggingface_hub/v2.5.0/zh/package_reference/cards#huggingface_hub.ModelCardData) 实例。调用该实例的 `.to_dict()` 方法可获取其字典表示形式。
  - `card.text`：返回卡片的文本，*不包括元数据头部*。
  - `card.content`：返回卡片的文本内容，*包括元数据头部*。

## 创建模型卡片

### 从文本

要从文本初始化模型卡，只需在初始化时将卡片的文本内容传递给 `ModelCard` 即可。

```python
content = """
---
language: en
license: mit
---

# My Model Card
"""

card = ModelCard(content)
card.data.to_dict() == {'language': 'en', 'license': 'mit'}  # True
```

另一种可能的方式是使用 f-string。在下面的示例中，我们：

- 使用 [ModelCardData.to_yaml()](/docs/huggingface_hub/v2.5.0/zh/package_reference/cards#huggingface_hub.CardData.to_yaml) 将我们定义的元数据转换为 YAML，以便将其插入到模型卡中的 YAML 代码块。
- 展示如何通过 Python f-string 使用模板变量。

```python
card_data = ModelCardData(language='en', license='mit', library='timm')

example_template_var = 'nateraw'
content = f"""
---
{ card_data.to_yaml() }
---

# My Model Card

This model created by [@{example_template_var}](https://github.com/{example_template_var})
"""

card = ModelCard(content)
print(card)
```

上述示例将生成如下所示的卡片：

```
---
language: en
license: mit
library: timm
---

# My Model Card

This model created by [@nateraw](https://github.com/nateraw)
```

### 来自 Jinja 模板

如果已安装 `Jinja2`，您可以从 jinja 模板文件创建 Model Cards。下面是一个基本示例：

```python
from pathlib import Path

from huggingface_hub import ModelCard, ModelCardData

# Define your jinja template
template_text = """
---
{{ card_data }}
---

# Model Card for MyCoolModel

This model does this and that.

This model was created by [@{{ author }}](https://hf.co/{{author}}).
""".strip()

# Write the template to a file
Path('custom_template.md').write_text(template_text)

# Define card metadata
card_data = ModelCardData(language='en', license='mit', library_name='keras')

# Create card from template, passing it any jinja template variables you want.
# In our case, we'll pass author
card = ModelCard.from_template(card_data, template_path='custom_template.md', author='nateraw')
card.save('my_model_card_1.md')
print(card)
```

生成的卡片的 Markdown 内容如下：

```
---
language: en
license: mit
library_name: keras
---

# Model Card for MyCoolModel

This model does this and that.

This model was created by [@nateraw](https://hf.co/nateraw).
```

如果您更新任何 card.data，更改将反映在卡片本身中。

```
card.data.library_name = 'timm'
card.data.language = 'fr'
card.data.license = 'apache-2.0'
print(card)
```

现在，如您所见，元数据头部已更新：

```
---
language: fr
license: apache-2.0
library_name: timm
---

# Model Card for MyCoolModel

This model does this and that.

This model was created by [@nateraw](https://hf.co/nateraw).
```

在更新卡片数据时，您可以通过调用 [ModelCard.validate()](/docs/huggingface_hub/v2.5.0/zh/package_reference/cards#huggingface_hub.RepoCard.validate) 来验证该卡片在 Hub 上是否仍然有效。这可以确保卡片通过 Hugging Face Hub 上设置的所有验证规则。

### 来自默认模板

除了使用自己的模板，你还可以使用[默认模板](https://github.com/huggingface/huggingface_hub/blob/main/src/huggingface_hub/templates/modelcard_template.md)，这是一个功能完整的模型卡片，包含许多你可能需要填写的部分。其底层使用[Jinja2](https://jinja.palletsprojects.com/en/3.1.x/)来填充模板文件。

> [!TIP]
> 请注意，使用 `from_template` 需要安装 Jinja2。您可以通过 `pip install Jinja2` 进行安装。

```python
card_data = ModelCardData(language='en', license='mit', library_name='keras')
card = ModelCard.from_template(
    card_data,
    model_id='my-cool-model',
    model_description="this model does this and that",
    developers="Nate Raw",
    repo="https://github.com/huggingface/huggingface_hub",
)
card.save('my_model_card_2.md')
print(card)
```

## 共享模型卡片

如果您已通过 Hugging Face Hub 进行身份验证（无论是使用 `hf auth login` 还是 [login()](/docs/huggingface_hub/v2.5.0/zh/package_reference/authentication#huggingface_hub.login)），只需调用 [ModelCard.push_to_hub()](/docs/huggingface_hub/v2.5.0/zh/package_reference/cards#huggingface_hub.RepoCard.push_to_hub) 即可将卡片推送到 Hub。让我们来看看具体操作……

首先，我们将在已认证用户的命名空间下创建一个名为 'hf-hub-modelcards-pr-test' 的新仓库：

```python
from huggingface_hub import whoami, create_repo

user = whoami()['name']
repo_id = f'{user}/hf-hub-modelcards-pr-test'
url = create_repo(repo_id, exist_ok=True)
```

然后，我们将使用默认模板（与上面部分中定义的模板相同）创建一个卡片：

```python
card_data = ModelCardData(language='en', license='mit', library_name='keras')
card = ModelCard.from_template(
    card_data,
    model_id='my-cool-model',
    model_description="this model does this and that",
    developers="Nate Raw",
    repo="https://github.com/huggingface/huggingface_hub",
)
```

最后，我们将把它推送到 hub

```python
card.push_to_hub(repo_id)
```

您可以在此处查看生成的卡片 [here](https://huggingface.co/nateraw/hf-hub-modelcards-pr-test/blob/main/README.md)。

如果您希望以拉取请求的形式推送卡片，只需在调用 `push_to_hub` 时指定 `create_pr=True` 即可：

```python
card.push_to_hub(repo_id, create_pr=True)
```

由此命令生成的 PR 可以在[此处](https://huggingface.co/nateraw/hf-hub-modelcards-pr-test/discussions/3)查看。

## 更新元数据

在本节中，我们将了解仓库卡片中包含哪些元数据，以及如何更新它们。

`metadata` 指的是一个哈希映射（或键值对）上下文，用于提供有关模型、数据集或 Space 的一些高层信息。这些信息可以包括模型的 `pipeline type`、`model_id` 或 `model_description` 等详细信息。如需了解更多，请参阅以下指南：[Model Card](https://huggingface.co/docs/hub/model-cards#model-card-metadata)、[Dataset Card](https://huggingface.co/docs/hub/datasets-cards#dataset-card-metadata) 和 [Spaces Settings](https://huggingface.co/docs/hub/spaces-settings#spaces-settings)。下面让我们通过一些示例来看看如何更新这些元数据。

让我们从一个示例开始：

```python
>>> from huggingface_hub import metadata_update
>>> metadata_update("username/my-cool-model", {"pipeline_tag": "image-classification"})
```

使用这两行代码，您可以更新元数据以设置新的 `pipeline_tag`。

默认情况下，您无法更新卡片上已存在的键。如果您希望执行此操作，必须显式传入 `overwrite=True`：

```python
>>> from huggingface_hub import metadata_update
>>> metadata_update("username/my-cool-model", {"pipeline_tag": "text-generation"}, overwrite=True)
```

这种情况很常见：你希望向一个没有写入权限的仓库提交一些更改。你可以通过在该仓库上创建一个 PR 来实现，这样仓库的所有者就可以审查并合并你的建议。

```python
>>> from huggingface_hub import metadata_update
>>> metadata_update("someone/model", {"pipeline_tag": "text-classification"}, create_pr=True)
```

## 包含评估结果

若要在元数据 `model-index` 中包含评估结果，您可以传入一个 [EvalResult](/docs/huggingface_hub/v2.5.0/zh/package_reference/cards#huggingface_hub.EvalResult) 或一个包含相关评估结果的 `EvalResult` 列表。在内部，当您调用 `card.data.to_dict()` 时，它会创建 `model-index`。有关此机制的更多信息，请参阅 [Hub 文档中的此部分](https://huggingface.co/docs/hub/models-cards#evaluation-results)。

> [!TIP]
> 请注意，使用此函数需要在 [ModelCardData](/docs/huggingface_hub/v2.5.0/zh/package_reference/cards#huggingface_hub.ModelCardData) 中包含 `model_name` 属性。

```python
card_data = ModelCardData(
    language='en',
    license='mit',
    model_name='my-cool-model',
    eval_results = EvalResult(
        task_type='image-classification',
        dataset_type='beans',
        dataset_name='Beans',
        metric_type='accuracy',
        metric_value=0.7
    )
)

card = ModelCard.from_template(card_data)
print(card.data)
```

生成的 `card.data` 应如下所示：

```
language: en
license: mit
model-index:
- name: my-cool-model
  results:
  - task:
      type: image-classification
    dataset:
      name: Beans
      type: beans
    metrics:
    - type: accuracy
      value: 0.7
```

如果您有多个想要分享的评估结果，只需传入一个`EvalResult`列表即可：

```python
card_data = ModelCardData(
    language='en',
    license='mit',
    model_name='my-cool-model',
    eval_results = [
        EvalResult(
            task_type='image-classification',
            dataset_type='beans',
            dataset_name='Beans',
            metric_type='accuracy',
            metric_value=0.7
        ),
        EvalResult(
            task_type='image-classification',
            dataset_type='beans',
            dataset_name='Beans',
            metric_type='f1',
            metric_value=0.65
        )
    ]
)
card = ModelCard.from_template(card_data)
card.data
```

这样，你的 `card.data` 应该如下所示：

```
language: en
license: mit
model-index:
- name: my-cool-model
  results:
  - task:
      type: image-classification
    dataset:
      name: Beans
      type: beans
    metrics:
    - type: accuracy
      value: 0.7
    - type: f1
      value: 0.65
```

