LoginSignup
1
0

More than 1 year has passed since last update.

DatabricksからGCPのCloud Translation Basicで翻訳を行う

Posted at

作業の過程で使えるのかなと思った次第で。普通に使えました。

事前準備

  • Cloud Translation APIの有効化
  • サービスアカウントの作成
  • キーの取得: ローカルにjsonファイルをダウンロードします。ここでは、credential.jsonとします。
credential.json
{
  "type": "service_account",
  "project_id": "my-project",
  "private_key_id": "...",
  "private_key": "-----BEGIN PRIVATE 
  ....

ライブラリのインストール

%pip install google-cloud-translate==2.0.1

キーファイルの格納

ここでは、ワークスペースファイルとして格納します。

Screenshot 2023-05-29 at 16.13.50.png

関数の定義

APIを呼び出す関数を定義します。translate.Client.from_service_account_jsonでワークスペースのパスを指定しています。

def translate_text(target, text):
    """Translates text into the target language.

    Target must be an ISO 639-1 language code.
    See https://g.co/cloud/translate/v2/translate-reference#supported_languages
    """
    from google.cloud import translate_v2 as translate

    translate_client = translate.Client.from_service_account_json('/Workspace/Users/takaaki.yayoi@databricks.com/.../credential.json')

    if isinstance(text, bytes):
        text = text.decode("utf-8")

    # Text can also be a sequence of strings, in which case this method
    # will return a sequence of results for each text.
    result = translate_client.translate(text, target_language=target)

    print("Text: {}".format(result["input"]))
    print("Translation: {}".format(result["translatedText"]))
    print("Detected source language: {}".format(result["detectedSourceLanguage"]))

翻訳

translate_text("ja-JP", "what is the difference between data warehouse and data lake?")

英語が日本語に翻訳されました。

Text: what is the difference between data warehouse and data lake?
Translation: データ ウェアハウスとデータ レイクの違いは何ですか?
Detected source language: en

料金に注意しながら活用します。

Databricksクイックスタートガイド

Databricksクイックスタートガイド

Databricks無料トライアル

Databricks無料トライアル

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0