Add Image Recognition to your Chatbot with Google Dialogflow and Vision API | by Priyanka Vergadia | Towards Data Science

Conversational AI use cases are diverse. They include customer support, e-commerce, controlling IoT devices, enterprise productivity and much more. In very simplistic terms, these use cases involve a user asking a specific question (intent) and the conversational experience (or the chatbot) responding to the question by making calls to a backend system like a CRM, Database or an API. These “intents” are identified by utilizing Natural Language Processing (NLP) and the Machine Learning (ML).
It turns out that some of these use cases can be enriched by allowing a user to upload an image. In such cases, you would want the conversation experience to take an action based on what exactly is in that image.
Let’s imagine an e-commerce customer support example: If you are offering automated refunds, then you would ask the user to upload an image of the receipt, send the image to a pre-trained ML model, extract the text from the image, identify the purchase date from the text, see if it fits the refund window and then process the refund or deny it.
Let’s image another support example: Your hardware product requires the customer to follow some setup steps and if they run into issues they turn to the chatbot, the chatbot asks them to upload the image of the device which in is sent to a pre-trained ML model which identifies what the problem can be and relays it back to the user via Chatbot.
In this tutorial, you will learn how to integrate Dialogflow with Vision API to provide rich and dynamic ML based responses to user provided image inputs. You will create a simple chatbot application that will take an image as input, process it in Vision API and return the identified landmark to the user. See the image below.
You will create a Dialogflow agent
Implement a django front-end to upload a file
Implement Dialogflow fulfillment to invoke vision API against the uploaded image. Just like the image below.
Here is a video explaining the steps that follow.
We are creating a conversation experience with a custom Django front-end and integrating it with Vision API. We will build the front-end with Django-framework, run and test it locally and then deploy it on Google App Engine. The front-end will look like this:
The request flow will be:
The user will send a request via this front-end.This will trigger a call to the Dialogflow DetectIntent API to map the user’s utterance to the right intent.Once the “Explore Landmark” intent is detected, Dialogflow fulfillment will then send a request to the Vision API, receive a response back and send it back to the user.
The user will send a request via this front-end.
This will trigger a call to the Dialogflow DetectIntent API to map the user’s utterance to the right intent.
Once the “Explore Landmark” intent is detected, Dialogflow fulfillment will then send a request to the Vision API, receive a response back and send it back to the user.
Overall architecture:
Google cloud Vision API is a pre-trained Machine Learning model that helps derive insights from images. You can get insights including image labeling, face and landmark detection, optical character recognition (OCR), and tagging of explicit content. Here is the link to learn more specifically about the Vision API.
Go to the Dialogflow Console.Sign-in, if you are a first time user, then use your email to sign upAccept the terms and conditions and you will be in the consoleCreate an Agent. To create, click on the dropdown menu in the left pane in order to see “Create new agent”Call this “VisionAPI”Dialogflow creates a Google Cloudproject for you to access logs, cloud functions etc. You can select an existing project as well.When you’re ready, click Create.Dialogflow creates two default intents as a part of the agent. Default Welcome intent helps greet your users. Default Fallback intent helps catch all the questions that your bot does not understand.
Go to the Dialogflow Console.
Sign-in, if you are a first time user, then use your email to sign up
Accept the terms and conditions and you will be in the console
Create an Agent. To create, click on the dropdown menu in the left pane in order to see “Create new agent”
Call this “VisionAPI”
Dialogflow creates a Google Cloudproject for you to access logs, cloud functions etc. You can select an existing project as well.
When you’re ready, click Create.
Dialogflow creates two default intents as a part of the agent. Default Welcome intent helps greet your users. Default Fallback intent helps catch all the questions that your bot does not understand.
At this point, we have a functional bot that greets the users. But we need to update it slightly to let the user know that they can upload an image to explore landmarks.
Click on “Default Welcome Intent”Update the “Response” to “Hi! You can upload a picture to explore landmarks.”
Click on “Default Welcome Intent”
Update the “Response” to “Hi! You can upload a picture to explore landmarks.”
Click on “Entities”Create a new entity, name it “filename” and “save”.
Click on “Entities”
Create a new entity, name it “filename” and “save”.
Click on “Intents”
Name it “Explore uploaded image”
Click on “Training phrases” and add “file is demo.jpg” and “file is taj.jpeg” with @filename as the entity.
Click on “Responses” and add “Assessing file” as the Text Response
Click on “Fulfillment” and toggle “Enable webhook call for this intent”
Navigate to Dialogflow Agent “VisionAPI” and click on “Fulfillment”
Enable inline code editor by toggling the switch.
Update the index.js file with the following code and update YOUR-BUCKET-NAME with the name of your storage bucket.
Click package.json and paste the following to replace its contents.
Click Deploy at the bottom of the page.
Clone this repository to your local machine: https://github.com/priyankavergadia/visionapi-dialogflow.git
Change to the directory that contains the code/. Alternatively, you can download the sample as a zip and extract it.
When deployed, your app uses the Cloud SQL Proxy that is built in to the App Engine environment to communicate with your Cloud SQL instance. However, to test your app locally, you must install and use a local copy of the Cloud SQL Proxy in your development environment. Learn more about the Cloud SQL Proxy here. To perform basic admin tasks on your Cloud SQL instance, you can use the MySQL client.
Note: You must authenticate gcloud to use the proxy to connect from your local machine
Download and install the Cloud SQL Proxy. The Cloud SQL Proxy is used to connect to your Cloud SQL instance when running locally.
Download the proxy:
curl -o cloud_sql_proxy https://dl.google.com/cloudsql/cloud_sql_proxy.darwin.amd64
Make the proxy executable:
chmod +x cloud_sql_proxy
Create a Cloud SQL for MySQL Second Generation instance. Name the instance “polls-instance” or similar. It can take a few minutes for the instance to be ready. After the instance is ready, it should be visible in the instance list. Be sure to create a Second Generation instance.
Now use the Cloud SDK to run the following command where [YOUR_INSTANCE_NAME] represents the name of your Cloud SQL instance. Make a note of the value shown for connectionName for the next step. The connectionName value is in the format [PROJECT_NAME]:[REGION_NAME]:[INSTANCE_NAME]
gcloud sql instances describe [YOUR_INSTANCE_NAME]
Alternatively, you can get the connection name from the console by clicking on the instance
Start the Cloud SQL Proxy using the connectionName from the previous step.
./cloud_sql_proxy -instances=”[YOUR_INSTANCE_CONNECTION_NAME]”=tcp:3306
Replace [YOUR_INSTANCE_CONNECTION_NAME] with the value of connectionName that you recorded in the previous step.
This step establishes a connection from your local computer to your Cloud SQL instance for local testing purposes. Keep the Cloud SQL Proxy running the entire time you test your app locally.
Next, you create a new Cloud SQL user and database.
Create a new database using the Google CloudConsole for your Cloud SQL instance polls-instance. For example, you can use the name polls.
Create a new user using the Google CloudConsole for your Cloud SQL instance polls-instance.
Open mysite/settings-changeme.py for editing.
Rename the file to setting.py
In two places, replace [YOUR-USERNAME] and [YOUR-PASSWORD] with the database username and password you created previously in the step “Create a Cloud SQL instance”. This helps set up the connection to the database for both App Engine deployment and local testing.
In line ‘HOST’: ‘cloudsql/ [PROJECT_NAME]:[REGION_NAME]:[INSTANCE_NAME]’ replace [PROJECT_NAME]:[REGION_NAME]:[INSTANCE_NAME] with your instance name acquired in previous step.
Run the following command. Copy the outputted connectionName value for the next step.
gcloud sql instances describe [YOUR_INSTANCE_NAME]
Replace [YOUR-CONNECTION-NAME] with connectionName from the previous step
Replace [YOUR-DATABASE] with the name you choose during the “Initialize your Cloud SQL instance” step and then, close and save settings.py
# [START db_setup]if os.getenv(‘GAE_APPLICATION’, None):# Running on production App Engine, so connect to Google Cloud SQL using# the unix socket at /cloudsql/<your-cloudsql-connection string>DATABASES = {‘default’: {‘ENGINE’: ‘django.db.backends.mysql’,‘HOST’: ‘/cloudsql/[PROJECT_NAME]:[REGION_NAME]:[INSTANCE_NAME]’,‘USER’: ‘[YOUR-USERNAME]’,‘PASSWORD’: ‘[YOUR-PASSWORD]’,‘NAME’: ‘[YOUR-DATABASE]’,}}else:# Running locally so connect to either a local MySQL instance or connect to# Cloud SQL via the proxy. To start the proxy via command line:# $ cloud_sql_proxy -instances=[INSTANCE_CONNECTION_NAME]=tcp:3306# See https://cloud.google.com/sql/docs/mysql-connect-proxyDATABASES = {‘default’: {‘ENGINE’: ‘django.db.backends.mysql’,‘HOST’: ‘127.0.0.1’,‘PORT’: ‘3306’,‘NAME’: ‘[YOUR-DATABASE]’,‘USER’: ‘[YOUR-USERNAME]’,‘PASSWORD’: ‘[YOUR-PASSWORD]’}}# [END db_setup]
In Dialogflow’s console, go to settings ⚙ and under the general tab, you’ll see the Google Project section. Click on the service account. This will open the Google Cloud Console.
In the Google Cloudconsole, the presented webpage will show the Dialogflow service account. Click on the 3 dots in the “Actions” section to the far right and then click “Create Key”
A JSON file will be downloaded to your computer that you will need in the setup sections below.
Inside chat folder, replace the key-sample.json with your own credentials json file and call it key.json.
In views.py in chat folder, Change the GOOGLE_PROJECT_ID = “<YOUR_PROJECT_ID>” to your project ID
Navigate to the Google CloudProject and click on Storage from the hamburger menu
Click on “Create New Bucket”
Provide a name — this has to be a globally unique name
Choose where to store your data — Pick “Regional” and select the location that best suits your needs.
Choose default storage class of your data as “Standard”
Choose how to control access to objects as “Set permissions uniformly at bucket-level” and then continue to create the bucket.
Once the bucket is created, click on the “Browser” and locate the bucket you just created.
Click on the three dots on the right hand side corresponding to the bucket and click “Edit bucket permissions”
In the presented side panel, click on “Add Members” and then add a new member “allUsers”, then click on “Select a role” to add “Storage Object Viewer” role. We do this to provide view access to the static front end files to allUsers. This is not an ideal security setting for the files but for the purpose of this particular lab it will work.
Follow the same instructions and create a separate bucket to upload user images.
Set permissions to “allUsers” and role “Storage Object Creator” and “Storage Object Viewer”
Open mysite/setting.py
Locate GCS_BUCKET variable and replace the “<YOUR-GCS-BUCKET-NAME>” with your GCS static bucket
Locate GS_MEDIA_BUCKET_NAME variable and replace the “<YOUR-GCS-BUCKET-NAME-MEDIA>” with your GCS bucket name for the images.
Locate GS_STATIC_BUCKET_NAME variable and replace the “<YOUR-GCS-BUCKET-NAME-STATIC>” with your GCS bucket name for the static files.
Save the file.
GCS_BUCKET = ‘<YOUR-GCS-BUCKET-NAME>’GS_MEDIA_BUCKET_NAME = ‘<YOUR-GCS-BUCKET-NAME-MEDIA>’GS_STATIC_BUCKET_NAME = ‘<YOUR-GCS-BUCKET-NAME-STATIC>’
Open chat -> templates -> home-changeme.html
Rename it to home.html
Look for <YOUR-GCS-BUCKET-NAME-MEDIA> and replace it with your bucket name for where you would like the user uploaded file to be saved. We do this so we don’t store the user uploaded file in the front-end and keep the static assets all in GCS bucket. The Vision API calls the GCS bucket to pick up the file and do the prediction.
To run the Django app on your local computer, you’ll need to set up a Python development environment, including Python, pip, and virtualenv. For instructions, refer to Setting Up a Python Development Environment for Google Cloud Platform.
Create an isolated Python environment, and install dependencies:
virtualenv envsource env/bin/activatepip install -r requirements.txt
Run the Django migrations to set up your models:
python3 manage.py makemigrationspython3 manage.py makemigrations pollspython3 manage.py migrate
Start a local web server:
python3 manage.py runserver
In your web browser, enter this address http://localhost:8000/ You should see a simple webpage with the text: “Dialogflow” a textbox and submit button.
The sample app pages are delivered by the Django web server running on your computer. When you’re ready to move forward, press Ctrl+C to stop the local web server.
Gather all the static content into one folder. This command moves all of the app’s static files into the folder specified by STATIC_ROOT in settings.py:
python3 manage.py collectstatic
Upload the app by running the following command from within the directory of the application where the app.yaml file is located:
gcloud app deploy
Wait for the message that notifies you that the update has been completed.
In your web browser, enter this address:
https://<your_project_id>.appspot.com
This time, your request is served by a web server running in the App Engine standard environment.
This command deploys the application as described in app.yaml and sets the newly deployed version as the default version, causing it to serve all new traffic.
When you are ready to serve your content in production, in mysite/settings.py, change the DEBUG variable to False.
Let’s test our chatbot with the following prompts
User: “hi”Chatbot response: “Hi! You can upload a picture to explore landmarks.”User: uploads an image.Download an image with a landmark, name it “demo.jpg”Chatbot response: “file is being processed, here are the results: XXXX<whatever landmark is in your image>”Overall, it should look like this.
User: “hi”
Chatbot response: “Hi! You can upload a picture to explore landmarks.”
User: uploads an image.
Download an image with a landmark, name it “demo.jpg”
Chatbot response: “file is being processed, here are the results: XXXX<whatever landmark is in your image>”
Overall, it should look like this.
Make sure to delete the Google Cloud project and the Dialogflow agent to avoid incurring any charges.
Checkout my video series Deconstructing Chatbots, where I share how to get started and build conversational experiences using Dialogflow and Google Cloud tools.
Dialogflow, Django app on Appengine, https://github.com/vkosuri/django-dialogflow