Skip to content

Instantly share code, notes, and snippets.

@foohm71
Created July 27, 2020 01:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save foohm71/5dc9f1a6b1b76c9fc021737090c7e155 to your computer and use it in GitHub Desktop.
Save foohm71/5dc9f1a6b1b76c9fc021737090c7e155 to your computer and use it in GitHub Desktop.
AppEngine code
# [START gae_python38_app]
from flask import Flask, request
import sys
import os
from google.api_core.client_options import ClientOptions
from google.cloud import automl_v1
from google.cloud.automl_v1.proto import service_pb2
# If `entrypoint` is not defined in app.yaml, App Engine will look for an app
# called `app` in `main.py`.
app = Flask(__name__)
model_name = "projects/157961863513/locations/us-central1/models/TCN7663932496156819456"
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = "./octopus-282815-fd31678fbf06.json"
def inline_text_payload(content):
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(content, model_name):
options = ClientOptions(api_endpoint='automl.googleapis.com')
prediction_client = automl_v1.PredictionServiceClient(client_options=options)
payload = inline_text_payload(content)
# Uncomment the following line (and comment the above line) if want to predict on PDFs.
# payload = pdf_payload(file_path)
params = {}
request = prediction_client.predict(model_name, payload, params)
return request # waits until request is returned
@app.route('/')
def hello():
"""Return a friendly HTTP greeting."""
return 'Hello World!'
@app.route("/predict", methods=["GET","POST"])
def predict():
if request.method == "GET":
return "Please send Post Request"
elif request.method == "POST":
data = request.get_json()
app.logger.info("%s was obtained", str(data))
title = data['title']
description = data['description']
app.logger.info("description = %s", str(description))
app.logger.info("title = %s", str(title))
sentence = str(title) + " " + str(description)
app.logger.info("sentence = %s", sentence)
pred = get_prediction(sentence, model_name)
prediction = pred.payload[0].display_name
score = pred.payload[0].classification.score
app.logger.info("prediction = %s score = %.3f", prediction, score)
return { 'statusCode': 200, 'prediction': prediction, 'score': score }
if __name__ == '__main__':
# This is used when running locally only. When deploying to Google App
# Engine, a webserver process such as Gunicorn will serve the app. This
# can be configured by adding an `entrypoint` to app.yaml.
app.run(host='127.0.0.1', port=8080, debug=True)
# [END gae_python38_app]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment