loading...
Cover image for Your first A.I. Web App!

Your first A.I. Web App!

joe733 profile image Jovial Joe Jayarson ・6 min read

Hello DEV Community!

Last week me and my friend Shaheen had the privilege to take a webinar on software development as a practical holistic approach. Here's my article sketching out how we deployed a very basic toy AI web app. Follow along!

ML in just 5 lines!

Here's a mermaid graph explaining the difference between
Conventional Programming

and ML Programming1
(Training)

(Testing)

Deep Blue won the world Chess championship using conventional programming, on the other hand AlphaGo won the world Go championship using AI programming (Deep Learning).
Why such a change in approach? Because it would be astoundingly crazy to code rules for all the quadrillion possibilities on the Go board. Here I'll demonstrate a very simple AI application2 and then walk you through the steps of deploying it.

Apples or Oranges?

Let's try to write some rules to classify apples and oranges in a given picture. We may come up with something like this:

  • Apples are lighter than Oranges
  • Apples may have either red or green colour while oranges are orange.
  • Apple are smooth and oranges bumpy.
  • ... so on.

But what if the picture was of your cat! Would the machine be able to tell the difference? or what if you had pencil drawing instead? And obviously what about all the variants of these fruits? You see... the world around us is complex to be classified within strict mathematical rules. So...

How does the AI work?

The term learning seems strange to computers, memorizing is not but learning, really? There is a model called Decision Tree Classifier3 which comes to a conclusion after asking certain relevant questions repeatedly, something like the Akinator game.

AI models consist of three phases: Training, Testing & Deploying. The training phase is where the model learns (I'll explain what it means in a moment). In the testing phase model gets to see new data and predict what it is. Finally just like any other computer programs AI models are prepared to be production ready.

Coming back to Apples and Oranges we'll train a pre-built Decision Tree Classifier (DTC). Here we'll describe our training data set as in the table below:

Texture Weight Fruit
Smooth 140 Apple
Bumpy 150 Orange
Smooth 120 Apple
Bumpy 170 Orange
Smooth 110 Apple
Bumpy 180 Orange

Here's the cue.
The DTC takes the input and says: "Hmm.. if the Texture is Smooth and Weight is around 140 the Fruit is likely to be an Apple"
But then it gets the next input and so it says: "Oh. If the Texture is Bumpy and the Weight is around 150 the Fruit is likely to be an Orange".

Yep! This way in the training period it slightly keeps on adjusting parameters whenever it receives new data.
While testing no parameters are changed but it predicts the possible Fruit after repeated questioning. Here's a picture of another DTC model4:

Simple Decision Tree

Let's Code!

To run this code you can either use Google Colab or create and account on PythonAnywhere and then create a new file say decision.py and start coding. Make sure you have a similar directory structure:

.
├── decision.py
├── hello_ai.py
├── templates
    └── index.html

1 directory, 3 files

decision.py

from sklearn import tree
features = [[140, 1], [130, 1], [150, 0], [170, 0], [110, 1], [180, 0]] # inputs
fruits = [1, 1, 0, 0, 1, 0] # outputs
clf = tree.DecisionTreeClassifier().fit(features, fruits) # training
print(clf.predict([[160, 0]])) # testing

This classifier takes only numeric inputs so we just encoded it like:

Texture Fruit 0 / 1
Smooth Apple 1
Bumpy Orange 0

The .fit() method (or function) is what trains our classifier. Finally the .predict() method is used to tell whether the new feature pair (Weight & Texture) is an Apple or an Orange.

Now since we're planning it to host it I've refactored the code to make it bit more package friendly. So here's our new decision.py:

from sklearn import tree

features = [[140, 1], [130, 1], [150, 0], [170, 0], [110, 1], [180, 0]] # let 1 = smooth & 0 = bumpy
fruits = [1, 1, 0, 0, 1, 0] # let 1 = apples & 0 = oranges

class Fruit:
    def __init__(self, weight, texture):
        self.clf = tree.DecisionTreeClassifier()
        self.wt = weight
        self.txt = 1 if texture == 'smooth' else 0

    def train(self):
        self.clf = self.clf.fit(features, fruits)

    def test(self):
        return 'Orange' if self.clf.predict([[self.wt, self.txt]]) == [0] else 'Apple'

Enter Flask

Flask is a well know Python micro framework for web (WSGI5) applications. So our web app will look something like this:

The backend (not a fancy one ;) is what we just wrote decision.py.
Lets' code first and then I'll explain how it works:

hello_ai.py

from flask import Flask, render_template, request
from decision import Fruit

app = Flask(__name__)

@app.route("/", methods=['GET', 'POST'])
def index():
    weight = texture = result = 0
    if request.method == 'POST':
        weight = request.form['weight']
        texture = request.form['texture']
        fruit = Fruit(weight, result)
        fruit.train()
        result = fruit.test()
        return render_template("index.html", title="Hello AI", value=result)
    else:
        return render_template("index.html", title="Hello AI")


if __name__ == '__main__':
    app.run() # disable debug=True in production

This flask Application renders the HTML webpage (which we'll see in a moment) and based on the query from the webpage the required data is passed on from the decision.py to index.html. And for that flask uses the GET & POST methods.

index.html

<html>
    <head>
        <title> AI WebApp </title>
    </head>
    <body>
        <h1 align="center"> {{title}} </h1>
        <form name="form_ai" method="POST">
             <fieldset>
                <legend>Predict Fruit</legend>
                <div>
                    <label for="weight">Enter Weight: </label>
                    <input id="weight" type="number" name="weight" required>
                </div>
                <br>
                <div>
                    <label for="texture">Choose Texture:</label>
                    <select id="texture" name="texture">
                        <option value="bumpy">Bumpy</option>
                        <option value="smooth">Smooth</option>
                    </select>
                </div>
                <br>
                <input type="submit" value="Submit">
           </fieldset>
       </form>
       <div>
            <h4> Predicted Fruit: {{ value }} </h4>
       </div>
   </body>
</html>

Now HTML needs no elucidation. This {{ value }} is where the predicted fruit will be inserted.
That's it! Your first AI app is ready to be deployed!

Deploying your App

Show time! There are many hosting services available online, but for convenience and ease of setup we will use PythonAnywhere.

Steps to deploy:

  1. Sign up @ https://pythonanywhere.com.
  2. Open the Web tab and click Add a new web app button on top left.
    • Click Next and select Flask
    • Select any Python3.x version.
  3. Name your app as hello_ai.py and hit Finish.
  4. Scroll down the current page and toggle button Force https to enable it.
  5. Open the Files tab and navigate to mysite folder delete the existing file and upload the files hello_ai.py, decision.py.
  6. Create a new folder named templates and upload index.html to it.
  7. Finally navigate back to Web tab and click Reload username.pythonanywhere.com
  8. Check out your webapp username.pythonanywhere.com!

Hello AI

Bingo! You've just hosted your first artificially intelligent web application!


Conclusion

This is a fun project that you can try out at no cost except your time and attention. I learned a lot when I did it, hope you'll too. Share your thoughts in the comments below. Thanks for reading!


References & Info

1 Machine Learning Zero to Hero @ Google IO'19
2 Machine Learning Recipes by Josh Gordon @ Google
3 Decision tree learning
4 Decision Tree
5 Web Server Gateway Interface

  • See.. here (useless) training takes place every time the query from the webpage is sent.
  • This deployment is obviously very immature so you might want to consider options like Docker, Kubernetes or Heroku.

Posted on Jun 6 by:

joe733 profile

Jovial Joe Jayarson

@joe733

I love to write what I learn and learn what I love to write

Discussion

markdown guide