הפעלת רמת סמך ברמת המילה

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

רמת סמך ברמת המילה

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

{
  "results": [
    {
      "alternatives": [
        {
          "transcript": "how old is the Brooklyn Bridge",
          "confidence": 0.96748614
        }
      ]
    }
  ]
}

בנוסף לרמת הסמך של התמלול כולו, Cloud STT יכול גם לספק את רמת הסמך של מילים ספציפיות בתמלול. התגובה כוללת את הפרטים של WordInfo בתמליל, שמציינים את רמת הסבירות של מילים ספציפיות, כמו בדוגמה הבאה.

{
  "results": [
    {
      "alternatives": [
        {
          "transcript": "how old is the Brooklyn Bridge",
          "confidence": 0.98360395,
          "words": [
            {
              "startTime": "0s",
              "endTime": "0.300s",
              "word": "how",
              "confidence": SOME NUMBER
            },
            ...
          ]
        }
      ]
    }
  ]
}

הפעלת רמת סמך ברמת המילה בבקשה

בקטע הקוד הבא אפשר לראות איך להפעיל רמת מהימנות ברמת המילה בבקשת תמלול ל-Cloud Speech-to-Text באמצעות קבצים מקומיים ומרוחקים.

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

פרוטוקול

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

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

בדוגמה הבאה אפשר לראות איך לשלוח בקשת POST באמצעות curl, כשגוף הבקשה מפעיל את רמת הסמך ברמת המילה.

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": "FLAC",
        "sampleRateHertz": 16000,
        "languageCode": "en-US",
        "enableWordTimeOffsets": true,
        "enableWordConfidence": true
    },
    "audio": {
        "uri": "gs://cloud-samples-tests/speech/brooklyn.flac"
    }
}' > word-level-confidence.txt

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

{
  "results": [
    {
      "alternatives": [
        {
          "transcript": "how old is the Brooklyn Bridge",
          "confidence": 0.98360395,
          "words": [
            {
              "startTime": "0s",
              "endTime": "0.300s",
              "word": "how",
              "confidence": 0.98762906
            },
            {
              "startTime": "0.300s",
              "endTime": "0.600s",
              "word": "old",
              "confidence": 0.96929157
            },
            {
              "startTime": "0.600s",
              "endTime": "0.800s",
              "word": "is",
              "confidence": 0.98271006
            },
            {
              "startTime": "0.800s",
              "endTime": "0.900s",
              "word": "the",
              "confidence": 0.98271006
            },
            {
              "startTime": "0.900s",
              "endTime": "1.100s",
              "word": "Brooklyn",
              "confidence": 0.98762906
            },
            {
              "startTime": "1.100s",
              "endTime": "1.500s",
              "word": "Bridge",
              "confidence": 0.98762906
            }
          ]
        }
      ],
      "languageCode": "en-us"
    }
  ]
}

Java

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

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

/**
 * Transcribe a local audio file with word level confidence
 *
 * @param fileName the path to the local audio file
 */
public static void transcribeWordLevelConfidence(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();

    RecognitionConfig config = RecognitionConfig.newBuilder()
        .setEncoding(AudioEncoding.LINEAR16)
        .setSampleRateHertz(16000)
        .setLanguageCode("en-US")
        .setEnableWordConfidence(true)
        .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", alternative.getTranscript());
      System.out.format(
          "First Word and Confidence : %s %s \n",
          alternative.getWords(0).getWord(), alternative.getWords(0).getConfidence());
    }
  }
}

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: 'FLAC',
  sampleRateHertz: 16000,
  languageCode: 'en-US',
  enableWordConfidence: true,
};

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');
const confidence = response.results
  .map(result => result.alternatives[0].confidence)
  .join('\n');
console.log(`Transcription: ${transcription} \n Confidence: ${confidence}`);

console.log('Word-Level-Confidence:');
const words = response.results.map(result => result.alternatives[0]);
words[0].words.forEach(a => {
  console.log(` word: ${a.word}, confidence: ${a.confidence}`);
});

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/Google_Gnome.wav"

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=16000,
    language_code="en-US",
    enable_word_confidence=True,
)

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}")
    print(
        "First Word and Confidence: ({}, {})".format(
            alternative.words[0].word, alternative.words[0].confidence
        )
    )

return response.results

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

Java

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

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

/**
 * Transcribe a remote audio file with word level confidence
 *
 * @param gcsUri path to the remote audio file
 */
public static void transcribeWordLevelConfidenceGcs(String gcsUri) throws Exception {
  try (SpeechClient speechClient = SpeechClient.create()) {

    RecognitionConfig config = RecognitionConfig.newBuilder()
        .setEncoding(AudioEncoding.FLAC)
        .setSampleRateHertz(16000)
        .setLanguageCode("en-US")
        .setEnableWordConfidence(true)
        .build();

    // Set the remote path for the audio file
    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);
    }

    SpeechRecognitionResult result = response.get().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());
    System.out.format(
        "First Word and Confidence : %s %s \n",
        alternative.getWords(0).getWord(), alternative.getWords(0).getConfidence());
  }
}

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: 'FLAC',
  sampleRateHertz: 16000,
  languageCode: 'en-US',
  enableWordConfidence: true,
};

const audio = {
  uri: gcsUri,
};

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

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

console.log('Word-Level-Confidence:');
const words = response.results.map(result => result.alternatives[0]);
words[0].words.forEach(a => {
  console.log(` word: ${a.word}, confidence: ${a.confidence}`);
});

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_word_level_confidence(audio_uri: str) -> str:
    """Transcribe a remote audio file with word level confidence.
    Args:
        audio_uri (str): The Cloud Storage URI of the input audio.
            E.g., gs://[BUCKET]/[FILE]
    Returns:
        The generated transcript from the audio file provided with word level confidence.
    """

    client = speech.SpeechClient()

    # Configure request to enable word level confidence
    config = speech.RecognitionConfig(
        encoding=speech.RecognitionConfig.AudioEncoding.FLAC,
        sample_rate_hertz=44100,
        language_code="en-US",
        enable_word_confidence=True,  # Enable word level confidence
    )

    # 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=config, audio=audio).result(
        timeout=300
    )

    transcript_builder = []
    for i, result in enumerate(response.results):
        alternative = result.alternatives[0]
        transcript_builder.append("-" * 20)
        transcript_builder.append(f"\nFirst alternative of result {i}")
        transcript_builder.append(f"\nTranscript: {alternative.transcript}")
        transcript_builder.append(
            "\nFirst Word and Confidence: ({}, {})".format(
                alternative.words[0].word, alternative.words[0].confidence
            )
        )

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

    return transcript