Membuat set data dan mengimpor gambar

Sebuah set data adalah yang berisi sampel perwakilan dari jenis konten yang ingin Anda klasifikasikan, yang dilabeli dengan label kategori yang Anda inginkan untuk model kustom anda. Set data berfungsi sebagai input untuk melatih sebuah model.

Langkah-langkah utama untuk membangun sebuah set data adalah:

  1. Buat set data dan tentukan apakah akan mengizinkan adanya label lebih dari satu untuk setiap item.
  2. Impor item data ke dalam set data.
  3. Memberi label pada item.

Jika Anda mengimpor item dengan label yang telah ditetapkan sebelumnya, langkah 2 dan 3 akan dilakukan pada saat yang sama.

Membuat set data

Langkah pertama dalam membuat sebuah model kustom adalah dengan membuat set data kosong yang akan menyimpan data pelatihan untuk model tersebut. Saat membuat set data, tentukan jenis klasifikasi yang ingin dijalankan oleh model kustom Anda:

  • MULTICLASS akan menetapkan hanya satu label ke setiap gambar yang diklasifikasikan
  • MULTILABEL akan memungkinkan sebuah gambar diberi lebih dari satu label

Mulai dari AutoML API versi v1, permintaan ini menampilkan ID operasi yang berjalan lama.

Setelah operasi yang berjalan lama telah selesai, Anda dapat mengimpor gambar ke dalamnya. Set data yang baru dibuat tidak berisi data apa pun sebelum Anda mengimpor gambar ke dalamnya.

Simpan ID set data dari set data baru (dari respons) untuk digunakan dengan operasi lain, seperti mengimpor gambar ke set data Anda dan melatih model.

UI Web

  1. Buka Dasbor Vision.

    Anda juga dapat mengakses halaman ini dari konsol melalui item menu navigasi Kecerdasan Buatan > Vision. Ini akan membawa anda ke dasbor Vision yang terintegrasi. Pilih kartu AutoML Vision.

    UI dasbor Vision yang terintegrasi

  2. Pilih Set Data dari menu navigasi sebelah kiri.

  3. Pilih tombol Set Data Baru di bagian atas, perbarui nama set data (opsional), lalu pilih klasifikasi label tunggal atau label majemuk berdasarkan data yang Anda miliki.

    Pilih jenis model untuk halaman set data

  4. Setelah menentukan jenis klasifikasi, pilih Buat Set Data.

  5. Pada halaman Buat Set Data, Anda dapat memilih sebuah file CSV dari Google Cloud Storage, atau file gambar lokal untuk diimpor ke dalam set data.

    pilih jendela impor csv

    Pilih Lanjut untuk memulai impor gambar ke set data Anda. Saat impor dimulai, set data akan menampilkan status Sedang Menjalankan: Mengimpor gambar.

  6. Anda akan menerima email saat proses impor telah selesai.

REST

Contoh di bawah ini membuat set data yang mendukung satu label per item (lihat MULTICLASS).

Set data yang baru saja dibuat tidak berisi data apa pun sampai Anda mengimpor item ke dalamnya.

Simpan "name" dari set data baru (dari respons) untuk digunakan saat operasi lain, seperti mengimpor item ke set data Anda dan melatih sebuah model.

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • project-id: project ID GCP Anda.
  • display-name: nama tampilan string pilihan Anda.

Metode HTTP dan URL:

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

Isi JSON permintaan:

{
  "displayName": "DISPLAY_NAME",
  "imageClassificationDatasetMetadata": {
    "classificationType": "MULTICLASS"
  }
}

Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:

curl

Simpan isi permintaan dalam file bernama request.json, dan jalankan perintah berikut:

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

PowerShell

Simpan isi permintaan dalam file bernama request.json, dan jalankan perintah berikut:

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

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

Anda akan melihat output yang serupa dengan berikut ini: Anda dapat menggunakan ID operasi (dalam hal ini, ICN3819960680614725486) untuk mendapatkan status tugas. Sebagai contoh, lihat Bekerja dengan operasi yang berjalan lama:

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

Setelah operasi yang berjalan lama selesai, Anda bisa mendapatkan ID set data dengan permintaan status operasi yang sama. Responsnya akan terlihat seperti berikut:

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

Go

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan untuk bahasa ini di halaman Library Klien.

import (
	"context"
	"fmt"
	"io"

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

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

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

	req := &automlpb.CreateDatasetRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		Dataset: &automlpb.Dataset{
			DisplayName: datasetName,
			DatasetMetadata: &automlpb.Dataset_ImageClassificationDatasetMetadata{
				ImageClassificationDatasetMetadata: &automlpb.ImageClassificationDatasetMetadata{
					// Specify the classification type:
					// - MULTILABEL: Multiple labels are allowed for one example.
					// - MULTICLASS: At most one label is allowed per example.
					ClassificationType: automlpb.ClassificationType_MULTILABEL,
				},
			},
		},
	}

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

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

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

	return nil
}

Java

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan untuk bahasa ini di halaman Library Klien.

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

class VisionClassificationCreateDataset {

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

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

      // Specify the classification type
      // Types:
      // MultiLabel: Multiple labels are allowed for one example.
      // MultiClass: At most one label is allowed per example.
      ClassificationType classificationType = ClassificationType.MULTILABEL;
      ImageClassificationDatasetMetadata metadata =
          ImageClassificationDatasetMetadata.newBuilder()
              .setClassificationType(classificationType)
              .build();
      Dataset dataset =
          Dataset.newBuilder()
              .setDisplayName(displayName)
              .setImageClassificationDatasetMetadata(metadata)
              .build();
      OperationFuture<Dataset, OperationMetadata> future =
          client.createDatasetAsync(projectLocation, dataset);

      Dataset createdDataset = future.get();

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

Node.js

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan untuk bahasa ini di halaman Library Klien.

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

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

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

async function createDataset() {
  // Construct request
  // Specify the classification type
  // Types:
  // MultiLabel: Multiple labels are allowed for one example.
  // MultiClass: At most one label is allowed per example.
  const request = {
    parent: client.locationPath(projectId, location),
    dataset: {
      displayName: displayName,
      imageClassificationDatasetMetadata: {
        classificationType: 'MULTILABEL',
      },
    },
  };

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

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

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

createDataset();

Python

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan untuk bahasa ini di halaman Library Klien.

from google.cloud import automl

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

client = automl.AutoMlClient()

# A resource that represents Google Cloud Platform location.
project_location = f"projects/{project_id}/locations/us-central1"
# Specify the classification type
# Types:
# MultiLabel: Multiple labels are allowed for one example.
# MultiClass: At most one label is allowed per example.
# https://cloud.google.com/automl/docs/reference/rpc/google.cloud.automl.v1#classificationtype
metadata = automl.ImageClassificationDatasetMetadata(
    classification_type=automl.ClassificationType.MULTILABEL
)
dataset = automl.Dataset(
    display_name=display_name,
    image_classification_dataset_metadata=metadata,
)

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

created_dataset = response.result()

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

Bahasa tambahan

C# : Ikuti Petunjuk penyiapan C# di halaman library klien, lalu kunjungi dokumentasi referensi AutoML Vision untuk .NET.

PHP : Ikuti Petunjuk penyiapan PHP di halaman library klien, lalu kunjungi dokumentasi referensi AutoML Vision untuk PHP.

Ruby : Harap ikuti Petunjuk penyiapan Ruby di halaman library klien, lalu kunjungi Dokumentasi referensi AutoML Vision untuk Ruby.

Mengimpor item ke dalam set data

Setelah membuat set data, Anda dapat mengimpor URI dan label item untuk item dari file CSV yang disimpan dalam sebuah bucket Google Cloud Storage. Untuk mengetahui detail tentang cara menyiapkan data dan membuat file CSV untuk diimpor, lihat Menyiapkan data pelatihan.

Anda dapat mengimpor item ke set data kosong atau mengimpor item tambahan ke set data yang ada.

UI Web

UI AutoML Vision memungkinkan Anda membuat set data baru dan mengimpor item ke dalamnya dari halaman yang sama; lihat Membuat set data. Langkah-langkah di bawah ini menunjukkan cara mengimpor item ke set data yang telah ada.

  1. Buka Vision Dashboard, lalu pilih set data dari halaman Set Data.

    Halaman daftar set data

  2. Di halaman Gambar, klik Tambahkan item di batang judul lalu pilih metode impor dari menu drop-down.

    Anda dapat:

    • Upload file .csv yang berisi gambar pelatihan dan label kategori yang terkait dari komputer lokal atau dari Google Cloud Storage.

    • Upload file .txt atau .zip yang berisi gambar pelatihan dari komputer lokal Anda.

  3. Pilih file yang akan diimpor.

REST

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • project-id: project ID GCP Anda.
  • dataset-id: ID set data Anda. ID adalah elemen terakhir dari nama set data Anda. Contoh:
    • nama set data: projects/project-id/locations/location-id/datasets/3104518874390609379
    • id set data: 3104518874390609379
  • input-storage-path: jalur ke file CSV yang disimpan di Google Cloud Storage. Pengguna yang meminta setidaknya harus memiliki izin baca ke bucket.

Metode HTTP dan URL:

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

Isi JSON permintaan:

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

Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:

curl

Simpan isi permintaan dalam file bernama request.json, dan jalankan perintah berikut:

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

PowerShell

Simpan isi permintaan dalam file bernama request.json, dan jalankan perintah berikut:

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

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

Anda akan melihat output yang serupa dengan berikut ini: Anda dapat menggunakan ID operasi (dalam contoh ini, ICN3819960680614725486) untuk mendapatkan status tugas tersebut. Sebagai contoh, lihat Bekerja dengan operasi yang berjalan lama.

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

Go

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan untuk bahasa ini di halaman Library Klien.

import (
	"context"
	"fmt"
	"io"

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

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

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

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

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

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

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

	return nil
}

Java

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan untuk bahasa ini di halaman Library Klien.

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

class ImportDataset {

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

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

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

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

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

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

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

Node.js

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan untuk bahasa ini di halaman Library Klien.

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

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

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

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

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

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

importDataset();

Python

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan untuk bahasa ini di halaman Library Klien.

from google.cloud import automl

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

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

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

Memberi label item pelatihan

Agar berguna untuk melatih model, setiap item dalam set data harus memiliki minimal satu label kategori yang ditetapkan padanya. AutoML Vision akan mengabaikan item yang tidak mempunyai label kategori. Anda dapat memberikan label untuk item pelatihan dengan tiga cara:

  1. Menyertakan label di file .csv Anda
  2. Memberikan label pada item di UI AutoML Vision
  3. Meminta pelabelan dari layanan pelabelan oleh manusia seperti Layanan Pelabelan Data AI Platform dari Google.

Pelabelan di UI

UI web

Untuk melabeli item di UI AutoML Vision, pilih set data dari halaman listingan Set Data untuk melihat detailnya.

Panel samping meringkas jumlah item yang berlabel dan yang tidak berlabel. Di sini, Anda dapat memfilter daftar item menurut label, atau memilih Tambahkan label baru untuk membuat label baru.

Halaman gambar

Dari layar tampian ini Anda juga dapat menambahkan atau mengubah label dari sebuah gambar.

Pilih gambar untuk menambahkan atau mengubah labelnya.

layar tampilan untuk menambahkan atau mengubah label gambar

Meminta pelabelan

Anda dapat memanfaatkan Layanan Pelabelan Data AI Platform Google untuk melabeli gambar-gambar Anda. Lihat dokumentasi produk untuk informasi selengkapnya.

Menangani operasi yang berjalan lama

Anda dapat mengetahui status dari sebuah operasi yang berjalan lama menggunakan contoh kode berikut.

REST

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • project-id: project ID GCP Anda.
  • operation-id: ID operasi Anda. ID tersebut adalah elemen terakhir dari nama operasi Anda. Contoh:
    • nama operasi: projects/project-id/locations/location-id/operations/IOD5281059901324392598
    • ID Operasi: IOD5281059901324392598

Metode HTTP dan URL:

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

Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:

curl

Jalankan perintah berikut:

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

PowerShell

Jalankan perintah berikut:

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

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID" | Select-Object -Expand Content
Anda akan melihat output yang serupa dengan berikut ini dari operasi impor yang telah selesai:
{
  "name": "projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2018-10-29T15:56:29.176485Z",
    "updateTime": "2018-10-29T16:10:41.326614Z",
    "importDataDetails": {}
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.protobuf.Empty"
  }
}

Anda akan melihat output yang mirip dengan hal berikut ini untuk membuat operasi model yang telah selesai:

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

Go

Sebelum mencoba sampel ini, ikuti petunjuk penyiapan untuk bahasa ini di halaman API & Referensi > Library Klien.

import (
	"context"
	"fmt"
	"io"

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

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

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

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

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

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

	return nil
}

Java

Sebelum mencoba sampel ini, ikuti petunjuk penyiapan untuk bahasa ini di halaman API & Referensi > Library Klien.

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

class GetOperationStatus {

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

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

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

Node.js

Sebelum mencoba sampel ini, ikuti petunjuk penyiapan untuk bahasa ini di halaman API & Referensi > Library Klien.

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

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

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

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

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

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

getOperationStatus();

Python

Sebelum mencoba sampel ini, ikuti petunjuk penyiapan untuk bahasa ini di halaman API & Referensi > Library Klien.

from google.cloud import automl

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

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

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

Bahasa tambahan

C# : Ikuti Petunjuk penyiapan C# di halaman library klien, lalu kunjungi dokumentasi referensi AutoML Vision untuk .NET.

PHP : Ikuti Petunjuk penyiapan PHP di halaman library klien, lalu kunjungi dokumentasi referensi AutoML Vision untuk PHP.

Ruby : Ikuti Petunjuk penyiapan Ruby di halaman library klien, lalu kunjungi dokumentasi referensi AutoML Vision untuk Ruby.