写真のテキストの翻訳

このページでは、画像からテキストを検出する方法、翻訳をカスタマイズする方法、テキストから合成音声を生成する方法を説明します。 このチュートリアルでは、Cloud Vision を使用して画像ファイルからテキストを検出します。次に、Cloud Translation を使用して、検出されたテキストのカスタム翻訳を提供する方法を説明します。最後に、Text-to-Speech を使用して、翻訳テキストのマシン ディクテーションを生成します。

目標

  1. Cloud Vision API により認識されたテキストを Cloud Translation API に渡します。

  2. Cloud Translation の用語集を作成し、それを使用して Cloud Translation API の翻訳をカスタマイズします。

  3. Text-to-Speech API を使用して、翻訳されたテキストの音声表現を作成します。

費用

Google Cloud の各 API には個別の料金体系があります。

料金の詳細は、Cloud Vision の料金ガイドCloud Translation の料金ガイドText-to Speech の料金ガイドをご覧ください。

始める前に

以下を準備します。

クライアント ライブラリの設定

このチュートリアルでは、VisionTranslationText-to-Speech の各クライアント ライブラリを使用します。

関連するクライアント ライブラリをインストールするには、次のコマンドをターミナルから実行します。

Python

  pip install --upgrade google-cloud-vision
  pip install --upgrade google-cloud-translate
  pip install --upgrade google-cloud-texttospeech
  

Node.js

  npm install @google-cloud/vision
  npm install @google-cloud/translate
  npm install @google-cloud/text-to-speech
  

用語集の作成権限を設定する

翻訳用語集を作成するには、「Cloud Translation API 編集者」の権限が付与されたサービス アカウント キーを使用する必要があります。

Cloud Translation API 編集者権限を持つサービス アカウント キーを設定するには、次の手順に従います。

  1. サービス アカウントを作成する。

    1. Google Cloud コンソールで、[サービス アカウント] ページに移動します。

      [サービス アカウント] に移動

    2. プロジェクトを選択します。

    3. [ サービス アカウントを作成] をクリックします。

    4. [サービス アカウント名] フィールドに名前を入力します。Google Cloud コンソールでは、この名前に基づいて [サービス アカウント ID] フィールドに値が入力されます。

    5. 省略可: [サービス アカウントの説明] フィールドに、サービス アカウントの説明を入力します。

    6. [作成して続行] をクリックします。

    7. [ロールを選択] フィールドをクリックし、[Cloud Translation] > [Cloud Translation API 編集者] を選択します。

    8. [完了] をクリックして、サービス アカウントの作成を完了します。

      ブラウザ ウィンドウは閉じないでください。次のステップでこれを使用します。

  2. 作成したサービス アカウントの JSON キーをダウンロードします。

    1. Google Cloud コンソールで、作成したサービス アカウントのメールアドレスをクリックします。
    2. [キー] をクリックします。
    3. [鍵を追加]、[新しい鍵を作成] の順にクリックします。
    4. [作成] をクリックします。JSON キーファイルがパソコンにダウンロードされます。

      鍵ファイルは、サービス アカウントとしての認証で使用できるため、安全な場所に保管してください。このファイルは任意の場所に移動できます。名前の変更も可能です。

    5. [閉じる] をクリックします。

  3. ターミナルで、次のコマンドを使用して GOOGLE_APPLICATION_CREDENTIALS 変数を設定します。 path_to_key は、新しいサービス アカウント キーが含まれている、ダウンロードした JSON ファイルへのパスに置き換えます。

    Linux または macOS

    export GOOGLE_APPLICATION_CREDENTIALS=path_to_key

    Windows

    set GOOGLE_APPLICATION_CREDENTIALS=path_to_key

ライブラリのインポート

このチュートリアルでは、次のシステム インポートとクライアント ライブラリ インポートを使用します。

Python

このサンプルを試す前に、Cloud Translation クイックスタート: クライアント ライブラリの使用にある Python の設定手順を完了してください。詳細については、Cloud Translation Python API リファレンス ドキュメントをご覧ください。

Cloud Translation に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

import html
import os

# Imports the Google Cloud client libraries
from google.api_core.exceptions import AlreadyExists
from google.cloud import texttospeech
from google.cloud import translate_v3beta1 as translate
from google.cloud import vision

Node.js

このサンプルを試す前に、Cloud Translation クイックスタート: クライアント ライブラリの使用にある手順で Node.js の設定を完了してください。詳細については、Cloud Translation Node.js API リファレンス ドキュメントをご覧ください。

Cloud Translation に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

// Imports the Google Cloud client library
const textToSpeech = require('@google-cloud/text-to-speech');
const translate = require('@google-cloud/translate').v3beta1;
const vision = require('@google-cloud/vision');

// Import other required libraries
const fs = require('fs');
//const escape = require('escape-html');
const util = require('util');

プロジェクト ID の設定

Google Cloud API へのリクエストごとに Google Cloud プロジェクトを関連付ける必要があります。GCLOUD_PROJECT 環境変数をターミナルから設定して、Google Cloud プロジェクトを指定します。

次のコマンドを実行します。project-id は Google Cloud プロジェクトの ID で置き換えます。次のコマンドをターミナルから実行します。

Linux または macOS

export GCLOUD_PROJECT=project-id

Windows

set GCLOUD_PROJECT=project-id

Vision を使用して画像からテキストを検出する

Vision API を使用して、画像からテキストを検出して抽出します。Vision API は光学式文字認識(OCR)を採用し、高密度テキスト検出機能(DOCUMENT_TEXT_DETECTION)とスパース テキスト検出機能(TEXT_DETECTION)の 2 つのテキスト検出機能をサポートします。

次のコードは、Vision API の DOCUMENT_TEXT_DETECTION 機能を使用して高密度テキストを含む写真からテキストを検出する方法を示しています。

Python

このサンプルを試す前に、Cloud Translation クイックスタート: クライアント ライブラリの使用にある Python の設定手順を完了してください。詳細については、Cloud Translation Python API リファレンス ドキュメントをご覧ください。

Cloud Translation に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

def pic_to_text(infile: str) -> str:
    """Detects text in an image file

    Args:
    infile: path to image file

    Returns:
    String of text detected in image
    """

    # Instantiates a client
    client = vision.ImageAnnotatorClient()

    # Opens the input image file
    with open(infile, "rb") as image_file:
        content = image_file.read()

    image = vision.Image(content=content)

    # For dense text, use document_text_detection
    # For less dense text, use text_detection
    response = client.document_text_detection(image=image)
    text = response.full_text_annotation.text
    print(f"Detected text: {text}")

    return text

Node.js

このサンプルを試す前に、Cloud Translation クイックスタート: クライアント ライブラリの使用にある手順で Node.js の設定を完了してください。詳細については、Cloud Translation Node.js API リファレンス ドキュメントをご覧ください。

Cloud Translation に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

/**
 * Detects text in an image file
 *
 * ARGS
 * inputFile: path to image file
 * RETURNS
 * string of text detected in the input image
 **/
async function picToText(inputFile) {
  // Creates a client
  const client = new vision.ImageAnnotatorClient();

  // Performs text detection on the local file
  const [result] = await client.textDetection(inputFile);
  return result.fullTextAnnotation.text;
}

Translation で用語集を使用する

テキストを画像から抽出したら、翻訳用語集を使用して、抽出したテキストの翻訳をカスタマイズします。Cloud Translation API によって翻訳された訳語は、用語集に事前に定義された訳語により上書きされます。

用語集には、次のようなユースケースがあります。

  • 商品名: たとえば、「Google Home」は「Google Home」と翻訳されます。

  • 曖昧語: たとえば、「bat」という単語は、スポーツ用具のバット、または動物のコウモリを意味します。スポーツに関する内容を翻訳している場合は、「bat」の訳として動物用語ではなくスポーツ用語を Cloud Translation API に提示できる用語集を使用する必要があります。

  • 借用語: たとえば、フランス語の「bouillabaisse」の英語訳は「bouillabaisse」です。これは、英語がフランス語の「bouillabaisse」という語を借用しているためです。フランスの文化的背景を知らない英語の話者は、「bouillabaisse」がフランスの魚介類の煮込み料理であることを知らないことがあります。用語集を使用することで、フランス語の「bouillabaisse」が英語で「fish stew」と訳されるように、オーバーライドできます。

用語集ファイルを作成する

Cloud Translation API は TSV、CSV、TMX 形式の用語集ファイルに対応しています。このチュートリアルでは、Cloud Storage にアップロードされた CSV ファイルを使用して対訳集を定義します。

用語集 CSV ファイルを作成するには:

  1. 列の言語を指定するには、ISO-639BCP-47 のいずれかの言語コードを CSV ファイルの 1 行目で使用します。

    fr,en,

  2. CSV ファイルの各行で対訳のペアをリストします。対訳となる語句をカンマで区切ります。次の例では、いくつかのフランス語の料理用語の英語訳を定義しています。

    fr,en,
    chèvre,goat cheese,
    crème brulée,crème brulée,
    bouillabaisse,fish stew,
    steak frites,steak with french fries,
    

  3. 単語の異形を定義します。Cloud Translation API では、大文字と小文字、アクセント付き単語などの特殊文字が区別されます。単語のいろいろなスペルを明示的に定義して、単語のバリエーションに用語集が対処できるようにします。

    fr,en,
    chevre,goat cheese,
    Chevre,Goat cheese,
    chèvre,goat cheese,
    Chèvre,Goat cheese,
    crème brulée,crème brulée,
    Crème brulée,Crème brulée,
    Crème Brulée,Crème Brulée,
    bouillabaisse,fish stew,
    Bouillabaisse,Fish stew,
    steak frites,steak with french fries,
    Steak frites,Steak with french fries,
    Steak Frites,Steak with French Fries,
    

  4. 用語集を Cloud Storage バケットアップロードします。このチュートリアルでは、用語集ファイルの Cloud Storage バケットへのアップロードや、Cloud Storage バケットの作成を行う必要はありません。代わりにこのチュートリアルのために作成された一般公開の用語集ファイルを使用して、Cloud Storage の料金が発生しないようにします。Cloud Storage の用語集ファイルの URI を Cloud Translation API に送信して、用語集リソースを作成します。このチュートリアル用に一般公開されている用語集ファイルの URI は gs://cloud-samples-data/translation/bistro_glossary.csv です。用語集をダウンロードするには、上の URI リンクをクリックします。ただし、新しいタブで開かないでください。

用語集リソースを作成する

用語集を使用するには、Cloud Translation API を使用して用語集リソースを作成する必要があります。用語集リソースを作成するには、Cloud Storage にある用語集ファイルの URI を Cloud Translation API に送信します。

必ず「Cloud Translation API 編集者」の権限があるサービス アカウント キーを使用してください。また、プロジェクト ID をターミナルから設定したことを確認してください。

次の関数は、用語集リソースを作成します。このチュートリアルの次のステップでは、この用語集リソースを使用して、翻訳リクエストをカスタマイズします。

Python

このサンプルを試す前に、Cloud Translation クイックスタート: クライアント ライブラリの使用にある Python の設定手順を完了してください。詳細については、Cloud Translation Python API リファレンス ドキュメントをご覧ください。

Cloud Translation に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

def create_glossary(
    languages: list,
    project_id: str,
    glossary_name: str,
    glossary_uri: str,
) -> str:
    """Creates a GCP glossary resource
    Assumes you've already manually uploaded a glossary to Cloud Storage

    Args:
    languages: list of languages in the glossary
    project_id: GCP project id
    glossary_name: name you want to give this glossary resource
    glossary_uri: the uri of the glossary you uploaded to Cloud Storage

    Returns:
    name of the created or existing glossary
    """

    # Instantiates a client
    client = translate.TranslationServiceClient()

    # Designates the data center location that you want to use
    location = "us-central1"

    # Set glossary resource name
    name = client.glossary_path(project_id, location, glossary_name)

    # Set language codes
    language_codes_set = translate.Glossary.LanguageCodesSet(language_codes=languages)

    gcs_source = translate.GcsSource(input_uri=glossary_uri)

    input_config = translate.GlossaryInputConfig(gcs_source=gcs_source)

    # Set glossary resource information
    glossary = translate.Glossary(
        name=name, language_codes_set=language_codes_set, input_config=input_config
    )

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

    # Create glossary resource
    # Handle exception for case in which a glossary
    #  with glossary_name already exists
    try:
        operation = client.create_glossary(parent=parent, glossary=glossary)
        operation.result(timeout=90)
        print("Created glossary " + glossary_name + ".")
    except AlreadyExists:
        print(
            "The glossary "
            + glossary_name
            + " already exists. No new glossary was created."
        )

    return glossary_name

Node.js

このサンプルを試す前に、Cloud Translation クイックスタート: クライアント ライブラリの使用にある手順で Node.js の設定を完了してください。詳細については、Cloud Translation Node.js API リファレンス ドキュメントをご覧ください。

Cloud Translation に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

/** Creates a GCP glossary resource
 * Assumes you've already manually uploaded a glossary to Cloud Storage
 *
 * ARGS
 * languages: list of languages in the glossary
 * projectId: GCP project id
 * glossaryName: name you want to give this glossary resource
 * glossaryUri: the uri of the glossary you uploaded to Cloud Storage
 * RETURNS
 * nothing
 **/
async function createGlossary(
  languages,
  projectId,
  glossaryName,
  glossaryUri
) {
  // Instantiates a client
  const translationClient = await new translate.TranslationServiceClient();

  // Construct glossary
  const glossary = {
    languageCodesSet: {
      languageCodes: languages,
    },
    inputConfig: {
      gcsSource: {
        inputUri: glossaryUri,
      },
    },
    name: translationClient.glossaryPath(
      projectId,
      'us-central1',
      glossaryName
    ),
  };

  // Construct request
  const request = {
    parent: translationClient.locationPath(projectId, 'us-central1'),
    glossary: glossary,
  };

  // Create glossary using a long-running operation.
  try {
    const [operation] = await translationClient.createGlossary(request);
    // Wait for operation to complete.
    await operation.promise();
    console.log('Created glossary ' + glossaryName + '.');
  } catch (AlreadyExists) {
    console.log(
      'The glossary ' +
        glossaryName +
        ' already exists. No new glossary was created.'
    );
  }
}

用語集を使用して翻訳する

用語集リソースを作成したら、この用語集リソースを使用して Cloud Translation API に送信するテキストの翻訳をカスタマイズできます。

次の関数は、前に作成した用語集リソースを使用してテキストの翻訳をカスタマイズします。

Python

このサンプルを試す前に、Cloud Translation クイックスタート: クライアント ライブラリの使用にある Python の設定手順を完了してください。詳細については、Cloud Translation Python API リファレンス ドキュメントをご覧ください。

Cloud Translation に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

def translate_text(
    text: str,
    source_language_code: str,
    target_language_code: str,
    project_id: str,
    glossary_name: str,
) -> str:
    """Translates text to a given language using a glossary

    Args:
    text: String of text to translate
    source_language_code: language of input text
    target_language_code: language of output text
    project_id: GCP project id
    glossary_name: name you gave your project's glossary
        resource when you created it

    Return:
    String of translated text
    """

    # Instantiates a client
    client = translate.TranslationServiceClient()

    # Designates the data center location that you want to use
    location = "us-central1"

    glossary = client.glossary_path(project_id, location, glossary_name)

    glossary_config = translate.TranslateTextGlossaryConfig(glossary=glossary)

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

    result = client.translate_text(
        request={
            "parent": parent,
            "contents": [text],
            "mime_type": "text/plain",  # mime types: text/plain, text/html
            "source_language_code": source_language_code,
            "target_language_code": target_language_code,
            "glossary_config": glossary_config,
        }
    )

    # Extract translated text from API response
    return result.glossary_translations[0].translated_text

Node.js

このサンプルを試す前に、Cloud Translation クイックスタート: クライアント ライブラリの使用にある手順で Node.js の設定を完了してください。詳細については、Cloud Translation Node.js API リファレンス ドキュメントをご覧ください。

Cloud Translation に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

/**
 * Translates text to a given language using a glossary
 *
 * ARGS
 * text: String of text to translate
 * sourceLanguageCode: language of input text
 * targetLanguageCode: language of output text
 * projectId: GCP project id
 * glossaryName: name you gave your project's glossary
 *     resource when you created it
 * RETURNS
 * String of translated text
 **/
async function translateText(
  text,
  sourceLanguageCode,
  targetLanguageCode,
  projectId,
  glossaryName
) {
  // Instantiates a client
  const translationClient = new translate.TranslationServiceClient();
  const glossary = translationClient.glossaryPath(
    projectId,
    'us-central1',
    glossaryName
  );
  const glossaryConfig = {
    glossary: glossary,
  };
  // Construct request
  const request = {
    parent: translationClient.locationPath(projectId, 'us-central1'),
    contents: [text],
    mimeType: 'text/plain', // mime types: text/plain, text/html
    sourceLanguageCode: sourceLanguageCode,
    targetLanguageCode: targetLanguageCode,
    glossaryConfig: glossaryConfig,
  };

  // Run request
  const [response] = await translationClient.translateText(request);
  // Extract the string of translated text
  return response.glossaryTranslations[0].translatedText;
}