Google Cloud Translation API入门

本文章需要全程科学上网

1. 介绍

官方文档主页:https://cloud.google.com/translate/docs/, GCP 首页: https://cloud.google.com/

入门文档:Quickstart Go 语言 Github

前置条件:

注册 Google 账号,

  1. 创建或者选择一个 Project
  2. 在 Project 中启用 Google Cloud Translation API 访问调用

2. 简单通过 API + Key 访问

比如请求获取支持的语言列表:语言参考 ISO 639-1

https://translation.googleapis.com/language/translate/v2/languages/?target=en&key=YOUR_API_KEY_HERE

其中 YOUR_API_KEY_HERE 是我们在创建密钥过程中选择的 API Key 类型,官方教程 Setting up API keys。如果不是则会返回以下类型错误:API Key not valid error when trying to access Google cloud vision api

{
  "error": {
    "code": 400,
    "message": "API key not valid. Please pass a valid API key.",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.Help",
        "links": [
          {
            "description": "Google developer console API key",
            "url": "https://console.developers.google.com/project/414754136843/apiui/credential"
          }
        ]
      }
    ]
  }
}

3. Google Cloud Console

设置 GCP 命令行 Project

  1. 创建一个服务账号(Service Account)

  2. 下载 Private Key 作为 Json 文件

安装和初始化 Cloud SDK

详细步骤参见:https://cloud.google.com/sdk/docs/, 如果是在本地安装的话,中间会弹出使用 Google 账号登录授权的页面。如果是在 GCP 的命令行中,则不需要该步骤,直接跳到下一个步骤即可。

设置授权密钥

gcloud auth activate-service-account --key-file=[PATH]   # key file 为下载的 Json 文件

使用 API 请求测试

curl -s -X POST -H "Content-Type: application/json" \
    -H "Authorization: Bearer "$(gcloud auth print-access-token) \
    --data "{
  'q': 'The Great Pyramid of Giza (also known as the Pyramid of Khufu or the
        Pyramid of Cheops) is the oldest and largest of the three pyramids in
        the Giza pyramid complex.',
  'source': 'en',
  'target': 'es',
  'format': 'text'
}" "https://translation.googleapis.com/language/translate/v2"

4. Cloud Translation API Client Libraries

以 go 语言为例。

安装客户端库

go get -u cloud.google.com/go/translate

设置授权密钥

创建服务账号(Service Account)过程同上。需要设置环境变量 ”GOOGLE_APPLICATION_CREDENTIALS“, 指向将作为私钥下载的Json文件。

使用以下 代码访问 即可:

// Sample translate-quickstart translates "Hello, world!" into Russian.
package main

import (
        "fmt"
        "log"

        // Imports the Google Cloud Translate client package.
        "cloud.google.com/go/translate"
        "golang.org/x/net/context"
        "golang.org/x/text/language"
)

func main() {
        ctx := context.Background()

        // Creates a client.
        client, err := translate.NewClient(ctx)
        if err != nil {
                log.Fatalf("Failed to create client: %v", err)
        }

        // Sets the text to translate.
        text := "Hello, world!"
        // Sets the target language.
        target, err := language.Parse("ru")
        if err != nil {
                log.Fatalf("Failed to parse target language: %v", err)
        }

        // Translates the text into Russian.
        translations, err := client.Translate(ctx, []string{text}, target, nil)
        if err != nil {
                log.Fatalf("Failed to translate text: %v", err)
        }

        fmt.Printf("Text: %v\n", text)
        fmt.Printf("Translation: %v\n", translations[0].Text)
}

其他翻译服务:

Baidu 全新翻译平台, 特点如下:

  1. 通用翻译,支持 28 种语言实时互译,每月 200万 字符免费,无访问频次限制
  2. 定制化翻译 API
  3. 拍照翻译 SDK
  4. 语音翻译 SDK

有道翻译

http://ai.youdao.com/?keyfrom=BSEM-fanyisdk-08

金山词霸

http://open.iciba.com/?c=api

必应翻译

https://www.bing.com/translator

参考

  1. 谷歌翻译SDK (Google Translate SDK)的使用
  2. 给大家分享一个免费的谷歌翻译api
  3. Translate-API-js-library-Google-Translate-and-Baidu-Translate

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注