由于篇幅有限,前篇文章我们主要介绍了 Cloud Translation API如何调用的准备工作,那么本篇文章将主要来跟大家聊一聊核心步骤——Cloud Translation API的调用方法。就让我们直奔主题吧!
共有三种调用方法,分别是:使用apikey调用(仅v2版本)使用服务账号调用使用客户端库调用

我们首先来说针对v2版本使用的apikey调用

Step 1.
将刚创建的API key复制到剪贴板,然后使用以下代码行将其保存到终端的环境变量中。确保使用剪贴板中的密钥替换YOUR_API_KEY。

export API_KEY=YOUR_API_KEY

Step2.    
翻译文本

$ curl "https://translation.googleapis.com/language/translate/v2?target=es&key=${API_KEY}&q=${TEXT}"
{
  "data": {
    "translations": [
      {
        "translatedText": "Mi nombre es Steve",
        "detectedSourceLanguage": "en"
      }
    ]
  }
}

再看使用服务账号调用

Step1.    
将环境变量 GOOGLE_APPLICATION_CREDENTIALS 设置为包含服务帐号密钥的 JSON 文件的路径。此变量仅适用于当前的 shell 会话,因此,如果您打开新的会话,请重新设置该变量。
示例:
将 [PATH] 替换为包含您服务帐号密钥的 JSON 文件的路径

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"

Step2.
使用如下命令进行调用(v2)。示例:curl 命令使用 gcloud auth application-default print-access-token 命令来获取身份验证令牌。使用如下命令进行调用(v2)。示例:curl 命令使用 gcloud auth application-default print-access-token 命令来获取身份验证令牌。

$ curl -s -X POST -H "Content-Type: application/json"     -H "Authorization: Bearer "$(gcloud auth application-default 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': 'zh',
  'format': 'text'
}" "https://translation.googleapis.com/language/translate/v2"
{
  "data": {
    "translations": [
      {
        "translatedText": "吉萨大金字塔(也称为胡夫金字塔或\n        Cheops金字塔)是美国三座金字塔中最古老和最大的金字 塔\n        吉萨金字塔情结。"
      }
    ]
  }
}

Step3.  
使用如下命令调用(v3),HTTP 方法和网址:

POST https://translation.googleapis.com/v3/projects/project-number-or-id:translateText

请求 JSON 正文:

{
  "sourceLanguageCode": "en",  
  "targetLanguageCode": "zh",
  "contents": ["Dr. Watson, come here!", "Bring me some coffee!"]
}

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://translation.googleapis.com/v3/projects/webeye-internal-test:translateText

返回结果如下:

{  
  "translations": [    
    {
      "translatedText": "沃森博士,过来!"  
    },  
    {
      "translatedText": "给我一杯咖啡!"
    }  
  ]
}

最后我们来看看如何使用客户端库来进行调用
以python为例

Step1.    
安装客户端库

pip install google-cloud-translate

Step2.    
从https://translation.googleapis.com/language/translate/v2 接口请求翻译

#!/usr/bin/env python

def run_quickstart():
    # [START translate_quickstart]# Imports the Google Cloud client library
    from google.cloud import translate_v2 as translate

    # Instantiates a client
    translate_client = translate.Client()

    # The text to translate
    text = u'Hello, world!'
    # The target language
    target = 'ru'

    # Translates some text into Russian
    translation = translate_client.translate(
        text,
        target_language=target)

     print(u'Text: {}'.format(text))
    print(u'Translation: {}'.format(translation['translatedText']))
    # [END translate_quickstart]


if __name__ == '__main__':
    run_quickstart()

Step3.    
结果如下

$ python quickstart.py
Text: Hello, world!
Translation: Привет мир!

Step4.    
使用v3接口请求翻译,v3接口和v2接口调用起来是有区别的。
主要区别在接口的endpoint中要加入project id, location

from google.cloud import translate

def translate_text(text="YOUR_TEXT_TO_TRANSLATE", project_id="YOUR_PROJECT_ID"):
    """Translating Text."""

    client = translate.TranslationServiceClient()

    location = "global"

    parent = f"projects/{project_id}/locations/{location}"

    # Detail on supported types can be found here:
    # https://cloud.google.com/translate/docs/supported-formats

    response = client.translate_text(
        request={
            "parent": parent,
            "contents": [text],
            "mime_type": "text/plain",  # mime types: text/plain, text/html
            "source_language_code": "en-US",
            "target_language_code": "fr",
        }
     )

    # Display the translation for each input text provided

   
for translation in response.translations:
        print("Translated text: {}".format(translation.translated_text))

到这里关于Cloud Translation API的调用方法就基本介绍完了。
那么,你学废了么!

返回全部