From d9216d5f27d49e42bab2c980879ffc72a66616d6 Mon Sep 17 00:00:00 2001 From: nirupa-kumar Date: Mon, 23 Jul 2018 16:04:13 -0700 Subject: [PATCH] Translate AutoML files added --- .../cloud/translate/automl/DatasetApi.java | 314 ++++++++++++++++ .../cloud/translate/automl/ModelApi.java | 341 ++++++++++++++++++ .../cloud/translate/automl/PredictionApi.java | 140 +++++++ 3 files changed, 795 insertions(+) create mode 100644 translate/automl/src/main/java/com/google/cloud/translate/automl/DatasetApi.java create mode 100644 translate/automl/src/main/java/com/google/cloud/translate/automl/ModelApi.java create mode 100644 translate/automl/src/main/java/com/google/cloud/translate/automl/PredictionApi.java diff --git a/translate/automl/src/main/java/com/google/cloud/translate/automl/DatasetApi.java b/translate/automl/src/main/java/com/google/cloud/translate/automl/DatasetApi.java new file mode 100644 index 00000000000..03cc96aa45f --- /dev/null +++ b/translate/automl/src/main/java/com/google/cloud/translate/automl/DatasetApi.java @@ -0,0 +1,314 @@ +/* + * 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.translate.automl; + +// Imports the Google Cloud client library +import com.google.cloud.automl.v1beta1.AutoMlClient; +import com.google.cloud.automl.v1beta1.Dataset; +import com.google.cloud.automl.v1beta1.DatasetName; +import com.google.cloud.automl.v1beta1.GcsSource; +import com.google.cloud.automl.v1beta1.GcsSource.Builder; +import com.google.cloud.automl.v1beta1.InputConfig; +import com.google.cloud.automl.v1beta1.ListDatasetsRequest; +import com.google.cloud.automl.v1beta1.LocationName; +import com.google.cloud.automl.v1beta1.TranslationDatasetMetadata; +import com.google.protobuf.Empty; + +import java.io.IOException; +import java.io.PrintStream; + +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 Translate API sample application. Example usage: mvn package exec:java + * -Dexec.mainClass ='com.google.cloud.translate.samples.DatasetAPI' -Dexec.args='create_dataset + * test_dataset' + */ +public class DatasetApi { + + // [START automl_translate_create_dataset] + /** + * Demonstrates using the AutoML client to create a dataset + * + * @param projectId the Google Cloud Project ID. + * @param computeRegion the Region name. (e.g., "us-central1"). + * @param datasetName the name of the dataset to be created. + * @param source the Source language + * @param target the Target language + * @throws IOException on Input/Output errors. + */ + public static void createDataset( + String projectId, String computeRegion, String datasetName, String source, String target) + throws IOException { + // Instantiates a client + AutoMlClient client = AutoMlClient.create(); + + // A resource that represents Google Cloud Platform location. + LocationName projectLocation = LocationName.of(projectId, computeRegion); + + // Specify the source and target language. + TranslationDatasetMetadata translationDatasetMetadata = + TranslationDatasetMetadata.newBuilder() + .setSourceLanguageCode(source) + .setTargetLanguageCode(target) + .build(); + + // Set dataset name and dataset metadata. + Dataset myDataset = + Dataset.newBuilder() + .setDisplayName(datasetName) + .setTranslationDatasetMetadata(translationDatasetMetadata) + .build(); + + // Create a dataset with the dataset metadata in the region. + Dataset dataset = client.createDataset(projectLocation, myDataset); + + // Display the dataset information. + System.out.println(String.format("Dataset name: %s", dataset.getName())); + System.out.println( + String.format( + "Dataset id: %s", + dataset.getName().split("/")[dataset.getName().split("/").length - 1])); + System.out.println(String.format("Dataset display name: %s", dataset.getDisplayName())); + System.out.println("Translation dataset Metadata:"); + System.out.println( + String.format( + "\tSource language code: %s", + dataset.getTranslationDatasetMetadata().getSourceLanguageCode())); + System.out.println( + String.format( + "\tTarget language code: %s", + dataset.getTranslationDatasetMetadata().getTargetLanguageCode())); + System.out.println("Dataset create time:"); + System.out.println(String.format("\tseconds: %s", dataset.getCreateTime().getSeconds())); + System.out.println(String.format("\tnanos: %s", dataset.getCreateTime().getNanos())); + } + // [END automl_translation_create_dataset] + + // [START automl_translation_list_datasets] + /** + * Demonstrates using the AutoML client to list all datasets. + * + * @param projectId the Google Cloud Project ID. + * @param computeRegion the Region name. (e.g., "us-central1"). + * @param filter the Filter expression. + * @throws Exception on AutoML Client errors + */ + public static void listDatasets(String projectId, String computeRegion, String filter) + throws IOException { + // Instantiates a client + AutoMlClient client = AutoMlClient.create(); + + // A resource that represents Google Cloud Platform location. + LocationName projectLocation = LocationName.of(projectId, computeRegion); + + ListDatasetsRequest request = + ListDatasetsRequest.newBuilder() + .setParent(projectLocation.toString()) + .setFilter(filter) + .build(); + + // List all the datasets available in the region by applying filter. + System.out.println("List of datasets:"); + for (Dataset dataset : client.listDatasets(request).iterateAll()) { + // Display the dataset information + System.out.println(String.format("\nDataset name: %s", dataset.getName())); + System.out.println( + String.format( + "Dataset id: %s", + dataset.getName().split("/")[dataset.getName().split("/").length - 1])); + System.out.println(String.format("Dataset display name: %s", dataset.getDisplayName())); + System.out.println("Translation dataset metadata:"); + System.out.println( + String.format( + "\tSource language code: %s", + dataset.getTranslationDatasetMetadata().getSourceLanguageCode())); + System.out.println( + String.format( + "\tTarget language code: %s", + dataset.getTranslationDatasetMetadata().getTargetLanguageCode())); + System.out.println("Dataset create time:"); + System.out.println(String.format("\tseconds: %s", dataset.getCreateTime().getSeconds())); + System.out.println(String.format("\tnanos: %s", dataset.getCreateTime().getNanos())); + } + } + // [END automl_translation_list_datasets] + + // [START automl_translation_get_dataset] + /** + * Demonstrates using the AutoML client to get a dataset by ID. + * + * @param projectId the Google Cloud Project ID. + * @param computeRegion the Region name. (e.g., "us-central1"). + * @param datasetId the Id of the dataset. + * @throws Exception on AutoML Client errors + */ + public static void getDataset(String projectId, String computeRegion, String datasetId) + throws Exception { + // Instantiates a client + AutoMlClient client = AutoMlClient.create(); + + // Get the complete path of the dataset. + DatasetName datasetFullId = DatasetName.of(projectId, computeRegion, datasetId); + + // Get all the information about a given dataset. + Dataset dataset = client.getDataset(datasetFullId); + + // Display the dataset information + System.out.println(String.format("Dataset name: %s", dataset.getName())); + System.out.println( + String.format( + "Dataset id: %s", + dataset.getName().split("/")[dataset.getName().split("/").length - 1])); + System.out.println(String.format("Dataset display name: %s", dataset.getDisplayName())); + System.out.println("Translation dataset metadata:"); + System.out.println( + String.format( + "\tSource language code: %s", + dataset.getTranslationDatasetMetadata().getSourceLanguageCode())); + System.out.println( + String.format( + "\tTarget language code: %s", + dataset.getTranslationDatasetMetadata().getTargetLanguageCode())); + System.out.println("Dataset create time:"); + System.out.println(String.format("\tseconds: %s", dataset.getCreateTime().getSeconds())); + System.out.println(String.format("\tnanos: %s", dataset.getCreateTime().getNanos())); + } + // [END automl_translation_get_dataset] + + // [START automl_translation_import_data] + /** + * Import sentence pairs to the dataset. + * + * @param projectId the Google Cloud Project ID. + * @param computeRegion the Region name. (e.g., "us-central1"). + * @param datasetId the Id of the dataset. + * @param path the remote Path of the training data csv file. + * @throws Exception on AutoML Client errors + */ + public static void importData( + String projectId, String computeRegion, String datasetId, String path) throws Exception { + // Instantiates a client + AutoMlClient client = AutoMlClient.create(); + + // Get the complete path of the dataset. + DatasetName datasetFullId = DatasetName.of(projectId, computeRegion, datasetId); + + Builder gcsSource = GcsSource.newBuilder(); + + // Get multiple Google Cloud Storage URIs to import data from + String[] inputUris = path.split(","); + for (String inputUri : inputUris) { + gcsSource.addInputUris(inputUri); + } + + // Import data from the input URI + InputConfig inputConfig = InputConfig.newBuilder().setGcsSource(gcsSource).build(); + System.out.println("Processing import..."); + + Empty response = client.importDataAsync(datasetFullId, inputConfig).get(); + System.out.println(String.format("Dataset imported. %s", response)); + } + // [END automl_translation_import_data] + + // [START automl_translation_delete_dataset] + /** + * Delete a dataset. + * + * @param projectId the Google Cloud Project ID. + * @param computeRegion the Region name. (e.g., "us-central1"). + * @param datasetId the Id of the dataset. + * @throws Exception on AutoML Client errors + */ + public static void deleteDataset(String projectId, String computeRegion, String datasetId) + throws Exception { + // Instantiates a client + AutoMlClient client = AutoMlClient.create(); + + // Get the full path of the dataset. + DatasetName datasetFullId = DatasetName.of(projectId, computeRegion, datasetId); + + // Delete a dataset. + Empty response = client.deleteDatasetAsync(datasetFullId).get(); + + System.out.println(String.format("Dataset deleted. %s", response)); + } + // [END automl_translation_delete_dataset] + + public static void main(String[] args) throws Exception { + DatasetApi datasetApi = new DatasetApi(); + datasetApi.argsHelper(args, System.out); + } + + public static void argsHelper(String[] args, PrintStream out) throws Exception { + ArgumentParser parser = ArgumentParsers.newFor("").build(); + Subparsers subparsers = parser.addSubparsers().dest("command"); + + Subparser createDatasetParser = subparsers.addParser("create_dataset"); + createDatasetParser.addArgument("datasetName"); + createDatasetParser.addArgument("source"); + createDatasetParser.addArgument("target"); + + Subparser listDatasetParser = subparsers.addParser("list_datasets"); + listDatasetParser.addArgument("filter").nargs("?").setDefault("translation_dataset_metadata:*"); + + Subparser getDatasetParser = subparsers.addParser("get_dataset"); + getDatasetParser.addArgument("datasetId"); + + Subparser importDataParser = subparsers.addParser("import_data"); + importDataParser.addArgument("datasetId"); + importDataParser.addArgument("path"); + + Subparser deleteDatasetParser = subparsers.addParser("delete_dataset"); + deleteDatasetParser.addArgument("datasetId"); + + String projectId = System.getenv("PROJECT_ID"); + String computeRegion = System.getenv("REGION_NAME"); + + Namespace ns = null; + try { + ns = parser.parseArgs(args); + if (ns.get("command").equals("create_dataset")) { + createDataset( + projectId, + computeRegion, + ns.getString("datasetName"), + ns.getString("source"), + ns.getString("target")); + } + if (ns.get("command").equals("list_datasets")) { + listDatasets(projectId, computeRegion, ns.getString("filter")); + } + if (ns.get("command").equals("get_dataset")) { + getDataset(projectId, computeRegion, ns.getString("datasetId")); + } + if (ns.get("command").equals("import_data")) { + importData(projectId, computeRegion, ns.getString("datasetId"), ns.getString("path")); + } + if (ns.get("command").equals("delete_dataset")) { + deleteDataset(projectId, computeRegion, ns.getString("datasetId")); + } + } catch (ArgumentParserException e) { + parser.handleError(e); + } + } +} diff --git a/translate/automl/src/main/java/com/google/cloud/translate/automl/ModelApi.java b/translate/automl/src/main/java/com/google/cloud/translate/automl/ModelApi.java new file mode 100644 index 00000000000..c720c3d5f40 --- /dev/null +++ b/translate/automl/src/main/java/com/google/cloud/translate/automl/ModelApi.java @@ -0,0 +1,341 @@ +/* + * 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.translate.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.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.cloud.automl.v1beta1.TranslationModelMetadata; +import com.google.longrunning.Operation; +import com.google.protobuf.Empty; + +import java.io.IOException; +import java.io.PrintStream; +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 Translate API sample application. Example usage: mvn package exec:java + * -Dexec.mainClass ='com.example.translate.ModelApi' -Dexec.args='create_model [datasetId] + * test_model' + */ +public class ModelApi { + + // [START automl_translation_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. + * @throws Exception on AutoML Client errors + */ + public static void createModel( + String projectId, String computeRegion, String dataSetId, String modelName) throws Exception { + // Instantiates a client + AutoMlClient client = AutoMlClient.create(); + + // A resource that represents Google Cloud Platform location. + LocationName projectLocation = LocationName.of(projectId, computeRegion); + + // Set model metadata. + TranslationModelMetadata translationModelMetadata = + TranslationModelMetadata.newBuilder().setBaseModel("").build(); + + // Set model name, dataset and metadata. + Model myModel = + Model.newBuilder() + .setDisplayName(modelName) + .setDatasetId(dataSetId) + .setTranslationModelMetadata(translationModelMetadata) + .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..."); + } + // [END automl_translation_create_model] + + // [START automl_translation_list_models] + /** + * Demonstrates using the AutoML client to list all models. + * + * @param projectId the Id of the project. + * @param computeRegion the Region name. + * @param filter the filter expression. + * @throws IOException on Input/Output errors. + */ + public static void listModels(String projectId, String computeRegion, String filter) + throws IOException { + // Instantiates a client + AutoMlClient client = AutoMlClient.create(); + + // A resource that represents Google Cloud Platform location. + LocationName projectLocation = LocationName.of(projectId, computeRegion); + + // Create list models request. + ListModelsRequest listModlesRequest = + ListModelsRequest.newBuilder() + .setParent(projectLocation.toString()) + .setFilter(filter) + .build(); + + // List all the models available in the region by applying filter. + System.out.println("List of models:"); + for (Model model : client.listModels(listModlesRequest).iterateAll()) { + // Display the model information. + System.out.println(String.format("Model name: %s", model.getName())); + System.out.println( + String.format( + "Model id: %s", model.getName().split("/")[model.getName().split("/").length - 1])); + System.out.println(String.format("Model display name: %s", model.getDisplayName())); + System.out.println("Model create time:"); + System.out.println(String.format("\tseconds: %s", model.getCreateTime().getSeconds())); + System.out.println(String.format("\tnanos: %s", model.getCreateTime().getNanos())); + System.out.println(String.format("Model deployment state: %s", model.getDeploymentState())); + } + } + // [END automl_translation_list_models] + + // [START automl_translation_get_model] + /** + * Demonstrates using the AutoML client to get model details. + * + * @param projectId the Id of the project. + * @param computeRegion the Region name. + * @param modelId the Id of the model. + * @throws IOException on Input/Output errors. + */ + public static void getModel(String projectId, String computeRegion, String modelId) + throws IOException { + // Instantiates a client + AutoMlClient client = AutoMlClient.create(); + + // Get the full path of the model. + ModelName modelFullId = ModelName.of(projectId, computeRegion, modelId); + + // Get complete detail of the model. + Model model = client.getModel(modelFullId); + + // Display the model information. + System.out.println(String.format("Model name: %s", model.getName())); + System.out.println( + String.format( + "Model id: %s", model.getName().split("/")[model.getName().split("/").length - 1])); + System.out.println(String.format("Model display name: %s", model.getDisplayName())); + System.out.println("Model create time:"); + System.out.println(String.format("\tseconds: %s", model.getCreateTime().getSeconds())); + System.out.println(String.format("\tnanos: %s", model.getCreateTime().getNanos())); + System.out.println(String.format("Model deployment state: %s", model.getDeploymentState())); + } + // [END automl_translation_get_model] + + // [START automl_translation_list_model_evaluations] + /** + * Demonstrates using the AutoML client to list model evaluations. + * + * @param projectId the Id of the project. + * @param computeRegion the Region name. + * @param modelId the Id of the model. + * @param filter the filter expression. + * @throws IOException on Input/Output errors. + */ + public static void listModelEvaluations( + String projectId, String computeRegion, String modelId, String filter) throws IOException { + // Instantiates a client + AutoMlClient client = AutoMlClient.create(); + + // Get the full path of the model. + ModelName modelFullId = ModelName.of(projectId, computeRegion, modelId); + + // Create list model evaluations request + ListModelEvaluationsRequest modelEvaluationsrequest = + ListModelEvaluationsRequest.newBuilder() + .setParent(modelFullId.toString()) + .setFilter(filter) + .build(); + + // List all the model evaluations in the model by applying filter. + System.out.println("List of model evaluations:"); + for (ModelEvaluation element : + client.listModelEvaluations(modelEvaluationsrequest).iterateAll()) { + System.out.println(element); + } + } + // [END automl_translation_list_model_evaluations] + + // [START automl_translation_get_model_evaluation] + /** + * Demonstrates using the AutoML client to get model evaluations. + * + * @param projectId the Id of the project. + * @param computeRegion the Region name. + * @param modelId the Id of the model. + * @param modelEvaluationId the Id of your model evaluation. + * @throws IOException on Input/Output errors. + */ + public static void getModelEvaluation( + String projectId, String computeRegion, String modelId, String modelEvaluationId) + throws IOException { + // Instantiates a client + AutoMlClient client = AutoMlClient.create(); + + // Get the full path of the model evaluation. + ModelEvaluationName modelEvaluationFullId = + ModelEvaluationName.of(projectId, computeRegion, modelId, modelEvaluationId); + + // Get complete detail of the model evaluation. + ModelEvaluation response = client.getModelEvaluation(modelEvaluationFullId); + + System.out.println(response); + } + // [END automl_translation_get_model_evaluation] + + // [START automl_translation_delete_model] + /** + * Demonstrates using the AutoML client to delete a model. + * + * @param projectId the Id of the project. + * @param computeRegion the Region name. + * @param modelId the Id of the model. + * @throws Exception on AutoML Client errors + */ + public static void deleteModel(String projectId, String computeRegion, String modelId) + throws InterruptedException, ExecutionException, IOException { + // Instantiates a client + AutoMlClient client = AutoMlClient.create(); + + // Get the full path of the model. + ModelName modelFullId = ModelName.of(projectId, computeRegion, modelId); + + // Delete a model. + Empty response = client.deleteModelAsync(modelFullId).get(); + + System.out.println("Model deletion started..."); + } + // [END automl_translation_delete_model] + + // [START automl_translation_get_operation_status] + /** + * Demonstrates using the AutoML client to get operation status. + * + * @param operationFullId Full name of a operation. For example, the name of your operation is + * projects/[projectId]/locations/us-central1/operations/[operationId]. + * @throws IOException on Input/Output errors. + */ + private static void getOperationStatus(String operationFullId) throws IOException { + // Instantiates a client + AutoMlClient client = AutoMlClient.create(); + + // Get the latest state of a long-running operation. + Operation response = client.getOperationsClient().getOperation(operationFullId); + + System.out.println(String.format("Operation status: %s", response)); + } + // [END automl_translation_get_operation_status] + + public static void main(String[] args) throws Exception { + ModelApi modelApi = new ModelApi(); + modelApi.argsHelper(args, System.out); + } + + public static void argsHelper(String[] args, PrintStream out) throws Exception { + + 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"); + + Subparser listModelParser = subparsers.addParser("list_models"); + listModelParser.addArgument("filter").nargs("?").setDefault(""); + + Subparser getModelParser = subparsers.addParser("get_model"); + getModelParser.addArgument("modelId"); + + Subparser listModelEvaluationsParser = subparsers.addParser("list_model_evaluations"); + listModelEvaluationsParser.addArgument("modelId"); + listModelEvaluationsParser.addArgument("filter").nargs("?").setDefault(""); + + Subparser getModelEvaluationParser = subparsers.addParser("get_model_evaluation"); + getModelEvaluationParser.addArgument("modelId"); + getModelEvaluationParser.addArgument("modelEvaluationId"); + + Subparser deleteModelParser = subparsers.addParser("delete_model"); + deleteModelParser.addArgument("modelId"); + + Subparser getOperationStatusParser = subparsers.addParser("get_operation_status"); + getOperationStatusParser.addArgument("operationFullId"); + + String projectId = System.getenv("PROJECT_ID"); + String computeRegion = System.getenv("REGION_NAME"); + + Namespace ns = null; + try { + ns = parser.parseArgs(args); + if (ns.get("command").equals("create_model")) { + createModel(projectId, computeRegion, ns.getString("datasetId"), ns.getString("modelName")); + } + if (ns.get("command").equals("list_models")) { + listModels(projectId, computeRegion, ns.getString("filter")); + } + if (ns.get("command").equals("get_model")) { + getModel(projectId, computeRegion, ns.getString("modelId")); + } + if (ns.get("command").equals("list_model_evaluations")) { + listModelEvaluations( + projectId, computeRegion, ns.getString("modelId"), ns.getString("filter")); + } + if (ns.get("command").equals("get_model_evaluation")) { + getModelEvaluation( + projectId, computeRegion, ns.getString("modelId"), ns.getString("modelEvaluationId")); + } + if (ns.get("command").equals("delete_model")) { + deleteModel(projectId, computeRegion, ns.getString("modelId")); + } + if (ns.get("command").equals("get_operation_status")) { + getOperationStatus(ns.getString("operationFullId")); + } + } catch (ArgumentParserException e) { + parser.handleError(e); + } + } +} diff --git a/translate/automl/src/main/java/com/google/cloud/translate/automl/PredictionApi.java b/translate/automl/src/main/java/com/google/cloud/translate/automl/PredictionApi.java new file mode 100644 index 00000000000..d3b1170897f --- /dev/null +++ b/translate/automl/src/main/java/com/google/cloud/translate/automl/PredictionApi.java @@ -0,0 +1,140 @@ +/* + * 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.translate.automl; + +// Imports the Google Cloud client library +import com.google.cloud.automl.v1beta1.ExamplePayload; +import com.google.cloud.automl.v1beta1.ModelName; +import com.google.cloud.automl.v1beta1.PredictResponse; +import com.google.cloud.automl.v1beta1.PredictionServiceClient; + +import com.google.cloud.automl.v1beta1.TextSnippet; +import java.io.IOException; +import java.io.PrintStream; +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; +import net.sourceforge.argparse4j.inf.Subparser; +import net.sourceforge.argparse4j.inf.Subparsers; + +/** + * Google Cloud AutoML Translate 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_translation_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 translationAllowFallback set to true to use a Google translation. + * @throws IOException on Input/Output errors. + */ + public static void predict( + String projectId, + String computeRegion, + String modelId, + String filePath, + boolean translationAllowFallback) + throws IOException { + // Instantiate client for prediction service. + PredictionServiceClient predictionClient = PredictionServiceClient.create(); + + // Get the full path of the model. + ModelName name = ModelName.of(projectId, computeRegion, modelId); + + // Read the file content for translation. + String content = new String(Files.readAllBytes(Paths.get(filePath))); + + TextSnippet textSnippet = TextSnippet.newBuilder().setContent(content).build(); + + // Set the payload by giving the content of the file. + ExamplePayload payload = ExamplePayload.newBuilder().setTextSnippet(textSnippet).build(); + + // Additional parameters that can be provided for prediction + Map params = new HashMap<>(); + if (translationAllowFallback) { + params.put("translation_allow_fallback", "True");//Allow Google Translation Model + } + + PredictResponse response = predictionClient.predict(name, payload, params); + TextSnippet translatedContent = response.getPayload(0).getTranslation().getTranslatedContent(); + + System.out.println(String.format("Translated Content: %s", translatedContent.getContent())); + } + // [END automl_translation_predict] + + public static void main(String[] args) throws IOException { + PredictionApi predictApi = new PredictionApi(); + predictApi.argsHelper(args, System.out); + } + + public static void argsHelper(String[] args, PrintStream out) throws IOException { + ArgumentParser parser = ArgumentParsers.newFor("PredictionApi") + .build() + .defaultHelp(true) + .description("Prediction API Operation"); + Subparsers subparsers = parser.addSubparsers().dest("command"); + + Subparser predictParser = subparsers.addParser("predict"); + predictParser.addArgument("modelId"); + predictParser.addArgument("filePath"); + predictParser + .addArgument("translationAllowFallback") + .nargs("?") + .type(Boolean.class) + .setDefault(Boolean.FALSE); + + String projectId = System.getenv("PROJECT_ID"); + String computeRegion = System.getenv("REGION_NAME"); + + Namespace ns = null; + try { + ns = parser.parseArgs(args); + if (ns.get("command").equals("predict")) { + predict( + projectId, + computeRegion, + ns.getString("modelId"), + ns.getString("filePath"), + ns.getBoolean("translationAllowFallback")); + } + } catch (ArgumentParserException e) { + parser.handleError(e); + } + } +}