ToxGuard AI is a production-ready, full-stack application designed to automatically detect and classify toxic language in user-generated content. Built to solve the pervasive issue of online harassment and abusive behavior, the project uses a custom-trained Bidirectional LSTM deep learning model to evaluate text across six specific dimensions of toxicity.
The system features a sleek, highly responsive frontend interface built with React and TailwindCSS, communicating with a robust, memory-optimized Python FastAPI backend. The entire application is containerized using Docker, allowing for seamless deployment to modern cloud platforms.
- ๐ง Deep Learning Inference: Accurately classifies text across 6 categories (Toxic, Severe Toxic, Obscene, Threat, Insult, Identity Hate).
- โก Real-Time Analysis: Lightning-fast API responses powered by FastAPI and an optimized TensorFlow pipeline.
- ๐จ Modern UI/UX: Premium dark-mode interface with glassmorphism effects, built with TailwindCSS v4 and Framer Motion.
- ๐ณ Containerized Architecture: Fully dockerized services with
docker-composefor rapid local development and production deployment. - ๐ Memory Optimized: TensorFlow threading and memory configuration tuned specifically for low-resource environments (e.g., Render free tier).
- ๐ Scan History: Locally persisted session history for easy review of recent scans.
| Category | Technologies |
|---|---|
| Frontend | React 19, TypeScript, Vite, TailwindCSS v4, Framer Motion, Lucide-React |
| Backend | FastAPI, Python 3.9, Uvicorn, Pydantic |
| AI / Machine Learning | TensorFlow 2.15 (CPU), Keras, Pandas, NumPy |
| Deep Learning Architecture | Bidirectional LSTM, Embedding layers, TextVectorization |
| DevOps & Deployment | Docker, Docker Compose, NGINX, Render |
The system follows a modern decoupled frontend/backend architecture, communicating via RESTful API over HTTP.
graph TD
Client[Web Browser] -->|HTTP POST| UI[React Frontend]
UI -->|JSON Request| API[FastAPI Backend]
subgraph Backend Service
API -->|Text Processing| Pre[TextVectorization Layer]
Pre -->|Token Sequences| ML[TensorFlow Bi-LSTM Model]
ML -->|Probabilities| API
end
API -->|JSON Response| UI
UI -->|Render UI| Client
The machine learning pipeline takes raw text strings and maps them through a robust sequence model to output classification probabilities.
- Dataset: Trained on the Jigsaw Toxic Comment Classification Challenge dataset (
train.csv). - Preprocessing: Handled dynamically using Keras
TextVectorization. The model utilizes a vocabulary constraint mapped dynamically from an extractedvocab.pkl. - Model Architecture:
- Embedding Layer: Maps vocabulary indices to dense 32-dimensional vectors.
- Bidirectional LSTM: 32 units utilizing
tanhactivation to capture context from both directions. - Fully Connected (Dense) Layers: Three dense layers (128 โ 256 โ 128 units) with
reluactivation for feature extraction. - Output Layer: 6 units with
sigmoidactivation for multi-label binary classification.
- Training: Compiled with Binary Crossentropy loss and the Adam optimizer.
- Inference Adjustments: The backend includes explicit profanity overrides and scaled thresholds to counter LSTM padding dilution on longer sequences.
- Type: Deep Sequence Model (NLP)
- Framework: TensorFlow / Keras
- Input: Raw text string
- Output: 6-dimensional float array (Probabilities:
0.0to1.0)
project/
โโโ backend/ # FastAPI Backend Service
โ โโโ main.py # Application entry point & API routes
โ โโโ config.py # Environment & configuration settings
โ โโโ requirements.txt # Python dependencies
โ โโโ Dockerfile # Backend container definition
โ โโโ model/ # ML Assets
โ โ โโโ model_service.py # TF model loader & inference engine
โ โ โโโ toxicity.h5 # Pre-trained model weights
โ โ โโโ vocab.pkl # Serialized vocabulary map
โ โโโ scripts/ # Utilities
โ โ โโโ extract_vocab.py # Vocab extraction script
โ โโโ utils/
โ โโโ schemas.py # Pydantic request/response models
โโโ frontend/ # React Frontend Service
โ โโโ src/
โ โ โโโ App.tsx # Main React component & UI
โ โ โโโ api.ts # Axios API client
โ โ โโโ index.css # Tailwind directives
โ โ โโโ main.tsx # React DOM entry
โ โโโ package.json # Node dependencies
โ โโโ vite.config.ts # Vite configuration
โ โโโ Dockerfile # NGINX frontend container definition
โโโ docker-compose.yml # Multi-container orchestration
Backend Setup:
cd project/backend
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
uvicorn main:app --reload --port 8000Frontend Setup:
cd project/frontend
npm install
npm run devThe application will be accessible at http://localhost:5173.
To run the entire stack locally using Docker:
cd project
docker compose up --build -d- Frontend: Access via
http://localhost:3000 - Backend API: Access via
http://localhost:8000
The project utilizes multi-stage Docker builds to ensure lean production images:
- Backend Container: Uses
python:3.9-slim. Injects specific environment variables (MALLOC_ARENA_MAX,TF_NUM_INTEROP_THREADS) to limit TensorFlow memory footprint. - Frontend Container: Uses
node:22-alpinefor the build stage andnginx:alpineto serve the static SPA assets.
The application is configured for seamless deployment to Render. Both the backend and frontend can be deployed directly from your GitHub repository.
- In your Render Dashboard, click New + and select Web Service.
- Connect your GitHub repository.
- Set the following configurations:
- Environment:
Docker - Build Command: (Leave default, Render uses the Dockerfile)
- Start Command:
uvicorn main:app --host 0.0.0.0 --port $PORT - Instance Type: Minimum 512MB RAM (Free tier is sufficient but might take slightly longer to boot).
- Environment:
- Click Create Web Service.
- In your Render Dashboard, click New + and select Static Site.
- Connect the same GitHub repository.
- Set the following configurations:
- Root Directory:
project/frontend(or justfrontenddepending on your repo structure) - Build Command:
npm install && npm run build - Publish Directory:
dist
- Root Directory:
- Add the following Environment Variable:
VITE_API_URL: Set this to your newly deployed backend URL (e.g.,https://toxguard-backend.onrender.com).
- Add a Rewrite Rule (for React Router/SPA support):
- Source:
/* - Destination:
/index.html - Action:
Rewrite
- Source:
- Click Create Static Site.
Analyzes a text string and returns toxicity probabilities.
Request Body:
{
"text": "The comment text to analyze"
}Response:
{
"text": "The comment text to analyze",
"predictions": {
"toxic": { "probability": 0.12, "flag": false },
"severe_toxic": { "probability": 0.01, "flag": false },
"obscene": { "probability": 0.05, "flag": false },
"threat": { "probability": 0.00, "flag": false },
"insult": { "probability": 0.08, "flag": false },
"identity_hate": { "probability": 0.02, "flag": false }
},
"is_toxic": false
}Health check endpoint used for load balancer pinging.
Response:
{
"status": "healthy",
"model_loaded": true,
"version": "1.0.0"
}
Analyze text with real-time probability breakdown.
Review historical comment scans using the persistent history log.
- Transformer Migration: Upgrade the Bi-LSTM model to a lightweight Transformer (e.g., DistilBERT) for better contextual understanding.
- Multilingual Support: Expand the dataset and tokenizer to support multiple languages.
- Explainable AI (XAI): Highlight the exact words or phrases in the UI that triggered the toxicity flags.
- Rate Limiting: Implement API rate limiting in FastAPI using
slowapito prevent abuse in production.
Contributions are always welcome! Please follow these steps:
- Fork the project.
- Create your feature branch (
git checkout -b feature/AmazingFeature). - Commit your changes (
git commit -m 'Add some AmazingFeature'). - Push to the branch (
git push origin feature/AmazingFeature). - Open a Pull Request.
Distributed under the MIT License. See LICENSE for more information.
Aaditya
- Software Engineer & ML Practitioner
- Passionate about building robust AI-driven applications and solving real-world problems.