제품 세트 만들기

제품 세트는 제품 그룹의 단순한 컨테이너입니다.

빈 제품 세트 만들기

모든 품목에 하나의 상품 세트만 사용하고 필요에 따라 테스트용 추가 제품 세트를 만드는 것이 좋습니다. 다음 코드 샘플에서는 빈 상품 세트를 만드는 방법을 보여줍니다.

REST

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

  • PROJECT_ID: Google Cloud 프로젝트 ID입니다.
  • LOCATION_ID: 유효한 위치 식별자입니다. 유효한 위치 식별자는 us-west1, us-east1, europe-west1, asia-east1입니다.
  • DISPLAY_NAME: 선택한 문자열 표시 이름입니다.

HTTP 메서드 및 URL:

POST https://vision.googleapis.com/v1/projects/project-id/locations/location-id/productSets

JSON 요청 본문:

{
  "displayName": "display-name"
}

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

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://vision.googleapis.com/v1/projects/project-id/locations/location-id/productSets"

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://vision.googleapis.com/v1/projects/project-id/locations/location-id/productSets" | Select-Object -Expand Content

요청이 성공하면 서버가 200 OK HTTP 상태 코드와 응답을 JSON 형식으로 반환합니다.

다음과 비슷한 출력이 표시됩니다. 제품 세트 ID(이 경우 b6d809615b6dd675)를 사용하여 제품 세트의 다른 작업을 수행할 수 있습니다.

{
  "name": "projects/project-id/locations/location-id/productSets/b6d809615b6dd675",
  "displayName": "new-product-set"
}

Go

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Go API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	"cloud.google.com/go/vision/v2/apiv1/visionpb"
)

// createProductSet creates a product set.
func createProductSet(w io.Writer, projectID string, location string, productSetID string, productSetDisplayName string) error {
	ctx := context.Background()
	c, err := vision.NewProductSearchClient(ctx)
	if err != nil {
		return fmt.Errorf("NewProductSearchClient: %w", err)
	}
	defer c.Close()

	req := &visionpb.CreateProductSetRequest{
		Parent:       fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		ProductSetId: productSetID,
		ProductSet: &visionpb.ProductSet{
			DisplayName: productSetDisplayName,
		},
	}

	resp, err := c.CreateProductSet(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateProductSet: %w", err)
	}

	fmt.Fprintf(w, "Product set name: %s\n", resp.Name)

	return nil
}

Java

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Java API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

/**
 * Create a product set
 *
 * @param projectId - Id of the project.
 * @param computeRegion - Region name.
 * @param productSetId - Id of the product set.
 * @param productSetDisplayName - Display name of the product set.
 * @throws IOException - on I/O errors.
 */
public static void createProductSet(
    String projectId, String computeRegion, String productSetId, String productSetDisplayName)
    throws IOException {
  try (ProductSearchClient client = ProductSearchClient.create()) {

    // A resource that represents Google Cloud Platform location.
    String formattedParent = LocationName.format(projectId, computeRegion);

    // Create a product set with the product set specification in the region.
    ProductSet myProductSet =
        ProductSet.newBuilder().setDisplayName(productSetDisplayName).build();
    CreateProductSetRequest request =
        CreateProductSetRequest.newBuilder()
            .setParent(formattedParent)
            .setProductSet(myProductSet)
            .setProductSetId(productSetId)
            .build();
    ProductSet productSet = client.createProductSet(request);
    // Display the product set information
    System.out.println(String.format("Product set name: %s", productSet.getName()));
  }
}

Node.js

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Node.js API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

// Imports the Google Cloud client library
const vision = require('@google-cloud/vision');

// Creates a client
const client = new vision.ProductSearchClient();

async function createProductSet() {
  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const projectId = 'Your Google Cloud project Id';
  // const location = 'A compute region name';
  // const productSetId = 'Id of the product set';
  // const productSetDisplayName = 'Display name of the product set';

  // Resource path that represents Google Cloud Platform location.
  const locationPath = client.locationPath(projectId, location);

  const productSet = {
    displayName: productSetDisplayName,
  };

  const request = {
    parent: locationPath,
    productSet: productSet,
    productSetId: productSetId,
  };

  const [createdProductSet] = await client.createProductSet(request);
  console.log(`Product Set name: ${createdProductSet.name}`);
}
createProductSet();

Python

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Python API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

from google.cloud import vision

def create_product_set(project_id, location, product_set_id, product_set_display_name):
    """Create a product set.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        product_set_id: Id of the product set.
        product_set_display_name: Display name of the product set.
    """
    client = vision.ProductSearchClient()

    # A resource that represents Google Cloud Platform location.
    location_path = f"projects/{project_id}/locations/{location}"

    # Create a product set with the product set specification in the region.
    product_set = vision.ProductSet(display_name=product_set_display_name)

    # The response is the product set with `name` populated.
    response = client.create_product_set(
        parent=location_path, product_set=product_set, product_set_id=product_set_id
    )

    # Display the product set information.
    print(f"Product set name: {response.name}")

추가 언어

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

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

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

일괄 가져오기를 사용하여 제품으로 제품 세트 만들기

또한 일괄 가져오기 기능을 사용하여 동시에 제품 세트를 만들고 여러 제품 및 참조 이미지를 만들 수 있습니다.

제품 세트, 제품, 참조 이미지에 대한 다양한 참조는 모두 사용자가 사용하는 일괄 가져오기 CSV에서 설정됩니다. 자세한 내용은 일괄 가져오기 CSV 형식 지정을 참조하세요.

다음 코드를 실행하여 일괄 가져오기를 수행합니다.

REST

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

  • PROJECT_ID: Google Cloud 프로젝트 ID입니다.
  • LOCATION_ID: 유효한 위치 식별자입니다. 유효한 위치 식별자는 us-west1, us-east1, europe-west1, asia-east1입니다.
  • STORAGE_PATH: 입력 CSV 파일이 저장된 Cloud Storage 버킷/디렉터리입니다. 요청하는 사용자에게 적어도 버킷에 대한 읽기 권한이 있어야 합니다.

HTTP 메서드 및 URL:

POST https://vision.googleapis.com/v1/projects/project-id/locations/location-id/productSets:import

JSON 요청 본문:

{
  "inputConfig": {
    "gcsSource": {
      "csvFileUri": "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://vision.googleapis.com/v1/projects/project-id/locations/location-id/productSets:import"

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://vision.googleapis.com/v1/projects/project-id/locations/location-id/productSets:import" | Select-Object -Expand Content

다음과 비슷한 출력이 표시됩니다. 작업 ID(이 경우 f10f34e32c40a710)를 사용하여 작업 상태를 가져올 수 있습니다. 예를 들어 작업 상태 가져오기를 살펴보면 다음과 같습니다.

{
  "name": "projects/project-id/locations/location-id/operations/f10f34e32c40a710"
}

장기 실행 작업이 완료되면 가져오기 작업의 세부정보를 가져올 수 있습니다. 응답은 다음과 비슷하게 표시됩니다.

{
  "name": "locations/location-id/operations/f10f34e32c40a710",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.vision.v1.BatchOperationMetadata",
    "state": "SUCCESSFUL",
    "submitTime": "2019-12-06T21:16:04.476466873Z",
    "endTime": "2019-12-06T21:16:40.594258084Z"
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.vision.v1.ImportProductSetsResponse",
    "referenceImages": [
      {
        "name": "projects/project-id/locations/location-id/products/product_id0/referenceImages/image0",
        "uri": "gs://my-storage-bucket/img_039.jpg"
      },
      {
        "name": "projects/project-id/locations/location-id/products/product_id1/referenceImages/image1",
        "uri": "gs://my-storage-bucket/img_105.jpg"
      },
      {
        "name": "projects/project-id/locations/location-id/products/product_id2/referenceImages/image2",
        "uri": "gs://my-storage-bucket/img_224.jpg"
      },
      {
        "name": "projects/project-id/locations/location-id/products/product_id3/referenceImages/image3",
        "uri": "gs://my-storage-bucket/img_385.jpg"
      }
    ],
    "statuses": [
      {},
      {},
      {},
      {}
    ]
  }
}

Go

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Go API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.



import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	"cloud.google.com/go/vision/v2/apiv1/visionpb"
)

// importProductSets creates a product set using information in a csv file on GCS.
func importProductSets(w io.Writer, projectID string, location string, gcsURI string) error {
	ctx := context.Background()
	c, err := vision.NewProductSearchClient(ctx)
	if err != nil {
		return fmt.Errorf("NewProductSearchClient: %w", err)
	}
	defer c.Close()

	req := &visionpb.ImportProductSetsRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		InputConfig: &visionpb.ImportProductSetsInputConfig{
			Source: &visionpb.ImportProductSetsInputConfig_GcsSource{
				GcsSource: &visionpb.ImportProductSetsGcsSource{
					CsvFileUri: gcsURI,
				},
			},
		},
	}

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

	fmt.Fprintf(w, "Processing operation name: %s\n", op.Name())

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

	fmt.Fprintf(w, "processing done.\n")

	for i, status := range resp.Statuses {
		// `0` is the coee for OK in google.rpc.code
		fmt.Fprintf(w, "Status of processing line %d of the csv: %d\n", i, status.Code)

		if status.Code == 0 {
			fmt.Fprintf(w, "Reference image name: %s\n", resp.ReferenceImages[i].Name)
		} else {
			fmt.Fprintf(w, "Status code not OK: %s\n", status.Message)
		}
	}

	return nil
}

Java

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Java API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

/**
 * Import images of different products in the product set.
 *
 * @param projectId - Id of the project.
 * @param computeRegion - Region name.
 * @param gcsUri - Google Cloud Storage URI.Target files must be in Product Search CSV format.
 * @throws Exception - on client errors.
 */
public static void importProductSets(String projectId, String computeRegion, String gcsUri)
    throws Exception {
  try (ProductSearchClient client = ProductSearchClient.create()) {

    // A resource that represents Google Cloud Platform location.
    String formattedParent = LocationName.format(projectId, computeRegion);
    Builder gcsSource = ImportProductSetsGcsSource.newBuilder().setCsvFileUri(gcsUri);

    // Set the input configuration along with Google Cloud Storage URI
    ImportProductSetsInputConfig inputConfig =
        ImportProductSetsInputConfig.newBuilder().setGcsSource(gcsSource).build();

    // Import the product sets from the input URI.
    OperationFuture<ImportProductSetsResponse, BatchOperationMetadata> response =
        client.importProductSetsAsync(formattedParent, inputConfig);

    System.out.println(String.format("Processing operation name: %s", response.getName()));
    ImportProductSetsResponse results = response.get();
    System.out.println("Processing done.");
    System.out.println("Results of the processing:");

    for (int i = 0; i < results.getStatusesCount(); i++) {
      System.out.println(
          String.format(
              "Status of processing line %s of the csv: %s", i, results.getStatuses(i)));
      // Check the status of reference image.
      if (results.getStatuses(i).getCode() == 0) {
        ReferenceImage referenceImage = results.getReferenceImages(i);
        System.out.println(referenceImage);
      } else {
        System.out.println("No reference image.");
      }
    }
  }
}

Node.js

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Node.js API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

// Imports the Google Cloud client library
const vision = require('@google-cloud/vision');
// Creates a client
const client = new vision.ProductSearchClient();

async function importProductSets() {
  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const projectId = 'Your Google Cloud project Id';
  // const location = 'A compute region name';
  // const gcsUri = 'Google Cloud Storage URI. Target files must be in Product Search CSV format';

  // A resource that represents Google Cloud Platform location.
  const projectLocation = client.locationPath(projectId, location);

  // Set the input configuration along with Google Cloud Storage URI
  const inputConfig = {
    gcsSource: {
      csvFileUri: gcsUri,
    },
  };

  // Import the product sets from the input URI.
  const [response, operation] = await client.importProductSets({
    parent: projectLocation,
    inputConfig: inputConfig,
  });

  console.log('Processing operation name: ', operation.name);

  // synchronous check of operation status
  const [result] = await response.promise();
  console.log('Processing done.');
  console.log('Results of the processing:');

  for (const i in result.statuses) {
    console.log(
      'Status of processing ',
      i,
      'of the csv:',
      result.statuses[i]
    );

    // Check the status of reference image
    if (result.statuses[i].code === 0) {
      console.log(result.referenceImages[i]);
    } else {
      console.log('No reference image.');
    }
  }
}
importProductSets();

Python

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Python API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

def import_product_sets(project_id, location, gcs_uri):
    """Import images of different products in the product set.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        gcs_uri: Google Cloud Storage URI.
            Target files must be in Product Search CSV format.
    """
    client = vision.ProductSearchClient()

    # A resource that represents Google Cloud Platform location.
    location_path = f"projects/{project_id}/locations/{location}"

    # Set the input configuration along with Google Cloud Storage URI
    gcs_source = vision.ImportProductSetsGcsSource(csv_file_uri=gcs_uri)
    input_config = vision.ImportProductSetsInputConfig(gcs_source=gcs_source)

    # Import the product sets from the input URI.
    response = client.import_product_sets(
        parent=location_path, input_config=input_config
    )

    print(f"Processing operation name: {response.operation.name}")
    # synchronous check of operation status
    result = response.result()
    print("Processing done.")

    for i, status in enumerate(result.statuses):
        print("Status of processing line {} of the csv: {}".format(i, status))
        # Check the status of reference image
        # `0` is the code for OK in google.rpc.Code.
        if status.code == 0:
            reference_image = result.reference_images[i]
            print(reference_image)
        else:
            print(f"Status code not OK: {status.message}")

추가 언어

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

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

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

작업 상태 가져오기

요청한 여러 작업은 일괄 가져오기를 통한 제품 세트 생성, 제품 세트 삭제, 분리된 제품 삭제처럼 장기 실행되는 작업입니다. 이러한 유형의 요청은 작업 상태를 가져오는 데 사용할 수 있는 작업 ID와 함께 JSON을 반환합니다.

예를 들어 일괄 삭제( purge ) 요청은 다음 JSON을 반환합니다.

{
"name": "projects/project-id/locations/location-id/operations/bc4e1d412863e626"
}

이 경우 작업 ID는 bc4e1d412863e626입니다. 다음 샘플은 이 ID로 이 작업의 상태를 가져오는 방법을 보여줍니다.

REST

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

  • PROJECT_ID: Google Cloud 프로젝트 ID입니다.
  • LOCATION_ID: 유효한 위치 식별자입니다. 유효한 위치 식별자는 us-west1, us-east1, europe-west1, asia-east1입니다.
  • OPERATION_ID: 작업의 ID입니다. ID는 작업 이름의 마지막 요소입니다. 예를 들면 다음과 같습니다.
    • 작업 이름: projects/PROJECT_ID/locations/LOCATION_ID/operations/bc4e1d412863e626
    • 작업 ID: bc4e1d412863e626

HTTP 메서드 및 URL:

GET https://vision.googleapis.com/v1/locations/location-id/operations/operation-id

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

curl

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

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
"https://vision.googleapis.com/v1/locations/location-id/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://vision.googleapis.com/v1/locations/location-id/operations/operation-id" | Select-Object -Expand Content
제품 세트 삭제 작업이 완료되면 다음과 비슷한 출력이 표시됩니다.
{
  "name": "locations/location-id/operations/operation-id",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.vision.v1.BatchOperationMetadata",
    "state": "SUCCESSFUL",
    "submitTime": "2019-09-04T15:58:39.131591882Z",
    "endTime": "2019-09-04T15:58:43.099020580Z"
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.vision.v1.PurgeProductsRequest",
    "parent": "projects/project-id/locations/location-id",
    "productSetPurgeConfig": {
      "productSetId": "project-set-id"
    },
    "force": true
  }
}

분리된 제품 삭제 작업이 완료되면 다음과 비슷한 출력이 표시됩니다.

{
  "name": "locations/location-id/operations/operation-id",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.vision.v1.BatchOperationMetadata",
    "state": "SUCCESSFUL",
    "submitTime": "2019-09-04T16:08:38.278197397Z",
    "endTime": "2019-09-04T16:08:45.075778639Z"
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.vision.v1.PurgeProductsRequest",
    "parent": "projects/project-id/locations/location-id",
    "deleteOrphanProducts": true,
    "force": true
  }
}