A production-ready sentiment analysis system for movie reviews that demonstrates comprehensive MLOps practices from data ingestion to model serving and monitoring. Built with industry-standard tools including DVC for pipeline orchestration, Flask for model serving, and optional Prometheus/Grafana monitoring integration.
β¨ Features
ποΈ Production MLOps Architecture: Complete workflow from data versioning through model deployment with industry best practices
π Cookiecutter Data Science Structure: Organized project layout with clear separation of data, source code, models, and documentation
π Reproducible ML Pipelines: DVC-orchestrated workflows with configurable parameters and automatic dependency tracking
π¦ Model Packaging & Distribution: pip-installable package structure with proper dependency management and version control
π API-Ready Model Serving: Flask-based REST API for real-time sentiment prediction with JSON input/output
π Comprehensive Monitoring: Optional Prometheus metrics and Grafana dashboards for production model observability
ποΈ Project structure
.
βββ .dvc/ # DVC configuration and cache management
βββ .github/workflows/ # CI/CD automation with GitHub Actions
βββ docs/ # Sphinx documentation framework
βββ flask_app/ # Production Flask API for model serving
βββ models/ # Serialized model artifacts and weights
βββ notebooks/ # Jupyter notebooks for EDA and experiments
βββ references/ # Data dictionaries and project documentation
βββ reports/ # Generated analysis reports and visualizations
βββ src/ # Source code package (data, features, models, viz)
βββ tests/ # Unit tests and integration tests
βββ dvc.yaml # ML pipeline definition and stages
βββ dvc.lock # Locked pipeline versions for reproducibility
βββ params.yaml # Centralized hyperparameters and configuration
βββ Makefile # Development workflow automation
βββ requirements.txt # Python dependencies
π Quickstart
Prerequisites
- Python 3.8 or higher
- Git and DVC for version control and pipeline management
1) Clone & setup environment
git clone https://github.com/AbdullahRasheed45/Movie_sentiment_analysis_MLOPS.git
cd Movie_sentiment_analysis_MLOPS
# Create virtual environment (recommended)
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
# Install dependencies and package
pip install -r requirements.txt
pip install -e . # Install src/ as editable package2) Configure pipeline parameters
# Edit params.yaml for your specific requirements
data:
raw_data_path: "data/raw/movie_reviews.csv"
test_size: 0.2
random_state: 42
model:
algorithm: "logistic_regression"
max_features: 10000
ngram_range: [1, 2]
training:
epochs: 100
batch_size: 32
learning_rate: 0.0013) Execute ML pipeline
# Initialize DVC (if not already done)
dvc init
# Run complete pipeline from data to model
dvc repro
# Check pipeline status
dvc dag4) Validate environment & run tests
# Sanity check Python environment
python test_environment.py
# Run comprehensive test suite
pytest tests/ -v
# Check code quality
make lint5) Start model serving API
# Launch Flask API server
cd flask_app/
python app.py
# Test API endpoint
curl -X POST http://127.0.0.1:5000/predict \
-H "Content-Type: application/json" \
-d '{"text": "This movie was absolutely fantastic!"}'π§ MLOps pipeline architecture
Stage 1: Data Ingestion
# src/data/make_dataset.py
def load_movie_reviews():
"""Download and preprocess raw movie review data"""
# - Fetch data from external sources
# - Handle missing values and duplicates
# - Store in data/raw/ for immutable referenceStage 2: Feature Engineering
# src/features/build_features.py
def create_text_features(df):
"""Transform raw text into ML-ready features"""
# - Text preprocessing (tokenization, stopwords)
# - TF-IDF vectorization with n-grams
# - Feature selection and dimensionality reductionStage 3: Model Training
# src/models/train_model.py
def train_sentiment_model(X_train, y_train):
"""Train and validate sentiment classification model"""
# - Cross-validation with stratified splits
# - Hyperparameter optimization
# - Model serialization to models/Stage 4: Model Evaluation
# src/models/evaluate_model.py
def evaluate_performance(model, X_test, y_test):
"""Generate comprehensive model evaluation metrics"""
# - Classification reports and confusion matrices
# - ROC curves and precision-recall analysis
# - Save results to reports/Stage 5: Model Packaging
# Automated model versioning and deployment preparation
# - Model artifact packaging with metadata
# - API-ready prediction interface
# - Performance benchmarkingβοΈ Configuration management
Centralized Parameters (params.yaml):
# Data processing configuration
preprocessing:
text_cleaning: true
lowercase: true
remove_punctuation: true
min_word_length: 2
max_vocab_size: 50000
# Model hyperparameters
model_params:
classifier_type: "logistic_regression"
regularization: "l2"
C: 1.0
max_iter: 1000
# Training configuration
training_config:
validation_split: 0.2
stratify: true
cross_validation_folds: 5
# Evaluation metrics
metrics:
primary: "f1_score"
track: ["accuracy", "precision", "recall", "auc"]DVC Pipeline (dvc.yaml):
stages:
prepare_data:
cmd: python src/data/make_dataset.py
deps: [data/external/]
outs: [data/raw/movie_reviews.csv]
build_features:
cmd: python src/features/build_features.py
deps: [data/raw/, src/features/]
outs: [data/processed/]
train_model:
cmd: python src/models/train_model.py
deps: [data/processed/, src/models/, params.yaml]
outs: [models/sentiment_model.pkl]
metrics: [reports/training_metrics.json]π§ Development workflow automation
Makefile Commands:
# Data operations
make data # Download and prepare datasets
make features # Generate ML features from raw data
# Model operations
make train # Train models with current parameters
make evaluate # Generate model performance reports
make predict # Run batch predictions on test data
# Quality assurance
make test # Run full test suite
make lint # Code quality checks and formatting
make clean # Clean temporary files and caches
# Deployment
make serve # Start Flask API server
make docker # Build Docker container for deploymentAutomated Testing Pipeline:
# tests/test_data_processing.py
def test_data_loading():
"""Verify data loading and preprocessing pipeline"""
def test_feature_engineering():
"""Validate feature creation and transformation"""
def test_model_training():
"""Ensure model training completes successfully"""
def test_api_endpoints():
"""Integration tests for Flask API"""π Model serving & deployment
Flask API Structure:
# flask_app/app.py
@app.route('/predict', methods=['POST'])
def predict_sentiment():
"""Real-time sentiment prediction endpoint"""
data = request.get_json()
text = data['text']
# Preprocessing and feature extraction
processed_text = preprocess_text(text)
features = vectorizer.transform([processed_text])
# Model prediction
prediction = model.predict_proba(features)[0]
return jsonify({
'sentiment': 'positive' if prediction[1] > 0.5 else 'negative',
'confidence': float(max(prediction)),
'probabilities': {
'negative': float(prediction[0]),
'positive': float(prediction[1])
}
})API Usage Examples:
# Single prediction
curl -X POST http://localhost:5000/predict \
-H "Content-Type: application/json" \
-d '{"text": "The cinematography was breathtaking and the acting superb!"}'
# Batch predictions
curl -X POST http://localhost:5000/predict_batch \
-H "Content-Type: application/json" \
-d '{"texts": ["Great movie!", "Terrible plot.", "Average film."]}'
# Model info and health check
curl http://localhost:5000/info
curl http://localhost:5000/healthπ Monitoring & observability
Prometheus Metrics Integration:
# flask_app/monitoring.py
from prometheus_client import Counter, Histogram, generate_latest
# Track API usage metrics
prediction_counter = Counter('sentiment_predictions_total',
'Total predictions made')
prediction_latency = Histogram('sentiment_prediction_duration_seconds',
'Time spent on predictions')
@app.route('/metrics')
def metrics():
"""Prometheus metrics endpoint"""
return generate_latest()Grafana Dashboard Panels:
- Request Volume: Predictions per minute/hour
- Response Latency: P50, P95, P99 prediction times
- Model Performance: Confidence distribution, prediction accuracy
- System Health: Memory usage, CPU utilization, error rates
- Data Drift: Feature distribution changes over time
π Experiment tracking & versioning
DVC Data Versioning:
# Track dataset changes
dvc add data/raw/movie_reviews.csv
git add data/raw/movie_reviews.csv.dvc
git commit -m "Add movie reviews dataset v1.0"
# Update datasets
dvc checkout data/raw/movie_reviews.csv.dvc
dvc push # Sync to remote storage
# Compare experiments
dvc plots diff experiment1 experiment2
dvc metrics diff HEAD~1Model Registry & Comparison:
# Track model versions and performance
model_metrics = {
'version': '1.2.0',
'accuracy': 0.892,
'f1_score': 0.885,
'training_time': '00:12:34',
'model_size_mb': 15.7,
'parameters': params
}
# Automated model comparison and selection
best_model = compare_models(current_model, previous_models)π Production considerations
Security & Privacy:
# Input validation and sanitization
def validate_input(text):
if len(text) > MAX_TEXT_LENGTH:
raise ValidationError("Text too long")
# Remove potential security threats
clean_text = sanitize_text(text)
return clean_text
# Rate limiting and abuse prevention
@limiter.limit("100 per minute")
@app.route('/predict', methods=['POST'])
def predict_sentiment():
# Prediction logic with rate limiting
passScalability & Performance:
- Model Caching: In-memory model loading for faster predictions
- Batch Processing: Efficient handling of multiple predictions
- Load Balancing: Multiple Flask workers with Gunicorn
- Container Deployment: Docker support for cloud deployment
π§ͺ Quality assurance pipeline
Continuous Integration:
# .github/workflows/ci.yml
name: MLOps Pipeline
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup Python
uses: actions/setup-python@v2
- name: Install dependencies
run: pip install -r requirements.txt
- name: Run tests
run: pytest tests/ --cov=src/
- name: Run DVC pipeline
run: dvc repro
- name: Validate model performance
run: python src/models/validate_model.pyModel Validation & Testing:
# Automated model quality checks
def validate_model_performance(model, test_data):
"""Ensure model meets production quality standards"""
metrics = evaluate_model(model, test_data)
assert metrics['accuracy'] > 0.85, "Model accuracy below threshold"
assert metrics['f1_score'] > 0.80, "Model F1 score insufficient"
assert metrics['precision'] > 0.82, "Model precision too low"
return metricsπ Troubleshooting guide
Pipeline Issues:
- DVC Pipeline Fails β Check
dvc doctor, verify file paths inparams.yaml - Import Errors β Ensure
pip install -e .completed successfully - Memory Issues β Reduce batch size or feature dimensions in
params.yaml
API Issues:
- Flask Won't Start β Verify model artifacts exist in
models/directory - Slow Predictions β Enable model caching or reduce feature complexity
- JSON Errors β Validate request format matches API schema
Data Issues:
- Missing Data β Run
dvc pullto sync from remote storage - Data Drift β Update preprocessing pipeline and retrain model
- Large Files β Configure DVC remote storage (S3, GCS, Azure)
π References & attribution
This project follows the Cookiecutter Data Science template for reproducible, production-ready ML projects. The MLOps practices implemented here are based on industry best practices from organizations like Google, Netflix, and Uber.
Key Technologies:
- DVC: Data version control and ML pipeline orchestration
- Flask: Lightweight web framework for model serving
- Prometheus/Grafana: Production monitoring and observability
- pytest: Testing framework with coverage reporting
- GitHub Actions: Continuous integration and deployment
π License
MIT License - see LICENSE file for complete terms.
Let's build scalable, production-ready ML systems together!
Built with β€οΈ following MLOps best practices. Perfect for learning production ML workflows and building enterprise-grade machine learning systems.