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

# Python SDK 빠른 시작

Unitlab Python SDK 빠른 시작 가이드입니다. 바운딩 박스 온톨로지로 프로젝트를 만들고, 이미지 폴더를 업로드해 Batch Queue 처리를 기다린 뒤, 생성된 Data Unit을 확인하는 과정을 5분 안에 따라 해 봅니다.

약 5분 안에 바운딩 박스 온톨로지가 있는 프로젝트를 만들고, 이미지 폴더를 업로드한 다음, Unitlab이 생성한 항목을 조회합니다.

## 시작하기 전에 <a href="#before-you-begin" id="before-you-begin"></a>

* [SDK를 설치](https://docs.unitlab.ai/api-sdk-cli/ko/get-started/install-the-python-sdk-and-cli.md)하고 [`UNITLAB_API_KEY`를 설정](https://docs.unitlab.ai/api-sdk-cli/ko/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/ko/get-started/upload-label-and-export.md): 모델 라벨을 가져오고 검토한 뒤 릴리스를 내보냅니다.
* [프로젝트 업로드](https://docs.unitlab.ai/api-sdk-cli/ko/sdks/project-uploads.md): 비디오 프레임 레이트, CSV, 의료 영상, 타일 래스터와 제한 사항.
* [Python으로 온톨로지 구성](https://docs.unitlab.ai/api-sdk-cli/ko/sdks/build-ontologies-in-python.md): 모든 도형과 속성 유형.

## 관련 문서 <a href="#related" id="related"></a>

[CLI 빠른 시작](https://docs.unitlab.ai/api-sdk-cli/ko/get-started/cli-quickstart.md) · [UnitlabClient와 리소스 네임스페이스](https://docs.unitlab.ai/api-sdk-cli/ko/sdks/unitlabclient-and-resource-namespaces.md) · [예외, 타임아웃, 재시도](https://docs.unitlab.ai/api-sdk-cli/ko/sdks/exceptions-timeouts-and-retries.md)
