Skip to content

About

Transformer-based offensive language detection using DistilBERT embeddings, sentiment analysis, CI/CD testing, and an interactive Streamlit web application.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

ย 

History

31 Commits

Folders and files

Repository files navigation

OffensEval NLP Banner

๐Ÿšจ OffensEval NLP

Transformer-Based Offensive Language Detection with Sentiment-Aware Modeling

A cloud-deployed NLP application for real-time offensive language detection using DistilBERT sentence embeddings, VADER sentiment features, and a Logistic Regression classifier.

The system is implemented using a production-style architecture with a FastAPI inference backend, an interactive Streamlit frontend, Docker containers, Azure Container Registry, and Azure Container Apps.


๐ŸŒ Live Application

Frontend

https://offenseval-frontend.icysea-bc6cd350.centralindia.azurecontainerapps.io/

The live application provides real-time offensive language classification, confidence scores, cleaned-text visibility, and sentiment-aware output. The production inference backend is not exposed as a public portfolio endpoint.


๐Ÿ“Œ Project Overview

OffensEval NLP is an end-to-end machine learning application designed to identify offensive language in user-provided text.

The project combines transformer-based semantic representations with sentiment information to improve contextual understanding. DistilBERT sentence embeddings are generated through SentenceTransformers, while VADER sentiment scores are added as an additional numerical feature. The combined feature vector is passed to a Logistic Regression classifier for binary prediction.

The application is divided into two independently deployed services:

  • A FastAPI backend responsible for preprocessing, model loading, sentiment analysis, and prediction
  • A Streamlit frontend responsible for user interaction and result presentation

Both services are containerized using Docker, stored in Azure Container Registry, and deployed through Azure Container Apps.


๐ŸŽฏ Key Features

  • ๐Ÿ” DistilBERT sentence embeddings through SentenceTransformers
  • ๐Ÿ˜Š Sentiment-aware feature augmentation using VADER
  • โš–๏ธ Interpretable Logistic Regression classifier
  • ๐Ÿ“Š Prediction confidence and sentiment distribution
  • ๐Ÿงน Centralized text preprocessing
  • โšก FastAPI REST inference service
  • ๐ŸŒ Interactive Streamlit frontend
  • ๐Ÿณ Dockerized frontend and backend
  • โ˜๏ธ Deployment through Azure Container Apps
  • ๐Ÿ“ฆ Container storage through Azure Container Registry
  • ๐Ÿงช Automated testing with PyTest
  • โค๏ธ Backend health monitoring
  • ๐Ÿ“ Modular production-style repository structure

๐Ÿ”’ Security Notes

  • Only the Streamlit frontend is intended to be publicly accessible in production.
  • The FastAPI inference service should use internal ingress within the Azure Container Apps environment.
  • Production credentials, tokens, registry passwords, connection strings, and .env files must never be committed to the repository.
  • Public deployment documentation intentionally omits production backend addresses and sensitive cloud configuration.
  • Cost controls, scaling limits, and monitoring should be configured separately in Azure.

๐Ÿ—๏ธ System Architecture

                         User
                           โ”‚
                           โ–ผ
                  Streamlit Frontend
              Public Azure Container App
                           โ”‚
                           โ”‚ Internal HTTPS
                           โ–ผ
                    FastAPI Backend
             Internal Azure Container App
                           โ”‚
                           โ–ผ
              Text Cleaning and Normalization
                           โ”‚
                           โ–ผ
           DistilBERT Sentence Embeddings (768D)
                           โ”‚
                    โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                    โ”‚               โ”‚
                    โ–ผ               โ–ผ
            Semantic Features   VADER Sentiment
                    โ”‚               โ”‚
                    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                            โ–ผ
              Feature Concatenation (769D)
                            โ”‚
                            โ–ผ
               Logistic Regression Model
                            โ”‚
                            โ–ผ
            Prediction, Confidence, Sentiment

๐Ÿง  Machine Learning Pipeline

Input Text
   โ†“
Text Cleaning and Normalization
   โ†“
DistilBERT Sentence Embedding
   โ†“
VADER Sentiment Feature
   โ†“
Feature Concatenation
   โ†“
Logistic Regression Classification
   โ†“
Offensive / Not Offensive Prediction

Feature Dimensions

Component Dimensions
DistilBERT sentence embedding 768
VADER compound sentiment score 1
Final feature vector 769

๐Ÿ› ๏ธ Technology Stack

Category Technology
Programming Language Python 3.12
Backend Framework FastAPI
Frontend Framework Streamlit
ASGI Server Uvicorn
Machine Learning Scikit-learn
Embeddings SentenceTransformers
Transformer Model DistilBERT
Sentiment Analysis VADER
Validation Pydantic
Testing PyTest
Containerization Docker
Local Orchestration Docker Compose
Container Registry Azure Container Registry
Cloud Deployment Azure Container Apps
Version Control Git and GitHub

๐Ÿ“Š Dataset

  • Dataset: TweetEval โ€“ Offensive Language

  • Task: Binary text classification

  • Classes:

    • Offensive
    • Not Offensive

TweetEval provides benchmark datasets for evaluating language models on social media classification tasks. This project uses the offensive language subset for supervised model development and validation.


๐Ÿ“ˆ Model Performance

Metric Validation Score
Macro F1 ~0.72
ROC-AUC ~0.81

The reported values are based on a held-out validation set used during model development.


๐ŸŒ Web Application Features

The Streamlit frontend provides:

  • Preprocessed text preview
  • Offensive or non-offensive prediction
  • Prediction confidence
  • VADER compound sentiment score
  • Positive, neutral, and negative sentiment percentages
  • Sentiment category
  • Color-coded sentiment visualizations
  • Backend availability check
  • Error handling for failed API requests
  • Clear usage disclaimer

โšก REST API

The FastAPI backend provides application-internal endpoints for service information, health checks, and offensive-language prediction.

Method Endpoint Description
GET / API information
GET /health Backend and model health check
POST /predict Offensive language prediction

The production backend is intended for communication from the deployed frontend within the application environment. Local development can access these endpoints through http://127.0.0.1:8000.


๐Ÿ“ฅ Example Prediction Request

For local development:

curl -X POST \
  "http://127.0.0.1:8000/predict" \
  -H "Content-Type: application/json" \
  -d '{
    "text": "You are an idiot."
  }'

๐Ÿ“ค Example Prediction Response

{
  "prediction": "Offensive",
  "confidence": 0.94,
  "cleaned_text": "you are an idiot",
  "sentiment_score": -0.73,
  "sentiment_category": "Negative",
  "positive_score": 0.0,
  "neutral_score": 0.29,
  "negative_score": 0.71
}

Exact prediction values depend on the trained model and input text.


๐Ÿ“ Repository Structure

offenseval-nlp/
โ”‚
โ”œโ”€โ”€ assets/
โ”‚   โ””โ”€โ”€ offenseval-nlp-banner.png
โ”‚
โ”œโ”€โ”€ backend/
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ config.py
โ”‚   โ”œโ”€โ”€ inference.py
โ”‚   โ”œโ”€โ”€ main.py
โ”‚   โ”œโ”€โ”€ preprocessing.py
โ”‚   โ””โ”€โ”€ schemas.py
โ”‚
โ”œโ”€โ”€ frontend/
โ”‚   โ””โ”€โ”€ app.py
โ”‚
โ”œโ”€โ”€ embeddings/
โ”‚   โ”œโ”€โ”€ X_train_distil.npy
โ”‚   โ”œโ”€โ”€ X_val_distil.npy
โ”‚   โ”œโ”€โ”€ X_test_distil.npy
โ”‚   โ”œโ”€โ”€ X_train_minilm.npy
โ”‚   โ”œโ”€โ”€ X_val_minilm.npy
โ”‚   โ”œโ”€โ”€ X_test_minilm.npy
โ”‚   โ”œโ”€โ”€ y_train.npy
โ”‚   โ”œโ”€โ”€ y_val.npy
โ”‚   โ””โ”€โ”€ y_test.npy
โ”‚
โ”œโ”€โ”€ model/
โ”‚   โ”œโ”€โ”€ final_model_tuned_distilbert.joblib
โ”‚   โ””โ”€โ”€ label_encoder.json
โ”‚
โ”œโ”€โ”€ tests/
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ pytest.ini
โ”‚   โ”œโ”€โ”€ test_api.py
โ”‚   โ”œโ”€โ”€ test_inference.py
โ”‚   โ””โ”€โ”€ test_preprocessing.py
โ”‚
โ”œโ”€โ”€ Dockerfile.backend
โ”œโ”€โ”€ Dockerfile.frontend
โ”œโ”€โ”€ docker-compose.yml
โ”œโ”€โ”€ requirements.txt
โ”œโ”€โ”€ Model_Training_and_Evaluation.ipynb
โ”œโ”€โ”€ .dockerignore
โ”œโ”€โ”€ .gitignore
โ”œโ”€โ”€ LICENSE
โ””โ”€โ”€ README.md

๐Ÿš€ Running the Project Locally

1. Clone the repository

git clone https://github.com/ArunavaKumar/offenseval-nlp.git
cd offenseval-nlp

2. Create a virtual environment

python -m venv .venv
source .venv/bin/activate

For Windows:

.venv\Scripts\activate

3. Install dependencies

pip install --upgrade pip
pip install -r requirements.txt

4. Start the FastAPI backend

uvicorn backend.main:app --reload

The backend will be available at:

http://127.0.0.1:8000

API documentation:

http://127.0.0.1:8000/docs

5. Start the Streamlit frontend

Open another terminal and run:

streamlit run frontend/app.py

The frontend will usually be available at:

http://localhost:8501

๐Ÿณ Running with Docker Compose

Build and start both services:

docker compose up --build

The services will be available at:

Service Local Address
Streamlit frontend http://localhost:8501
FastAPI backend http://localhost:8000
FastAPI documentation http://localhost:8000/docs

Stop the services with:

docker compose down

๐Ÿงช Automated Testing

Run the complete test suite:

python -m pytest -v

The tests validate:

  • Root endpoint availability
  • Health endpoint response
  • Prediction endpoint response
  • Model loading
  • Request and response schema compatibility
  • Text preprocessing
  • Prediction confidence range
  • Sentiment score output

โ˜๏ธ Azure Deployment Architecture

Local Development
       โ”‚
       โ–ผ
Docker Images
       โ”‚
       โ–ผ
Azure Container Registry
       โ”‚
       โ–ผ
Azure Container Apps Environment
       โ”‚
       โ”œโ”€โ”€ Streamlit Frontend
       โ”‚      Public HTTPS ingress
       โ”‚
       โ””โ”€โ”€ FastAPI Backend
              Internal application ingress

The frontend is the public portfolio entry point. The inference backend is deployed as a separate service and is intended to communicate with the frontend through the Azure Container Apps environment.

Deployed Azure Resources

Resource Type Purpose
Resource Group Groups project cloud resources
Container Registry Stores frontend and backend container images
Container Apps Environment Hosts the application services
Frontend Container App Public Streamlit portfolio interface
Backend Container App Internal FastAPI inference service
Azure Region Central India

๐Ÿ”„ Deployment Workflow

Application updates follow a container-based deployment workflow:

  1. Modify and test the application locally.
  2. Build updated frontend or backend Docker images.
  3. Push versioned images to Azure Container Registry.
  4. Update the corresponding Azure Container App revision.
  5. Validate frontend availability and backend health.
  6. Keep production credentials and service configuration outside the repository.

Deployment commands depend on the target Azure subscription, registry, resource group, and application configuration, so production-specific values are intentionally omitted from this public README.


๐Ÿฉบ Health Monitoring

The backend includes an internal health endpoint:

GET /health

Example response:

{
  "status": "healthy",
  "model_ready": true
}

This endpoint verifies that:

  • The FastAPI service is running
  • The trained model has loaded successfully
  • The backend is ready to accept prediction requests

In production, health checks are used for application monitoring and service-to-service validation rather than being advertised as a public endpoint.


๐Ÿ” Environment Configuration

The frontend connects to the backend through the API_URL environment variable.

Local default:

http://127.0.0.1:8000

Example local configuration:

export API_URL=http://127.0.0.1:8000

Production service addresses, credentials, registry authentication, and other environment-specific values are intentionally excluded from the public repository and should be configured through the deployment environment.


โš ๏ธ Disclaimer and Limitations

This application predicts offensive language based on patterns learned from social media text.

Known limitations include:

  • Sarcasm and humor may be interpreted incorrectly
  • Cultural and regional language differences may be missed
  • Indirect insults may not always be detected
  • Quoted offensive language may be classified without understanding intent
  • Very short or ambiguous text may produce uncertain predictions
  • Sentiment does not always correspond directly to offensiveness
  • Model outputs may reflect biases present in the training data

The application is intended to support content analysis and experimentation. It should not replace human review in high-impact moderation or disciplinary decisions.


๐Ÿ”ฎ Future Improvements

  • Multi-class toxicity detection
  • Hate-speech category classification
  • Explainable AI using SHAP or LIME
  • Batch prediction endpoint
  • Authentication and rate limiting
  • GitHub Actions CI/CD
  • Azure Monitor and Application Insights
  • Structured application logging
  • Model version tracking
  • Drift monitoring
  • Database-backed prediction history
  • Kubernetes deployment
  • Transformer fine-tuning instead of fixed embeddings

๐Ÿ‘จโ€๐Ÿ’ป Developer

Arunava Kumar Chakraborty

Data Analyst | Machine Learning Enthusiast


๐Ÿ“œ License

This project is licensed under the MIT License.

See the LICENSE file for details.


โญ Acknowledgements

  • Hugging Face
  • SentenceTransformers
  • DistilBERT
  • VADER Sentiment Analysis
  • TweetEval
  • FastAPI
  • Streamlit
  • Docker
  • Microsoft Azure

About

Transformer-based offensive language detection using DistilBERT embeddings, sentiment analysis, CI/CD testing, and an interactive Streamlit web application.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages