Google应用程序凭据出现问题

时间:2019-04-16 07:38:38

标签: python api authentication google-vision

首先,您好,这是我第一次使用Google服务。我正在尝试使用Google AutoML Vision Api(自定义模型)开发应用程序。我已经建立了一个自定义模型并生成了API密钥(我希望这样做是正确的)。

经过多次尝试通过Ionics和Android开发,但未连接到API。

我现在已经在Google Colab上使用Python(在Google 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

1 个答案:

答案 0 :(得分: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)

请注意,尽管我尚未对此进行测试,所以请尝试一下,看看它是否确实有效。