# Google Cloud Storage

Google Cloud Storage에서 이미지 데이터 저장을 다루고 Roboflow에 업로드할 때, 일반적으로 두 가지 विकल्प이 있습니다: 서명된 URL(signed URLs)을 사용하거나, 수동으로 이미지를 로컬에 다운로드(gsutil CLI를 통해)한 뒤 로컬에서 업로드하는 방법입니다. 이 방법들 중 무엇을 선택할지는 데이터 처리 및 관리에 대한 특정 요구사항에 따라 달라집니다.

* **서명된 URL(Signed URLs)**: 이 방법은 이미지를 로컬 머신으로 다운로드하는 데 따르는 추가 단계와 시간 소모를 피하고 싶을 때 특히 유리합니다. 서명된 URL을 사용하면 이미지를 로컬에 저장할 필요 없이 Google Cloud Storage에서 Roboflow API로 이미지 데이터를 직접 업로드할 수 있습니다. 그 결과 처리 속도는 더 빨라지고 로컬 시스템의 부담은 줄어듭니다.
* **CLI로 로컬에서**: 어떤 경우에는 먼저 이미지를 로컬 환경으로 다운로드하는 편을 선호할 수도 있습니다. 예를 들어, Roboflow에 업로드하기 전에 이미지를 전처리하거나 수동으로 확인해야 한다면 로컬 복사본이 있으면 유용합니다.

적절한 방법을 선택하는 것은 데이터 전송 속도, 전처리 필요성, 이미지의 수동 검토와 같은 구체적인 사용 사례 요구사항에 따라 달라집니다.

### Google Cloud JSON 키

해당 버킷에 대한 적절한 권한을 가진 서비스 계정을 만들고 JSON 키 파일을 다운로드하세요. 이 파일에는 애플리케이션 인증에 사용되는 자격 증명이 들어 있습니다.

### 옵션 1: 서명된 URL을 통해 업로드:

Python에서 Google Cloud SDK를 사용하여 Google Cloud Storage 버킷에 있는 이미지의 서명된 URL을 생성할 수 있습니다.

```python
def get_gcs_signed_url(bucket_name: str, blob_name: str) -> str:
    """GCS 객체에 대한 서명된 URL을 생성합니다."""
    storage_client = storage.Client.from_service_account_json(GOOGLE_APPLICATION_CREDENTIALS)
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.get_blob(blob_name)
    
    url = blob.generate_signed_url(
        version="v4",
        expiration=3600,  # 1시간(초 단위)
        method="GET"
    )
    return url
```

위 코드 스니펫에서는 Google Cloud Storage 버킷 이름과 blob 이름이 필요합니다. 이미지의 서명된 URL이 생성되어 반환됩니다.

이를 바탕으로, 버킷에 있는 사용 가능한 모든 객체를 가져온 다음 API를 통해 Roboflow에 업로드하는 완전한 솔루션을 만들 수 있습니다. 이 솔루션의 개요는 아래에서 볼 수 있습니다:

```python
from google.cloud import storage
import requests
import urllib.parse

# ************* 이 변수들을 설정하세요 *************
GCS_BUCKET_NAME = "YOUR_GCS_BUCKET_NAME"
ROBOFLOW_API_KEY = "YOUR_ROBOFLOW_API_KEY"
ROBOFLOW_PROJECT_NAME = "YOUR_ROBOFLOW_PROJECT_NAME"
GOOGLE_APPLICATION_CREDENTIALS = "path/to/your-service-account-file.json"
# ***********************************************

def get_gcs_signed_url(bucket_name: str, blob_name: str) -> str:
    """GCS 객체에 대한 서명된 URL을 생성합니다."""
    storage_client = storage.Client.from_service_account_json(GOOGLE_APPLICATION_CREDENTIALS)
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.get_blob(blob_name)
    
    url = blob.generate_signed_url(
        version="v4",
        expiration=3600,  # 1시간(초 단위)
        method="GET"
    )
    return url

def get_gcs_objects(bucket_name: str) -> list:
    """지정된 GCS 버킷에 있는 객체 키 목록을 가져옵니다."""
    storage_client = storage.Client.from_service_account_json(GOOGLE_APPLICATION_CREDENTIALS)
    bucket = storage_client.get_bucket(bucket_name)
    blobs = bucket.list_blobs()

    object_names = []
    for blob in blobs:
        object_names.append(blob.name)
    return object_names

def upload_to_roboflow(api_key: str, project_name: str, presigned_url: str, img_name='', split="train"):
    """이미지를 Roboflow에 업로드합니다."""
    API_URL = "https://api.roboflow.com"
    if img_name == '':
        img_name = presigned_url.split("/")[-1]

    upload_url = "".join([
        API_URL + "/dataset/" + project_name + "/upload",
        "?api_key=" + api_key,
        "&name=" + img_name,
        "&split=" + split,
        "&image=" + urllib.parse.quote_plus(presigned_url),
    ])
    response = requests.post(upload_url)

    # 응답 코드 확인
    if response.status_code == 200:
        print(f"{img_name}을(를) {project_name}에 성공적으로 업로드했습니다")
        return True
    else:
        print(f"{img_name} 업로드에 실패했습니다. 오류: {response.content.decode('utf-8')}")
        return False

if __name__ == "__main__":
    # 사용 가능한 blob 목록 가져오기
    available_blobs = get_gcs_objects(GCS_BUCKET_NAME)
    
    # 선택 사항: 여기서 blob 필터링
    # 예: available_blobs = [blob for blob in available_blobs if "some_condition"]
    
    # blob을 Roboflow에 업로드
    for blob in available_blobs:
        blob_url = get_gcs_signed_url(GCS_BUCKET_NAME, blob)
        upload_to_roboflow(ROBOFLOW_API_KEY, ROBOFLOW_PROJECT_NAME, blob_url)

```

### 옵션 2: GCP에서 데이터를 로컬로 다운로드

GCP에서 데이터를 다운로드하려면 먼저 GCP CLI를 설치하세요. 그런 다음 GCP 사용자 계정으로 인증합니다.

이미지 또는 이미지 폴더를 다운로드하려면 다음 명령을 사용하세요:

```bash
gsutil cp -r gs://mybucket/folder .
```

다음을 `mybucket` GCP 스토리지 버킷의 이름으로 바꾸고, `folder` 를 복사하려는 파일 또는 폴더의 대상으로 바꾸세요. 이 명령은 대상 파일 또는 폴더를 현재 작업 디렉터리(`.`).

### 데이터를 Roboflow에 업로드

이제 데이터를 다운로드했으므로, 이를 다음을 사용해 Roboflow에 업로드할 수 있습니다. [업로드 웹 인터페이스](/roboflow/roboflow-ko/datasets/adding-data.md#upload-data-with-the-web-interface) 또는 [Roboflow CLI](/developer/command-line-interface/upload-a-dataset.md).

### 도 참고하세요

* [Roboflow 프로젝트 ID 가져오기](https://docs.roboflow.com/api-reference/workspace-and-project-ids)


---

# 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/datasets/adding-data/upload-data-from-aws-gcp-and-azure/google-cloud-storage.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.
