Skip to content

Commit

Permalink
Merge pull request #1194 from GoogleCloudPlatform/translate-alpha
Browse files Browse the repository at this point in the history
Add support for Google Translate
  • Loading branch information
mziccard committed Aug 25, 2016
2 parents 343f77d + 0a9c791 commit 9d413c0
Show file tree
Hide file tree
Showing 36 changed files with 3,140 additions and 2 deletions.
38 changes: 38 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ This client supports the following Google Cloud Platform services:
- [Google Cloud Pub/Sub] (#google-cloud-pubsub-alpha) (Alpha - Not working on App Engine Standard)
- [Google Cloud Resource Manager] (#google-cloud-resource-manager-alpha) (Alpha)
- [Google Cloud Storage] (#google-cloud-storage)
- [Google Cloud Translate] (#google-translate) (Alpha)

> Note: This client is a work-in-progress, and may occasionally
> make backwards-incompatible changes.
Expand Down Expand Up @@ -569,6 +570,40 @@ if (blob != null) {
}
```

Google Translate
----------------

- [API Documentation][translate-api]
- [Official Documentation][translate-docs]

#### Preview

Here's a snippet showing a simple usage example. The example shows how to detect the language of
some text and how to translate some text. The example assumes that the `GOOGLE_API_KEY` is set and
contains a valid API key. Alternatively, you can use the `apiKey(String)` setter in
`TranslateOptions.Builder` to set the API key. Complete source code can be found at
[DetectLanguageAndTranslate.java](./gcloud-java-examples/src/main/java/com/google/cloud/examples/translate/snippets/DetectLanguageAndTranslate.java).
```java
import com.google.cloud.translate.Detection;
import com.google.cloud.translate.Translate;
import com.google.cloud.translate.Translate.TranslateOption;
import com.google.cloud.translate.TranslateOptions;
import com.google.cloud.translate.Translation;
Translate translate = TranslateOptions.defaultInstance().service();
Detection detection = translate.detect("Hola");
String detectedLanguage = detection.language();
Translation translation = translate.translate(
"World",
TranslateOption.sourceLanguage("en"),
TranslateOption.targetLanguage(detectedLanguage));
System.out.printf("Hola %s%n", translation.translatedText());
```
Troubleshooting
---------------
Expand Down Expand Up @@ -648,3 +683,6 @@ Apache 2.0 - See [LICENSE] for more information.
[cloud-compute]: https://cloud.google.com/compute/
[cloud-compute-docs]: https://cloud.google.com/compute/docs/overview
[compute-api]: http://googlecloudplatform.github.io/gcloud-java/apidocs/index.html?com/google/cloud/compute/package-summary.html

[translate-docs]: https://cloud.google.com/translate/docs/
[translate-api]: http://googlecloudplatform.github.io/gcloud-java/apidocs/index.html?com/google/cloud/translate/package-summary.html
20 changes: 20 additions & 0 deletions TESTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -270,5 +270,25 @@ Here is an example that clears the bucket created in Step 3 with a timeout of 5
RemoteStorageHelper.forceDelete(storage, bucket, 5, TimeUnit.SECONDS);
```
### Testing code that uses Translate
`RemoteTranslateHelper` contains convenience methods to make is easier to run tests against the
Google Translate service.
1. Create a test Google Cloud project.
2. Follow [Translate Quickstart](https://cloud.google.com/translate/v2/quickstart) to get an API
key.
3. Create a `RemoteTranslateHelper` object using your project ID and API key. Here is an example
that uses the `RemoteTranslateHelper` to list supported languages.
```java
RemoteTranslateHelper translateHelper = RemoteTranslateHelper.create(PROJECT_ID, API_KEY);
Translate translate = translateHelper.options().service();
List<Language> languages = translate.listSupportedLanguages();
```
4. Run your tests.
[cloud-platform-storage-authentication]:https://cloud.google.com/storage/docs/authentication?hl=en#service_accounts
[create-service-account]:https://developers.google.com/identity/protocols/OAuth2ServiceAccount#creatinganaccount
10 changes: 10 additions & 0 deletions gcloud-java-examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,16 @@ To run examples from your command line:
via the NIO API. It lists gcloud-java-nio as a dependency, and that enables it to interpret
`gs://` paths.

* Here's an example run of `TranslateExample`.

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.
```
target/appassembler/bin/TranslateExample <apiKey> languages
target/appassembler/bin/TranslateExample <apiKey> detect Hello,\ World!
target/appassembler/bin/TranslateExample <apiKey> translate ¡Hola\ Mundo!
target/appassembler/bin/TranslateExample <apiKey> es translate Hello,\ World!
```

Troubleshooting
---------------

Expand Down
4 changes: 4 additions & 0 deletions gcloud-java-examples/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,10 @@
<mainClass>com.google.cloud.examples.storage.StorageExample</mainClass>
<name>StorageExample</name>
</program>
<program>
<mainClass>com.google.cloud.examples.translate.TranslateExample</mainClass>
<name>TranslateExample</name>
</program>
</programs>
</configuration>
</plugin>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.examples.translate;

import com.google.cloud.translate.Detection;
import com.google.cloud.translate.Language;
import com.google.cloud.translate.Translate;
import com.google.cloud.translate.TranslateOptions;
import com.google.cloud.translate.Translation;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* An example of using Google Translate.
*
* <p>This example demonstrates a simple/typical Translate usage.
*
* <p>See the
* <a href="https://github.com/GoogleCloudPlatform/gcloud-java/blob/master/gcloud-java-examples/README.md">
* README</a> for compilation instructions. Run this code with
* <pre>{@code target/appassembler/bin/TranslateExample
* -Dexec.args="<apiKey> [<targetLanguage>]
* list languages <languageCode>?
* detect <text>+
* translate <text>+"}</pre>
*
* <p>The first parameter is an optional {@code targetLanguage}. If the target language is not
* supplied, {@code en} is used (see {@link TranslateOptions.Builder#targetLanguage(String)}).
*/
public class TranslateExample {

private static final Map<String, TranslateAction> ACTIONS = new HashMap<>();

private abstract static class TranslateAction<T> {

abstract void run(Translate translate, T arg) throws Exception;

abstract T parse(String... args) throws Exception;

protected String params() {
return "";
}
}

/**
* This class demonstrates how to list supported languages.
*
* @see <a href="https://cloud.google.com/translate/v2/discovering-supported-languages-with-rest">
* Discovering Supported Languages</a>
*/
private static class ListLanguagesAction extends TranslateAction<Void> {
@Override
public void run(Translate translate, Void arg) {
List<Language> languages = translate.listSupportedLanguages();
System.out.println("Supported languages:");
for (Language language : languages) {
System.out.println(language);
}
}

@Override
Void parse(String... args) throws Exception {
if (args.length == 0) {
return null;
}
throw new IllegalArgumentException("This action takes no arguments.");
}
}

/**
* This class demonstrates how detect the language of some texts.
*
* @see <a href="https://cloud.google.com/translate/v2/detecting-language-with-rest">Detecting
* Language</a>
*/
private static class DetectLanguageAction extends TranslateAction<List<String>> {
@Override
public void run(Translate translate, List<String> texts) {
List<Detection> detections = translate.detect(texts);
if (texts.size() == 1) {
System.out.println("Detected language is:");
} else {
System.out.println("Detected languages are:");
}
for (Detection detection : detections) {
System.out.println(detection);
}
}

@Override
List<String> parse(String... args) throws Exception {
if (args.length >= 1) {
return Arrays.asList(args);
} else {
throw new IllegalArgumentException("Missing required texts.");
}
}

@Override
public String params() {
return "<text>+";
}
}

/**
* This class demonstrates how to translate some texts.
*
* @see <a href="https://cloud.google.com/translate/v2/translating-text-with-rest">Translating
* Text</a>
*/
private static class TranslateTextAction extends TranslateAction<List<String>> {
@Override
public void run(Translate translate, List<String> texts) {
List<Translation> translations = translate.translate(texts);
if (texts.size() == 1) {
System.out.println("Translation is:");
} else {
System.out.println("Translations are:");
}
for (Translation translation : translations) {
System.out.println(translation);
}
}

@Override
List<String> parse(String... args) throws Exception {
if (args.length >= 1) {
return Arrays.asList(args);
} else {
throw new IllegalArgumentException("Missing required texts.");
}
}

@Override
public String params() {
return "<text>+";
}
}

static {
ACTIONS.put("languages", new ListLanguagesAction());
ACTIONS.put("detect", new DetectLanguageAction());
ACTIONS.put("translate", new TranslateTextAction());
}

private static void printUsage() {
StringBuilder actionAndParams = new StringBuilder();
for (Map.Entry<String, TranslateAction> entry : ACTIONS.entrySet()) {
actionAndParams.append(System.lineSeparator()).append('\t').append(entry.getKey());
String param = entry.getValue().params();
if (param != null && !param.isEmpty()) {
actionAndParams.append(' ').append(param);
}
}
System.out.printf("Usage: %s [<apiKey>] [<targetLanguage>] operation <args>*%s%n",
TranslateExample.class.getSimpleName(), actionAndParams);
}

@SuppressWarnings("unchecked")
public static void main(String... args) throws Exception {
if (args.length < 1) {
System.out.println("Missing required action");
printUsage();
return;
}
TranslateOptions.Builder optionsBuilder = TranslateOptions.builder();
TranslateAction action;
String actionName;
if (args.length >= 3 && !ACTIONS.containsKey(args[1])) {
optionsBuilder.apiKey(args[0]);
actionName = args[2];
optionsBuilder.targetLanguage(args[1]);
args = Arrays.copyOfRange(args, 3, args.length);
} else if (args.length >= 2 && !ACTIONS.containsKey(args[0])) {
optionsBuilder.apiKey(args[0]);
actionName = args[1];
args = Arrays.copyOfRange(args, 2, args.length);
} else {
actionName = args[0];
args = Arrays.copyOfRange(args, 1, args.length);
}
action = ACTIONS.get(actionName);
if (action == null) {
System.out.println("Unrecognized action.");
printUsage();
return;
}
Object arg;
try {
arg = action.parse(args);
} catch (IllegalArgumentException ex) {
System.out.printf("Invalid input for action '%s'. %s%n", actionName, ex.getMessage());
System.out.printf("Expected: %s%n", action.params());
return;
} catch (Exception ex) {
System.out.println("Failed to parse arguments.");
ex.printStackTrace();
return;
}
Translate translate = optionsBuilder.build().service();
action.run(translate, arg);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.
*/

/*
* EDITING INSTRUCTIONS
* This file is referenced in READMEs and javadoc. Any change to this file should be reflected in
* the project's READMEs and package-info.java.
*/

package com.google.cloud.examples.translate.snippets;

import com.google.cloud.translate.Detection;
import com.google.cloud.translate.Translate;
import com.google.cloud.translate.Translate.TranslateOption;
import com.google.cloud.translate.TranslateOptions;
import com.google.cloud.translate.Translation;

/**
* A snippet for Google Translate showing how to detect the language of some text and translate
* some other text.
*/
public class DetectLanguageAndTranslate {

public static void main(String... args) {
// Create a service object
// API key is read from the GOOGLE_API_KEY environment variable
Translate translate = TranslateOptions.defaultInstance().service();

// Detect the language of some text
Detection detection = translate.detect("Hola");
String detectedLanguage = detection.language();

// Translate some text
Translation translation = translate.translate(
"World",
TranslateOption.sourceLanguage("en"),
TranslateOption.targetLanguage(detectedLanguage));

System.out.printf("Hola %s%n", translation.translatedText());
}
}
Loading

0 comments on commit 9d413c0

Please sign in to comment.