Teste a Speech-to-Text

Neste guia, mostramos o processo de execução de um teste de conversão Speech-to-Text usando o serviço Vertex AI Speech do Google.

Antes de testar essa amostra, siga as instruções de configuração para Python no Guia de início rápido da Vertex AI: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Python da Vertex AI.

  1. Crie um arquivo Python speech-to-text-test.py. Substitua o valor image_uri_to_test pelo URI de uma imagem de origem, conforme mostrado:

    from google.cloud import speech
    
    def transcribe_gcs_audio(gcs_uri: str) -> speech.RecognizeResponse:
        client = speech.SpeechClient()
    
        audio = speech.RecognitionAudio(uri=gcs_uri)
        config = speech.RecognitionConfig(
            encoding=speech.RecognitionConfig.AudioEncoding.FLAC,
            sample_rate_hertz=16000,
            language_code="en-US", # Specify the language code (e.g., "en-US" for US English)
            # You can add more features here, e.g.:
            # enable_automatic_punctuation=True,
            # model="default" # or "latest_long", "phone_call", "video", "chirp" (v2 API)
        )
    
        # Performs synchronous speech recognition on the audio file
        response = client.recognize(config=config, audio=audio)
    
        # Print the transcription
        for result in response.results:
            print(f"Transcript: {result.alternatives[0].transcript}")
            if result.alternatives[0].confidence:
                print(f"Confidence: {result.alternatives[0].confidence:.2f}")
    
        return response
    
    if __name__ == "__main__":
        # Replace with the URI of your audio file in Google Cloud Storage
        audio_file_uri = "AUDIO_FILE_URI"
    
        print(f"Transcribing audio from: {audio_file_uri}")
        transcribe_gcs_audio(audio_file_uri)
    

    Substitua:

    • AUDIO_FILE_URI: o URI de um arquivo de áudio "gs://your-bucket/your-image.png"
  2. Crie um Dockerfile:

    ROM python:3.9-slim
    
    WORKDIR /app
    
    COPY speech-to-text-test.py /app/
    
    # Install 'requests' for HTTP calls
    RUN pip install --no-cache-dir requests
    
    CMD ["python", "speech-to-text-test.py"]
    
  3. Crie a imagem do Docker para o aplicativo Speech-to-Text:

    docker build -t speech-to-text-app .
    
  4. Siga as instruções em Configurar o Docker para:

    1. Configure o Docker.
    2. Crie um secret e
    3. Faça upload da imagem para o HaaS.
  5. Faça login no cluster de usuário e gere o arquivo kubeconfig com uma identidade de usuário. Verifique se você definiu o caminho do kubeconfig como uma variável de ambiente:

    export KUBECONFIG=${CLUSTER_KUBECONFIG_PATH}
    
  6. Execute o seguinte comando no terminal, colando sua chave de API, para criar um secret do Kubernetes:

    kubectl create secret generic gcp-api-key-secret \
      --from-literal=GCP_API_KEY='PASTE_YOUR_API_KEY_HERE'
    

    Esse comando cria um secret chamado gcp-api-key-secret com uma chave GCP_API_KEY.

  7. Aplique o manifesto do Kubernetes:

    apiVersion: batch/v1
    kind: Job
    metadata:
      name: speech-to-text-test-job
    spec:
      template:
        spec:
          containers:
          - name: speech-to-text-test-container
            image: HARBOR_INSTANCE_URL/HARBOR_PROJECT/speech-to-text-app:latest # Your image path
            # Mount the API key from the secret into the container
            # as an environment variable named GCP_API_KEY.
            imagePullSecrets:
            - name: SECRET
            envFrom:
            - secretRef:
                name: gcp-api-key-secret
          restartPolicy: Never
      backoffLimit: 4
    
    

    Substitua:

    • HARBOR_INSTANCE_URL: o URL da instância do Harbor.
    • HARBOR_PROJECT: o projeto do Harbor.
    • SECRET: o nome do secret criado para armazenar credenciais do Docker.
  8. Verifique o status do job:

    kubectl get jobs/speech-to-text-test-job
    # It will show 0/1 completions, then 1/1 after it succeeds
    
  9. Depois que o job for concluído, será possível conferir a saída nos registros do pod:

    kubectl logs -l job-name=speech-to-text-test-job