הפעלת זיהוי שפה ב-Cloud Speech-to-Text

בדף הזה מוסבר איך להפעיל זיהוי שפה לבקשות תמלול אודיו שנשלחות אל Cloud Speech-to-Text.

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

זיהוי של כמה שפות

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

התכונה הזו מתאימה לאפליקציות שצריכות לתמלל משפטים קצרים, כמו פקודות קוליות או חיפוש. אתם יכולים לציין עד שלוש שפות חלופיות מבין השפות שנתמכות ב-Cloud Speech-to-Text, בנוסף לשפה הראשית (סה"כ ארבע שפות).

אפשר לציין שפות חלופיות לבקשת תמלול הדיבור, אבל עדיין צריך לספק קוד שפה ראשי בשדה languageCode. בנוסף, כדאי להגביל את מספר השפות שאתם מבקשים למינימום ההכרחי. ככל שתבקשו פחות קודי שפה חלופיים, כך Cloud Speech-to-Text יוכל לבחור את הקוד הנכון בצורה מוצלחת יותר. כדי לקבל את התוצאות הכי טובות, מומלץ לציין רק שפה אחת.

הפעלת זיהוי שפה בבקשות לתמלול אודיו

כדי לציין שפות חלופיות בתמלול האודיו, צריך להגדיר את השדה alternativeLanguageCodes לרשימה של קודי שפה בפרמטרים של RecognitionConfig לבקשה. ‫Cloud STT תומך בקודי שפה חלופיים לכל השיטות של זיהוי דיבור: speech:recognize, speech:longrunningrecognize ו-Streaming.

שימוש בקובץ מקומי

פרוטוקול

פרטים מלאים זמינים בנקודת הקצה ל-API של speech:recognize.

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

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

curl -s -H "Content-Type: application/json" \
    -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
    https://speech.googleapis.com/v1p1beta1/speech:recognize \
    --data '{
    "config": {
        "encoding": "LINEAR16",
        "languageCode": "en-US",
        "alternativeLanguageCodes": ["fr-FR", "de-DE"],
        "model": "command_and_search"
    },
    "audio": {
        "uri": "gs://cloud-samples-tests/speech/commercial_mono.wav"
    }
}' > multi-language.txt

אם הבקשה תתבצע בהצלחה, השרת יחזיר את קוד הסטטוס 200 OK של HTTP ואת התגובה בפורמט JSON, שתישמר בקובץ בשם multi-language.txt.

{
  "results": [
    {
      "alternatives": [
        {
          "transcript": "hi I'd like to buy a Chromecast I'm ..."
          "confidence": 0.9466864
        }
      ],
      "languageCode": "en-us"
    },
    {
      "alternatives": [
        {
          "transcript": " let's go with the black one",
          "confidence": 0.9829583
        }
      ],
      "languageCode": "en-us"
    },
  ]
}

Java

במאמר ספריות הלקוח של Cloud STT מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Cloud STT. למידע נוסף, קראו את מאמרי העזרה של Cloud STT Java API.

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

/**
 * Transcribe a local audio file with multi-language recognition
 *
 * @param fileName the path to the audio file
 */
public static void transcribeMultiLanguage(String fileName) throws Exception {
  Path path = Paths.get(fileName);
  byte[] content = Files.readAllBytes(path);

  try (SpeechClient speechClient = SpeechClient.create()) {

    RecognitionAudio recognitionAudio = RecognitionAudio.newBuilder()
        .setContent(ByteString.copyFrom(content))
        .build();
    ArrayList<String> languageList = new ArrayList<>();
    languageList.add("es-ES");
    languageList.add("en-US");

    RecognitionConfig config = RecognitionConfig.newBuilder()
        .setEncoding(AudioEncoding.LINEAR16)
        .setSampleRateHertz(16000)
        .setLanguageCode("ja-JP")
        .addAllAlternativeLanguageCodes(languageList)
        .build();
    RecognizeResponse recognizeResponse = speechClient.recognize(config, recognitionAudio);

    for (SpeechRecognitionResult result : recognizeResponse.getResultsList()) {
      // There can be several alternative transcripts for a given chunk of speech.
      // Just use the first (most likely) one here.
      SpeechRecognitionAlternative alternative = result.getAlternatives(0);
      System.out.format("Transcript : %s\n\n", alternative.getTranscript());
    }
  }
}

Node.js

במאמר ספריות הלקוח של Cloud STT מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Cloud STT. למידע נוסף, קראו את מאמרי העזרה של Cloud STT Node.js API.

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

const fs = require('fs');

// Imports the Google Cloud client library
const speech = require('@google-cloud/speech').v1p1beta1;

// Creates a client
const client = new speech.SpeechClient();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const fileName = 'Local path to audio file, e.g. /path/to/audio.raw';

const config = {
  encoding: 'LINEAR16',
  sampleRateHertz: 44100,
  languageCode: 'en-US',
  alternativeLanguageCodes: ['es-ES', 'en-US'],
};

const audio = {
  content: fs.readFileSync(fileName).toString('base64'),
};

const request = {
  config: config,
  audio: audio,
};

const [response] = await client.recognize(request);
const transcription = response.results
  .map(result => result.alternatives[0].transcript)
  .join('\n');
console.log(`Transcription: ${transcription}`);

Python

במאמר ספריות הלקוח של Cloud STT מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Cloud STT. למידע נוסף, קראו את מאמרי העזרה של Cloud STT Python API.

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

from google.cloud import speech_v1p1beta1 as speech

client = speech.SpeechClient()

speech_file = "resources/multi.wav"
first_lang = "en-US"
second_lang = "es"

with open(speech_file, "rb") as audio_file:
    content = audio_file.read()

audio = speech.RecognitionAudio(content=content)

config = speech.RecognitionConfig(
    encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
    sample_rate_hertz=44100,
    audio_channel_count=2,
    language_code=first_lang,
    alternative_language_codes=[second_lang],
)

print("Waiting for operation to complete...")
response = client.recognize(config=config, audio=audio)

for i, result in enumerate(response.results):
    alternative = result.alternatives[0]
    print("-" * 20)
    print(f"First alternative of result {i}: {alternative}")
    print(f"Transcript: {alternative.transcript}")

return response.results

שימוש בקובץ מרוחק

Java

במאמר ספריות הלקוח של Cloud STT מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Cloud STT. למידע נוסף, קראו את מאמרי העזרה של Cloud STT Java API.

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

/**
 * Transcribe a remote audio file with multi-language recognition
 *
 * @param gcsUri the path to the remote audio file
 */
public static void transcribeMultiLanguageGcs(String gcsUri) throws Exception {
  try (SpeechClient speechClient = SpeechClient.create()) {

    ArrayList<String> languageList = new ArrayList<>();
    languageList.add("es-ES");
    languageList.add("en-US");

    RecognitionConfig config = RecognitionConfig.newBuilder()
        .setEncoding(AudioEncoding.LINEAR16)
        .setSampleRateHertz(16000)
        .setLanguageCode("ja-JP")
        .addAllAlternativeLanguageCodes(languageList)
        .build();

    RecognitionAudio audio = RecognitionAudio.newBuilder()
        .setUri(gcsUri)
        .build();

    // Use non-blocking call for getting file transcription
    OperationFuture<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response =
        speechClient.longRunningRecognizeAsync(config, audio);

    while (!response.isDone()) {
      System.out.println("Waiting for response...");
      Thread.sleep(10000);
    }

    for (SpeechRecognitionResult result : response.get().getResultsList()) {

      // There can be several alternative transcripts for a given chunk of speech.
      // Just use the first (most likely) one here.
      SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);

      System.out.printf("Transcript : %s\n\n", alternative.getTranscript());
    }
  }
}

Node.js

במאמר ספריות הלקוח של Cloud STT מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Cloud STT. למידע נוסף, קראו את מאמרי העזרה של Cloud STT Node.js API.

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

// Imports the Google Cloud client library
const speech = require('@google-cloud/speech').v1p1beta1;

// Creates a client
const client = new speech.SpeechClient();

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const uri = path to GCS audio file e.g. `gs:/bucket/audio.wav`;

const config = {
  encoding: 'LINEAR16',
  sampleRateHertz: 44100,
  languageCode: 'en-US',
  alternativeLanguageCodes: ['es-ES', 'en-US'],
};

const audio = {
  uri: gcsUri,
};

const request = {
  config: config,
  audio: audio,
};

const [operation] = await client.longRunningRecognize(request);
const [response] = await operation.promise();
const transcription = response.results
  .map(result => result.alternatives[0].transcript)
  .join('\n');
console.log(`Transcription: ${transcription}`);

Python

במאמר ספריות הלקוח של Cloud STT מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Cloud STT. למידע נוסף, קראו את מאמרי העזרה של Cloud STT Python API.

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


from google.cloud import speech_v1p1beta1 as speech


def transcribe_file_with_multilanguage_gcs(audio_uri: str) -> str:
    """Transcribe a remote audio file with multi-language recognition
    Args:
        audio_uri (str): The Google Cloud Storage path to an audio file.
            E.g., gs://[BUCKET]/[FILE]
    Returns:
        str: The generated transcript from the audio file provided.
    """

    client = speech.SpeechClient()

    first_language = "es-ES"
    alternate_languages = ["en-US", "fr-FR"]

    # Configure request to enable multiple languages
    recognition_config = speech.RecognitionConfig(
        encoding=speech.RecognitionConfig.AudioEncoding.FLAC,
        sample_rate_hertz=44100,
        language_code=first_language,
        alternative_language_codes=alternate_languages,
    )

    # Set the remote path for the audio file
    audio = speech.RecognitionAudio(uri=audio_uri)

    # Use non-blocking call for getting file transcription
    response = client.long_running_recognize(
        config=recognition_config, audio=audio
    ).result(timeout=300)

    transcript_builder = []
    for i, result in enumerate(response.results):
        alternative = result.alternatives[0]
        transcript_builder.append("-" * 20 + "\n")
        transcript_builder.append(f"First alternative of result {i}: {alternative}")
        transcript_builder.append(f"Transcript: {alternative.transcript} \n")

    transcript = "".join(transcript_builder)
    print(transcript)

    return transcript