> 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/upload-label-and-export.md).

# 업로드, 라벨링, 내보내기

Python으로 이미지 업로드, 모델 사전 라벨 가져오기, 워크플로 검토, COCO 릴리스 다운로드까지 엔드 투 엔드로 진행하는 예제입니다.

이 예제는 로봇 셀 이미지 폴더를 업로드부터 COCO 릴리스 다운로드까지 진행합니다. 모델 예측은 사전 라벨(pre-label)이 되고, 사람이 Workbench에서 검토하며, 승인된 항목만 내보냅니다.

**데이터:** JPG 이미지와 COCO 예측 파일 · **사용 도구:** Python SDK, Unitlab 앱 · **결과:** `train`, `test` COCO 아카이브

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

* 워크스페이스 멤버가 만든 API 키. **Manage data**, **View labeling interface**, **Create labels**, **Manage releases** 권한이 필요합니다. [인증과 API 키](https://docs.unitlab.ai/api-sdk-cli/ko/get-started/authentication-and-api-keys.md)를 참고하세요.
* 클래스 이름이 COCO 파일의 `categories`와 일치하는 온톨로지를 가진 프로젝트. [Python SDK 빠른 시작](https://docs.unitlab.ai/api-sdk-cli/ko/get-started/python-sdk-quickstart.md)에서 만들 수 있습니다.
* 이미지 폴더와, `file_name` 값이 이미지 이름과 일치하는 COCO 형식의 `predictions.json`.

```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/ko/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/ko/sdks/annotation-imports.md) · [워크플로 단계와 작업](https://docs.unitlab.ai/api-sdk-cli/ko/sdks/workflow-stages-and-tasks.md) · [릴리스 생성과 다운로드](https://docs.unitlab.ai/api-sdk-cli/ko/sdks/create-and-download-releases.md)
