# 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 key를 찾는 데 도움이 필요하면 다음을 참조하세요 [authentication guide](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/`

파일을 필터링하기 위해 glob 패턴을 포함할 수 있습니다:

* `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 파일의 경로 또는 URL, 혹은 그러한 파일을 가리키는 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 %}

## Staged Data 검사

```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 %}

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

start 명령은 **Job ID**를 출력합니다. 이를 사용해 상태를 확인하세요:

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

## 결과 내보내기

작업 세부 정보에는 **output batch ID**가 포함됩니다. 이를 사용해 결과를 내보내세요:

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

## Webhook 자동화

상태를 폴링하는 대신, 수집 또는 처리가 완료되었을 때 알림을 받기 위해 webhook을 사용할 수 있습니다.

### 데이터 수집 Webhook

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
}
```

### 작업 완료 Webhook

추가하세요 `--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 Token(권장):**

```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"
```

**Account Key:**

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

Azure CLI를 통해 SAS token 생성:

```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
```
