Google Translate #Translation_API_Basic: Translate

Google Translate: Translation API Basic, Translate
Google Translate: Translation API Basic, Translate
Translates using Google Translation API v2. Specifying the target language is mandatory, but specifying the source language is optional (Detected). The NMT (Neural Machine Translation) model is applied in most languages, while the PBMT (Phrase-Based Machine Translation) model is done in some languages.
Configs
  • U: Select HTTP_Authz Setting *
  • A1: Set Source Lang Code (eg “en”)#{EL}
  • A2: Set Source Text *#{EL}
  • A3: Set Source Text Format “html” (default) or “text”#{EL}
  • B1: Set Target Lang Code (eg “ja”, “de”) *#{EL}
  • B2: Select STRING that stores Translated Text (update) *
Script (click to open)
// GraalJS Script (engine type: 2)

//////// START "main()" /////////////////////////////////////////////////////////////////
main();
function main(){ 

//// == Config Retrieving / 工程コンフィグの参照 ==
const strAuthzSetting     = configs.get      ( "AuthzConfU" );   /// REQUIRED
  engine.log( " AutomatedTask Config: Authz Setting: " + strAuthzSetting );
const strSourceLang       = configs.get      ( "StrConfA1" );    // NotRequired
  if( strSourceLang     === "" ){
    engine.log( " AutomatedTask ConfigWarning:" +
                " Config {A1:SourceLang} is empty" );
  }else{
    engine.log( " AutomatedTask Config: SourceLang: " + strSourceLang );
  }
const strSourceText       = configs.get      ( "StrConfA2" );    /// REQUIRED
  if( strSourceText     === "" ){
    throw new Error( "\n AutomatedTask ConfigError:" +
                     " Config {A2:SourceText} is empty \n" );
  }
let   strSourceFormat     = "html";
let   strSourceFormatTmp  = configs.get      ( "StrConfA3" );    // NotRequired
  if( strSourceFormatTmp === "text" ){
      strSourceFormat     = "text";
  }
const strTargetLang       = configs.get      ( "StrConfB1" );    /// REQUIRED
  if( strTargetLang     === "" ){
    throw new Error( "\n AutomatedTask ConfigError:" +
                     " Config {B1:TargetLang} is empty \n" );
  }
const strPocketTargetText = configs.getObject( "SelectConfB2" ); /// REQUIRED


//// == Data Retrieving / ワークフローデータの参照 ==
// (Nothing. Retrieved via Expression Language in Config Retrieving)


//// == Calculating / 演算 ==
/// (Google Clound > Cloud Translation > Translation API Basic)
/// https://cloud.google.com/translate/docs/reference/rest/v2/translate
// request1, prepare
let postUri1 = "https://translation.googleapis.com/language/translate/v2";
let request1 = httpClient.begin(); // HttpRequestWrapper
    request1 = request1.authSetting( strAuthzSetting ); // with "Authorization: Bearer XX"
    // https://questetra.zendesk.com/hc/en-us/articles/360024574471-R2300#HttpRequestWrapper
    request1 = request1.queryParam( "q",      strSourceText );
    request1 = request1.queryParam( "format", strSourceFormat );
    if( strSourceLang !== "" ){
      request1 = request1.queryParam( "source", strSourceLang );
    }
    request1 = request1.queryParam( "target", strTargetLang );
// request1, try
const response1     = request1.post( postUri1 ); // HttpResponseWrapper
engine.log( " AutomatedTask ApiRequest1 Start: " + postUri1 );
const response1Code = response1.getStatusCode() + "";
const response1Body = response1.getResponseAsString() + "";
engine.log( " AutomatedTask ApiResponse Status: " + response1Code );
if( response1Code !== "200"){
  throw new Error( "\n AutomatedTask UnexpectedResponseError: " +
                    response1Code + "\n" + response1Body + "\n" );
}
// response1, parse
engine.log( response1Body ); // debug
/*
{
  "data": {
    "translations": [
      {
        "translatedText": "吾輩は猫である。まだ名前はありません。どこで生まれたのかわかりません。"
      }
    ]
  }
}
*/
const response1Obj  = JSON.parse( response1Body );
let   strTargetText = response1Obj.data.translations[0].translatedText;


//// == Data Updating / ワークフローデータへの代入 ==
engine.setData( strPocketTargetText,  strTargetText );


} //////// END "main()" /////////////////////////////////////////////////////////////////



/*
Notes:
- Machine translation is performed using Google Cloud Translation Basic (Translation API v2).
    - Charged for Cloud Translation based on monthly usage.
    - https://cloud.google.com/translate?hl=en#section-5
- Does not support Glossary unlike Google Cloud Translation Advanced (Translation API v3), 
- The input text can be plain text or HTML. (any HTML tags in the input not be translated)
    - https://cloud.google.com/translate?hl=en#section-4
- Set up automatic communication (API communication) in advance on "Google Cloud Console".
    - Select (or Create if needed) a Google Cloud project.
        - Console: https://console.cloud.google.com/projectselector2/home/dashboard
    - Activate "Cloud Translation API" in the project.
    - Create an OAuth 2.0 Client in credential, then make a note of ClientID and ClientSecret.
        - Setting example of OAuth consent screen
            - App name: "TransForBpms"
        - Setting example of OAuth 2.0 client
            - Application type: "Web application"
            - Name: "Bpms-Trans"
            - JavaScript Source: ""
            - Redirect URI: "https://s.questetra.net/oauth2callback"
    - Documentation: https://cloud.google.com/translate/docs/setup
- Config [HTTP Authentication] of the Workflow Platform, then get the Refresh token.
    - Setting example of "HTTP Authentication" (OAuth2)
        - Name:
            -"GoogleTrans"
        - Authorization Endpoint URL
            -"https://accounts.google.com/o/oauth2/auth?access_type=offline&approval_prompt=force"
        - Token Endpoint URL
            -"https://accounts.google.com/o/oauth2/token"
        - Scope
            -"https://www.googleapis.com/auth/cloud-translation"
        - Client ID
            - (noted ClientID)
        - Consumer Secret
            - (noted ClientSecret)

Notes-ja:
- Google Cloud Translation Basic (Translation API v2) で機械翻訳されます。
    - 月間使用量に基づいて料金が請求されます。
    - https://cloud.google.com/translate?hl=ja#section-5
- Google Cloud Translation Advanced (Translation API v3) と異なり "用語集" 等には対応していません。
- プレーンテキストまたはHTMLフォーマットの文字列を翻訳します。(HTMLタグは翻訳されません)
    - https://cloud.google.com/translate?hl=ja#section-4
- あらかじめ "Google Cloud Console" にて、自動通信(API通信)に関する設定を行います。
    - Google Cloud プロジェクトを選択(必要に応じて作成)します。
        - Console: https://console.cloud.google.com/projectselector2/home/dashboard?hl=ja
    - プロジェクトにて "Cloud Translation API" を[有効化]します。
    - 認証情報から[OAuth 2.0 クライアント]を作成し、"Client ID" および "Client Secret" をメモします。
        - "OAuth 同意画面" の設定例
            - アプリ名: "TransForBpms"
        - "認証情報" の設定例 (OAuth 2.0 クライアント)
            - アプリケーションの種類: "ウェブアプリケーション"
            - 名前: "Bpms-Trans"
            - 承認済みのJavaScript生成元: ""
            - 承認済みのリダイレクトURI: "https://s.questetra.net/oauth2callback"
    - ドキュメント: https://cloud.google.com/translate/docs/setup?hl=ja
- ワークフロー基盤の[HTTP認証]にてGoogleへの自動通信設定を入力し、Refreshトークンを取得します。
    - "HTTP認証" (OAuth2)の設定例
        - Name:
            - "GoogleTrans"
        - Authorization Endpoint URL
            - "https://accounts.google.com/o/oauth2/auth?access_type=offline&approval_prompt=force"
        - Token Endpoint URL
            - "https://accounts.google.com/o/oauth2/token"
        - Scope
            - "https://www.googleapis.com/auth/cloud-translation"
        - Client ID
            - (メモしたクライアントID)
        - Consumer Secret
            - (メモしたクライアントシークレット)
*/


/*
APPENDIX
- Supported Language Codes in Cloud Translation API (v2) - Over 100 languages
    - English: "en", Spanish: "es", French: "fr", German: "de", Portuguese: "pt"
    - Japanese: "ja", Korean: "ko", Chinese Simplified: "zh-CN", Chinese Traditional: "zh-TW", etc
    - https://cloud.google.com/translate/docs/languages?hl=ja
    - https://cloud.google.com/translate/docs/basic/discovering-supported-languages?hl=ja

APPENDIX-ja
- Cloud Translation API (v2) でサポートされている言語コード - 100言語以上
    - 英語: "en", スペイン語: "es", フランス語: "fr", ドイツ語: "de", ポルトガル語: "pt"
    - 日本語: "ja", 韓国語: "ko", 簡体中国語: "zh-CN", 繁体中国語: "zh-TW", 等
    - https://cloud.google.com/translate/docs/languages?hl=ja
    - https://cloud.google.com/translate/docs/basic/discovering-supported-languages?hl=ja
*/


Download

2021-03-09 (C) Questetra, Inc. (MIT License)
https://support.questetra.com/addons/google-translate-translation-api-basic-translate/
The Addon-import feature is available with Professional edition.

Notes

  • Machine translation is performed using Google Cloud Translation Basic (Translation API v2).
  • Does not support Glossary, unlike Google Cloud Translation Advanced (Translation API v3).
  • The input text can be plain text or HTML. (Any HTML tags in the input will not be translated.)
  • Set up automatic communication (API communication) in advance on Google Cloud Console.
    • Select (or create, if needed) a Google Cloud project.
    • Activate Cloud Translation API in the project.
    • Create an OAuth 2.0 Client in credential, then make a note of ClientID and ClientSecret.
      • Setting example of OAuth consent screen
        • App name: TransForBpms
      • Setting example of OAuth 2.0 client
        • Application type: Web application
        • Name: Bpms-Trans
        • JavaScript Source:
        • Redirect URI: https://s.questetra.net/oauth2callback
    • Documentation: https://cloud.google.com/translate/docs/setup
  • Config [HTTP Authentication] of the Workflow Platform, then get the Refresh token.
    • Setting example of HTTP Authentication (OAuth2)
      • Name:
        -“GoogleTrans
      • Authorization Endpoint URL
        -“https://accounts.google.com/o/oauth2/auth?access_type=offline&approval_prompt=force
      • Token Endpoint URL
        -“https://accounts.google.com/o/oauth2/token
      • Scope
        -“https://www.googleapis.com/auth/cloud-translation
      • Client ID
        • (noted ClientID)
      • Consumer Secret
        • (noted ClientSecret)

Capture

Translates using Google Translation API v2. Specifying the target language is mandatory, but specifying the source language is optional (Detected). The NMT model is applied, but in some languages the PBMT model is applied.

Appendix

  • Supported Language Codes in Cloud Translation API (v2) – Over 100 languages
  • Retranslation A
    • On the back cover of their final issue was a photograph of an early morning country road, the kind you might find yourself hitchhiking on if you were so adventurous. Beneath it were the words: “Stay Hungry. Stay Foolish.” It was their farewell message as they signed off. Stay Hungry. Stay Foolish. And I have always wished that for myself. And now, as you graduate to begin anew, I wish that for you. Stay Hungry. Stay Foolish.
    • 最終号の裏表紙には、早朝の田舎道の写真がありました。冒険心があれば、ヒッチハイクをしているかもしれません。その下には、「空腹のまま。愚かのまま」という言葉がありました。彼らがサインオフしたとき、それは彼らの別れのメッセージでした。空腹のまま。愚かでいなさい。そして、私はいつも自分自身のためにそれを望んでいました。そして今、あなたが卒業して新たに始めるとき、私はあなたのためにそれを望みます。空腹のまま。愚かでいなさい。
    • On the back cover of the final issue was a photo of a country road in the early morning. If you are adventurous, you may be hitchhiking. Below that was the phrase, “Stay hungry. Stay stupid.” It was their farewell message when they signed off. Stay hungry. Be stupid. And I always wanted it for myself. And now, when you graduate and start anew, I want it for you. Stay hungry. Be stupid.
  • Retranslation B
    • I have a dream that my four little children will one day live in a nation where they will not be judged by the color of their skin but by the content of their character. I have a dream today!
    • いつの日か、4人の小さな子供たちが肌の色ではなく性格の内容で判断される国に住むことを夢見ています。今日は夢があります!
    • One day, I dream of four little children living in a country that is judged by their personality rather than their skin color. I have a dream today!
  • Retranslation C
    • 吾輩は猫である。名前はまだ無い。どこで生れたかとんと見当がつかぬ。何でも薄暗いじめじめした所でニャーニャー泣いていた事だけは記憶している。吾輩はここで始めて人間というものを見た。しかもあとで聞くとそれは書生という人間中で一番獰悪(どうあく)な種族であったそうだ。
    • I am a cat. As yet I have no name. I’ve no idea where I was born. All I remember is that I was miaowing in a dampish dark place when, for the first time, I saw a human being. This human being, I heard afterwards, was a member of the most ferocious human species; a shosei, one of those students who, in return for board and lodging, perform small chores about the house.
    • 吾輩は猫である。まだ名前はありません。どこで生まれたのかわかりません。私が覚えているのは、初めて人間を見たとき、私は湿った暗い場所で呟いていたということだけです。この人間は、後で聞いたように、最も凶暴な人間の種のメンバーでした。宿舎と宿泊の見返りに家の雑用をする学生の一人、正生。

See also

Converter: Datetimes in different timezones
DeepL: Text, Translate

1 thought on “Google Translate #Translation_API_Basic: Translate”

  1. Pingback: DeepL: Text, Translate – Questetra Support

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Questetra Support

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top