Transcrever um áudio de um arquivo de vídeo usando a Speech-to-Text


Neste tutorial, veja como transcrever a faixa de áudio de um arquivo de vídeo usando o Speech-to-Text.

Os arquivos de áudio podem ter várias origens diferentes. Os dados de áudio podem vir de um smartphone (como correio de voz) ou da trilha sonora incluída em um arquivo de vídeo.

No Speech-to-Text, é possível usar um dos vários modelos de machine learning para transcrever o arquivo de áudio, com a finalidade de conseguir a melhor correspondência com a fonte original do áudio. Especifique a fonte do áudio original para conseguir melhores resultados na transcrição do áudio. Dessa maneira, o Speech-to-Text processa os arquivos de áudio usando um modelo de machine learning treinado para dados similares aos contidos no arquivo de áudio.

Objetivos

  • Enviar uma solicitação de transcrição de áudio para um arquivo de vídeo ao Speech-to-Text.

Custos

Neste documento, você vai usar os seguintes componentes faturáveis do Google Cloud:

  • Speech-to-Text

Para gerar uma estimativa de custo baseada na sua projeção de uso, use a calculadora de preços.

Novos usuários do Google Cloud podem estar qualificados para um teste gratuito.

Antes de começar

Os pré-requisitos para este tutorial são:

Preparar os dados de áudio

Antes de poder transcrever o áudio de um vídeo, é preciso extrair os dados do arquivo de vídeo. Depois de extrair os dados de áudio, armazene-os em um bucket do Cloud Storage ou converta-os em codificação base64.

Extrair os dados de áudio

É possível usar qualquer ferramenta de conversão de arquivos que manipule arquivos de áudio e vídeo, como o FFmpeg.

Use o snippet de código abaixo para converter um arquivo de vídeo em um arquivo de áudio usando o ffmpeg.

ffmpeg -i video-input-file audio-output-file

Armazenar ou converter os dados de áudio

É possível transcrever um arquivo de áudio armazenado em sua máquina local ou em um bucket do Cloud Storage.

Use o comando a seguir para fazer o upload do seu arquivo de áudio para um bucket do Cloud Storage usando a CLI do Google Cloud.

gcloud storage cp audio-output-file storage-bucket-uri

Se você usa um arquivo local e planeja enviar uma solicitação usando a ferramenta curl da linha de comando, primeiro converta o arquivo de áudio em dados codificados em base64.

Use o seguinte comando para converter um arquivo de áudio em um arquivo de texto.

base64 audio-output-file -w 0 > audio-data-text

Enviar uma solicitação de transcrição

Use o código a seguir para enviar uma solicitação de transcrição para o Speech-to-Text.

Solicitação de arquivo local

Protocolo

Consulte o endpoint da API speech:recognize para todos os detalhes.

Para realizar o reconhecimento de fala síncrono, faça uma solicitação POST e forneça o corpo apropriado a ela. Confira a seguir um exemplo de uma solicitação POST usando curl. O exemplo usa a CLI do Google Cloud para gerar um token de acesso. Para instruções sobre como instalar a gcloud CLI, consulte o guia de início rápido.

curl -s -H "Content-Type: application/json" \
    -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
    https://speech.googleapis.com/v1/speech:recognize \
    --data '{
    "config": {
        "encoding": "LINEAR16",
        "sampleRateHertz": 16000,
        "languageCode": "en-US",
        "model": "video"
    },
    "audio": {
        "uri": "gs://cloud-samples-tests/speech/Google_Gnome.wav"
    }
}'

Consulte a documentação de referência RecognitionConfig para mais informações sobre como configurar o corpo da solicitação.

Quando a solicitação é bem-sucedida, o servidor retorna um código de status HTTP 200 OK e a resposta no formato JSON:

{
  "results": [
    {
      "alternatives": [
        {
          "transcript": "OK Google stream stranger things from
            Netflix to my TV okay stranger things from
            Netflix playing on TV from the people that brought you
            Google home comes the next evolution of the smart home
            and it's just outside your window me Google know hi
            how can I help okay no what's the weather like outside
            the weather outside is sunny and 76 degrees he's right
            okay no turn on the hose I'm holding sure okay no I'm can
            I eat this lemon tree leaf yes what about this Daisy yes
            but I wouldn't recommend it but I could eat it okay
            Nomad milk to my shopping list I'm sorry that sounds like
            an indoor request I keep doing that sorry you do keep
            doing that okay no is this compost really we're all
            compost if you think about it pretty much everything is
            made up of organic matter and will return",
          "confidence": 0.9251011
        }
      ]
    }
  ]
}

Go

Para aprender a instalar e usar a biblioteca de cliente do Speech-to-Text, consulte Bibliotecas de cliente do Speech-to-Text. Para mais informações, consulte a documentação de referência da API Speech-to-Text Go.

Para se autenticar no Speech-to-Text, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.


func modelSelection(w io.Writer) error {
	ctx := context.Background()

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

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

	req := &speechpb.RecognizeRequest{
		Config: &speechpb.RecognitionConfig{
			Encoding:        speechpb.RecognitionConfig_LINEAR16,
			SampleRateHertz: 16000,
			LanguageCode:    "en-US",
			Model:           "video",
		},
		Audio: &speechpb.RecognitionAudio{
			AudioSource: &speechpb.RecognitionAudio_Content{Content: data},
		},
	}

	resp, err := client.Recognize(ctx, req)
	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

Para aprender a instalar e usar a biblioteca de cliente do Speech-to-Text, consulte Bibliotecas de cliente do Speech-to-Text. Para mais informações, consulte a documentação de referência da API Speech-to-Text Java.

Para se autenticar no Speech-to-Text, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

/**
 * Performs transcription of the given audio file synchronously with the selected model.
 *
 * @param fileName the path to a audio file to transcribe
 */
public static void transcribeModelSelection(String fileName) throws Exception {
  Path path = Paths.get(fileName);
  byte[] content = Files.readAllBytes(path);

  try (SpeechClient speech = SpeechClient.create()) {
    // Configure request with video media type
    RecognitionConfig recConfig =
        RecognitionConfig.newBuilder()
            // encoding may either be omitted or must match the value in the file header
            .setEncoding(AudioEncoding.LINEAR16)
            .setLanguageCode("en-US")
            // sample rate hertz may be either be omitted or must match the value in the file
            // header
            .setSampleRateHertz(16000)
            .setModel("video")
            .build();

    RecognitionAudio recognitionAudio =
        RecognitionAudio.newBuilder().setContent(ByteString.copyFrom(content)).build();

    RecognizeResponse recognizeResponse = speech.recognize(recConfig, recognitionAudio);
    // Just print the first result here.
    SpeechRecognitionResult result = recognizeResponse.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());
  }
}

Node.js

Para aprender a instalar e usar a biblioteca de cliente do Speech-to-Text, consulte Bibliotecas de cliente do Speech-to-Text. Para mais informações, consulte a documentação de referência da API Speech-to-Text Node.js.

Para se autenticar no Speech-to-Text, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

// Imports the Google Cloud client library for Beta API
/**
 * TODO(developer): Update client library import to use new
 * version of API when desired features become available
 */
const speech = require('@google-cloud/speech').v1p1beta1;
const fs = require('fs');

// 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 model = 'Model to use, e.g. phone_call, video, default';
// 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,
  sampleRateHertz: sampleRateHertz,
  languageCode: languageCode,
  model: model,
};
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

Para aprender a instalar e usar a biblioteca de cliente do Speech-to-Text, consulte Bibliotecas de cliente do Speech-to-Text. Para mais informações, consulte a documentação de referência da API Speech-to-Text Python.

Para se autenticar no Speech-to-Text, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

from google.cloud import speech

# Instantiates a client
client = speech.SpeechClient()
# Reads a file as bytes
with open("resources/Google_Gnome.wav", "rb") as f:
    audio_content = f.read()

audio = speech.RecognitionAudio(content=audio_content)

config = speech.RecognitionConfig(
    encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
    sample_rate_hertz=16000,
    language_code="en-US",
    model="video",  # Chosen model
)

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}")

Linguagens adicionais

C#: siga as instruções de configuração do C# na página das bibliotecas de cliente e, em seguida, acesse a documentação de referência do Speech-to-Text para .NET.

PHP: siga as instruções de configuração do PHP na página das bibliotecas de cliente e, em seguida, acesse a documentação de referência do Speech-to-Text para PHP.

Ruby: siga as instruções de configuração do Ruby na página das bibliotecas de cliente e, em seguida, acesse a documentação de referência do Speech-to-Text para Ruby.

Solicitação de arquivo remoto

Go

Para aprender a instalar e usar a biblioteca de cliente do Speech-to-Text, consulte Bibliotecas de cliente do Speech-to-Text. Para mais informações, consulte a documentação de referência da API Speech-to-Text Go.

Para se autenticar no Speech-to-Text, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.


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

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

// transcribe_model_selection_gcs Transcribes the given audio file asynchronously with
// the selected model.
func transcribe_model_selection_gcs(w io.Writer) error {
	ctx := context.Background()

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

	audio := &speechpb.RecognitionAudio{
		AudioSource: &speechpb.RecognitionAudio_Uri{Uri: "gs://cloud-samples-tests/speech/Google_Gnome.wav"},
	}

	// The speech recognition model to use
	// See, https://cloud.google.com/speech-to-text/docs/speech-to-text-requests#select-model
	recognitionConfig := &speechpb.RecognitionConfig{
		Encoding:        speechpb.RecognitionConfig_LINEAR16,
		SampleRateHertz: 16000,
		LanguageCode:    "en-US",
		Model:           "video",
	}

	longRunningRecognizeRequest := &speechpb.LongRunningRecognizeRequest{
		Config: recognitionConfig,
		Audio:  audio,
	}

	operation, err := client.LongRunningRecognize(ctx, longRunningRecognizeRequest)
	if err != nil {
		return fmt.Errorf("error running recognize %w", err)
	}

	response, err := operation.Wait(ctx)
	if err != nil {
		return err
	}
	for i, result := range response.Results {
		alternative := result.Alternatives[0]
		fmt.Fprintf(w, "%s\n", strings.Repeat("-", 20))
		fmt.Fprintf(w, "First alternative of result %d", i)
		fmt.Fprintf(w, "Transcript: %s", alternative.Transcript)
	}
	return nil
}

Java

Para aprender a instalar e usar a biblioteca de cliente do Speech-to-Text, consulte Bibliotecas de cliente do Speech-to-Text. Para mais informações, consulte a documentação de referência da API Speech-to-Text Java.

Para se autenticar no Speech-to-Text, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

/**
 * Performs transcription of the remote audio file asynchronously with the selected model.
 *
 * @param gcsUri the path to the remote audio file to transcribe.
 */
public static void transcribeModelSelectionGcs(String gcsUri) throws Exception {
  try (SpeechClient speech = SpeechClient.create()) {

    // Configure request with video media type
    RecognitionConfig config =
        RecognitionConfig.newBuilder()
            // encoding may either be omitted or must match the value in the file header
            .setEncoding(AudioEncoding.LINEAR16)
            .setLanguageCode("en-US")
            // sample rate hertz may be either be omitted or must match the value in the file
            // header
            .setSampleRateHertz(16000)
            .setModel("video")
            .build();

    RecognitionAudio audio = RecognitionAudio.newBuilder().setUri(gcsUri).build();

    // Use non-blocking call for getting file transcription
    OperationFuture<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response =
        speech.longRunningRecognizeAsync(config, audio);

    while (!response.isDone()) {
      System.out.println("Waiting for response...");
      Thread.sleep(10000);
    }

    List<SpeechRecognitionResult> results = response.get().getResultsList();

    // Just print the first result here.
    SpeechRecognitionResult result = results.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());
  }
}

Node.js

Para aprender a instalar e usar a biblioteca de cliente do Speech-to-Text, consulte Bibliotecas de cliente do Speech-to-Text. Para mais informações, consulte a documentação de referência da API Speech-to-Text Node.js.

Para se autenticar no Speech-to-Text, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

// Imports the Google Cloud client library for Beta API
/**
 * TODO(developer): Update client library import to use new
 * version of API when desired features become available
 */
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 gcsUri = 'gs://my-bucket/audio.raw';
// const model = 'Model to use, e.g. phone_call, video, default';
// 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,
  sampleRateHertz: sampleRateHertz,
  languageCode: languageCode,
  model: model,
};
const audio = {
  uri: gcsUri,
};

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

Para aprender a instalar e usar a biblioteca de cliente do Speech-to-Text, consulte Bibliotecas de cliente do Speech-to-Text. Para mais informações, consulte a documentação de referência da API Speech-to-Text Python.

Para se autenticar no Speech-to-Text, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

from google.cloud import speech

client = speech.SpeechClient()

audio = speech.RecognitionAudio(
    uri="gs://cloud-samples-tests/speech/Google_Gnome.wav"
)

config = speech.RecognitionConfig(
    encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
    sample_rate_hertz=16000,
    language_code="en-US",
    model="video",  # Chosen model
)

operation = client.long_running_recognize(config=config, audio=audio)

print("Waiting for operation to complete...")
response = operation.result(timeout=90)

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}")

Linguagens adicionais

C#: siga as instruções de configuração do C# na página das bibliotecas de cliente e, em seguida, acesse a documentação de referência do Speech-to-Text para .NET.

PHP: siga as instruções de configuração do PHP na página das bibliotecas de cliente e, em seguida, acesse a documentação de referência do Speech-to-Text para PHP.

Ruby: siga as instruções de configuração do Ruby na página das bibliotecas de cliente e, em seguida, acesse a documentação de referência do Speech-to-Text para Ruby.

Limpeza

Para evitar cobranças na sua conta do Google Cloud pelos recursos usados neste tutorial, exclua o projeto que os contém ou mantenha o projeto e exclua os recursos individuais.

Excluir o projeto

O jeito mais fácil de evitar cobranças é excluindo o projeto que você criou para o tutorial.

Para excluir o projeto:

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

Excluir instâncias

Para excluir uma instância do Compute Engine:

  1. In the Google Cloud console, go to the VM instances page.

    Go to VM instances

  2. Select the checkbox for the instance that you want to delete.
  3. To delete the instance, click More actions, click Delete, and then follow the instructions.

Excluir as regras de firewall da rede padrão

Para excluir uma regra de firewall:

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

    Go to Firewall

  2. Select the checkbox for the firewall rule that you want to delete.
  3. To delete the firewall rule, click Delete.

A seguir

Faça um teste

Se você ainda não conhece o Google Cloud, crie uma conta para avaliar o desempenho do Speech-to-Text em cenários reais. Clientes novos também recebem US$ 300 em créditos sem custos para executar, testar e implantar cargas de trabalho.

Faça um teste do Speech-to-Text sem custos financeiros