Google Application Credentials问题

问题描述 投票:0回答:1

嗨,首先,这是我第一次使用谷歌服务。我正在尝试使用Google AutoML Vision Api(自定义模型)开发应用。我已经构建了一个自定义模型并生成了API密钥(我希望我能正确地完成它)。

在通过Ionics和Android进行多次尝试并且未能连接到API之后。

我现在已经在Python(在谷歌Colab上)给出了给定代码的预测建模,即便如此,我仍然会收到一条错误消息,指出无法自动确定凭据。我不确定我在哪里出错了。请帮忙。奄奄一息。

#installing & importing libraries 

!pip3 install google-cloud-automl

import sys  

from google.cloud import automl_v1beta1
from google.cloud.automl_v1beta1.proto import service_pb2


#import key.json file generated by GOOGLE_APPLICATION_CREDENTIALS
from google.colab import files
credentials = files.upload()


#explicit function given by Google accounts 

[https://cloud.google.com/docs/authentication/production#auth-cloud-implicit-python][1]

def explicit():
from google.cloud import storage

# Explicitly use service account credentials by specifying the private key
# file.
storage_client = storage.Client.from_service_account_json(credentials)

# Make an authenticated API request
buckets = list(storage_client.list_buckets())
print(buckets)




#import image for prediction
from google.colab import files
YOUR_LOCAL_IMAGE_FILE = files.upload()


#prediction code from modelling
def get_prediction(content, project_id, model_id):
prediction_client = automl_v1beta1.PredictionServiceClient()

name = 'projects/{}/locations/uscentral1/models/{}'.format(project_id, 
        model_id)
payload = {'image': {'image_bytes': content }}
params = {}
request = prediction_client.predict(name, payload, params)
return request  # waits till request is returned

#print function substitute with values 
 content = YOUR_LOCAL_IMAGE_FILE
 project_id = "REDACTED_PROJECT_ID"
 model_id = "REDACTED_MODEL_ID"

 print (get_prediction(content, project_id,  model_id))

运行最后一行代码时出现错误消息:

enter image description here

python api authentication google-vision
1个回答
0
投票
credentials = files.upload()
storage_client = storage.Client.from_service_account_json(credentials)

这两行是我认为的问题。第一个实际上加载文件的内容,但第二个期望文件的路径,而不是内容。

让我们首先解决第一行:我看到只是通过调用credentials后得到的credentials = files.upload()将不会像the docs for it中解释的那样工作。就像你正在做的那样,credentials实际上并不直接包含文件的值,而是文件名和内容的字典。

假设您只上传了1个凭证文件,您可以获取该文件的内容,如(stolen from this SO answer)

from google.colab import files
uploaded = files.upload()
credentials_as_string = uploaded[uploaded.keys()[0]]

所以现在我们实际上将上传文件的内容作为字符串,下一步是从中创建一个实际的凭证对象。

This answer on Github演示了如何从转换为json的字符串创建凭证对象。

import json
from google.oauth2 import service_account

credentials_as_dict = json.loads(credentials_as_string)
credentials = service_account.Credentials.from_service_account_info(credentials_as_dict)

最后,我们可以使用此凭证对象创建存储客户端对象:

storage_client = storage.Client(credentials=credentials)

请注意我虽然没有测试过,所以请试一试,看看它是否真的有效。

© www.soinside.com 2019 - 2024. All rights reserved.