Questa pagina mostra come trascrivere file audio lunghi (più di un minuto) in testo utilizzando l'API Speech-to-Text e il riconoscimento vocale asincrono.
Informazioni sul riconoscimento vocale asincrono
Il riconoscimento vocale batch avvia un'operazione di trattamento audio a lunga esecuzione. Utilizza il riconoscimento vocale asincrono per trascrivere l'audio di durata superiore a 60 secondi. Per l'audio più breve, il riconoscimento vocale sincrono è più veloce e semplice. Il limite massimo per il riconoscimento vocale asincrono è di 480 minuti (8 ore).
Il riconoscimento vocale batch è in grado di trascrivere solo l'audio archiviato in Cloud Storage. L'output della trascrizione può essere fornito in linea nella risposta (per le richieste di riconoscimento batch di un singolo file) o scritto in Cloud Storage.
La richiesta di riconoscimento batch restituisce un Operation
che contiene informazioni sull'elaborazione del riconoscimento in corso della
richiesta. Puoi eseguire il polling dell'operazione per sapere quando l'
operazione è completa e le trascrizioni sono disponibili.
Prima di iniziare
- Accedi al tuo Google Cloud account. Se non conosci Google Cloud, crea un account per valutare le prestazioni dei nostri prodotti in scenari reali. I nuovi clienti ricevono anche 300 $di crediti senza costi per l'esecuzione, il test e il deployment dei workload.
-
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 theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
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 theserviceusage.services.enablepermission. Learn how to grant roles.-
Make sure that you have the following role or roles on the project: Cloud Speech Administrator
Check for the roles
-
In the Google Cloud console, go to the IAM page.
Go to IAM - Select the project.
-
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.
- 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
-
In the Google Cloud console, go to the IAM page.
Go to IAM - Select the project.
- Click Grant access.
-
In the New principals field, enter your user identifier. This is typically the email address for a Google Account.
- Click Select a role, then search for the role.
- To grant additional roles, click Add another role and add each additional role.
- Click Save.
-
-
Installa Google Cloud CLI.
-
Se utilizzi un provider di identità (IdP) esterno, devi prima accedere a gcloud CLI con la tua identità federata.
-
Per inizializzare gcloud CLI, esegui questo comando:
gcloud init -
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 theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
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 theserviceusage.services.enablepermission. Learn how to grant roles.-
Make sure that you have the following role or roles on the project: Cloud Speech Administrator
Check for the roles
-
In the Google Cloud console, go to the IAM page.
Go to IAM - Select the project.
-
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.
- 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
-
In the Google Cloud console, go to the IAM page.
Go to IAM - Select the project.
- Click Grant access.
-
In the New principals field, enter your user identifier. This is typically the email address for a Google Account.
- Click Select a role, then search for the role.
- To grant additional roles, click Add another role and add each additional role.
- Click Save.
-
-
Installa Google Cloud CLI.
-
Se utilizzi un provider di identità (IdP) esterno, devi prima accedere a gcloud CLI con la tua identità federata.
-
Per inizializzare gcloud CLI, esegui questo comando:
gcloud init -
Se utilizzi una shell locale, crea le credenziali di autenticazione locali per il tuo account utente:
gcloud auth application-default login
Non devi eseguire questa operazione se utilizzi Cloud Shell.
Se viene restituito un errore di autenticazione e utilizzi un provider di identità (IdP) esterno, verifica di aver acceduto a gcloud CLI con la tua identità federata.
Le librerie client possono utilizzare Credenziali predefinite dell'applicazione per autenticarsi facilmente con le API di Google e inviare richieste a queste API. Con Credenziali predefinite dell'applicazione, puoi testare la tua applicazione localmente ed eseguirne il deployment senza modificare il codice sottostante. Per saperne di più, vedi Autenticazione per l'utilizzo delle librerie client.
Assicurati inoltre di aver installato la libreria client.
Abilita l'accesso a Cloud Storage
Speech-to-Text utilizza un account di servizio per accedere ai tuoi file in Cloud Storage. Per impostazione predefinita, il account di servizio ha accesso ai file di Cloud Storage nello stesso progetto.
L'indirizzo email del account di servizio è il seguente:
service-PROJECT_NUMBER@gcp-sa-speech.iam.gserviceaccount.com
Per trascrivere i file di Cloud Storage in un altro progetto, puoi assegnare a questo account di servizio il ruolo [Agente di servizio Speech-to-Text][speech-service-agent] nell'altro progetto:
gcloud projects add-iam-policy-binding PROJECT_ID \
--member=serviceAccount:service-PROJECT_NUMBER@gcp-sa-speech.iam.gserviceaccount.com \
--role=roles/speech.serviceAgentPer saperne di più sulla policy IAM del progetto, consulta [Gestisci l'accesso a progetti, cartelle e organizzazioni][manage-access].
Puoi anche concedere al account di servizio un accesso più granulare concedendogli l'autorizzazione a un bucket Cloud Storage specifico:
gcloud storage buckets add-iam-policy-binding gs://BUCKET_NAME \
--member=serviceAccount:service-PROJECT_NUMBER@gcp-sa-speech.iam.gserviceaccount.com \
--role=roles/storage.adminPer saperne di più sulla gestione dell'accesso a Cloud Storage, consulta [Crea e gestisci gli elenchi di controllo dell'accesso][buckets-manage-acl] nella documentazione di Cloud Storage.
Esegui il riconoscimento batch con risultati in linea
Ecco un esempio di esecuzione del riconoscimento vocale batch su un file audio in Cloud Storage e di lettura dei risultati della trascrizione in linea dalla risposta:
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_batch_gcs_input_inline_output_v2(
audio_uri: str,
) -> cloud_speech.BatchRecognizeResults:
"""Transcribes audio from a Google Cloud Storage URI using the Google Cloud Speech-to-Text API.
The transcription results are returned inline in the response.
Args:
audio_uri (str): The Google Cloud Storage URI of the input audio file.
Such as gs://[BUCKET]/[FILE]
Returns:
cloud_speech.BatchRecognizeResults: The response containing the transcription results.
"""
# Instantiates a client
client = SpeechClient()
config = cloud_speech.RecognitionConfig(
auto_decoding_config=cloud_speech.AutoDetectDecodingConfig(),
language_codes=["en-US"],
model="chirp_3",
)
file_metadata = cloud_speech.BatchRecognizeFileMetadata(uri=audio_uri)
request = cloud_speech.BatchRecognizeRequest(
recognizer=f"projects/{PROJECT_ID}/locations/global/recognizers/_",
config=config,
files=[file_metadata],
recognition_output_config=cloud_speech.RecognitionOutputConfig(
inline_response_config=cloud_speech.InlineOutputConfig(),
),
)
# Transcribes the audio into text
operation = client.batch_recognize(request=request)
print("Waiting for operation to complete...")
response = operation.result(timeout=120)
for result in response.results[audio_uri].transcript.results:
print(f"Transcript: {result.alternatives[0].transcript}")
return response.results[audio_uri].transcript
Esegui il riconoscimento batch e scrivi i risultati in Cloud Storage
Ecco un esempio di esecuzione del riconoscimento vocale batch su un file audio in Cloud Storage e di lettura dei risultati della trascrizione dal file di output in Cloud Storage. Tieni presente che il file scritto in Cloud Storage è un
BatchRecognizeResults messaggio in formato JSON:
Python
import os
import re
from google.cloud import storage
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_batch_gcs_input_gcs_output_v2(
audio_uri: str,
gcs_output_path: str,
) -> cloud_speech.BatchRecognizeResults:
"""Transcribes audio from a Google Cloud Storage URI using the Google Cloud Speech-to-Text API.
The transcription results are stored in another Google Cloud Storage bucket.
Args:
audio_uri (str): The Google Cloud Storage URI of the input audio file.
E.g., gs://[BUCKET]/[FILE]
gcs_output_path (str): The Google Cloud Storage bucket URI where the output transcript will be stored.
E.g., gs://[BUCKET]
Returns:
cloud_speech.BatchRecognizeResults: The response containing the URI of the transcription results.
"""
# Instantiates a client
client = SpeechClient()
config = cloud_speech.RecognitionConfig(
auto_decoding_config=cloud_speech.AutoDetectDecodingConfig(),
language_codes=["en-US"],
model="chirp_3",
)
file_metadata = cloud_speech.BatchRecognizeFileMetadata(uri=audio_uri)
request = cloud_speech.BatchRecognizeRequest(
recognizer=f"projects/{PROJECT_ID}/locations/global/recognizers/_",
config=config,
files=[file_metadata],
recognition_output_config=cloud_speech.RecognitionOutputConfig(
gcs_output_config=cloud_speech.GcsOutputConfig(
uri=gcs_output_path,
),
),
)
# Transcribes the audio into text
operation = client.batch_recognize(request=request)
print("Waiting for operation to complete...")
response = operation.result(timeout=120)
file_results = response.results[audio_uri]
print(f"Operation finished. Fetching results from {file_results.uri}...")
output_bucket, output_object = re.match(
r"gs://([^/]+)/(.*)", file_results.uri
).group(1, 2)
# Instantiates a Cloud Storage client
storage_client = storage.Client()
# Fetch results from Cloud Storage
bucket = storage_client.bucket(output_bucket)
blob = bucket.blob(output_object)
results_bytes = blob.download_as_bytes()
batch_recognize_results = cloud_speech.BatchRecognizeResults.from_json(
results_bytes, ignore_unknown_fields=True
)
for result in batch_recognize_results.results:
print(f"Transcript: {result.alternatives[0].transcript}")
return batch_recognize_results
Esegui il riconoscimento batch su più file
Ecco un esempio di esecuzione del riconoscimento vocale batch su più file audio in Cloud Storage e di lettura dei risultati della trascrizione dai file di output in Cloud Storage:
Python
import os
import re
from typing import List
from google.cloud import storage
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_batch_multiple_files_v2(
audio_uris: List[str],
gcs_output_path: str,
) -> cloud_speech.BatchRecognizeResponse:
"""Transcribes audio from multiple Google Cloud Storage URIs using the Google Cloud Speech-to-Text API.
The transcription results are stored in another Google Cloud Storage bucket.
Args:
audio_uris (List[str]): The list of Google Cloud Storage URIs of the input audio files.
Such as ["gs://[BUCKET]/[FILE]", "gs://[BUCKET]/[FILE]"]
gcs_output_path (str): The Google Cloud Storage bucket URI where the output transcript is stored.
Such as gs://[BUCKET]
Returns:
cloud_speech.BatchRecognizeResponse: The response containing the URIs of the transcription results.
"""
# Instantiates a client
client = SpeechClient()
config = cloud_speech.RecognitionConfig(
auto_decoding_config=cloud_speech.AutoDetectDecodingConfig(),
language_codes=["en-US"],
model="chirp_3",
)
files = [cloud_speech.BatchRecognizeFileMetadata(uri=uri) for uri in audio_uris]
request = cloud_speech.BatchRecognizeRequest(
recognizer=f"projects/{PROJECT_ID}/locations/global/recognizers/_",
config=config,
files=files,
recognition_output_config=cloud_speech.RecognitionOutputConfig(
gcs_output_config=cloud_speech.GcsOutputConfig(
uri=gcs_output_path,
),
),
)
# Transcribes the audio into text
operation = client.batch_recognize(request=request)
print("Waiting for operation to complete...")
response = operation.result(timeout=120)
print("Operation finished. Fetching results from:")
for uri in audio_uris:
file_results = response.results[uri]
print(f" {file_results.uri}...")
output_bucket, output_object = re.match(
r"gs://([^/]+)/(.*)", file_results.uri
).group(1, 2)
# Instantiates a Cloud Storage client
storage_client = storage.Client()
# Fetch results from Cloud Storage
bucket = storage_client.bucket(output_bucket)
blob = bucket.blob(output_object)
results_bytes = blob.download_as_bytes()
batch_recognize_results = cloud_speech.BatchRecognizeResults.from_json(
results_bytes, ignore_unknown_fields=True
)
for result in batch_recognize_results.results:
print(f" Transcript: {result.alternatives[0].transcript}")
return response
Abilita il batch dinamico per il riconoscimento batch
Il batch dinamico consente di ridurre i costi di trascrizione per una latenza maggiore. Questa funzionalità è disponibile solo per il riconoscimento batch.
Ecco un esempio di esecuzione del riconoscimento batch su un file audio in Cloud Storage con il batch dinamico abilitato:
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_batch_dynamic_batching_v2(
audio_uri: str,
) -> cloud_speech.BatchRecognizeResults:
"""Transcribes audio from a Google Cloud Storage URI using dynamic batching.
Args:
audio_uri (str): The Cloud Storage URI of the input audio.
E.g., gs://[BUCKET]/[FILE]
Returns:
cloud_speech.BatchRecognizeResults: The response containing the transcription results.
"""
# Instantiates a client
client = SpeechClient()
config = cloud_speech.RecognitionConfig(
auto_decoding_config=cloud_speech.AutoDetectDecodingConfig(),
language_codes=["en-US"],
model="chirp_3",
)
file_metadata = cloud_speech.BatchRecognizeFileMetadata(uri=audio_uri)
request = cloud_speech.BatchRecognizeRequest(
recognizer=f"projects/{PROJECT_ID}/locations/global/recognizers/_",
config=config,
files=[file_metadata],
recognition_output_config=cloud_speech.RecognitionOutputConfig(
inline_response_config=cloud_speech.InlineOutputConfig(),
),
processing_strategy=cloud_speech.BatchRecognizeRequest.ProcessingStrategy.DYNAMIC_BATCHING,
)
# Transcribes the audio into text
operation = client.batch_recognize(request=request)
print("Waiting for operation to complete...")
response = operation.result(timeout=120)
for result in response.results[audio_uri].transcript.results:
print(f"Transcript: {result.alternatives[0].transcript}")
return response.results[audio_uri].transcript
Esegui l'override delle funzionalità di riconoscimento per file
Per impostazione predefinita, il riconoscimento batch utilizza la stessa configurazione di riconoscimento per ogni file nella richiesta di riconoscimento batch. Se file diversi richiedono configurazioni o funzionalità diverse, è possibile eseguire l'override della configurazione per file utilizzando il
config campo nel
BatchRecognizeFileMetadata messaggio. Per un esempio
di override delle funzionalità di riconoscimento, consulta la documentazione relativa ai riconoscitori.
Libera spazio
Per evitare che al tuo Google Cloud account vengano addebitati costi relativi alle risorse utilizzate in questa pagina, segui questi passaggi.
-
(Facoltativo) Revoca le credenziali di autenticazione che hai creato ed elimina il file delle credenziali locali
gcloud auth application-default revoke
-
(Facoltativo) Revoca le credenziali da gcloud CLI.
gcloud auth revoke
Console
gcloud
Elimina un Google Cloud progetto:
gcloud projects delete PROJECT_ID