Integrating Artificial Intelligence into Web Applications with Flask



Artificial Intelligence (AI) has become an essential component in modern web applications, enabling personalized user experiences, automation, and advanced analytics. Integrating AI into web applications can transform how users interact with your services. In this article, we will guide you through the process of integrating AI into a web application using Flask, a lightweight and powerful web framework for Python.

Why Integrate AI into Web Applications?

Integrating AI into web applications offers numerous benefits, including:
  • Enhanced User Experience: AI can provide personalized recommendations, chatbots, and intelligent search capabilities.
  • Automation: Automate repetitive tasks and decision-making processes.
  • Advanced Analytics: Gain deeper insights from data through predictive analytics and data visualization.

Getting Started with Flask

Before we dive into the integration process, make sure you have Flask installed. You can install Flask using pip:

bash

pip install flask

Step 1: Setting Up the Flask Application

Create a new directory for your project and set up a basic Flask application. In this example, we'll create an application that predicts house prices using a pre-trained AI model.

python

# app.py from flask import Flask, request, jsonify import numpy as np import joblib app = Flask(__name__) # Load the pre-trained model model = joblib.load('house_price_model.pkl') @app.route('/') def home(): return "Welcome to the House Price Prediction API!" @app.route('/predict', methods=['POST']) def predict(): data = request.get_json(force=True) features = np.array([data['features']]) prediction = model.predict(features) return jsonify({'prediction': prediction[0]}) if __name__ == '__main__': app.run(debug=True)


Step 2: Pre-Training the AI Model

For this example, we assume you have a pre-trained machine learning model for house price prediction. You can train the model using Scikit-Learn and save it using joblib.

python

import numpy as np import pandas as pd from sklearn.datasets import fetch_california_housing from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LinearRegression import joblib # Load the California Housing dataset data = fetch_california_housing() X = pd.DataFrame(data.data, columns=data.feature_names) y = data.target # Split the data into training and testing sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Standardize the features scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) # Train the model model = LinearRegression() model.fit(X_train, y_train) # Save the model joblib.dump(model, 'house_price_model.pkl')


Step 3: Creating the HTML Frontend

To interact with our Flask API, we'll create a simple HTML form that allows users to input house features and get a price prediction.

html

<!-- index.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>House Price Prediction</title> </head> <body> <h1>House Price Prediction</h1> <form id="prediction-form"> <label for="features">Enter house features:</label><br> <input type="text" id="features" name="features" placeholder="Enter comma-separated features"><br><br> <button type="button" onclick="getPrediction()">Predict Price</button> </form> <p id="prediction-result"></p> <script> function getPrediction() { const features = document.getElementById('features').value.split(',').map(Number); fetch('/predict', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ features: features }) }) .then(response => response.json()) .then(data => { document.getElementById('prediction-result').innerText = 'Predicted Price: $' + data.prediction.toFixed(2); }) .catch(error => console.error('Error:', error)); } </script> </body> </html>


Step 4: Running the Flask Application

Save the HTML file in the templates folder within your project directory. Then, modify your Flask application to render the HTML file.

python

# app.py from flask import Flask, request, jsonify, render_template import numpy as np import joblib app = Flask(__name__) # Load the pre-trained model model = joblib.load('house_price_model.pkl') @app.route('/') def home(): return render_template('index.html') @app.route('/predict', methods=['POST']) def predict(): data = request.get_json(force=True) features = np.array([data['features']]) prediction = model.predict(features) return jsonify({'prediction': prediction[0]}) if __name__ == '__main__': app.run(debug=True)

Run the Flask application:

bash

python app.py

Open your browser and navigate to http://127.0.0.1:5000/ to see your house price prediction application in action.


Conclusion

In this article, we demonstrated how to integrate AI into a web application using Flask. We built a simple house price prediction application that uses a pre-trained machine learning model to provide predictions based on user input. By following these steps, you can create powerful AI-driven web applications that enhance user experiences and provide valuable insights.
Flask's simplicity and flexibility make it an excellent choice for integrating AI into web applications. As you gain more experience, you can explore more advanced techniques and models to create even more sophisticated applications.

Share:

0 Comments:

New Post

Recent Posts

    Support Me