谷歌云语音api在尝试使用时抛出403

Lic*_*ing 5 python linux google-speech-api

我在谷歌云语音api上使用python我在ubuntu和Windows上的" 如何在python中使用谷歌语音识别api "中执行了所有步骤,当我尝试从这里运行简单脚本时 - " https: //github.com/GoogleCloudPlatform/python-docs-samples/blob/master/speech/api/speech_rest.py "

我收到下一个错误: <HttpError 403 when requesting https://speech.googleapis.com/$discovery/rest?version=v1beta1 returned "Google Cloud Speech API has not been used in project google.com:cloudsdktool before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/speech.googleapis.com/overview?project=google.com:cloudsdktool then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.">

奇怪的是,我没有名为"cloudsdktool"的项目

我运行"gcloud init",并将我在创建服务帐户密钥时获得的json文件与"gcloud auth activate-service-account --key-file = jsonfile"命令相关联,我在linux中尝试创建google凭据环境变量我仍然得到同样的按摩

Lic*_*ing 3

所以我找到了两种方法来解决这个问题:

1 - 如果使用 google cloud sdk 并且云语音处于 beta 版本,您需要运行“gcloud beta init”而不是“gcloud init”,然后提供 json 文件

2 - 如果你不想使用谷歌的云sdk,你可以直接在python应用程序中传递json文件

以下是实现此目的的方法:

from oauth2client.client import GoogleCredentials

GoogleCredentials.from_stream('path/to/your/json')
Run Code Online (Sandbox Code Playgroud)

然后,您只需在信用上创建范围并进行授权,或者如果使用 grpc(streaming),则将其传递到标头,就像示例中一样。

以下是 grpc 的更改脚本:

def make_channel(host, port):
    """Creates an SSL channel with auth credentials from the environment."""
    # In order to make an https call, use an ssl channel with defaults
    ssl_channel = implementations.ssl_channel_credentials(None, None, None)

    # Grab application default credentials from the environment
    creds = GoogleCredentials.from_stream('path/to/your/json').create_scoped([SPEECH_SCOPE])
    # Add a plugin to inject the creds into the header
    auth_header = (
        'Authorization',
        'Bearer ' + creds.get_access_token().access_token)
    auth_plugin = implementations.metadata_call_credentials(
        lambda _, cb: cb([auth_header], None),
        name='google_creds')

    # compose the two together for both ssl and google auth
    composite_channel = implementations.composite_channel_credentials(
        ssl_channel, auth_plugin)

    return implementations.secure_channel(host, port, composite_channel)
Run Code Online (Sandbox Code Playgroud)