/web-to-ai-ml-integrations

Flask App with Real-Time Feedback from ML Model

Build a Flask app with real-time ML insights. Our step-by-step guide helps you integrate live feedback for dynamic predictions.

Book a free  consultation
4.9
Clutch rating 🌟
600+
Happy partners
17+
Countries served
190+
Team members
Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

Flask App with Real-Time Feedback from ML Model

Creating the Flask Application and ML Model Endpoint

 
  • Overview: In this guide, we integrate a machine learning (ML) model into a Flask web application to provide real-time feedback. For clarity, “real-time” means the webpage will update as soon as the ML model processes data, without the user manually reloading.
  • The guide will cover setting up a ML endpoint that receives user data, processes it using the ML model, and sends the results back to the frontend immediately.

Integrating the ML Model into Flask

 
  • Explanation: A typical ML workflow involves loading a pre-trained model (using packages like scikit-learn, TensorFlow, or PyTorch) and then using the model to predict results based on user input.
  • Loading the Model: For demonstration, we assume you have a pre-trained model saved as model.pkl (if using scikit-learn) or a similar file. We will load it when the Flask app starts so that predictions are available for any request.

// Import libraries for Flask and ML model handling
from flask import Flask, request, jsonify, render\_template
import pickle       // To load a pickled model
import numpy as np  // For handling numerical data

// Initialize Flask application
app = Flask(**name**)

// Load the pre-trained ML model (for example, scikit-learn model)
with open("model.pkl", "rb") as file:
    model = pickle.load(file)

Setting Up Real-Time Communication with Flask-SocketIO

 
  • Explanation: Instead of making users wait via standard HTTP requests, we leverage Flask-SocketIO allowing bidirectional communication between the server and client. This means that once the ML model finishes a prediction, it can push the result directly to the front end.
  • Installation: If you haven’t already installed Flask-SocketIO, install it via pip. (This guide skips environment setup instructions per the requirements.)

// Import and initialize Flask-SocketIO
from flask\_socketio import SocketIO, emit

socketio = SocketIO(app)

Defining the Prediction Endpoint and Socket Event

 
  • Prediction Endpoint: You create an endpoint that receives user input (for example, form data), uses the loaded ML model for prediction, and then returns the result
  • Real-time Feedback: Once the model returns a prediction, the server uses SocketIO to emit an event with the prediction result to the client.

// Define a route that renders the main page with SocketIO client code
@app.route("/")
def index():
    return render\_template("index.html")  // This HTML file must connect to the SocketIO server

// Define a route for making predictions via HTTP POST (optional if using SocketIO only)
@app.route("/predict", methods=["POST"])
def predict():
    data = request.get\_json()  // Accepts JSON input from the client
    // Assume the input is in the key 'input\_data'
    input_data = np.array(data["input_data"]).reshape(1, -1)
    prediction = model.predict(input\_data)
    
    // Send response back
    return jsonify({"prediction": prediction.tolist()})

// Define a SocketIO event for real time predictions
@socketio.on("request\_prediction")
def handle_prediction(json_data):
    // json_data is expected to have user input details in 'input_data'
    input_data = np.array(json_data["input\_data"]).reshape(1, -1)
    prediction = model.predict(input\_data)
    
    // Emit the prediction back to the client in real time
    emit("prediction\_response", {"prediction": prediction.tolist()})

Creating the Frontend (index.html) with Real-Time Updates

 
  • Explanation: In the frontend HTML, we include Socket.IO client scripts to communicate with our Flask server. Upon a user action (like clicking a button), the client emits an event to request a prediction and listens for the prediction result.
  • Key Concepts: 1) Emitting an event: The process of sending a message from the client to the server. 2) Listening for an event: The client (or server) waiting for a message from the other side.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Real-Time ML Feedback</title>
  // Include Socket.IO client script (from a CDN)
  <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.0/socket.io.js"></script>
</head>
<body>
  <h2>Invoke ML Prediction in Real-Time</h2>
  
  <div id="result"></div>
  
  <input type="text" id="userInput" placeholder="Enter data (comma separated)" />
  <button onclick="sendData()">Submit</button>
  
  <script type="text/javascript">
    // Connect to the SocketIO server
    var socket = io();
    
    // Function to send user input for prediction
    function sendData() {
      var inputText = document.getElementById("userInput").value;
      // Convert comma-separated input into an array of numbers
      var inputData = inputText.split(",").map(Number);
      
      // Emit the prediction request event to the server
      socket.emit("request_prediction", {"input_data": inputData});
    }
    
    // Listen for prediction response from the server
    socket.on("prediction\_response", function(data) {
      // Display the prediction result in div#result
      document.getElementById("result").innerHTML = "Prediction: " + data.prediction;
    });
  </script>
</body>
</html>

Running the Flask-SocketIO Application

 
  • Explanation: When using Flask-SocketIO, it is important to start the application with the SocketIO run command rather than the typical Flask app.run(). This ensures a proper websocket connection.
  • Implementation: Replace the standard Flask entry point with SocketIO's run method.

if **name** == "**main**":
    // Use socketio.run instead of app.run to start the server
    socketio.run(app, debug=True)

Troubleshooting and Key Considerations

 
  • Error Handling: Always add appropriate error handling on both backend and frontend. For instance, if the ML model input is not valid, return a descriptive error message.
  • Data Preprocessing: Ensure the data sent from the client is processed similarly to how the ML model was originally trained. This can involve normalization, reshaping, or encoding.
  • Scalability: For highly concurrent applications, consider production-ready tools like eventlet or gevent with Flask-SocketIO to handle concurrent connections efficiently.
  • Security: Validate and sanitize all user input to avoid injection or malicious data causing faults in your application.

Conclusion

 
  • Summary: You now have a comprehensive Flask application that integrates an ML model and provides real-time feedback using Flask-SocketIO. The key steps include loading the ML model, setting up relevant endpoints for predictions, enabling real-time communications, and building a frontend that listens for responses.
  • This guide should give you a complete, clear, and functional starting point to further improve and extend real-time interactions in your applications.


Recognized by the best

Trusted by 600+ businesses globally

From startups to enterprises and everything in between, see for yourself our incredible impact.

RapidDev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with.

They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

Arkady
CPO, Praction
Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost.

He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Donald Muir
Co-Founder, Arc
RapidDev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space.

They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Mat Westergreen-Thorne
Co-CEO, Grantify
RapidDev is an excellent developer for custom-code solutions.

We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Emmanuel Brown
Co-Founder, Church Real Estate Marketplace
Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 

This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Samantha Fekete
Production Manager, Media Production Company
The pSEO strategy executed by RapidDev is clearly driving meaningful results.

Working with RapidDev has delivered measurable, year-over-year growth. Comparing the same period, clicks increased by 129%, impressions grew by 196%, and average position improved by 14.6%. Most importantly, qualified contact form submissions rose 350%, excluding spam.

Appreciation as well to Matt Graham for championing the collaboration!

Michael W. Hammond
Principal Owner, OCD Tech

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We’ll discuss your project and provide a custom quote at no cost.