Today, you will build your first AI-Powered web application. We will provide you instructions, as well as code snippets, to create an interactive AI powered web application using the Clarifai API.
Tools we will be using
- Python 3
- Streamlit.io: A free python library to convert python code into an interactive web application.
- Clarifai Python gRPC Client library: https://github.com/Clarifai/clarifai-python-grpc/
- Pandas Python library
- Pillow python library
Step 1: Create a Clarifai Account
Head over to https://www.clarifai.com/ and create an account.
Step 2: Create an Application
Once your account is created, select “Create An Application”. Enter the following information in the application:
- An App-ID: The App-Id is the unique identifier for your new Application, make sure to choose a unique & memorable one.
- Display Name
- A Description of the application.
Select Create.
Step 3: Create an Application Specific API key
Once your application is created, you can see that an Application Specific Application Key (App Key) has already been created for you. Copy the App Key your clipboard using Cmd+C (if using Mac) or Ctrl+C (if using Windows)
Hold onto your App Key, because we will need it for the web application your are building.
Step 4: Create Python Environment and install essential python packages
Open up your terminal, and run this command to install virtualenv.
pip install virtualenv
Create a python3 virtual environment called py3env
virtualenv --python=`which python3.7` ~/virtualenv/py3env
To activate the virtual environment, run the following command:
source /Users/andrewmendez/virtualenv/v1/bin/activate
To verify your python environment has been activated you should see the name of your python environment activated in your terminal:
(py3env) user@Users-MacBook-Pro %
Step 5: Install Python Packages
With your python virtual environment activated, create a file named `requirements.txt`, and paste the following python packages to install:
pip install streamlit
pip install clarifai-grpc
pip install pandas
pip install pillow
In the terminal, run the command
pip install -r requirements.txt
Step 6: Create Streamlit Web application
Here is a walkthrough of the sample code you will create to integrate the Clarifai API into your streamlit application. Create a python file called app.py, and paste the following code snippets.
import streamlit as st
from PIL import Image
import pandas as pd
The python packages streamlit, PIL (aka Pillow) and Pandas
st.title("Classifier Demo")
st.header("Step 1: Enter an App Key")
Create a title for our web application, and a header informing the user to enter the app key.
key = st.text_input("App Key")
if key == '':
st.warning("An app key has not been entered")
st.stop()
else:
st.write("App Key has been uploaded!")
Use st.text_input() (documentation) to allow a user to enter their Application Specific App Key, and check if an app key was entered using an if-else code block. If an app key is not entered, we provide a warning and stop the application from further executing.
file_data = st.file_uploader("Upload Image",type=['jpg'])
if file_data == None:
st.warning("File needs to be uploaded")
st.stop()
else:
image = Image.open(file_data)
st.image(image)
Use st.file_uploader() (documentation) to allow the user to upload an image in the web application. The if-else statement is used to check if a user entered an image.
If a file has not been uploaded, provide a warning message and stop further execution. If a file has been uploaded, load the image and preview it.
Next we will leverage the Clarifai API python client (located here) to connect to your Clarifai Application in python. First we need to import some objects, and create a Stub Object:
from clarifai_grpc.channel.clarifai_channel import ClarifaiChannel
from clarifai_grpc.grpc.api import service_pb2_grpc
stub = service_pb2_grpc.V2Stub(ClarifaiChannel.get_grpc_channel())
Next, we need to enter the App Key, and make a POST request to process the image and retrieve predictions. We can upload an image in base64 binary format using a method in file_data, called file_data.getvalue(). As there are many Machine Learning models available with your Clarifai application, we will be using the general image classifier. The general image classifier can be used by its model_id: 'aaa03c23b3724a16a56b629203edc62c' For more details about the classifier, read here.
The code below provides all the functionality needed:
from clarifai_grpc.grpc.api import service_pb2, resources_pb2
from clarifai_grpc.grpc.api.status import status_code_pb2
# This is how you authenticate.
metadata = (('authorization', 'Key {}'.format(key)),)
request = service_pb2.PostModelOutputsRequest(
# This is the model ID of a publicly available General model. You may use any other public or custom model ID.
model_id='aaa03c23b3724a16a56b629203edc62c',
inputs=[
resources_pb2.Input(data=resources_pb2.Data(image=resources_pb2.Image(base64=file_data.getvalue())))
])
response = stub.PostModelOutputs(request, metadata=metadata)
if response.status.code != status_code_pb2.SUCCESS:
raise Exception("Request failed, status code: " + str(response.status.code))
names = []
confidences = []
for concept in response.outputs[0].data.concepts:
names.append(concept.name)
confidences.append(concept.value)
Finally, to visualize the concepts the model predicted in the image, we will create a Pandas Dataframe, and visualize the predictions as a table using st.datafreme() (documentation)
df = pd.DataFrame({
"Concept Name":names,
"Model Confidence":confidences
})
st.dataframe(df)
Step 7: Run your web application
You can start your web application by running the following command:
Streamlit run app.py
Open your favorite web browser, and enter the following url: localhost:8501