Production-Ready Aspect-Based Sentiment Analysis & Rating Prediction Platform
An AI-powered system that analyzes user-generated reviews to extract product aspects, determine sentiment per aspect, and predict overall ratings with state-of-the-art accuracy.
- Overview
- Key Features
- Architecture
- Installation
- Quick Start
- Model Details
- API Documentation
- Training & Fine-Tuning
- Dataset
- Project Structure
- Performance Metrics
- Development
- Documentation
- Roadmap
- Contributing
- License
ReviewMind is an end-to-end Aspect-Based Sentiment Analysis (ABSA) system that combines cutting-edge Large Language Models with traditional machine learning techniques to provide comprehensive review analysis.
Given a user review like:
"The product quality is amazing and delivery was super fast,
but the packaging was damaged."
ReviewMind outputs:
{
"aspects": [
{ "aspect": "quality", "sentiment": "positive" },
{ "aspect": "delivery", "sentiment": "positive" },
{ "aspect": "packaging", "sentiment": "negative" }
],
"rating": 3.8
}- ๐ E-commerce: Analyze product reviews to identify strengths and weaknesses
- ๐ฑ SaaS: Monitor customer feedback for feature-specific sentiment
- ๐จ Hospitality: Track service quality across multiple dimensions
- ๐ Market Research: Extract actionable insights from customer feedback
- ๐ Competitive Analysis: Compare sentiment across product categories
- Fine-tuned LLM: Qwen2.5-7B with LoRA/QLoRA for aspect extraction and sentiment classification
- Ensemble ML: XGBoost + CatBoost + LightGBM with Ridge meta-learner for rating prediction
- Multi-task Learning: Joint training for aspect detection, sentiment analysis, and rating regression
- FastAPI Backend: RESTful API with < 2s inference latency
- Modular Design: Separated concerns for easy maintenance and extensibility
- Configuration-Driven: YAML-based hyperparameter management
- Type-Safe: Dataclass validation throughout the pipeline
- Comprehensive Logging: Structured logging for debugging and monitoring
- 43+ Features: Aspect-based, text-based, quality-based, and interaction features
- Configurable Lexicons: Domain-specific sentiment dictionaries
- Quality Scoring: Automatic LLM output quality assessment
- Weighted Predictions: Confidence-based sample weighting
- Reproducible: Fixed random seeds, versioned datasets, documented experiments
- Well-Documented: Complete SRS, MDD, DRS, and training plans
- Extensible: Easy to add new models, features, or evaluation metrics
- Transparent: Semi-supervised annotation strategy with human validation
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Frontend (Next.js) โ
โ [In Development - Coming Soon] โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ REST API
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ FastAPI Backend โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ ReviewMind Pipeline Orchestrator โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โ โ
โ โผ โผ โ
โ โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโ โ
โ โ LLM Component โ โ Ensemble ML โ โ
โ โ Qwen2.5-7B โ โ Rating Predictor โ โ
โ โ + LoRA โ โ XGB+Cat+LGB+Ridge โ โ
โ โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โ โ
โ โผ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Feature Extraction & Processing โ โ
โ โ โข Aspect Parser โข Text Features โข Quality Score โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
- API Layer (
api/): FastAPI endpoints for single and batch inference - Pipeline Layer (
src/pipeline/): Orchestrates LLM and ensemble models - Model Layer (
src/model/): Feature extraction, training, and evaluation - Inference Layer (
src/inference/): Production-ready prediction interface - Data Layer (
src/data/): Data loading, preprocessing, and validation - Training Layer (
src/training/): Model fine-tuning and ensemble training
- Python: 3.10 or higher
- Hardware:
- Apple Silicon (M1/M2/M3/M4) with Metal support (recommended)
- OR NVIDIA GPU with CUDA support
- Minimum 16GB RAM (24GB recommended for training)
- OS: macOS, Linux, or Windows with WSL2
git clone https://github.com/barandincoguz/SentimentAnalysis.git
cd ReviewMind\ Sentiment\ Analysis# Create virtual environment
python3 -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install requirements
pip install -r requirements.txt
# Install PyTorch (for Apple Silicon)
pip3 install torch torchvision torchaudio
# Install PyTorch (for CUDA)
# pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118# Download base Qwen2.5-7B model
python scripts/download_model.py
# Or manually download fine-tuned model from Hugging Face
# Model will be loaded automatically during first inference# Start FastAPI server
cd api
uvicorn main:app --reload --host 0.0.0.0 --port 8000Access API documentation at http://localhost:8000/docs
from src.pipeline.run_pipeline import ReviewMindPipeline
# Initialize pipeline
pipeline = ReviewMindPipeline()
# Analyze a review
review_text = "Amazing product! Quality is top-notch but delivery was slow."
result = pipeline.predict(review_text)
print(f"Rating: {result['rating']}โญ")
print("Aspects:")
for aspect in result['aspects']:
print(f" - {aspect['aspect']}: {aspect['sentiment']}")curl -X POST "http://localhost:8000/analyze" \
-H "Content-Type: application/json" \
-d '{
"text": "Great quality but shipping was terrible!",
"include_aspects": true
}'import requests
response = requests.post(
"http://localhost:8000/analyze",
json={"text": "Excellent product, highly recommend!"}
)
result = response.json()
print(result)reviews = [
{"text": "Great product!"},
{"text": "Poor quality, very disappointed."},
{"text": "Good value for money."}
]
response = requests.post(
"http://localhost:8000/analyze/batch",
json={"reviews": reviews}
)
results = response.json()Base Model: Qwen/Qwen2.5-7B-Instruct
Fine-Tuning Strategy:
- Method: Parameter-Efficient Fine-Tuning (PEFT) with LoRA
- LoRA Configuration:
- Rank (r): 16
- Alpha: 32
- Target modules:
q_proj,v_proj - Dropout: 0.05
- Quantization: 4-bit QLoRA for efficient training on consumer hardware
- Precision: bfloat16 computation
Training Configuration:
- Batch size: 1-2 with gradient accumulation
- Epochs: 3-5
- Learning rate: 2e-4 with cosine scheduler
- Optimizer: AdamW
- Warmup: 5% of total steps
Model Capabilities:
- Structured JSON output generation
- Multi-task learning (aspect extraction + sentiment classification)
- Multilingual support (English + Turkish)
- Instruction-following with zero-shot generalization
Architecture: Stacked Ensemble with Meta-Learning
Base Models:
- XGBoost Regressor
- RandomizedSearchCV for hyperparameter tuning
- 20 iterations, 5-fold cross-validation
- Objective:
reg:squarederror
- CatBoost Regressor
- MAE loss function
- Early stopping (50 rounds)
- Max depth: 6, Iterations: 1000
- LightGBM Regressor
- Leaf-wise growth strategy
- Early stopping (50 rounds)
- Num leaves: 31, Iterations: 1000
Meta-Learner: Ridge Regression (ฮฑ=0.5)
- Combines predictions from base models
- Trained on out-of-fold predictions
- Prevents overfitting through regularization
Feature Engineering (43 features):
- Aspect Features (8): Positive/negative/neutral counts, ratios, net score, entropy
- Text Features (25): Sentiment keywords, punctuation signals, linguistic markers
- Quality Features (6): Generic aspect detection, diversity scores
- Interaction Features (4): Sentiment alignment, confidence scores
Analyze a single review
Request:
{
"text": "Amazing product!",
"include_aspects": true
}Response:
{
"text": "Amazing product!",
"aspects": [{ "aspect": "quality", "sentiment": "positive" }],
"rating": 4.8,
"processing_time": 1.23
}Analyze multiple reviews in one request
Request:
{
"reviews": [{ "text": "Great quality!" }, { "text": "Poor service." }]
}Response:
{
"results": [
{
"text": "Great quality!",
"aspects": [...],
"rating": 4.5
},
{
"text": "Poor service.",
"aspects": [...],
"rating": 2.1
}
],
"total_processed": 2,
"processing_time": 2.45
}Submit feedback for model improvement
Request:
{
"review_text": "...",
"predicted_rating": 4.2,
"actual_rating": 4.0,
"aspects": [...]
}Visit http://localhost:8000/docs for Swagger UI documentation with live testing capabilities.
# Prepare training data
python src/data/format_for_training.py
# Start fine-tuning
python src/training/train.pyData Format:
{
"instruction": "Analyze the following review...",
"input": "The product quality is excellent!",
"output": {
"aspects": [{ "aspect": "quality", "sentiment": "positive" }],
"rating": 5.0
}
}# Train rating prediction ensemble
python -m src.training.train_ensemble_refactoredConfiguration: Edit configs/ensemble_config.yaml to customize:
- Data paths
- Model hyperparameters
- Feature engineering settings
- Training parameters
Output:
- Trained models:
models/rating_production/ - Predictions:
predictions_test.csv - Feature importance:
feature_importance_xgboost.csv - Training metadata:
training_metadata.pkl
# Merge fine-tuned adapters with base model
python src/utils/merge_models.pyPrimary Datasets:
- SemEval-2014 Task 4: Restaurant and Laptop reviews with aspect annotations
- Amazon Product Reviews: Multi-domain product reviews
- Custom Annotated Data: Semi-automatically labeled using weak supervision
Semi-Supervised Approach:
- Base LLM generates pseudo-labels for raw reviews
- Human validation on stratified sample (20%)
- Iterative refinement based on validation feedback
- Final dataset: ~10,000 reviews with quality assurance
Closed aspect set for consistency:
| Aspect | Description |
|---|---|
quality |
Product or service quality |
price |
Cost and value for money |
delivery |
Shipping speed and reliability |
packaging |
Packaging condition |
usability |
Ease of use |
support |
Customer service |
experience |
Overall experience |
- positive: Favorable opinion
- neutral: Mixed or factual statement
- negative: Unfavorable opinion
- Continuous values: 1.0 to 5.0
- One decimal precision
- Original scale preserved (no normalization)
| Split | Samples | Percentage |
|---|---|---|
| Train | ~8,000 | 80% |
| Validation | ~1,000 | 10% |
| Test | ~1,000 | 10% |
ReviewMind/
โโโ api/ # FastAPI application
โ โโโ main.py # API endpoints
โ โโโ schemas.py # Pydantic models
โ โโโ __init__.py
โโโ configs/ # Configuration files
โ โโโ ensemble_config.yaml # Ensemble model config
โ โโโ model/
โ โโโ qwen2.5-7b-instruct.yaml
โโโ data/ # Datasets
โ โโโ raw/ # Raw review data
โ โโโ processed/ # Processed training data
โ โโโ ready/ # Train/val/test splits
โ โโโ splits/ # JSON splits
โ โโโ schema/ # JSON schemas
โโโ docs/ # Documentation
โ โโโ review_mind_software_requirements_specification_srs.md
โ โโโ review_mind_model_design_document_mdd.md
โ โโโ review_mind_dataset_requirements_specification_drs.md
โ โโโ review_mind_training_plan_experiment_design.md
โ โโโ ensemble_model_README.md
โ โโโ REFACTORING_SUMMARY.md
โ โโโ BEFORE_AFTER_COMPARISON.md
โโโ models/ # Model weights
โ โโโ base/ # Base Qwen2.5-7B
โ โโโ finetuned/ # Fine-tuned LoRA adapters
โ โโโ final/ # Merged models
โ โโโ rating/ # Ensemble models (dev)
โ โโโ rating_production/ # Production ensemble
โโโ scripts/ # Utility scripts
โ โโโ download_model.py # Model downloader
โ โโโ test_inference.py # Inference testing
โ โโโ test_refactored_ensemble.py
โโโ src/ # Source code
โ โโโ data/ # Data processing
โ โ โโโ ingestion.py
โ โ โโโ preprocess.py
โ โ โโโ labeler.py
โ โ โโโ format_for_training.py
โ โ โโโ ensemble_data_loader.py
โ โโโ model/ # Model components
โ โ โโโ config.py
โ โ โโโ feature_extractors.py
โ โ โโโ ensemble_trainer.py
โ โ โโโ model_evaluator.py
โ โโโ training/ # Training scripts
โ โ โโโ train.py # LLM fine-tuning
โ โ โโโ train_ensemble_refactored.py
โ โโโ inference/ # Inference
โ โ โโโ ensemble_predictor.py
โ โโโ pipeline/ # Pipeline orchestration
โ โ โโโ run_pipeline.py
โ โโโ tests/ # Test scripts
โ โ โโโ test_model.py
โ โ โโโ test_pipeline.py
โ โ โโโ interactive_demo.py
โ โ โโโ interactive_pipeline_tester.py
โ โโโ utils/ # Utilities
โ โโโ llm_parser.py
โ โโโ merge_models.py
โโโ frontend/ # Next.js frontend (Coming Soon)
โโโ requirements.txt # Python dependencies
โโโ pyproject.toml # Project metadata
โโโ README.md # This file
| Metric | Score |
|---|---|
| Aspect Extraction F1 | 0.87 |
| Sentiment Accuracy | 0.89 |
| Aspect-Sentiment Joint Accuracy | 0.82 |
| Metric | Score |
|---|---|
| MAE (Mean Absolute Error) | 0.31 |
| RMSE (Root Mean Square Error) | 0.42 |
| Rยฒ Score | 0.88 |
| Accuracy ยฑ0.5 stars | 89% |
| Accuracy ยฑ1.0 stars | 97% |
- Single Review Latency: < 2 seconds
- Batch Processing (100 reviews): < 15 seconds
- Memory Usage: ~4GB (with model loaded)
- Hardware: Apple M4 Pro (14-core CPU, 20-core GPU)
# Test LLM inference
python scripts/test_inference.py
# Test ensemble model
python scripts/test_refactored_ensemble.py
# Test full pipeline
python src/tests/test_pipeline.py
# Interactive demo
python src/tests/interactive_demo.py# Format code
black src/ api/
# Type checking
mypy src/
# Linting
pylint src/ api/Edit configs/ensemble_config.yaml for:
- Hyperparameter tuning
- Feature engineering adjustments
- Data path configuration
- Model selection
All changes take effect without code modifications.
Comprehensive documentation available in the docs/ directory:
- Software Requirements Specification (SRS): Functional and non-functional requirements
- Model Design Document (MDD): Model architecture and design decisions
- Dataset Requirements Specification (DRS): Dataset design and annotation schema
- Training Plan & Experiment Design: Training procedures and experiments
- Ensemble Model README: Detailed ensemble model documentation
- Refactoring Summary: Code quality improvements and architecture changes
- Fine-tune Qwen2.5-7B for aspect extraction
- Build ensemble rating prediction model
- Create FastAPI backend
- Implement feature engineering pipeline
- Add comprehensive testing
- Write documentation
- Next.js application setup
- Review input interface
- Results visualization
- Batch analysis dashboard
- Historical analytics
- Docker containerization
- Kubernetes orchestration
- CI/CD pipeline
- Monitoring and logging
- Load balancing
- Auto-scaling
- Multilingual expansion (Spanish, French, German)
- Open aspect discovery
- Confidence scores per prediction
- Explainability features (attention visualization)
- Model distillation for faster inference
- Mobile app (React Native)
Contributions are welcome! Please follow these steps:
- Fork the repository
- Create a 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
- Follow PEP 8 style guide
- Add type hints to all functions
- Write docstrings for public APIs
- Include tests for new features
- Update documentation as needed
This project is licensed under the MIT License - see the LICENSE file for details.
Ahmet Baran Dinรงoguz
- GitHub: @barandincoguz
- Repository: SentimentAnalysis
- Qwen Team for the excellent base model
- Hugging Face for the Transformers library and model hosting
- FastAPI for the modern web framework
- SemEval for providing benchmark datasets
- Open-source community for inspiration and tools
For questions, issues, or feature requests:
- Open an issue
- Check the documentation
- Contact the author
Made with โค๏ธ for the AI/NLP community
โญ Star this repo if you find it useful!