Skip to content

Commit 9d413c0

Browse files
authored
Merge pull request #1194 from GoogleCloudPlatform/translate-alpha
Add support for Google Translate
2 parents 343f77d + 0a9c791 commit 9d413c0

36 files changed

Lines changed: 3140 additions & 2 deletions

README.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ This client supports the following Google Cloud Platform services:
2222
- [Google Cloud Pub/Sub] (#google-cloud-pubsub-alpha) (Alpha - Not working on App Engine Standard)
2323
- [Google Cloud Resource Manager] (#google-cloud-resource-manager-alpha) (Alpha)
2424
- [Google Cloud Storage] (#google-cloud-storage)
25+
- [Google Cloud Translate] (#google-translate) (Alpha)
2526

2627
> Note: This client is a work-in-progress, and may occasionally
2728
> make backwards-incompatible changes.
@@ -569,6 +570,40 @@ if (blob != null) {
569570
}
570571
```
571572
573+
Google Translate
574+
----------------
575+
576+
- [API Documentation][translate-api]
577+
- [Official Documentation][translate-docs]
578+
579+
#### Preview
580+
581+
Here's a snippet showing a simple usage example. The example shows how to detect the language of
582+
some text and how to translate some text. The example assumes that the `GOOGLE_API_KEY` is set and
583+
contains a valid API key. Alternatively, you can use the `apiKey(String)` setter in
584+
`TranslateOptions.Builder` to set the API key. Complete source code can be found at
585+
[DetectLanguageAndTranslate.java](./gcloud-java-examples/src/main/java/com/google/cloud/examples/translate/snippets/DetectLanguageAndTranslate.java).
586+
587+
```java
588+
import com.google.cloud.translate.Detection;
589+
import com.google.cloud.translate.Translate;
590+
import com.google.cloud.translate.Translate.TranslateOption;
591+
import com.google.cloud.translate.TranslateOptions;
592+
import com.google.cloud.translate.Translation;
593+
594+
Translate translate = TranslateOptions.defaultInstance().service();
595+
596+
Detection detection = translate.detect("Hola");
597+
String detectedLanguage = detection.language();
598+
599+
Translation translation = translate.translate(
600+
"World",
601+
TranslateOption.sourceLanguage("en"),
602+
TranslateOption.targetLanguage(detectedLanguage));
603+
604+
System.out.printf("Hola %s%n", translation.translatedText());
605+
```
606+
572607
Troubleshooting
573608
---------------
574609
@@ -648,3 +683,6 @@ Apache 2.0 - See [LICENSE] for more information.
648683
[cloud-compute]: https://cloud.google.com/compute/
649684
[cloud-compute-docs]: https://cloud.google.com/compute/docs/overview
650685
[compute-api]: http://googlecloudplatform.github.io/gcloud-java/apidocs/index.html?com/google/cloud/compute/package-summary.html
686+
687+
[translate-docs]: https://cloud.google.com/translate/docs/
688+
[translate-api]: http://googlecloudplatform.github.io/gcloud-java/apidocs/index.html?com/google/cloud/translate/package-summary.html

TESTING.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,5 +270,25 @@ Here is an example that clears the bucket created in Step 3 with a timeout of 5
270270
RemoteStorageHelper.forceDelete(storage, bucket, 5, TimeUnit.SECONDS);
271271
```
272272

273+
### Testing code that uses Translate
274+
275+
`RemoteTranslateHelper` contains convenience methods to make is easier to run tests against the
276+
Google Translate service.
277+
278+
1. Create a test Google Cloud project.
279+
280+
2. Follow [Translate Quickstart](https://cloud.google.com/translate/v2/quickstart) to get an API
281+
key.
282+
283+
3. Create a `RemoteTranslateHelper` object using your project ID and API key. Here is an example
284+
that uses the `RemoteTranslateHelper` to list supported languages.
285+
```java
286+
RemoteTranslateHelper translateHelper = RemoteTranslateHelper.create(PROJECT_ID, API_KEY);
287+
Translate translate = translateHelper.options().service();
288+
List<Language> languages = translate.listSupportedLanguages();
289+
```
290+
291+
4. Run your tests.
292+
273293
[cloud-platform-storage-authentication]:https://cloud.google.com/storage/docs/authentication?hl=en#service_accounts
274294
[create-service-account]:https://developers.google.com/identity/protocols/OAuth2ServiceAccount#creatinganaccount

gcloud-java-examples/README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,16 @@ To run examples from your command line:
168168
via the NIO API. It lists gcloud-java-nio as a dependency, and that enables it to interpret
169169
`gs://` paths.
170170
171+
* Here's an example run of `TranslateExample`.
172+
173+
Before running the example, go to the [Google Developers Console][developers-console] to ensure that "Google Translate API" is enabled and that you have a valid API key.
174+
```
175+
target/appassembler/bin/TranslateExample <apiKey> languages
176+
target/appassembler/bin/TranslateExample <apiKey> detect Hello,\ World!
177+
target/appassembler/bin/TranslateExample <apiKey> translate ¡Hola\ Mundo!
178+
target/appassembler/bin/TranslateExample <apiKey> es translate Hello,\ World!
179+
```
180+
171181
Troubleshooting
172182
---------------
173183

gcloud-java-examples/pom.xml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,10 @@
106106
<mainClass>com.google.cloud.examples.storage.StorageExample</mainClass>
107107
<name>StorageExample</name>
108108
</program>
109+
<program>
110+
<mainClass>com.google.cloud.examples.translate.TranslateExample</mainClass>
111+
<name>TranslateExample</name>
112+
</program>
109113
</programs>
110114
</configuration>
111115
</plugin>
Lines changed: 220 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,220 @@
1+
/*
2+
* Copyright 2016 Google Inc. All Rights Reserved.
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.google.cloud.examples.translate;
18+
19+
import com.google.cloud.translate.Detection;
20+
import com.google.cloud.translate.Language;
21+
import com.google.cloud.translate.Translate;
22+
import com.google.cloud.translate.TranslateOptions;
23+
import com.google.cloud.translate.Translation;
24+
25+
import java.util.Arrays;
26+
import java.util.HashMap;
27+
import java.util.List;
28+
import java.util.Map;
29+
30+
/**
31+
* An example of using Google Translate.
32+
*
33+
* <p>This example demonstrates a simple/typical Translate usage.
34+
*
35+
* <p>See the
36+
* <a href="https://github.com/GoogleCloudPlatform/gcloud-java/blob/master/gcloud-java-examples/README.md">
37+
* README</a> for compilation instructions. Run this code with
38+
* <pre>{@code target/appassembler/bin/TranslateExample
39+
* -Dexec.args="<apiKey> [<targetLanguage>]
40+
* list languages <languageCode>?
41+
* detect <text>+
42+
* translate <text>+"}</pre>
43+
*
44+
* <p>The first parameter is an optional {@code targetLanguage}. If the target language is not
45+
* supplied, {@code en} is used (see {@link TranslateOptions.Builder#targetLanguage(String)}).
46+
*/
47+
public class TranslateExample {
48+
49+
private static final Map<String, TranslateAction> ACTIONS = new HashMap<>();
50+
51+
private abstract static class TranslateAction<T> {
52+
53+
abstract void run(Translate translate, T arg) throws Exception;
54+
55+
abstract T parse(String... args) throws Exception;
56+
57+
protected String params() {
58+
return "";
59+
}
60+
}
61+
62+
/**
63+
* This class demonstrates how to list supported languages.
64+
*
65+
* @see <a href="https://cloud.google.com/translate/v2/discovering-supported-languages-with-rest">
66+
* Discovering Supported Languages</a>
67+
*/
68+
private static class ListLanguagesAction extends TranslateAction<Void> {
69+
@Override
70+
public void run(Translate translate, Void arg) {
71+
List<Language> languages = translate.listSupportedLanguages();
72+
System.out.println("Supported languages:");
73+
for (Language language : languages) {
74+
System.out.println(language);
75+
}
76+
}
77+
78+
@Override
79+
Void parse(String... args) throws Exception {
80+
if (args.length == 0) {
81+
return null;
82+
}
83+
throw new IllegalArgumentException("This action takes no arguments.");
84+
}
85+
}
86+
87+
/**
88+
* This class demonstrates how detect the language of some texts.
89+
*
90+
* @see <a href="https://cloud.google.com/translate/v2/detecting-language-with-rest">Detecting
91+
* Language</a>
92+
*/
93+
private static class DetectLanguageAction extends TranslateAction<List<String>> {
94+
@Override
95+
public void run(Translate translate, List<String> texts) {
96+
List<Detection> detections = translate.detect(texts);
97+
if (texts.size() == 1) {
98+
System.out.println("Detected language is:");
99+
} else {
100+
System.out.println("Detected languages are:");
101+
}
102+
for (Detection detection : detections) {
103+
System.out.println(detection);
104+
}
105+
}
106+
107+
@Override
108+
List<String> parse(String... args) throws Exception {
109+
if (args.length >= 1) {
110+
return Arrays.asList(args);
111+
} else {
112+
throw new IllegalArgumentException("Missing required texts.");
113+
}
114+
}
115+
116+
@Override
117+
public String params() {
118+
return "<text>+";
119+
}
120+
}
121+
122+
/**
123+
* This class demonstrates how to translate some texts.
124+
*
125+
* @see <a href="https://cloud.google.com/translate/v2/translating-text-with-rest">Translating
126+
* Text</a>
127+
*/
128+
private static class TranslateTextAction extends TranslateAction<List<String>> {
129+
@Override
130+
public void run(Translate translate, List<String> texts) {
131+
List<Translation> translations = translate.translate(texts);
132+
if (texts.size() == 1) {
133+
System.out.println("Translation is:");
134+
} else {
135+
System.out.println("Translations are:");
136+
}
137+
for (Translation translation : translations) {
138+
System.out.println(translation);
139+
}
140+
}
141+
142+
@Override
143+
List<String> parse(String... args) throws Exception {
144+
if (args.length >= 1) {
145+
return Arrays.asList(args);
146+
} else {
147+
throw new IllegalArgumentException("Missing required texts.");
148+
}
149+
}
150+
151+
@Override
152+
public String params() {
153+
return "<text>+";
154+
}
155+
}
156+
157+
static {
158+
ACTIONS.put("languages", new ListLanguagesAction());
159+
ACTIONS.put("detect", new DetectLanguageAction());
160+
ACTIONS.put("translate", new TranslateTextAction());
161+
}
162+
163+
private static void printUsage() {
164+
StringBuilder actionAndParams = new StringBuilder();
165+
for (Map.Entry<String, TranslateAction> entry : ACTIONS.entrySet()) {
166+
actionAndParams.append(System.lineSeparator()).append('\t').append(entry.getKey());
167+
String param = entry.getValue().params();
168+
if (param != null && !param.isEmpty()) {
169+
actionAndParams.append(' ').append(param);
170+
}
171+
}
172+
System.out.printf("Usage: %s [<apiKey>] [<targetLanguage>] operation <args>*%s%n",
173+
TranslateExample.class.getSimpleName(), actionAndParams);
174+
}
175+
176+
@SuppressWarnings("unchecked")
177+
public static void main(String... args) throws Exception {
178+
if (args.length < 1) {
179+
System.out.println("Missing required action");
180+
printUsage();
181+
return;
182+
}
183+
TranslateOptions.Builder optionsBuilder = TranslateOptions.builder();
184+
TranslateAction action;
185+
String actionName;
186+
if (args.length >= 3 && !ACTIONS.containsKey(args[1])) {
187+
optionsBuilder.apiKey(args[0]);
188+
actionName = args[2];
189+
optionsBuilder.targetLanguage(args[1]);
190+
args = Arrays.copyOfRange(args, 3, args.length);
191+
} else if (args.length >= 2 && !ACTIONS.containsKey(args[0])) {
192+
optionsBuilder.apiKey(args[0]);
193+
actionName = args[1];
194+
args = Arrays.copyOfRange(args, 2, args.length);
195+
} else {
196+
actionName = args[0];
197+
args = Arrays.copyOfRange(args, 1, args.length);
198+
}
199+
action = ACTIONS.get(actionName);
200+
if (action == null) {
201+
System.out.println("Unrecognized action.");
202+
printUsage();
203+
return;
204+
}
205+
Object arg;
206+
try {
207+
arg = action.parse(args);
208+
} catch (IllegalArgumentException ex) {
209+
System.out.printf("Invalid input for action '%s'. %s%n", actionName, ex.getMessage());
210+
System.out.printf("Expected: %s%n", action.params());
211+
return;
212+
} catch (Exception ex) {
213+
System.out.println("Failed to parse arguments.");
214+
ex.printStackTrace();
215+
return;
216+
}
217+
Translate translate = optionsBuilder.build().service();
218+
action.run(translate, arg);
219+
}
220+
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/*
2+
* Copyright 2016 Google Inc. All Rights Reserved.
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+
/*
18+
* EDITING INSTRUCTIONS
19+
* This file is referenced in READMEs and javadoc. Any change to this file should be reflected in
20+
* the project's READMEs and package-info.java.
21+
*/
22+
23+
package com.google.cloud.examples.translate.snippets;
24+
25+
import com.google.cloud.translate.Detection;
26+
import com.google.cloud.translate.Translate;
27+
import com.google.cloud.translate.Translate.TranslateOption;
28+
import com.google.cloud.translate.TranslateOptions;
29+
import com.google.cloud.translate.Translation;
30+
31+
/**
32+
* A snippet for Google Translate showing how to detect the language of some text and translate
33+
* some other text.
34+
*/
35+
public class DetectLanguageAndTranslate {
36+
37+
public static void main(String... args) {
38+
// Create a service object
39+
// API key is read from the GOOGLE_API_KEY environment variable
40+
Translate translate = TranslateOptions.defaultInstance().service();
41+
42+
// Detect the language of some text
43+
Detection detection = translate.detect("Hola");
44+
String detectedLanguage = detection.language();
45+
46+
// Translate some text
47+
Translation translation = translate.translate(
48+
"World",
49+
TranslateOption.sourceLanguage("en"),
50+
TranslateOption.targetLanguage(detectedLanguage));
51+
52+
System.out.printf("Hola %s%n", translation.translatedText());
53+
}
54+
}

0 commit comments

Comments
 (0)