DEV Community 👩‍💻👨‍💻

Cover image for Your first A.I. Web App!
Jovial Joe Jayarson
Jovial Joe Jayarson

Posted on

Your first A.I. Web App!

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


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 and start coding. Make sure you have a similar directory structure:

├── templates
    └── index.html

1 directory, 3 files
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

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 =, fruits)

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

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
Lets' code first and then I'll explain how it works:

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)
        result = fruit.test()
        return render_template("index.html", title="Hello AI", value=result)
        return render_template("index.html", title="Hello AI")

if __name__ == '__main__': # disable debug=True in production
Enter fullscreen mode Exit fullscreen mode

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 to index.html. And for that flask uses the GET & POST methods.


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

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 @
  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 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,
  6. Create a new folder named templates and upload index.html to it.
  7. Finally navigate back to Web tab and click Reload
  8. Check out your webapp!

Hello AI

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


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.

Top comments (0)

🌚 Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.