הוספת פיסוק אוטומטי

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

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

כדי להפעיל פיסוק אוטומטי, מגדירים את השדה enableAutomaticPunctuation לערך true בפרמטרים של RecognitionConfig בבקשה. ‫Cloud Speech-to-Text API תומך בפיסוק אוטומטי לכל שיטות זיהוי הדיבור: ‫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 print-access-token) \
    https://speech.googleapis.com/v1/speech:recognize \
    --data '{
  "config": {
    "encoding":"FLAC",
    "sampleRateHertz": 16000,
    "languageCode": "en-US",
    "enableAutomaticPunctuation": true
  },
  "audio": {
    "uri":"gs://cloud-samples-tests/speech/brooklyn.flac"
  }
}'

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

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

{
  "results": [
    {
      "alternatives": [
        {
          "transcript": "How old is the Brooklyn Bridge?",
          "confidence": 0.98360395
        }
      ]
    }
  ]
}

Go

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

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


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

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

func autoPunctuation(w io.Writer, path string) error {
	ctx := context.Background()

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

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

	resp, err := client.Recognize(ctx, &speechpb.RecognizeRequest{
		Config: &speechpb.RecognitionConfig{
			Encoding:        speechpb.RecognitionConfig_LINEAR16,
			SampleRateHertz: 8000,
			LanguageCode:    "en-US",
			// Enable automatic punctuation.
			EnableAutomaticPunctuation: true,
		},
		Audio: &speechpb.RecognitionAudio{
			AudioSource: &speechpb.RecognitionAudio_Content{Content: data},
		},
	})
	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 on remote FLAC file and prints the transcription.
 *
 * @param gcsUri the path to the remote FLAC audio file to transcribe.
 */
public static void transcribeGcsWithAutomaticPunctuation(String gcsUri) throws Exception {
  try (SpeechClient speechClient = SpeechClient.create()) {
    // Configure request with raw PCM audio
    RecognitionConfig config =
        RecognitionConfig.newBuilder()
            .setEncoding(AudioEncoding.FLAC)
            .setLanguageCode("en-US")
            .setSampleRateHertz(16000)
            .setEnableAutomaticPunctuation(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);
    }

    // Just print the first result here.
    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);

    // Print out the result
    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 API
/**
 * TODO(developer): Update client library import to use new
 * version of API when desired features become available
 */

const speech = require('@google-cloud/speech');
const fs = require('fs');

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 * Include the sampleRateHertz field in the config object.
 */
// const filename = 'Local path to audio file, e.g. /path/to/audio.raw';
// 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,
  languageCode: languageCode,
  enableAutomaticPunctuation: true,
};

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


def transcribe_file_with_auto_punctuation(audio_file: str) -> speech.RecognizeResponse:
    """Transcribe the given audio file with auto punctuation enabled.
    Args:
        audio_file (str): Path to the local audio file to be transcribed.
    Returns:
        speech.RecognizeResponse: The response containing the transcription results.
    """
    client = speech.SpeechClient()

    with open(audio_file, "rb") as f:
        audio_content = f.read()

    audio = speech.RecognitionAudio(content=audio_content)
    config = speech.RecognitionConfig(
        encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
        sample_rate_hertz=8000,
        language_code="en-US",
        # Enable automatic punctuation
        enable_automatic_punctuation=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}")

    return response

שפות נוספות

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

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

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

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

איך שולחים בקשות תמלול סנכרוניות