Nesta página, descrevemos como transcrever um arquivo de áudio curto para texto usando o reconhecimento de fala síncrono.
O reconhecimento de fala síncrono converte um áudio curto (menos de 60 segundos) em um texto que é retornado ao usuário.
É possível fornecer um arquivo local com o conteúdo de áudio diretamente à Speech-to-Text ou pedir que ela processe conteúdos de áudio armazenados em um bucket do Cloud Storage. Saiba mais sobre os limites das solicitações de reconhecimento de fala síncrono na página de cotas e limites.
Antes de começar
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
-
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
(
roles/resourcemanager.projectCreator
), which contains theresourcemanager.projects.create
permission. 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.enable
permission. 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.
Acessar o IAM - Selecione o projeto.
- Clique em Conceder acesso.
-
No campo Novos principais, digite seu identificador de usuário. Normalmente, é o endereço de e-mail de uma Conta do Google.
- Na lista Selecionar papel, escolha um.
- Para conceder outros papéis, adicione-os clicando em Adicionar outro papel.
- Clique em Salvar.
Install the Google Cloud CLI.
Ao usar um provedor de identidade (IdP) externo, primeiro faça login na gcloud CLI com sua identidade federada.
Para inicializar a gcloud CLI, execute o seguinte 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
(
roles/resourcemanager.projectCreator
), which contains theresourcemanager.projects.create
permission. 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.enable
permission. 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.
Acessar o IAM - Selecione o projeto.
- Clique em Conceder acesso.
-
No campo Novos principais, digite seu identificador de usuário. Normalmente, é o endereço de e-mail de uma Conta do Google.
- Na lista Selecionar papel, escolha um.
- Para conceder outros papéis, adicione-os clicando em Adicionar outro papel.
- Clique em Salvar.
Install the Google Cloud CLI.
Ao usar um provedor de identidade (IdP) externo, primeiro faça login na gcloud CLI com sua identidade federada.
Para inicializar a gcloud CLI, execute o seguinte comando:
gcloud init
-
-
If you're using a local shell, then create local authentication credentials for your user account:
gcloud auth application-default login
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
-
Optional: Revoke the authentication credentials that you created, and delete the local credential file.
gcloud auth application-default revoke
-
Optional: Revoke credentials from the gcloud CLI.
gcloud auth revoke
- In the Google Cloud console, go to the Manage resources page.
- In the project list, select the project that you want to delete, and then click Delete.
- In the dialog, type the project ID, and then click Shut down to delete the project.
- In the Google Cloud console, go to the Manage resources page.
- In the project list, select the project that you want to delete, and then click Delete.
- In the dialog, type the project ID, and then click Shut down to delete the project.
- Consulte a documentação de referência para saber mais sobre o reconhecimento síncrono.
- Aprenda a transcrever um streaming de áudio.
- Aprenda a transcrever arquivos de áudio longos.
- Para o melhor desempenho e acurácia e outras dicas, consulte a documentação sobre práticas recomendadas.
As bibliotecas de cliente podem usar o Application Default Credentials para se autenticar facilmente nas APIs do Google e enviar solicitações para elas. Com o Application Default Credentials, é possível testar seu aplicativo localmente e implantá-lo sem alterar o código. Para mais informações, consulte Autenticação para usar bibliotecas de cliente.
Verifique também se você instalou a biblioteca de cliente.
Realizar o reconhecimento de fala síncrono em um arquivo local
Este é um exemplo de como realizar o reconhecimento de fala síncrono em um arquivo de áudio local:
Python
from google.cloud.speech_v2 import SpeechClient
from google.cloud.speech_v2.types import cloud_speech
# TODO(developer): Update and un-comment below line
# PROJECT_ID = "your-project-id"
# Instantiates a client
client = SpeechClient()
# Reads a file as bytes
with open("resources/audio.wav", "rb") as f:
audio_content = f.read()
config = cloud_speech.RecognitionConfig(
auto_decoding_config=cloud_speech.AutoDetectDecodingConfig(),
language_codes=["en-US"],
model="chirp_3",
)
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}")
Executar o reconhecimento de fala síncrono em um arquivo remoto
Para sua comodidade, a API Speech-to-Text pode realizar o reconhecimento de fala síncrono diretamente em um arquivo de áudio localizado no Google Cloud Storage, para que você não precise enviar o conteúdo no corpo da solicitação.
A Speech-to-Text usa uma conta de serviço para acessar os arquivos no Cloud Storage. Por padrão, a conta de serviço tem acesso aos arquivos do Cloud Storage no mesmo projeto.
O endereço de e-mail da conta de serviço é:
service-PROJECT_NUMBER@gcp-sa-speech.iam.gserviceaccount.com
Para transcrever arquivos do Cloud Storage em outro projeto, conceda a essa conta de serviço o papel Agente de serviço da Speech-to-Text nesse outro projeto:
gcloud projects add-iam-policy-binding PROJECT_ID \
--member=serviceAccount:service-PROJECT_NUMBER@gcp-sa-speech.iam.gserviceaccount.com \
--role=roles/speech.serviceAgent
Saiba mais sobre políticas do IAM para projetos em Gerenciar o acesso a projetos, pastas e organizações.
Também é possível atribuir à conta de serviço um acesso mais granular, concedendo permissão para um bucket específico do Cloud Storage:
gcloud storage buckets add-iam-policy-binding gs://BUCKET_NAME \
--member=serviceAccount:service-PROJECT_NUMBER@gcp-sa-speech.iam.gserviceaccount.com \
--role=roles/storage.admin
Saiba como gerenciar o acesso ao Cloud Storage em Criar e gerenciar listas de controle de acesso na documentação do Cloud Storage.
Este é um exemplo de reconhecimento de fala síncrono em um arquivo localizado no Cloud Storage:
Python
from google.cloud.speech_v2 import SpeechClient
from google.cloud.speech_v2.types import cloud_speech
# Instantiates a client
client = SpeechClient()
# TODO(developer): Update and un-comment below line
# PROJECT_ID = "your-project-id"
config = cloud_speech.RecognitionConfig(
auto_decoding_config=cloud_speech.AutoDetectDecodingConfig(),
language_codes=["en-US"],
model="chirp_3",
)
request = cloud_speech.RecognizeRequest(
recognizer=f"projects/{PROJECT_ID}/locations/global/recognizers/_",
config=config,
uri="gs://cloud-samples-data/speech/audio.flac", # URI of the audio file in Google Cloud Storage
)
# Transcribes the audio into text
response = client.recognize(request=request)
for result in response.results:
print(f"Transcript: {result.alternatives[0].transcript}")
Limpar
Para evitar cobranças na conta do Google Cloud pelos recursos usados nesta página, siga as etapas abaixo.
Console
gcloud