Sure! Here's an example of an advanced Python program that combines several high-level concepts, including:
Asynchronous programming with asyncio
Machine learning with PyTorch
Web API with FastAPI
Real-time streaming using WebSockets
Background task scheduling
Type hinting and Pydantic models
Dependency injection
This example creates a real-time sentiment analysis API using a pre-trained transformer model (from Hugging Face), served via FastAPI, with WebSocket support for live updates.
🚀 Advanced Python Code: Real-Time Sentiment Analysis API
python
# Install required packages before running:
# pip install fastapi uvicorn transformers torch pydantic[dotenv] aiofiles
import asyncio
from typing import List
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, BackgroundTasks
from pydantic import BaseModel
from transformers import pipeline
import torch
# Initialize FastAPI app
app = FastAPI(title="Real-Time Sentiment Analysis API")
# Load sentiment analysis pipeline (using Hugging Face Transformers)
device = 0 if torch.cuda.is_available() else -1
sentiment_pipeline = pipeline("sentiment-analysis", device=device)
# Pydantic model for HTTP POST requests
class TextInput(BaseModel):
texts: List[str]
# In-memory store for connected WebSocket clients
class ConnectionManager:
def __init__(self):
self.active_connections: List[WebSocket] = []
async def connect(self, websocket: WebSocket):
await websocket.accept()
self.active_connections.append(websocket)
print(f"Client connected: {websocket.client}")
def disconnect(self, websocket: WebSocket):
self.active_connections.remove(websocket)
print(f"Client disconnected: {websocket.client}")
async def broadcast(self, message: dict):
for connection in self.active_connections:
await connection.send_json(message)
manager = ConnectionManager()
# Background task to analyze sentiment and broadcast results
async def analyze_and_broadcast(text: str):
result = sentiment_pipeline(text)[0]
await manager.broadcast({
"text": text,
"label": result['label'],
"score": round(result['score'], 4)
})
# HTTP endpoint for batch sentiment analysis
@app.post("/analyze")
async def analyze_text(input: TextInput, background_tasks: BackgroundTasks):
results = []
for text in input.texts:
result = sentiment_pipeline(text)[0]
results.append({
"text": text,
"label": result['label'],
"score": round(result['score'], 4)
})
background_tasks.add_task(analyze_and_broadcast, text)
return {"results": results}
# WebSocket endpoint for real-time updates
@app.websocket("/ws/sentiment")
async def websocket_endpoint(websocket: WebSocket):
await manager.connect(websocket)
try:
while True:
data = await websocket.receive_text()
asyncio.create_task(analyze_and_broadcast(data))
except WebSocketDisconnect:
manager.disconnect(websocket)
# Root endpoint
@app.get("/")
async def root():
return {"message": "Welcome to the Real-Time Sentiment Analysis API!"}