Skip to content

Commit acd0ce4

Browse files
nnegreykurtisvg
andauthored
translate: add basic translation samples (#1938)
* translate: add basic translation samples * Update pom.xml * bump timeout for batch call * Update readme to include info about v3 samples and basic vs advanced links * Update blunderbuss.yml Co-authored-by: Kurtis Van Gent <[email protected]>
1 parent 5e01277 commit acd0ce4

File tree

5 files changed

+388
-11
lines changed

5 files changed

+388
-11
lines changed

translate/cloud-client/README.md

Lines changed: 43 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,23 +8,55 @@ arbitrary string into any supported language.
88
These sample Java applications demonstrate how to access the Google Translate API using
99
the [Google Cloud Client Library for Java][google-cloud-java].
1010

11-
[translate]: https://cloud.google.com/translate/
11+
[translate]: https://cloud.google.com/translate/docs/
1212
[google-cloud-java]: https://github.com/GoogleCloudPlatform/google-cloud-java
1313

14-
## Quickstart
14+
Translate has two API versions: basic and advanced. For more info on the difference, see the
15+
[editions](https://cloud.google.com/translate/docs/editions) documentation page.
16+
- [Introducing Translation Advanced](https://cloud.google.com/translate/docs/intro-to-v3)
17+
- [Migrating to Advanced](https://cloud.google.com/translate/docs/migrate-to-v3)
18+
19+
## Translate a string (using the quickstart sample)
1520

1621
Install [Maven](http://maven.apache.org/).
1722

1823
Build your project with:
1924

2025
mvn clean package -DskipTests
21-
22-
You can then run a given `ClassName` via:
23-
24-
mvn exec:java -Dexec.mainClass=com.example.translate.ClassName \
25-
-DpropertyName=propertyValue \
26-
-Dexec.args="any arguments to the app"
27-
28-
### Translate a string (using the quickstart sample)
29-
3026
mvn exec:java -Dexec.mainClass=com.example.translate.QuickstartSample
27+
28+
## Samples for the Basic API Version
29+
- [Translating text](https://cloud.google.com/translate/docs/basic/translating-text)
30+
- [Discovering supported languages](https://cloud.google.com/translate/docs/basic/discovering-supported-languages)
31+
- [Detecting language](https://cloud.google.com/translate/docs/basic/detecting-language)
32+
33+
## Samples for the Advanced API Version
34+
35+
#### Translating text - [Documentation](https://cloud.google.com/translate/docs/advanced/translating-text-v3)
36+
Related samples:
37+
- [TranslateText.java](src/main/java/com/example/translate/TranslateText.java)
38+
- [TranslateTextWithModel.java](src/main/java/com/example/translate/TranslateTextWithModel.java)
39+
40+
#### Discovering supported languages - [Documentation](https://cloud.google.com/translate/docs/advanced/discovering-supported-languages-v3)
41+
Related samples:
42+
- [GetSupportedLanguages.java](src/main/java/com/example/translate/GetSupportedLanguages.java)
43+
- [GetSupportedLanguagesForTarget.java](src/main/java/com/example/translate/GetSupportedLanguagesForTarget.java)
44+
45+
#### Detecting language - [Documentation](https://cloud.google.com/translate/docs/advanced/detecting-language-v3)
46+
Related samples:
47+
- [DetectLangauge.java](src/main/java/com/example/translate/DetectLanguage.java)
48+
49+
#### Creating and using glossaries - [Documentation](https://cloud.google.com/translate/docs/advanced/glossary)
50+
Related samples:
51+
- [CreateGlossary.java](src/main/java/com/example/translate/CreateGlossary.java)
52+
- [TranslateTextWithGlossary.java](src/main/java/com/example/translate/TranslateTextWithGlossary.java)
53+
- [GetGlossary.java](src/main/java/com/example/translate/GetGlossary.java)
54+
- [ListGlossaries.java](src/main/java/com/example/translate/ListGlossaries.java)
55+
- [DeleteGlossary.java](src/main/java/com/example/translate/DeleteGlossary.java)
56+
57+
#### Making batch requests - [Documentation](https://cloud.google.com/translate/docs/advanced/batch-translation)
58+
Related samples:
59+
- [BatchTranslateText.java](src/main/java/com/example/translate/BatchTranslateText.java)
60+
- [BatchTranslateTextWithModel.java](src/main/java/com/example/translate/BatchTranslateTextWithModel.java)
61+
- [BatchTranslateTextWithGlossary.java](src/main/java/com/example/translate/BatchTranslateTextWithGlossary.java)
62+
- [BatchTranslateTextWithGlossaryAndModel](src/main/java/com/example/translate/BatchTranslateTextWithGlossaryAndModel.java)
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
/*
2+
* Copyright 2020 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.translate;
18+
19+
// [START translate_v3_batch_translate_text]
20+
import com.google.api.gax.longrunning.OperationFuture;
21+
import com.google.cloud.translate.v3.BatchTranslateMetadata;
22+
import com.google.cloud.translate.v3.BatchTranslateResponse;
23+
import com.google.cloud.translate.v3.BatchTranslateTextRequest;
24+
import com.google.cloud.translate.v3.GcsDestination;
25+
import com.google.cloud.translate.v3.GcsSource;
26+
import com.google.cloud.translate.v3.InputConfig;
27+
import com.google.cloud.translate.v3.LocationName;
28+
import com.google.cloud.translate.v3.OutputConfig;
29+
import com.google.cloud.translate.v3.TranslationServiceClient;
30+
31+
import java.io.IOException;
32+
import java.util.concurrent.ExecutionException;
33+
import java.util.concurrent.TimeUnit;
34+
import java.util.concurrent.TimeoutException;
35+
36+
public class BatchTranslateText {
37+
38+
public static void batchTranslateText()
39+
throws InterruptedException, ExecutionException, IOException, TimeoutException {
40+
// TODO(developer): Replace these variables before running the sample.
41+
String projectId = "YOUR-PROJECT-ID";
42+
// Supported Languages: https://cloud.google.com/translate/docs/languages
43+
String sourceLanguage = "your-source-language";
44+
String targetLanguage = "your-target-language";
45+
String inputUri = "gs://your-gcs-bucket/path/to/input/file.txt";
46+
String outputUri = "gs://your-gcs-bucket/path/to/results/";
47+
batchTranslateText(projectId, sourceLanguage, targetLanguage, inputUri, outputUri);
48+
}
49+
50+
// Batch translate text
51+
public static void batchTranslateText(
52+
String projectId,
53+
String sourceLanguage,
54+
String targetLanguage,
55+
String inputUri,
56+
String outputUri)
57+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
58+
59+
// Initialize client that will be used to send requests. This client only needs to be created
60+
// once, and can be reused for multiple requests. After completing all of your requests, call
61+
// the "close" method on the client to safely clean up any remaining background resources.
62+
try (TranslationServiceClient client = TranslationServiceClient.create()) {
63+
// Supported Locations: `us-central1`
64+
LocationName parent = LocationName.of(projectId, "us-central1");
65+
66+
GcsSource gcsSource = GcsSource.newBuilder().setInputUri(inputUri).build();
67+
// Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats
68+
InputConfig inputConfig =
69+
InputConfig.newBuilder().setGcsSource(gcsSource).setMimeType("text/plain").build();
70+
71+
GcsDestination gcsDestination =
72+
GcsDestination.newBuilder().setOutputUriPrefix(outputUri).build();
73+
OutputConfig outputConfig =
74+
OutputConfig.newBuilder().setGcsDestination(gcsDestination).build();
75+
76+
BatchTranslateTextRequest request =
77+
BatchTranslateTextRequest.newBuilder()
78+
.setParent(parent.toString())
79+
.setSourceLanguageCode(sourceLanguage)
80+
.addTargetLanguageCodes(targetLanguage)
81+
.addInputConfigs(inputConfig)
82+
.setOutputConfig(outputConfig)
83+
.build();
84+
85+
OperationFuture<BatchTranslateResponse, BatchTranslateMetadata> future =
86+
client.batchTranslateTextAsync(request);
87+
88+
System.out.println("Waiting for operation to complete...");
89+
BatchTranslateResponse response = future.get(120, TimeUnit.SECONDS);
90+
System.out.printf("Total Characters: %s\n", response.getTotalCharacters());
91+
System.out.printf("Translated Characters: %s\n", response.getTranslatedCharacters());
92+
}
93+
}
94+
}
95+
// [END translate_v3_batch_translate_text]
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/*
2+
* Copyright 2020 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.translate;
18+
19+
// [START translate_v3_translate_text]
20+
import com.google.cloud.translate.v3.LocationName;
21+
import com.google.cloud.translate.v3.TranslateTextRequest;
22+
import com.google.cloud.translate.v3.TranslateTextResponse;
23+
import com.google.cloud.translate.v3.Translation;
24+
import com.google.cloud.translate.v3.TranslationServiceClient;
25+
26+
import java.io.IOException;
27+
28+
public class TranslateText {
29+
30+
public static void translateText() throws IOException {
31+
// TODO(developer): Replace these variables before running the sample.
32+
String projectId = "YOUR-PROJECT-ID";
33+
// Supported Languages: https://cloud.google.com/translate/docs/languages
34+
String targetLanguage = "your-target-language";
35+
String text = "your-text";
36+
translateText(projectId, targetLanguage, text);
37+
}
38+
39+
// Translating Text
40+
public static void translateText(String projectId, String targetLanguage, String text)
41+
throws IOException {
42+
43+
// Initialize client that will be used to send requests. This client only needs to be created
44+
// once, and can be reused for multiple requests. After completing all of your requests, call
45+
// the "close" method on the client to safely clean up any remaining background resources.
46+
try (TranslationServiceClient client = TranslationServiceClient.create()) {
47+
// Supported Locations: `global`, [glossary location], or [model location]
48+
// Glossaries must be hosted in `us-central1`
49+
// Custom Models must use the same location as your model. (us-central1)
50+
LocationName parent = LocationName.of(projectId, "global");
51+
52+
// Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats
53+
TranslateTextRequest request =
54+
TranslateTextRequest.newBuilder()
55+
.setParent(parent.toString())
56+
.setMimeType("text/plain")
57+
.setTargetLanguageCode(targetLanguage)
58+
.addContents(text)
59+
.build();
60+
61+
TranslateTextResponse response = client.translateText(request);
62+
63+
// Display the translation for each input text provided
64+
for (Translation translation : response.getTranslationsList()) {
65+
System.out.printf("Translated text: %s\n", translation.getTranslatedText());
66+
}
67+
}
68+
}
69+
}
70+
// [END translate_v3_translate_text]
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
/*
2+
* Copyright 2020 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.translate;
18+
19+
import static com.google.common.truth.Truth.assertThat;
20+
import static junit.framework.TestCase.assertNotNull;
21+
22+
import com.google.api.gax.paging.Page;
23+
import com.google.cloud.storage.Blob;
24+
import com.google.cloud.storage.Storage;
25+
import com.google.cloud.storage.StorageOptions;
26+
27+
import java.io.ByteArrayOutputStream;
28+
import java.io.IOException;
29+
import java.io.PrintStream;
30+
import java.util.concurrent.ExecutionException;
31+
import java.util.concurrent.TimeoutException;
32+
33+
import org.junit.After;
34+
import org.junit.Before;
35+
import org.junit.BeforeClass;
36+
import org.junit.Test;
37+
import org.junit.runner.RunWith;
38+
import org.junit.runners.JUnit4;
39+
40+
/** Tests for Batch Translate Text sample. */
41+
@RunWith(JUnit4.class)
42+
@SuppressWarnings("checkstyle:abbreviationaswordinname")
43+
public class BatchTranslateTextTests {
44+
private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT");
45+
private static final String INPUT_URI = "gs://cloud-samples-data/translation/text.txt";
46+
47+
private ByteArrayOutputStream bout;
48+
private PrintStream out;
49+
50+
private static void cleanUpBucket() {
51+
Storage storage = StorageOptions.getDefaultInstance().getService();
52+
Page<Blob> blobs =
53+
storage.list(
54+
PROJECT_ID,
55+
Storage.BlobListOption.currentDirectory(),
56+
Storage.BlobListOption.prefix("BATCH_TRANSLATION_OUTPUT/"));
57+
58+
deleteDirectory(storage, blobs);
59+
}
60+
61+
private static void deleteDirectory(Storage storage, Page<Blob> blobs) {
62+
for (Blob blob : blobs.iterateAll()) {
63+
System.out.println(blob.getBlobId());
64+
if (!blob.delete()) {
65+
Page<Blob> subBlobs =
66+
storage.list(
67+
PROJECT_ID,
68+
Storage.BlobListOption.currentDirectory(),
69+
Storage.BlobListOption.prefix(blob.getName()));
70+
71+
deleteDirectory(storage, subBlobs);
72+
}
73+
}
74+
}
75+
76+
private static void requireEnvVar(String varName) {
77+
assertNotNull(
78+
"Environment variable '%s' is required to perform these tests.".format(varName),
79+
System.getenv(varName));
80+
}
81+
82+
@BeforeClass
83+
public static void checkRequirements() {
84+
requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS");
85+
requireEnvVar("GOOGLE_CLOUD_PROJECT");
86+
}
87+
88+
@Before
89+
public void setUp() {
90+
bout = new ByteArrayOutputStream();
91+
out = new PrintStream(bout);
92+
System.setOut(out);
93+
}
94+
95+
@After
96+
public void tearDown() {
97+
cleanUpBucket();
98+
System.setOut(null);
99+
}
100+
101+
@Test
102+
public void testBatchTranslateText()
103+
throws InterruptedException, ExecutionException, IOException, TimeoutException {
104+
BatchTranslateText.batchTranslateText(
105+
PROJECT_ID, "en", "es", INPUT_URI, "gs://" + PROJECT_ID + "/BATCH_TRANSLATION_OUTPUT/");
106+
String got = bout.toString();
107+
assertThat(got).contains("Total Characters: 13");
108+
}
109+
}

0 commit comments

Comments
 (0)