Effectuer des prédictions par lot

Après avoir créé (entraîné) un modèle, vous pouvez envoyer une requête de prédiction asynchrone pour un lot d'images à l'aide de la méthode batchPredict. La méthode batchPredict applique des annotations à votre image en fonction des objets identifiés par votre modèle.

La durée de vie maximale d'un modèle personnalisé est de 18 mois. Vous devez créer et entraîner un nouveau modèle pour continuer à annoter du contenu au-delà de cette période.

Prédiction par lot

Vous pouvez demander des annotations (prédictions) pour les images à l'aide de la commande batchPredict. La commande batchPredict utilise un fichier CSV stocké dans votre emplacement Google Cloud Storage qui contient les chemins d'accès aux images à annoter. Chaque ligne spécifie un chemin d'accès distinct pour une image dans Google Cloud Storage. Exemple :

batch_prediction.csv

gs://my-cloud-storage-bucket/prediction_files/image1.jpg
gs://my-cloud-storage-bucket/prediction_files/image2.jpg
gs://my-cloud-storage-bucket/prediction_files/image3.jpg
gs://my-cloud-storage-bucket/prediction_files/image4.jpg
gs://my-cloud-storage-bucket/prediction_files/image5.jpg
gs://my-cloud-storage-bucket/prediction_files/image6.png

En fonction du nombre d'images que vous avez spécifié dans votre fichier CSV, la tâche de prédiction par lot peut prendre un certain temps. Même avec un petit nombre d'images, la prédiction par lot prendra au moins 30 minutes.

REST

Avant d'utiliser les données de requête ci-dessous, effectuez les remplacements suivants :

  • project-id : ID de votre projet GCP.
  • location-id : identifiant d'emplacement valide. Actuellement, vous devez utiliser la valeur suivante :
    • us-central1
  • model-id : ID de votre modèle, issu de la réponse obtenue lors de sa création. L'ID est le dernier élément du nom du modèle. Exemple :
    • Nom du modèle : projects/project-id/locations/location-id/models/IOD4412217016962778756
    • ID du modèle : IOD4412217016962778756
  • input-storage-path : chemin d'accès à un fichier CSV stocké sur Google Cloud Storage. L'utilisateur demandeur doit au minimum disposer d'autorisations en lecture sur le bucket.
  • output-storage-bucket : répertoire/bucket Google Cloud Storage dans lequel enregistrer les fichiers de sortie, sous ce format : gs://bucket/directory/. L'utilisateur demandeur doit disposer d'autorisations en écriture sur le bucket.

Remarque sur les champs :

  • params.score_threshold : valeur comprise entre 0 et 1. Seuls les résultats dont les scores sont supérieurs ou égaux à cette valeur sont renvoyés.

Méthode HTTP et URL :

POST https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/models/MODEL_ID:batchPredict

Corps JSON de la requête :

{
  "inputConfig": {
    "gcsSource": {
       "inputUris": [ "INPUT_STORAGE_PATH" ]
    }
  },
  "outputConfig": {
    "gcsDestination": {
      "outputUriPrefix": "OUTPUT_STORAGE_BUCKET"
    }
  },
  "params": {
    "score_threshold": "0.0"
  }
}

Pour envoyer votre requête, choisissez l'une des options suivantes :

curl

Enregistrez le corps de la requête dans un fichier nommé request.json, puis exécutez la commande suivante :

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/LOCATION_ID/models/MODEL_ID:batchPredict"

PowerShell

Enregistrez le corps de la requête dans un fichier nommé request.json, puis exécutez la commande suivante :

$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/LOCATION_ID/models/MODEL_ID:batchPredict" | Select-Object -Expand Content
Réponse :

La sortie obtenue doit ressembler à ceci :

{
  "name": "projects/PROJECT_ID/locations/LOCATION_ID/operations/IOD926615623331479552",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2019-06-19T21:28:35.302067Z",
    "updateTime": "2019-06-19T21:28:35.302067Z",
    "batchPredictDetails": {
      "inputConfig": {
        "gcsSource": {
          "inputUris": [
            "INPUT_STORAGE_PATH"
          ]
        }
      }
    }
  }
}

Vous pouvez utiliser l'ID d'opération (IOD926615623331479552 dans ce cas) pour connaître l'état de la tâche. Pour consulter un exemple, reportez-vous à la section Travailler avec des opérations de longue durée.

En fonction du nombre d'images que vous avez spécifié dans votre fichier CSV, la tâche de prédiction par lot peut prendre un certain temps. Même avec un petit nombre d'images, la prédiction par lot prendra au moins 30 minutes.

Une fois l'opération terminée, state prend la valeur DONE, et le résultat est enregistré dans le fichier Google Cloud Storage que vous avez spécifié :

{
  "name": "projects/PROJECT_ID/locations/LOCATION_ID/operations/IOD926615623331479552",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2019-06-19T21:28:35.302067Z",
    "updateTime": "2019-06-19T21:57:18.310033Z",
    "batchPredictDetails": {
      "inputConfig": {
        "gcsSource": {
          "inputUris": [
            "INPUT_STORAGE_PATH"
          ]
        }
      },
      "outputInfo": {
        "gcsOutputDirectory": "gs://STORAGE_BUCKET_VCM/SUBDIRECTORY/prediction-8370559933346329705-YYYY-MM-DDThh:mm:ss.sssZ"
      }
    }
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.BatchPredictResult"
  }
}

Consultez la section Fichiers JSONL de sortie ci-dessous pour obtenir un exemple de fichier de sortie.

Java

Avant d'essayer l'exemple ci-dessous, suivez les instructions de configuration pour ce langage sur la page Bibliothèques clientes.

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.automl.v1.BatchPredictInputConfig;
import com.google.cloud.automl.v1.BatchPredictOutputConfig;
import com.google.cloud.automl.v1.BatchPredictRequest;
import com.google.cloud.automl.v1.BatchPredictResult;
import com.google.cloud.automl.v1.GcsDestination;
import com.google.cloud.automl.v1.GcsSource;
import com.google.cloud.automl.v1.ModelName;
import com.google.cloud.automl.v1.OperationMetadata;
import com.google.cloud.automl.v1.PredictionServiceClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

abstract class BatchPredict {

  static void batchPredict() throws IOException, ExecutionException, InterruptedException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String modelId = "YOUR_MODEL_ID";
    String inputUri = "gs://YOUR_BUCKET_ID/path_to_your_input_csv_or_jsonl";
    String outputUri = "gs://YOUR_BUCKET_ID/path_to_save_results/";
    batchPredict(projectId, modelId, inputUri, outputUri);
  }

  static void batchPredict(String projectId, String modelId, String inputUri, String outputUri)
      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 (PredictionServiceClient client = PredictionServiceClient.create()) {
      // Get the full path of the model.
      ModelName name = ModelName.of(projectId, "us-central1", modelId);
      GcsSource gcsSource = GcsSource.newBuilder().addInputUris(inputUri).build();
      BatchPredictInputConfig inputConfig =
          BatchPredictInputConfig.newBuilder().setGcsSource(gcsSource).build();
      GcsDestination gcsDestination =
          GcsDestination.newBuilder().setOutputUriPrefix(outputUri).build();
      BatchPredictOutputConfig outputConfig =
          BatchPredictOutputConfig.newBuilder().setGcsDestination(gcsDestination).build();
      BatchPredictRequest request =
          BatchPredictRequest.newBuilder()
              .setName(name.toString())
              .setInputConfig(inputConfig)
              .setOutputConfig(outputConfig)
              .build();

      OperationFuture<BatchPredictResult, OperationMetadata> future =
          client.batchPredictAsync(request);

      System.out.println("Waiting for operation to complete...");
      future.get();
      System.out.println("Batch Prediction results saved to specified Cloud Storage bucket.");
    }
  }
}

Node.js

Avant d'essayer l'exemple ci-dessous, suivez les instructions de configuration pour ce langage sur la page Bibliothèques clientes.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const modelId = 'YOUR_MODEL_ID';
// const inputUri = 'gs://YOUR_BUCKET_ID/path_to_your_input_csv_or_jsonl';
// const outputUri = 'gs://YOUR_BUCKET_ID/path_to_save_results/';

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

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

async function batchPredict() {
  // Construct request
  const request = {
    name: client.modelPath(projectId, location, modelId),
    inputConfig: {
      gcsSource: {
        inputUris: [inputUri],
      },
    },
    outputConfig: {
      gcsDestination: {
        outputUriPrefix: outputUri,
      },
    },
  };

  const [operation] = await client.batchPredict(request);

  console.log('Waiting for operation to complete...');
  // Wait for operation to complete.
  const [response] = await operation.promise();
  console.log(
    `Batch Prediction results saved to Cloud Storage bucket. ${response}`
  );
}

batchPredict();

Python

Avant d'essayer l'exemple ci-dessous, suivez les instructions de configuration pour ce langage sur la page Bibliothèques clientes.

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"
# model_id = "YOUR_MODEL_ID"
# input_uri = "gs://YOUR_BUCKET_ID/path/to/your/input/csv_or_jsonl"
# output_uri = "gs://YOUR_BUCKET_ID/path/to/save/results/"

prediction_client = automl.PredictionServiceClient()

# Get the full path of the model.
model_full_id = f"projects/{project_id}/locations/us-central1/models/{model_id}"

gcs_source = automl.GcsSource(input_uris=[input_uri])

input_config = automl.BatchPredictInputConfig(gcs_source=gcs_source)
gcs_destination = automl.GcsDestination(output_uri_prefix=output_uri)
output_config = automl.BatchPredictOutputConfig(gcs_destination=gcs_destination)

response = prediction_client.batch_predict(
    name=model_full_id, input_config=input_config, output_config=output_config
)

print("Waiting for operation to complete...")
print(
    f"Batch Prediction results saved to Cloud Storage bucket. {response.result()}"
)

Langages supplémentaires

C# : Veuillez suivre les Instructions de configuration pour C# sur la page des bibliothèques clientes, puis consultez la Documentation de référence sur la détection d'objets AutoML Vision pour .NET.

PHP : Veuillez suivre les Instructions de configuration pour PHP sur la page des bibliothèques clientes, puis consultez la Documentation de référence sur la détection d'objets AutoML Vision pour PHP.

Ruby : Veuillez suivre les Instructions de configuration de Ruby sur la page des bibliothèques clientes, puis consultez la Documentation de référence sur la détection d'objets AutoML Vision pour Ruby.

Fichiers JSONL de sortie

Une fois la tâche de prédiction par lot terminée, le résultat de la prédiction est stocké dans le bucket Google Cloud Storage spécifié dans la commande.

Dans l'emplacement de stockage de sortie (avec le préfixe d'objet choisi), les fichiers image_object_detection_1.jsonl, image_object_detection_2.jsonl,..., image_object_detection_N.jsonl seront créés, où N peut être égal à 1 et dépend du nombre total d'images et d'annotations correctement prédites.

Chaque image ne sera répertoriée qu'une seule fois avec toutes ses annotations, et ses annotations ne seront jamais réparties entre les fichiers.

Chaque fichier JSONL contiendra, par ligne, une représentation JSON d'un proto qui entoure la valeur "ID" : "<id_value>" de l'image, suivi d'une liste comportant zéro ou plusieurs protos AnnotationPayload (appelés annotations), dont les détails imageObjectDetection sont renseignés.

Exemple de fichier JSONL (un seul fichier .jsonl avec 2 lignes/annotations de fichier) :

image_object_detection_0.jsonl

Travailler avec des opérations de longue durée

REST

Avant d'utiliser les données de requête ci-dessous, effectuez les remplacements suivants :

  • project-id : ID de votre projet GCP.
  • operation-id : ID de l'opération. L'ID est le dernier élément du nom de l'opération. Exemple :
    • Nom de l'opération : projects/project-id/locations/location-id/operations/IOD5281059901324392598
    • ID de l'opération : IOD5281059901324392598

Méthode HTTP et URL :

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

Pour envoyer votre requête, choisissez l'une des options suivantes :

curl

Exécutez la commande suivante :

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

Exécutez la commande suivante :

$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
Vous devez obtenir un résultat semblable au suivant à l'issue d'une opération d'importation :
{
  "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"
  }
}

Vous devez obtenir un résultat semblable au suivant à l'issue d'une opération de création de modèle :

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

Avant d'essayer l'exemple ci-dessous, suivez les instructions de configuration pour ce langage sur la page Bibliothèques clientes.

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

Avant d'essayer l'exemple ci-dessous, suivez les instructions de configuration pour ce langage sur la page Bibliothèques clientes.

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

Avant d'essayer l'exemple ci-dessous, suivez les instructions de configuration pour ce langage sur la page Bibliothèques clientes.

/**
 * 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

Avant d'essayer l'exemple ci-dessous, suivez les instructions de configuration pour ce langage sur la page Bibliothèques clientes.

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)

Langages supplémentaires

C# : Veuillez suivre les Instructions de configuration pour C# sur la page des bibliothèques clientes, puis consultez la Documentation de référence sur la détection d'objets AutoML Vision pour .NET.

PHP : Veuillez suivre les Instructions de configuration pour PHP sur la page des bibliothèques clientes, puis consultez la Documentation de référence sur la détection d'objets AutoML Vision pour PHP.

Ruby : Veuillez suivre les Instructions de configuration pour Ruby sur la page des bibliothèques clientes, puis consultez la Documentation de référence sur la détection d'objets AutoML Vision pour Ruby.