Installing and Verifying Flask
Before building the application, ensure that Flask is installed. Run the following commands to install Flask, check its version, and inspect the directory structure of your Flask app:flask_app/ directory, an important part of your model deployment workflow.
If Flask is already installed, you may see output indicating that the requirements are already satisfied, for example:
Creating the Flask Application
Before starting the Flask server, initialize the app by loading any required environment variables and your machine learning model. In this example, we use the MobileNetV3 Large pre-trained model. It is essential that the model is loaded before the application processes any requests. Below is an example of the initial setup with logging and error handling:Make sure that all required modules are imported and logging is correctly configured. The model must be loaded before any request is processed to avoid runtime errors.
Creating Endpoints
Prediction Endpoint
The/predict endpoint handles POST requests. It accepts a JSON payload that contains an image encoded in Base64. This endpoint decodes the image, preprocesses it, performs inference using the model, and returns the prediction in JSON format.
- Parses the request payload and verifies the presence of an
"image"key. - Decodes the Base64-encoded image and converts it into an RGB image.
- Applies image preprocessing before passing the tensor to the model.
- Retrieves and returns the prediction using Flask’s
jsonifymethod.
Health Endpoint
The/health endpoint is a simple GET endpoint used to verify that the server is running correctly. It returns a JSON response with a health status.
Testing the Flask Application
Running the App Directly
To start the Flask application, run the following command from your terminal:http://127.0.0.1:5000.
Example terminal output:
Do not use the Flask development server in a production environment. For production deployments, consider using a WSGI server such as Gunicorn.
Sending Test Requests
You can use the Pythonrequests library to test your endpoints. Begin by creating a Base64-encoded string from an image (for example, “dog-1.jpg”):
Testing Error Handling
Test error handling by sending requests without the required payload or using an incorrect key:Running the App with Gunicorn
For production deployments, use a robust WSGI server like Gunicorn. Start the Gunicorn server with the following command:Interpreting the Model Prediction
To convert the numeric prediction (e.g., 207) into a human-readable class label, use a mapping file (labels.json) available from Hugging Face. The labels file can be downloaded from: Imagenet 1K Labels After downloading the file, use the following code to interpret the prediction:This concludes our introduction to Flask and model deployment. With Flask, you can quickly set up HTTP endpoints to serve machine learning models, complete with robust error handling and logging. Happy coding!