Deploy DL Model using Flask

Environment Setup

(1)Python Installation
=> Done
(2)Visual Studio Code Installation
=> Done
(3)Flask and required libraries installation
(3)-1 Navigate to Project directory

D:
cd 스터디/FlaskApplication/

(3)-2 Generate and activate Your Virtual Environment

python -m venv venv
# Windows Command Prompt
venv\Scripts\activate.bat

Flask_DL1
(3)-3 Install the Required Library

pip install Flask tensorflow numpy

Flask_DL2
. (3)-4 Create new python file Flask_DL4
Right click mouse > +새로 만들기 > 텍스트 문서> Change the file name to app.py
(3)-5 Open up the script using the preferred text editor (Visual Studio Code)
(4) Write app.py Script
(4)-1 Import necessary libraries

from flask import Flask, request, render_template
from werkzeug.utils import secure_filename
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.imagenet_utils import preprocess_input, decode_predictions
import numpy as np
import os

-Flask:
A lightweight WSGI (Web Server Gateway Interface) web application framework in Python
Create the web server that handles HTTP requests and responses
-Werkzeug:
A WSGI utility library for Python that powers Flask and can work with any WSGI application. It’s packed with useful utilities
-TensorFlow:
An end-to-end open-source platform for machine learning
Keras: High-level neural networks API, written in Python and capable of running on top of TensorFlow
-NumPy:
A fundamental package for scientific computing with Python
-os:
portable way of using operating system-dependent functionality
(4)-2 Initialize the Flask application

app = Flask(__name__)

Define a flask app
(4)-3 Path to the trained model
Download the ResNet50 Model with ImageNet Weights

from tensorflow.keras.applications.resnet50 import ResNet50

# Load the ResNet50 model with ImageNet weights
model = ResNet50(weights='imagenet')

# Specify the local path in Colab to save the model
model_path = '/content/drive/My Drive/AI_Models/resnet50_imagenet.h5'

# Save the model
model.save(model_path, save_format='h5')

print(f'Model saved at {model_path}')

Loads the ResNet50 model pre-trained with ImageNet weights and save it as a file
Prepare the Project Directory to store models:
Flask_DL5
On your local system, where your Flask application resides, create a directory named models in the root of your project directory
This is where you’ll store the downloaded model

MODEL_PATH = 'models/resnet50_imagenet.h5'

Make models folder in the project directory > Define MODEL_PATH variable
(4)-4 Load the pre-trained Keras model (ensure TensorFlow 2.x is being used)

model = load_model(MODEL_PATH)

(4)-5 Define the uploads directory relative to this file’s location

UPLOAD_FOLDER = os.path.join(os.path.dirname(__file__), 'uploads')
os.makedirs(UPLOAD_FOLDER, exist_ok=True)  # Create uploads directory if it doesn't exist

(4)-6 Define a route for the default URL, which loads the form

@app.route('/')
def upload_file():
    return render_template('index.html')

(4)-7 Define a route for handling the prediction

@app.route('/predict', methods=['POST'])
def upload_and_predict():
    if request.method == 'POST':
        # Get the file from post request
        f = request.files['file']
        if f and allowed_file(f.filename):
            # Secure the filename and save the file to the uploads directory
            filename = secure_filename(f.filename)
            file_path = os.path.join(UPLOAD_FOLDER, filename)
            f.save(file_path)
            
            # Make prediction
            preds = predict(file_path)
            
            # Decode and return the prediction result
            pred_class = decode_predictions(preds, top=1)  # Decode the prediction result
            result = str(pred_class[0][0][1])  # Convert the result to string
            return result
        else:
            return 'File not allowed'
    return None

def predict(img_path):
    img = image.load_img(img_path, target_size=(224, 224))
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)
    x = preprocess_input(x, mode='caffe')

    preds = model.predict(x)
    return preds

Define Flask Route for Prediction and The predict Function

(4)-8 File Extension Validation

def allowed_file(filename):
    # Check if the file has an allowed extension
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in {'png', 'jpg', 'jpeg', 'gif'}

Validate the file extension of an uploaded file, ensuring it matches a predefined set of allowed extensions. This is important in web applications to prevent the upload of potentially harmful files

(4)-9 Running the Flask Server

if __name__ == '__main__':
    app.run(debug=True)

Actually running the app
(5) Run the application
(5)-1 Run the python code in terminal

python app.py

Flask_DL78
(5)-2 Select image for classification
Flask_DL79
Click Choose… button > Navigate the file explorer and choose the jpeg or jpg file > Double click the image
(5)-3 Image uploaded
Flask_DL80
(5)-4 Classifed result displayed
Flask_DL81
Click Predict! Button
Image classified as Maltese_dog

Reference:
https://www.youtube.com/watch?v=CSEmUmkfb8Q