מדריך ל-Google Product Search

במדריך הזה מוסבר איך ליצור קבוצת מוצרים שמכילה קבוצה של מוצרים עם תמונות לדוגמה של המוצרים האלה. ההדרכה מראה למשתמשים איך ליצור קבוצת מוצרים באמצעות ייבוא אונליין (בנפרד). אחרי שהמערכת תבצע אינדוקס של קבוצת המוצרים, תוכלו לשלוח שאילתה לגבי קבוצת המוצרים באמצעות התכונה 'חיפוש מוצרים' ב-Vision API.

במדריך הזה תלמדו איך:

  1. יצירת קבוצת מוצרים באמצעות ייבוא אונליין (בודד)
  2. יצירת מוצר בודד
  3. הוספת מוצר לקבוצת מוצרים
  4. עדכון מוצר
  5. יצירת תמונה לדוגמה
  6. חיפוש מוצרים דומים

לפני שמתחילים

לפני שמתחילים את המדריך הזה, צריך לוודא שהתקנתם את ספריות הלקוח המתאימות, הפעלתם את החיוב ואת ה-API בפרויקט והגדרתם את האימות בצורה נכונה.

ייבוא ספריות

כדי להשתמש ב-Google Product Search ב-Vision API, צריך לייבא את המודולים הבאים אחרי שמורידים ומתקינים את ספריית הלקוח:

Go

מידע על התקנת ספריית הלקוח של Vision API Google Product Search ושימוש בה מופיע במאמר ספריות הלקוח של Vision API Google Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Google Product Search Go API.

כדי לבצע אימות ב-Google Product Search של Vision API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


import (
	"context"
	"fmt"
	"io"

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

Java

מידע על התקנת ספריית הלקוח של Vision API Google Product Search ושימוש בה מופיע במאמר ספריות הלקוח של Vision API Google Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Google Product Search Java API.

כדי לבצע אימות ב-Google Product Search של Vision API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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.LocationName;
import com.google.cloud.vision.v1.ProductSearchClient;
import com.google.cloud.vision.v1.ReferenceImage;
import java.io.PrintStream;
import javax.swing.JPanel;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import net.sourceforge.argparse4j.inf.Subparsers;

Node.js

מידע על התקנת ספריית הלקוח של Vision API Google Product Search ושימוש בה מופיע במאמר ספריות הלקוח של Vision API Google Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Google Product Search Node.js API.

כדי לבצע אימות ב-Google Product Search של Vision API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

Python

מידע על התקנת ספריית הלקוח של Vision API Google Product Search ושימוש בה מופיע במאמר ספריות הלקוח של Vision API Google Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Google Product Search Python API.

כדי לבצע אימות ב-Google Product Search של Vision API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

from google.cloud import vision

שפות נוספות

C#‎: צריך לפעול לפי הוראות ההגדרה של C# ‎ בדף של ספריות הלקוח ואז לעבור אל מאמרי העזרה בנושא Google Product Search ב-Vision API עבור ‎ .NET.

PHP: עליכם לפעול לפי הוראות ההגדרה של PHP בדף של ספריות הלקוח ואז לעבור אל מסמכי העזר של Google Product Search ב-Vision API ל-PHP.

Ruby: צריך לפעול לפי ההוראות להגדרת Ruby בדף של ספריות הלקוח ולעיין במסמכי העזר של Vision API Google Product Search ל-Ruby.

הפעלת האפליקציה

שלב 1: יצירת קטלוג מוצרים

למשתמשים יש שתי אפשרויות ליצירת קטלוג מוצרים: ייבוא באצווה באמצעות קובץ CSV, שמאפשר לייבא קטלוג מוצרים שלם בקריאה ל-API אחת, או ייבוא אונליין, שמאפשר לכם לשלוט בערכות המוצרים ולנהל משאב או קשר אחד בכל פעם. המשמעות העיקרית היא יצירה של קבוצות מוצרים, מוצרים ותמונות ייחוס בנפרד. ייבוא אונליין מאפשר גם לעדכן באופן מצטבר קטלוג מוצרים שכבר יצרתם באמצעות ייבוא באצווה.

במדריך הזה תשתמשו בייבוא אונליין. במדריך למתחילים מופיעה דוגמה לייבוא קבוצתי באמצעות קובץ CSV.

ייבוא אונליין (אישי)

1. יצירת קבוצת מוצרים

יוצרים קבוצת מוצרים ריקה, שהיא מאגר פשוט לקבוצת מוצרים.

בקשה

יוצרים קבוצת מוצרים ריקה בשם PS_CLOTH-SHOE_070318 באמצעות הפעלת הבקשה הבאה בשיטה create_product_set(). מעבירים את מזהה קבוצת המוצרים ואת השם לתצוגה כארגומנטים.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
  • LOCATION_ID: מזהה מיקום תקין. מזהי מיקום תקינים: us-west1,‏ us-east1,‏ europe-west1 ו-asia-east1.
  • DISPLAY_NAME: שם מוצג במחרוזת לפי בחירתכם.

ה-method של ה-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.

הפלט שיוצג אמור להיות דומה לזה שמופיע כאן. אפשר להשתמש במזהה קבוצת המוצרים (b6d809615b6dd675 במקרה הזה) כדי לבצע פעולות אחרות בקבוצת המוצרים.

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

Go

מידע על התקנת ספריית הלקוח של Vision API Google Product Search ושימוש בה מופיע במאמר ספריות הלקוח של Vision API Google Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Google Product Search Go API.

כדי לבצע אימות ב-Google Product Search של Vision API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


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 Google Product Search ושימוש בה מופיע במאמר ספריות הלקוח של Vision API Google Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Google Product Search Java API.

כדי לבצע אימות ב-Google Product Search של Vision API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

/**
 * 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 Google Product Search ושימוש בה מופיע במאמר ספריות הלקוח של Vision API Google Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Google Product Search Node.js API.

כדי לבצע אימות ב-Google Product Search של Vision API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

// 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 Google Product Search ושימוש בה מופיע במאמר ספריות הלקוח של Vision API Google Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Google Product Search Python API.

כדי לבצע אימות ב-Google Product Search של Vision API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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# ‎ בדף של ספריות הלקוח ואז לעבור אל מאמרי העזרה בנושא Google Product Search ב-Vision API עבור ‎ .NET.

PHP: עליכם לפעול לפי הוראות ההגדרה של PHP בדף של ספריות הלקוח ואז לעבור אל מסמכי העזר של Google Product Search ב-Vision API ל-PHP.

Ruby: צריך לפעול לפי ההוראות להגדרת Ruby בדף של ספריות הלקוח ולעיין במסמכי העזר של Vision API Google Product Search ל-Ruby.

תשובה

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. יצירת מוצר

אחרי שיוצרים קבוצת מוצרים, השלב הבא הוא ליצור מוצר. יוצרים מוצר באמצעות הפעלת הבקשה הבאה.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
  • LOCATION_ID: מזהה מיקום תקין. מזהי מיקום תקינים: us-west1,‏ us-east1,‏ europe-west1 ו-asia-east1.
  • DISPLAY_NAME: שם מוצג במחרוזת לפי בחירתכם.
  • PRODUCT_DESCRIPTION: תיאור מחרוזת לפי בחירתכם.
  • product-category: קטגוריית מוצר תקינה. קטגוריות המוצרים שזמינות כרגע הן: homegoods-v2, apparel-v2, toys-v2, packagedgoods-v1 ו-general-v1.
  • productLabels: צמד מפתח/ערך אחד או יותר שמשויכים למוצר. לכל KEY_STRING צריך להיות VALUE_STRING משויך.

ה-method של ה-HTTP וכתובת ה-URL:

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

גוף בקשת JSON:

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

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

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/products"

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

דוגמה לגוף הבקשה:

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

אם הבקשה תתבצע בהצלחה, השרת יחזיר קוד סטטוס 200 OK של HTTP ואת התשובה בפורמט JSON.

הפלט שיוצג אמור להיות דומה לזה שמופיע כאן. אפשר להשתמש במזהה המוצר (37b9811d308c4e42 במקרה הזה) כדי לבצע פעולות אחרות על המוצר.

{
  "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"
    }
  ]
}

Go

מידע על התקנת ספריית הלקוח של Vision API Google Product Search ושימוש בה מופיע במאמר ספריות הלקוח של Vision API Google Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Google Product Search Go API.

כדי לבצע אימות ב-Google Product Search של Vision API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


import (
	"context"
	"fmt"
	"io"

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

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

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

	return nil
}

Java

מידע על התקנת ספריית הלקוח של Vision API Google Product Search ושימוש בה מופיע במאמר ספריות הלקוח של Vision API Google Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Google Product Search Java API.

כדי לבצע אימות ב-Google Product Search של Vision API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

/**
 * 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 = LocationName.format(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

מידע על התקנת ספריית הלקוח של Vision API Google Product Search ושימוש בה מופיע במאמר ספריות הלקוח של Vision API Google Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Google Product Search Node.js API.

כדי לבצע אימות ב-Google Product Search של Vision API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

// Creates a client
const client = new vision.ProductSearchClient();
async function createProduct() {
  /**
   * 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}`);
}
createProduct();

Python

מידע על התקנת ספריית הלקוח של Vision API Google Product Search ושימוש בה מופיע במאמר ספריות הלקוח של Vision API Google Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Google Product Search Python API.

כדי לבצע אימות ב-Google Product Search של Vision API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

from google.cloud import vision
from google.protobuf import field_mask_pb2 as field_mask

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 = f"projects/{project_id}/locations/{location}"

    # Create a product with the product specification in the region.
    # Set product display name and product category.
    product = vision.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(f"Product name: {response.name}")


שפות נוספות

C#‎: צריך לפעול לפי הוראות ההגדרה של C# ‎ בדף של ספריות הלקוח ואז לעבור אל מאמרי העזרה בנושא Google Product Search ב-Vision API עבור ‎ .NET.

PHP: עליכם לפעול לפי הוראות ההגדרה של PHP בדף של ספריות הלקוח ואז לעבור אל מסמכי העזר של Google Product Search ב-Vision API ל-PHP.

Ruby: צריך לפעול לפי ההוראות להגדרת Ruby בדף של ספריות הלקוח ולעיין במסמכי העזר של Vision API Google Product Search ל-Ruby.

תשובה

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. הוספת מוצר לקבוצת מוצרים

אחרי שיוצרים קבוצת מוצרים ומוצר, אפשר להוסיף את המוצר לקבוצת המוצרים.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
  • LOCATION_ID: מזהה מיקום תקין. מזהי מיקום תקינים: us-west1,‏ us-east1,‏ europe-west1 ו-asia-east1.
  • PRODUCT_SET_ID: המזהה של קבוצת המוצרים שרוצים להריץ עליה את הפעולה.
  • PRODUCT_NAME: שם המשאב המלא של המוצר. פורמט:
    • projects/PROJECT_ID/locations/LOCATION_ID/products/PRODUCT_ID

ה-method של ה-HTTP וכתובת ה-URL:

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

גוף בקשת JSON:

{
  "product": "product-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/product-set-id:addProduct"

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

אתם אמורים לקבל תגובת JSON שדומה לזו:

{}

Go

מידע על התקנת ספריית הלקוח של Vision API Google Product Search ושימוש בה מופיע במאמר ספריות הלקוח של Vision API Google Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Google Product Search Go API.

כדי לבצע אימות ב-Google Product Search של Vision API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


import (
	"context"
	"fmt"
	"io"

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

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

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

	return nil
}

Java

מידע על התקנת ספריית הלקוח של Vision API Google Product Search ושימוש בה מופיע במאמר ספריות הלקוח של Vision API Google Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Google Product Search Java API.

כדי לבצע אימות ב-Google Product Search של Vision API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


/**
 * 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 = ProductSetName.format(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

מידע על התקנת ספריית הלקוח של Vision API Google Product Search ושימוש בה מופיע במאמר ספריות הלקוח של Vision API Google Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Google Product Search Node.js API.

כדי לבצע אימות ב-Google Product Search של Vision API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

const vision = require('@google-cloud/vision');
const client = new vision.ProductSearchClient();

async function addProductToProductSet() {
  /**
   * 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.');
}
addProductToProductSet();

Python

מידע על התקנת ספריית הלקוח של Vision API Google Product Search ושימוש בה מופיע במאמר ספריות הלקוח של Vision API Google Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Google Product Search Python API.

כדי לבצע אימות ב-Google Product Search של Vision API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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.")


שפות נוספות

C#‎: צריך לפעול לפי הוראות ההגדרה של C# ‎ בדף של ספריות הלקוח ואז לעבור אל מאמרי העזרה בנושא Google Product Search ב-Vision API עבור ‎ .NET.

PHP: עליכם לפעול לפי הוראות ההגדרה של PHP בדף של ספריות הלקוח ואז לעבור אל מסמכי העזר של Google Product Search ב-Vision API ל-PHP.

Ruby: צריך לפעול לפי ההוראות להגדרת Ruby בדף של ספריות הלקוח ולעיין במסמכי העזר של Vision API Google Product Search ל-Ruby.

תשובה

Product added to product set.

4. עדכון מוצר

אם אתם צריכים לעדכן מוצר או קבוצת מוצרים אחרי שהם נוצרו, אתם יכולים להשתמש בשיטות העדכון שלנו. בדוגמה הזו מוצג עדכון מוצר שבו התוויות משתנות:

שורת פקודה

כששולחים בקשת PATCH, כל השדות הקודמים והערכים שלהם נמחקים, למעט השדה productCategory, שהוא קבוע. כששולחים את בקשת העדכון PATCH, צריך לשלוח את כל השדות שרוצים לעדכן עם הערכים שלהם.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
  • LOCATION_ID: מזהה מיקום תקין. מזהי מיקום תקינים: us-west1,‏ us-east1,‏ europe-west1 ו-asia-east1.
  • PRODUCT_ID: המזהה של המוצר שמשויך לתמונה לדוגמה. המזהה הזה מוגדר באופן אקראי או מצוין על ידי המשתמש בזמן יצירת המוצר.
  • display-name: שם מוצג במחרוזת לפי בחירתכם. הערך יכול להיות זהה לשם המוצג הקודם או ערך מעודכן.
  • description: תיאור מחרוזת לפי בחירתכם. הערך יכול להיות זהה לשם המוצג הקודם או ערך מעודכן. אם אין לכם צורך בשדה description ובערך שלו, אל תכללו אותם.
  • productLabels: צמד מפתח/ערך אחד או יותר שמשויכים למוצר. לכל KEY_STRING צריך להיות VALUE_STRING משויך.

ה-method של ה-HTTP וכתובת ה-URL:

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

גוף בקשת JSON:

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

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

curl -X PATCH \
-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/products/product-id"

PowerShell

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

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

Invoke-WebRequest `
-Method PATCH `
-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" | Select-Object -Expand Content

אתם אמורים לקבל תגובת JSON שדומה לזו:

{
  "name": "projects/project-id/locations/location-id/products/product-id",
  "displayName": "display-name",
  "description": "description",
  "productCategory": "apparel-v2",
  "productLabels": [
    {
      "key": "style",
      "value": "womens"
    },
    {
      "key": "onSale",
      "value": "true"
    }
  ]
}

Go

מידע על התקנת ספריית הלקוח של Vision API Google Product Search ושימוש בה מופיע במאמר ספריות הלקוח של Vision API Google Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Google Product Search Go API.

כדי לבצע אימות ב-Google Product Search של Vision API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	"cloud.google.com/go/vision/v2/apiv1/visionpb"
	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: %w", 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: %w", err)
	}

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

	return nil
}

Java

מידע על התקנת ספריית הלקוח של Vision API Google Product Search ושימוש בה מופיע במאמר ספריות הלקוח של Vision API Google Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Google Product Search Java API.

כדי לבצע אימות ב-Google Product Search של Vision API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

/**
 * 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 = ProductName.format(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

מידע על התקנת ספריית הלקוח של Vision API Google Product Search ושימוש בה מופיע במאמר ספריות הלקוח של Vision API Google Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Google Product Search Node.js API.

כדי לבצע אימות ב-Google Product Search של Vision API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

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

async function updateProductLabels() {
  /**
   * 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}`
  );
}
updateProductLabels();

Python

מידע על התקנת ספריית הלקוח של Vision API Google Product Search ושימוש בה מופיע במאמר ספריות הלקוח של Vision API Google Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Google Product Search Python API.

כדי לבצע אימות ב-Google Product Search של Vision API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

from google.cloud import vision
from google.protobuf import field_mask_pb2 as field_mask

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.Product.KeyValue(key=key, value=value)
    product = vision.Product(name=product_path, product_labels=[key_value])

    # Updating only the product_labels field here.
    update_mask = field_mask.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(f"Product name: {updated_product.name}")
    print(f"Updated product labels: {product.product_labels}")


שפות נוספות

C#‎: צריך לפעול לפי הוראות ההגדרה של C# ‎ בדף של ספריות הלקוח ואז לעבור אל מאמרי העזרה בנושא Google Product Search ב-Vision API עבור ‎ .NET.

PHP: עליכם לפעול לפי הוראות ההגדרה של PHP בדף של ספריות הלקוח ואז לעבור אל מסמכי העזר של Google Product Search ב-Vision API ל-PHP.

Ruby: צריך לפעול לפי ההוראות להגדרת Ruby בדף של ספריות הלקוח ולעיין במסמכי העזר של Vision API Google Product Search ל-Ruby.

תשובה

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. יצירת תמונת הפניה של מוצר

יצירת תמונה לדוגמה של מוצר מסוים מאפשרת ל-Google Product Search לחפש את המוצר לפי התמונה הזו אחרי שהיא עוברת אינדוקס. אתם יכולים להוסיף כמה תמונות לדוגמה של מוצר, במיוחד אם אתם רוצים שהתמונות מה-AI יהיו באיכות גבוהה יותר.

אפשר להוסיף תמונה לדוגמה למוצר בכל שלב.

כשיוצרים תמונה לדוגמה, אפשר לכלול קואורדינטות של פוליגון תיחום. פוליגון תחום תוחם מזהה אזור עניין בתמונת ההפניה. לדוגמה, אם יוצרים תמונה לדוגמה של מוצר שהוא מעיל, אפשר לספק את הקואורדינטות של המעיל בארגומנט של הפוליגון התוחם, והמערכת תתייחס רק למעיל כשתחפש התאמות למוצר. הערה: אפשר לספק כמה פוליגונים של תיבות תוחמות בזמן יצירת האינדקס, אבל בזמן השאילתה ה-API תומך רק בפוליגון אחד של תיבה תוחמת.

דרך נוחה לקבל את הקואורדינטות של הפוליגון התוחם של תמונה היא באמצעות איתור אובייקטים ב-Vision API. למידע נוסף על לוקליזציה של אובייקטים, אפשר לעיין במאמר זיהוי של כמה אובייקטים.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
  • LOCATION_ID: מזהה מיקום תקין. מזהי מיקום תקינים: us-west1,‏ us-east1,‏ europe-west1 ו-asia-east1.
  • PRODUCT_ID: המזהה של המוצר שמשויך לתמונה לדוגמה. המזהה הזה מוגדר באופן אקראי או מצוין על ידי המשתמש בזמן יצירת המוצר.
  • CLOUD_STORAGE_IMAGE_URI: הנתיב לקובץ תמונה תקין בקטגוריה של Cloud Storage. צריכות להיות לכם לפחות הרשאות קריאה לקובץ. דוגמה:
    • gs://storage-bucket/filename.jpg

ה-method של ה-HTTP וכתובת ה-URL:

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

גוף בקשת JSON:

{
  "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
        }
      ]
    }
  ]
}

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

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/products/product-id/referenceImages"

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

אם הבקשה תתבצע בהצלחה, השרת יחזיר קוד סטטוס 200 OK של HTTP ואת התשובה בפורמט JSON.

הפלט שיוצג אמור להיות דומה לזה שמופיע כאן. בדוגמה של הבקשה צוין boundingPoly אחד בתמונה. הקודקודים של התיבה התוחמת לא מנורמלים. ערכי הקודקודים הם ערכי הפיקסלים בפועל, והם לא יחסיים לתמונה המקורית ומוגדרים בקנה מידה מ-0 עד 1. הקודקודים האלה כוללים את הערכים הבאים: [(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
        }
      ]
    }
  ]
}

Go

מידע על התקנת ספריית הלקוח של Vision API Google Product Search ושימוש בה מופיע במאמר ספריות הלקוח של Vision API Google Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Google Product Search Go API.

כדי לבצע אימות ב-Google Product Search של Vision API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


import (
	"context"
	"fmt"
	"io"

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

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

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

	return nil
}

Java

מידע על התקנת ספריית הלקוח של Vision API Google Product Search ושימוש בה מופיע במאמר ספריות הלקוח של Vision API Google Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Google Product Search Java API.

כדי לבצע אימות ב-Google Product Search של Vision API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

/**
 * 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 = ProductName.format(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

מידע על התקנת ספריית הלקוח של Vision API Google Product Search ושימוש בה מופיע במאמר ספריות הלקוח של Vision API Google Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Google Product Search Node.js API.

כדי לבצע אימות ב-Google Product Search של Vision API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

const client = new vision.ProductSearchClient();

async function createReferenceImage() {
  /**
   * 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}`);
}
createReferenceImage();

Python

מידע על התקנת ספריית הלקוח של Vision API Google Product Search ושימוש בה מופיע במאמר ספריות הלקוח של Vision API Google Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Google Product Search Python API.

כדי לבצע אימות ב-Google Product Search של Vision API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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.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(f"Reference image name: {image.name}")
    print(f"Reference image uri: {image.uri}")


שפות נוספות

C#‎: צריך לפעול לפי הוראות ההגדרה של C# ‎ בדף של ספריות הלקוח ואז לעבור אל מאמרי העזרה בנושא Google Product Search ב-Vision API עבור ‎ .NET.

PHP: עליכם לפעול לפי הוראות ההגדרה של PHP בדף של ספריות הלקוח ואז לעבור אל מסמכי העזר של Google Product Search ב-Vision API ל-PHP.

Ruby: צריך לפעול לפי ההוראות להגדרת Ruby בדף של ספריות הלקוח ולעיין במסמכי העזר של Vision API Google Product Search ל-Ruby.

תשובה

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
}

שלב 2: מחפשים מוצרים תואמים

הממשק הזה מאפשר לכם לשלוח שאילתות לקטלוג המוצרים שיצרתם על ידי הזנת תמונה חדשה וחיפוש המוצר שהכי מתאים לה.

בדומה ליצירת תמונה לדוגמה, כשמחפשים תמונות תואמות אפשר לכלול קואורדינטות של פוליגון תיחום. פוליגון תיחום מזהה את האזור הרלוונטי בתמונת המקור שרוצים למצוא לו התאמות. לדוגמה, אם תמונת המקור מכילה גם שמלה וגם תיק, ואתם רוצים למצוא התאמות רק לשמלה, אתם יכולים לציין את קואורדינטות הפוליגון התוחם של האזור בתמונה שמכיל רק את השמלה. כברירת מחדל, אם לא מציינים פוליגון תחום, ה-API קובע את הפוליגון התחום הגדול ביותר ושולח אליו שאילתה באופן אוטומטי.

דרך נוחה לקבל את הקואורדינטות של הפוליגון התוחם של תמונה היא באמצעות איתור אובייקטים ב-Vision API. למידע נוסף על לוקליזציה של אובייקטים, אפשר לעיין במאמר זיהוי של כמה אובייקטים. לדוגמה, אפשר לשלוח שאילתה מפורשת לגבי תמונה מלאה על ידי ציון פוליגון תיחום של תיבת התמונה כולה: [(0, 0), (0, 1), (1, 1), (1, 0)].

הבקשה מחזירה תגובת API שכוללת את המוצר התואם ביותר לתמונה עם הניקוד והתמונה התואמת. התמונה הזו מוחזרת עם ערך המהימנות הגבוה ביותר.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • BASE64_ENCODED_IMAGE: ייצוג base64 (מחרוזת ASCII) של נתוני התמונה הבינאריים. המחרוזת הזו צריכה להיראות כמו המחרוזת הבאה:
    • /9j/4QAYRXhpZgAA...9tAVx/zDQDlGxn//2Q==
    מידע נוסף זמין בנושא קידוד base64.
  • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
  • LOCATION_ID: מזהה מיקום תקין. מזהי מיקום תקינים: us-west1,‏ us-east1,‏ europe-west1 ו-asia-east1.
  • PRODUCT_SET_ID: המזהה של קבוצת המוצרים שרוצים להריץ עליה את הפעולה.

שיקולים ספציפיים לשדה:

  • features.maxResults – המספר המקסימלי של התוצאות שיוחזרו.
  • imageContext.productCategories – קטגוריית המוצרים שבה רוצים לחפש. בשלב הזה אפשר לציין רק קטגוריית מוצרים אחת (מוצרים לבית, ביגוד, צעצועים, מוצרים ארוזים וכללי).
  • imageContext.filter – (אופציונלי) ביטוי סינון של מפתח/ערך (או כמה ביטויים) לתווית מוצר. פורמט: ‎"key=value". סינון: אפשר לקשר בין זוגות של מפתח-ערך באמצעות הביטויים AND או OR: ‏‎"color=blue AND style=mens"‎ או ‎"color=blue OR color=black"‎. אם משתמשים בביטוי OR, כל המפתחות בביטוי צריכים להיות זהים.

ה-method של ה-HTTP וכתובת ה-URL:

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

גוף בקשת JSON:

{
  "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"
        }
      }
    }
  ]
}

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

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/images:annotate"

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/images:annotate" | Select-Object -Expand Content

אם הבקשה תתבצע בהצלחה, השרת יחזיר קוד סטטוס 200 OK של HTTP ואת התשובה בפורמט JSON.

קובץ ה-JSON של התגובה כולל את שני סוגי התוצאות הבאים:

  • productSearchResults – מכיל רשימה של מוצרים תואמים לכל התמונה. בדוגמה לתשובה, המוצרים התואמים הם: product_id65, product_id35, product_id34, product_id62, product_id32.
  • productGroupedResults – מכיל קואורדינטות של תיבת תוחמת ופריטים תואמים לכל מוצר שזוהה בתמונה. בתגובה הבאה יש רק מוצר אחד שזוהה, ואחריו מוצרים תואמים במדגם המוצרים: product_id65, product_id35, product_id34, product_id93, product_id62.

שימו לב שיש חפיפה בין שני סוגי התוצאות, אבל יכול להיות שיהיו גם הבדלים (למשל, product_id32 ו-product_id93 בתגובה).

Go

מידע על התקנת ספריית הלקוח של Vision API Google Product Search ושימוש בה מופיע במאמר ספריות הלקוח של Vision API Google Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Google Product Search Go API.

כדי לבצע אימות ב-Google Product Search של Vision API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


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

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

// 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: %w", err)
	}
	defer c.Close()

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

	image, err := vision.NewImageFromReader(f)
	if err != nil {
		return fmt.Errorf("NewImageFromReader: %w", 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: %w", 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

מידע על התקנת ספריית הלקוח של Vision API Google Product Search ושימוש בה מופיע במאמר ספריות הלקוח של Vision API Google Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Google Product Search Java API.

כדי לבצע אימות ב-Google Product Search של Vision API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

/**
 * 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 = ProductSetName.format(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

מידע על התקנת ספריית הלקוח של Vision API Google Product Search ושימוש בה מופיע במאמר ספריות הלקוח של Vision API Google Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Google Product Search Node.js API.

כדי לבצע אימות ב-Google Product Search של Vision API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

// 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();

async function getSimilarProductsFile() {
  /**
   * 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);
  });
}
getSimilarProductsFile();

Python

מידע על התקנת ספריית הלקוח של Vision API Google Product Search ושימוש בה מופיע במאמר ספריות הלקוח של Vision API Google Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Google Product Search Python API.

כדי לבצע אימות ב-Google Product Search של Vision API, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

from google.cloud import vision

def get_similar_products_file(
    project_id,
    location,
    product_set_id,
    product_category,
    file_path,
    filter,
    max_results,
):
    """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
        max_results: The maximum number of results (matches) to return. If omitted, all results are returned.
    """
    # 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.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.ProductSearchParams(
        product_set=product_set_path,
        product_categories=[product_category],
        filter=filter,
    )
    image_context = vision.ImageContext(product_search_params=product_search_params)

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

    index_time = response.product_search_results.index_time
    print("Product set index time: ")
    print(index_time)

    results = response.product_search_results.results

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

        print(f"Score(Confidence): {result.score}")
        print(f"Image name: {result.image}")

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


שפות נוספות

C#‎: צריך לפעול לפי הוראות ההגדרה של C# ‎ בדף של ספריות הלקוח ואז לעבור אל מאמרי העזרה בנושא Google Product Search ב-Vision API עבור ‎ .NET.

PHP: עליכם לפעול לפי הוראות ההגדרה של PHP בדף של ספריות הלקוח ואז לעבור אל מסמכי העזר של Google Product Search ב-Vision API ל-PHP.

Ruby: צריך לפעול לפי ההוראות להגדרת Ruby בדף של ספריות הלקוח ולעיין במסמכי העזר של Vision API Google Product Search ל-Ruby.

דוגמה לתגובה לגבי פריטי לבוש

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

תוצאה של חיפוש תמונות

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

חיפוש באמצעות תווית

בדוגמה הבאה לחיפוש יש מסנן שמבוסס על צבע.

בקשה

שולחים בקשת חיפוש על ידי הפעלת הבקשה הבאה עם method‏ get_similar_products_file() או get_similar_products_uri(). מזהה קבוצת המוצרים, נתיב קובץ התמונה המקומי ומסנן מועברים כארגומנטים. תמונת הקלט הזו נמצאת גם בתיקייה resources/input/.

Python

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

תשובה

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

תוצאה של חיפוש תמונות 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