תרגום טקסט מתוך תמונה

בדף הזה מוסבר איך לזהות טקסט בתמונה, איך להתאים אישית תרגומים ואיך ליצור דיבור סינתטי מטקסט. במדריך הזה נשתמש ב-Cloud Vision כדי לזהות טקסט בקובץ תמונה. לאחר מכן, נראה איך משתמשים ב-Cloud Translation כדי לספק תרגום בהתאמה אישית של הטקסט שזוהה. בסוף המדריך הזה נשתמש בהמרת טקסט לדיבור (TTS) כדי לספק הכתבה ממוחשבת של הטקסט המתורגם.

מטרות

  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 ושל המרת טקסט לדיבור.

לפני שמתחילים

ודאו ש:

הגדרת ספריות לקוח

במדריך הזה משתמשים בספריות הלקוח של Vision, ‏Translation ו-Text-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. נכנסים לדף Service Accounts במסוף Google Cloud .

      כניסה לדף Service Accounts

    2. בוחרים את הפרויקט הרצוי.

    3. לוחצים על Create Service Account.

    4. כותבים שם בשדה Service account name. השדה Service account ID ימולא במסוףGoogle Cloud בהתאם לשם הזה.

    5. אופציונלי: בשדה Service account description, מזינים תיאור לחשבון השירות.

    6. לוחצים על Create and continue.

    7. לוחצים על השדה Select a role ובוחרים באפשרות Cloud Translation > Cloud Translation API Editor.

    8. לוחצים על Done כדי לסיים ליצור את חשבון השירות.

      חשוב לא לסגור את החלון של הדפדפן, כי תשתמשו בו גם בשלב הבא.

  2. מורידים מפתח JSON לחשבון השירות שיצרתם:

    1. במסוף Google Cloud , לוחצים על כתובת האימייל של חשבון השירות שיצרתם.
    2. לוחצים על Keys.
    3. לוחצים על Add key ואז על Create new key.
    4. לוחצים על יצירה. למחשב שלכם תתבצע הורדה של קובץ JSON עם המפתח.

      חשוב לאחסן את קובץ המפתח באופן מאובטח כי הוא יכול לשמש לצורך אימות כחשבון השירות שלכם. אפשר להעביר את הקובץ לאן שרוצים ולשנות את השם שלו למה שרוצים.

    5. לוחצים על Close.

  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, אתם צריכים להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

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, אתם צריכים להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

// 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');

הגדרת מזהה הפרויקט

צריך לשייך פרויקט ב-Google Cloud לכל בקשה ל-API של Google Cloud . מגדירים את הפרויקט ב-Google Cloud באמצעות הגדרת משתנה הסביבה GCLOUD_PROJECT מהטרמינל.

בפקודה הבאה, מחליפים את project-id במזהה הפרויקט ב- Google Cloud . מריצים את הפקודה הבאה מהטרמינל.

Linux או macOS

export GCLOUD_PROJECT=project-id

Windows

set GCLOUD_PROJECT=project-id

שימוש ב-Vision כדי לזהות טקסט מתמונה

משתמשים ב-Vision API כדי לזהות ולחלץ טקסט מתמונה. ‫Vision API משתמש בזיהוי תווים אופטי (OCR) כדי לתמוך בשתי תכונות של זיהוי טקסט: זיהוי טקסט צפוף (DOCUMENT_TEXT_DETECTION) וזיהוי טקסט דליל (TEXT_DETECTION).

הקוד הבא מראה איך להשתמש בתכונה DOCUMENT_TEXT_DETECTION של Vision API כדי לזהות טקסט בתמונה עם טקסט צפוף.

Python

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Python במדריך למתחילים של Cloud Translation באמצעות ספריות לקוח. למידע נוסף, קראו את מאמרי העזרה של Cloud Translation Python API.

כדי לבצע אימות ב-Cloud Translation, אתם צריכים להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

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, אתם צריכים להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

/**
 * 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".

  • מילים דו-משמעיות: למשל, המילה "עטלף" יכולה להתייחס לבעל חיים או למטוס קרב. אם אתם יודעים שאתם מתרגמים מילים שקשורות לספורט, אתם יכולים להשתמש במילון מונחים כדי להזין ל-Cloud Translation API את התרגום של המילה "bat" שקשור לספורט (מחבט), ולא את התרגום שקשור לבעלי חיים (עטלף).

  • מילים שאולות: לדוגמה, המילה "bouillabaisse" בצרפתית מתורגמת ל-"bouillabaisse" באנגלית. השפה האנגלית שאלה את המילה "bouillabaisse" מהשפה הצרפתית. דובר אנגלית שלא מכיר את ההקשר התרבותי הצרפתי לא בהכרח יודע ש-bouillabaisse הוא נזיד דגים צרפתי. מילוני מונחים יכולים לשנות תרגום, כך שהמילה bouillabaisse בצרפתית תתורגם ל-fish stew באנגלית.

יצירת קובץ מילון מונחים

‫Cloud Translation API מקבל קובצי מילון מונחים בפורמט TSV,‏ CSV או TMX. במדריך הזה משתמשים בקובץ CSV שהועלה ל-Cloud Storage כדי להגדיר קבוצות של מונחים מקבילים.

כדי ליצור קובץ CSV של מילון מונחים:

  1. מגדירים את השפה של העמודה באמצעות קודי השפה ISO-639 או BCP-47 בשורה הראשונה של קובץ ה-CSV.

    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 תלוי אותיות רישיות (case-sensitive) ותלוי תווים מיוחדים, כמו מילים עם סימני הטעמה. כדי לוודא שמילון המונחים מטפל בווריאציות של מילה, צריך להגדיר במפורש את האיותים השונים של המילה.

    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. כדי ליצור משאב של מילון מונחים, שולחים את ה-URI של קובץ מילון המונחים ב-Cloud Storage אל Cloud Translation API. מזהה ה-URI של קובץ מילון המונחים שזמין באופן ציבורי למדריך הזה הוא gs://cloud-samples-data/translation/bistro_glossary.csv. כדי להוריד את מילון המונחים, לוחצים על הקישור שלמעלה, אבל לא פותחים אותו בכרטיסייה חדשה.

יצירת משאב של מילון מונחים

כדי להשתמש במילון מונחים, צריך ליצור משאב של מילון מונחים באמצעות Cloud Translation API. כדי ליצור משאב של מילון מונחים, שולחים את ה-URI של קובץ מילון המונחים ב-Cloud Storage אל Cloud Translation API.

חשוב לוודא שאתם משתמשים במפתח של חשבון שירות עם הרשאות Cloud Translation API Editor, ושהגדרתם את מזהה הפרויקט מהטרמינל.

הפונקציה הבאה יוצרת משאב מילון מונחים. באמצעות משאב מילון המונחים הזה, תוכלו להתאים אישית את בקשת התרגום בשלב הבא של המדריך הזה.

Python

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Python במדריך למתחילים של Cloud Translation באמצעות ספריות לקוח. למידע נוסף, קראו את מאמרי העזרה של Cloud Translation Python API.

כדי לבצע אימות ב-Cloud Translation, אתם צריכים להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

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, אתם צריכים להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

/** 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, אתם צריכים להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

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, אתם צריכים להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

/**
 * 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;
}

שימוש בהמרת טקסט לדיבור (TTS) עם שפת סימון לסינתזת דיבור (SSML)

עכשיו, אחרי שהתאמתם אישית את התרגום של הטקסט שזוהה בתמונה, אתם יכולים להשתמש ב-Text-to-Speech API. בעזרת Text-to-Speech API אפשר ליצור אודיו סינתטי של הטקסט המתורגם.

‫Text-to-Speech API יוצר אודיו סינתטי ממחרוזת של טקסט פשוט או ממחרוזת של טקסט שמסומן באמצעות Speech Synthesis Markup Language ‏(SSML). ‫SSML היא שפת Markup שמאפשרת להוסיף הערות לטקסט באמצעות תגי SSML. אתם יכולים להשתמש בתגי SSML כדי להשפיע על האופן שבו Text-to-Speech API מעצב את יצירת הדיבור המסונתז.

הפונקציה הבאה ממירה מחרוזת של SSML לקובץ MP3 של דיבור סינתטי.

Python

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Python במדריך למתחילים של Cloud Translation באמצעות ספריות לקוח. למידע נוסף, קראו את מאמרי העזרה של Cloud Translation Python API.

כדי לבצע אימות ב-Cloud Translation, אתם צריכים להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

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, אתם צריכים להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

/**
 * 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

  • ליצור דיבור סינתטי של הטקסט המתורגם באמצעות המרת טקסט לדיבור (TTS)

Python

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Python במדריך למתחילים של Cloud Translation באמצעות ספריות לקוח. למידע נוסף, קראו את מאמרי העזרה של Cloud Translation Python API.

כדי לבצע אימות ב-Cloud Translation, אתם צריכים להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

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, אתם צריכים להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

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

אחרי שמריצים את הקוד, עוברים לספרייה resources מהספרייה hybrid_glossaries. בודקים אם יש קובץ example.mp3 בספריית המשאבים.

כדאי להאזין לקטע האודיו הבא כדי לוודא שקובץ ה-example.mp3 נשמע אותו דבר.


פתרון בעיות שקשורות להודעות שגיאה

סידור וארגון

אם אתם לא צריכים את הפרויקט, אתם יכולים למחוק אותו באמצעות מסוףGoogle Cloud . מחיקת הפרויקט מונעת חיובים נוספים בחשבון לחיוב ב-Cloud על המשאבים שבהם השתמשתם במדריך הזה.

מחיקת הפרויקט

  1. במסוףGoogle Cloud , נכנסים לדף Projects.
  2. ברשימת הפרויקטים, בוחרים את הפרויקט שרוצים למחוק ולוחצים על Delete.
  3. כדי למחוק את הפרויקט, כותבים את מזהה הפרויקט בתיבת הדו-שיח ולוחצים על Shut down.

המאמרים הבאים

כל הכבוד! עכשיו השתמשתם ב-Vision OCR כדי לזהות טקסט בתמונה. אחר כך יצרתם מילון מונחים לתרגום וביצעתם תרגום באמצעות מילון המונחים הזה. לאחר מכן, השתמשתם בהמרת טקסט לדיבור (TTS) כדי ליצור אודיו סינתטי של הטקסט המתורגם.

כדי להרחיב את הידע שלכם על Vision,‏ Translation ו-Text-to-Speech: