尝试验证Google Cloud Platform(GCP)以使用语音文本APi

时间:2019-06-25 14:46:28

标签: python google-cloud-platform speech-to-text

我正在尝试使用Google Cloud Platform(GCP)来实现python语音文本API的功能,但是由于某些原因,我似乎无法访问GCP来使用该API。如何验证我的凭据?

我尝试按照google提供的说明对我的凭据进行身份验证,但是我迷路了,因为似乎没有任何操作。

我已经创建了一个GCP项目,设置了帐单信息,启用了API,并创建了服务帐户,没有任何问题。

我尝试使用命令行将环境设置为set GOOGLE_APPLICATION_CREDENTIALS=[PATH]

,然后运行直接从Google教程页面获取的以下代码:

def transcribe_streaming(stream_file):
    """Streams transcription of the given audio file."""
    from google.cloud import speech
    from google.cloud.speech import enums
    from google.cloud.speech import types
    client = speech.SpeechClient()

    with io.open(stream_file, 'rb') as audio_file:
        content = audio_file.read()

    # In practice, stream should be a generator yielding chunks of audio data.
    stream = [content]
    requests = (types.StreamingRecognizeRequest(audio_content=chunk)
                for chunk in stream)

    config = types.RecognitionConfig(
        encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,
        sample_rate_hertz=16000,
        language_code='en-US')
    streaming_config = types.StreamingRecognitionConfig(config=config)

    # streaming_recognize returns a generator.
    responses = client.streaming_recognize(streaming_config, requests)

    for response in responses:
        # Once the transcription has settled, the first result will contain the
        # is_final result. The other results will be for subsequent portions of
        # the audio.
        for result in response.results:
            print('Finished: {}'.format(result.is_final))
            print('Stability: {}'.format(result.stability))
            alternatives = result.alternatives
            # The alternatives are ordered from most likely to least.
            for alternative in alternatives:
                print('Confidence: {}'.format(alternative.confidence))
                print(u'Transcript: {}'.format(alternative.transcript))

我收到以下错误消息:

DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started

2 个答案:

答案 0 :(得分:0)

您也可以直接在脚本中设置凭据

from google.oauth2 import service_account
credentials = service_account.Credentials.from_service_account_file("/path/to/your/crendentials.json")
client = speech.SpeechClient(credentials=credentials)

答案 1 :(得分:0)

您可能未正确设置服务帐户json文件的路径:

第1步:将服务帐户json文件下载到本地计算机上,假设为credentials.json

第2步:运行set GOOGLE_APPLICATION_CREDENTIALS=path_to_credentials.json,例如set GOOGLE_APPLICATION_CREDENTIALS=C:\MY_DATA\work\credentials.json

注意:像这样设置环境变量仅对当前cmd会话有效,如果您打开一个新的会话,请再次设置该变量