Google 自然语言预测示例

时间:2021-04-13 10:19:49

标签: python google-api nlp data-science google-natural-language

我是 Python 新手。已经训练了自定义的 Google 自然语言模型并尝试执行 google 提供的示例。

import sys
import os

from google.api_core.client_options import ClientOptions
from google.cloud import automl


os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="my_service_account.json"

def inline_text_payload(file_path):
  with open(file_path, 'rb') as ff:
    content = ff.read()
  return {'text_snippet': {'content': content, 'mime_type': 'text/plain'} }

def get_prediction(file_path, model_name):
  options = ClientOptions(api_endpoint='eu-automl.googleapis.com')
  prediction_client = automl.PredictionServiceClient(client_options=options)

  payload = inline_text_payload(file_path)

  params = {}
  request = prediction_client.predict(model_name, payload, params)
  return request  # waits until request is returned

if __name__ == '__main__':
  file_path = sys.argv[1]
  model_name = sys.argv[2]

  print(get_prediction(file_path, model_name))

通过执行此代码,我收到错误:

Traceback (most recent call last):
  File "predict.py", line 33, in <module>
    print(get_prediction(file_path, model_name))
  File "predict.py", line 26, in get_prediction
    request = prediction_client.predict(model_name, payload, params)
TypeError: predict() takes from 1 to 2 positional arguments but 4 were given

我进行了多次搜索,但似乎无法找到问题所在。如果任何有经验的人可以看看并指出正确的方向,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

]更新]

不得不改写 prediction_client.predict 参数。工作代码:

import sys

from google.api_core.client_options import ClientOptions
from google.cloud import automl
import os

os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="my_service_account.json"

def inline_text_payload(file_path):
  with open(file_path, 'rb') as ff:
    content = ff.read()
  return {'text_snippet': {'content': content, 'mime_type': 'text/plain'} }

def pdf_payload(file_path):
  return {'document': {'input_config': {'gcs_source': {'input_uris': [file_path] } } } }

def get_prediction(file_path, model_name):
  options = ClientOptions(api_endpoint='eu-automl.googleapis.com')
  prediction_client = automl.PredictionServiceClient(client_options=options)

  payload = inline_text_payload(file_path)

  params = {}
  request = prediction_client.predict(name=model_name, payload=payload, params=params)
  return request  # waits until request is returned

if __name__ == '__main__':
  file_path = sys.argv[1]
  model_name = sys.argv[2]

  print(get_prediction(file_path, model_name))