pythongoogle-apinlpdata-sciencegoogle-natural-language

Googe Natural Language predict example


Im new to python. Have already trained custom Google Natural Language model and trying to execute example provided by 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))

By executing this code I receive error:

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

I've done multiple searches, but cant seem to find what is the issue. If anybody experienced could take a look and maybe point me to the right direction, I would higly appreciate it.


Solution

  • ]UPDATE]

    Had to rephrase prediction_client.predict params. Working code:

    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))