Arabic Sentiment Analysis with AraBERT v2 — fine-tuned NLP pipeline for Arabic text classification (positive/negative/neutral) with custom training loop, Streamlit demo, and full evaluation suite
Python
2
0 commits
updated Jan 30, 2026
Deep learning pipeline for Arabic text sentiment classification using fine-tuned AraBERT
Features · Architecture · Results · Quick Start · Demo
Arabic is the 5th most spoken language globally (~400M+ speakers), yet it remains severely underrepresented in NLP research and tooling. Most sentiment analysis solutions are English-first, leaving Arabic-speaking markets — e-commerce, social media, customer support — without reliable automated sentiment understanding.
This project builds a production-ready Arabic sentiment analysis pipeline that handles the unique challenges of Arabic NLP:
By fine-tuning AraBERT v2 — a BERT model pre-trained on 77GB of Arabic text — this pipeline achieves strong 3-class sentiment classification (positive / neutral / negative) on real-world Arabic social media data.
| Feature | Description |
|---|---|
| 🏗️ Custom Training Loop | Full control over learning rate scheduling, gradient clipping, and mixed-precision training |
| 🔤 AraBERT Preprocessing | Arabic-specific normalization, diacritics removal, and Farasa segmentation |
| 📊 Multi-Dataset Support | Combines ArSarcasm (~12K) + AJGT (~1.8K) for robust training |
| 📈 Comprehensive Evaluation | Per-class metrics, confusion matrix, training curves, classification reports |
| 🚀 Production Inference | Single text, batch prediction, and interactive CLI mode |
| 🎨 Streamlit Demo | Interactive web UI with real-time probability visualization |
| 🔁 Reproducible | Seeded random states, pinned dependencies, configuration management |
┌─────────────────────────────────────────────────────────┐
│ Raw Arabic Text │
│ "هذا المنتج ممتاز والجودة عالية" │
└───────────────────────┬─────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ Arabic Preprocessing Layer │
│ ┌─────────────┐ ┌──────────────┐ ┌──────────────────┐ │
│ │ Diacritics │ │ Character │ │ AraBERT-Specific│ │
│ │ Removal │ │Normalization │ │ Preparation │ │
│ └─────────────┘ └──────────────┘ └──────────────────┘ │
└───────────────────────┬─────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ AraBERT v2 Tokenizer (WordPiece) │
│ max_length = 128 │
└───────────────────────┬─────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ AraBERT v2 Transformer Encoder │
│ 12 layers · 768 hidden · 12 heads · 136M params │
└───────────────────────┬─────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ Classification Head: [CLS] → Dropout → Linear │
│ 768 → 3 classes │
│ (Optional: 2-layer MLP with GELU activation) │
└───────────────────────┬─────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ 😞 Negative │ 😐 Neutral │ 😊 Positive │
└─────────────────────────────────────────────────────────┘
| Metric | Score |
|---|---|
| F1 (weighted) | ~0.85 |
| Accuracy | ~0.84 |
| Precision (weighted) | ~0.85 |
| Recall (weighted) | ~0.84 |
| Class | Precision | Recall | F1-Score |
|---|---|---|---|
| 😞 Negative | ~0.88 | ~0.87 | ~0.87 |
| 😐 Neutral | ~0.72 | ~0.70 | ~0.71 |
| 😊 Positive | ~0.86 | ~0.88 | ~0.87 |
Approximate scores from training on combined ArSarcasm + AJGT datasets. Run
python scripts/train.pyfollowed bypython scripts/evaluate.pyto reproduce exact results on your hardware.
| Parameter | Value |
|---|---|
| Base Model | aubmindlab/bert-base-arabertv2 |
| Optimizer | AdamW (weight decay: 0.01) |
| Learning Rate | 2e-5 with linear warmup (10%) + decay |
| Batch Size | 32 |
| Epochs | 5 |
| Mixed Precision | FP16 (CUDA) |
| Gradient Clipping | max norm 1.0 |
arabic-sentiment-analysis/
├── src/ # Core library
│ ├── __init__.py # Package exports
│ ├── config.py # Configuration dataclasses
│ ├── preprocessing.py # Arabic text preprocessing
│ ├── dataset.py # Dataset loading & DataLoaders
│ ├── model.py # AraBERT classifier architecture
│ ├── trainer.py # Custom training loop
│ ├── evaluate.py # Evaluation & visualization
│ └── inference.py # Prediction & interactive mode
├── scripts/ # Entry points
│ ├── train.py # Training script
│ ├── evaluate.py # Evaluation script
│ └── predict.py # Prediction script
├── app/
│ └── streamlit_app.py # Interactive demo app
├── tests/ # Unit & integration tests
│ ├── __init__.py
│ ├── test_preprocessing.py
│ ├── test_model.py
│ └── test_config.py
├── models/ # Saved checkpoints (.gitignored)
├── data/ # Dataset cache (.gitignored)
├── results/ # Evaluation outputs
├── requirements.txt
├── LICENSE
└── README.md
git clone https://github.com/salehA13/arabic-sentiment-analysis.git
cd arabic-sentiment-analysis
python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
pip install -r requirements.txt
# Default configuration (5 epochs, batch_size=32, lr=2e-5)
python scripts/train.py
# Custom hyperparameters
python scripts/train.py --epochs 10 --batch_size 16 --lr 3e-5
# With MLP classification head
python scripts/train.py --use_mlp_head
Datasets are downloaded automatically from HuggingFace Hub on first run.
python scripts/evaluate.py
Outputs:
results/metrics.json — Full metrics reportresults/confusion_matrix.png — Confusion matrix heatmapresults/training_curves.png — Loss & metric curves# Interactive mode
python scripts/predict.py
# Single text
python scripts/predict.py --text "هذا المنتج ممتاز والجودة عالية"
# Batch from file
python scripts/predict.py --input_file texts.txt --output_file predictions.json
python -m pytest tests/ -v
Launch the Streamlit web app for real-time sentiment analysis:
streamlit run app/streamlit_app.py
The demo features:
This model trains on a combination of two public Arabic sentiment datasets:
| Dataset | Source | Samples | Labels | Description |
|---|---|---|---|---|
| ArSarcasm | HuggingFace | ~12,000 | 3-class | Arabic tweets with sentiment & sarcasm annotations |
| AJGT | HuggingFace | ~1,800 | Binary → 3-class | Arabic Jordanian General Tweets |
Total: ~13,800 samples with stratified 70/15/15 train/validation/test split.
aubmindlab/bert-base-arabertv2) — BERT-base architecture pre-trained on 77GB of Arabic text[CLS] → Dropout(0.1) → Linear(768, 3) or optionally a 2-layer MLP with GELU activationtorch.ampIf you found this useful, consider giving it a ⭐
Arabic Sentiment Analysis with AraBERT v2 — fine-tuned NLP pipeline for Arabic text classification (positive/negative/neutral) with custom training loop, Streamlit demo, and full evaluation suite
Python
2
0 commits
updated Jan 30, 2026
Deep learning pipeline for Arabic text sentiment classification using fine-tuned AraBERT
Features · Architecture · Results · Quick Start · Demo
Arabic is the 5th most spoken language globally (~400M+ speakers), yet it remains severely underrepresented in NLP research and tooling. Most sentiment analysis solutions are English-first, leaving Arabic-speaking markets — e-commerce, social media, customer support — without reliable automated sentiment understanding.
This project builds a production-ready Arabic sentiment analysis pipeline that handles the unique challenges of Arabic NLP:
By fine-tuning AraBERT v2 — a BERT model pre-trained on 77GB of Arabic text — this pipeline achieves strong 3-class sentiment classification (positive / neutral / negative) on real-world Arabic social media data.
| Feature | Description |
|---|---|
| 🏗️ Custom Training Loop | Full control over learning rate scheduling, gradient clipping, and mixed-precision training |
| 🔤 AraBERT Preprocessing | Arabic-specific normalization, diacritics removal, and Farasa segmentation |
| 📊 Multi-Dataset Support | Combines ArSarcasm (~12K) + AJGT (~1.8K) for robust training |
| 📈 Comprehensive Evaluation | Per-class metrics, confusion matrix, training curves, classification reports |
| 🚀 Production Inference | Single text, batch prediction, and interactive CLI mode |
| 🎨 Streamlit Demo | Interactive web UI with real-time probability visualization |
| 🔁 Reproducible | Seeded random states, pinned dependencies, configuration management |
┌─────────────────────────────────────────────────────────┐
│ Raw Arabic Text │
│ "هذا المنتج ممتاز والجودة عالية" │
└───────────────────────┬─────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ Arabic Preprocessing Layer │
│ ┌─────────────┐ ┌──────────────┐ ┌──────────────────┐ │
│ │ Diacritics │ │ Character │ │ AraBERT-Specific│ │
│ │ Removal │ │Normalization │ │ Preparation │ │
│ └─────────────┘ └──────────────┘ └──────────────────┘ │
└───────────────────────┬─────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ AraBERT v2 Tokenizer (WordPiece) │
│ max_length = 128 │
└───────────────────────┬─────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ AraBERT v2 Transformer Encoder │
│ 12 layers · 768 hidden · 12 heads · 136M params │
└───────────────────────┬─────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ Classification Head: [CLS] → Dropout → Linear │
│ 768 → 3 classes │
│ (Optional: 2-layer MLP with GELU activation) │
└───────────────────────┬─────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ 😞 Negative │ 😐 Neutral │ 😊 Positive │
└─────────────────────────────────────────────────────────┘
| Metric | Score |
|---|---|
| F1 (weighted) | ~0.85 |
| Accuracy | ~0.84 |
| Precision (weighted) | ~0.85 |
| Recall (weighted) | ~0.84 |
| Class | Precision | Recall | F1-Score |
|---|---|---|---|
| 😞 Negative | ~0.88 | ~0.87 | ~0.87 |
| 😐 Neutral | ~0.72 | ~0.70 | ~0.71 |
| 😊 Positive | ~0.86 | ~0.88 | ~0.87 |
Approximate scores from training on combined ArSarcasm + AJGT datasets. Run
python scripts/train.pyfollowed bypython scripts/evaluate.pyto reproduce exact results on your hardware.
| Parameter | Value |
|---|---|
| Base Model | aubmindlab/bert-base-arabertv2 |
| Optimizer | AdamW (weight decay: 0.01) |
| Learning Rate | 2e-5 with linear warmup (10%) + decay |
| Batch Size | 32 |
| Epochs | 5 |
| Mixed Precision | FP16 (CUDA) |
| Gradient Clipping | max norm 1.0 |
arabic-sentiment-analysis/
├── src/ # Core library
│ ├── __init__.py # Package exports
│ ├── config.py # Configuration dataclasses
│ ├── preprocessing.py # Arabic text preprocessing
│ ├── dataset.py # Dataset loading & DataLoaders
│ ├── model.py # AraBERT classifier architecture
│ ├── trainer.py # Custom training loop
│ ├── evaluate.py # Evaluation & visualization
│ └── inference.py # Prediction & interactive mode
├── scripts/ # Entry points
│ ├── train.py # Training script
│ ├── evaluate.py # Evaluation script
│ └── predict.py # Prediction script
├── app/
│ └── streamlit_app.py # Interactive demo app
├── tests/ # Unit & integration tests
│ ├── __init__.py
│ ├── test_preprocessing.py
│ ├── test_model.py
│ └── test_config.py
├── models/ # Saved checkpoints (.gitignored)
├── data/ # Dataset cache (.gitignored)
├── results/ # Evaluation outputs
├── requirements.txt
├── LICENSE
└── README.md
git clone https://github.com/salehA13/arabic-sentiment-analysis.git
cd arabic-sentiment-analysis
python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
pip install -r requirements.txt
# Default configuration (5 epochs, batch_size=32, lr=2e-5)
python scripts/train.py
# Custom hyperparameters
python scripts/train.py --epochs 10 --batch_size 16 --lr 3e-5
# With MLP classification head
python scripts/train.py --use_mlp_head
Datasets are downloaded automatically from HuggingFace Hub on first run.
python scripts/evaluate.py
Outputs:
results/metrics.json — Full metrics reportresults/confusion_matrix.png — Confusion matrix heatmapresults/training_curves.png — Loss & metric curves# Interactive mode
python scripts/predict.py
# Single text
python scripts/predict.py --text "هذا المنتج ممتاز والجودة عالية"
# Batch from file
python scripts/predict.py --input_file texts.txt --output_file predictions.json
python -m pytest tests/ -v
Launch the Streamlit web app for real-time sentiment analysis:
streamlit run app/streamlit_app.py
The demo features:
This model trains on a combination of two public Arabic sentiment datasets:
| Dataset | Source | Samples | Labels | Description |
|---|---|---|---|---|
| ArSarcasm | HuggingFace | ~12,000 | 3-class | Arabic tweets with sentiment & sarcasm annotations |
| AJGT | HuggingFace | ~1,800 | Binary → 3-class | Arabic Jordanian General Tweets |
Total: ~13,800 samples with stratified 70/15/15 train/validation/test split.
aubmindlab/bert-base-arabertv2) — BERT-base architecture pre-trained on 77GB of Arabic text[CLS] → Dropout(0.1) → Linear(768, 3) or optionally a 2-layer MLP with GELU activationtorch.ampIf you found this useful, consider giving it a ⭐