python-web-development ai-powered-web-apps fastapi-tutorial fastapi-machine-learning building-ai-apps python-ai-integration web-development-with-fastapi sentiment-analysis-app fastapi-api-tutorial ai-powered-web-applications
Tutorial: Building AI-Powered Web Apps with Python and FastAPI
In this tutorial, we will walk through how to build an AI-powered web application using Python and FastAPI. FastAPI is a modern, fast (high-performance) web framework that is particularly suited for building APIs with Python. Combining it with AI tools, such as machine learning models, allows us to create powerful web applications.
Prerequisites
- Basic knowledge of Python
- Familiarity with machine learning concepts (optional but helpful)
- Python installed on your machine
- Basic understanding of FastAPI and web development
Step 1: Setting up FastAPI
Before diving into the AI part, let’s first set up FastAPI to create a web application.
- Install FastAPI and Uvicorn:
FastAPI works best with Uvicorn, a lightweight ASGI server. You can install them both via pip:
pip install fastapi uvicorn
- Create a Basic FastAPI App:
Start by creating a basic FastAPI application to test that everything is working correctly.
# app.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Welcome to the AI-powered web app!"}
- Run the App:
You can run the app using Uvicorn:
uvicorn app:app --reload
Visit http://127.0.0.1:8000/
to check if the app is running.
Step 2: Integrating Machine Learning with FastAPI
Let’s add AI functionality to the application. For this example, we’ll use a pre-trained machine learning model for text sentiment analysis, leveraging the Hugging Face's transformers
library.
- Install Required Libraries:
Install the transformers
and torch
libraries to use pre-trained AI models from Hugging Face.
pip install transformers torch
- Loading a Pre-trained AI Model:
Load a sentiment analysis model from Hugging Face’s model hub. We’ll use the distilbert-base-uncased-finetuned-sst-2-english
model for sentiment analysis.
from transformers import pipeline
# Load the pre-trained sentiment-analysis pipeline
sentiment_analysis = pipeline("sentiment-analysis")
- Integrating the Model with FastAPI:
Let’s create an API endpoint where users can submit text, and the app will return the sentiment of that text using the AI model.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
# Define request body
class TextInput(BaseModel):
text: str
# Endpoint for sentiment analysis
@app.post("/analyze/")
def analyze_text(input: TextInput):
result = sentiment_analysis(input.text)
return {"text": input.text, "sentiment": result[0]}
- Test the Endpoint:
Restart your server and test the endpoint. You can use a tool like Postman or CURL to send a POST request to http://127.0.0.1:8000/analyze/
with the following body:
{
"text": "I love learning FastAPI!"
}
The response will return the sentiment analysis:
{
"text": "I love learning FastAPI!",
"sentiment": {
"label": "POSITIVE",
"score": 0.9998
}
}
Step 3: Creating a Frontend for the Web App
Next, let’s add a simple frontend for the web app where users can submit text and view the sentiment analysis results.
- Add HTML and JavaScript:
We will serve a basic HTML page that allows users to input text and see the results.
from fastapi.responses import HTMLResponse
@app.get("/", response_class=HTMLResponse)
def home():
html_content = """
<html>
<head>
<title>AI Sentiment Analysis</title>
</head>
<body>
<h1>Enter text for Sentiment Analysis</h1>
<form action="/analyze/" method="post" id="form">
<textarea name="text" rows="4" cols="50"></textarea><br>
<button type="submit">Analyze</button>
</form>
<div id="result"></div>
<script>
const form = document.getElementById('form');
form.addEventListener('submit', async (e) => {
e.preventDefault();
const formData = new FormData(form);
const response = await fetch('/analyze/', {
method: 'POST',
body: JSON.stringify({ text: formData.get('text') }),
headers: {
'Content-Type': 'application/json'
}
});
const result = await response.json();
document.getElementById('result').innerText = 'Sentiment: ' + result.sentiment.label;
});
</script>
</body>
</html>
"""
return HTMLResponse(content=html_content)
- Testing the Frontend:
With this frontend, you can now visit http://127.0.0.1:8000/
, enter some text, and get the sentiment analysis results directly on the web page without needing Postman or CURL.
Step 4: Deploying the Web App
Once your AI-powered web app is ready, you can deploy it using platforms like Heroku, AWS, or DigitalOcean.
- Deploy on Heroku:
- Create a
Procfile
that tells Heroku how to run your application:
web: uvicorn app:app --host=0.0.0.0 --port=${PORT:-5000}
- Push your app to a Git repository and deploy it on Heroku following their deployment instructions.
- Deploy on DigitalOcean:
- You can use Docker to containerize your app and deploy it on DigitalOcean’s App Platform.
Conclusion
In this tutorial, we built a basic AI-powered web app using Python, FastAPI, and Hugging Face's transformers library. This app allows users to perform sentiment analysis by interacting with a simple web interface. FastAPI’s speed and ease of use make it an excellent choice for integrating AI models into production-ready web applications.
With this foundation, you can expand the app by integrating more advanced AI models, adding user authentication, or scaling it using cloud platforms.
Comments
Please log in to leave a comment.