From 2f559d29dacba50c2944257c7f6e11ff13f0a297 Mon Sep 17 00:00:00 2001 From: Jeff Ching Date: Wed, 17 Mar 2021 15:28:49 -0700 Subject: [PATCH] samples: migrate samples from GoogleCloudPlatform/java-docs-samples /vision/automl (#261) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * samples: Automl (#1158) * Test push * Vision AutoML * Vision AutoML updates + Translate AutoML * Translate README fixes * Fixing Kokoro failure issue * Language AutoML * Vision AutoML * Translate AutoML files added * Triggering tests * Triggering tests * samples: Automl (#1162) * Test push * Vision AutoML * Vision AutoML updates + Translate AutoML * Translate README fixes * Fixing Kokoro failure issue * Language AutoML * Vision AutoML * Translate AutoML files added * Triggering tests * Triggering tests * Updates based on comments * Updates after review comments * Fixed build issue * samples: Clean up the code and fix the sample tests (#1463) * samples: Prevent Name collisions on tests (#1466) * samples: fix misspelling reported by user (#1451) * samples: Auto-update dependencies. (#1467) * Auto-update dependencies. * Rollback * Auto-update dependencies. * Fix merge errors * Rollback * Fix tests * Fix test * samples: Add new sample for deploying a model with a node count (#1601) * samples: Add missing samples for classification and rename object detection sa… (#1604) * Add missing samples for classification and rename object detection sample to add clarification * Update test function names * samples: automl: fix old beta snippet tests (#1994) * samples: docs: update tests that are failing or not cleaning up resources * samples: update shared config (#2443) * update shared config * Update to 1.0.13 * lint * Fix linting * lint * fix imports Co-authored-by: Les Vogel * samples: bug: fix importData sample in order to bump libraries-bom version (#3011) Fixes #2943 * samples: automl: remove vision samples no longer on cgc (#2844) - [ x] `pom.xml` parent set to latest `shared-configuration` - [ in progress] Appropriate changes to README are included in PR - [ ] API's need to be enabled to test (tell us) - [ ] Environment Variables need to be set (ask us to set them) - [see below] Tests pass (`mvn -P lint clean verify`) - [x ] Please **merge** this PR for me once it is approved. Need to take a look still at modelApi tests (it looks like the entire file is obviated, but could be refactored to test model creation?) Could use a second set of eyes here. * samples: samples: increased wait time for undeployed model prediction (#3286) * samples: increased wait time for undeployed model prediction * fixed the lint issue Co-authored-by: Nirupa Anantha Kumar Co-authored-by: Noah Negrey Co-authored-by: Andrew Ferlitsch Co-authored-by: DPEBot Co-authored-by: nnegrey Co-authored-by: Averi Kitsch Co-authored-by: Les Vogel Co-authored-by: Stephanie Wang Co-authored-by: Anthony Co-authored-by: Mike <45373284+munkhuushmgl@users.noreply.github.com> --- .../automl/ClassificationDeployModel.java | 60 ++++++++ .../ClassificationDeployModelNodeCount.java | 61 ++++++++ .../automl/ClassificationUndeployModel.java | 60 ++++++++ .../cloud/vision/samples/automl/ModelApi.java | 143 ++++++++++++++++++ .../ObjectDetectionDeployModelNodeCount.java | 60 ++++++++ .../vision/samples/automl/PredictionApi.java | 136 +++++++++++++++++ .../automl/ClassificationDeployModelIT.java | 88 +++++++++++ ...ObjectDetectionDeployModelNodeCountIT.java | 65 ++++++++ .../samples/automl/PredictionApiIT.java | 82 ++++++++++ 9 files changed, 755 insertions(+) create mode 100644 automl/snippets/src/main/java/com/google/cloud/vision/samples/automl/ClassificationDeployModel.java create mode 100644 automl/snippets/src/main/java/com/google/cloud/vision/samples/automl/ClassificationDeployModelNodeCount.java create mode 100644 automl/snippets/src/main/java/com/google/cloud/vision/samples/automl/ClassificationUndeployModel.java create mode 100644 automl/snippets/src/main/java/com/google/cloud/vision/samples/automl/ModelApi.java create mode 100644 automl/snippets/src/main/java/com/google/cloud/vision/samples/automl/ObjectDetectionDeployModelNodeCount.java create mode 100644 automl/snippets/src/main/java/com/google/cloud/vision/samples/automl/PredictionApi.java create mode 100644 automl/snippets/src/test/java/com/google/cloud/vision/samples/automl/ClassificationDeployModelIT.java create mode 100644 automl/snippets/src/test/java/com/google/cloud/vision/samples/automl/ObjectDetectionDeployModelNodeCountIT.java create mode 100644 automl/snippets/src/test/java/com/google/cloud/vision/samples/automl/PredictionApiIT.java diff --git a/automl/snippets/src/main/java/com/google/cloud/vision/samples/automl/ClassificationDeployModel.java b/automl/snippets/src/main/java/com/google/cloud/vision/samples/automl/ClassificationDeployModel.java new file mode 100644 index 00000000000..63da52ead0d --- /dev/null +++ b/automl/snippets/src/main/java/com/google/cloud/vision/samples/automl/ClassificationDeployModel.java @@ -0,0 +1,60 @@ +/* + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.vision.samples.automl; + +// [START automl_vision_classification_deploy_model] +import com.google.api.gax.longrunning.OperationFuture; +import com.google.cloud.automl.v1beta1.AutoMlClient; +import com.google.cloud.automl.v1beta1.DeployModelRequest; +import com.google.cloud.automl.v1beta1.ModelName; +import com.google.cloud.automl.v1beta1.OperationMetadata; +import com.google.protobuf.Empty; +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +class ClassificationDeployModel { + + // Deploy a model + static void classificationDeployModel(String projectId, String modelId) + throws IOException, ExecutionException, InterruptedException { + // String projectId = "YOUR_PROJECT_ID"; + // String modelId = "YOUR_MODEL_ID"; + + // 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 full path of the model. + ModelName modelFullId = ModelName.of(projectId, "us-central1", modelId); + + // Build deploy model request. + DeployModelRequest deployModelRequest = + DeployModelRequest.newBuilder().setName(modelFullId.toString()).build(); + + // Deploy a model with the deploy model request. + OperationFuture future = + client.deployModelAsync(deployModelRequest); + + future.get(); + + // Display the deployment details of model. + System.out.println("Model deployment finished"); + } + } +} +// [END automl_vision_classification_deploy_model] diff --git a/automl/snippets/src/main/java/com/google/cloud/vision/samples/automl/ClassificationDeployModelNodeCount.java b/automl/snippets/src/main/java/com/google/cloud/vision/samples/automl/ClassificationDeployModelNodeCount.java new file mode 100644 index 00000000000..655cd7218c9 --- /dev/null +++ b/automl/snippets/src/main/java/com/google/cloud/vision/samples/automl/ClassificationDeployModelNodeCount.java @@ -0,0 +1,61 @@ +/* + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.vision.samples.automl; + +// [START automl_vision_classification_deploy_model_node_count] +import com.google.api.gax.longrunning.OperationFuture; +import com.google.cloud.automl.v1beta1.AutoMlClient; +import com.google.cloud.automl.v1beta1.DeployModelRequest; +import com.google.cloud.automl.v1beta1.ImageClassificationModelDeploymentMetadata; +import com.google.cloud.automl.v1beta1.ModelName; +import com.google.cloud.automl.v1beta1.OperationMetadata; +import com.google.protobuf.Empty; +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +class ClassificationDeployModelNodeCount { + + // Deploy a model with a specified node count + static void classificationDeployModelNodeCount(String projectId, String modelId) + throws IOException, ExecutionException, InterruptedException { + // String projectId = "YOUR_PROJECT_ID"; + // String modelId = "YOUR_MODEL_ID"; + + // 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 full path of the model. + ModelName modelFullId = ModelName.of(projectId, "us-central1", modelId); + + // Set how many nodes the model is deployed on + ImageClassificationModelDeploymentMetadata deploymentMetadata = + ImageClassificationModelDeploymentMetadata.newBuilder().setNodeCount(2).build(); + + DeployModelRequest request = + DeployModelRequest.newBuilder() + .setName(modelFullId.toString()) + .setImageClassificationModelDeploymentMetadata(deploymentMetadata) + .build(); + // Deploy the model + OperationFuture future = client.deployModelAsync(request); + future.get(); + System.out.println("Model deployment on 2 nodes finished"); + } + } +} +// [END automl_vision_classification_deploy_model_node_count] diff --git a/automl/snippets/src/main/java/com/google/cloud/vision/samples/automl/ClassificationUndeployModel.java b/automl/snippets/src/main/java/com/google/cloud/vision/samples/automl/ClassificationUndeployModel.java new file mode 100644 index 00000000000..33e75cdb876 --- /dev/null +++ b/automl/snippets/src/main/java/com/google/cloud/vision/samples/automl/ClassificationUndeployModel.java @@ -0,0 +1,60 @@ +/* + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.vision.samples.automl; + +// [START automl_vision_classification_undeploy_model] +import com.google.api.gax.longrunning.OperationFuture; +import com.google.cloud.automl.v1beta1.AutoMlClient; +import com.google.cloud.automl.v1beta1.ModelName; +import com.google.cloud.automl.v1beta1.OperationMetadata; +import com.google.cloud.automl.v1beta1.UndeployModelRequest; +import com.google.protobuf.Empty; +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +class ClassificationUndeployModel { + + // Deploy a model + static void classificationUndeployModel(String projectId, String modelId) + throws IOException, ExecutionException, InterruptedException { + // String projectId = "YOUR_PROJECT_ID"; + // String modelId = "YOUR_MODEL_ID"; + + // 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 full path of the model. + ModelName modelFullId = ModelName.of(projectId, "us-central1", modelId); + + // Build deploy model request. + UndeployModelRequest undeployModelRequest = + UndeployModelRequest.newBuilder().setName(modelFullId.toString()).build(); + + // Deploy a model with the deploy model request. + OperationFuture future = + client.undeployModelAsync(undeployModelRequest); + + future.get(); + + // Display the deployment details of model. + System.out.println("Model undeploy finished"); + } + } +} +// [END automl_vision_classification_undeploy_model] diff --git a/automl/snippets/src/main/java/com/google/cloud/vision/samples/automl/ModelApi.java b/automl/snippets/src/main/java/com/google/cloud/vision/samples/automl/ModelApi.java new file mode 100644 index 00000000000..4b07977df3e --- /dev/null +++ b/automl/snippets/src/main/java/com/google/cloud/vision/samples/automl/ModelApi.java @@ -0,0 +1,143 @@ +/* + * Copyright 2018 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.vision.samples.automl; + +// Imports the Google Cloud client library +import com.google.api.gax.longrunning.OperationFuture; +import com.google.cloud.automl.v1beta1.AutoMlClient; +import com.google.cloud.automl.v1beta1.ClassificationProto.ClassificationEvaluationMetrics; +import com.google.cloud.automl.v1beta1.ClassificationProto.ClassificationEvaluationMetrics.ConfidenceMetricsEntry; +import com.google.cloud.automl.v1beta1.ImageClassificationModelMetadata; +import com.google.cloud.automl.v1beta1.ListModelEvaluationsRequest; +import com.google.cloud.automl.v1beta1.ListModelsRequest; +import com.google.cloud.automl.v1beta1.LocationName; +import com.google.cloud.automl.v1beta1.Model; +import com.google.cloud.automl.v1beta1.ModelEvaluation; +import com.google.cloud.automl.v1beta1.ModelEvaluationName; +import com.google.cloud.automl.v1beta1.ModelName; +import com.google.cloud.automl.v1beta1.OperationMetadata; +import com.google.longrunning.Operation; +import com.google.protobuf.Empty; +import java.io.IOException; +import java.util.List; +import java.util.concurrent.ExecutionException; +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; + +/** + * Google Cloud AutoML Vision API sample application. Example usage: mvn package exec:java + * -Dexec.mainClass ='com.google.cloud.vision.samples.automl.ModelApi' -Dexec.args='create_model + * [datasetId] test_model' + */ +public class ModelApi { + + // [START automl_vision_create_model] + /** + * Demonstrates using the AutoML client to create a model. + * + * @param projectId the Id of the project. + * @param computeRegion the Region name. + * @param dataSetId the Id of the dataset to which model is created. + * @param modelName the Name of the model. + * @param trainBudget the Budget for training the model. + */ + static void createModel( + String projectId, + String computeRegion, + String dataSetId, + String modelName, + String trainBudget) { + // Instantiates a client + try (AutoMlClient client = AutoMlClient.create()) { + + // A resource that represents Google Cloud Platform location. + LocationName projectLocation = LocationName.of(projectId, computeRegion); + + // Set model metadata. + ImageClassificationModelMetadata imageClassificationModelMetadata = + Long.valueOf(trainBudget) == 0 + ? ImageClassificationModelMetadata.newBuilder().build() + : ImageClassificationModelMetadata.newBuilder() + .setTrainBudget(Long.valueOf(trainBudget)) + .build(); + + // Set model name and model metadata for the image dataset. + Model myModel = + Model.newBuilder() + .setDisplayName(modelName) + .setDatasetId(dataSetId) + .setImageClassificationModelMetadata(imageClassificationModelMetadata) + .build(); + + // Create a model with the model metadata in the region. + OperationFuture response = + client.createModelAsync(projectLocation, myModel); + + System.out.println( + String.format( + "Training operation name: %s", response.getInitialFuture().get().getName())); + System.out.println("Training started..."); + } catch (IOException | ExecutionException | InterruptedException e) { + e.printStackTrace(); + } + } + // [END automl_vision_create_model] + + public static void main(String[] args) { + argsHelper(args); + } + + static void argsHelper(String[] args) { + ArgumentParser parser = + ArgumentParsers.newFor("ModelApi") + .build() + .defaultHelp(true) + .description("Model API operations."); + Subparsers subparsers = parser.addSubparsers().dest("command"); + + Subparser createModelParser = subparsers.addParser("create_model"); + createModelParser.addArgument("datasetId"); + createModelParser.addArgument("modelName"); + createModelParser.addArgument("trainBudget"); + + String projectId = System.getenv("GOOGLE_CLOUD_PROJECT"); + String computeRegion = System.getenv("REGION_NAME"); + + if (projectId == null || computeRegion == null) { + System.out.println("Set `GOOGLE_CLOUD_PROJECT` and `REGION_NAME` as specified in the README"); + System.exit(-1); + } + + try { + Namespace ns = parser.parseArgs(args); + if (ns.get("command").equals("create_model")) { + createModel( + projectId, + computeRegion, + ns.getString("datasetId"), + ns.getString("modelName"), + ns.getString("trainBudget")); + } + } catch (ArgumentParserException e) { + parser.handleError(e); + } + } +} diff --git a/automl/snippets/src/main/java/com/google/cloud/vision/samples/automl/ObjectDetectionDeployModelNodeCount.java b/automl/snippets/src/main/java/com/google/cloud/vision/samples/automl/ObjectDetectionDeployModelNodeCount.java new file mode 100644 index 00000000000..cd6de5c5bcc --- /dev/null +++ b/automl/snippets/src/main/java/com/google/cloud/vision/samples/automl/ObjectDetectionDeployModelNodeCount.java @@ -0,0 +1,60 @@ +/* + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.vision.samples.automl; + +// [START automl_vision_object_detection_deploy_model_node_count] +import com.google.api.gax.longrunning.OperationFuture; +import com.google.cloud.automl.v1beta1.AutoMlClient; +import com.google.cloud.automl.v1beta1.DeployModelRequest; +import com.google.cloud.automl.v1beta1.ImageObjectDetectionModelDeploymentMetadata; +import com.google.cloud.automl.v1beta1.ModelName; +import com.google.cloud.automl.v1beta1.OperationMetadata; +import com.google.protobuf.Empty; +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +class ObjectDetectionDeployModelNodeCount { + + static void objectDetectionDeployModelNodeCount(String projectId, String modelId) + throws IOException, ExecutionException, InterruptedException { + // String projectId = "YOUR_PROJECT_ID"; + // String modelId = "YOUR_MODEL_ID"; + + // 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 full path of the model. + ModelName modelFullId = ModelName.of(projectId, "us-central1", modelId); + + // Set how many nodes the model is deployed on + ImageObjectDetectionModelDeploymentMetadata deploymentMetadata = + ImageObjectDetectionModelDeploymentMetadata.newBuilder().setNodeCount(2).build(); + + DeployModelRequest request = + DeployModelRequest.newBuilder() + .setName(modelFullId.toString()) + .setImageObjectDetectionModelDeploymentMetadata(deploymentMetadata) + .build(); + // Deploy the model + OperationFuture future = client.deployModelAsync(request); + future.get(); + System.out.println("Model deployment on 2 nodes finished"); + } + } +} +// [END automl_vision_object_detection_deploy_model_node_count] diff --git a/automl/snippets/src/main/java/com/google/cloud/vision/samples/automl/PredictionApi.java b/automl/snippets/src/main/java/com/google/cloud/vision/samples/automl/PredictionApi.java new file mode 100644 index 00000000000..224c9a6db44 --- /dev/null +++ b/automl/snippets/src/main/java/com/google/cloud/vision/samples/automl/PredictionApi.java @@ -0,0 +1,136 @@ +/* + * Copyright 2018 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * This application demonstrates how to perform basic operations on prediction + * with the Google AutoML Vision API. + * + * For more information, the documentation at + * https://cloud.google.com/vision/automl/docs. + */ + +package com.google.cloud.vision.samples.automl; + +// Imports the Google Cloud client library +import com.google.cloud.automl.v1beta1.AnnotationPayload; +import com.google.cloud.automl.v1beta1.ExamplePayload; +import com.google.cloud.automl.v1beta1.Image; +import com.google.cloud.automl.v1beta1.ModelName; +import com.google.cloud.automl.v1beta1.PredictResponse; +import com.google.cloud.automl.v1beta1.PredictionServiceClient; +import com.google.protobuf.ByteString; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Map; +import net.sourceforge.argparse4j.ArgumentParsers; +import net.sourceforge.argparse4j.inf.ArgumentParser; +import net.sourceforge.argparse4j.inf.ArgumentParserException; +import net.sourceforge.argparse4j.inf.Namespace; + +/** + * Google Cloud AutoML Vision API sample application. Example usage: mvn package exec:java + * -Dexec.mainClass ='com.google.cloud.vision.samples.automl.PredictionApi' -Dexec.args='predict + * [modelId] [path-to-image] [scoreThreshold]' + */ +public class PredictionApi { + + // [START automl_vision_predict] + /** + * Demonstrates using the AutoML client to predict an image. + * + * @param projectId the Id of the project. + * @param computeRegion the Region name. + * @param modelId the Id of the model which will be used for text classification. + * @param filePath the Local text file path of the content to be classified. + * @param scoreThreshold the Confidence score. Only classifications with confidence score above + * scoreThreshold are displayed. + */ + static void predict( + String projectId, + String computeRegion, + String modelId, + String filePath, + String scoreThreshold) { + + // Instantiate client for prediction service. + try (PredictionServiceClient predictionClient = PredictionServiceClient.create()) { + + // Get the full path of the model. + ModelName name = ModelName.of(projectId, computeRegion, modelId); + + // Read the image and assign to payload. + ByteString content = ByteString.copyFrom(Files.readAllBytes(Paths.get(filePath))); + Image image = Image.newBuilder().setImageBytes(content).build(); + ExamplePayload examplePayload = ExamplePayload.newBuilder().setImage(image).build(); + + // Additional parameters that can be provided for prediction e.g. Score Threshold + Map params = new HashMap<>(); + if (scoreThreshold != null) { + params.put("score_threshold", scoreThreshold); + } + // Perform the AutoML Prediction request + PredictResponse response = predictionClient.predict(name, examplePayload, params); + + System.out.println("Prediction results:"); + for (AnnotationPayload annotationPayload : response.getPayloadList()) { + System.out.println("Predicted class name :" + annotationPayload.getDisplayName()); + System.out.println( + "Predicted class score :" + annotationPayload.getClassification().getScore()); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + // [END automl_vision_predict] + + public static void main(String[] args) { + argsHelper(args); + } + + static void argsHelper(String[] args) { + ArgumentParser parser = + ArgumentParsers.newFor("PredictionApi") + .build() + .defaultHelp(true) + .description("Prediction API Operation"); + + parser.addArgument("modelId").required(true); + parser.addArgument("filePath").required(true); + parser.addArgument("scoreThreshold").nargs("?").type(String.class).setDefault(""); + + String projectId = System.getenv("GOOGLE_CLOUD_PROJECT"); + String computeRegion = System.getenv("REGION_NAME"); + + if (projectId == null || computeRegion == null) { + System.out.println("Set `GOOGLE_CLOUD_PROJECT` and `REGION_NAME` as specified in the README"); + System.exit(-1); + } + + try { + Namespace ns = parser.parseArgs(args); + predict( + projectId, + computeRegion, + ns.getString("modelId"), + ns.getString("filePath"), + ns.getString("scoreThreshold")); + } catch (ArgumentParserException e) { + parser.handleError(e); + } + } +} diff --git a/automl/snippets/src/test/java/com/google/cloud/vision/samples/automl/ClassificationDeployModelIT.java b/automl/snippets/src/test/java/com/google/cloud/vision/samples/automl/ClassificationDeployModelIT.java new file mode 100644 index 00000000000..fa49c779fce --- /dev/null +++ b/automl/snippets/src/test/java/com/google/cloud/vision/samples/automl/ClassificationDeployModelIT.java @@ -0,0 +1,88 @@ +/* + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.vision.samples.automl; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.concurrent.ExecutionException; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class ClassificationDeployModelIT { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String MODEL_ID = "ICN0000000000000000000"; + private ByteArrayOutputStream bout; + private PrintStream out; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + System.setOut(out); + } + + @After + public void tearDown() { + System.setOut(null); + } + + @Test + public void testClassificationDeployModelApi() { + // As model deployment can take a long time, instead try to deploy a + // nonexistent model and confirm that the model was not found, but other + // elements of the request were valid. + try { + ClassificationDeployModel.classificationDeployModel(PROJECT_ID, MODEL_ID); + String got = bout.toString(); + assertThat(got).contains("The model does not exist"); + } catch (IOException | ExecutionException | InterruptedException e) { + assertThat(e.getMessage()).contains("The model does not exist"); + } + } + + @Test + public void testClassificationUndeployModelApi() { + // As model deployment can take a long time, instead try to deploy a + // nonexistent model and confirm that the model was not found, but other + // elements of the request were valid. + try { + ClassificationUndeployModel.classificationUndeployModel(PROJECT_ID, MODEL_ID); + String got = bout.toString(); + assertThat(got).contains("The model does not exist"); + } catch (IOException | ExecutionException | InterruptedException e) { + assertThat(e.getMessage()).contains("The model does not exist"); + } + } + + @Test + public void testClassificationDeployModelNodeCountApi() { + // As model deployment can take a long time, instead try to deploy a + // nonexistent model and confirm that the model was not found, but other + // elements of the request were valid. + try { + ClassificationDeployModelNodeCount.classificationDeployModelNodeCount(PROJECT_ID, MODEL_ID); + String got = bout.toString(); + assertThat(got).contains("The model does not exist"); + } catch (IOException | ExecutionException | InterruptedException e) { + assertThat(e.getMessage()).contains("The model does not exist"); + } + } +} diff --git a/automl/snippets/src/test/java/com/google/cloud/vision/samples/automl/ObjectDetectionDeployModelNodeCountIT.java b/automl/snippets/src/test/java/com/google/cloud/vision/samples/automl/ObjectDetectionDeployModelNodeCountIT.java new file mode 100644 index 00000000000..54a7f48dd85 --- /dev/null +++ b/automl/snippets/src/test/java/com/google/cloud/vision/samples/automl/ObjectDetectionDeployModelNodeCountIT.java @@ -0,0 +1,65 @@ +/* + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.vision.samples.automl; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.concurrent.ExecutionException; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for vision "Deploy Model Node Count" sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class ObjectDetectionDeployModelNodeCountIT { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String MODEL_ID = "0000000000000000000000"; + private ByteArrayOutputStream bout; + private PrintStream out; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + System.setOut(out); + } + + @After + public void tearDown() { + System.setOut(null); + } + + @Test + public void testObjectDetectionDeployModelNodeCountApi() { + // As model deployment can take a long time, instead try to deploy a + // nonexistent model and confirm that the model was not found, but other + // elements of the request were valid. + try { + ObjectDetectionDeployModelNodeCount.objectDetectionDeployModelNodeCount(PROJECT_ID, MODEL_ID); + String got = bout.toString(); + assertThat(got).contains("The model does not exist"); + } catch (IOException | ExecutionException | InterruptedException e) { + assertThat(e.getMessage()).contains("The model does not exist"); + } + } +} diff --git a/automl/snippets/src/test/java/com/google/cloud/vision/samples/automl/PredictionApiIT.java b/automl/snippets/src/test/java/com/google/cloud/vision/samples/automl/PredictionApiIT.java new file mode 100644 index 00000000000..01e4a91cb59 --- /dev/null +++ b/automl/snippets/src/test/java/com/google/cloud/vision/samples/automl/PredictionApiIT.java @@ -0,0 +1,82 @@ +/* + * Copyright 2018 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.vision.samples.automl; + +import static com.google.common.truth.Truth.assertThat; + +import com.google.cloud.automl.v1beta1.AutoMlClient; +import com.google.cloud.automl.v1beta1.DeployModelRequest; +import com.google.cloud.automl.v1beta1.Model; +import com.google.cloud.automl.v1beta1.ModelName; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for vision "PredictionAPI" sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class PredictionApiIT { + private static final String COMPUTE_REGION = "us-central1"; + private static final String PROJECT_ID = "java-docs-samples-testing"; + private static final String modelId = "ICN620201829169141520"; + private static final String filePath = "./resources/dandelion.jpg"; + private static final String scoreThreshold = "0.7"; + private ByteArrayOutputStream bout; + private PrintStream out; + + @Before + public void setUp() + throws IOException, ExecutionException, InterruptedException, TimeoutException { + // Verify that the model is deployed for prediction + try (AutoMlClient client = AutoMlClient.create()) { + ModelName modelFullId = ModelName.of(PROJECT_ID, "us-central1", modelId); + Model model = client.getModel(modelFullId); + if (model.getDeploymentState() == Model.DeploymentState.UNDEPLOYED) { + // Deploy the model if not deployed + DeployModelRequest request = + DeployModelRequest.newBuilder().setName(modelFullId.toString()).build(); + Future future = client.deployModelAsync(request); + future.get(30, TimeUnit.MINUTES); + } + } + + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + System.setOut(out); + } + + @After + public void tearDown() { + System.setOut(null); + } + + @Test + public void testPredict() { + PredictionApi.predict(PROJECT_ID, COMPUTE_REGION, modelId, filePath, scoreThreshold); + String got = bout.toString(); + assertThat(got).contains("dandelion"); + } +}