בחירת מודל תמלול

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

מודלים של תמלול

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

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

לדוגמה, ל-Cloud STT יש מודל תמלול שאומן לזיהוי דיבור שהוקלט בטלפון. כש-Cloud STT משתמש במודל telephony או telephony_short כדי לתמלל אודיו מטלפון, הוא מפיק תוצאות תמלול מדויקות יותר מאשר אם הוא היה מתמלל אודיו מטלפון באמצעות המודלים latest_short או latest_long.

בטבלה הבאה מפורטים מודלים של תמלול שאפשר להשתמש בהם עם Cloud STT.

שם הדגם תיאור
latest_long אפשר להשתמש במודל הזה לכל סוג של תוכן ארוך, כמו מדיה או דיבור ושיחות ספונטניים. כדאי להשתמש במודל הזה במקום במודל ליצירת סרטונים, במיוחד אם המודל ליצירת סרטונים לא זמין בשפת היעד שלכם. אפשר גם להשתמש בו במקום במודל ברירת המחדל.
latest_short מומלץ להשתמש במודל הזה לביטויים קצרים שאורכם כמה שניות. הוא שימושי לניסיון ללכוד פקודות או תרחישי שימוש אחרים של דיבור מכוון חד-פעמי. כדאי להשתמש במודל הזה במקום במודל של פקודה וחיפוש.
telephony גרסה משופרת של המודל phone_call, הכי מתאים לאודיו שמקורו בשיחת טלפון, בדרך כלל מוקלט בתדירות דגימה של 8kHz.
telephony_short גרסה ייעודית של מודל ה "טלפוניה" המודרני לביטויים קצרים או אפילו מילה אחת באודיו שמקורו בשיחה טלפונית, בדרך כלל מוקלט בקצב דגימה של 8kHz.
medical_dictation אפשר להשתמש במודל הזה כדי לתמלל הערות שהוכתבו על ידי איש מקצוע רפואי.

זהו מודל פרימיום שעולה יותר מהתעריף הרגיל. פרטים נוספים מופיעים בדף התמחור.

medical_conversation תשתמש במודל הזה כדי לתמלל שיחה בין איש מקצוע רפואי לבין מטופל.

זהו מודל פרימיום שעולה יותר מהתעריף הרגיל. פרטים נוספים מופיעים בדף התמחור.

המודלים הבאים מבוססים בעיקר על ארכיטקטורות קלאסיות של Non-Conformer, והם נשמרים בעיקר מסיבות של תאימות לאחור.
command_and_search הכי מתאים להגייה קצרה או להגייה של מילה אחת, כמו פקודות קוליות או חיפוש קולי.
default הכי מתאים לאודיו שלא מתאים למודלים אחרים של אודיו, כמו אודיו ארוך או הכתבה. המודל שמוגדר כברירת מחדל יפיק תוצאות תמלול לכל סוג של אודיו, כולל אודיו כמו קליפים של סרטונים שיש להם מודל נפרד שמותאם במיוחד בשבילם. עם זאת, זיהוי אודיו של קטע וידאו באמצעות מודל ברירת המחדל צפוי להניב תוצאות באיכות נמוכה יותר מאשר שימוש במודל הווידאו. מומלץ שהאודיו יהיה באיכות גבוהה, ויוקלט בתדירות דגימה של 16kHz או יותר.
phone_call הכי מתאים לאודיו שמקורו בשיחה טלפונית (בדרך כלל מוקלט בתדירות דגימה של 8kHz).
video

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

בחירת מודל לתמלול אודיו

כדי לציין מודל ספציפי לשימוש בתמלול אודיו, צריך להגדיר את השדה model לאחד מהערכים המותרים – כמו latest_long,‏ latest_short,‏ telephony או telephony_short – בפרמטרים RecognitionConfig של הבקשה. ‫Cloud STT תומך בבחירת מודל לכל שיטות זיהוי הדיבור: speech:recognize,‏ speech:longrunningrecognize ושידור.

תמלול של קובץ אודיו מקומי

פרוטוקול

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

כדי לבצע זיהוי דיבור סינכרוני, שולחים בקשת 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/v2/speech:recognize \
    --data '{
    "config": {
        "encoding": "LINEAR16",
        "sampleRateHertz": 16000,
        "languageCode": "en-US",
        "model": "video"
    },
    "audio": {
        "uri": "gs://cloud-samples-tests/speech/Google_Gnome.wav"
    }
}'

למידע נוסף על הגדרת גוף הבקשה, אפשר לעיין במסמכי התיעוד של RecognitionConfig.

אם הבקשה מצליחה, השרת מחזיר קוד סטטוס 200 OK של HTTP ואת התשובה בפורמט JSON:

{
  "results": [
    {
      "alternatives": [
        {
          "transcript": "OK Google stream stranger things from
            Netflix to my TV okay stranger things from
            Netflix playing on TV from the people that brought you
            Google home comes the next evolution of the smart home
            and it's just outside your window me Google know hi
            how can I help okay no what's the weather like outside
            the weather outside is sunny and 76 degrees he's right
            okay no turn on the hose I'm holding sure okay no I'm can
            I eat this lemon tree leaf yes what about this Daisy yes
            but I wouldn't recommend it but I could eat it okay
            Nomad milk to my shopping list I'm sorry that sounds like
            an indoor request I keep doing that sorry you do keep
            doing that okay no is this compost really we're all
            compost if you think about it pretty much everything is
            made up of organic matter and will return",
          "confidence": 0.9251011
        }
      ]
    }
  ]
}

Go

מידע על התקנת ספריית הלקוח של Cloud STT ושימוש בה מופיע במאמר ספריות הלקוח של Cloud STT. מידע נוסף מופיע במאמרי העזרה של Cloud STT Go API.

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


func modelSelection(w io.Writer) error {
	ctx := context.Background()

	client, err := speech.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	data, err := os.ReadFile("../testdata/Google_Gnome.wav")
	if err != nil {
		return fmt.Errorf("ReadFile: %w", err)
	}

	req := &speechpb.RecognizeRequest{
		Config: &speechpb.RecognitionConfig{
			Encoding:        speechpb.RecognitionConfig_LINEAR16,
			SampleRateHertz: 16000,
			LanguageCode:    "en-US",
			Model:           "video",
		},
		Audio: &speechpb.RecognitionAudio{
			AudioSource: &speechpb.RecognitionAudio_Content{Content: data},
		},
	}

	resp, err := client.Recognize(ctx, req)
	if err != nil {
		return fmt.Errorf("recognize: %w", err)
	}

	for i, result := range resp.Results {
		fmt.Fprintf(w, "%s\n", strings.Repeat("-", 20))
		fmt.Fprintf(w, "Result %d\n", i+1)
		for j, alternative := range result.Alternatives {
			fmt.Fprintf(w, "Alternative %d: %s\n", j+1, alternative.Transcript)
		}
	}
	return nil
}

Java

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

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

/**
 * Performs transcription of the given audio file synchronously with the selected model.
 *
 * @param fileName the path to a audio file to transcribe
 */
public static void transcribeModelSelection(String fileName) throws Exception {
  Path path = Paths.get(fileName);
  byte[] content = Files.readAllBytes(path);

  try (SpeechClient speech = SpeechClient.create()) {
    // Configure request with video media type
    RecognitionConfig recConfig =
        RecognitionConfig.newBuilder()
            // encoding may either be omitted or must match the value in the file header
            .setEncoding(AudioEncoding.LINEAR16)
            .setLanguageCode("en-US")
            // sample rate hertz may be either be omitted or must match the value in the file
            // header
            .setSampleRateHertz(16000)
            .setModel("video")
            .build();

    RecognitionAudio recognitionAudio =
        RecognitionAudio.newBuilder().setContent(ByteString.copyFrom(content)).build();

    RecognizeResponse recognizeResponse = speech.recognize(recConfig, recognitionAudio);
    // Just print the first result here.
    SpeechRecognitionResult result = recognizeResponse.getResultsList().get(0);
    // 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", alternative.getTranscript());
  }
}

Node.js

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

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

// Imports the Google Cloud client library for Beta API
/**
 * TODO(developer): Update client library import to use new
 * version of API when desired features become available
 */
const speech = require('@google-cloud/speech').v1p1beta1;
const fs = require('fs');

// 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 model = 'Model to use, e.g. phone_call, video, default';
// const encoding = 'Encoding of the audio file, e.g. LINEAR16';
// const sampleRateHertz = 16000;
// const languageCode = 'BCP-47 language code, e.g. en-US';

const config = {
  encoding: encoding,
  sampleRateHertz: sampleRateHertz,
  languageCode: languageCode,
  model: model,
};
const audio = {
  content: fs.readFileSync(filename).toString('base64'),
};

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

// Detects speech in the audio file
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

# Instantiates a client
client = speech.SpeechClient()
# Reads a file as bytes
with open("resources/Google_Gnome.wav", "rb") as f:
    audio_content = f.read()

audio = speech.RecognitionAudio(content=audio_content)

config = speech.RecognitionConfig(
    encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
    sample_rate_hertz=16000,
    language_code="en-US",
    model="video",  # Chosen model
)

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}")
    print(f"Transcript: {alternative.transcript}")

שפות נוספות

‫C#‎: צריך לפעול לפי ההוראות להגדרה של C# ‎ בדף של ספריות הלקוח ואז לעבור אל מאמרי העזרה של Cloud STT ל-‎ .NET.

‫PHP: צריך לפעול לפי הוראות ההגדרה של PHP בדף של ספריות הלקוח ואז לעבור אל מסמכי העיון של Cloud STT ל-PHP.

‫Ruby: פועלים לפי הוראות ההגדרה של Ruby בדף של ספריות הלקוח, ואז עוברים אל מאמרי העזרה של Cloud STT ל-Ruby.

ביצוע תמלול של קובץ אודיו ב-Cloud Storage

Go

מידע על התקנת ספריית הלקוח של Cloud STT ושימוש בה מופיע במאמר ספריות הלקוח של Cloud STT. מידע נוסף מופיע במאמרי העזרה של Cloud STT Go API.

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


import (
	"context"
	"fmt"
	"io"
	"strings"

	speech "cloud.google.com/go/speech/apiv1"
	"cloud.google.com/go/speech/apiv1/speechpb"
)

// transcribe_model_selection_gcs Transcribes the given audio file asynchronously with
// the selected model.
func transcribe_model_selection_gcs(w io.Writer) error {
	ctx := context.Background()

	client, err := speech.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	audio := &speechpb.RecognitionAudio{
		AudioSource: &speechpb.RecognitionAudio_Uri{Uri: "gs://cloud-samples-tests/speech/Google_Gnome.wav"},
	}

	// The speech recognition model to use
	// See, https://cloud.google.com/speech-to-text/docs/speech-to-text-requests#select-model
	recognitionConfig := &speechpb.RecognitionConfig{
		Encoding:        speechpb.RecognitionConfig_LINEAR16,
		SampleRateHertz: 16000,
		LanguageCode:    "en-US",
		Model:           "video",
	}

	longRunningRecognizeRequest := &speechpb.LongRunningRecognizeRequest{
		Config: recognitionConfig,
		Audio:  audio,
	}

	operation, err := client.LongRunningRecognize(ctx, longRunningRecognizeRequest)
	if err != nil {
		return fmt.Errorf("error running recognize %w", err)
	}

	response, err := operation.Wait(ctx)
	if err != nil {
		return err
	}
	for i, result := range response.Results {
		alternative := result.Alternatives[0]
		fmt.Fprintf(w, "%s\n", strings.Repeat("-", 20))
		fmt.Fprintf(w, "First alternative of result %d", i)
		fmt.Fprintf(w, "Transcript: %s", alternative.Transcript)
	}
	return nil
}

Java

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

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

/**
 * Performs transcription of the remote audio file asynchronously with the selected model.
 *
 * @param gcsUri the path to the remote audio file to transcribe.
 */
public static void transcribeModelSelectionGcs(String gcsUri) throws Exception {
  try (SpeechClient speech = SpeechClient.create()) {

    // Configure request with video media type
    RecognitionConfig config =
        RecognitionConfig.newBuilder()
            // encoding may either be omitted or must match the value in the file header
            .setEncoding(AudioEncoding.LINEAR16)
            .setLanguageCode("en-US")
            // sample rate hertz may be either be omitted or must match the value in the file
            // header
            .setSampleRateHertz(16000)
            .setModel("video")
            .build();

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

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

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

    List<SpeechRecognitionResult> results = response.get().getResultsList();

    // Just print the first result here.
    SpeechRecognitionResult result = results.get(0);
    // 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", alternative.getTranscript());
  }
}

Node.js

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

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

// Imports the Google Cloud client library for Beta API
/**
 * TODO(developer): Update client library import to use new
 * version of API when desired features become available
 */
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 gcsUri = 'gs://my-bucket/audio.raw';
// const model = 'Model to use, e.g. phone_call, video, default';
// const encoding = 'Encoding of the audio file, e.g. LINEAR16';
// const sampleRateHertz = 16000;
// const languageCode = 'BCP-47 language code, e.g. en-US';

const config = {
  encoding: encoding,
  sampleRateHertz: sampleRateHertz,
  languageCode: languageCode,
  model: model,
};
const audio = {
  uri: gcsUri,
};

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

// Detects speech in the audio file.
const [response] = await client.recognize(request);
const transcription = response.results
  .map(result => result.alternatives[0].transcript)
  .join('\n');
console.log('Transcription: ', transcription);

שפות נוספות

‫C#‎: צריך לפעול לפי ההוראות להגדרה של C# ‎ בדף של ספריות הלקוח ואז לעבור אל מאמרי העזרה של Cloud STT ל-‎ .NET.

‫PHP: צריך לפעול לפי הוראות ההגדרה של PHP בדף של ספריות הלקוח ואז לעבור אל מסמכי העיון של Cloud STT ל-PHP.

‫Ruby: פועלים לפי הוראות ההגדרה של Ruby בדף של ספריות הלקוח, ואז עוברים אל מאמרי העזרה של Cloud STT ל-Ruby.