翻譯相片中的文字


本頁說明如何偵測圖片中的文字、如何個人化翻譯,以及如何從文字生成合成語音。本教學課程會使用 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
  

設定詞彙表建立權限

如要建立 Translation 詞彙表,必須使用具備「Cloud Translation API 編輯者」權限的服務帳戶金鑰。

如要設定具有 Cloud Translation API 編輯器權限的服務帳戶金鑰,請按照下列步驟操作:

  1. 建立服務帳戶:

    1. 前往 Google Cloud 控制台的「Service Accounts」(服務帳戶) 頁面。

      前往「Service Accounts」(服務帳戶)

    2. 選取專案。

    3. 按一下「建立服務帳戶」

    4. 在「Service account name」(服務帳戶名稱) 欄位中輸入名稱。Google Cloud 控制台會根據這個名稱填入「服務帳戶 ID」欄位。

    5. 選用:在「服務帳戶說明」欄位中,輸入服務帳戶的說明。

    6. 按一下「建立並繼續」

    7. 按一下「Select a role」(請選擇角色) 欄位,然後依序選取「Cloud Translation」>「Cloud Translation API Editor」(Cloud Translation API 編輯者)

    8. 按一下「Done」(完成),即完成建立服務帳戶。

      請勿關閉瀏覽器視窗。您將在下一個步驟中使用此項目。

  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

在試用這個範例之前,請先按照Python使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 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

在試用這個範例之前,請先按照Node.js使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 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 專案與對 Google Cloud API 的每項要求建立關聯。從終端機設定 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)。

下列程式碼說明如何使用 Vision API DOCUMENT_TEXT_DETECTION 功能,偵測文字密集的相片中的文字。

Python

在試用這個範例之前,請先按照Python使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 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

在試用這個範例之前,請先按照Node.js使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 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;
}

使用詞彙表翻譯

從圖片擷取文字後,可以使用翻譯詞彙表,自訂擷取文字的翻譯結果。詞彙表提供預先定義的翻譯,可覆寫 Cloud Translation API 對指定字詞的翻譯。

詞彙表用途包括:

  • 產品名稱:例如「Google Home」必須翻譯為「Google Home」。

  • 含糊不清的字詞:例如「蝙蝠」一詞可以指運動器材,也可以指動物。 如果您知道要翻譯的字詞與運動有關,不妨使用字彙表,讓 Cloud Translation API 翻譯「bat」時,採用運動相關的譯文,而非動物相關的譯文。

  • 借用字:舉例來說,法文的「bouillabaisse」翻譯成英文也是「bouillabaisse」; 英文是從法文借用「bouillabaisse」這個字。 如果英語使用者不瞭解法國文化背景,可能不知道馬賽魚湯是法國的魚類燉湯。詞彙表可以覆寫翻譯結果,因此法文的「bouillabaisse」會翻譯成英文的「fish stew」。

建立詞彙表檔案

Cloud Translation API 接受 TSV、CSV 或 TMX 字彙表檔案。本教學課程會使用上傳至 Cloud Storage 的 CSV 檔案,定義同義詞集。

如要製作詞彙表 CSV 檔案,請按照下列步驟操作:

  1. 在 CSV 檔案的第一列中,使用 ISO-639BCP-47 語言代碼指定資料欄的語言

    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 bucket,也不需要建立 Cloud Storage bucket。請改用本教學課程建立的公開術語表檔案,以免產生任何 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

在試用這個範例之前,請先按照Python使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 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

在試用這個範例之前,請先按照Node.js使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 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

在試用這個範例之前,請先按照Python使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 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

在試用這個範例之前,請先按照Node.js使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 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;
}

搭配語音合成標記語言使用 Text-to-Speech

現在您已完成圖片偵測文字的個人化翻譯,可以開始使用 Text-to-Speech API。Text-to-Speech API 可以根據翻譯後的文字建立合成音訊。

Text-to-Speech API 會從純文字字串或以語音合成標記語言 (SSML) 標記的文字字串,生成合成音訊。SSML 是一種標記語言,支援使用 SSML 標記為文字加上註解。您可以使用 SSML 標記,影響 Text-to-Speech API 格式化合成語音建立作業的方式。

以下函式會將 SSML 字串轉換為合成語音的 MP3 檔案。

Python

在試用這個範例之前,請先按照Python使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 Cloud Translation Python API 參考說明文件

如要向 Cloud Translation 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

def text_to_speech(text: str, outfile: str) -> str:
    """Converts plaintext to SSML and
    generates synthetic audio from SSML

    Args:

    text: text to synthesize
    outfile: filename to use to store synthetic audio

    Returns:
    String of synthesized audio
    """

    # Replace special characters with HTML Ampersand Character Codes
    # These Codes prevent the API from confusing text with
    # SSML commands
    # For example, '<' --> '&lt;' and '&' --> '&amp;'
    escaped_lines = html.escape(text)

    # Convert plaintext to SSML in order to wait two seconds
    #   between each line in synthetic speech
    ssml = "<speak>{}</speak>".format(
        escaped_lines.replace("\n", '\n<break time="2s"/>')
    )

    # Instantiates a client
    client = texttospeech.TextToSpeechClient()

    # Sets the text input to be synthesized
    synthesis_input = texttospeech.SynthesisInput(ssml=ssml)

    # Builds the voice request, selects the language code ("en-US") and
    # the SSML voice gender ("MALE")
    voice = texttospeech.VoiceSelectionParams(
        language_code="en-US", ssml_gender=texttospeech.SsmlVoiceGender.MALE
    )

    # Selects the type of audio file to return
    audio_config = texttospeech.AudioConfig(
        audio_encoding=texttospeech.AudioEncoding.MP3
    )

    # Performs the text-to-speech request on the text input with the selected
    # voice parameters and audio file type

    request = texttospeech.SynthesizeSpeechRequest(
        input=synthesis_input, voice=voice, audio_config=audio_config
    )

    response = client.synthesize_speech(request=request)

    # Writes the synthetic audio to the output file.
    with open(outfile, "wb") as out:
        out.write(response.audio_content)
        print("Audio content written to file " + outfile)

Node.js

在試用這個範例之前,請先按照Node.js使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 Cloud Translation Node.js API 參考說明文件

如要向 Cloud Translation 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

/**
 * Generates synthetic audio from plaintext tagged with SSML.
 *
 * Given the name of a text file and an output file name, this function
 * tags the text in the text file with SSML. This function then
 * calls the Text-to-Speech API. The API returns a synthetic audio
 * version of the text, formatted according to the SSML commands. This
 * function saves the synthetic audio to the designated output file.
 *
 * ARGS
 * text: String of plaintext
 * outFile: String name of file under which to save audio output
 * RETURNS
 * nothing
 *
 */
async function syntheticAudio(text, outFile) {
  // Replace special characters with HTML Ampersand Character Codes
  // These codes prevent the API from confusing text with SSML tags
  // For example, '<' --> '&lt;' and '&' --> '&amp;'
  let escapedLines = text.replace(/&/g, '&amp;');
  escapedLines = escapedLines.replace(/"/g, '&quot;');
  escapedLines = escapedLines.replace(/</g, '&lt;');
  escapedLines = escapedLines.replace(/>/g, '&gt;');

  // Convert plaintext to SSML
  // Tag SSML so that there is a 2 second pause between each address
  const expandedNewline = escapedLines.replace(/\n/g, '\n<break time="2s"/>');
  const ssmlText = '<speak>' + expandedNewline + '</speak>';

  // Creates a client
  const client = new textToSpeech.TextToSpeechClient();

  // Constructs the request
  const request = {
    // Select the text to synthesize
    input: {ssml: ssmlText},
    // Select the language and SSML Voice Gender (optional)
    voice: {languageCode: 'en-US', ssmlGender: 'MALE'},
    // Select the type of audio encoding
    audioConfig: {audioEncoding: 'MP3'},
  };

  // Performs the Text-to-Speech request
  const [response] = await client.synthesizeSpeech(request);
  // Write the binary audio content to a local file
  const writeFile = util.promisify(fs.writeFile);
  await writeFile(outFile, response.audioContent, 'binary');
  console.log('Audio content written to file ' + outFile);
}

全面整合使用

在先前的步驟中,您在 hybrid_glossaries.py 中定義了使用 Vision、Translation 和 Text-to-Speech 的函式。現在您已準備好使用這些函式,從下列相片產生翻譯文字的合成語音。

下列程式碼會呼叫 hybrid_glossaries.py 中定義的函式,以執行下列操作:

  • 建立 Cloud Translation API 詞彙表資源

  • 使用 Vision API 偵測上圖中的文字

  • 使用 Cloud Translation API 詞彙表翻譯偵測到的文字

  • 生成譯文的文字轉語音合成語音

Python

在試用這個範例之前,請先按照Python使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 Cloud Translation Python API 參考說明文件

如要向 Cloud Translation 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

def main() -> None:
    """This method is called when the tutorial is run in the Google Cloud
    Translation API. It creates a glossary, translates text to
    French, and speaks the translated text.

    Args:
    None

    Returns:
    None
    """
    # Photo from which to extract text
    infile = "resources/example.png"
    # Name of file that will hold synthetic speech
    outfile = "resources/example.mp3"

    # Defines the languages in the glossary
    # This list must match the languages in the glossary
    #   Here, the glossary includes French and English
    glossary_langs = ["fr", "en"]
    # Name that will be assigned to your project's glossary resource
    glossary_name = "bistro-glossary"
    # uri of .csv file uploaded to Cloud Storage
    glossary_uri = "gs://cloud-samples-data/translation/bistro_glossary.csv"

    created_glossary_name = create_glossary(
        glossary_langs, PROJECT_ID, glossary_name, glossary_uri
    )

    # photo -> detected text
    text_to_translate = pic_to_text(infile)
    # detected text -> translated text
    text_to_speak = translate_text(
        text_to_translate, "fr", "en", PROJECT_ID, created_glossary_name
    )
    # translated text -> synthetic audio
    text_to_speech(text_to_speak, outfile)

Node.js

在試用這個範例之前,請先按照Node.js使用用戶端程式庫的 Cloud Translation 快速入門導覽課程中的操作說明進行設定。詳情請參閱 Cloud Translation Node.js API 參考說明文件

如要向 Cloud Translation 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

await createGlossary(glossaryLangs, projectId, glossaryName, glossaryUri);
const text = await picToText(inFile);
const translatedText = await translateText(
  text,
  'fr',
  'en',
  projectId,
  glossaryName
);
syntheticAudio(translatedText, outFile);

執行程式碼

如要執行程式碼,請在程式碼所在的目錄中,於終端機輸入下列指令:

Python

python hybrid_tutorial.py
  

Node.js

  node hybridGlossaries.js
  

畫面會出現以下輸出結果:

Created glossary bistro-glossary.
Audio content written to file resources/example.mp3

執行程式碼後,請從 hybrid_glossaries 目錄前往 resources 目錄。檢查資源目錄是否有 example.mp3 檔案。

請聆聽下列音訊片段,確認 example.mp3 檔案的音質是否相同。


錯誤訊息疑難排解

  • 403 IAM permission 'cloudtranslate.glossaries.create' denied.

    如果服務帳戶金鑰沒有「Cloud Translation API 編輯者」權限,就會引發這項例外狀況。

  • KeyError: 'GCLOUD_PROJECT'

    如果沒有設定 GCLOUD_PROJECT 變數,就會產生這項錯誤。

  • 400 Invalid resource name project id

    如果使用的字彙表名稱包含小寫字母、數字、句號、半形冒號或連字號以外的字元,或是服務帳戶金鑰沒有「Cloud Translation API 編輯者」權限,就會引發這項例外狀況。

  • File filename was not found.

    如果將 GOOGLE_APPLICATION_CREDENTIALS 變數設為無效的檔案路徑,就會引發這項例外狀況。

  • Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application

    如果未設定 GOOGLE_APPLICATION_CREDENTIALS 變數,就會引發這項例外狀況。

  • Forbidden: 403 POST API has not been used or is disabled

    如果未啟用 API 就呼叫 Cloud Translation API、Cloud Vision API 或 Text-to-Speech API,系統就會產生這項警告。

  • AttributeError: 'module' object has no attribute 'escape'

    Python 2.7.10 以下版本與 HTML 不相容。如要修正這項錯誤,請使用 Python 虛擬環境。虛擬環境會使用最新版本的 Python。

  • UnicodeEncodeError

    Python 2.7.10 以下版本與 HTML 不相容。如要修正這項錯誤,請使用 Python 虛擬環境。虛擬環境會使用最新版本的 Python。

正在清除所用資源

使用 Google Cloud 控制台刪除不需要的專案。刪除專案可避免系統向您的 Cloud Billing 帳戶收取本教學課程所用資源的額外費用。

刪除專案

  1. 前往 Google Cloud 控制台的「專案」頁面。
  2. 在專案清單中選取您要刪除的專案,並按一下 [Delete] (刪除)
  3. 在對話方塊中輸入專案 ID,然後按一下「Shut down」(關閉) 即可刪除專案。

後續步驟

恭喜!您剛才使用 Vision OCR 偵測圖片中的文字。然後,您建立了翻譯詞彙表,並使用該詞彙表進行翻譯。接著,您使用 Text-to-Speech 產生翻譯文字的合成音訊。

如要進一步瞭解 Vision、Translation 和 Text-to-Speech,請參閱下列內容: