0

我正在尝试将用于 AI 平台(统一)的 Google Python 客户端“包装”到云函数中。

import json
from google.cloud import aiplatform
from google.protobuf import json_format
from google.protobuf.struct_pb2 import Value

def infer(request):
    """Responds to any HTTP request.
    Args:
        request (flask.Request): HTTP request object.
    Returns:
        The response text or any set of values that can be turned into a
        Response object using
        `make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>`.
    """
    request_json = request.get_json()

    project="simple-1234"
    endpoint_id="7106293183897665536"
    location="europe-west4"

    api_endpoint = "europe-west4-aiplatform.googleapis.com"

    # The AI Platform services require regional API endpoints.
    client_options = {"api_endpoint": api_endpoint}
    # Initialize client that will be used to create and send requests.
    # This client only needs to be created once, and can be reused for multiple requests.
    client = aiplatform.gapic.PredictionServiceClient(client_options=client_options)
    # for more info on the instance schema, please use get_model_sample.py
    # and look at the yaml found in instance_schema_uri

    endpoint = client.endpoint_path(
        project=project, location=location, endpoint=endpoint_id
    )

    instance = request.json["instances"]
    instances = [instance]

    parameters_dict = {}
    parameters = json_format.ParseDict(parameters_dict, Value())
    
    try:
        response = client.predict(endpoint=endpoint, instances=instances, parameters=parameters)
        if 'error' in response:
            return (json.dumps({"msg": 'Error during prediction'}), 500)
    except Exception as e:
        print("Exception when calling predict: ", e)
        return (json.dumps({"msg": 'Exception when calling predict'}), 500)
    
    print(" deployed_model_id:", response.deployed_model_id)
    # See gs://google-cloud-aiplatform/schema/predict/prediction/tables_classification.yaml for the format of the predictions.
    predictions = response.predictions
    for prediction in predictions:
        print(" prediction:", dict(prediction))
    return (json.dumps({"prediction": response['predictions']}), 200)

打电话时出现client.predict()异常400

{"error": "Required property Values is not found"}

我究竟做错了什么?

4

1 回答 1

0

我相信您的parameters变量不正确,在文档示例中,变量设置如下,例如:

parameters = predict.params.ImageClassificationPredictionParams(
                 confidence_threshold=0.5, max_predictions=5,
             ).to_value()

这可能就是错误提示找不到属性的原因。您必须设置自己的参数,然后调用 predict 方法。

于 2021-06-01T14:53:11.697 回答