Use of Google Translate SDK (Google Translate SDK)

一、安装Google Cloud SDK(http://blog.csdn.net/nicolelili1/article/details/68947164)

2. Set up your project

1. Log in to your Google account and register if you don't have one (https://accounts.google.com/SignUp)

https://accounts.google.com/signin/v2/identifier?flowName=GlifWebSignIn&flowEntry=ServiceLogin


2. In the management background interface, select or create a new project (https://console.cloud.google.com/cloud-resource-manager?_ga=1.106468362.863623109.1502182438&pli=1)


Click "Create"

You can see the generated project in the list


3. Allow billing for the project and set up an account

Click the drop-down menu on the left, click "Settlement" (if no bank card is bound, you need to bind it first)


Select "Manage Billing Accounts"


Select "Create Account"


Click to continue


Click "Confirm" (the country selects the information that matches the credit card, for example, if it is wrongly written in the United States, the money will be deducted and the bill may be blocked because the information is not the same as the account number, and you need to re-appeal)



Created successfully


Click on "My Projects"



Select the account you just created and click "Set Account"



4. Enable Cloud Translation API (Cloud Translation API)

1. Open the URL https://console.cloud.google.com/flows/enableapi?apiid=translation.googleapis.com&_ga=1.1612088.863623109.1502182438 and select the item to be enabled


2. Click "Go to API Overview"



3.点击“ENABLE APIS AND SERVICES”


4. Enter "Google Cloud Translation API" in the search box to search and find the required API


5. Select the API and double-click, select "Enable" in the opened interface


Enabled interface


5. Create Credentials

1. Click on APIs&services-->Credentials-->Create Credentials-->API Keys on the left




6. Initialize Google Cloud SDK

1. Initialize the input command gcloud init


2. Choose to reinitialize the configuration: 1 or recreate a new configuration


3. Use the original account: 1 or log in to a new account: 2


4. Select the item you want to use


5. Authorize Google Cloud SDK


6. Set variables

Computer-->Right click "Properties"-->Advanced System Settings-->New-->GOOGLE_API_KEY:Key


7. Configuration

1. Add dependencies in build.gradle

    compile 'com.google.cloud:google-cloud-translate:1.3.1'

Code:

    private void googleTranslate() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //Translate translate = TranslateOptions.getDefaultInstance().getService();
                Translate translate = TranslateOptions.newBuilder().setApiKey("AIzaSyAuPO3rl-CClveK6XulCapCITeSONanpVA").build().getService();
                String sourceLanguage = "en";
                String targetLanguage = "zh-CN";
                TranslateOption srcLang = TranslateOption.sourceLanguage (sourceLanguage);
                TranslateOption tgtLang = TranslateOption.targetLanguage (targetLanguage);
                // Use translate `model` parameter with `base` and `nmt` options.
                TranslateOption model = TranslateOption.model("nmt");

                String sourceText = "Robinson Crusoe is a real hero. " +
                        "He almost has everything needed for becoming a successful man, " +
                        "such as his excellent creativity, great working capacity, courage, and persistence in overcoming obstacles. " +
                        "However, Robinson Crusoe is not a perfect man. " +
                        "He also has shortcomings. " +
                        "He was such a coward when he encountered a storm the first time. " +
                        "He sweared and repented yet ate his words and sailed on after the storm. " +
                        "By showing Robinson’s shortcomings, Daniel Defoe made Robinson a real person. " +
                        "After all, no one is perfect. " +
                        "Robinson Crusoe can not only lead the ambitious ones to success, but also guide average people to face up to life. " +
                        "This is the significance of the study of Robinson Crusoe";
                Log.e("MainActivity", "googleTranslate.............................1");
                Translation translation = translate.translate(sourceText, srcLang, tgtLang, model);
                Log.e("MainActivity", "Source Text:.............................."+sourceLanguage+"..............."+sourceText);
                Log.e("MainActivity", "TranslatedText.............................."+targetLanguage+"............"+translation.getTranslatedText());
            }
        }).start();
    }
Result after running:

original language

Source Text:..............................en...............Robinson Crusoe is a real hero. He almost has everything needed for becoming a successful man, such as his excellent creativity, great working capacity, courage, and persistence in overcoming obstacles. However, Robinson Crusoe is not a perfect man. He also has shortcomings. He was such a coward when he encountered a storm the first time. He sweared and repented yet ate his words and sailed on after the storm. By showing Robinson’s shortcomings, Daniel Defoe made Robinson a real person. After all, no one is perfect. Robinson Crusoe can not only lead the ambitious ones to success, but also guide average people to face up to life. This is the significance of the study of Robinson Crusoe
 
 
 
 
translated language
TranslatedText.........................................en-CN............Robinson Crusoe yes true hero. He has almost everything it takes to be a successful person like his brilliant creativity, great work ability, courage and persistence to overcome obstacles. However, Robinson Crusoe is not a perfect person. He also has flaws. When he first encountered the storm, he was a coward. He swore and repented, ate his words, and sailed after the storm. By showing Robinson's flaws, Daniel Defoe made Robinson a real character. After all, no one is perfect. Robinson Crusoe can lead not only to ambitious success, but also to ordinary people to face life. Here's what the study of Robinson Crusoe means











Note: 1. References: https://cloud.google.com/translate/docs/getting-started

https://cloud.google.com/docs/authentication/getting-started

http://blog.csdn.net/wangbailin2009/article/details/72742246

https://github.com/GoogleCloudPlatform/google-cloud-java/tree/master/google-cloud-translate

2. Jar download address: https://jar-download.com/?detail_search=g%3A%22com.google.cloud%22&g=com.google.cloud&p=3

problems encountered

3.Error:Failed to resolve: com.google.cloud:google-cloud-translate:0.20.1-alpha


The above problem occurs after adding the following dependencies according to the official website abbreviation


Solution:

将 compile group: 'com.google.cloud', name: 'google-cloud-translate', version: '0.20.1-alpha' 替换为 compile 'com.google.cloud:google-cloud-translate:1.3.1'


4.Execution failed for task ':app:transformClassesWithDexForOffcialSiteDebug'.

> com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536


Solution:

Allow multiDex in build.gradle

android {

    defaultConfig {
        ...

        // Enabling multidex support.
        multiDexEnabled true
    }
    ...
}

dependencies {
  compile 'com.android.support:multidex:1.0.0'
}

5、

Execution failed for task ':app:transformResourcesWithMergeJavaResForOffcialSiteDebug'.
> com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK project.properties
File1: C:\Users\zjhl\.gradle\caches\modules-2\files-2.1\com.google.cloud\google-cloud-translate\1.3.1\ccef30bae3b4358c83d671cc8731bbbde4ed1d17\google-cloud-translate-1.3.1.jar
File2: C:\Users\zjhl\.gradle\caches\modules-2\files-2.1\com.google.cloud\google-cloud-core\1.3.1\6688ecc0b0527ddd08fad76adc5419ba40b68599\google-cloud-core-1.3.1.jar


Duplicate files copied in APK project.properties
File1: C:\Users\zjhl\.gradle\caches\modules-2\files-2.1\com.google.cloud\google-cloud-translate\1.3.1\ccef30bae3b4358c83d671cc8731bbbde4ed1d17\google-cloud-translate-1.3.1.jar
File2: C:\Users\zjhl\.gradle\caches\modules-2\files-2.1\com.google.cloud\google-cloud-core\1.3.1\6688ecc0b0527ddd08fad76adc5419ba40b68599\google-cloud-core-1.3.1.jar


Solution: configure do not add this package option

android {

    packagingOptions {
        exclude 'project.properties'
    }
}

6.

* What went wrong:
Execution failed for task ':app:transformResourcesWithMergeJavaResForOffcialSiteDebug'.
> com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK META-INF/INDEX.LIST
File1: C:\Users\zjhl\.gradle\caches\modules-2\files-2.1\com.google.cloud\google-cloud-core-http\1.3.1\13ff41068c2db0e43cf3ed96e24746fabbcbee21\google-cloud-core-http-1.3.1.jar
File2: C:\Users\zjhl\.gradle\caches\modules-2\files-2.1\com.google.cloud\google-cloud-translate\1.3.1\ccef30bae3b4358c83d671cc8731bbbde4ed1d17\google-cloud-translate-1.3.1.jar
File3: C:\Users\zjhl\.gradle\caches\modules-2\files-2.1\com.google.cloud\google-cloud-core\1.3.1\6688ecc0b0527ddd08fad76adc5419ba40b68599\google-cloud-core-1.3.1.jar




* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.


BUILD FAILED


Total time: 2.86 secs
Duplicate files copied in APK META-INF/INDEX.LIST
File1: C:\Users\zjhl\.gradle\caches\modules-2\files-2.1\com.google.cloud\google-cloud-core-http\1.3.1\13ff41068c2db0e43cf3ed96e24746fabbcbee21\google-cloud-core-http-1.3.1.jar
File2: C:\Users\zjhl\.gradle\caches\modules-2\files-2.1\com.google.cloud\google-cloud-translate\1.3.1\ccef30bae3b4358c83d671cc8731bbbde4ed1d17\google-cloud-translate-1.3.1.jar
File3: C:\Users\zjhl\.gradle\caches\modules-2\files-2.1\com.google.cloud\google-cloud-core\1.3.1\6688ecc0b0527ddd08fad76adc5419ba40b68599\google-cloud-core-1.3.1.jar


Workaround: add exclude INDEX.LIST

    packagingOptions {
        exclude 'project.properties'
        exclude 'META-INF/INDEX.LIST'
    }


6.com.google.cloud.translate.TranslateException: The request is missing a valid API key.


Reason: Originally, TranslateOptions.getDefaultInstance().getService() will call the value of GOOGLE_API_KEY configured on the computer by default, but I don't know which step went wrong. If it is not configured, you can use the following method to dynamically set the API Key

Solution:

Translate translate = TranslateOptions.getDefaultInstance().getService();
Become dynamic to set app key from code

Translate translate = TranslateOptions.newBuilder().setApiKey("AIzaSyAuPO3rl-CClwwwkeXulCapCITeSONanpVA").build().getService();



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324963032&siteId=291194637