Project - How to Deploy an Image Classification Model using Flask

14 / 15

Creating the app.py File

Now we shall create the app.py file, where we define all the routes and functions to perform for each action. This file is the root of our Flask application which we will run in the command line prompt.

Note:

  • Flask from flask is an instance of the flask framework for web app development. So we need to initialize a flask app by using Flask(__name__). By writing app = Flask(__name__), we name the flask instance as app.

  • @app.route is a python decorator that specifies to the application which function should be executed based on the URL. For example, here in our web app, the default URL route / calls(invokes) the function index. Also, as soon as the user submits the input image file, the /uploader route will be activated(this is defined in the index.html file, you could have a look at it). This URL route calls(invokes) the function upload_file, since we have written @app.route('/uploader', methods = ['POST']) before defining the upload_file function.

  • The request method is used to deal with the requests made by the client through the web app. The request method from the flask app is a global request variable, which has the request data like the data entered/submitted in the form, the current request type(like GET, POST, etc), and others.

    In our web app, we use request to get the image file submitted by the user. We access that file using request.files['file']. This request is of method POST.

  • To render a template from the function in app.py, we can use the render_template() method of flask. We just need to provide the name of the template and the variables we want to pass to the template as keyword arguments.

    For example,

    render_template("upload.html", predictions=preds, display_image=f.filename)
    

    Here, we are rendering the upload.html file, and passing the variable preds as predictions, f.filename as display_image.

    • These variables will be used in the upload.html file to display the image file with filename f.filename using {{display_image}}.
    • Similarly, the predictions will be shown using predictions.
    • Here the variable preds is passed as predictions, f.filename is passed as display_image so as to make the job easier for the front-end developer(in the real-time software development scenario), who generally doesn't need to know the coding knowledge and Python technicalities.
  • secure_filename method from flask is used to secure a filename before storing it directly on the filesystem. We need to do this because we can't always trust the user input and we should be secure about the files we are receiving from the user. More about this is here.

  • os.path.dirname(__file__) is the file path of app.py.

  • os.path.join(basepath, 'static','uploads', secure_filename(f.filename)) joins the paths of files/directories which are passed arguments to the function os.path.join. Here, we are saving the file uploaded by the user into the static/uploads directory which we have created earlier.

  • app.run(host="0.0.0.0",debug=True,port="4100") method is used to run the flask app as soon as the file is executed, based on the URL given in the browser. The app runs on the given host at the given port number, with debug mode, meaning any errors/warnings/messages will be shown on the command prompt.

INSTRUCTIONS
  • This file app.py should be created inside the Image-Classification-App directory. So make sure you are in the directory Image-Classification-App. You could check your present working directory using the command:

    pwd
    

    This command should output the path:

    /home/$USER/Image-Classification-App
    

    If the path displayed is not the same as the above, switch to the Image-Classification-App using

    cd ~
    cd Image-Classification-App
    
  • Now inside Image-Classification-App, create the file named app.py using vi command. Then, do as directed below:

  • Import Flask, request, render_template from flask.

    from flask import << your code comes here >>
    
  • Import secure_filename from werkzeug.utils.

    from werkzeug.utils import  << your code comes here >>
    
  • Import os

    import << your code comes here >>
    
  • Import all functions from the app_helper file we created previously. We do this using the following:

    from app_helper import *
    
  • Initialize the Flask app as follows:

    app = Flask(__name__)
    
  • Define the function index to perform, upon reaching to the default link /. Remember we have already created the HTML file for the home page for our app? It is the index.html.

    This page will be opened as the default page, by writing as follows:

    @app.route("/")
    def index():
      return render_template("index.html")
    
  • Define upload_file function which will be performed after the user submits the input image file.

    @app.route('/uploader', methods = ['POST'])
    def upload_file():
        predictions=""
        if request.method == 'POST':
            f = request.files['file']
    
            # Save the file to ./uploads
            basepath = os.path.dirname(__file__)
            file_path = os.path.join(basepath, 'static','uploads', secure_filename(f.filename))
            f.save(file_path)
    
            predictions = get_classes(file_path)
            pred_strings = []
            for _,pred_class,pred_prob in predictions:
                pred_strings.append(str(pred_class).strip()+" : "+str(round(pred_prob,5)).strip())
            preds = ", ".join(pred_strings)
            print("preds:::",preds)
        return render_template("upload.html", predictions=preds, display_image=f.filename)
    

    Here,

    • We are saving the user-uploaded file using f.save(file_path).

    • We call the get_classes function defined in the file app_helper.py(which we have created earlier and imported above), and pass the input image file given by the user through the web interface. We will be returned the predictions predictions are outputted by the model defined in the get_classes function. predictions is a tuple containing the predicted classes and the probabilities in the decreasing order.

    • We would further process the predictions to form preds, and pass this variable as predictions to the upload.html file while rendering that template.
  • Write the following code to initiate the app running when the file is executed.

    if __name__ == "__main__":
        app.run(host="0.0.0.0",debug=True,port="4100")
    

    CloudxLab has ports open from 4040 to 4140. So could change the port number in case of any issues while executing the app.

Get Hint See Answer


Note - Having trouble with the assessment engine? Follow the steps listed here

Loading comments...