Tutorial da pesquisa de produtos

Neste tutorial, você verá como criar um conjunto com um grupo de produtos com imagens de referência a eles. Com o tutorial, os usuários podem ver como criar um conjunto de produtos pela importação on-line (individual). Depois que o conjunto de produtos tiver sido indexado, será possível consultá-lo usando a Pesquisa de produtos do Vision.

Neste tutorial, você aprenderá a:

  1. Criar um conjunto de produtos pela importação on-line (individual).
  2. Criar um produto individual.
  3. Adicionar um produto a um conjunto de produtos.
  4. Atualizar um produto.
  5. criar uma imagem de referência;
  6. Pesquisar produtos similares.

Antes de começar

Antes de começar este tutorial, instale as bibliotecas de cliente apropriadas, ative o faturamento e a API para o projeto e configure a autenticação corretamente.

Importar bibliotecas

Para usar a Pesquisa de produtos do Cloud Vision, importe os seguintes módulos após fazer o download e instalar a biblioteca de cliente:

C#

using Google.Cloud.Vision.V1;

Go


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1"
)

Java

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.vision.v1.BatchOperationMetadata;
import com.google.cloud.vision.v1.ImportProductSetsGcsSource;
import com.google.cloud.vision.v1.ImportProductSetsGcsSource.Builder;
import com.google.cloud.vision.v1.ImportProductSetsInputConfig;
import com.google.cloud.vision.v1.ImportProductSetsResponse;
import com.google.cloud.vision.v1.ProductSearchClient;
import com.google.cloud.vision.v1.ReferenceImage;

Node.js

const vision = require('@google-cloud/vision');

PHP

use Google\Cloud\Vision\V1\ProductSearchClient;
use Google\Cloud\Vision\V1\ImportProductSetsGcsSource;
use Google\Cloud\Vision\V1\ImportProductSetsInputConfig;

Python

from google.cloud import vision

Ruby

require "google/cloud/vision"

Como executar o aplicativo

Etapa 1: criar um catálogo de produtos

Os usuários têm duas opções para criar um catálogo de produtos, seja através de importação em lote usando um arquivo CSV, que permite que um catálogo de produtos inteiro seja importado em uma única chamada de API, ou via importação on-line, que oferece controle sobre seus conjuntos de produtos e permite gerenciamento de um recurso ou relacionamento por vez. Isso significa principalmente a criação individual de conjuntos, produtos e imagens de referência. A importação on-line também permite atualizar gradativamente um catálogo de produtos já criado por meio da importação em lote.

Neste tutorial, você usará a importação on-line. Consulte o Início rápido para ver um exemplo de importação em lote com um CSV.

Importação on-line (individual)

1. Criar um conjunto de produtos

Crie um conjunto de produtos vazio, que é um contêiner simples para um grupo de produtos.

Solicitação

Crie um conjunto de produtos vazio e nomeie-o como "PS_CLOTH-SHOE_070318" executando a seguinte solicitação usando o método create_product_set(). Transmita o código do conjunto de produtos e exiba o nome como argumentos.

REST e LINHA DE CMD

Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:

  • project-id: ID do projeto do GCP.
  • location-id: um identificador de local válido. Os identificadores de local válidos são: us-west1, us-east1, europe-west1 e asia-east1.
  • display-name: um nome de exibição de string de sua escolha.

Método HTTP e URL:

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

Corpo JSON da solicitação:

{
  "displayName": "display-name"
}

Para enviar a solicitação, escolha uma destas opções:

curl

Salve o corpo da solicitação em um arquivo chamado request.json e execute o comando a seguir:

curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://vision.googleapis.com/v1/projects/project-id/locations/location-id/productSets

PowerShell

Salve o corpo da solicitação em um arquivo chamado request.json e execute o comando a seguir:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

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

Quando a solicitação é bem-sucedida, o servidor retorna um código de status HTTP 200 OK e a resposta no formato JSON:

Será exibido um código semelhante a este. É possível usar o ID do conjunto de produtos (neste caso, b6d809615b6dd675) para executar outras operações no conjunto de produtos.

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

C#

        private static object CreateProductSet(CreateProductSetsOptions opts)
        {
            var client = ProductSearchClient.Create();

            // Create a product set with the product set specification in the region.
            var request = new CreateProductSetRequest
            {
                // A resource that represents Google Cloud Platform location
                ParentAsLocationName = new LocationName(opts.ProjectID,
                                                        opts.ComputeRegion),
                ProductSetId = opts.ProductSetId,
                ProductSet = new ProductSet
                {
                    DisplayName = opts.ProductSetDisplayName
                }
            };

            // The response is the product set with the `name` populated
            var response = client.CreateProductSet(request);

            Console.WriteLine($"Product set name: {response.DisplayName}");

            return 0;
        }

Go


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1"
)

// 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: %v", 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: %v", err)
	}

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

	return nil
}

Java

/**
 * 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 = ProductSearchClient.formatLocationName(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

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

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

  /**
   * 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}`);
}

PHP

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ProductSearchClient;
use Google\Cloud\Vision\V1\ProductSet;

/**
 * Create a product set
 *
 * @param string $projectId Your Google Cloud project ID
 * @param string $location Google Cloud compute region name
 * @param string $productSetId ID of the product set
 * @param string $productSetDisplayName Display name of the product set
 */
function product_set_create($projectId, $location, $productSetId, $productSetDisplayName)
{
    $client = new ProductSearchClient();

    # a resource that represents Google Cloud Platform location.
    $locationPath = $client->locationName($projectId, $location);

    # create a product set with the product set specification in the region.
    $productSet = (new ProductSet())
        ->setDisplayName($productSetDisplayName);

    # the response is the product set with the `name` field populated.
    $response = $client->createProductSet($locationPath, $productSet, ['productSetId' => $productSetId]);

    # display the product information.
    printf('Product set name: %s' . PHP_EOL, $response->getName());

    $client->close();
}

Python

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 = client.location_path(
        project=project_id, location=location)

    # Create a product set with the product set specification in the region.
    product_set = vision.types.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('Product set name: {}'.format(response.name))

Ruby

require "google/cloud/vision"

def product_search_create_product_set project_id = "your-project-id"
  client = Google::Cloud::Vision.product_search

  # A resource that represents Google Cloud Platform location.
  location = "us-west1" # specify a compute region name
  location_path = client.location_path project: project_id, location: location

  # Create a product set with the product set specification in the region.
  product_set = {
    display_name: "display-name"
  }

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

  # Display the product set information.
  puts "Product set name: #{product_set.name}"
end

Resposta

Product set name: projects/prj-prod-search-tutorials/locations/us-east1/productSets/PS_CLOTH-SHOE_070318
Product set id: PS_CLOTH-SHOE_070318
Product set display name: CLOTH-SHOE

2. Criar um produto

Depois que um conjunto de produtos for criado, a próxima etapa será criar um produto. Crie um produto executando a seguinte solicitação:

REST e LINHA DE CMD

Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:

  • project-id: o ID do projeto do GCP.
  • location-id: um identificador de local válido. Os identificadores de local válidos são: us-west1, us-east1, europe-west1 e asia-east1.
  • display-name: um nome de exibição de string de sua escolha.
  • product-description: uma descrição de string de sua escolha.
  • product-category: uma categoria de produto válida. As seguintes categorias de produtos estão disponíveis no momento: homegoods-v2, apparel-v2, toys-v2, packagedgoods-v1 e general-v1 .
  • productLabels: um ou mais pares de chave-valor associados a um produto. Cada key-string precisa ter um value-string associado.

Método HTTP e URL:

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

Corpo JSON da solicitação:

{
  "displayName": "display-name",
  "description": "product-description",
  "productCategory": "product-category",
  "productLabels": [
      {
        "key": "key-string",
        "value": "value-string"
      }
  ]
}

Para enviar a solicitação, escolha uma destas opções:

curl

Salve o corpo da solicitação em um arquivo chamado request.json e execute o comando a seguir:

curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products

PowerShell

Salve o corpo da solicitação em um arquivo chamado request.json e execute o comando a seguir:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

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/products" | Select-Object -Expand Content

Exemplo de corpo da solicitação:

{
  "displayName": "sample-product-1234",
  "description": "Athletic shorts",
  "productCategory": "apparel-v2",
  "productLabels": [
      {
        "key": "style",
        "value": "womens"
      },
      {
        "key": "color",
        "value": "blue"
      }
  ]
}

Quando a solicitação é bem-sucedida, o servidor retorna um código de status HTTP 200 OK e a resposta no formato JSON:

Será exibido um código semelhante a este. Use o ID do produto (neste caso, 37b9811d308c4e42) para realizar outras operações no produto.

{
  "name": "projects/project-id/locations/location-id/products/37b9811d308c4e42",
  "displayName": "sample-product-456",
  "description": "Athletic shorts",
  "productCategory": "apparel-v2",
  "productLabels": [
    {
      "key": "style",
      "value": "womens"
    },
    {
      "key": "color",
      "value": "blue"
    }
  ]
}

C#

private static int CreateProduct(CreateProductOptions opts)
{
    var client = ProductSearchClient.Create();
    var request = new CreateProductRequest
    {
        // A resource that represents Google Cloud Platform location.
        ParentAsLocationName = new LocationName(opts.ProjectID,
                                                opts.ComputeRegion),
        // Set product category and product display name
        Product = new Product
        {
            DisplayName = opts.DisplayName,
            ProductCategory = opts.ProductCategory
        },
        ProductId = opts.ProductID
    };

    // The response is the product with the `name` field populated.
    var product = client.CreateProduct(request);

    Console.WriteLine($"Product name: {product.Name}");
    return 0;
}

Go


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1"
)

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

	req := &visionpb.CreateProductRequest{
		Parent:    fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		ProductId: productID,
		Product: &visionpb.Product{
			DisplayName:     productDisplayName,
			ProductCategory: productCategory,
		},
	}

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

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

	return nil
}

Java

/**
 * Create one product.
 *
 * @param projectId - Id of the project.
 * @param computeRegion - Region name.
 * @param productId - Id of the product.
 * @param productDisplayName - Display name of the product.
 * @param productCategory - Category of the product.
 * @throws IOException - on I/O errors.
 */
public static void createProduct(
    String projectId,
    String computeRegion,
    String productId,
    String productDisplayName,
    String productCategory)
    throws IOException {
  try (ProductSearchClient client = ProductSearchClient.create()) {

    // A resource that represents Google Cloud Platform location.
    String formattedParent = ProductSearchClient.formatLocationName(projectId, computeRegion);
    // Create a product with the product specification in the region.
    // Multiple labels are also supported.
    Product myProduct =
        Product.newBuilder()
            .setName(productId)
            .setDisplayName(productDisplayName)
            .setProductCategory(productCategory)
            .build();
    Product product = client.createProduct(formattedParent, myProduct, productId);
    // Display the product information
    System.out.println(String.format("Product name: %s", product.getName()));
  }
}

Node.js

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

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

  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const projectId = 'Your Google Cloud project Id';
  // const location = 'A compute region name';
  // const productId = 'Id of the product';
  // const productDisplayName = 'Display name of the product';
  // const productCategory = 'Catoegory of the product';

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

  const product = {
    displayName: productDisplayName,
    productCategory: productCategory,
  };

  const request = {
    parent: locationPath,
    product: product,
    productId: productId,
  };

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

PHP

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ProductSearchClient;
use Google\Cloud\Vision\V1\Product;

/**
 * Create one product
 *
 * @param string $projectId Your Google Cloud project ID
 * @param string $location Google Cloud compute region name
 * @param string $productId ID of the product
 * @param string $productDisplayName Display name of the product
 * @param string $productCategory Category of the product
 */
function product_create($projectId, $location, $productId, $productDisplayName, $productCategory)
{
    $client = new ProductSearchClient();

    # a resource that represents Google Cloud Platform location.
    $locationPath = $client->locationName($projectId, $location);

    # create a product with the product specification in the region.
    # set product name and product display name.
    $product = (new Product())
        ->setDisplayName($productDisplayName)
        ->setProductCategory($productCategory);

    # the response is the product with the `name` field populated.
    $response = $client->createProduct($locationPath, $product, ['productId' => $productId]);

    # display the product information.
    printf('Product name: %s' . PHP_EOL, $response->getName());

    $client->close();
}

Python

from google.cloud import vision

def create_product(
        project_id, location, product_id, product_display_name,
        product_category):
    """Create one product.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        product_id: Id of the product.
        product_display_name: Display name of the product.
        product_category: Category of the product.
    """
    client = vision.ProductSearchClient()

    # A resource that represents Google Cloud Platform location.
    location_path = client.location_path(project=project_id, location=location)

    # Create a product with the product specification in the region.
    # Set product display name and product category.
    product = vision.types.Product(
        display_name=product_display_name,
        product_category=product_category)

    # The response is the product with the `name` field populated.
    response = client.create_product(
        parent=location_path,
        product=product,
        product_id=product_id)

    # Display the product information.
    print('Product name: {}'.format(response.name))

Ruby

require "google/cloud/vision"

def product_search_create_product project_id = "your-project-id"
  client = Google::Cloud::Vision.product_search

  # A resource that represents Google Cloud Platform location.
  location      = "us-west1" # specify a compute region name
  location_path = client.location_path project: project_id, location: location

  # Create a product with the product specification in the region.
  # Set product display name and product category.
  product = {
    display_name:     "sample-product-1234",
    description:      "Athletic shorts",
    product_category: "apparel",
    product_labels:   [{ key: "color", value: "blue" }]
  }

  # The response is the product with the `name` field populated.
  product = client.create_product parent: location_path, product: product

  # Display the product information.
  puts "Product name: #{product.name}"
end

Resposta

Product name: projects/prj-prod-search-tutorials/locations/us-east1/products/P_CLOTH-SHOE_46903668_070318
Product id: P_CLOTH-SHOE_46903668_070318
Product display name: Blue Dress
Product category: apparel
Product description: Short sleeved and 1950s style satin dress
Product labels:
  Product label 1:
        key: style
        value: women
  Product label 2:
        key: category
        value: dress
  Product label 3:
        key: color
        value: dark-blue

3. Adicionar um produto a um conjunto

Depois que um conjunto e um produto tiverem sido criados, será possível adicionar o produto ao conjunto.

REST e LINHA DE CMD

Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:

  • project-id: o ID do projeto do GCP.
  • location-id: um identificador de local válido. Os identificadores de local válidos são: us-west1, us-east1, europe-west1 e asia-east1.
  • product-set-id: o ID do conjunto de produtos no qual você quer executar a operação.
  • product-name: o nome completo do recurso do produto. Formato:
    • projects/project-id/locations/location-id/products/product-id

Método HTTP e URL:

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

Corpo JSON da solicitação:

{
  "product": "product-name"
}

Para enviar a solicitação, escolha uma destas opções:

curl

Salve o corpo da solicitação em um arquivo chamado request.json e execute o comando a seguir:

curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://vision.googleapis.com/v1/projects/project-id/locations/location-id/productSets/product-set-id:addProduct

PowerShell

Salve o corpo da solicitação em um arquivo chamado request.json e execute o comando a seguir:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

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/product-set-id:addProduct" | Select-Object -Expand Content

Você receberá uma resposta JSON semelhante a esta:

{}

C#

private static int AddProductToProductSet(AddProductToProductSetOptions opts)
{
    var client = ProductSearchClient.Create();
    var request = new AddProductToProductSetRequest
    {
        // Get the full path of the products
        ProductAsProductName = new ProductName(opts.ProjectID,
                                              opts.ComputeRegion,
                                              opts.ProductID),
        // Get the full path of the product set.
        ProductSetName = new ProductSetName(opts.ProjectID,
                                           opts.ComputeRegion,
                                           opts.ProductSetId),
    };

    client.AddProductToProductSet(request);

    Console.WriteLine("Product added to product set.");

    return 0;
}

Go


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1"
)

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

	req := &visionpb.AddProductToProductSetRequest{
		Name:    fmt.Sprintf("projects/%s/locations/%s/productSets/%s", projectID, location, productSetID),
		Product: fmt.Sprintf("projects/%s/locations/%s/products/%s", projectID, location, productID),
	}

	if err = c.AddProductToProductSet(ctx, req); err != nil {
		return fmt.Errorf("NewProductSearchClient: %v", err)
	}

	fmt.Fprintf(w, "Product added to product set.\n")

	return nil
}

Java

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

    // Get the full path of the product set.
    String formattedName =
        ProductSearchClient.formatProductSetName(projectId, computeRegion, productSetId);

    // Get the full path of the product.
    String productPath = ProductName.of(projectId, computeRegion, productId).toString();

    // Add the product to the product set.
    client.addProductToProductSet(formattedName, productPath);

    System.out.println(String.format("Product added to product set."));
  }
}

Node.js

async function addProductToProductSet() {
  const vision = require('@google-cloud/vision');

  const client = new vision.ProductSearchClient();

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

  const productPath = client.productPath(projectId, location, productId);
  const productSetPath = client.productSetPath(
    projectId,
    location,
    productSetId
  );

  const request = {
    name: productSetPath,
    product: productPath,
  };

  await client.addProductToProductSet(request);
  console.log('Product added to product set.');
}

PHP

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ProductSearchClient;

/**
 * Create a product set
 *
 * @param string $projectId Your Google Cloud project ID
 * @param string $location Google Cloud compute region name
 * @param string $productId ID of the product
 * @param string $productSetId ID of the product set
 */
function product_set_add_product($projectId, $location, $productId, $productSetId)
{
    $client = new ProductSearchClient();

    # get the name of the product set
    $productSetPath = $client->productSetName($projectId, $location, $productSetId);

    # get the name of the product.
    $productPath = $client->productName($projectId, $location, $productId);

    # add product to product set
    $client->addProductToProductSet($productSetPath, $productPath);
    print('Product added to product set.' . PHP_EOL);

    $client->close();
}

Python

from google.cloud import vision

def add_product_to_product_set(
        project_id, location, product_id, product_set_id):
    """Add a product to a product set.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        product_id: Id of the product.
        product_set_id: Id of the product set.
    """
    client = vision.ProductSearchClient()

    # Get the full path of the product set.
    product_set_path = client.product_set_path(
        project=project_id, location=location,
        product_set=product_set_id)

    # Get the full path of the product.
    product_path = client.product_path(
        project=project_id, location=location, product=product_id)

    # Add the product to the product set.
    client.add_product_to_product_set(
        name=product_set_path, product=product_path)
    print('Product added to product set.')

Ruby

require "google/cloud/vision"

def product_search_add_product_to_product_set \
    project_id     = "your-project-id",
    location       = "us-west1",
    product_id     = "your-product-id",
    product_set_id = "your-product-set-id"

  client = Google::Cloud::Vision.product_search

  # Get the full path of the product set.
  product_set_path = client.product_set_path project:     project_id,
                                             location:    location,
                                             product_set: product_set_id

  # Get the full path of the product.
  product_path = client.product_path project:  project_id,
                                     location: location,
                                     product:  product_id

  # Add the product to the product set.
  client.add_product_to_product_set name:    product_set_path,
                                    product: product_path

  puts "Product #{product_id} added to product set #{product_set_id}."
end

Resposta

Product added to product set.

4. Atualizar um produto

Se você precisar atualizar um produto ou um conjunto de produtos após a criação, poderá usar nossos métodos de atualização. Neste exemplo, você verá uma atualização do produto em que os rótulos são alterados:

Linha de comando

Para atualizar um produto, envie uma solicitação PATCH para o URI a seguir.
  • Substitua project-id pelo ID do projeto do Google Cloud Platform (GCP).
  • Substitua location-id por um identificador de local válido. Os identificadores de local válidos são: us-west1, us-east1, europe-west1 e asia-east1.
  • Substitua product-id pelo ID do produto a ser atualizado.
curl -X PATCH \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-H "Content-Type: application/json" \
https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products/product-id -d "{
   'updateMask': { 'paths': ['display_name'] },
   'product': { 'display_name': 'new-display-name' }
}"

C#

private static int UpdateProductLabels(UpdateProductLabelsOptions opts)
{
    var client = ProductSearchClient.Create();
    var request = new UpdateProductRequest
    {
        Product = new Product
        {
            // Get the name of the product
            ProductName = new ProductName(opts.ProjectID,
                                         opts.ComputeRegion,
                                         opts.ProductID),
            // Set the product name, product label, and product display
            // name. Multiple labels are also supported.
            ProductLabels =
            {
                new Product.Types.KeyValue
                {
                    Key = opts.Labels.Split(",").First(),
                    Value = opts.Labels.Split(",").Last()
                }
            }
        },
        // Updating only the product_labels field here.
        UpdateMask = new FieldMask
        {
            Paths = { "product_labels" }
        }
    };

    // This overwrites the product_labels.
    var product = client.UpdateProduct(request);

    var productId = product.Name.Split("/").Last();
    Console.WriteLine($"\nProduct name: {product.Name}");
    Console.WriteLine($"Product id: {productId}");
    Console.WriteLine($"Product display name: {product.DisplayName}");
    Console.WriteLine($"Product category: {product.ProductCategory}");
    Console.WriteLine($"Product labels:");
    foreach (var label in product.ProductLabels)
    {
        Console.WriteLine($"\tLabel: {label.ToString()}");
    }
    return 0;
}

Go


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1"
	field_mask "google.golang.org/genproto/protobuf/field_mask"
)

// updateProductLabels updates product labels of a product.
func updateProductLabels(w io.Writer, projectID string, location string, productID string, key string, value string) error {
	ctx := context.Background()
	c, err := vision.NewProductSearchClient(ctx)
	if err != nil {
		return fmt.Errorf("NewProductSearchClient: %v", err)
	}
	defer c.Close()

	req := &visionpb.UpdateProductRequest{
		UpdateMask: &field_mask.FieldMask{
			Paths: []string{
				"product_labels",
			},
		},
		Product: &visionpb.Product{
			Name: fmt.Sprintf("projects/%s/locations/%s/products/%s", projectID, location, productID),
			ProductLabels: []*visionpb.Product_KeyValue{
				{
					Key:   key,
					Value: value,
				},
			},
		},
	}

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

	fmt.Fprintf(w, "Product name: %s\n", resp.Name)
	fmt.Fprintf(w, "Updated product labels: %s\n", resp.ProductLabels)

	return nil
}

Java

/**
 * Update the product labels.
 *
 * @param projectId - Id of the project.
 * @param computeRegion - Region name.
 * @param productId -Id of the product.
 * @param productLabels - Labels of the product.
 * @throws IOException - on I/O errors.
 */
public static void updateProductLabels(
    String projectId, String computeRegion, String productId, String productLabels)
    throws IOException {
  try (ProductSearchClient client = ProductSearchClient.create()) {

    // Get the full path of the product.
    String formattedName =
        ProductSearchClient.formatProductName(projectId, computeRegion, productId);

    // Set product name, product labels and product display name.
    // Multiple labels are also supported.
    Product product =
        Product.newBuilder()
            .setName(formattedName)
            .addProductLabels(
                KeyValue.newBuilder()
                    .setKey(productLabels.split(",")[0].split("=")[0])
                    .setValue(productLabels.split(",")[0].split("=")[1])
                    .build())
            .build();

    // Set product update field name.
    FieldMask updateMask = FieldMask.newBuilder().addPaths("product_labels").build();

    // Update the product.
    Product updatedProduct = client.updateProduct(product, updateMask);
    // Display the product information
    System.out.println(String.format("Product name: %s", updatedProduct.getName()));
    System.out.println(String.format("Updated product labels: "));
    for (Product.KeyValue element : updatedProduct.getProductLabelsList()) {
      System.out.println(String.format("%s: %s", element.getKey(), element.getValue()));
    }
  }
}

Node.js

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

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

  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const projectId = 'Your Google Cloud project Id';
  // const location = 'A compute region name';
  // const productId = 'Id of the product';
  // const key = 'The key of the label';
  // const value = 'The value of the label';

  // Resource path that represents full path to the product.
  const productPath = client.productPath(projectId, location, productId);

  const product = {
    name: productPath,
    productLabels: [
      {
        key: key,
        value: value,
      },
    ],
  };

  const updateMask = {
    paths: ['product_labels'],
  };

  const request = {
    product: product,
    updateMask: updateMask,
  };

  const [updatedProduct] = await client.updateProduct(request);
  console.log(`Product name: ${updatedProduct.name}`);
  console.log(`Product display name: ${updatedProduct.displayName}`);
  console.log(`Product description: ${updatedProduct.description}`);
  console.log(`Product category: ${updatedProduct.productCategory}`);
  console.log(
    `Product Labels: ${updatedProduct.productLabels[0].key}: ${updatedProduct.productLabels[0].value}`
  );
}

PHP

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ProductSearchClient;
use Google\Cloud\Vision\V1\Product\KeyValue;
use Google\Cloud\Vision\V1\Product;
use Google\Protobuf\FieldMask;

/**
 * Update product labels
 *
 * @param string $projectId Your Google Cloud project ID
 * @param string $location Google Cloud compute region name
 * @param string $productId ID of the product
 * @param string $key Key of the label to update
 * @param string $value Value of label to update
 */
function product_update($projectId, $location, $productId, $key, $value)
{
    $client = new ProductSearchClient();

    # get the name of the product.
    $productPath = $client->productName($projectId, $location, $productId);

    # set product name, product label and product display name.
    # multiple labels are also supported.
    $keyValue = (new KeyValue())
        ->setKey($key)
        ->setValue($value);
    $product = (new Product())
        ->setName($productPath)
        ->setProductLabels([$keyValue]);

    # updating only the product labels field here.
    $updateMask = (new FieldMask())
        ->setPaths(['product_labels']);

    # this overwrites the product_labels.
    $updatedProduct = $client->updateProduct($product, ['updateMask' => $updateMask]);

    # display the product information.
    printf('Product name: %s' . PHP_EOL, $updatedProduct->getName());
    print('Product labels: ' . PHP_EOL);
    foreach ($product->getProductLabels() as $label) {
        printf('%s : %s' . PHP_EOL, $label->getKey(), $label->getValue());
    }

    $client->close();
}

Python

from google.cloud import vision

def update_product_labels(
        project_id, location, product_id, key, value):
    """Update the product labels.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        product_id: Id of the product.
        key: The key of the label.
        value: The value of the label.
    """
    client = vision.ProductSearchClient()

    # Get the name of the product.
    product_path = client.product_path(
        project=project_id, location=location, product=product_id)

    # Set product name, product label and product display name.
    # Multiple labels are also supported.
    key_value = vision.types.Product.KeyValue(key=key, value=value)
    product = vision.types.Product(
        name=product_path,
        product_labels=[key_value])

    # Updating only the product_labels field here.
    update_mask = vision.types.FieldMask(paths=['product_labels'])

    # This overwrites the product_labels.
    updated_product = client.update_product(
        product=product, update_mask=update_mask)

    # Display the updated product information.
    print('Product name: {}'.format(updated_product.name))
    print('Updated product labels: {}'.format(product.product_labels))

Ruby

require "google/cloud/vision"

def product_search_update_product_labels project_id = "your-project-id",
                                         location   = "us-west1",
                                         product_id = "your-product-id"

  client = Google::Cloud::Vision.product_search

  product_path = client.product_path project:  project_id,
                                     location: location,
                                     product:  product_id
  product = {
    name:           product_path,
    product_labels: [{ key: "color", value: "green" }]
  }

  client.update_product product:     product,
                        update_mask: { "paths": ["product_labels"] }
end

Resposta

Product name: projects/prj-prod-search-tutorials/locations/us-east1/products/P_CLOTH-SHOE_46903668_070318
Product id: P_CLOTH-SHOE_46903668_070318
Product display name: Blue Dress
Updated product labels:
  Product label 1:
        key: style
        value: women
  Product label 2:
        key: category
        value: dress
  Product label 3:
        key: color
        value: blue
Product description: Short sleeved and 1950s style satin dress

5. Criar uma imagem de referência do produto

Com a criação de uma imagem de referência para um produto individual, é possível encontrá-lo na Pesquisa de produtos do Vision com essa imagem depois que ele for indexado. Você pode ter várias imagens de referência em um produto, principalmente se quiser uma melhor qualidade de correspondência.

Você pode adicionar uma nova imagem de referência a um produto a qualquer momento.

Ao criar uma imagem de referência, você tem a opção de incluir coordenadas poligonais limitadas. Um polígono delimitador identifica uma área de interesse na imagem de referência. Por exemplo, se você criar uma imagem de referência para um produto que seja uma jaqueta, poderá fornecer as coordenadas para a jaqueta no argumento de polígono delimitador e o sistema considerará apenas a jaqueta ao procurar por correspondências de produto. Observação: você pode fornecer vários polígonos delimitadores no momento do índice, mas no momento da consulta a API aceita apenas um único polígono delimitador.

Uma maneira conveniente de receber as coordenadas poligonais limitantes para uma imagem é usar a localização de objeto da API do Vision. Para saber mais informações sobre localização de objetos, consulte Como detectar vários objetos.

REST e LINHA DE CMD

Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:

  • project-id: o ID do projeto do GCP.
  • location-id: um identificador de local válido. Os identificadores de local válidos são: us-west1, us-east1, europe-west1 e asia-east1.
  • product-id: o ID do produto associado a uma imagem de referência. Esse ID é definido aleatoriamente ou especificado pelo usuário no momento da criação do produto.
  • cloud-storage-image-uri: o caminho para um arquivo de imagem válido em um bucket do Cloud Storage. Você precisa ter, pelo menos, privilégios de leitura para o arquivo. Exemplo:
    • gs://storage-bucket/filename.jpg

Método HTTP e URL:

POST https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products/product-id/referenceImages

Corpo JSON da solicitação:

{
  "uri": "cloud-storage-image-uri",
  "boundingPolys": [
    {
      "vertices": [
        {
          "x": X_MIN,
          "y": Y_MIN
        },
        {
          "x": X_MAX,
          "y": Y_MIN
        },
        {
          "x": X_MAX,
          "y": Y_MAX
        },
        {
          "x": X_MIN,
          "y": Y_MAX
        }
      ]
    }
  ]
}

Para enviar a solicitação, escolha uma destas opções:

curl

Salve o corpo da solicitação em um arquivo chamado request.json e execute o comando a seguir:

curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products/product-id/referenceImages

PowerShell

Salve o corpo da solicitação em um arquivo chamado request.json e execute o comando a seguir:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

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/products/product-id/referenceImages" | Select-Object -Expand Content

Quando a solicitação é bem-sucedida, o servidor retorna um código de status HTTP 200 OK e a resposta no formato JSON:

Será exibido um código semelhante a este. O exemplo de solicitação especificou um único boundingPoly na imagem. Os vértices da caixa delimitadora não são normalizados. Os valores de vértice são os valores reais de pixel, não estão relacionados à imagem original e são dimensionados de 0 a 1. Esses vértices têm os seguintes valores: [(33,22),(282,22),(282,278),(33,278)].


{
  "name": "projects/project-id/locations/location-id/products/product-id/referenceImages/image-id",
  "uri": "gs://storage-bucket/filename.jpg",
  "boundingPolys": [
    {
      "vertices": [
        {
          "x": 33,
          "y": 22
        },
        {
          "x": 282,
          "y": 22
        },
        {
          "x": 282,
          "y": 278
        },
        {
          "x": 33,
          "y": 278
        }
      ]
    }
  ]
}

C#

private static int CreateReferenceImage(CreateReferenceImageOptions opts)
{
    var client = ProductSearchClient.Create();
    var request = new CreateReferenceImageRequest
    {
        // Get the full path of the product.
        ParentAsProductName = new ProductName(opts.ProjectID,
                                              opts.ComputeRegion,
                                              opts.ProductID),
        ReferenceImageId = opts.ReferenceImageID,
        // Create a reference image.
        ReferenceImage = new ReferenceImage
        {
            Uri = opts.ReferenceImageURI
        }
    };

    var referenceImage = client.CreateReferenceImage(request);

    Console.WriteLine($"Reference image name: {referenceImage.Name}");
    Console.WriteLine($"Reference image URI: {referenceImage.Uri}");

    return 0;
}

Go


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1"
)

// createReferenceImage creates a reference image for a product.
func createReferenceImage(w io.Writer, projectID string, location string, productID string, referenceImageID string, gcsURI string) error {
	ctx := context.Background()
	c, err := vision.NewProductSearchClient(ctx)
	if err != nil {
		return fmt.Errorf("NewProductSearchClient: %v", err)
	}
	defer c.Close()

	req := &visionpb.CreateReferenceImageRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s/products/%s", projectID, location, productID),
		ReferenceImage: &visionpb.ReferenceImage{
			Uri: gcsURI,
		},
		ReferenceImageId: referenceImageID,
	}

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

	fmt.Fprintf(w, "Reference image name: %s\n", resp.Name)
	fmt.Fprintf(w, "Reference image uri: %s\n", resp.Uri)

	return nil
}

Java

/**
 * Create a reference image.
 *
 * @param projectId - Id of the project.
 * @param computeRegion - Region name.
 * @param productId - Id of the product.
 * @param referenceImageId - Id of the image.
 * @param gcsUri - Google Cloud Storage path of the input image.
 * @throws IOException - on I/O errors.
 */
public static void createReferenceImage(
    String projectId,
    String computeRegion,
    String productId,
    String referenceImageId,
    String gcsUri)
    throws IOException {
  try (ProductSearchClient client = ProductSearchClient.create()) {

    // Get the full path of the product.
    String formattedParent =
        ProductSearchClient.formatProductName(projectId, computeRegion, productId);
    // Create a reference image.
    ReferenceImage referenceImage = ReferenceImage.newBuilder().setUri(gcsUri).build();

    ReferenceImage image =
        client.createReferenceImage(formattedParent, referenceImage, referenceImageId);
    // Display the reference image information.
    System.out.println(String.format("Reference image name: %s", image.getName()));
    System.out.println(String.format("Reference image uri: %s", image.getUri()));
  }
}

Node.js

async function createReferenceImage() {
  const vision = require('@google-cloud/vision');

  const client = new vision.ProductSearchClient();

  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const projectId = 'Your Google Cloud project Id';
  // const location = 'A compute region name';
  // const productId = 'Id of the product';
  // const referenceImageId = 'Id of the reference image';
  // const gcsUri = 'Google Cloud Storage path of the input image';

  const formattedParent = client.productPath(projectId, location, productId);

  const referenceImage = {
    uri: gcsUri,
  };

  const request = {
    parent: formattedParent,
    referenceImage: referenceImage,
    referenceImageId: referenceImageId,
  };

  const [response] = await client.createReferenceImage(request);
  console.log(`response.name: ${response.name}`);
  console.log(`response.uri: ${response.uri}`);
}

PHP

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ProductSearchClient;
use Google\Cloud\Vision\V1\ReferenceImage;

/**
 * Create a reference image
 *
 * @param string $projectId Your Google Cloud project ID
 * @param string $location Google Cloud compute region name
 * @param string $productId ID of the product
 * @param string $referenceImageId ID of the reference image
 * @param string $gcsUri Google Cloud Storage path of the input image
 */
function product_image_create($projectId, $location, $productId, $referenceImageId, $gcsUri)
{
    $client = new ProductSearchClient();

    # get the name of the product.
    $productPath = $client->productName($projectId, $location, $productId);

    # create a reference image.
    $referenceImage = (new ReferenceImage())
        ->setUri($gcsUri);

    # the response is the reference image with `name` populated.
    $image = $client->createReferenceImage($productPath, $referenceImage, ['referenceImageId' => $referenceImageId]);

    # display the reference image information
    printf('Reference image name: %s' . PHP_EOL, $image->getName());
    printf('Reference image uri: %s' . PHP_EOL, $image->getUri());

    $client->close();
}

Python

from google.cloud import vision

def create_reference_image(
        project_id, location, product_id, reference_image_id, gcs_uri):
    """Create a reference image.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        product_id: Id of the product.
        reference_image_id: Id of the reference image.
        gcs_uri: Google Cloud Storage path of the input image.
    """
    client = vision.ProductSearchClient()

    # Get the full path of the product.
    product_path = client.product_path(
        project=project_id, location=location, product=product_id)

    # Create a reference image.
    reference_image = vision.types.ReferenceImage(uri=gcs_uri)

    # The response is the reference image with `name` populated.
    image = client.create_reference_image(
        parent=product_path,
        reference_image=reference_image,
        reference_image_id=reference_image_id)

    # Display the reference image information.
    print('Reference image name: {}'.format(image.name))
    print('Reference image uri: {}'.format(image.uri))

Ruby

require "google/cloud/vision"

def product_search_create_reference_image project_id = "your-project-id",
                                          location   = "us-west1",
                                          product_id = "your-product-id"

  client = Google::Cloud::Vision.product_search

  product_path = client.product_path project:  project_id,
                                     location: location,
                                     product:  product_id
  reference_image = {
    uri: "gs://cloud-samples-data/vision/product_search/shoes_1.jpg"
  }

  reference_image = client.create_reference_image parent:          product_path,
                                                  reference_image: reference_image

  puts "Added reference image to #{product_id}."
  puts "Reference image name: #{reference_image.name}"
  puts "Reference image uri: #{reference_image.uri}"
end

Resposta

Reference image name: projects/prj-prod-search-tutorials/locations/us-east1/products/P_CLOTH-SHOE_46903668_070318/referenceImages/I_469a896b70ba11e8be97d20059124800_070418
Reference image id: I_469a896b70ba11e8be97d20059124800_070418
Reference image uri: gs://product-search-tutorial/dress-shoe-dataset/469a896b70ba11e8be97d20059124800.jpg
Reference image bounding polygons:
vertices {
  x: 80
  y: 50
}
vertices {
  x: 80
  y: 660
}
vertices {
  x: 300
  y: 50
}
vertices {
  x: 430
  y: 660
}

Etapa 2: pesquisar produtos correspondentes

Essa interface permite consultar o catálogo de produtos criado, com uma nova imagem como entrada e pesquisa do melhor produto correspondente.

Semelhante à criação de uma imagem de referência, ao pesquisar por imagens correspondentes, você tem a opção de incluir coordenadas poligonais limitadas. Um polígono delimitador identifica a área de interesse na imagem de origem para em que você quer encontrar correspondências. Por exemplo, caso sua imagem de origem contenha um vestido e uma bolsa, e você quiser apenas encontrar correspondências para o vestido, poderá identificar as coordenadas poligonais limitantes para a região da imagem que contém apenas o vestido. Por padrão, se nenhum polígono delimitador for especificado, a API determinará o maior polígono delimitador e o consultará automaticamente.

Uma maneira conveniente de receber as coordenadas poligonais limitantes para uma imagem é usar a localização de objeto da API do Vision. Para saber mais informações sobre localização de objetos, consulte Como detectar vários objetos. Por exemplo, é possível consultar explicitamente uma imagem completa especificando um polígono delimitador da caixa de imagem inteira: [(0, 0), (0, 1), (1, 1), (1, 0)].

A solicitação retorna uma resposta de API que inclui o melhor produto correspondente para uma imagem com a pontuação e a imagem correspondente. Essa imagem é retornada usando o maior nível de confiança.

REST e LINHA DE CMD

Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:

  • base64-encoded-image: a representação base64 (string ASCII) dos dados da imagem binária. Essa string precisa ser semelhante à seguinte:
    • /9j/4QAYRXhpZgAA...9tAVx/zDQDlGxn//2Q==
    Para mais informações, consulte o tópico Codificação Base64.
  • project-id: o ID do projeto do GCP.
  • location-id: um identificador de local válido. Os identificadores de local válidos são: us-west1, us-east1, europe-west1 e asia-east1.
  • product-set-id: o ID do conjunto de produtos no qual você quer executar a operação.

Considerações específicas de campo:

  • features.maxResults: o número máximo de resultados a serem retornados.
  • imageContext.productCategories: a categoria de produto para a pesquisa. No momento, só é possível especificar uma categoria, como produtos de casa, vestuário, brinquedos, produtos embalados e artigos em geral.
  • imageContext.filter: uma ou várias expressões de filtragem de chave-valor de rótulos de produto. Formato: "key=value". É possível vincular a filtragem de pares de chave-valor às expressões AND ou OR: "color=blue AND style=mens" ou "color=blue OR color=black". Se estiver usando a expressão OR, todas as chaves nela precisam ser iguais.

Método HTTP e URL:

POST https://vision.googleapis.com/v1/images:annotate

Corpo JSON da solicitação:

{
  "requests": [
    {
      "image": {
        "content": base64-encoded-image
      },
      "features": [
        {
          "type": "PRODUCT_SEARCH",
          "maxResults": 5
        }
      ],
      "imageContext": {
        "productSearchParams": {
          "productSet": "projects/project-id/locations/location-id/productSets/product-set-id",
          "productCategories": [
               "apparel"
          ],
          "filter": "style = womens"
        }
      }
    }
  ]
}

Para enviar a solicitação, escolha uma destas opções:

curl

Salve o corpo da solicitação em um arquivo chamado request.json e execute o comando a seguir:

curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://vision.googleapis.com/v1/images:annotate

PowerShell

Salve o corpo da solicitação em um arquivo chamado request.json e execute o comando a seguir:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://vision.googleapis.com/v1/images:annotate" | Select-Object -Expand Content

Quando a solicitação é bem-sucedida, o servidor retorna um código de status HTTP 200 OK e a resposta no formato JSON.

A resposta JSON inclui os dois tipos de resultados a seguir:

  • productSearchResults: contém uma lista de produtos correspondentes para a imagem inteira. Na resposta de amostra, os produtos correspondentes são: product_id65, product_id35, product_id34, product_id62 e product_id32.
  • productGroupedResults: contém as coordenadas da caixa delimitadora e os itens correspondentes de cada produto identificado na imagem. Na resposta a seguir, há apenas um produto identificado, seguido pelos produtos correspondentes no conjunto de amostra: product_id65, product_id35, product_id34, product_id93 e product_id62.

Há uma sobreposição nos dois tipos de resultados, mas também pode haver diferenças. Por exemplo, product_id32 e product_id93 na resposta.

C#

private static int GetSimilarProductsFile(GetSimilarProductsOptions opts)
{
    // Create annotate image request along with product search feature.
    Image image = Image.FromFile(opts.FilePath);
    var imageAnnotatorClient = ImageAnnotatorClient.Create();

    // Product Search specific parameters
    var productSearchParams = new ProductSearchParams
    {
        ProductSetAsProductSetName = new ProductSetName(opts.ProjectID,
                                                        opts.ComputeRegion,
                                                        opts.ProductSetId),
        ProductCategories = { opts.ProductCategory },
        Filter = opts.Filter
    };

    // Search products similar to the image.
    var results = imageAnnotatorClient.DetectSimilarProducts(image, productSearchParams);

    Console.WriteLine("Similar products:");
    foreach (var result in results.Results)
    {
        var product = result.Product;
        Console.WriteLine($"Score (Confidence): {result.Score}");
        Console.WriteLine($"Image name: {result.Image}");
        Console.WriteLine($"Product name: {product.Name}");
        Console.WriteLine($"Product display name: {product.DisplayName}");
        Console.WriteLine($"Product description: {product.Description}");
        Console.WriteLine($"Product labels: {product.ProductLabels}");
    }
    return 0;
}

Go


import (
	"context"
	"fmt"
	"io"
	"os"

	vision "cloud.google.com/go/vision/apiv1"
	visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1"
)

// getSimilarProducts searches for products from a product set similar to products in an image file.
func getSimilarProducts(w io.Writer, projectID string, location string, productSetID string, productCategory string, file string, filter string) error {
	ctx := context.Background()
	c, err := vision.NewImageAnnotatorClient(ctx)
	if err != nil {
		return fmt.Errorf("NewImageAnnotatorClient: %v", err)
	}
	defer c.Close()

	f, err := os.Open(file)
	if err != nil {
		return fmt.Errorf("Open: %v", err)
	}
	defer f.Close()

	image, err := vision.NewImageFromReader(f)
	if err != nil {
		return fmt.Errorf("NewImageFromReader: %v", err)
	}

	ictx := &visionpb.ImageContext{
		ProductSearchParams: &visionpb.ProductSearchParams{
			ProductSet:        fmt.Sprintf("projects/%s/locations/%s/productSets/%s", projectID, location, productSetID),
			ProductCategories: []string{productCategory},
			Filter:            filter,
		},
	}

	response, err := c.ProductSearch(ctx, image, ictx)
	if err != nil {
		return fmt.Errorf("ProductSearch: %v", err)
	}

	fmt.Fprintf(w, "Product set index time:\n")
	fmt.Fprintf(w, "seconds: %d\n", response.IndexTime.Seconds)
	fmt.Fprintf(w, "nanos: %d\n", response.IndexTime.Nanos)

	fmt.Fprintf(w, "Search results:\n")
	for _, result := range response.Results {
		fmt.Fprintf(w, "Score(Confidence): %f\n", result.Score)
		fmt.Fprintf(w, "Image name: %s\n", result.Image)

		fmt.Fprintf(w, "Prodcut name: %s\n", result.Product.Name)
		fmt.Fprintf(w, "Product display name: %s\n", result.Product.DisplayName)
		fmt.Fprintf(w, "Product labels: %s\n", result.Product.ProductLabels)
	}

	return nil
}

Java

/**
 * Search similar products to image in local file.
 *
 * @param projectId - Id of the project.
 * @param computeRegion - Region name.
 * @param productSetId - Id of the product set.
 * @param productCategory - Category of the product.
 * @param filePath - Local file path of the image to be searched
 * @param filter - Condition to be applied on the labels. Example for filter: (color = red OR
 *     color = blue) AND style = kids It will search on all products with the following labels:
 *     color:red AND style:kids color:blue AND style:kids
 * @throws IOException - on I/O errors.
 */
public static void getSimilarProductsFile(
    String projectId,
    String computeRegion,
    String productSetId,
    String productCategory,
    String filePath,
    String filter)
    throws IOException {
  try (ImageAnnotatorClient queryImageClient = ImageAnnotatorClient.create()) {

    // Get the full path of the product set.
    String productSetPath =
        ProductSearchClient.formatProductSetName(projectId, computeRegion, productSetId);

    // Read the image as a stream of bytes.
    File imgPath = new File(filePath);
    byte[] content = Files.readAllBytes(imgPath.toPath());

    // Create annotate image request along with product search feature.
    Feature featuresElement = Feature.newBuilder().setType(Type.PRODUCT_SEARCH).build();
    // The input image can be a HTTPS link or Raw image bytes.
    // Example:
    // To use HTTP link replace with below code
    //  ImageSource source = ImageSource.newBuilder().setImageUri(imageUri).build();
    //  Image image = Image.newBuilder().setSource(source).build();
    Image image = Image.newBuilder().setContent(ByteString.copyFrom(content)).build();
    ImageContext imageContext =
        ImageContext.newBuilder()
            .setProductSearchParams(
                ProductSearchParams.newBuilder()
                    .setProductSet(productSetPath)
                    .addProductCategories(productCategory)
                    .setFilter(filter))
            .build();

    AnnotateImageRequest annotateImageRequest =
        AnnotateImageRequest.newBuilder()
            .addFeatures(featuresElement)
            .setImage(image)
            .setImageContext(imageContext)
            .build();
    List<AnnotateImageRequest> requests = Arrays.asList(annotateImageRequest);

    // Search products similar to the image.
    BatchAnnotateImagesResponse response = queryImageClient.batchAnnotateImages(requests);

    List<Result> similarProducts =
        response.getResponses(0).getProductSearchResults().getResultsList();
    System.out.println("Similar Products: ");
    for (Result product : similarProducts) {
      System.out.println(String.format("\nProduct name: %s", product.getProduct().getName()));
      System.out.println(
          String.format("Product display name: %s", product.getProduct().getDisplayName()));
      System.out.println(
          String.format("Product description: %s", product.getProduct().getDescription()));
      System.out.println(String.format("Score(Confidence): %s", product.getScore()));
      System.out.println(String.format("Image name: %s", product.getImage()));
    }
  }
}

Node.js

async function getSimilarProductsFile() {
  // Imports the Google Cloud client library
  const vision = require('@google-cloud/vision');
  const fs = require('fs');
  // Creates a client
  const productSearchClient = new vision.ProductSearchClient();
  const imageAnnotatorClient = new vision.ImageAnnotatorClient();

  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const projectId = 'nodejs-docs-samples';
  // const location = 'us-west1';
  // const productSetId = 'indexed_product_set_id_for_testing';
  // const productCategory = 'apparel';
  // const filePath = './resources/shoes_1.jpg';
  // const filter = '';
  const productSetPath = productSearchClient.productSetPath(
    projectId,
    location,
    productSetId
  );
  const content = fs.readFileSync(filePath, 'base64');
  const request = {
    // The input image can be a GCS link or HTTPS link or Raw image bytes.
    // Example:
    // To use GCS link replace with below code
    // image: {source: {gcsImageUri: filePath}}    // To use HTTP link replace with below code
    // image: {source: {imageUri: filePath}}    image: {content: content},
    features: [{type: 'PRODUCT_SEARCH'}],
    imageContext: {
      productSearchParams: {
        productSet: productSetPath,
        productCategories: [productCategory],
        filter: filter,
      },
    },
  };
  const [response] = await imageAnnotatorClient.batchAnnotateImages({
    requests: [request],
  });
  console.log('Search Image:', filePath);
  const results = response['responses'][0]['productSearchResults']['results'];
  console.log('\nSimilar product information:');
  results.forEach(result => {
    console.log('Product id:', result['product'].name.split('/').pop(-1));
    console.log('Product display name:', result['product'].displayName);
    console.log('Product description:', result['product'].description);
    console.log('Product category:', result['product'].productCategory);
  });
}

PHP

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ImageAnnotatorClient;
use Google\Cloud\Vision\V1\ProductSearchClient;
use Google\Cloud\Vision\V1\ProductSearchParams;

/**
 * Search similar products to image
 *
 * @param string $projectId Your Google Cloud project ID
 * @param string $location Google Cloud compute region name
 * @param string $productSetId ID of the product set
 * @param string $productCategory Category of the product
 * @param string $filePath Local file path of the image to be searched
 * @param string $filter Condition to be applied on the labels
 */
function product_search_similar($projectId, $location, $productSetId, $productCategory, $filePath, $filter)
{
    $imageAnnotatorClient = new ImageAnnotatorClient();
    $productSearchClient = new ProductSearchClient();

    # read the image
    $image = file_get_contents($filePath);

    # get the name of the product set
    $productSetPath = $productSearchClient->productSetName($projectId, $location, $productSetId);

    # product search specific parameters
    $productSearchParams = (new ProductSearchParams())
        ->setProductSet($productSetPath)
        ->setProductCategories([$productCategory])
        ->setFilter($filter);

    # search products similar to the image
    $response = $imageAnnotatorClient->productSearch($image, $productSearchParams);

    if ($productSearchResults = $response->getProductSearchResults()) {
        $indexTime = $productSearchResults->getIndexTime();
        printf('Product set index time: %d seconds %d nanos' . PHP_EOL, $indexTime->getSeconds(), $indexTime->getNanos());

        $results = $productSearchResults->getResults();
        print('Search results: ' . PHP_EOL);
        foreach ($results as $result) {
            printf('Score (confidence): %d' . PHP_EOL, $result->getScore());

            # display the product information.
            $product = $result->getProduct();
            $productName = $product->getName();
            $productNameArray = explode('/', $productName);

            printf('Product name: %s' . PHP_EOL, $productName);
            printf('Product id: %s' . PHP_EOL, end($productNameArray));
            printf('Product display name: %s' . PHP_EOL, $product->getDisplayName());
            printf('Product description: %s' . PHP_EOL, $product->getDescription());
            printf('Product category: %s' . PHP_EOL, $product->getProductCategory());
            print('Product labels: ' . PHP_EOL);
            foreach ($product->getProductLabels() as $label) {
                printf('%s : %s' . PHP_EOL, $label->getKey(), $label->getValue());
            }
        }
    } else {
        print($response->getError()->getMessage());
    }

    $imageAnnotatorClient->close();
    $productSearchClient->close();
}

Python

from google.cloud import vision

def get_similar_products_file(
        project_id, location, product_set_id, product_category,
        file_path, filter):
    """Search similar products to image.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        product_set_id: Id of the product set.
        product_category: Category of the product.
        file_path: Local file path of the image to be searched.
        filter: Condition to be applied on the labels.
        Example for filter: (color = red OR color = blue) AND style = kids
        It will search on all products with the following labels:
        color:red AND style:kids
        color:blue AND style:kids
    """
    # product_search_client is needed only for its helper methods.
    product_search_client = vision.ProductSearchClient()
    image_annotator_client = vision.ImageAnnotatorClient()

    # Read the image as a stream of bytes.
    with open(file_path, 'rb') as image_file:
        content = image_file.read()

    # Create annotate image request along with product search feature.
    image = vision.types.Image(content=content)

    # product search specific parameters
    product_set_path = product_search_client.product_set_path(
        project=project_id, location=location,
        product_set=product_set_id)
    product_search_params = vision.types.ProductSearchParams(
        product_set=product_set_path,
        product_categories=[product_category],
        filter=filter)
    image_context = vision.types.ImageContext(
        product_search_params=product_search_params)

    # Search products similar to the image.
    response = image_annotator_client.product_search(
        image, image_context=image_context)

    index_time = response.product_search_results.index_time
    print('Product set index time:')
    print('  seconds: {}'.format(index_time.seconds))
    print('  nanos: {}\n'.format(index_time.nanos))

    results = response.product_search_results.results

    print('Search results:')
    for result in results:
        product = result.product

        print('Score(Confidence): {}'.format(result.score))
        print('Image name: {}'.format(result.image))

        print('Product name: {}'.format(product.name))
        print('Product display name: {}'.format(
            product.display_name))
        print('Product description: {}\n'.format(product.description))
        print('Product labels: {}\n'.format(product.product_labels))

Ruby

require "google/cloud/vision"

def product_search_get_similar_products \
    project_id       = "your-project-id",
    location         = "us-west1",
    product_set_id   = "your-product-set-id",
    product_category = "apparel",
    file_path        = "path/to/product_image.jpg",
    filter           = "(color = red OR color = blue) AND style = kids"

  product_search_client  = Google::Cloud::Vision.product_search
  image_annotator_client = Google::Cloud::Vision.image_annotator

  product_set_path = product_search_client.product_set_path(
    project:     project_id,
    location:    location,
    product_set: product_set_id
  )

  product_set = product_search_client.get_product_set name: product_set_path

  if product_set.index_time.seconds.zero?
    puts "Product set has not been indexed. Please wait and try again."
    return
  end

  product_search_params = {
    product_set:        product_set_path,
    product_categories: [product_category],
    filter:             filter
  }
  image_context = { product_search_params: product_search_params }

  response = image_annotator_client.product_search_detection(
    image:         file_path,
    image_context: image_context
  )

  display_similar_products response.responses.first.product_search_results
end

def display_similar_products search_results
  index_time = search_results.index_time
  puts "Product set index time:"
  puts "\tseconds: #{index_time.seconds}"
  puts "\tnanos: #{index_time.nanos}\n"

  puts "Search results:"
  search_results.results.each_with_index do |result, index|
    puts "Result #{index + 1}:"
    product = result.product

    puts "\tScore(Confidence): #{result.score}"
    puts "\tImage name: #{result.image}"

    puts "\tProduct name: #{product.name}"
    puts "\tProduct display name: #{product.display_name}"
    puts "\tProduct description: #{product.description}"
    puts "\tProduct labels: #{product.product_labels}"
  end
end

Exemplo de resposta de vestuário

Search Image:
  D:/product/final/images-20180618T073733Z-01/images/469355b570ba11e88ff2d20059124800.jpg

Resultado da pesquisa de imagens

Similar product information:
 Product id: 46930b6b
 Product display name: Evening gown
 Product description: Blue evening gown in 1940s style
 Product category: apparel
 style: women
 category: dress
 color: blue

Como pesquisar com um rótulo

O exemplo de pesquisa a seguir inclui um filtro com base na cor.

Solicitação

Faça uma solicitação de pesquisa executando a seguinte solicitação com o método get_similar_products_file() ou get_similar_products_uri(). O código do conjunto de produtos, o caminho do arquivo de imagem local e o filtro são transmitidos como argumentos. Essa imagem de entrada também está presente em "resources/input/".

Python

python product_search.py get_similar_products_file "12000002" "D:/product/final/images-20180618T073733Z-001/images/469355b570ba11e88ff2d20059124800.jpg" "color=white"

Resposta

Search Image:
  D:/product/final/images-20180618T073733Z-001/images/469355b570ba11e88ff2d20059124800.jpg

Resultado da pesquisa de imagens 2

Similar product information:
 Product id: p569d4e7a1
 Product display name: Wedding Dress
 Product description: Elegant Wedding Dress for women
 Product category: apparel
 style: women
 category: dress
 color: white