Skip to content
This repository has been archived by the owner on Aug 3, 2022. It is now read-only.

Commit

Permalink
Update to use Python 3, App Egine Flex and Dialogflow API V2
Browse files Browse the repository at this point in the history
Change-Id: Ide235fb43c14f66257fa8d6c0b852347a155ef4f
  • Loading branch information
Matt Carroll committed Apr 16, 2018
1 parent a67751d commit 9a79fc7
Show file tree
Hide file tree
Showing 8 changed files with 76 additions and 41 deletions.
1 change: 1 addition & 0 deletions .gitignore
@@ -1,2 +1,3 @@
*.pyc
.DS_Store

49 changes: 33 additions & 16 deletions README.md
@@ -1,21 +1,38 @@
# API.AI Webhook Translation Sample for Python (Flask)
========================================================
# Dialogflow Fulfillment Translation Sample for Python (Flask)
==============================================================
## Setup Instructions
# Pre-requisites
1. API.AI Agent: Create an account on API.AI and import or restore the agent in <code>translation_agent.zip</code> for your agent (or create a new one)
2. Set the fulfillment URL to the URL of the server on which this sample will be hosted and append <code>/webhook</code>
3. Get a Google Translate API key, by following the first 4 steps of the getting started guide [https://cloud.google.com/translate/docs/getting-started](https://cloud.google.com/translate/docs/getting-started) when you get to step 4 (creating credentials) for the credential type choose "API Key" and fill in the API key in <code>API_KEY</code> in <code>app.py</code>
# Steps:
4. Run <code>pip install requirements.txt</code>
5. Run <code>python app.py</code>
6. Test the responses in API.AI
## Documentation
* API.AI Translate Webhook: [https://docs.api.ai/docs/webhook#webhook-example]
## References and How to report bugs

### Dialogflow Setup
1. Create an account on Dialogflow
1. Create a new Dialogflow agent
1. Restore the `dialogflow-agent.zip` ZIP file in the root of this repo
1. Go to your agent's settings and then the *Export and Import* tab
1. Click the *Restore from ZIP* button
1. Select the `dialogflow-agent.zip` ZIP file in the root of this repo
1. Type *RESTORE* and and click the *Restore* button

### Fulfillment Setup
1. Click on the Google Cloud project ID in your agent's setting to open the Google Cloud console
1. Enable the [Google Cloud Translation API](http://console.cloud.google.com/apis/library/translate.googleapis.com/)
1. [Create an API key](https://cloud.google.com/docs/authentication/api-keys#creating_an_api_key) and copy the value into the `API_KEY` varible in `main.py` and save the file
1. Run `pip install -r requirements.txt`
1. Deploy fulfillment to App Engine
1. [Download and authenticate the Google Cloud SDK](https://cloud.google.com/sdk/docs/quickstart-macos)
1. Run `gcloud app deploy`, make a note of the service URL, which will be used in the next step
1. Set the fulfillment URL in Dialogflow to your App Engine service URL
1. Go to your [agent's fulfillment page](https://console.dialogflow.com/api-client/#/agent//fulfillment)
1. Click the switch to enable webhook for your agent
1. Enter you App Engine service URL and append `/webhook` (e.g. `https://translate-10929.appspot.com/webhook`) to the URL field
1. Click *Save* at the bottom of the page

## How to report bugs
* If you find any issues, please open a bug here on GitHub
How to make contributions?

## How to make contributions?
Please read and follow the steps in the CONTRIBUTING.md
License

## License
See LICENSE.md

## Terms
Your use of this sample is subject to, and by using or downloading the sample files you agree to comply with, the [Google APIs Terms of Service](https://developers.google.com/terms/) and the [API.AI's Terms of Use and Privacy Policy](https://api.ai/terms/).
Your use of this sample is subject to, and by using or downloading the sample files you agree to comply with, the [Google APIs Terms of Service](https://developers.google.com/terms/) and the [Dialogflow's Terms of Use and Privacy Policy](https://dialogflow.com/terms/).
17 changes: 17 additions & 0 deletions app.yaml
@@ -0,0 +1,17 @@
runtime: python
env: flex
entrypoint: gunicorn -b :$PORT main:app

runtime_config:
python_version: 3

# This sample incurs costs to run on the App Engine flexible environment.
# The settings below are to reduce costs during testing and are not appropriate
# for production use. For more information, see:
# https://cloud.google.com/appengine/docs/flexible/python/configuring-your-app-with-app-yaml
manual_scaling:
instances: 1
resources:
cpu: 1
memory_gb: 0.5
disk_size_gb: 10
Binary file added dialogflow-agent.zip
Binary file not shown.
4 changes: 2 additions & 2 deletions language_list.py
Expand Up @@ -13,9 +13,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.

"""This is a sample for a translation fulfillment webhook for an API.AI agent
"""This is a sample for a translation fulfillment webhook for an Dialogflow agent
This is meant to be used with the sample translate agent for API.AI, it uses
This is meant to be used with the sample translate agent for Dialogflow, it uses
the Google Cloud Translation API and requires an API key from an API project
with the Google Cloud Translation API enabled.
"""
Expand Down
41 changes: 20 additions & 21 deletions app.py → main.py
Expand Up @@ -13,17 +13,17 @@
# See the License for the specific language governing permissions and
# limitations under the License.

"""This is a sample for a translation fulfillment webhook for an API.AI agent
"""This is a sample for a translation fulfillment webhook for an Dialogflow agent
This is meant to be used with the sample translate agent for API.AI, it uses
This is meant to be used with the sample translate agent for Dialogflow, it uses
the Google Cloud Translation API and requires an API key from an API project
with the Google Cloud Translation API enabled.
"""

import json
import random
from httplib import HTTPException
from urllib2 import HTTPError, URLError
from http.client import HTTPException
from urllib.error import HTTPError, URLError

from flask import Flask, jsonify, make_response, request
from googleapiclient.discovery import build
Expand All @@ -40,41 +40,40 @@
# 1. Go to console.google.com create or use an existing project
# 2. Enable the Cloud Translation API in the console for your project
# 3. Create an API key in the credentials tab and paste it below
API_KEY = 'PUT GOOGLE DEVELOPER KEY HERE'
API_KEY = '<PASTE_API_KEY_HERE>'
TRANSLATION_SERVICE = build('translate', 'v2', developerKey=API_KEY)

APP = Flask(__name__)
LOG = APP.logger
app = Flask(__name__)
log = app.logger


@APP.route('/webhook', methods=['POST'])
@app.route('/webhook', methods=['POST'])
def webhook():
"""This method handles the http requests for the API.AI webhook
"""This method handles the http requests for the Dialogflow webhook
This is meant to be used in conjunction with the translate API.AI agent
This is meant to be used in conjunction with the translate Dialogflow agent
"""

# Get request parameters
req = request.get_json(silent=True, force=True)
action = req.get('result').get('action')
req = request.get_json(force=True)
action = req.get('queryResult').get('action')

# Check if the request is for the translate action
if action == 'translate.text':
# Get the parameters for the translation
text = req['result']['parameters'].get('text')
source_lang = req['result']['parameters'].get('lang-from')
target_lang = req['result']['parameters'].get('lang-to')
text = req['queryResult']['parameters'].get('text')
source_lang = req['queryResult']['parameters'].get('lang-from')
target_lang = req['queryResult']['parameters'].get('lang-to')

# Fulfill the translation and get a response
output = translate(text, source_lang, target_lang)

# Compose the response to API.AI
res = {'speech': output,
'displayText': output,
'contextOut': req['result']['contexts']}
# Compose the response to Dialogflow
res = {'fulfillmentText': output,
'outputContexts': req['queryResult']['outputContexts']}
else:
# If the request is not to the translate.text action throw an error
LOG.error('Unexpected action requested: %s', json.dumps(req))
log.error('Unexpected action requested: %s', json.dumps(req))
res = {'speech': 'error', 'displayText': 'error'}

return make_response(jsonify(res))
Expand Down Expand Up @@ -189,7 +188,7 @@ def validate_language(language):
if __name__ == '__main__':
PORT = 8080

APP.run(
app.run(
debug=True,
port=PORT,
host='0.0.0.0'
Expand Down
5 changes: 3 additions & 2 deletions requirements.txt
@@ -1,2 +1,3 @@
Flask==0.10.1
google-api-python-client==1.4.2
Flask==0.12.2
google-api-python-client==1.6.6
gunicorn==19.7.1
Binary file removed translate_agent.zip
Binary file not shown.

0 comments on commit 9a79fc7

Please sign in to comment.