מזהים

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

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

  1. נכנסים לחשבון Google Cloud . אם אתם משתמשים חדשים ב- Google Cloud, צרו חשבון כדי שתוכלו להעריך את הביצועים של המוצרים שלנו בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300$ להרצה, לבדיקה ולפריסה של עומסי העבודה.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Speech-to-Text APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  5. Make sure that you have the following role or roles on the project: Cloud Speech Administrator

    Check for the roles

    1. In the Google Cloud console, go to the IAM page.

      Go to IAM
    2. Select the project.
    3. In the Principal column, find all rows that identify you or a group that you're included in. To learn which groups you're included in, contact your administrator.

    4. For all rows that specify or include you, check the Role column to see whether the list of roles includes the required roles.

    Grant the roles

    1. In the Google Cloud console, go to the IAM page.

      Go to IAM
    2. Select the project.
    3. Click Grant access.
    4. In the New principals field, enter your user identifier. This is typically the email address for a Google Account.

    5. Click Select a role, then search for the role.
    6. To grant additional roles, click Add another role and add each additional role.
    7. Click Save.
  6. התקינו את ה-CLI של Google Cloud.

  7. אם אתם משתמשים בספק זהויות חיצוני (IdP), קודם אתם צריכים להיכנס ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

  8. כדי לאתחל את ה-CLI של gcloud, הריצו את הפקודה הבאה:

    gcloud init
  9. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  10. Verify that billing is enabled for your Google Cloud project.

  11. Enable the Speech-to-Text APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  12. Make sure that you have the following role or roles on the project: Cloud Speech Administrator

    Check for the roles

    1. In the Google Cloud console, go to the IAM page.

      Go to IAM
    2. Select the project.
    3. In the Principal column, find all rows that identify you or a group that you're included in. To learn which groups you're included in, contact your administrator.

    4. For all rows that specify or include you, check the Role column to see whether the list of roles includes the required roles.

    Grant the roles

    1. In the Google Cloud console, go to the IAM page.

      Go to IAM
    2. Select the project.
    3. Click Grant access.
    4. In the New principals field, enter your user identifier. This is typically the email address for a Google Account.

    5. Click Select a role, then search for the role.
    6. To grant additional roles, click Add another role and add each additional role.
    7. Click Save.
  13. התקינו את ה-CLI של Google Cloud.

  14. אם אתם משתמשים בספק זהויות חיצוני (IdP), קודם אתם צריכים להיכנס ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

  15. כדי לאתחל את ה-CLI של gcloud, הריצו את הפקודה הבאה:

    gcloud init
  16. בספריות הלקוח אפשר להשתמש ב-Application Default Credentials כדי לעבור בקלות אימות מול Google APIs ולשלוח בקשות לאותם ממשקי API. באמצעות Application Default Credentials, אתם יכולים לבדוק את האפליקציה ברמה המקומית ולפרוס אותה בלי לשנות את הקוד שלה. מידע נוסף זמין במאמר אימות לצורך שימוש בספריות לקוח.

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

    gcloud auth application-default login

    אם אתם משתמשים ב-Cloud Shell, אין צורך לבצע את הפעולה הזו.

    אם מוחזרת שגיאת אימות ואתם משתמשים בספק זהויות חיצוני (IdP), ודאו ש נכנסתם ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

בנוסף, חשוב לוודא שהתקנתם את ספריית הלקוח.

הסבר על רכיבי זיהוי

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

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

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

יצירת רכיבי זיהוי

דוגמה ליצירת רכיב לזיהוי דיבור שאפשר להשתמש בו כדי לשלוח בקשות לזיהוי דיבור:

Python

import os

from google.cloud.speech_v2 import SpeechClient
from google.cloud.speech_v2.types import cloud_speech

PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT")


def create_recognizer(recognizer_id: str) -> cloud_speech.Recognizer:
    """Сreates a recognizer with an unique ID and default recognition configuration.
    Args:
        recognizer_id (str): The unique identifier for the recognizer to be created.
    Returns:
        cloud_speech.Recognizer: The created recognizer object with configuration.
    """
    # Instantiates a client
    client = SpeechClient()

    request = cloud_speech.CreateRecognizerRequest(
        parent=f"projects/{PROJECT_ID}/locations/global",
        recognizer_id=recognizer_id,
        recognizer=cloud_speech.Recognizer(
            default_recognition_config=cloud_speech.RecognitionConfig(
                language_codes=["en-US"], model="long"
            ),
        ),
    )
    # Sends the request to create a recognizer and waits for the operation to complete
    operation = client.create_recognizer(request=request)
    recognizer = operation.result()

    print("Created Recognizer:", recognizer.name)
    return recognizer

שימוש בכלי קיים לזיהוי דיבור כדי לשלוח בקשות

דוגמה לשליחת כמה בקשות זיהוי באמצעות אותו מזהה:

Python

import os

from google.cloud.speech_v2 import SpeechClient
from google.cloud.speech_v2.types import cloud_speech

PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT")


def transcribe_reuse_recognizer(
    audio_file: str,
    recognizer_id: str,
) -> cloud_speech.RecognizeResponse:
    """Transcribe an audio file using an existing recognizer.
    Args:
        audio_file (str): Path to the local audio file to be transcribed.
            Example: "resources/audio.wav"
        recognizer_id (str): The ID of the existing recognizer to be used for transcription.
    Returns:
        cloud_speech.RecognizeResponse: The response containing the transcription results.
    """
    # Instantiates a client
    client = SpeechClient()

    # Reads a file as bytes
    with open(audio_file, "rb") as f:
        audio_content = f.read()

    request = cloud_speech.RecognizeRequest(
        recognizer=f"projects/{PROJECT_ID}/locations/global/recognizers/{recognizer_id}",
        content=audio_content,
    )

    # Transcribes the audio into text
    response = client.recognize(request=request)

    for result in response.results:
        print(f"Transcript: {result.alternatives[0].transcript}")

    return response

הפעלת תכונות במנגנון זיהוי

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

הנה דוגמה להפעלת פיסוק אוטומטי במנגנון זיהוי, שמפעיל פיסוק אוטומטי בבקשת הזיהוי באמצעות מנגנון הזיהוי הזה:

Python


from google.cloud.speech_v2 import SpeechClient
from google.cloud.speech_v2.types import cloud_speech

from google.api_core.exceptions import NotFound

# Instantiates a client
client = SpeechClient()

# TODO(developer): Update and un-comment below line
# PROJECT_ID = "your-project-id"
# recognizer_id = "id-recognizer"
recognizer_name = (
    f"projects/{PROJECT_ID}/locations/global/recognizers/{recognizer_id}"
)
try:
    # Use an existing recognizer
    recognizer = client.get_recognizer(name=recognizer_name)
    print("Using existing Recognizer:", recognizer.name)
except NotFound:
    # Create a new recognizer
    request = cloud_speech.CreateRecognizerRequest(
        parent=f"projects/{PROJECT_ID}/locations/global",
        recognizer_id=recognizer_id,
        recognizer=cloud_speech.Recognizer(
            default_recognition_config=cloud_speech.RecognitionConfig(
                auto_decoding_config=cloud_speech.AutoDetectDecodingConfig(),
                language_codes=["en-US"],
                model="latest_long",
                features=cloud_speech.RecognitionFeatures(
                    enable_automatic_punctuation=True,
                ),
            ),
        ),
    )
    operation = client.create_recognizer(request=request)
    recognizer = operation.result()
    print("Created Recognizer:", recognizer.name)

# Reads a file as bytes
with open(audio_file, "rb") as f:
    audio_content = f.read()

request = cloud_speech.RecognizeRequest(
    recognizer=f"projects/{PROJECT_ID}/locations/global/recognizers/{recognizer_id}",
    content=audio_content,
)

# Transcribes the audio into text
response = client.recognize(request=request)

for result in response.results:
    print(f"Transcript: {result.alternatives[0].transcript}")

שינוי תכונות של רכיב הזיהוי בבקשות זיהוי

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

Python

import os

from google.cloud.speech_v2 import SpeechClient
from google.cloud.speech_v2.types import cloud_speech
from google.protobuf.field_mask_pb2 import FieldMask

PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT")


def transcribe_override_recognizer(
    audio_file: str,
    recognizer_id: str,
) -> cloud_speech.RecognizeResponse:
    """Transcribe an audio file using an existing recognizer with overridden settings for the recognition request.
    Args:
        audio_file (str): Path to the local audio file to be transcribed.
            Example: "resources/audio.wav"
        recognizer_id (str): The unique ID of the recognizer to be used for transcription.
    Returns:
        cloud_speech.RecognizeResponse: The response containing the transcription results.
    """
    # Instantiates a client
    client = SpeechClient()

    request = cloud_speech.CreateRecognizerRequest(
        parent=f"projects/{PROJECT_ID}/locations/global",
        recognizer_id=recognizer_id,
        recognizer=cloud_speech.Recognizer(
            default_recognition_config=cloud_speech.RecognitionConfig(
                auto_decoding_config=cloud_speech.AutoDetectDecodingConfig(),
                language_codes=["en-US"],
                model="latest_long",
                features=cloud_speech.RecognitionFeatures(
                    enable_automatic_punctuation=True,
                    enable_word_time_offsets=True,
                ),
            ),
        ),
    )

    operation = client.create_recognizer(request=request)
    recognizer = operation.result()

    print("Created Recognizer:", recognizer.name)

    # Reads a file as bytes
    with open(audio_file, "rb") as f:
        audio_content = f.read()

    request = cloud_speech.RecognizeRequest(
        recognizer=f"projects/{PROJECT_ID}/locations/global/recognizers/{recognizer_id}",
        config=cloud_speech.RecognitionConfig(
            features=cloud_speech.RecognitionFeatures(
                enable_word_time_offsets=False,
            ),
        ),
        config_mask=FieldMask(paths=["features.enable_word_time_offsets"]),
        content=audio_content,
    )

    # Transcribes the audio into text
    response = client.recognize(request=request)

    for result in response.results:
        print(f"Transcript: {result.alternatives[0].transcript}")

    return response

שליחת בקשות ללא רכיבי זיהוי

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

Python

import os

from google.cloud.speech_v2 import SpeechClient
from google.cloud.speech_v2.types import cloud_speech

PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT")


def quickstart_v2(audio_file: str) -> cloud_speech.RecognizeResponse:
    """Transcribe an audio file.
    Args:
        audio_file (str): Path to the local audio file to be transcribed.
    Returns:
        cloud_speech.RecognizeResponse: The response from the recognize request, containing
        the transcription results
    """
    # Reads a file as bytes
    with open(audio_file, "rb") as f:
        audio_content = f.read()

    # Instantiates a client
    client = SpeechClient()

    config = cloud_speech.RecognitionConfig(
        auto_decoding_config=cloud_speech.AutoDetectDecodingConfig(),
        language_codes=["en-US"],
        model="long",
    )

    request = cloud_speech.RecognizeRequest(
        recognizer=f"projects/{PROJECT_ID}/locations/global/recognizers/_",
        config=config,
        content=audio_content,
    )

    # Transcribes the audio into text
    response = client.recognize(request=request)

    for result in response.results:
        print(f"Transcript: {result.alternatives[0].transcript}")

    return response

הסרת המשאבים

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

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

    gcloud auth application-default revoke
  2. אם רוצים, מבטלים את פרטי הכניסה של ה-CLI של gcloud.

    gcloud auth revoke

המסוף

  • במסוף Google Cloud , נכנסים לדף Manage resources.

    כניסה לדף Manage resources

  • ברשימת הפרויקטים, בוחרים את הפרויקט שרוצים למחוק ולוחצים על Delete.
  • כדי למחוק את הפרויקט, כותבים את מזהה הפרויקט בתיבת הדו-שיח ולוחצים על Shut down.
  • gcloud

    כדי למחוק Google Cloud פרויקט:

    gcloud projects delete PROJECT_ID

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