Transcribe audio from a video file using 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ê usará os seguintes componentes faturáveis do Google Cloud:

  • Speech-to-Text

Para gerar uma estimativa de custo baseada na projeção de uso deste tutorial, use a calculadora de preços. Novos usuários do Google Cloud podem estar qualificados para uma avaliação gratuita.

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 seguinte comando para fazer o upload do arquivo de áudio para um bucket do Cloud Storage usando a ferramenta gsutil.

gsutil 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

Envie uma solicitação de transcrição

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

Solicitação de arquivo local

Protocolo

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

Para executar o reconhecimento de fala síncrono, faça uma solicitação POST e forneça o corpo apropriado a ela. Veja 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 da Speech-to-Text, consulte Bibliotecas de cliente da Speech-to-Text. Para mais informações, consulte a documentação de referência da API Speech-to-Text Go.

Para 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, 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/Google_Gnome.wav"
	data, err := ioutil.ReadFile(path)
	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 da Speech-to-Text, consulte Bibliotecas de cliente da Speech-to-Text. Para mais informações, consulte a documentação de referência da API Speech-to-Text Java.

Para 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 da Speech-to-Text, consulte Bibliotecas de cliente da Speech-to-Text. Para mais informações, consulte a documentação de referência da API Speech-to-Text Node.js.

Para 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 da Speech-to-Text, consulte Bibliotecas de cliente da Speech-to-Text. Para mais informações, consulte a documentação de referência da API Speech-to-Text Python.

Para 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.

def transcribe_model_selection(
    speech_file: str,
    model: str,
) -> speech.RecognizeResponse:
    """Transcribe the given audio file synchronously with
    the selected model."""
    client = speech.SpeechClient()

    with open(speech_file, "rb") as audio_file:
        content = audio_file.read()

    audio = speech.RecognitionAudio(content=content)

    config = speech.RecognitionConfig(
        encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
        sample_rate_hertz=16000,
        language_code="en-US",
        model=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}")

    return response

Outras linguagens

C#: Siga as Instruções de configuração do C# na página das bibliotecas de cliente e acesse Documentação de referência da Speech-to-Text para .NET.

PHP: Siga as Instruções de configuração do PHP na página das bibliotecas de cliente e acesse Documentação de referência da Speech-to-Text para PHP.

Ruby: Siga as Instruções de configuração do Ruby na página das bibliotecas de cliente e acesse Documentação de referência da Speech-to-Text para Ruby.

Solicitação de arquivo remoto

Go

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

Para 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, gcsUri string, model string) error {
	// Google Cloud Storage URI pointing to the audio content.
	// gcsUri := "gs://bucket-name/path_to_audio_file"

	// The speech recognition model to use
	// See, https://cloud.google.com/speech-to-text/docs/speech-to-text-requests#select-model
	// model := "default"
	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: gcsUri},
	}

	recognitionConfig := &speechpb.RecognitionConfig{
		Encoding:        speechpb.RecognitionConfig_LINEAR16,
		SampleRateHertz: 16000,
		LanguageCode:    "en-US",
		Model:           model,
	}

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

	operation, err := client.LongRunningRecognize(ctx, longRunningRecognizeRequest)
	if err != nil {
		return fmt.Errorf("error running recognize %v", 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 da Speech-to-Text, consulte Bibliotecas de cliente da Speech-to-Text. Para mais informações, consulte a documentação de referência da API Speech-to-Text Java.

Para 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 da Speech-to-Text, consulte Bibliotecas de cliente da Speech-to-Text. Para mais informações, consulte a documentação de referência da API Speech-to-Text Node.js.

Para 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 da Speech-to-Text, consulte Bibliotecas de cliente da Speech-to-Text. Para mais informações, consulte a documentação de referência da API Speech-to-Text Python.

Para 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.

def transcribe_model_selection_gcs(
    gcs_uri: str,
    model: str,
) -> speech.RecognizeResponse:
    """Transcribe the given audio file asynchronously with
    the selected model."""
    from google.cloud import speech

    client = speech.SpeechClient()

    audio = speech.RecognitionAudio(uri=gcs_uri)

    config = speech.RecognitionConfig(
        encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
        sample_rate_hertz=16000,
        language_code="en-US",
        model=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}")

    return response

Outras linguagens

C#: Siga as Instruções de configuração do C# na página das bibliotecas de cliente e acesse Documentação de referência da Speech-to-Text para .NET.

PHP: Siga as Instruções de configuração do PHP na página das bibliotecas de cliente e acesse Documentação de referência da Speech-to-Text para PHP.

Ruby: Siga as Instruções de configuração do Ruby na página das bibliotecas de cliente e acesse Documentação de referência da Speech-to-Text para Ruby.

Limpeza

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

Exclua o projeto

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

Para excluir o projeto:

  1. No Console do Google Cloud, acesse a página Gerenciar recursos.

    Acessar "Gerenciar recursos"

  2. Na lista de projetos, selecione o projeto que você quer excluir e clique em Excluir .
  3. Na caixa de diálogo, digite o ID do projeto e clique em Encerrar para excluí-lo.

Excluir instâncias

Para excluir uma instância do Compute Engine:

  1. No Console do Google Cloud, acesse a página Instâncias de VMs.

    Acessar instâncias de VM

  2. Marque a caixa de seleção de a instância que você quer excluir.
  3. Para excluir a instância, clique em Mais ações, clique em Excluir e siga as instruções.

Excluir regras de firewall para a 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 da Speech-to-Text em cenários reais. Clientes novos também recebem US$ 300 em créditos para executar, testar e implantar cargas de trabalho.

Faça um teste gratuito da Speech-to-Text