diff --git a/translate/cloud-client/README.md b/translate/cloud-client/README.md index 6a4aebbc22d..29c3e4083b8 100644 --- a/translate/cloud-client/README.md +++ b/translate/cloud-client/README.md @@ -8,23 +8,55 @@ arbitrary string into any supported language. These sample Java applications demonstrate how to access the Google Translate API using the [Google Cloud Client Library for Java][google-cloud-java]. -[translate]: https://cloud.google.com/translate/ +[translate]: https://cloud.google.com/translate/docs/ [google-cloud-java]: https://github.com/GoogleCloudPlatform/google-cloud-java -## Quickstart +Translate has two API versions: basic and advanced. For more info on the difference, see the +[editions](https://cloud.google.com/translate/docs/editions) documentation page. +- [Introducing Translation Advanced](https://cloud.google.com/translate/docs/intro-to-v3) +- [Migrating to Advanced](https://cloud.google.com/translate/docs/migrate-to-v3) + +## Translate a string (using the quickstart sample) Install [Maven](http://maven.apache.org/). Build your project with: mvn clean package -DskipTests - -You can then run a given `ClassName` via: - - mvn exec:java -Dexec.mainClass=com.example.translate.ClassName \ - -DpropertyName=propertyValue \ - -Dexec.args="any arguments to the app" - -### Translate a string (using the quickstart sample) - mvn exec:java -Dexec.mainClass=com.example.translate.QuickstartSample + +## Samples for the Basic API Version + - [Translating text](https://cloud.google.com/translate/docs/basic/translating-text) + - [Discovering supported languages](https://cloud.google.com/translate/docs/basic/discovering-supported-languages) + - [Detecting language](https://cloud.google.com/translate/docs/basic/detecting-language) + +## Samples for the Advanced API Version + +#### Translating text - [Documentation](https://cloud.google.com/translate/docs/advanced/translating-text-v3) +Related samples: + - [TranslateText.java](src/main/java/com/example/translate/TranslateText.java) + - [TranslateTextWithModel.java](src/main/java/com/example/translate/TranslateTextWithModel.java) + +#### Discovering supported languages - [Documentation](https://cloud.google.com/translate/docs/advanced/discovering-supported-languages-v3) +Related samples: + - [GetSupportedLanguages.java](src/main/java/com/example/translate/GetSupportedLanguages.java) + - [GetSupportedLanguagesForTarget.java](src/main/java/com/example/translate/GetSupportedLanguagesForTarget.java) + +#### Detecting language - [Documentation](https://cloud.google.com/translate/docs/advanced/detecting-language-v3) +Related samples: + - [DetectLangauge.java](src/main/java/com/example/translate/DetectLanguage.java) + +#### Creating and using glossaries - [Documentation](https://cloud.google.com/translate/docs/advanced/glossary) +Related samples: + - [CreateGlossary.java](src/main/java/com/example/translate/CreateGlossary.java) + - [TranslateTextWithGlossary.java](src/main/java/com/example/translate/TranslateTextWithGlossary.java) + - [GetGlossary.java](src/main/java/com/example/translate/GetGlossary.java) + - [ListGlossaries.java](src/main/java/com/example/translate/ListGlossaries.java) + - [DeleteGlossary.java](src/main/java/com/example/translate/DeleteGlossary.java) + +#### Making batch requests - [Documentation](https://cloud.google.com/translate/docs/advanced/batch-translation) +Related samples: + - [BatchTranslateText.java](src/main/java/com/example/translate/BatchTranslateText.java) + - [BatchTranslateTextWithModel.java](src/main/java/com/example/translate/BatchTranslateTextWithModel.java) + - [BatchTranslateTextWithGlossary.java](src/main/java/com/example/translate/BatchTranslateTextWithGlossary.java) + - [BatchTranslateTextWithGlossaryAndModel](src/main/java/com/example/translate/BatchTranslateTextWithGlossaryAndModel.java) \ No newline at end of file diff --git a/translate/cloud-client/src/main/java/com/example/translate/BatchTranslateText.java b/translate/cloud-client/src/main/java/com/example/translate/BatchTranslateText.java new file mode 100644 index 00000000000..30d2ab181d2 --- /dev/null +++ b/translate/cloud-client/src/main/java/com/example/translate/BatchTranslateText.java @@ -0,0 +1,95 @@ +/* + * Copyright 2020 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.example.translate; + +// [START translate_v3_batch_translate_text] +import com.google.api.gax.longrunning.OperationFuture; +import com.google.cloud.translate.v3.BatchTranslateMetadata; +import com.google.cloud.translate.v3.BatchTranslateResponse; +import com.google.cloud.translate.v3.BatchTranslateTextRequest; +import com.google.cloud.translate.v3.GcsDestination; +import com.google.cloud.translate.v3.GcsSource; +import com.google.cloud.translate.v3.InputConfig; +import com.google.cloud.translate.v3.LocationName; +import com.google.cloud.translate.v3.OutputConfig; +import com.google.cloud.translate.v3.TranslationServiceClient; + +import java.io.IOException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +public class BatchTranslateText { + + public static void batchTranslateText() + throws InterruptedException, ExecutionException, IOException, TimeoutException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + // Supported Languages: https://cloud.google.com/translate/docs/languages + String sourceLanguage = "your-source-language"; + String targetLanguage = "your-target-language"; + String inputUri = "gs://your-gcs-bucket/path/to/input/file.txt"; + String outputUri = "gs://your-gcs-bucket/path/to/results/"; + batchTranslateText(projectId, sourceLanguage, targetLanguage, inputUri, outputUri); + } + + // Batch translate text + public static void batchTranslateText( + String projectId, + String sourceLanguage, + String targetLanguage, + String inputUri, + String outputUri) + 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 (TranslationServiceClient client = TranslationServiceClient.create()) { + // Supported Locations: `us-central1` + LocationName parent = LocationName.of(projectId, "us-central1"); + + GcsSource gcsSource = GcsSource.newBuilder().setInputUri(inputUri).build(); + // Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats + InputConfig inputConfig = + InputConfig.newBuilder().setGcsSource(gcsSource).setMimeType("text/plain").build(); + + GcsDestination gcsDestination = + GcsDestination.newBuilder().setOutputUriPrefix(outputUri).build(); + OutputConfig outputConfig = + OutputConfig.newBuilder().setGcsDestination(gcsDestination).build(); + + BatchTranslateTextRequest request = + BatchTranslateTextRequest.newBuilder() + .setParent(parent.toString()) + .setSourceLanguageCode(sourceLanguage) + .addTargetLanguageCodes(targetLanguage) + .addInputConfigs(inputConfig) + .setOutputConfig(outputConfig) + .build(); + + OperationFuture future = + client.batchTranslateTextAsync(request); + + System.out.println("Waiting for operation to complete..."); + BatchTranslateResponse response = future.get(120, TimeUnit.SECONDS); + System.out.printf("Total Characters: %s\n", response.getTotalCharacters()); + System.out.printf("Translated Characters: %s\n", response.getTranslatedCharacters()); + } + } +} +// [END translate_v3_batch_translate_text] diff --git a/translate/cloud-client/src/main/java/com/example/translate/TranslateText.java b/translate/cloud-client/src/main/java/com/example/translate/TranslateText.java new file mode 100644 index 00000000000..94989428218 --- /dev/null +++ b/translate/cloud-client/src/main/java/com/example/translate/TranslateText.java @@ -0,0 +1,70 @@ +/* + * Copyright 2020 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.example.translate; + +// [START translate_v3_translate_text] +import com.google.cloud.translate.v3.LocationName; +import com.google.cloud.translate.v3.TranslateTextRequest; +import com.google.cloud.translate.v3.TranslateTextResponse; +import com.google.cloud.translate.v3.Translation; +import com.google.cloud.translate.v3.TranslationServiceClient; + +import java.io.IOException; + +public class TranslateText { + + public static void translateText() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + // Supported Languages: https://cloud.google.com/translate/docs/languages + String targetLanguage = "your-target-language"; + String text = "your-text"; + translateText(projectId, targetLanguage, text); + } + + // Translating Text + public static void translateText(String projectId, String targetLanguage, String text) + 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 (TranslationServiceClient client = TranslationServiceClient.create()) { + // Supported Locations: `global`, [glossary location], or [model location] + // Glossaries must be hosted in `us-central1` + // Custom Models must use the same location as your model. (us-central1) + LocationName parent = LocationName.of(projectId, "global"); + + // Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats + TranslateTextRequest request = + TranslateTextRequest.newBuilder() + .setParent(parent.toString()) + .setMimeType("text/plain") + .setTargetLanguageCode(targetLanguage) + .addContents(text) + .build(); + + TranslateTextResponse response = client.translateText(request); + + // Display the translation for each input text provided + for (Translation translation : response.getTranslationsList()) { + System.out.printf("Translated text: %s\n", translation.getTranslatedText()); + } + } + } +} +// [END translate_v3_translate_text] diff --git a/translate/cloud-client/src/test/java/com/example/translate/BatchTranslateTextTests.java b/translate/cloud-client/src/test/java/com/example/translate/BatchTranslateTextTests.java new file mode 100644 index 00000000000..daebf827fb9 --- /dev/null +++ b/translate/cloud-client/src/test/java/com/example/translate/BatchTranslateTextTests.java @@ -0,0 +1,109 @@ +/* + * Copyright 2020 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import com.google.api.gax.paging.Page; +import com.google.cloud.storage.Blob; +import com.google.cloud.storage.Storage; +import com.google.cloud.storage.StorageOptions; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeoutException; + +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Batch Translate Text sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class BatchTranslateTextTests { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String INPUT_URI = "gs://cloud-samples-data/translation/text.txt"; + + private ByteArrayOutputStream bout; + private PrintStream out; + + private static void cleanUpBucket() { + Storage storage = StorageOptions.getDefaultInstance().getService(); + Page blobs = + storage.list( + PROJECT_ID, + Storage.BlobListOption.currentDirectory(), + Storage.BlobListOption.prefix("BATCH_TRANSLATION_OUTPUT/")); + + deleteDirectory(storage, blobs); + } + + private static void deleteDirectory(Storage storage, Page blobs) { + for (Blob blob : blobs.iterateAll()) { + System.out.println(blob.getBlobId()); + if (!blob.delete()) { + Page subBlobs = + storage.list( + PROJECT_ID, + Storage.BlobListOption.currentDirectory(), + Storage.BlobListOption.prefix(blob.getName())); + + deleteDirectory(storage, subBlobs); + } + } + } + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + System.setOut(out); + } + + @After + public void tearDown() { + cleanUpBucket(); + System.setOut(null); + } + + @Test + public void testBatchTranslateText() + throws InterruptedException, ExecutionException, IOException, TimeoutException { + BatchTranslateText.batchTranslateText( + PROJECT_ID, "en", "es", INPUT_URI, "gs://" + PROJECT_ID + "/BATCH_TRANSLATION_OUTPUT/"); + String got = bout.toString(); + assertThat(got).contains("Total Characters: 13"); + } +} diff --git a/translate/cloud-client/src/test/java/com/example/translate/TranslateTextTests.java b/translate/cloud-client/src/test/java/com/example/translate/TranslateTextTests.java new file mode 100644 index 00000000000..0c6ddbd835d --- /dev/null +++ b/translate/cloud-client/src/test/java/com/example/translate/TranslateTextTests.java @@ -0,0 +1,71 @@ +/* + * Copyright 2020 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Translate Text sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class TranslateTextTests { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + + private ByteArrayOutputStream bout; + private PrintStream out; + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + System.setOut(out); + } + + @After + public void tearDown() { + System.setOut(null); + } + + @Test + public void testTranslateText() throws IOException { + TranslateText.translateText(PROJECT_ID, "es", "Hello world"); + String got = bout.toString(); + assertThat(got).contains("Hola Mundo"); + } +}