An automated ML-Ops pipeline for detecting phishing URLs using machine learning
Overview β’ Architecture β’ Features β’ Installation β’ Usage
- Project Overview
- Why This Project?
- How It Works
- Architecture & Components
- Build Flow & Pipeline
- Component Map
- Tech Stack
- Prerequisites
- Installation & Setup
- Usage
- Project Structure
- API Documentation
- Conclusion
Network Security is an end-to-end machine learning operations (MLOps) pipeline designed to classify and detect phishing URLs in web traffic. The system automates the entire workflow from data ingestion to model deployment, enabling organizations to identify malicious URLs and protect users from phishing attacks.
- Automated ML Pipeline: Orchestrated data processing, validation, and model training
- Real-time Prediction: REST API for predicting whether a URL is phishing or legitimate
- Model Monitoring: Integration with MLflow and DagsHub for experiment tracking and model versioning
- Cloud Integration: AWS S3 support for model artifact storage and synchronization
- Production-Ready: Containerized with Docker for seamless deployment
Phishing attacks are one of the most prevalent cybersecurity threats, causing billions of dollars in damage annually. Attackers use:
- Fake domain registrations
- SSL certificate manipulation
- URL obfuscation techniques
- DOM-based attacks
Traditional rule-based systems struggle to keep pace with evolving attack patterns.
This project implements a data-driven machine learning approach to:
- Learn patterns from a dataset of 31 phishing indicators
- Generalize to new, unseen URLs using ensemble methods
- Scale through automated pipeline orchestration
- Monitor model performance with built-in MLOps infrastructure
- Deploy with confidence using containerization and cloud storage
Raw Data (MongoDB)
β
[Data Ingestion] β Split into Train/Test
β
[Data Validation] β Check schema, detect drift
β
[Data Transformation] β Encode, scale, impute missing values
β
[Model Training] β Train ensemble models, select best
β
[Model Evaluation] β Track metrics with MLflow
β
[Model Deployment] β Save to final_model/
β
REST API
β
Predictions on New URLs
The model analyzes these URL characteristics:
Domain Features:
having_IP_Address- Uses IP instead of domain nameURL_Length- Suspicious if overly longPrefix_Suffix- Contains hyphen in domainhaving_Sub_Domain- Multiple subdomains presentSSLfinal_State- SSL certificate statusDomain_registeration_length- Domain ageDNSRecord- DNS record presence
URL Structure:
having_At_Symbol- @ symbol used to obfuscate domainShortining_Service- URL shortening service useddouble_slash_redirecting- Double slash for redirectionAbnormal_URL- Non-standard URL formatRedirect- URL redirect behavior
Web Content Features:
Favicon- Custom favicon presenceport- Non-standard port usedHTTPS_token- Inconsistent HTTPS usageRequest_URL- Requests from different domainURL_of_Anchor- Anchor links to different domainLinks_in_tags- External links in meta tagsSFH(Server Form Handler) - Form submission endpointSubmitting_to_email- Mail link in formon_mouseover- Mouseover event handlersRightClick- Right-click disabledpopUpWidnow- Popup windows usedIframe- Iframes embedded
Reputation Features:
web_traffic- Traffic statisticsPage_Rank- Google PageRank scoreGoogle_Index- Google indexing statusLinks_pointing_to_page- Backlink countage_of_domain- Domain registration ageStatistical_report- Statistical phishing reports
Target:
Result- Classification (Legitimate: 1, Phishing: -1)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β NetworkSecurity Package (ML Pipeline) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β ββββββββββββββββββββββββββββββββββββββββββββββββ β
β β 1. Data Ingestion Component β β
β β β MongoDB β Pandas DataFrame β β
β β β Train/Test split (80/20) β β
β ββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β ββββββββββββββββββββββββββββββββββββββββββββββββ β
β β 2. Data Validation Component β β
β β β Schema validation (YAML) β β
β β β Data drift detection β β
β β β Separate valid/invalid data β β
β ββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β ββββββββββββββββββββββββββββββββββββββββββββββββ β
β β 3. Data Transformation Component β β
β β β Handle missing values (KNN Imputation) β β
β β β Feature encoding & scaling β β
β β β Save preprocessing object β β
β ββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β ββββββββββββββββββββββββββββββββββββββββββββββββ β
β β 4. Model Training Component β β
β β β Train multiple algorithms: β β
β β β’ Logistic Regression β β
β β β’ Random Forest β β
β β β’ Gradient Boosting β β
β β β’ Decision Tree β β
β β β’ AdaBoost β β
β β β Hyperparameter tuning β β
β β β Model evaluation & selection β β
β β β MLflow tracking β β
β ββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β ββββββββββββββββββββββββββββββββββββββββββββββββ β
β β 5. Model Estimator β β
β β β Combines preprocessor + trained model β β
β β β Handles prediction pipeline β β
β ββββββββββββββββββββββββββββββββββββββββββββββββ β
β β
β ββββββββββββββββββββββββββββββββββββββββββββββββ β
β β 6. Cloud Integration (S3) β β
β β β Sync models to AWS S3 β β
β β β Versioning & backup β β
β ββββββββββββββββββββββββββββββββββββββββββββββββ β
β β
β ββββββββββββββββββββββββββββββββββββββββββββββββ β
β β 7. Logging & Exception Handling β β
β β β Custom exception class β β
β β β Logger instance β β
β ββββββββββββββββββββββββββββββββββββββββββββββββ β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
ββββββββββββββββββββββββββββββββ
β FastAPI REST Application β
β β Training endpoint β
β β Prediction endpoint β
β β CORS middleware support β
ββββββββββββββββββββββββββββββββ
| Module | Path | Purpose |
|---|---|---|
| Data Ingestion | components/data_ingestion.py |
Fetch data from MongoDB, perform train-test split |
| Data Validation | components/data_validation.py |
Validate schema, detect data drift |
| Data Transformation | components/data_transformation.py |
Handle missing values, scale features |
| Model Training | components/model_trainer.py |
Train & evaluate multiple ML algorithms |
| Estimator | utils/ml_utils/model/estimator.py |
Production model wrapper |
| Classification Metrics | utils/ml_utils/metric/classification_metric.py |
Compute F1, Precision, Recall |
| Utilities | utils/main_utils/utils.py |
Helper functions (save/load objects) |
| Training Pipeline | pipeline/training_pipeline.py |
Orchestrate full pipeline |
| Batch Prediction | pipeline/batch_prediction.py |
Batch prediction on datasets |
| Config Entity | entity/config_entity.py |
Configuration classes |
| Artifact Entity | entity/artifact_entity.py |
Artifact classes for component outputs |
| Exception Handling | exceptionHandling/exception.py |
Custom exception class |
| Logger | logging/logger.py |
Logging utility |
# Retrieve phishing data from MongoDB
# Input: MongoDB connection URL, database name, collection name
# Process:
# - Connect to MongoDB
# - Load collection as Pandas DataFrame
# - Remove MongoDB _id field
# - Replace "na" strings with NaN
# - Split into train (80%) and test (20%)
# Output: DataIngestionArtifact
# - train.csv β artifacts/data_ingestion/ingested/
# - test.csv β artifacts/data_ingestion/ingested/
# - Full data β artifacts/data_ingestion/feature_store/# Validate data against schema and detect drift
# Input: DataIngestionArtifact, schema.yaml
# Process:
# - Load schema from data_schema/schema.yaml
# - Validate column names and data types
# - Check for missing values
# - Detect data drift using statistical tests
# - Separate valid and invalid records
# Output: DataValidationArtifact
# - valid data β artifacts/data_validation/validated/
# - invalid data β artifacts/data_validation/invalid/
# - drift report β artifacts/data_validation/drift_report/report.yaml# Transform and preprocess data
# Input: DataValidationArtifact
# Process:
# - Separate features (X) and target (y)
# - Handle missing values using KNN Imputer
# - Encode categorical variables (if any)
# - Scale numerical features using StandardScaler
# - Save preprocessing pipeline as .pkl
# Output: DataTransformationArtifact
# - transformed_train β .npy (NumPy array)
# - transformed_test β .npy (NumPy array)
# - preprocessor.pkl β artifacts/data_transformation/transformed_object/# Train and evaluate multiple ML algorithms
# Input: DataTransformationArtifact
# Process:
# - Load transformed training data
# - Train 5 algorithms:
# β’ LogisticRegression(max_iter=1000)
# β’ RandomForestClassifier(verbose=1)
# β’ GradientBoostingClassifier(verbose=1)
# β’ DecisionTreeClassifier()
# β’ AdaBoostClassifier()
# - Perform hyperparameter tuning (GridSearchCV)
# - Evaluate on test set
# - Log metrics to MLflow (F1, Precision, Recall)
# - Select best model based on F1-score
# Output: ModelTrainerArtifact
# - model.pkl β artifacts/model_trainer/trained_model/
# - Metrics logged to DagsHub/MLflow# Save model to production location
# Input: ModelTrainerArtifact
# Process:
# - Copy trained model to final_model/model.pkl
# - Copy preprocessor to final_model/preprocessor.pkl
# - Sync artifacts to AWS S3 (optional)
# Output: Production-ready models in final_model/βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Training Pipeline Flow β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
START
β
βββ Initialize TrainingPipelineConfig
β ββ Set artifact directory with timestamp
β
βββ start_data_ingestion()
β ββ Load phisingData.csv from MongoDB
β ββ Split into train (80%) & test (20%)
β ββ Save β artifacts/data_ingestion/ingested/
β
βββ start_data_validation()
β ββ Validate schema against schema.yaml
β ββ Check data types and columns
β ββ Detect drift
β ββ Save β artifacts/data_validation/validated/
β
βββ start_data_transformation()
β ββ Impute missing values (KNN)
β ββ Scale features (StandardScaler)
β ββ Save β artifacts/data_transformation/transformed/
β
βββ start_model_trainer()
β ββ Load transformed data
β ββ Train 5 algorithms
β ββ Evaluate models
β ββ Log to MLflow
β ββ Save best model β artifacts/model_trainer/trained_model/
β
βββ start_model_pusher()
β ββ Copy model to final_model/model.pkl
β ββ Copy preprocessor to final_model/preprocessor.pkl
β ββ Sync to S3 (optional)
β
βββ END (Success/Failure notification)
π¦ networkSecurity/
β
βββ π components/ # Core ML pipeline components
β βββ data_ingestion.py # Fetch & split data
β βββ data_validation.py # Validate schema & detect drift
β βββ data_transformation.py # Impute, encode, scale features
β βββ model_trainer.py # Train & evaluate models
β
βββ π pipeline/ # High-level orchestration
β βββ training_pipeline.py # Main pipeline orchestrator
β βββ batch_prediction.py # Batch prediction interface
β
βββ π entity/ # Configuration & artifact classes
β βββ config_entity.py # Config classes for each component
β βββ artifact_entity.py # Artifact classes for outputs
β
βββ π utils/ # Utility functions
β βββ π main_utils/
β β βββ utils.py # Save/load objects, evaluate models
β βββ π ml_utils/
β βββ π model/
β β βββ estimator.py # Production model wrapper
β βββ π metric/
β βββ classification_metric.py # F1, Precision, Recall
β
βββ π cloud/ # Cloud integration
β βββ s3_syncer.py # AWS S3 sync utility
β
βββ π constant/ # Constants & configuration
β βββ π training_pipeline/
β βββ __init__.py # Pipeline constants
β
βββ π exceptionHandling/ # Custom exceptions
β βββ exception.py
β
βββ π logging/ # Logging utility
β βββ logger.py
β
βββ π __init__.py
| Category | Technology | Purpose |
|---|---|---|
| Language | Python 3.8+ | Core programming language |
| ML/Data | scikit-learn | Training algorithms, preprocessing |
| pandas | Data manipulation | |
| NumPy | Numerical computing | |
| Database | MongoDB | Data storage (with MongoDB Atlas) |
| API | FastAPI | REST API framework |
| Uvicorn | ASGI web server | |
| Starlette | Web framework (FastAPI dependency) | |
| MLOps | MLflow | Experiment tracking & model registry |
| DagsHub | ML collaboration platform | |
| Cloud | AWS S3 | Model artifact storage |
| Containerization | Docker | Production deployment |
| Utilities | python-dotenv | Environment variable management |
| PyYAML | Schema configuration | |
| dill | Object serialization | |
| certifi | SSL certificate verification |
- Python 3.8 or higher
- pip or conda package manager
- Docker (for containerized deployment)
- Git (for version control)
-
MongoDB Atlas Account
- Create free cluster at https://www.mongodb.com/cloud/atlas
- Obtain connection string (MONGODB_URL_KEY)
-
AWS Account (Optional, for S3 integration)
- AWS Access Key ID
- AWS Secret Access Key
- S3 bucket for model storage
-
DagsHub Account (Optional, for MLOps)
- DagsHub MLflow remote URI
- Repository credentials
Create a .env file in the project root:
MONGODB_URL_KEY=mongodb+srv://<username>:<password>@<cluster>.mongodb.net/?retryWrites=true&w=majority
# Optional: AWS S3 credentials
AWS_ACCESS_KEY_ID=your_access_key
AWS_SECRET_ACCESS_KEY=your_secret_key
AWS_BUCKET_NAME=your_bucket_name
# Optional: DagsHub credentials
DAGSHUB_REPO_OWNER=your_username
DAGSHUB_REPO_NAME=your_repo_namegit clone https://github.com/realadityagupta/NIDS_with_Automated_MLOPS_pipeline.git
cd networksecurity# Using venv
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Using conda
conda create -n networksecurity python=3.8
conda activate networksecuritypip install -r requirements.txt
# Or install in development mode:
pip install -e .# Create .env file with MongoDB connection
echo "MONGODB_URL_KEY=your_mongodb_uri" > .env# Ensure phisingData.csv is in Network_Data/ directory
# Or configure MongoDB connection with phishing datasetpython main.pyThis executes the full ML pipeline:
- Data ingestion β Validation β Transformation β Model Training
python app.py
# or
uvicorn app:app --reload --host 0.0.0.0 --port 8000- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
curl -X GET "http://localhost:8000/train"# Upload CSV file for batch prediction
curl -X POST "http://localhost:8000/predict" \
-F "file=@test.csv"# Build Docker image
docker build -t networksecurity:latest .
# Run container
docker run -p 8000:8000 \
-e MONGODB_URL_KEY="your_mongodb_uri" \
networksecurity:latestfrom networkSecurity.utils.main_utils.utils import load_object
from networkSecurity.utils.ml_utils.model.estimator import NetworkModel
import pandas as pd
# Load trained model and preprocessor
preprocessor = load_object("final_model/preprocessor.pkl")
model = load_object("final_model/model.pkl")
# Create NetworkModel wrapper
network_model = NetworkModel(preprocessor=preprocessor, model=model)
# Load test data
df = pd.read_csv("test.csv")
# Make predictions
predictions = network_model.predict(df)
print(predictions) # Output: [1, -1, 1, ...] (1 = Legitimate, -1 = Phishing)networksecurity/
βββ app.py # FastAPI application
βββ main.py # Training pipeline entry point
βββ push_data.py # MongoDB data upload utility
βββ test_mongodb.py # MongoDB connection test
βββ setup.py # Package setup configuration
βββ requirements.txt # Python dependencies
βββ Dockerfile # Docker configuration
βββ README.md # This file
β
βββ networkSecurity/ # Main package
β βββ __init__.py
β β
β βββ components/ # ML pipeline components
β β βββ data_ingestion.py
β β βββ data_validation.py
β β βββ data_transformation.py
β β βββ model_trainer.py
β β
β βββ pipeline/ # Pipeline orchestration
β β βββ training_pipeline.py
β β βββ batch_prediction.py
β β
β βββ entity/ # Config & artifact classes
β β βββ config_entity.py
β β βββ artifact_entity.py
β β
β βββ utils/ # Utility functions
β β βββ main_utils/
β β β βββ utils.py
β β βββ ml_utils/
β β βββ model/
β β β βββ estimator.py
β β βββ metric/
β β βββ classification_metric.py
β β
β βββ cloud/ # Cloud integration
β β βββ s3_syncer.py
β β
β βββ constant/ # Constants
β β βββ training_pipeline/
β β βββ __init__.py
β β
β βββ exceptionHandling/ # Exception handling
β β βββ exception.py
β β
β βββ logging/ # Logging
β βββ logger.py
β
βββ data_schema/ # Schema configuration
β βββ schema.yaml
β
βββ Network_Data/ # Input data
β βββ phisingData.csv
β
βββ Artifacts/ # Generated artifacts (timestamped)
β βββ mm_dd_yyyy_hh_mm_ss/
β βββ data_ingestion/
β βββ data_validation/
β βββ data_transformation/
β βββ model_trainer/
β
βββ final_model/ # Production models
β βββ model.pkl
β βββ preprocessor.pkl
β
βββ prediction_output/ # Prediction results
β βββ output.csv
β
βββ valid_data/ # Validated test data
β βββ test.csv
β
βββ templates/ # HTML templates
β βββ table.html
β
βββ notebooks/ # Jupyter notebooks
β
βββ NetworkSecurity.egg-info/ # Package metadata
http://localhost:8000
GET /train
Description: Trigger the full ML pipeline training
Response (Success):
{
"message": "Training is successful"
}Response (Error):
{
"detail": "Error message"
}POST /predict
Description: Upload CSV file and get phishing predictions
Parameters:
file(multipart/form-data): CSV file with 30 features (no Result column)
Response (Success):
- Returns HTML table with predictions
- Saves results to
prediction_output/output.csv - Prediction column:
1(Legitimate),-1(Phishing)
Example Request:
curl -X POST "http://localhost:8000/predict" \
-H "accept: text/html" \
-F "file=@test.csv"GET /docs # Swagger UI
GET /redoc # ReDoc
The system trains and compares 5 classification algorithms:
| Algorithm | Speed | Accuracy | Robustness |
|---|---|---|---|
| Logistic Regression | β‘β‘β‘ | ββ | βββ |
| Decision Tree | β‘β‘β‘ | ββ | ββ |
| Random Forest | β‘β‘ | βββ | ββββ |
| Gradient Boosting | β‘ | ββββ | βββ |
| AdaBoost | β‘β‘ | βββ | βββ |
Evaluation Metrics:
- F1-Score: Harmonic mean of precision and recall
- Precision: True positives / (True positives + False positives)
- Recall: True positives / (True positives + False negatives)
- Environment Variables: Store sensitive credentials in
.env, never commit - MongoDB: Use MongoDB Atlas with network access restrictions
- AWS S3: Use IAM roles with minimal required permissions
- CORS: API allows all origins (
*), restrict in production - Input Validation: Always validate and sanitize user inputs
Error: Unable to connect to MongoDB
Solution:
- Verify MONGODB_URL_KEY in .env
- Check MongoDB Atlas network access settings
- Ensure cluster is running
Error: ModuleNotFoundError: No module named 'sklearn'
Solution:
pip install -r requirements.txt# Use different port
uvicorn app:app --port 8080- Real-time model monitoring and retraining triggers
- Explainable AI (SHAP) for prediction interpretability
- Kubernetes deployment orchestration
- Advanced feature engineering with domain knowledge
- Multi-model ensemble with voting mechanisms
- A/B testing framework for model versions
- GraphQL API alternative to REST
- Mobile app for predictions
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit changes (
git commit -m 'Add amazing feature') - Push to branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the MIT License - see LICENSE file for details.
Aditya Gupta
- Email: ajaygupta995566@gmail.com
- GitHub: @realadityagupta
- Data Source: Phishing URL dataset
- MLOps Framework: MLflow + DagsHub
- Inspiration: Modern ML pipeline best practices
For issues, questions, or suggestions:
- Open an issue on GitHub
- Check existing issues for solutions
- Email: ajaygupta995566@gmail.com
- FastAPI Documentation
- scikit-learn Guide
- MongoDB Documentation
- MLflow Documentation
- AWS S3 Documentation
Network Security demonstrates an enterprise-grade ML pipeline for cybersecurity applications. By combining:
- Automated data processing via orchestrated components
- Ensemble machine learning with multiple algorithms
- MLOps best practices using MLflow and cloud integration
- Production readiness through containerization and REST APIs
This system provides a robust, scalable solution for phishing URL detection. The modular architecture allows easy extension with new features, algorithms, or data sources while maintaining code quality and reproducibility.
The project serves as a reference implementation for building production-ready ML systems that can:
β
Process data at scale
β
Train models reliably
β
Monitor performance continuously
β
Deploy confidently to production
Deploy this system to protect your organization from phishing attacks today!
Last Updated: September 2026
Version: 1.0.0
Status: β
Production Ready