> For the complete documentation index, see [llms.txt](https://docs.unitlab.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.unitlab.ai/api-sdk-cli/zh/get-started/upload-label-and-export.md).

# 上传、标注与导出

端到端 Python 教程：用 Unitlab SDK 上传图像，将 COCO 格式的模型预测导入为预标注，在工作流中审核，再创建并下载包含 train 与 test 划分的 COCO 发布，并附上使用 unitlab CLI 完成上传与发布的等效命令。

本教程将一个机器人工作单元图像文件夹从上传一直处理到下载 COCO 发布。模型预测作为预标注导入，由人在 Workbench 中审核，只有已批准的条目才会被导出。

**数据：** JPG 图像和一个 COCO 预测文件 · **使用：** Python SDK、Unitlab 应用 · **结果：** `train` 和 `test` 两个 COCO 文件

## 开始之前 <a href="#before-you-begin" id="before-you-begin"></a>

* 一个由工作区成员创建、具备 **Manage data**、**View labeling interface**、**Create labels** 和 **Manage releases** 权限的 API 密钥。详见[身份认证与 API 密钥](https://docs.unitlab.ai/api-sdk-cli/zh/get-started/authentication-and-api-keys.md)。
* 一个带有本体的项目，其类别名称与 COCO 文件中的 `categories` 一致。[Python SDK 快速入门](https://docs.unitlab.ai/api-sdk-cli/zh/get-started/python-sdk-quickstart.md)会创建这样的项目。
* 一个图像文件夹，以及一个 COCO 格式的 `predictions.json`，其中的 `file_name` 值与图像名称一致。

```bash
export UNITLAB_API_KEY="YOUR_API_KEY"
export PROJECT_ID="YOUR_PROJECT_ID"
```

## 1. 上传图像 <a href="#id-1.-upload-the-images" id="id-1.-upload-the-images"></a>

```python
import os
from unitlab import UnitlabClient

client = UnitlabClient()
project = client.projects.get(os.environ["PROJECT_ID"])

batch = project.upload("./images")
status = batch.wait(timeout=1800)
if batch.failed or status.failed:
    raise SystemExit(f"Fix failed files first: {batch.failed}, {status.failed} on the server")
print("Batch Queue:", batch.batch_queue_id)
```

导入标注前请先等待处理完成。标注只能匹配服务器已处理完的媒体。

## 2. 将预测导入为预标注 <a href="#id-2.-import-the-predictions-as-pre-labels" id="id-2.-import-the-predictions-as-pre-labels"></a>

```python
imported = project.annotation_imports.create(
    "./predictions.json",
    source_name="detector-v3",   # reuse the same name for the same model
)
print(imported.preview["counts"])
for issue in imported.preview["issues"][:5]:
    print("Issue:", issue)

report = imported.commit()
print(report)
```

`create()` 会上传文件并返回一份**预览**：有多少对象匹配到媒体、与现有标注冲突或无法导入。在调用 `commit()` 之前不会保存任何内容。重复提交是安全的：超时后再次调用，会返回已保存的报告，不会产生重复标注。

## 3. 在工作流中审核 <a href="#id-3.-review-in-the-workflow" id="id-3.-review-in-the-workflow"></a>

导入的标注是预标注，而不是已批准的工作。团队成员在 Workbench 中打开每个任务，修正边界框，并按项目工作流提交。阶段配置请参阅[工作流](https://docs.unitlab.ai/documentation/zh/workflows/workflows-overview)。

在代码中查看进度：

```python
for stage in project.workflow.stages:
    print(f"{stage.name:<12} {stage.type:<10} {stage.task_count} tasks")
```

```
Project      dataset    0 tasks
Annotate     annotate   38 tasks
Review       review     10 tasks
Complete     complete   52 tasks
```

从脚本中批准已审核的任务（例如在自动化 QA 检查之后）：

```python
review = project.workflow.get_stage(stage_type="review")
for task in review.get_tasks():
    task.claim()
    task.approve()
```

## 4. 创建并下载发布 <a href="#id-4.-create-and-download-the-release" id="id-4.-create-and-download-the-release"></a>

```python
release = client.releases.create(
    project,
    export_type="COCO",
    split_ratios={"train": 80, "test": 20},
    completed_only=True,   # only items that finished the workflow
)
print(release.name, release.version, release.data_item_count, "items")

for split in ("train", "test"):
    path = release.download(split, dest="./export")
    print(split, path)
client.close()
```

```
Warehouse picks 0.1 52 items
train /home/me/warehouse-picks/export/coco-34ba4072-...-v0.1_train.json
test /home/me/warehouse-picks/export/coco-34ba4072-...-v0.1_test.json
```

`create()` 会等待发布就绪，大型项目可能需要几分钟。传入 `wait=False` 可立即返回，稍后再调用 `release.wait()`。

{% hint style="warning" %}
发布只包含标注通过本体校验的条目。如果某个类别有必填属性，每个对象（包括导入的预标注）都必须为其赋值。条目很少时，某个划分可能为空；下载该划分会抛出 `ValidationError: No data available for split`。
{% endhint %}

在 COCO 中，`file_name` 是 Unitlab 存储该文件时使用的名称，`source_url` 是媒体的下载链接。如需下载媒体本身，请使用 `release.download_files("./export/files")`。

## 在 CLI 中完成相同流程 <a href="#the-same-flow-in-the-cli" id="the-same-flow-in-the-cli"></a>

CLI 支持上传、等待和发布。标注导入请使用 SDK。

```bash
unitlab project upload "$PROJECT_ID" --source ./images --json > upload.json
unitlab batch-queue wait "$PROJECT_ID" "$(jq -r .batch_queue_id upload.json)"
# ...import labels with the SDK, review in the app...
RELEASE_ID=$(unitlab release create "$PROJECT_ID" --format COCO \
  --splits train=80,test=20 --wait --json | jq -r .id)
unitlab release download "$RELEASE_ID" --split-type train --dest ./export
```

## 相关内容 <a href="#related" id="related"></a>

[标注导入](https://docs.unitlab.ai/api-sdk-cli/zh/sdks/annotation-imports.md) · [工作流阶段与任务](https://docs.unitlab.ai/api-sdk-cli/zh/sdks/workflow-stages-and-tasks.md) · [创建与下载发布](https://docs.unitlab.ai/api-sdk-cli/zh/sdks/create-and-download-releases.md)
