> 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/python-sdk-quickstart.md).

# Python SDK 快速入门

Unitlab Python SDK 快速入门：用一个脚本在五分钟内创建带边界框本体的项目、上传一整个图像文件夹、等待服务端处理完成并列出生成的 Data Unit，同时了解每一步的结果和常见错误的解决方法。

大约五分钟内，你将创建一个使用边界框本体的项目，上传一个图像文件夹，并列出 Unitlab 创建的条目。

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

* [安装 SDK](https://docs.unitlab.ai/api-sdk-cli/zh/get-started/install-the-python-sdk-and-cli.md) 并[设置 `UNITLAB_API_KEY`](https://docs.unitlab.ai/api-sdk-cli/zh/get-started/authentication-and-api-keys.md)。该密钥需要 **Manage projects**、**Manage ontologies** 和 **Manage data** 权限。
* 在脚本旁边创建一个名为 `images` 的文件夹，放入几张 JPG 或 PNG 图像。

```
warehouse-picks/
├── quickstart.py
└── images/
    ├── bin-001.jpg
    └── bin-002.jpg
```

## 运行脚本 <a href="#run-the-script" id="run-the-script"></a>

将以下代码保存为 `quickstart.py`，并用 Python 运行。

```python
from pathlib import Path

from unitlab import OntologyStructure, RadioAttribute, Shape, UnitlabClient

client = UnitlabClient()  # reads UNITLAB_API_KEY
try:
    # 1. Describe what annotators will label.
    structure = OntologyStructure()
    item = structure.add_object("Item", Shape.BOUNDING_BOX)
    grasp = item.add_attribute(RadioAttribute, "Graspable", required=True)
    grasp.add_option("Yes")
    grasp.add_option("No")
    ontology = client.ontologies.create("Bin picking", structure=structure)

    # 2. Create a project that uses it.
    project = client.projects.create("Warehouse picks", ontology_hash=ontology.id)
    print("Project:", project.id)

    # 3. Upload the folder. One call creates one Batch Queue.
    batch = project.upload(Path(__file__).parent / "images")
    print(f"Uploaded {batch.uploaded} of {batch.total} files")
    for failure in batch.failed:
        print("Not uploaded:", failure.path, failure.error)

    # 4. Wait until the server has processed every file.
    status = batch.wait(timeout=1800)
    print(f"Processed: {status.completed}, failed: {status.failed}")

    # 5. List the items in this upload.
    for unit in project.data_units(batch_queue=batch.batch_queue_id):
        print(unit.name, unit.data_type, unit.status)
finally:
    client.close()
```

你会看到类似下面的输出。在终端中，`batch.wait()` 还会显示进度条。

```
Project: 7c9e6679-7425-40de-944b-e07fc1f90ae7
Uploaded 2 of 2 files
Processed: 2, failed: 0
bin-001.jpg image annotate
bin-002.jpg image annotate
```

{% hint style="success" %}
在应用中打开该项目。两张图像都在 **Data** 中，点击 **Start Annotating** 即可使用 **Item** 类别打开它们。
{% endhint %}

## 执行过程说明 <a href="#what-happened" id="what-happened"></a>

| 步骤 | 调用                           | 结果                                                 |
| -- | ---------------------------- | -------------------------------------------------- |
| 1  | `client.ontologies.create()` | 一个包含一个类别和一个必填属性的工作区本体                              |
| 2  | `client.projects.create()`   | 一个以该本体初始化的项目                                       |
| 3  | `project.upload()`           | 并行发送文件；返回 Batch Queue ID 和本地失败项                    |
| 4  | `batch.wait()`               | 轮询直到没有处理中的文件；返回已处理和失败的数量                           |
| 5  | `project.data_units()`       | 每个文件对应一个 Data Unit，并带有工作流状态（在第一个阶段等待时为 `annotate`） |

每次运行都会创建新的本体和项目。如需复用项目，请改为调用 `client.projects.get("PROJECT_ID")`。

## 故障排查 <a href="#if-something-goes-wrong" id="if-something-goes-wrong"></a>

| 现象                                         | 解决方法                                                                        |
| ------------------------------------------ | --------------------------------------------------------------------------- |
| `AuthenticationError: No API key provided` | 设置 `UNITLAB_API_KEY`。                                                       |
| `PermissionDeniedError`                    | 为密钥打开**开始之前**中列出的权限。                                                        |
| 文件出现在 `batch.failed` 中                     | 查看 `failure.error`，修复文件后仅重新上传该文件。                                           |
| `status.failed` 大于 0                       | 在应用中打开该 Batch Queue，或调用 `project.batch_queue(batch.batch_queue_id).data()`。 |
| `ProcessingTimeoutError`                   | 处理仍在进行中。稍后再次调用 `project.batch_queue(id).wait()`。                            |

## 后续步骤 <a href="#next-steps" id="next-steps"></a>

* [上传、标注与导出](https://docs.unitlab.ai/api-sdk-cli/zh/get-started/upload-label-and-export.md)：导入模型标注、审核并导出发布。
* [项目上传](https://docs.unitlab.ai/api-sdk-cli/zh/sdks/project-uploads.md)：视频帧率、CSV、医学影像、瓦片化栅格及各项限制。
* [用 Python 构建本体](https://docs.unitlab.ai/api-sdk-cli/zh/sdks/build-ontologies-in-python.md)：所有形状和属性类型。

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

[CLI 快速入门](https://docs.unitlab.ai/api-sdk-cli/zh/get-started/cli-quickstart.md) · [UnitlabClient 与资源命名空间](https://docs.unitlab.ai/api-sdk-cli/zh/sdks/unitlabclient-and-resource-namespaces.md) · [异常、超时与重试](https://docs.unitlab.ai/api-sdk-cli/zh/sdks/exceptions-timeouts-and-retries.md)
