# CLI 사용법

설치하면 `inference-cli` 에 액세스할 수 있습니다. `inference rf-cloud` 명령을 사용할 수 있으며, 이를 통해 Roboflow Batch Processing의 핵심 구성 요소인 Batch Processing과 Data Staging을 상호 작용할 수 있습니다.

## 설정

```bash
pip install inference-cli
export ROBOFLOW_API_KEY="YOUR-API-KEY-GOES-HERE"
```

클라우드 스토리지 지원을 위해:

```bash
pip install 'inference-cli[cloud-storage]'
```

API 키를 찾는 데 도움이 필요하면 다음을 참고하세요. [인증 가이드](https://docs.roboflow.com/api-reference/authentication).

## 데이터 수집

### 이미지

```bash
inference rf-cloud data-staging create-batch-of-images \
  --images-dir <your-images-dir-path> \
  --batch-id <your-batch-id>
```

### 동영상

```bash
inference rf-cloud data-staging create-batch-of-videos \
  --videos-dir <your-videos-dir-path> \
  --batch-id <your-batch-id>
```

{% hint style="info" %}
**Batch ID 형식:** 소문자여야 하며, 최대 64자까지 가능하고, 문자, 숫자, 하이픈(`-`) 및 밑줄(`_`).
{% endhint %}

### 클라우드 스토리지

데이터가 이미 클라우드 스토리지(S3, Google Cloud Storage 또는 Azure)에 있다면, 파일을 로컬로 다운로드하지 않고도 직접 처리할 수 있습니다.

**이미지의 경우:**

```bash
inference rf-cloud data-staging create-batch-of-images \
  --data-source cloud-storage \
  --bucket-path <cloud-path> \
  --batch-id <your-batch-id>
```

**동영상의 경우:**

```bash
inference rf-cloud data-staging create-batch-of-videos \
  --data-source cloud-storage \
  --bucket-path <cloud-path> \
  --batch-id <your-batch-id>
```

다음 `--bucket-path` 매개변수는 다음을 지원합니다:

* **S3**: `s3://bucket-name/path/`
* **Google Cloud Storage**: `gs://bucket-name/path/`
* **Azure Blob Storage**: `az://container-name/path/`

글롭 패턴을 포함하여 파일을 필터링할 수 있습니다:

* `s3://my-bucket/training-data/**/*.jpg` — 모든 JPG 파일을 재귀적으로
* `gs://my-bucket/videos/2024-*/*.mp4` — 2024-\* 폴더의 MP4 파일
* `az://container/images/*.png` — images 폴더의 PNG 파일

{% hint style="info" %}
클라우드 스토리지 자격 증명은 **로컬에서만** CLI에 의해 presigned URL을 생성하는 데 사용됩니다. 자격 증명은 **절대 업로드되지 않습니다** Roboflow 서버로.
{% endhint %}

{% hint style="warning" %}
생성된 presigned URL은 24시간 동안 유효합니다. Batch Processing 작업이 이 시간 내에 완료되도록 하세요.
{% endhint %}

대용량 데이터셋의 경우, 시스템은 이미지를 각각 20,000개 파일씩 자동으로 분할합니다. 동영상은 1,000개 미만의 배치에서 가장 잘 작동합니다.

### Signed URL 수집

고급 자동화를 위해, 로컬 파일 대신 signed URL을 통해 데이터를 수집할 수 있습니다:

* `--data-source references-file` — signed URL로 참조된 파일을 처리합니다.
* `--references <path_or_url>` — 파일 URL이 포함된 JSONL 파일의 경로 또는 해당 파일을 가리키는 signed URL입니다.

**참조 파일 형식(JSONL):**

```
{"name": "<unique-file-name-1>", "url": "https://<signed-url>"}
{"name": "<unique-file-name-2>", "url": "https://<signed-url>"}
```

{% hint style="info" %}
Signed URL 수집은 Growth Plan 및 Enterprise 고객에게 제공됩니다.
{% endhint %}

## 스테이징된 데이터 검사

```bash
inference rf-cloud data-staging show-batch-details --batch-id <your-batch-id>
```

## 작업 시작

### 이미지 처리

```bash
inference rf-cloud batch-processing process-images-with-workflow \
  --workflow-id <workflow-id> \
  --batch-id <batch-id> \
  --machine-type gpu
```

### 동영상 처리

```bash
inference rf-cloud batch-processing process-videos-with-workflow \
  --workflow-id <workflow-id> \
  --batch-id <batch-id> \
  --machine-type gpu \
  --max-video-fps <your-desired-fps>
```

{% hint style="info" %}
**Workflow ID 찾기:** Roboflow App에서 Workflow Editor를 열고, "Deploy"를 클릭한 다음, 코드 스니펫에서 식별자를 찾으세요.
{% endhint %}

{% hint style="info" %}
기본적으로 처리는 CPU에서 실행됩니다. 다음을 사용하세요. `--machine-type gpu` 여러 개의 모델이 있거나 큰 모델이 있는 Workflows에 대해.
{% endhint %}

## 작업 진행 상황 모니터링

시작 명령은 **Job ID**를 출력합니다. 상태를 확인할 때 사용하세요:

```bash
inference rf-cloud batch-processing show-job-details --job-id <your-job-id>
```

## 결과 내보내기

작업 세부 정보에는 **출력 Batch ID**가 포함됩니다. 결과를 내보낼 때 사용하세요:

```bash
inference rf-cloud data-staging export-batch \
  --target-dir <dir-to-export-result> \
  --batch-id <output-batch-of-a-job>
```

## Webhook 자동화

상태를 주기적으로 확인하는 대신, 수집 또는 처리가 완료되면 알림을 받도록 webhooks를 사용할 수 있습니다.

### 데이터 수집 Webhooks

CLI 명령 `create-batch-of-images` 및 `create-batch-of-videos` 는 다음을 지원합니다:

* `--notifications-url <webhook_url>` — 알림을 위한 webhook 엔드포인트.
* `--notification-category <value>` — 알림 필터:
  * `ingest-status` (기본값) — 전체 수집 프로세스 상태.
  * `files-status` — 개별 파일 처리 상태.

알림은 HTTP POST를 통해 전송되며, `Authorization` 헤더에 Roboflow Publishable Key가 포함됩니다.

#### 수집 상태 알림

```json
{
    "type": "roboflow-data-staging-notification-v1",
    "event_id": "8c20f970-fe10-41e1-9ef2-e057c63c07ff",
    "ingest_id": "8cd48813430f2be70b492db67e07cc86",
    "batch_id": "test-batch-117",
    "shard_id": null,
    "notification": {
        "type": "ingest-status-notification-v1",
        "success": false,
        "error_details": {
            "type": "unsafe-url-detected",
            "reason": "신뢰할 수 없는 도메인이 발견됨: https://example.com/image.png"
        }
    },
    "delivery_attempt": 1
}
```

#### 파일 상태 알림

```json
{
    "type": "roboflow-data-staging-notification-v1",
    "event_id": "8f42708b-aeb7-4b73-9d83-cf18518b6d81",
    "ingest_id": "d5cb69aa-b2d1-4202-a1c1-0231f180bda9",
    "batch_id": "prod-batch-1",
    "shard_id": "0d40fa12-349e-439f-83f8-42b9b7987b33",
    "notification": {
        "type": "ingest-files-status-notification-v1",
        "success": true,
        "ingested_files": [
            "000000494869.jpg",
            "000000186042.jpg"
        ],
        "failed_files": [
            {
                "type": "file-size-limit-exceeded",
                "file_name": "big_image.png",
                "reason": "단일 이미지의 최대 크기는 20971520B입니다."
            }
        ],
        "content_truncated": false
    },
    "delivery_attempt": 1
}
```

### 작업 완료 Webhooks

추가 `--notifications-url` 를 작업 시작 시:

```bash
inference rf-cloud batch-processing process-images-with-workflow \
  --workflow-id <workflow-id> \
  --batch-id <batch-id> \
  --notifications-url <webhook_url>
```

#### 작업 완료 알림

```json
{
  "type": "roboflow-batch-job-notification-v1",
  "event_id": "8f42708b-aeb7-4b73-9d83-cf18518b6d81",
  "job_id": "<your-batch-job-id>",
  "job_state": "success | fail",
  "delivery_attempt": 1
}
```

## 클라우드 스토리지 인증

### AWS S3 및 S3 호환 스토리지

자격 증명은 다음에서 자동으로 감지됩니다:

1. **환경 변수:**

```bash
export AWS_ACCESS_KEY_ID=your-access-key-id
export AWS_SECRET_ACCESS_KEY=your-secret-access-key
export AWS_SESSION_TOKEN=your-session-token  # 선택 사항
```

2. **AWS 자격 증명 파일** (`~/.aws/credentials`, `~/.aws/config`)
3. **IAM 역할** (EC2, ECS, Lambda)

**이름이 지정된 프로필:**

```bash
export AWS_PROFILE=production
```

**S3 호환 서비스(Cloudflare R2, MinIO 등):**

```bash
export AWS_ENDPOINT_URL=https://account-id.r2.cloudflarestorage.com
export AWS_REGION=auto  # R2는 region='auto'가 필요합니다
export AWS_ACCESS_KEY_ID=your-r2-access-key
export AWS_SECRET_ACCESS_KEY=your-r2-secret-key
```

### Google Cloud Storage

자격 증명은 다음에서 감지됩니다:

1. **서비스 계정 키 파일** (자동화에 권장):

```bash
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account-key.json
```

2. **사용자 자격 증명** gcloud CLI에서 (`gcloud auth login`)
3. **GCP 메타데이터 서비스** (Google Cloud Platform에서 실행 중인 경우)

### Azure Blob Storage

**SAS 토큰(권장):**

```bash
export AZURE_STORAGE_ACCOUNT_NAME=mystorageaccount
export AZURE_STORAGE_SAS_TOKEN="sv=2021-06-08&ss=b&srt=sco&sp=rl&se=2024-12-31"
```

**계정 키:**

```bash
export AZURE_STORAGE_ACCOUNT_NAME=mystorageaccount
export AZURE_STORAGE_ACCOUNT_KEY=your-account-key
```

Azure CLI를 통해 SAS 토큰 생성:

```bash
az storage container generate-sas \
  --account-name mystorageaccount \
  --name my-container \
  --permissions rl \
  --expiry 2024-12-31T23:59:59Z
```

### 사용자 지정 스크립트

고급 사용 사례의 경우, signed URL 파일 생성을 위한 스크립트를 참고하세요:

* **AWS S3:** [generateS3SignedUrls.sh](https://raw.githubusercontent.com/roboflow/roboflow-python/main/scripts/generateS3SignedUrls.sh)
* **Google Cloud Storage:** [generateGCSSignedUrls.sh](https://github.com/roboflow/roboflow-python/blob/main/scripts/generateGCSSignedUrls.sh)
* **Azure Blob Storage:** [generateAzureSasUrls.sh](https://raw.githubusercontent.com/roboflow/roboflow-python/main/scripts/generateAzureSasUrls.sh)

## 모든 옵션 살펴보기

```bash
inference rf-cloud --help
inference rf-cloud data-staging --help
inference rf-cloud batch-processing --help
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.roboflow.com/roboflow/roboflow-ko/deploy/batch-processing/cli-usage.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
