데이터 세트 만들기 및 이미지 가져오기

데이터 세트에는 라벨과 경계 상자로 주석을 추가해 분류하려는 콘텐츠 유형의 대표 샘플이 있습니다. 데이터 세트는 모델 학습을 위한 입력으로 사용됩니다.

데이터세트 빌드의 주요 단계는 다음과 같습니다.

  1. 데이터세트를 만들고 기억하기 쉬운 이름을 지정합니다.
  2. 데이터세트로 데이터 예시를 가져옵니다.
  3. 이미지에서 경계 상자 및 라벨을 추가, 삭제, 수정하려면 가져온 이미지의 주석을 수정합니다(선택사항).

데이터 세트 만들기

AutoML API로 커스텀 모델을 만드는 첫 단계는 모델 학습용 데이터를 저장할 빈 데이터 세트를 만드는 것입니다.

AutoML Vision 객체 감지의 정식 버전(GA) 출시부터 이 요청은 장기 실행 작업의 ID를 반환합니다.

장기 실행 작업이 완료되면 이미지를 가져올 수 있습니다. 새로 만든 데이터 세트에는 이미지를 가져올 때까지는 어떤 데이터도 포함되지 않습니다.

데이터 세트로 이미지 가져오기나 모델 학습과 같은 다른 작업에 사용할 수 있도록 (응답에서) 새 데이터 세트의 데이터 세트 ID를 저장합니다.

웹 UI

AutoML Vision 객체 감지 UI를 사용하면 새 데이터 세트를 만들고 같은 페이지에서 이미지를 데이터 세트로 가져올 수 있습니다.

  1. AutoML Vision 객체 감지 UI를 엽니다.

    데이터 세트 페이지에는 현재 프로젝트를 위해 이전에 작성한 데이터 세트의 상태가 표시됩니다. 데이터세트 이미지 만들기

    다른 프로젝트를 위한 데이터세트를 추가하려면 제목 표시줄의 오른쪽 위에 있는 드롭다운 목록에서 프로젝트를 선택하세요.

  2. 제목 표시줄에서 새 데이터 세트 버튼을 클릭합니다.

  3. 새 데이터 세트 만들기 팝업 창에 데이터 세트의 이름을 입력하고 '데이터 세트 만들기' 옵션을 선택합니다.

    데이터 세트 만들기의 새 데이터 세트 이름 창

    빈 데이터 세트를 만들면 데이터 세트 세부정보 페이지의 가져오기 탭으로 이동합니다. 그러면 데이터 세트에 포함할 학습 이미지가 나열된 .csv 파일의 Google Cloud Storage 위치를 지정할 수 있습니다. 이러한 학습 이미지도 Google Cloud Storage 버킷에 저장되어야 합니다.

    데이터 세트 업로드 CSV 이미지 만들기

    데이터 세트를 만들려면 학습 이미지와 관련 경계 상자 및 라벨을 포함하는 csv 파일을 Google Cloud Storage에서 업로드해야 합니다.

    가져오기가 완료되면 UI에서 주석을 추가, 삭제 또는 수정할 수 있습니다.

  4. 가져오기를 선택합니다.

    데이터 세트 페이지가 다시 표시되며, 이미지를 가져오는 동안 데이터 세트에 진행률 애니메이션이 표시됩니다. 이 프로세스에는 예시 1,000개당 약 10분이 소요되지만 더 걸릴 수도, 덜 걸릴 수도 있습니다.

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • project-id: GCP 프로젝트 ID입니다.
  • display-name: 선택한 문자열 표시 이름입니다.

HTTP 메서드 및 URL:

POST https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/datasets

JSON 요청 본문:

{
  "displayName": "DISPLAY_NAME",
  "imageObjectDetectionDatasetMetadata": {
  }
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/datasets"

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/datasets" | Select-Object -Expand Content

다음과 비슷한 출력이 표시됩니다. 작업 ID(이 경우 IOD3819960680614725486)를 사용하여 작업 상태를 가져올 수 있습니다. 예시를 보려면 장기 실행 작업 다루기를 참조하세요.

{
  "name": "projects/PROJECT_ID/locations/us-central1/operations/IOD3819960680614725486",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2019-11-14T16:49:13.667526Z",
    "updateTime": "2019-11-14T16:49:13.667526Z",
    "createDatasetDetails": {}
  }
}

장기 실행 작업이 완료되면 동일한 작업 상태 요청으로 데이터 세트의 ID를 가져올 수 있습니다. 응답은 다음과 비슷하게 표시됩니다.

{
  "name": "projects/PROJECT_ID/locations/us-central1/operations/IOD3819960680614725486",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2019-11-14T16:49:13.667526Z",
    "updateTime": "2019-11-14T16:49:17.975314Z",
    "createDatasetDetails": {}
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.Dataset",
    "name": "projects/PROJECT_ID/locations/us-central1/datasets/IOD5496445433112696489"
  }
}

Go

이 샘플을 사용해 보기 전에 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	"cloud.google.com/go/automl/apiv1/automlpb"
)

// visionObjectDetectionCreateDataset creates a dataset for image object detection.
func visionObjectDetectionCreateDataset(w io.Writer, projectID string, location string, datasetName string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// datasetName := "dataset_display_name"

	ctx := context.Background()
	client, err := automl.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	req := &automlpb.CreateDatasetRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		Dataset: &automlpb.Dataset{
			DisplayName: datasetName,
			DatasetMetadata: &automlpb.Dataset_ImageObjectDetectionDatasetMetadata{
				ImageObjectDetectionDatasetMetadata: &automlpb.ImageObjectDetectionDatasetMetadata{},
			},
		},
	}

	op, err := client.CreateDataset(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateDataset: %w", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())

	dataset, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Wait: %w", err)
	}

	fmt.Fprintf(w, "Dataset name: %v\n", dataset.GetName())

	return nil
}

Java

이 샘플을 사용해 보기 전에 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.Dataset;
import com.google.cloud.automl.v1.ImageObjectDetectionDatasetMetadata;
import com.google.cloud.automl.v1.LocationName;
import com.google.cloud.automl.v1.OperationMetadata;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

class VisionObjectDetectionCreateDataset {

  static void createDataset() throws IOException, ExecutionException, InterruptedException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String displayName = "YOUR_DATASET_NAME";
    createDataset(projectId, displayName);
  }

  // Create a dataset
  static void createDataset(String projectId, String displayName)
      throws IOException, ExecutionException, InterruptedException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (AutoMlClient client = AutoMlClient.create()) {
      // A resource that represents Google Cloud Platform location.
      LocationName projectLocation = LocationName.of(projectId, "us-central1");

      ImageObjectDetectionDatasetMetadata metadata =
          ImageObjectDetectionDatasetMetadata.newBuilder().build();
      Dataset dataset =
          Dataset.newBuilder()
              .setDisplayName(displayName)
              .setImageObjectDetectionDatasetMetadata(metadata)
              .build();
      OperationFuture<Dataset, OperationMetadata> future =
          client.createDatasetAsync(projectLocation, dataset);

      Dataset createdDataset = future.get();

      // Display the dataset information.
      System.out.format("Dataset name: %s\n", createdDataset.getName());
      // To get the dataset id, you have to parse it out of the `name` field. As dataset Ids are
      // required for other methods.
      // Name Form: `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}`
      String[] names = createdDataset.getName().split("/");
      String datasetId = names[names.length - 1];
      System.out.format("Dataset id: %s\n", datasetId);
    }
  }
}

Node.js

이 샘플을 사용해 보기 전에 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const displayName = 'YOUR_DISPLAY_NAME';

// Imports the Google Cloud AutoML library
const {AutoMlClient} = require('@google-cloud/automl').v1;

// Instantiates a client
const client = new AutoMlClient();

async function createDataset() {
  // Construct request
  const request = {
    parent: client.locationPath(projectId, location),
    dataset: {
      displayName: displayName,
      imageObjectDetectionDatasetMetadata: {},
    },
  };

  // Create dataset
  const [operation] = await client.createDataset(request);

  // Wait for operation to complete.
  const [response] = await operation.promise();

  console.log(`Dataset name: ${response.name}`);
  console.log(`
    Dataset id: ${
      response.name
        .split('/')
        [response.name.split('/').length - 1].split('\n')[0]
    }`);
}

createDataset();

Python

이 샘플을 사용해 보기 전에 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"
# display_name = "your_datasets_display_name"

client = automl.AutoMlClient()

# A resource that represents Google Cloud Platform location.
project_location = f"projects/{project_id}/locations/us-central1"
metadata = automl.ImageObjectDetectionDatasetMetadata()
dataset = automl.Dataset(
    display_name=display_name,
    image_object_detection_dataset_metadata=metadata,
)

# Create a dataset with the dataset metadata in the region.
response = client.create_dataset(parent=project_location, dataset=dataset)

created_dataset = response.result()

# Display the dataset information
print(f"Dataset name: {created_dataset.name}")
print("Dataset id: {}".format(created_dataset.name.split("/")[-1]))

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 다음 .NET용 AutoML Vision 객체 감지 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 다음 PHP용 AutoML Vision 객체 감지 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 AutoML Vision 객체 감지 참조 문서를 참조하세요.

데이터세트로 이미지 가져오기

데이터 세트를 만든 후에는 Google Cloud Storage 버킷에 저장된 CSV 파일에서 이미지의 라벨이 지정된 경계 상자 및 이미지 URI를 가져올 수 있습니다.

데이터 준비 및 가져올 CSV 파일 만들기에 대한 자세한 내용은 학습 데이터 준비를 참조하세요. 이미지를 가져온 후 이미지 주석 수정에 대한 자세한 내용은 가져온 학습 이미지에 주석 달기를 참조하십시오.

이미 학습 이미지가 포함된 데이터 세트 또는 빈 데이터 세트로는 이미지를 가져올 수 없습니다.

웹 UI

UI에서 AutoML Vision 객체 감지 데이터 세트 만들기와 이미지 가져오기는 연속 단계로 결합됩니다.

빈 데이터 세트로 이미지 가져오기:

후속 데이터 세트를 만드는 경우 빈 데이터 세트를 만든 후 바로 이미지를 가져올지 묻는 메시지가 표시됩니다. 단, 이 가져오기 단계는 필요하지 않습니다.

빈 데이터 세트로 이미지를 가져오려면 다음 단계를 완료하세요.

  1. 데이터세트 페이지에서 빈 데이터세트를 선택합니다.

    데이터 세트 이미지 나열

  2. 가져오기 페이지에서 .csv 파일의 Google Cloud Storage 위치를 추가합니다. Google Cloud Storage에서 .csv 파일의 위치를 지정한 후 가져오기를 선택하여 파일 가져오기 프로세스를 시작합니다.

    데이터 세트 업로드 CSV 이미지 만들기

비어 있지 않은 데이터 세트로 이미지 가져오기:

이미 학습 이미지가 포함된 데이터 세트에 학습 이미지를 추가할 수도 있습니다.

비어 있지 않은 데이터 세트에 학습 이미지를 추가하려면 다음 단계를 완료하세요.

  1. 데이터세트 페이지에서 비어 있지 않은 데이터세트를 선택합니다.

    데이터 세트 이미지 나열

    비어 있지 않은 데이터 세트를 선택하면 데이터 세트 세부정보 페이지로 이동합니다.

    라벨 학습 이미지 UI

  2. 데이터세트 세부정보 페이지에서 가져오기 탭을 선택합니다.

    비어 있지 않은 데이터세트로 가져오기

    가져오기 탭을 선택하면 데이터 세트 만들기 페이지로 이동합니다. 그러면 .csv 파일의 Google Cloud Storage 위치를 지정한 후 가져오기를 선택하여 이미지 가져오기 프로세스를 시작합니다.

    데이터 세트 업로드 CSV 이미지 만들기

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • project-id: GCP 프로젝트 ID입니다.
  • dataset-id: 데이터 세트의 ID입니다. ID는 데이터 세트 이름의 마지막 요소입니다. 예를 들면 다음과 같습니다.
    • 데이터 세트 이름: projects/project-id/locations/location-id/datasets/3104518874390609379
    • 데이터 세트 ID: 3104518874390609379
  • input-storage-path: Google Cloud Storage에 저장된 CSV 파일의 경로입니다. 요청하는 사용자에게 적어도 버킷에 대한 읽기 권한이 있어야 합니다.

HTTP 메서드 및 URL:

POST https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/datasets/DATASET_ID:importData

JSON 요청 본문:

{
  "inputConfig": {
    "gcsSource": {
       "inputUris": ["INPUT_STORAGE_PATH"]
    }
  }
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/datasets/DATASET_ID:importData"

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/datasets/DATASET_ID:importData" | Select-Object -Expand Content

다음과 비슷한 출력이 표시됩니다. 작업 ID를 사용하여 작업 상태를 가져올 수 있습니다. 예시를 보려면 장기 실행 작업 다루기를 참조하세요.

{
  "name": "projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2018-10-29T15:56:29.176485Z",
    "updateTime": "2018-10-29T15:56:29.176485Z",
    "importDataDetails": {}
  }
}

Go

이 샘플을 사용해 보기 전에 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	"cloud.google.com/go/automl/apiv1/automlpb"
)

// importDataIntoDataset imports data into a dataset.
func importDataIntoDataset(w io.Writer, projectID string, location string, datasetID string, inputURI string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// datasetID := "TRL123456789..."
	// inputURI := "gs://BUCKET_ID/path_to_training_data.csv"

	ctx := context.Background()
	client, err := automl.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	req := &automlpb.ImportDataRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/datasets/%s", projectID, location, datasetID),
		InputConfig: &automlpb.InputConfig{
			Source: &automlpb.InputConfig_GcsSource{
				GcsSource: &automlpb.GcsSource{
					InputUris: []string{inputURI},
				},
			},
		},
	}

	op, err := client.ImportData(ctx, req)
	if err != nil {
		return fmt.Errorf("ImportData: %w", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())

	if err := op.Wait(ctx); err != nil {
		return fmt.Errorf("Wait: %w", err)
	}

	fmt.Fprintf(w, "Data imported.\n")

	return nil
}

Java

이 샘플을 사용해 보기 전에 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.DatasetName;
import com.google.cloud.automl.v1.GcsSource;
import com.google.cloud.automl.v1.InputConfig;
import com.google.cloud.automl.v1.OperationMetadata;
import com.google.protobuf.Empty;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

class ImportDataset {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String datasetId = "YOUR_DATASET_ID";
    String path = "gs://BUCKET_ID/path_to_training_data.csv";
    importDataset(projectId, datasetId, path);
  }

  // Import a dataset
  static void importDataset(String projectId, String datasetId, String path)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (AutoMlClient client = AutoMlClient.create()) {
      // Get the complete path of the dataset.
      DatasetName datasetFullId = DatasetName.of(projectId, "us-central1", datasetId);

      // Get multiple Google Cloud Storage URIs to import data from
      GcsSource gcsSource =
          GcsSource.newBuilder().addAllInputUris(Arrays.asList(path.split(","))).build();

      // Import data from the input URI
      InputConfig inputConfig = InputConfig.newBuilder().setGcsSource(gcsSource).build();
      System.out.println("Processing import...");

      // Start the import job
      OperationFuture<Empty, OperationMetadata> operation =
          client.importDataAsync(datasetFullId, inputConfig);

      System.out.format("Operation name: %s%n", operation.getName());

      // If you want to wait for the operation to finish, adjust the timeout appropriately. The
      // operation will still run if you choose not to wait for it to complete. You can check the
      // status of your operation using the operation's name.
      Empty response = operation.get(45, TimeUnit.MINUTES);
      System.out.format("Dataset imported. %s%n", response);
    } catch (TimeoutException e) {
      System.out.println("The operation's polling period was not long enough.");
      System.out.println("You can use the Operation's name to get the current status.");
      System.out.println("The import job is still running and will complete as expected.");
      throw e;
    }
  }
}

Node.js

이 샘플을 사용해 보기 전에 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const datasetId = 'YOUR_DISPLAY_ID';
// const path = 'gs://BUCKET_ID/path_to_training_data.csv';

// Imports the Google Cloud AutoML library
const {AutoMlClient} = require('@google-cloud/automl').v1;

// Instantiates a client
const client = new AutoMlClient();

async function importDataset() {
  // Construct request
  const request = {
    name: client.datasetPath(projectId, location, datasetId),
    inputConfig: {
      gcsSource: {
        inputUris: path.split(','),
      },
    },
  };

  // Import dataset
  console.log('Proccessing import');
  const [operation] = await client.importData(request);

  // Wait for operation to complete.
  const [response] = await operation.promise();
  console.log(`Dataset imported: ${response}`);
}

importDataset();

Python

이 샘플을 사용해 보기 전에 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"
# dataset_id = "YOUR_DATASET_ID"
# path = "gs://YOUR_BUCKET_ID/path/to/data.csv"

client = automl.AutoMlClient()
# Get the full path of the dataset.
dataset_full_id = client.dataset_path(project_id, "us-central1", dataset_id)
# Get the multiple Google Cloud Storage URIs
input_uris = path.split(",")
gcs_source = automl.GcsSource(input_uris=input_uris)
input_config = automl.InputConfig(gcs_source=gcs_source)
# Import data from the input URI
response = client.import_data(name=dataset_full_id, input_config=input_config)

print("Processing import...")
print(f"Data imported. {response.result()}")

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 다음 .NET용 AutoML Vision 객체 감지 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 다음 PHP용 AutoML Vision 객체 감지 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 AutoML Vision 객체 감지 참조 문서를 참조하세요.

가져온 학습 이미지에 주석 달기 주제에서는 UI의 이미지에 경계 상자와 라벨을 수동으로 추가하는 방법과 라벨 통계를 나열하는 방법을 설명합니다.

데이터 세트 관리 주제에는 데이터 세트 나열, 가져오기, 내보내기, 삭제 방법과 같은 데이터 세트 리소스 사용에 대한 자세한 정보가 포함됩니다.

장기 실행 작업 다루기

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • project-id: GCP 프로젝트 ID입니다.
  • operation-id: 작업의 ID입니다. ID는 작업 이름의 마지막 요소입니다. 예를 들면 다음과 같습니다.
    • 작업 이름: projects/project-id/locations/location-id/operations/IOD5281059901324392598
    • 작업 ID: IOD5281059901324392598

HTTP 메서드 및 URL:

GET https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

다음 명령어를 실행합니다.

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
"https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID"

PowerShell

다음 명령어를 실행합니다.

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID" | Select-Object -Expand Content
가져오기 작업이 완료되면 다음과 유사한 출력이 표시됩니다.
{
  "name": "projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2018-10-29T15:56:29.176485Z",
    "updateTime": "2018-10-29T16:10:41.326614Z",
    "importDataDetails": {}
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.protobuf.Empty"
  }
}

모델 만들기 작업이 완료되면 다음과 유사한 출력이 표시됩니다.

{
  "name": "projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2019-07-22T18:35:06.881193Z",
    "updateTime": "2019-07-22T19:58:44.972235Z",
    "createModelDetails": {}
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.Model",
    "name": "projects/PROJECT_ID/locations/us-central1/models/MODEL_ID"
  }
}

Go

이 샘플을 사용해 보기 전에 API 및 참조 > 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	"cloud.google.com/go/automl/apiv1/automlpb"
)

// getOperationStatus gets an operation's status.
func getOperationStatus(w io.Writer, projectID string, location string, datasetID string, modelName string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// datasetID := "ICN123456789..."
	// modelName := "model_display_name"

	ctx := context.Background()
	client, err := automl.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	req := &automlpb.CreateModelRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		Model: &automlpb.Model{
			DisplayName: modelName,
			DatasetId:   datasetID,
			ModelMetadata: &automlpb.Model_ImageClassificationModelMetadata{
				ImageClassificationModelMetadata: &automlpb.ImageClassificationModelMetadata{
					TrainBudgetMilliNodeHours: 1000, // 1000 milli-node hours are 1 hour
				},
			},
		},
	}

	op, err := client.CreateModel(ctx, req)
	if err != nil {
		return err
	}
	fmt.Fprintf(w, "Name: %v\n", op.Name())

	// Wait for the longrunning operation complete.
	resp, err := op.Wait(ctx)
	if err != nil && !op.Done() {
		fmt.Println("failed to fetch operation status", err)
		return err
	}
	if err != nil && op.Done() {
		fmt.Println("operation completed with error", err)
		return err
	}
	fmt.Fprintf(w, "Response: %v\n", resp)

	return nil
}

Java

이 샘플을 사용해 보기 전에 API 및 참조 > 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

import com.google.cloud.automl.v1.AutoMlClient;
import com.google.longrunning.Operation;
import java.io.IOException;

class GetOperationStatus {

  static void getOperationStatus() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String operationFullId = "projects/[projectId]/locations/us-central1/operations/[operationId]";
    getOperationStatus(operationFullId);
  }

  // Get the status of an operation
  static void getOperationStatus(String operationFullId) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (AutoMlClient client = AutoMlClient.create()) {
      // Get the latest state of a long-running operation.
      Operation operation = client.getOperationsClient().getOperation(operationFullId);

      // Display operation details.
      System.out.println("Operation details:");
      System.out.format("\tName: %s\n", operation.getName());
      System.out.format("\tMetadata Type Url: %s\n", operation.getMetadata().getTypeUrl());
      System.out.format("\tDone: %s\n", operation.getDone());
      if (operation.hasResponse()) {
        System.out.format("\tResponse Type Url: %s\n", operation.getResponse().getTypeUrl());
      }
      if (operation.hasError()) {
        System.out.println("\tResponse:");
        System.out.format("\t\tError code: %s\n", operation.getError().getCode());
        System.out.format("\t\tError message: %s\n", operation.getError().getMessage());
      }
    }
  }
}

Node.js

이 샘플을 사용해 보기 전에 API 및 참조 > 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const operationId = 'YOUR_OPERATION_ID';

// Imports the Google Cloud AutoML library
const {AutoMlClient} = require('@google-cloud/automl').v1;

// Instantiates a client
const client = new AutoMlClient();

async function getOperationStatus() {
  // Construct request
  const request = {
    name: `projects/${projectId}/locations/${location}/operations/${operationId}`,
  };

  const [response] = await client.operationsClient.getOperation(request);

  console.log(`Name: ${response.name}`);
  console.log('Operation details:');
  console.log(`${response}`);
}

getOperationStatus();

Python

이 샘플을 사용해 보기 전에 API 및 참조 > 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# operation_full_id = \
#     "projects/[projectId]/locations/us-central1/operations/[operationId]"

client = automl.AutoMlClient()
# Get the latest state of a long-running operation.
response = client._transport.operations_client.get_operation(operation_full_id)

print(f"Name: {response.name}")
print("Operation details:")
print(response)

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 다음 .NET용 AutoML Vision 참고 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 다음 PHP용 AutoML Vision 참고 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 AutoML Vision 참조 문서를 참조하세요.