GitHub Actions commited on
Commit
5af35cc
·
0 Parent(s):

Deploy snapshot to HF Space

Browse files
Files changed (49) hide show
  1. .dockerignore +41 -0
  2. .gitattributes +1 -0
  3. .github/workflows/main.yml +24 -0
  4. .gitignore +217 -0
  5. Dockerfile +44 -0
  6. LICENSE +21 -0
  7. README.md +244 -0
  8. app.py +609 -0
  9. data_schema/schema.yaml +66 -0
  10. main.py +42 -0
  11. networksecurity/__init__.py +0 -0
  12. networksecurity/cloud/__init__.py +0 -0
  13. networksecurity/cloud/s3_syncer.py +10 -0
  14. networksecurity/components/__init__.py +0 -0
  15. networksecurity/components/data_ingestion.py +115 -0
  16. networksecurity/components/data_transformation.py +99 -0
  17. networksecurity/components/data_validation.py +125 -0
  18. networksecurity/components/model_trainer.py +222 -0
  19. networksecurity/constant/__init__.py +0 -0
  20. networksecurity/constant/training_pipeline/__init__.py +68 -0
  21. networksecurity/entity/__init__.py +0 -0
  22. networksecurity/entity/artifact_entity.py +38 -0
  23. networksecurity/entity/config_entity.py +123 -0
  24. networksecurity/exception/__init__.py +0 -0
  25. networksecurity/exception/exception.py +21 -0
  26. networksecurity/logging/__init__.py +0 -0
  27. networksecurity/logging/logger.py +16 -0
  28. networksecurity/pipeline/__init__.py +0 -0
  29. networksecurity/pipeline/batch_prediction.py +0 -0
  30. networksecurity/pipeline/training_pipeline.py +143 -0
  31. networksecurity/utils/__init__.py +0 -0
  32. networksecurity/utils/main_utils/__init__.py +0 -0
  33. networksecurity/utils/main_utils/utils.py +117 -0
  34. networksecurity/utils/ml_utils/__init__.py +0 -0
  35. networksecurity/utils/ml_utils/metric/__init.py +0 -0
  36. networksecurity/utils/ml_utils/metric/classfication_metric.py +19 -0
  37. networksecurity/utils/ml_utils/model/__init__.py +0 -0
  38. networksecurity/utils/ml_utils/model/estimator.py +35 -0
  39. push_data.py +61 -0
  40. requirements.txt +25 -0
  41. setup.py +29 -0
  42. static/css/style.css +1456 -0
  43. static/js/main.js +271 -0
  44. templates/index.html +341 -0
  45. templates/predict.html +230 -0
  46. templates/single_predict.html +436 -0
  47. test.py +119 -0
  48. valid_data/test.csv +13 -0
  49. verify_mongo.py +29 -0
.dockerignore ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # Python
3
+ __pycache__/
4
+ *.py[cod]
5
+ *$py.class
6
+ *.so
7
+ .Python
8
+ build/
9
+ develop-eggs/
10
+ dist/
11
+ downloads/
12
+ eggs/
13
+ .eggs/
14
+ lib/
15
+ lib64/
16
+ parts/
17
+ sdist/
18
+ var/
19
+ wheels/
20
+ share/python-wheels/
21
+ *.egg-info/
22
+ .installed.cfg
23
+ *.egg
24
+ MANIFEST
25
+
26
+ # Virtual Environment
27
+ .env
28
+ .venv
29
+ env/
30
+ venv/
31
+ ENV/
32
+
33
+ # Project Specific (Heavy/Unnecessary for Docker)
34
+ Artifact/
35
+ Network_data/
36
+ mlruns/
37
+ deploy_stage/
38
+ final_model/
39
+ .git/
40
+ .github/
41
+ .vscode/
.gitattributes ADDED
@@ -0,0 +1 @@
 
 
1
+
.github/workflows/main.yml ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Sync to Hugging Face hub
2
+ on:
3
+ push:
4
+ branches: [main]
5
+ workflow_dispatch:
6
+
7
+ jobs:
8
+ sync-to-hub:
9
+ runs-on: ubuntu-latest
10
+ steps:
11
+ - uses: actions/checkout@v3
12
+ - name: Push to hub
13
+ env:
14
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
15
+ run: |
16
+ git config user.email "actions@github.com"
17
+ git config user.name "GitHub Actions"
18
+ # HF Space rejects raw binaries. Strip images/ and push an orphan
19
+ # snapshot so neither the tip tree nor history contains PNGs.
20
+ git checkout --orphan hf-deploy
21
+ rm -rf images/
22
+ git add -A
23
+ git commit -m "Deploy snapshot to HF Space"
24
+ git push --force "https://inderjeet:${HF_TOKEN}@huggingface.co/spaces/inderjeet/NetworkSecurity" hf-deploy:main
.gitignore ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+ #poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
114
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
115
+ #pdm.lock
116
+ #pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # pixi
121
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
122
+ #pixi.lock
123
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
124
+ # in the .venv directory. It is recommended not to include this directory in version control.
125
+ .pixi
126
+
127
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
128
+ __pypackages__/
129
+
130
+ # Celery stuff
131
+ celerybeat-schedule
132
+ celerybeat.pid
133
+
134
+ # SageMath parsed files
135
+ *.sage.py
136
+
137
+ # Environments
138
+ .env
139
+ .envrc
140
+ .venv
141
+ env/
142
+ venv/
143
+ ENV/
144
+ env.bak/
145
+ venv.bak/
146
+
147
+ # Spyder project settings
148
+ .spyderproject
149
+ .spyproject
150
+
151
+ # Rope project settings
152
+ .ropeproject
153
+
154
+ # mkdocs documentation
155
+ /site
156
+
157
+ # mypy
158
+ .mypy_cache/
159
+ .dmypy.json
160
+ dmypy.json
161
+
162
+ # Pyre type checker
163
+ .pyre/
164
+
165
+ # pytype static type analyzer
166
+ .pytype/
167
+
168
+ # Cython debug symbols
169
+ cython_debug/
170
+
171
+ # PyCharm
172
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
173
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
174
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
175
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
176
+ #.idea/
177
+
178
+ # Abstra
179
+ # Abstra is an AI-powered process automation framework.
180
+ # Ignore directories containing user credentials, local state, and settings.
181
+ # Learn more at https://abstra.io/docs
182
+ .abstra/
183
+
184
+ # Visual Studio Code
185
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
186
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
187
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
188
+ # you could uncomment the following to ignore the entire vscode folder
189
+ # .vscode/
190
+
191
+ # Ruff stuff:
192
+ .ruff_cache/
193
+
194
+ # PyPI configuration file
195
+ .pypirc
196
+
197
+ # Cursor
198
+ # Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
199
+ # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
200
+ # refer to https://docs.cursor.com/context/ignore-files
201
+ .cursorignore
202
+ .cursorindexingignore
203
+
204
+ # Marimo
205
+ marimo/_static/
206
+ marimo/_lsp/
207
+ __marimo__/
208
+
209
+ # Project Specific
210
+ Artifact/
211
+ final_model/
212
+ deploy_stage/
213
+ mlruns/
214
+ Network_data/
215
+
216
+ mlflow.db
217
+ *.db
Dockerfile ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 1. Use Python 3.11 slim image for a smaller, faster container
2
+ FROM python:3.11-slim
3
+
4
+ # 2. Set the working directory
5
+ WORKDIR /app
6
+
7
+ # 3. Install system dependencies (git is needed for DagsHub/MLflow)
8
+ RUN apt-get update && apt-get install -y \
9
+ git \
10
+ && rm -rf /var/lib/apt/lists/*
11
+
12
+ # 4. Copy requirements first to use Docker caching
13
+ COPY requirements.txt .
14
+
15
+ # 5. Install Python libraries
16
+ RUN pip install --no-cache-dir --upgrade pip && \
17
+ pip install --no-cache-dir -r requirements.txt
18
+
19
+ # 6. Create a non-root user (Hugging Face requirement)
20
+ # This user must have UID 1000
21
+ RUN useradd -m -u 1000 user
22
+ USER user
23
+ ENV HOME=/home/user \
24
+ PATH=/home/user/.local/bin:$PATH
25
+
26
+ # 7. Set working directory to the user's home
27
+ WORKDIR $HOME/app
28
+
29
+ # 8. Copy all project files and change ownership to 'user'
30
+ COPY --chown=user . $HOME/app
31
+
32
+ # 9. Create directories that app.py uses for data and outputs
33
+ RUN mkdir -p final_model prediction_output validation_output valid_data static templates
34
+
35
+ # 10. Set environment variables
36
+ # Ensures logs are printed immediately to the terminal
37
+ ENV PYTHONUNBUFFERED=1
38
+
39
+ # 11. Expose the port Hugging Face listens on
40
+ EXPOSE 7860
41
+
42
+ # 12. Start the FastAPI application
43
+ # We use port 7860 to match Hugging Face's default
44
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Inderjeet
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: NetworkSecurity
3
+ emoji: 😻
4
+ colorFrom: blue
5
+ colorTo: blue
6
+ sdk: docker
7
+ pinned: false
8
+ license: mit
9
+ ---
10
+
11
+ # 🛡️ Network Security System: Phishing URL Detection
12
+
13
+ ![UI Homepage 1](images/home_page_1.png)
14
+ ![UI Homepage 2](images/home_page_2.png)
15
+ ![UI Homepage 3](images/home_page_3.png)
16
+ ![UI Homepage 4](images/home_page_4.png)
17
+ ![UI Homepage 5](images/home_page_5.png)
18
+
19
+ ## 📋 Table of Contents
20
+
21
+ - [About The Project](#-about-the-project)
22
+ - [Architecture](#-architecture)
23
+ - [Features](#-features)
24
+ - [Tech Stack](#-tech-stack)
25
+ - [Dataset](#-dataset)
26
+ - [Project Structure](#-project-structure)
27
+ - [Pipeline Workflow](#-pipeline-workflow)
28
+ - [Screenshots](#-screenshots)
29
+ - [Installation](#-installation)
30
+ - [Usage](#-usage)
31
+ - [Model Performance](#-model-performance)
32
+ - [Experiment Tracking](#-experiment-tracking)
33
+ - [Future Enhancements](#-future-enhancements)
34
+ - [Contributing](#-contributing)
35
+ - [License](#-license)
36
+ - [Contact](#-contact)
37
+
38
+ ## 🚀 Live Demo
39
+
40
+ - **Live Application**: [inderjeet-networksecurity.hf.space](https://inderjeet-networksecurity.hf.space/)
41
+ - **Experiment Tracking**: [DagsHub Experiments](https://dagshub.com/Inder-26/NetworkSecurity/experiments#/)
42
+
43
+ ## 🎯 About The Project
44
+
45
+ In the digital age, cybersecurity threats such as phishing attacks are becoming increasingly sophisticated. This project implements a robust **Network Security Machine Learning Pipeline** designed to detect phishing URLs with high accuracy.
46
+
47
+ It leverages a modular MLOps architecture, ensuring scalability, maintainability, and reproducibility. The system automates the entire flow from data ingestion to model deployment, utilizing advanced techniques like drift detection and automated model evaluation.
48
+
49
+ ## 🏗️ Architecture
50
+
51
+ The system follows a strict modular pipeline architecture, orchestrated by a central training pipeline.
52
+
53
+ ![Architecture Diagram](images/architecture_diagram.png)
54
+
55
+ ## ✨ Features
56
+
57
+ - **🚀 End-to-End Pipeline**: Fully automated workflow from data ingestion to model deployment.
58
+ - **🛡️ Data Validation**: Comprehensive schema checks and data drift detection using KS tests.
59
+ - **🔄 Robust Preprocessing**: Automated handling of missing values (KNN Imputer) and feature scaling (Robust Scaler).
60
+ - **🤖 Multi-Model Training**: Experiments with RandomForest, DecisionTree, GradientBoosting, and AdaBoost using GridSearchCV.
61
+ - **📊 Experiment Tracking**: Integrated with **MLflow** and **DagsHub** for tracking parameters, metrics, and models.
62
+ - **⚡ Fast API**: High-performance REST API built with **FastAPI** for real-time predictions.
63
+ - **🐳 Containerized**: Docker support for consistent deployment across environments.
64
+ - **☁️ Cloud Ready**: Designed to be deployed on platforms like AWS or Hugging Face Spaces.
65
+
66
+ ## 🛠️ Tech Stack
67
+
68
+ - **Languages**: Python 3.8+
69
+ - **Frameworks**: FastAPI, Uvicorn
70
+ - **ML Libraries**: Scikit-learn, Pandas, NumPy
71
+ - **MLOps**: MLflow, DagsHub
72
+ - **Database**: MongoDB
73
+ - **Containerization**: Docker
74
+ - **Frontend**: HTML, CSS (Custom Design System), JavaScript
75
+
76
+ ## 📊 Dataset
77
+
78
+ The project utilizes a dataset containing various URL features to distinguish between legitimate and phishing URLs.
79
+
80
+ - **Source**: [Phishing Dataset for Machine Learning](https://archive.ics.uci.edu/ml/datasets/Phishing+Websites) (or similar Phishing URL dataset)
81
+ - **Features**: IP Address, URL Length, TinyURL, forwarding, etc.
82
+ - **Target**: `Result` (LEGITIMATE / PHISHING)
83
+
84
+ ## 📁 Project Structure
85
+
86
+ ```
87
+ NetworkSecurity/
88
+ ├── images/ # Project diagrams and screenshots
89
+ ├── networksecurity/ # Main package
90
+ │ ├── components/ # Pipeline components (Ingestion, Validation, Transformation, Training)
91
+ │ ├── pipeline/ # Training and Prediction pipelines
92
+ │ ├── entity/ # Artifact and Config entities
93
+ │ ├── constants/ # Project constants
94
+ │ ├── utils/ # Utility functions
95
+ │ └── exception/ # Custom exception handling
96
+ ├── data_schema/ # Schema definitions
97
+ ├── Dockerfile # Docker configuration
98
+ ├── app.py # FastAPI application entry point
99
+ ├── requirements.txt # Project dependencies
100
+ └── README.md # Project documentation
101
+ ```
102
+
103
+ ## ⚙️ Pipeline Workflow
104
+
105
+ ### 1. Data Ingestion 📥
106
+
107
+ Fetches data from MongoDB, handles fallback to local CSV, and performs train-test split.
108
+ ![Data Ingestion](images/data_ingestion_diagram.png)
109
+
110
+ ### 2. Data Validation ✅
111
+
112
+ Validates data against schema and checks for data drift.
113
+ ![Data Validation](images/data_validation_diagram.png)
114
+
115
+ ### 3. Data Transformation 🔄
116
+
117
+ Imputes missing values and scales features for optimal model performance.
118
+ ![Data Transformation](images/data_transformation_diagram.png)
119
+
120
+ ### 4. Model Training 🤖
121
+
122
+ Trains and tunes multiple models, selecting the best one based on F1-score/Accuracy.
123
+ ![Model Training](images/model_training_diagram.png)
124
+
125
+ ## 📸 Screenshots
126
+
127
+ ### Prediction Results & Threat Assessment
128
+
129
+ ![Prediction Results](images/prediction_results.png)
130
+
131
+ ### Experiment Tracking (DagsHub/MLflow)
132
+
133
+ ![Experiment Tracking](images/dagshub_experiments.png)
134
+
135
+ ## 💻 Installation
136
+
137
+ ### Prerequisites
138
+
139
+ - Python 3.8+
140
+ - MongoDB Account
141
+ - DagsHub Account (for experiment tracking)
142
+
143
+ ### Step-by-Step
144
+
145
+ 1. **Clone the Repository**
146
+
147
+ ```bash
148
+ git clone https://github.com/Inder-26/NetworkSecurity.git
149
+ cd NetworkSecurity
150
+ ```
151
+
152
+ 2. **Create Virtual Environment**
153
+
154
+ ```bash
155
+ python -m venv .venv
156
+ source .venv/bin/activate # On Windows: .venv\Scripts\activate
157
+ ```
158
+
159
+ 3. **Install Dependencies**
160
+
161
+ ```bash
162
+ pip install -r requirements.txt
163
+ ```
164
+
165
+ 4. **Set Environment Variables**
166
+ Create a `.env` file with your credentials:
167
+ ```env
168
+ MONGO_DB_URL=your_mongodb_url_here
169
+ MLFLOW_TRACKING_URI=https://dagshub.com/your_username/project.mlflow
170
+ MLFLOW_TRACKING_USERNAME=your_username
171
+ MLFLOW_TRACKING_PASSWORD=your_password
172
+ ```
173
+
174
+ ## 🚀 Usage
175
+
176
+ ### Run the Web Application
177
+
178
+ ```bash
179
+ python app.py
180
+ ```
181
+
182
+ Visit `http://localhost:8000` to access the UI.
183
+
184
+ ### Train a New Model
185
+
186
+ To trigger the training pipeline:
187
+
188
+ ```bash
189
+ http://localhost:8000/train
190
+ ```
191
+
192
+ Or use the "Train New Model" button in the UI.
193
+
194
+ ## 📈 Model Performance
195
+
196
+ The system evaluates models using accuracy and F1 score.
197
+
198
+ - **Best Model**: [Automatically selected, typically RandomForest or GradientBoosting]
199
+ - **Recall**: Optimized to minimize false negatives (missing a phishing URL is dangerous).
200
+
201
+ ### Model Evaluation Metrics
202
+
203
+ Below are the performance visualizations for the best trained model:
204
+
205
+ #### Confusion Matrix
206
+
207
+ ![Confusion Matrix](images/confusion_matrix.png)
208
+
209
+ #### ROC Curve
210
+
211
+ ![ROC Curve](images/roc_curve.png)
212
+
213
+ #### Precision-Recall Curve
214
+
215
+ ![Precision-Recall Curve](images/precision_recall_curve.png)
216
+
217
+ ## 🧪 Experiment Tracking
218
+
219
+ All runs are logged to DagsHub. You can view parameters, metrics, and models in the MLflow UI.
220
+
221
+ ## 🚀 Future Enhancements
222
+
223
+ - [ ] Implement Deep Learning models (LSTM/CNN) for URL text analysis.
224
+ - [ ] Add real-time browser extension.
225
+ - [ ] Deploy serverless architecture.
226
+ - [ ] Add more comprehensive unit and integration tests.
227
+
228
+ ## 🤝 Contributing
229
+
230
+ Contributions are welcome! Please fork the repository and create a pull request.
231
+
232
+ 1. Fork the Project
233
+ 2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`)
234
+ 3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`)
235
+ 4. Push to the Branch (`git push origin feature/AmazingFeature`)
236
+ 5. Open a Pull Request
237
+
238
+ ## 📄 License
239
+
240
+ Distributed under the MIT License. See `LICENSE` for more information.
241
+
242
+ ## 📞 Contact
243
+
244
+ Inder - [GitHub Profile](https://github.com/Inder-26)
app.py ADDED
@@ -0,0 +1,609 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import pandas as pd
4
+ import numpy as np
5
+ import joblib
6
+ from pathlib import Path
7
+ from datetime import datetime
8
+ from typing import Optional
9
+
10
+ from fastapi import FastAPI, File, UploadFile, Request, HTTPException, Form
11
+ from fastapi.responses import HTMLResponse, FileResponse, JSONResponse
12
+ from fastapi.staticfiles import StaticFiles
13
+ from fastapi.templating import Jinja2Templates
14
+ from fastapi.middleware.cors import CORSMiddleware
15
+
16
+ import uvicorn
17
+ import mlflow
18
+ import dagshub
19
+ import shutil
20
+ from networksecurity.pipeline.training_pipeline import TrainingPipeline
21
+
22
+ # ============================================================
23
+ # Configuration
24
+ # ============================================================
25
+
26
+ APP_TITLE = "Network Security - Phishing Detection"
27
+ APP_DESCRIPTION = "ML-powered phishing URL detection system"
28
+ APP_VERSION = "1.0.0"
29
+
30
+ # Project Links
31
+ GITHUB_URL = "https://github.com/Inder-26/NetworkSecurity"
32
+ DAGSHUB_URL = "https://dagshub.com/Inder-26/NetworkSecurity"
33
+ LINKEDIN_URL = "https://linkedin.com/in/inderjeet" # Update with your actual LinkedIn
34
+
35
+ # Model Paths
36
+ MODEL_PATH = "final_model/model.pkl"
37
+ PREPROCESSOR_PATH = "final_model/preprocessor.pkl"
38
+
39
+ # Initialize DagsHub
40
+ if os.getenv("MLFLOW_TRACKING_USERNAME") and os.getenv("MLFLOW_TRACKING_PASSWORD"):
41
+ try:
42
+ dagshub.init(repo_owner="Inder-26", repo_name="NetworkSecurity", mlflow=True)
43
+ except Exception as e:
44
+ print(f"⚠️ Error initializing DagsHub: {e}")
45
+ else:
46
+ print("⚠️ DagsHub credentials not found. Skipping initialization.")
47
+
48
+ # Feature Columns (30 features)
49
+ FEATURE_COLUMNS = [
50
+ "having_IP_Address", "URL_Length", "Shortining_Service", "having_At_Symbol",
51
+ "double_slash_redirecting", "Prefix_Suffix", "having_Sub_Domain", "SSLfinal_State",
52
+ "Domain_registeration_length", "Favicon", "port", "HTTPS_token", "Request_URL",
53
+ "URL_of_Anchor", "Links_in_tags", "SFH", "Submitting_to_email", "Abnormal_URL",
54
+ "Redirect", "on_mouseover", "RightClick", "popUpWidnow", "Iframe", "age_of_domain",
55
+ "DNSRecord", "web_traffic", "Page_Rank", "Google_Index", "Links_pointing_to_page",
56
+ "Statistical_report"
57
+ ]
58
+
59
+ # Feature descriptions for UI
60
+ FEATURE_INFO = {
61
+ "having_IP_Address": {"group": "URL Structure", "desc": "IP address in URL"},
62
+ "URL_Length": {"group": "URL Structure", "desc": "Length of URL"},
63
+ "Shortining_Service": {"group": "URL Structure", "desc": "URL shortening service used"},
64
+ "having_At_Symbol": {"group": "URL Structure", "desc": "@ symbol in URL"},
65
+ "double_slash_redirecting": {"group": "URL Structure", "desc": "// redirecting"},
66
+ "Prefix_Suffix": {"group": "URL Structure", "desc": "Prefix/suffix in domain"},
67
+ "having_Sub_Domain": {"group": "URL Structure", "desc": "Subdomain presence"},
68
+ "SSLfinal_State": {"group": "Security", "desc": "SSL certificate state"},
69
+ "Domain_registeration_length": {"group": "Domain", "desc": "Domain registration length"},
70
+ "Favicon": {"group": "Security", "desc": "Favicon loaded from external"},
71
+ "port": {"group": "Security", "desc": "Non-standard port"},
72
+ "HTTPS_token": {"group": "Security", "desc": "HTTPS token in domain"},
73
+ "Request_URL": {"group": "Page Content", "desc": "External request URLs"},
74
+ "URL_of_Anchor": {"group": "Page Content", "desc": "Anchor URL analysis"},
75
+ "Links_in_tags": {"group": "Page Content", "desc": "Links in meta/script tags"},
76
+ "SFH": {"group": "Page Content", "desc": "Server Form Handler"},
77
+ "Submitting_to_email": {"group": "Page Content", "desc": "Form submits to email"},
78
+ "Abnormal_URL": {"group": "URL Structure", "desc": "Abnormal URL pattern"},
79
+ "Redirect": {"group": "Page Behavior", "desc": "Redirect count"},
80
+ "on_mouseover": {"group": "Page Behavior", "desc": "onMouseOver events"},
81
+ "RightClick": {"group": "Page Behavior", "desc": "Right-click disabled"},
82
+ "popUpWidnow": {"group": "Page Behavior", "desc": "Pop-up windows"},
83
+ "Iframe": {"group": "Page Behavior", "desc": "Iframe usage"},
84
+ "age_of_domain": {"group": "Domain", "desc": "Domain age"},
85
+ "DNSRecord": {"group": "Domain", "desc": "DNS record exists"},
86
+ "web_traffic": {"group": "Domain", "desc": "Web traffic ranking"},
87
+ "Page_Rank": {"group": "Domain", "desc": "Google PageRank"},
88
+ "Google_Index": {"group": "Domain", "desc": "Indexed by Google"},
89
+ "Links_pointing_to_page": {"group": "Domain", "desc": "External links count"},
90
+ "Statistical_report": {"group": "Security", "desc": "In statistical reports"}
91
+ }
92
+
93
+ # Actual Model Metrics from DagsHub experiments
94
+ MODEL_METRICS = {
95
+ "model_name": "Random Forest",
96
+ "accuracy": 0.0,
97
+ "f1_score": 0.0,
98
+ "precision": 0.0,
99
+ "recall": 0.0,
100
+ "training_date": "N/A"
101
+ }
102
+
103
+ # All model comparison data
104
+ ALL_MODELS = []
105
+
106
+ def get_latest_metrics():
107
+ """Fetch latest metrics from DagsHub/MLflow"""
108
+ global MODEL_METRICS, ALL_MODELS
109
+ try:
110
+ # Search for all successful runs
111
+ runs = mlflow.search_runs()
112
+
113
+ if runs.empty:
114
+ print("⚠️ No MLflow runs found.")
115
+ return
116
+
117
+ # Process all runs for the table
118
+ all_models_data = []
119
+ best_f1 = -1
120
+ best_run = None
121
+
122
+ for _, run in runs.iterrows():
123
+ # Extract metrics
124
+ accuracy = run.get("metrics.test_accuracy", 0) # Fallback if specific metric missing
125
+ f1 = run.get("metrics.test_f1", 0)
126
+ precision = run.get("metrics.test_precision", 0)
127
+ recall = run.get("metrics.test_recall", 0)
128
+
129
+ # Extract tags/params
130
+ model_name = run.get("tags.model_name", run.get("params.model_name", "Unknown Model"))
131
+
132
+ # Check if this is the best model so far
133
+ if f1 > best_f1:
134
+ best_f1 = f1
135
+ best_run = {
136
+ "model_name": model_name,
137
+ "accuracy": round(accuracy, 4),
138
+ "f1_score": round(f1, 4),
139
+ "precision": round(precision, 4),
140
+ "recall": round(recall, 4),
141
+ "training_date": run.get("start_time", datetime.now()).strftime("%Y-%m-%d") if isinstance(run.get("start_time"), datetime) else str(run.get("start_time"))[:10]
142
+ }
143
+
144
+ all_models_data.append({
145
+ "name": model_name,
146
+ "accuracy": round(accuracy, 4),
147
+ "f1": round(f1, 4),
148
+ "precision": round(precision, 4),
149
+ "recall": round(recall, 4),
150
+ "best": False # Will set best later
151
+ })
152
+
153
+ # Update global variables
154
+ if best_run:
155
+ MODEL_METRICS = best_run
156
+ # Mark the best model in the list
157
+ for m in all_models_data:
158
+ if m["name"] == best_run["model_name"] and m["f1"] == best_run["f1_score"]:
159
+ m["best"] = True
160
+
161
+ ALL_MODELS = sorted(all_models_data, key=lambda x: x['f1'], reverse=True)
162
+ print(f"✅ Metrics updated from MLflow. Best model: {best_run['model_name']}")
163
+
164
+ except Exception as e:
165
+ print(f"❌ Error fetching MLflow metrics: {e}")
166
+
167
+ # Fetch initial metrics
168
+ get_latest_metrics()
169
+
170
+ # ============================================================
171
+ # Initialize FastAPI App
172
+ # ============================================================
173
+
174
+ app = FastAPI(
175
+ title=APP_TITLE,
176
+ description=APP_DESCRIPTION,
177
+ version=APP_VERSION,
178
+ docs_url="/api/docs",
179
+ redoc_url="/api/redoc"
180
+ )
181
+
182
+ # CORS Middleware
183
+ app.add_middleware(
184
+ CORSMiddleware,
185
+ allow_origins=["*"],
186
+ allow_credentials=True,
187
+ allow_methods=["*"],
188
+ allow_headers=["*"],
189
+ )
190
+
191
+ # Static Files and Templates
192
+ app.mount("/static", StaticFiles(directory="static"), name="static")
193
+ templates = Jinja2Templates(directory="templates")
194
+
195
+ # ============================================================
196
+ # Load Models
197
+ # ============================================================
198
+
199
+ def load_models():
200
+ """Load the trained model and preprocessor"""
201
+ try:
202
+ if os.path.exists(MODEL_PATH) and os.path.exists(PREPROCESSOR_PATH):
203
+ model = joblib.load(MODEL_PATH)
204
+ preprocessor = joblib.load(PREPROCESSOR_PATH)
205
+ print("✅ Models loaded successfully!")
206
+ return model, preprocessor
207
+ else:
208
+ print("⚠️ Model files not found. Running in demo mode.")
209
+ return None, None
210
+ except Exception as e:
211
+ print(f"❌ Error loading models: {e}")
212
+ return None, None
213
+
214
+ model, preprocessor = load_models()
215
+
216
+ # ============================================================
217
+ # Utility Functions
218
+ # ============================================================
219
+
220
+ def generate_sample_data(n_samples: int = 5) -> pd.DataFrame:
221
+ """Generate sample input data for testing"""
222
+ np.random.seed(42)
223
+ data = {}
224
+ for col in FEATURE_COLUMNS:
225
+ data[col] = np.random.choice([-1, 0, 1], size=n_samples)
226
+ return pd.DataFrame(data)
227
+
228
+ def predict_single(features: dict) -> dict:
229
+ """Make prediction for a single sample"""
230
+ if model is None or preprocessor is None:
231
+ # Demo mode - return random prediction
232
+ prediction = np.random.choice([0, 1])
233
+ confidence = np.random.uniform(0.7, 0.99)
234
+ else:
235
+ df = pd.DataFrame([features])
236
+ X_transformed = preprocessor.transform(df)
237
+ prediction = model.predict(X_transformed)[0]
238
+
239
+ try:
240
+ proba = model.predict_proba(X_transformed)[0]
241
+ confidence = float(max(proba))
242
+ except:
243
+ confidence = 0.95
244
+
245
+ return {
246
+ "prediction": int(prediction),
247
+ "label": "Phishing" if prediction == 0 else "Legitimate",
248
+ "confidence": round(confidence * 100, 2),
249
+ "is_threat": prediction == 0
250
+ }
251
+
252
+ def predict_batch(df: pd.DataFrame) -> tuple:
253
+ """Make predictions for batch data"""
254
+ X = df[FEATURE_COLUMNS]
255
+
256
+ if model is None or preprocessor is None:
257
+ # Demo mode
258
+ predictions = np.random.choice([0, 1], size=len(df))
259
+ confidence = np.random.uniform(0.7, 0.99, size=len(df))
260
+ else:
261
+ X_transformed = preprocessor.transform(X)
262
+ predictions = model.predict(X_transformed)
263
+
264
+ try:
265
+ probabilities = model.predict_proba(X_transformed)
266
+ confidence = np.max(probabilities, axis=1)
267
+ except:
268
+ confidence = np.ones(len(predictions)) * 0.95
269
+
270
+ return predictions, confidence
271
+
272
+ # ============================================================
273
+ # Routes
274
+ # ============================================================
275
+
276
+ @app.get("/", response_class=HTMLResponse)
277
+ async def home(request: Request):
278
+ """Home page with upload interface"""
279
+ # Refresh metrics on page load
280
+ get_latest_metrics()
281
+
282
+ return templates.TemplateResponse(
283
+ request,
284
+ "index.html",
285
+ {
286
+ "title": APP_TITLE,
287
+ "github_url": GITHUB_URL,
288
+ "dagshub_url": DAGSHUB_URL,
289
+ "linkedin_url": LINKEDIN_URL,
290
+ "metrics": MODEL_METRICS,
291
+ "all_models": ALL_MODELS,
292
+ "feature_count": len(FEATURE_COLUMNS),
293
+ "features": FEATURE_COLUMNS,
294
+ "feature_info": FEATURE_INFO
295
+ }
296
+ )
297
+
298
+
299
+ @app.get("/manual", response_class=HTMLResponse)
300
+ async def manual_input(request: Request):
301
+ """Manual input form page"""
302
+ return templates.TemplateResponse(
303
+ request,
304
+ "single_predict.html",
305
+ {
306
+ "title": "Manual Prediction",
307
+ "features": FEATURE_COLUMNS,
308
+ "feature_info": FEATURE_INFO,
309
+ "github_url": GITHUB_URL,
310
+ "dagshub_url": DAGSHUB_URL,
311
+ "linkedin_url": LINKEDIN_URL
312
+ }
313
+ )
314
+
315
+
316
+ @app.get("/health")
317
+ async def health_check():
318
+ """Health check endpoint"""
319
+ return {
320
+ "status": "healthy",
321
+ "model_loaded": model is not None,
322
+ "preprocessor_loaded": preprocessor is not None,
323
+ "version": APP_VERSION
324
+ }
325
+
326
+
327
+ @app.get("/api/features")
328
+ async def get_features():
329
+ """Return list of required features"""
330
+ return {
331
+ "features": FEATURE_COLUMNS,
332
+ "count": len(FEATURE_COLUMNS),
333
+ "info": FEATURE_INFO
334
+ }
335
+
336
+
337
+ @app.get("/api/metrics")
338
+ async def get_metrics():
339
+ """Return model performance metrics"""
340
+ return {
341
+ "best_model": MODEL_METRICS,
342
+ "all_models": ALL_MODELS
343
+ }
344
+
345
+
346
+ @app.get("/download/sample")
347
+ async def download_sample():
348
+ """Download sample CSV file"""
349
+ sample_path = "valid_data/test.csv"
350
+
351
+ if not os.path.exists(sample_path):
352
+ # Fallback if specific file not found
353
+ return JSONResponse(status_code=404, content={"message": "Sample file not found at valid_data/test.csv"})
354
+
355
+ return FileResponse(
356
+ sample_path,
357
+ media_type="text/csv",
358
+ filename="sample_phishing_data.csv"
359
+ )
360
+
361
+
362
+ @app.post("/predict")
363
+ async def predict(request: Request, file: UploadFile = File(...)):
364
+ """Handle file upload and return predictions"""
365
+
366
+ # Validate file type
367
+ if not file.filename.endswith('.csv'):
368
+ raise HTTPException(
369
+ status_code=400,
370
+ detail="Please upload a CSV file"
371
+ )
372
+
373
+ try:
374
+ # Read uploaded file
375
+ df = pd.read_csv(file.file)
376
+ original_df = df.copy()
377
+
378
+ # Validate columns
379
+ missing_cols = set(FEATURE_COLUMNS) - set(df.columns)
380
+ if missing_cols:
381
+ raise HTTPException(
382
+ status_code=400,
383
+ detail=f"Missing columns: {', '.join(sorted(missing_cols))}"
384
+ )
385
+
386
+ # Make predictions
387
+ predictions, confidence = predict_batch(df)
388
+
389
+ # Map predictions to labels
390
+ prediction_labels = ["⚠️ Phishing" if p == 0 else "🔒 Legitimate" for p in predictions]
391
+
392
+ # Create results dataframe
393
+ results_df = original_df.copy()
394
+ results_df["Prediction"] = predictions
395
+ results_df["Label"] = prediction_labels
396
+ results_df["Confidence"] = (confidence * 100).round(2)
397
+
398
+ # Save results
399
+ os.makedirs("prediction_output", exist_ok=True)
400
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
401
+ output_filename = f"predictions_{timestamp}.csv"
402
+ output_path = f"prediction_output/{output_filename}"
403
+ results_df.to_csv(output_path, index=False)
404
+
405
+ # Calculate summary
406
+ total = len(predictions)
407
+ # 0 is Phishing (mapped from -1), 1 is Legitimate
408
+ phishing_count = int(np.sum(predictions == 0))
409
+ legitimate_count = total - phishing_count
410
+
411
+ # Prepare display columns (show first 5 features + results)
412
+ display_columns = FEATURE_COLUMNS[:5] + ["Prediction", "Label", "Confidence"]
413
+
414
+ return templates.TemplateResponse(
415
+ request,
416
+ "predict.html",
417
+ {
418
+ "title": "Prediction Results",
419
+ "results": results_df.to_dict(orient="records"),
420
+ "summary": {
421
+ "total": total,
422
+ "phishing": phishing_count,
423
+ "legitimate": legitimate_count,
424
+ "phishing_percent": round(phishing_count / total * 100, 1) if total > 0 else 0
425
+ },
426
+ "output_filename": output_filename,
427
+ "columns": display_columns,
428
+ "github_url": GITHUB_URL,
429
+ "dagshub_url": DAGSHUB_URL,
430
+ "linkedin_url": LINKEDIN_URL
431
+ }
432
+ )
433
+
434
+ except HTTPException:
435
+ raise
436
+ except Exception as e:
437
+ raise HTTPException(
438
+ status_code=500,
439
+ detail=f"Prediction error: {str(e)}"
440
+ )
441
+
442
+
443
+ @app.post("/api/predict/single")
444
+ async def predict_single_api(request: Request):
445
+ """Handle single prediction from form (API)"""
446
+ try:
447
+ form_data = await request.form()
448
+
449
+ # Build feature dictionary
450
+ features = {}
451
+ for col in FEATURE_COLUMNS:
452
+ value = form_data.get(col, "0")
453
+ try:
454
+ features[col] = int(value) if value else 0
455
+ except ValueError:
456
+ features[col] = 0
457
+
458
+ # Make prediction
459
+ result = predict_single(features)
460
+
461
+ def convert_numpy(obj):
462
+ if isinstance(obj, dict):
463
+ return {k: convert_numpy(v) for k, v in obj.items()}
464
+ elif isinstance(obj, list):
465
+ return [convert_numpy(v) for v in obj]
466
+ elif hasattr(obj, 'item'): # Numpy scalars
467
+ return obj.item()
468
+ elif hasattr(obj, 'tolist'): # Numpy arrays
469
+ return obj.tolist()
470
+ return obj
471
+
472
+ # Ensure result is JSON serializable
473
+ clean_result = convert_numpy(result)
474
+
475
+ return JSONResponse(clean_result)
476
+
477
+ except Exception as e:
478
+ print(f"Prediction Error: {e}") # Log error to console
479
+ raise HTTPException(status_code=500, detail=str(e))
480
+
481
+
482
+ @app.post("/predict/single", response_class=HTMLResponse)
483
+ async def predict_single_form(request: Request):
484
+ """Handle single prediction from form (HTML response)"""
485
+ try:
486
+ form_data = await request.form()
487
+
488
+ # Build feature dictionary
489
+ features = {}
490
+ for col in FEATURE_COLUMNS:
491
+ value = form_data.get(col, "0")
492
+ try:
493
+ features[col] = int(value) if value else 0
494
+ except ValueError:
495
+ features[col] = 0
496
+
497
+ # Make prediction
498
+ result = predict_single(features)
499
+
500
+ return templates.TemplateResponse(
501
+ request,
502
+ "single_predict.html",
503
+ {
504
+ "title": "Prediction Result",
505
+ "features": FEATURE_COLUMNS,
506
+ "feature_info": FEATURE_INFO,
507
+ "result": result,
508
+ "input_values": features,
509
+ "github_url": GITHUB_URL,
510
+ "dagshub_url": DAGSHUB_URL,
511
+ "linkedin_url": LINKEDIN_URL
512
+ }
513
+ )
514
+
515
+ except Exception as e:
516
+ raise HTTPException(status_code=500, detail=str(e))
517
+
518
+
519
+ @app.get("/download/results/{filename}")
520
+ async def download_results(filename: str):
521
+ """Download prediction results"""
522
+ file_path = f"prediction_output/{filename}"
523
+ if os.path.exists(file_path):
524
+ return FileResponse(
525
+ file_path,
526
+ media_type="text/csv",
527
+ filename=filename
528
+ )
529
+ raise HTTPException(status_code=404, detail="File not found")
530
+
531
+
532
+ @app.post("/api/reload-model")
533
+ async def reload_model():
534
+ """Force reload of the model and metrics"""
535
+ global model, preprocessor
536
+ try:
537
+ model, preprocessor = load_models()
538
+ get_latest_metrics()
539
+
540
+ status = "success" if model is not None else "failed"
541
+ return {
542
+ "status": status,
543
+ "message": "Model reload attempted",
544
+ "model_loaded": model is not None,
545
+ "metrics_updated": True
546
+ }
547
+ except Exception as e:
548
+ raise HTTPException(status_code=500, detail=str(e))
549
+
550
+
551
+ @app.post("/api/train")
552
+ async def train_model():
553
+ """Trigger model training"""
554
+ try:
555
+ pipeline = TrainingPipeline()
556
+ pipeline.run_pipeline()
557
+
558
+ # Reload model and metrics
559
+ global model, preprocessor
560
+ model, preprocessor = load_models()
561
+ get_latest_metrics()
562
+
563
+ return {
564
+ "status": "success",
565
+ "message": "Training completed successfully"
566
+ }
567
+ except Exception as e:
568
+ import traceback
569
+ traceback.print_exc()
570
+ print(f"Training Error: {e}", file=sys.stderr)
571
+ raise HTTPException(status_code=500, detail=str(e))
572
+
573
+
574
+ # ============================================================
575
+ # Error Handlers
576
+ # ============================================================
577
+
578
+ @app.exception_handler(404)
579
+ async def not_found_handler(request: Request, exc):
580
+ return templates.TemplateResponse(
581
+ request,
582
+ "index.html",
583
+ {
584
+ "title": APP_TITLE,
585
+ "error": "Page not found",
586
+ "github_url": GITHUB_URL,
587
+ "dagshub_url": DAGSHUB_URL,
588
+ "linkedin_url": LINKEDIN_URL,
589
+ "metrics": MODEL_METRICS,
590
+ "all_models": ALL_MODELS,
591
+ "feature_count": len(FEATURE_COLUMNS),
592
+ "features": FEATURE_COLUMNS,
593
+ "feature_info": FEATURE_INFO
594
+ },
595
+ status_code=404
596
+ )
597
+
598
+
599
+ # ============================================================
600
+ # Run Server
601
+ # ============================================================
602
+
603
+ if __name__ == "__main__":
604
+ uvicorn.run(
605
+ "app:app",
606
+ host="0.0.0.0",
607
+ port=8000,
608
+ reload=True
609
+ )
data_schema/schema.yaml ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ columns:
2
+ - having_IP_Address: int64
3
+ - URL_Length: int64
4
+ - Shortining_Service: int64
5
+ - having_At_Symbol: int64
6
+ - double_slash_redirecting: int64
7
+ - Prefix_Suffix: int64
8
+ - having_Sub_Domain: int64
9
+ - SSLfinal_State: int64
10
+ - Domain_registeration_length: int64
11
+ - Favicon: int64
12
+ - port: int64
13
+ - HTTPS_token: int64
14
+ - Request_URL: int64
15
+ - URL_of_Anchor: int64
16
+ - Links_in_tags: int64
17
+ - SFH: int64
18
+ - Submitting_to_email: int64
19
+ - Abnormal_URL: int64
20
+ - Redirect: int64
21
+ - on_mouseover: int64
22
+ - RightClick: int64
23
+ - popUpWidnow: int64
24
+ - Iframe: int64
25
+ - age_of_domain: int64
26
+ - DNSRecord: int64
27
+ - web_traffic: int64
28
+ - Page_Rank: int64
29
+ - Google_Index: int64
30
+ - Links_pointing_to_page: int64
31
+ - Statistical_report: int64
32
+ - Result: int64
33
+
34
+
35
+ numerical_columns:
36
+ - having_IP_Address
37
+ - URL_Length
38
+ - Shortining_Service
39
+ - having_At_Symbol
40
+ - double_slash_redirecting
41
+ - Prefix_Suffix
42
+ - having_Sub_Domain
43
+ - SSLfinal_State
44
+ - Domain_registeration_length
45
+ - Favicon
46
+ - port
47
+ - HTTPS_token
48
+ - Request_URL
49
+ - URL_of_Anchor
50
+ - Links_in_tags
51
+ - SFH
52
+ - Submitting_to_email
53
+ - Abnormal_URL
54
+ - Redirect
55
+ - on_mouseover
56
+ - RightClick
57
+ - popUpWidnow
58
+ - Iframe
59
+ - age_of_domain
60
+ - DNSRecord
61
+ - web_traffic
62
+ - Page_Rank
63
+ - Google_Index
64
+ - Links_pointing_to_page
65
+ - Statistical_report
66
+ - Result
main.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from networksecurity.components.data_ingestion import DataIngestion
2
+ from networksecurity.components.data_validation import DataValidation
3
+ from networksecurity.components.data_transformation import DataTransformation
4
+ from networksecurity.components.model_trainer import ModelTrainer,ModelTrainerConfig
5
+
6
+ from networksecurity.exception.exception import NetworkSecurityException
7
+ from networksecurity.logging.logger import logging
8
+ from networksecurity.entity.config_entity import DataIngestionConfig,DataValidationConfig,DataTransformationConfig
9
+ from networksecurity.entity.config_entity import TrainingPipelineConfig
10
+ import sys
11
+
12
+ if __name__ == "__main__":
13
+ try:
14
+ traningpipelineconfig=TrainingPipelineConfig()
15
+ dataingestionconfig=DataIngestionConfig(traningpipelineconfig)
16
+ data_ingestion=DataIngestion(dataingestionconfig)
17
+ logging.info("Initiate the data ingestion")
18
+ dataingestionartifact=data_ingestion.initiate_data_ingestion()
19
+ logging.info(f"Data ingestion completed {dataingestionartifact}")
20
+ print(dataingestionartifact)
21
+ data_validation_config=DataValidationConfig(traningpipelineconfig)
22
+ data_validation=DataValidation(dataingestionartifact,data_validation_config)
23
+ logging.info("Initiate the data validation")
24
+ data_validation_artifact=data_validation.initiate_data_validation()
25
+ logging.info(f"Data validation completed {data_validation_artifact}")
26
+ print(data_validation_artifact)
27
+ data_transformation_config=DataTransformationConfig(traningpipelineconfig)
28
+ data_transformation=DataTransformation(data_transformation_config,data_validation_artifact)
29
+ logging.info("Initiate the data transformation")
30
+ data_transformation_artifact=data_transformation.initiate_data_transformation()
31
+ logging.info(f"Data transformation completed {data_transformation_artifact}")
32
+ print(data_transformation_artifact)
33
+
34
+ logging.info("Model Trainer Started")
35
+ model_trainer_config=ModelTrainerConfig(traningpipelineconfig)
36
+ model_trainer=ModelTrainer(model_trainer_config=model_trainer_config,
37
+ data_transformation_artifact=data_transformation_artifact)
38
+ model_trainer_artifact=model_trainer.initiate_model_trainer()
39
+ logging.info(f"Model Trainer completed {model_trainer_artifact}")
40
+
41
+ except Exception as e:
42
+ raise NetworkSecurityException(e, sys)
networksecurity/__init__.py ADDED
File without changes
networksecurity/cloud/__init__.py ADDED
File without changes
networksecurity/cloud/s3_syncer.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ class S3Sync:
4
+ def sync_folder_to_s3(self, folder, aws_bucket_url):
5
+ command = f"aws s3 sync {folder} {aws_bucket_url} "
6
+ os.system(command)
7
+
8
+ def sync_folder_from_s3(self, folder, aws_bucket_url):
9
+ command = f"aws s3 sync {aws_bucket_url} {folder} "
10
+ os.system(command)
networksecurity/components/__init__.py ADDED
File without changes
networksecurity/components/data_ingestion.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from networksecurity.exception.exception import NetworkSecurityException
2
+ from networksecurity.logging.logger import logging
3
+ import os
4
+ import sys
5
+ import numpy as np
6
+ import pandas as pd
7
+ from typing import List
8
+ import pymongo
9
+ from sklearn.model_selection import train_test_split
10
+
11
+ ## Configuration of the data ingestion config
12
+ from networksecurity.entity.config_entity import DataIngestionConfig
13
+ from networksecurity.entity.artifact_entity import DataIngestionArtifact
14
+
15
+ from dotenv import load_dotenv
16
+ load_dotenv()
17
+
18
+ MONGO_DB_URL = os.getenv("MONGO_DB_URL")
19
+
20
+ class DataIngestion:
21
+ def __init__(self, data_ingestion_config):
22
+ try:
23
+ self.data_ingestion_config = data_ingestion_config
24
+ except Exception as e:
25
+ raise NetworkSecurityException(e, sys)
26
+
27
+ def export_collection_as_dataframe(self):
28
+ """
29
+ Read data from mongodb OR fallback to CSV if MongoDB unavailable
30
+ """
31
+ try:
32
+ # Original MongoDB code
33
+ database_name = self.data_ingestion_config.database_name
34
+ collection_name = self.data_ingestion_config.collection_name
35
+ self.mongo_client = pymongo.MongoClient(MONGO_DB_URL)
36
+ collection = self.mongo_client[database_name][collection_name]
37
+
38
+ df = pd.DataFrame(list(collection.find()))
39
+ if "_id" in df.columns.to_list():
40
+ df = df.drop(columns=["_id"], axis = 1)
41
+ df.replace({"na":np.nan}, inplace=True)
42
+ return df
43
+
44
+ except Exception as e:
45
+ # FALLBACK: Use your test.csv
46
+ import logging
47
+ logging.info(f"MongoDB unavailable, using sample CSV: {str(e)}")
48
+ try:
49
+ # Construct absolute path relative to this script file
50
+ # Script is in networksecurity/components/data_ingestion.py
51
+ # Root is 2 levels up from current_dir (components)
52
+ current_dir = os.path.dirname(os.path.abspath(__file__))
53
+ root_dir = os.path.dirname(os.path.dirname(current_dir))
54
+ csv_path = os.path.join(root_dir, "Network_data", "phisingData.csv")
55
+
56
+ logging.info(f"MongoDB unavailable. Attempting to load CSV from: {csv_path}")
57
+ df = pd.read_csv(csv_path)
58
+ logging.info(f" Loaded {len(df)} rows from CSV")
59
+ return df
60
+ except FileNotFoundError:
61
+ raise NetworkSecurityException(f"Sample CSV not found at {csv_path}. CWD: {os.getcwd()}", sys)
62
+
63
+
64
+ def export_data_into_feature_store(self, dataframe: pd.DataFrame):
65
+ try:
66
+ feature_store_file_path = self.data_ingestion_config.feature_store_file_path
67
+ ## Creating Folder
68
+ dir_path = os.path.dirname(feature_store_file_path)
69
+ os.makedirs(dir_path,exist_ok=True)
70
+ dataframe.to_csv(feature_store_file_path, index=False, header=True)
71
+ return dataframe
72
+
73
+ except Exception as e:
74
+ raise NetworkSecurityException(e, sys)
75
+
76
+ def split_data_as_train_test(self, dataframe: pd.DataFrame):
77
+ try:
78
+ train_set, test_set = train_test_split(
79
+ dataframe, test_size=self.data_ingestion_config.train_test_split_ratio
80
+ )
81
+ logging.info("Performed train test split on the dataframe")
82
+
83
+ logging.info("Exited split_data_as_train_test method of Data_Ingestion class")
84
+
85
+ dir_path = os.path.dirname(self.data_ingestion_config.training_file_path)
86
+
87
+ os.makedirs(dir_path, exist_ok=True)
88
+
89
+ logging.info(f"Exporting train and test file path")
90
+
91
+ train_set.to_csv(
92
+ self.data_ingestion_config.training_file_path, index=False, header=True
93
+ )
94
+
95
+ test_set.to_csv(
96
+ self.data_ingestion_config.testing_file_path, index=False, header=True
97
+ )
98
+
99
+ logging.info(f"Exported train and test file path")
100
+
101
+ except Exception as e:
102
+ raise NetworkSecurityException(e, sys)
103
+
104
+ def initiate_data_ingestion(self):
105
+ try:
106
+ dataframe = self.export_collection_as_dataframe()
107
+ dataframe = self.export_data_into_feature_store(dataframe)
108
+ self.split_data_as_train_test(dataframe)
109
+ dataingestionartifact=DataIngestionArtifact(training_file_path=self.data_ingestion_config.training_file_path,
110
+ testing_file_path=self.data_ingestion_config.testing_file_path)
111
+ return dataingestionartifact
112
+
113
+
114
+ except Exception as e:
115
+ raise NetworkSecurityException(e, sys)
networksecurity/components/data_transformation.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os,sys
2
+ import numpy as np
3
+ import pandas as pd
4
+ from sklearn.impute import KNNImputer
5
+ from sklearn.pipeline import Pipeline
6
+ from networksecurity.constant.training_pipeline import TARGET_COLUMN, DATA_TRANSFORMATION_IMPUTER_PARAMS
7
+ from networksecurity.entity.artifact_entity import DataTransformationArtifact, DataValidationArtifact
8
+ from networksecurity.entity.config_entity import DataTransformationConfig
9
+ from networksecurity.exception.exception import NetworkSecurityException
10
+ from networksecurity.logging.logger import logging
11
+ from networksecurity.utils.main_utils.utils import save_numpy_array_data, save_object
12
+
13
+ class DataTransformation:
14
+ def __init__(self,
15
+ data_transformation_config: DataTransformationConfig,
16
+ data_validation_artifact: DataValidationArtifact):
17
+ try:
18
+ logging.info(f"{'>>'*20} Data Transformation {'<<'*20}")
19
+ self.data_transformation_config = data_transformation_config
20
+ self.data_validation_artifact = data_validation_artifact
21
+ except Exception as e:
22
+ raise NetworkSecurityException(e, sys)
23
+
24
+ @staticmethod
25
+ def read_data(file_path) -> pd.DataFrame:
26
+ try:
27
+ return pd.read_csv(file_path)
28
+ except Exception as e:
29
+ raise NetworkSecurityException(e, sys)
30
+
31
+ def get_data_transformer_object(cls)-> Pipeline:
32
+ """
33
+ It initializes the KNNImputer object with the parameters specfied in the training_pipeline.py file
34
+ and returns the pipeline object with the KNNImputer object as the first step.
35
+
36
+ Args:
37
+ cls: DataTransformation
38
+
39
+ Returns:
40
+ Pipeline: Pipeline object with the KNNImputer object as the first step.
41
+ """
42
+ logging.info("Entered the get_data_transformer_object method of Data_Transformation class")
43
+ try:
44
+ imputer = KNNImputer(**DATA_TRANSFORMATION_IMPUTER_PARAMS)
45
+ logging.info("Created KNNImputer object with the parameters specified in the training_pipeline.py file")
46
+ preprocessor = Pipeline(steps=[("imputer", imputer)])
47
+ return preprocessor
48
+ except Exception as e:
49
+ raise NetworkSecurityException(e, sys)
50
+
51
+ def initiate_data_transformation(self)->DataTransformationArtifact:
52
+ logging.info("Entered initiate_data_transformation method of DataTransformation class")
53
+ try:
54
+ logging.info("Starting data transformation")
55
+ train_df = DataTransformation.read_data(self.data_validation_artifact.valid_train_file_path)
56
+ test_df = DataTransformation.read_data(self.data_validation_artifact.valid_test_file_path)
57
+
58
+ ## Training dataframe
59
+ input_feature_train_df = train_df.drop(columns=[TARGET_COLUMN], axis=1)
60
+ target_feature_train_df = train_df[TARGET_COLUMN]
61
+ target_feature_train_df = target_feature_train_df.replace(-1, 0)
62
+
63
+ ## Testing dataframe
64
+ input_feature_test_df = test_df.drop(columns=[TARGET_COLUMN], axis=1)
65
+ target_feature_test_df = test_df[TARGET_COLUMN]
66
+ target_feature_test_df = target_feature_test_df.replace(-1, 0)
67
+
68
+ preprocessor = self.get_data_transformer_object()
69
+
70
+ preprocessor_object=preprocessor.fit(input_feature_train_df)
71
+ transformed_input_train_feature = preprocessor_object.transform(input_feature_train_df)
72
+ transformed_input_test_feature = preprocessor_object.transform(input_feature_test_df)
73
+
74
+ train_arr = np.c_[transformed_input_train_feature, np.array(target_feature_train_df)]
75
+ test_arr = np.c_[transformed_input_test_feature, np.array(target_feature_test_df)]
76
+
77
+ ## Save numpy array data and preprocessor object
78
+ save_numpy_array_data(
79
+ file_path=self.data_transformation_config.transformed_train_file_path,
80
+ array=train_arr
81
+ )
82
+ save_numpy_array_data(
83
+ file_path=self.data_transformation_config.transformed_test_file_path,
84
+ array=test_arr
85
+ )
86
+ save_object(
87
+ file_path=self.data_transformation_config.transformed_object_file_path,
88
+ obj=preprocessor_object
89
+ )
90
+
91
+ data_transformation_artifact = DataTransformationArtifact(
92
+ transformed_object_file_path=self.data_transformation_config.transformed_object_file_path,
93
+ transformed_train_file_path=self.data_transformation_config.transformed_train_file_path,
94
+ transformed_test_file_path=self.data_transformation_config.transformed_test_file_path,
95
+ )
96
+ return data_transformation_artifact
97
+ logging.info("Data transformation completed")
98
+ except Exception as e:
99
+ raise NetworkSecurityException(e, sys)
networksecurity/components/data_validation.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from networksecurity.entity.artifact_entity import DataIngestionArtifact, DataValidationArtifact
2
+ from networksecurity.entity.config_entity import DataValidationConfig
3
+ from networksecurity.exception.exception import NetworkSecurityException
4
+ from networksecurity.constant.training_pipeline import SCHEMA_FILE_PATH
5
+ from networksecurity.utils.main_utils.utils import read_yaml_file
6
+ from networksecurity.utils.main_utils.utils import write_yaml_file
7
+ from networksecurity.logging.logger import logging
8
+ from scipy.stats import ks_2samp
9
+ import pandas as pd
10
+ import os,sys
11
+
12
+ class DataValidation:
13
+ def __init__(self, data_ingestion_artifact: DataIngestionArtifact,
14
+ data_validation_config: DataValidationConfig):
15
+
16
+ try:
17
+ self.data_ingestion_artifact = data_ingestion_artifact
18
+ self.data_validation_config = data_validation_config
19
+ self._schema_config = read_yaml_file(SCHEMA_FILE_PATH)
20
+ except Exception as e:
21
+ raise NetworkSecurityException(e, sys)
22
+
23
+ @staticmethod
24
+ def read_data(file_path)->pd.DataFrame:
25
+ try:
26
+ return pd.read_csv(file_path)
27
+ except Exception as e:
28
+ raise NetworkSecurityException(e, sys)
29
+
30
+ def validate_number_of_columns(self, dataframe: pd.DataFrame)->bool:
31
+ try:
32
+ number_of_columns = len(self._schema_config)
33
+ logging.info(f"Required number of columns: {number_of_columns}")
34
+ logging.info(f"DataFrame columns count: {len(dataframe.columns)}")
35
+
36
+ if len(dataframe.columns)==number_of_columns:
37
+ return True
38
+ return False
39
+
40
+ except Exception as e:
41
+ raise NetworkSecurityException(e, sys)
42
+
43
+ def validate_number_of_numerical_columns(self, dataframe: pd.DataFrame) -> bool:
44
+ try:
45
+ # Required numerical columns from schema
46
+ required_numerical_columns = self._schema_config["numerical_columns"]
47
+ required_count = len(required_numerical_columns)
48
+
49
+ # Actual numerical columns in dataframe
50
+ numerical_df = dataframe.select_dtypes(include=["int64"])
51
+ actual_count = len(numerical_df.columns)
52
+
53
+ logging.info(f"Required number of numerical columns: {required_count}")
54
+ logging.info(f"Dataframe numerical columns count: {actual_count}")
55
+
56
+ if actual_count == required_count:
57
+ return True
58
+ return False
59
+
60
+ except Exception as e:
61
+ raise NetworkSecurityException(e, sys)
62
+
63
+ def detect_dataset_drift(self, base_df, current_df, threshold=0.01)-> bool:
64
+ try:
65
+ status = True
66
+ report={}
67
+ for column in base_df.columns:
68
+ d1 = base_df[column]
69
+ d2 = current_df[column]
70
+ is_same_dist=ks_2samp(d1, d2)
71
+ if threshold <=is_same_dist.pvalue:
72
+ is_found = False
73
+ else:
74
+ is_found = True
75
+ status = False
76
+ report.update({column:{
77
+ "p_value":float(is_same_dist.pvalue),
78
+ "drift_status":is_found
79
+ }})
80
+ drift_report_file_path = self.data_validation_config.drift_report_file_path
81
+ dir_path = os.path.dirname(drift_report_file_path)
82
+ os.makedirs(dir_path, exist_ok=True)
83
+ write_yaml_file(file_path=drift_report_file_path, content=report)
84
+
85
+
86
+ except Exception as e:
87
+ raise NetworkSecurityException(e, sys)
88
+
89
+ def initiate_data_validation(self)-> DataValidationArtifact:
90
+ try:
91
+ train_file_path = self.data_ingestion_artifact.training_file_path
92
+ test_file_path = self.data_ingestion_artifact.testing_file_path
93
+
94
+ ## Read data from train and test
95
+ train_dataframe = DataValidation.read_data(train_file_path)
96
+ test_dataframe = DataValidation.read_data(test_file_path)
97
+
98
+ ## Validate number of columns
99
+ status = self.validate_number_of_columns(dataframe=train_dataframe)
100
+ if not status:
101
+ error_message = f"Train dataframe does not contain all columns \n"
102
+ status = self.validate_number_of_columns(dataframe=test_dataframe)
103
+ if not status:
104
+ error_message = f"Test dataframe does not contain all columns \n"
105
+
106
+ ## Check datadrift
107
+ status=self.detect_dataset_drift(base_df=train_dataframe, current_df=test_dataframe)
108
+ dir_path = os.path.dirname(self.data_validation_config.valid_train_file_path)
109
+ os.makedirs(dir_path, exist_ok=True)
110
+
111
+ train_dataframe.to_csv(self.data_validation_config.valid_train_file_path, index=False, header=True)
112
+ test_dataframe.to_csv(self.data_validation_config.valid_test_file_path, index=False, header=True)
113
+
114
+ data_validation_artifact = DataValidationArtifact(
115
+ validation_status=status,
116
+ valid_train_file_path=self.data_validation_config.valid_train_file_path,
117
+ valid_test_file_path=self.data_validation_config.valid_test_file_path,
118
+ invalid_train_file_path=None,
119
+ invalid_test_file_path=None,
120
+ drift_report_file_path=self.data_validation_config.drift_report_file_path
121
+ )
122
+ return data_validation_artifact
123
+
124
+ except Exception as e:
125
+ raise NetworkSecurityException(e, sys)
networksecurity/components/model_trainer.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import mlflow
4
+ import dagshub
5
+ import matplotlib
6
+ matplotlib.use("Agg")
7
+
8
+ import matplotlib.pyplot as plt
9
+ import seaborn as sns
10
+
11
+ from networksecurity.exception.exception import NetworkSecurityException
12
+ from networksecurity.logging.logger import logging
13
+
14
+ from networksecurity.entity.config_entity import ModelTrainerConfig
15
+ from networksecurity.entity.artifact_entity import (
16
+ DataTransformationArtifact,
17
+ ModelTrainerArtifact,
18
+ )
19
+
20
+ from networksecurity.utils.main_utils.utils import (
21
+ save_object,
22
+ load_object,
23
+ load_numpy_array_data,
24
+ evaluate_models,
25
+ )
26
+
27
+ from networksecurity.utils.ml_utils.metric.classfication_metric import (
28
+ get_classification_score,
29
+ )
30
+
31
+ from sklearn.linear_model import LogisticRegression
32
+ from sklearn.tree import DecisionTreeClassifier
33
+ from sklearn.ensemble import (
34
+ RandomForestClassifier,
35
+ GradientBoostingClassifier,
36
+ AdaBoostClassifier,
37
+ )
38
+ from sklearn.metrics import (
39
+ confusion_matrix,
40
+ roc_curve,
41
+ precision_recall_curve,
42
+ )
43
+
44
+ import os
45
+
46
+ # ---------------- Dagshub + MLflow ----------------
47
+ if os.getenv("MLFLOW_TRACKING_URI"):
48
+ print("info: MLflow tracking URI is already set, skipping DagsHub init")
49
+ elif os.getenv("MLFLOW_TRACKING_USERNAME") and os.getenv("MLFLOW_TRACKING_PASSWORD"):
50
+ dagshub.init(repo_owner="Inder-26", repo_name="NetworkSecurity", mlflow=True)
51
+ else:
52
+ print("Warning: DagsHub credentials not found. Tracking might rely on local configs or fail.")
53
+
54
+
55
+
56
+ # ---------------- Helper: log visual artifacts ----------------
57
+ def log_classification_artifacts(y_true, y_pred, y_proba):
58
+ # Confusion Matrix
59
+ cm = confusion_matrix(y_true, y_pred)
60
+ plt.figure(figsize=(4, 4))
61
+ sns.heatmap(cm, annot=True, fmt="d", cmap="Blues")
62
+ plt.xlabel("Predicted")
63
+ plt.ylabel("Actual")
64
+ plt.title("Confusion Matrix")
65
+ plt.tight_layout()
66
+ plt.savefig("confusion_matrix.png")
67
+ mlflow.log_artifact("confusion_matrix.png")
68
+ plt.close()
69
+
70
+ # ROC Curve
71
+ fpr, tpr, _ = roc_curve(y_true, y_proba)
72
+ plt.figure()
73
+ plt.plot(fpr, tpr)
74
+ plt.plot([0, 1], [0, 1], "--")
75
+ plt.xlabel("False Positive Rate")
76
+ plt.ylabel("True Positive Rate")
77
+ plt.title("ROC Curve")
78
+ plt.tight_layout()
79
+ plt.savefig("roc_curve.png")
80
+ mlflow.log_artifact("roc_curve.png")
81
+ plt.close()
82
+
83
+ # Precision-Recall Curve
84
+ precision, recall, _ = precision_recall_curve(y_true, y_proba)
85
+ plt.figure()
86
+ plt.plot(recall, precision)
87
+ plt.xlabel("Recall")
88
+ plt.ylabel("Precision")
89
+ plt.title("Precision-Recall Curve")
90
+ plt.tight_layout()
91
+ plt.savefig("precision_recall_curve.png")
92
+ mlflow.log_artifact("precision_recall_curve.png")
93
+ plt.close()
94
+
95
+
96
+ # ---------------- Model Trainer ----------------
97
+ class ModelTrainer:
98
+ def __init__(
99
+ self,
100
+ model_trainer_config: ModelTrainerConfig,
101
+ data_transformation_artifact: DataTransformationArtifact,
102
+ ):
103
+ try:
104
+ logging.info(f"{'>>'*20} Model Trainer {'<<'*20}")
105
+ self.model_trainer_config = model_trainer_config
106
+ self.data_transformation_artifact = data_transformation_artifact
107
+ except Exception as e:
108
+ raise NetworkSecurityException(e, sys)
109
+
110
+ def train_model(self, X_train, X_test, y_train, y_test):
111
+
112
+ models = {
113
+ "Logistic Regression": LogisticRegression(),
114
+ "Decision Tree": DecisionTreeClassifier(),
115
+ "Random Forest": RandomForestClassifier(),
116
+ "Gradient Boosting": GradientBoostingClassifier(),
117
+ "AdaBoost": AdaBoostClassifier(),
118
+ }
119
+
120
+ # ---------- MLflow logging ----------
121
+ best_f1 = -1
122
+ best_model = None
123
+ best_model_name = None
124
+ best_run_id = None
125
+
126
+
127
+ for model_name, model in models.items():
128
+
129
+ with mlflow.start_run(run_name=model_name) as run:
130
+
131
+ model.fit(X_train, y_train)
132
+
133
+ y_train_pred = model.predict(X_train)
134
+ y_test_pred = model.predict(X_test)
135
+ y_test_proba = model.predict_proba(X_test)[:, 1]
136
+
137
+ train_metric = get_classification_score(y_train, y_train_pred)
138
+ test_metric = get_classification_score(y_test, y_test_pred)
139
+
140
+ # Params & tags
141
+ mlflow.log_params(model.get_params())
142
+ mlflow.set_tag("model_name", model_name)
143
+ mlflow.set_tag("stage", "experiment")
144
+
145
+ # Metrics (decision metric = test_f1)
146
+ mlflow.log_metric("train_f1", train_metric.f1_score)
147
+ mlflow.log_metric("test_f1", test_metric.f1_score)
148
+ mlflow.log_metric("train_precision", train_metric.precision_score)
149
+ mlflow.log_metric("test_precision", test_metric.precision_score)
150
+ mlflow.log_metric("train_recall", train_metric.recall_score)
151
+ mlflow.log_metric("test_recall", test_metric.recall_score)
152
+
153
+ # Visual evaluation (artifacts)
154
+ log_classification_artifacts(
155
+ y_true=y_test,
156
+ y_pred=y_test_pred,
157
+ y_proba=y_test_proba,
158
+ )
159
+
160
+ if test_metric.f1_score > best_f1:
161
+ best_f1 = test_metric.f1_score
162
+ best_model = model
163
+ best_model_name = model_name
164
+ best_run_id = run.info.run_id
165
+
166
+
167
+ logging.info(
168
+ f"Best Model: {best_model_name} | "
169
+ f"Test F1: {best_f1}"
170
+ )
171
+
172
+
173
+ with mlflow.start_run(run_id=best_run_id):
174
+ mlflow.set_tag("best_model", "true")
175
+
176
+ # ---------- Save final model for deployment ----------
177
+ preprocessor = load_object(
178
+ self.data_transformation_artifact.transformed_object_file_path
179
+ )
180
+
181
+ final_model_dir = os.path.join(os.getcwd(), "final_model")
182
+ os.makedirs(final_model_dir, exist_ok=True)
183
+
184
+ save_object(
185
+ os.path.join(final_model_dir, "model.pkl"),
186
+ best_model,
187
+ )
188
+ save_object(
189
+ os.path.join(final_model_dir, "preprocessor.pkl"),
190
+ preprocessor,
191
+ )
192
+
193
+ logging.info(f"Final model and preprocessor saved in final_model")
194
+ y_train_pred = best_model.predict(X_train)
195
+ y_test_pred = best_model.predict(X_test)
196
+
197
+ best_train_metric = get_classification_score(y_train, y_train_pred)
198
+ best_test_metric = get_classification_score(y_test, y_test_pred)
199
+
200
+ return ModelTrainerArtifact(
201
+ trained_model_file_path=os.path.join(final_model_dir, "model.pkl"),
202
+ train_metric_artifact=best_train_metric,
203
+ test_metric_artifact=best_test_metric,
204
+ )
205
+
206
+
207
+ def initiate_model_trainer(self) -> ModelTrainerArtifact:
208
+ try:
209
+ train_array = load_numpy_array_data(
210
+ self.data_transformation_artifact.transformed_train_file_path
211
+ )
212
+ test_array = load_numpy_array_data(
213
+ self.data_transformation_artifact.transformed_test_file_path
214
+ )
215
+
216
+ X_train, y_train = train_array[:, :-1], train_array[:, -1]
217
+ X_test, y_test = test_array[:, :-1], test_array[:, -1]
218
+
219
+ return self.train_model(X_train, X_test, y_train, y_test)
220
+
221
+ except Exception as e:
222
+ raise NetworkSecurityException(e, sys)
networksecurity/constant/__init__.py ADDED
File without changes
networksecurity/constant/training_pipeline/__init__.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import numpy as np
4
+ import pandas as pd
5
+
6
+ """
7
+ Define all the constant variables for training pipeline
8
+ """
9
+ TARGET_COLUMN = "Result"
10
+ PIPELINE_NAME: str = "NetworkSecurity"
11
+ ARTIFACT_DIR: str = "Artifact"
12
+ FILE_NAME: str = "phisingkData.csv"
13
+
14
+ TRAIN_FILE_NAME: str = "train.csv"
15
+ TEST_FILE_NAME: str = "test.csv"
16
+
17
+ SCHEMA_FILE_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))), "data_schema", "schema.yaml")
18
+
19
+ SAVED_MODEL_DIR_NAME = os.path.join("saved_models")
20
+ MODEL_FILE_NAME: str = "model.pkl"
21
+
22
+ """
23
+ Data Ingestion realted constant start with DATA_INGESTION VAR NAME
24
+ """
25
+
26
+ DATA_INGESTION_COLLECTION_NAME: str = "NetworkData"
27
+ DATA_INGESTION_DATABASE_NAME: str = "Inderjeet"
28
+ DATA_INGESTION_DIR_NAME: str = "data_ingestion"
29
+ DATA_INGESTION_FEATURE_STORE_DIR: str = "feature_store"
30
+ DATA_INGESTION_INGESTED_DIR: str = "ingested"
31
+ DATA_INGESTION_TRAIN_TEST_SPLIT_RATION: float = 0.2
32
+
33
+
34
+ """
35
+ Data Validation related constant start with DATA_VALIDATION VAR NAME
36
+ """
37
+ DATA_VALIDATION_DIR_NAME: str ="data_validation"
38
+ DATA_VALIDATION_VALID_DIR: str ="validated"
39
+ DATA_VALIDATION_INVALID_DIR: str ="invalid"
40
+ DATA_VALIDATION_DRIFT_REPORT_DIR: str ="drift_report"
41
+ DATA_VALIDATION_DRIFT_REPORT_FILE_NAME: str ="report.yaml"
42
+
43
+ """
44
+ Data Transformation related constant start with DATA_TRANSFORMATION VAR NAME
45
+ """
46
+ DATA_TRANSFORMATION_DIR_NAME: str ="data_transformation"
47
+ DATA_TRANSFORMATION_TRANSFORMED_DATA_DIR: str ="transformed"
48
+ DATA_TRANSFORMATION_TRANSFORMED_OBJECT_DIR: str ="transformed_object"
49
+ DATA_TRANSFORMATION_IMPUTER_PARAMS: dict = {
50
+ "missing_values": np.nan,
51
+ "n_neighbors": 3,
52
+ "weights": "uniform",
53
+ }
54
+ DATA_TRANSFORMATION_TRAIN_FILE_PATH: str = "train.npy"
55
+ DATA_TRANSFORMATION_TEST_FILE_PATH: str = "test.npy"
56
+ PREPROCESSING_OBJECT_FILE_NAME: str = "preprocessing_object.pkl"
57
+
58
+ """
59
+ Model trainer related constanst with MODEL TRAINER VAR NAME
60
+ """
61
+
62
+ MODEL_TRAINER_DIR_NAME: str = "model_trainer"
63
+ MODEL_TRAINER_TRAINED_MODEL_DIR: str = "trained_model"
64
+ MODEL_TRAINER_TRAINED_MODEL_NAME: str = "model.pkl"
65
+ MODEL_TRAINER_EXPECTED_SCORE: float = 0.6
66
+ MODEL_TRAINER_OVER_FITTING_UNDER_FITTING_THRESHOLD: float = 0.05
67
+
68
+ TRAINING_BUCKET_NAME = "awsnetworksecuritybucket"
networksecurity/entity/__init__.py ADDED
File without changes
networksecurity/entity/artifact_entity.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+
3
+ @dataclass
4
+ class DataIngestionArtifact:
5
+ training_file_path:str
6
+ testing_file_path:str
7
+
8
+ @dataclass
9
+ class DataValidationArtifact:
10
+ validation_status: bool
11
+ valid_train_file_path: str
12
+ valid_test_file_path: str
13
+ invalid_train_file_path: str
14
+ invalid_test_file_path: str
15
+ drift_report_file_path: str
16
+
17
+ @dataclass
18
+ class DataTransformationArtifact:
19
+ transformed_train_file_path: str
20
+ transformed_test_file_path: str
21
+ transformed_object_file_path: str
22
+
23
+ @dataclass
24
+ class ClassificationMetricArtifact:
25
+ f1_score: float
26
+ precision_score: float
27
+ recall_score: float
28
+
29
+ @dataclass
30
+ class ModelTrainerArtifact:
31
+ trained_model_file_path: str
32
+ train_metric_artifact: ClassificationMetricArtifact
33
+ test_metric_artifact: ClassificationMetricArtifact
34
+
35
+ @dataclass
36
+ class ModelTrainerConfig:
37
+ model_trainer_dir: str
38
+ trained_model_file_path: str
networksecurity/entity/config_entity.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ import os
3
+ from networksecurity.constant import training_pipeline
4
+
5
+ print(training_pipeline.PIPELINE_NAME)
6
+ print(training_pipeline.ARTIFACT_DIR)
7
+
8
+
9
+ class TrainingPipelineConfig:
10
+ def __init__(self,timestamp=datetime.now()):
11
+ timestamp=timestamp.strftime("%m_%d_%Y_%H_M_%S")
12
+ self.pipeline_name = training_pipeline.PIPELINE_NAME
13
+ self.artifact_name = training_pipeline.ARTIFACT_DIR
14
+ self.artifact_dir = os.path.join(self.artifact_name,timestamp)
15
+ self.model_dir = os.path.join("final_model")
16
+ self.timestamp: str = timestamp
17
+
18
+ class DataIngestionConfig:
19
+ def __init__(self,training_pipeline_config: TrainingPipelineConfig):
20
+ self.data_ingestion_dir:str = os.path.join(
21
+ training_pipeline_config.artifact_dir,training_pipeline.DATA_INGESTION_DIR_NAME
22
+ )
23
+ self.feature_store_file_path: str = os.path.join(
24
+ self.data_ingestion_dir, training_pipeline.DATA_INGESTION_FEATURE_STORE_DIR, training_pipeline.FILE_NAME
25
+ )
26
+ self.training_file_path: str = os.path.join(
27
+ self.data_ingestion_dir, training_pipeline.DATA_INGESTION_INGESTED_DIR, training_pipeline.TRAIN_FILE_NAME
28
+ )
29
+ self.testing_file_path: str = os.path.join(
30
+ self.data_ingestion_dir, training_pipeline.DATA_INGESTION_INGESTED_DIR, training_pipeline.TEST_FILE_NAME
31
+ )
32
+ self.train_test_split_ratio: float = training_pipeline.DATA_INGESTION_TRAIN_TEST_SPLIT_RATION
33
+ self.collection_name: str = training_pipeline.DATA_INGESTION_COLLECTION_NAME
34
+ self.database_name: str = training_pipeline.DATA_INGESTION_DATABASE_NAME
35
+
36
+
37
+ class DataValidationConfig:
38
+ def __init__(self, training_pipeline_config: TrainingPipelineConfig):
39
+ # Main data validation directory
40
+ self.data_validation_dir: str = os.path.join(
41
+ training_pipeline_config.artifact_dir,
42
+ training_pipeline.DATA_VALIDATION_DIR_NAME
43
+ )
44
+
45
+ # Valid data directory
46
+ self.valid_data_dir: str = os.path.join(
47
+ self.data_validation_dir,
48
+ training_pipeline.DATA_VALIDATION_VALID_DIR
49
+ )
50
+
51
+ # Invalid data directory
52
+ self.invalid_data_dir: str = os.path.join(
53
+ self.data_validation_dir,
54
+ training_pipeline.DATA_VALIDATION_INVALID_DIR
55
+ )
56
+
57
+ # Valid train file path
58
+ self.valid_train_file_path: str = os.path.join(
59
+ self.valid_data_dir,
60
+ training_pipeline.TRAIN_FILE_NAME
61
+ )
62
+
63
+ # Valid test file path
64
+ self.valid_test_file_path: str = os.path.join(
65
+ self.valid_data_dir,
66
+ training_pipeline.TEST_FILE_NAME
67
+ )
68
+
69
+ # Invalid train file path
70
+ self.invalid_train_file_path: str = os.path.join(
71
+ self.invalid_data_dir,
72
+ training_pipeline.TRAIN_FILE_NAME
73
+ )
74
+
75
+ # Invalid test file path
76
+ self.invalid_test_file_path: str = os.path.join(
77
+ self.invalid_data_dir,
78
+ training_pipeline.TEST_FILE_NAME
79
+ )
80
+
81
+ # Drift report file path
82
+ self.drift_report_file_path: str = os.path.join(
83
+ self.data_validation_dir,
84
+ training_pipeline.DATA_VALIDATION_DRIFT_REPORT_DIR,
85
+ training_pipeline.DATA_VALIDATION_DRIFT_REPORT_FILE_NAME,
86
+ )
87
+
88
+ class DataTransformationConfig:
89
+ def __init__(self, training_pipeline_config: TrainingPipelineConfig):
90
+ self.data_transformation_dir: str = os.path.join(
91
+ training_pipeline_config.artifact_dir,
92
+ training_pipeline.DATA_TRANSFORMATION_DIR_NAME
93
+ )
94
+
95
+ self.transformed_train_file_path: str = os.path.join(
96
+ self.data_transformation_dir,
97
+ training_pipeline.DATA_TRANSFORMATION_TRANSFORMED_DATA_DIR,
98
+ training_pipeline.TRAIN_FILE_NAME.replace("csv", "npy")
99
+ )
100
+
101
+ self.transformed_test_file_path: str = os.path.join(
102
+ self.data_transformation_dir,
103
+ training_pipeline.DATA_TRANSFORMATION_TRANSFORMED_DATA_DIR,
104
+ training_pipeline.TEST_FILE_NAME.replace("csv", "npy")
105
+ )
106
+
107
+ self.transformed_object_file_path: str = os.path.join(
108
+ self.data_transformation_dir,
109
+ training_pipeline.DATA_TRANSFORMATION_TRANSFORMED_OBJECT_DIR,
110
+ training_pipeline.PREPROCESSING_OBJECT_FILE_NAME
111
+ )
112
+
113
+ class ModelTrainerConfig:
114
+ def __init__(self, training_pipeline_config: TrainingPipelineConfig):
115
+ self.model_trainer_dir: str = os.path.join(
116
+ training_pipeline_config.artifact_dir, training_pipeline.MODEL_TRAINER_DIR_NAME
117
+ )
118
+ self.trained_model_file_path: str = os.path.join(
119
+ self.model_trainer_dir, training_pipeline.MODEL_TRAINER_TRAINED_MODEL_DIR,
120
+ training_pipeline.MODEL_FILE_NAME
121
+ )
122
+ self.expected_accuracy: float = training_pipeline.MODEL_TRAINER_EXPECTED_SCORE
123
+ self.overfitting_underfitting_threshold = training_pipeline.MODEL_TRAINER_OVER_FITTING_UNDER_FITTING_THRESHOLD
networksecurity/exception/__init__.py ADDED
File without changes
networksecurity/exception/exception.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from networksecurity.logging import logger
3
+ class NetworkSecurityException(Exception):
4
+ def __init__(self, error_message, error_details:sys):
5
+ self.error_messge = error_message
6
+ _,_,exc_tb = error_details.exc_info()
7
+
8
+ self.lineno = exc_tb.tb_lineno
9
+ self.file_name = exc_tb.tb_frame.f_code.co_filename
10
+
11
+ def __str__(self):
12
+ return "Error occured in python script name [{0}] line number [{1}] error message [{2}]".format(
13
+ self.file_name, self.lineno, str(self.error_messge))
14
+
15
+ if __name__ == "__main__":
16
+ try:
17
+ logger.logging.info("try block chal gaya")
18
+ a=1/0
19
+ print("Chal gaya toh print nahi hona chahiye")
20
+ except Exception as e:
21
+ raise NetworkSecurityException(e, sys)
networksecurity/logging/__init__.py ADDED
File without changes
networksecurity/logging/logger.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ from datetime import datetime
4
+
5
+ LOG_FILE=f"{datetime.now().strftime('%m_%d_%Y_%H_%M_%S')}.log"
6
+
7
+ logs_path=os.path.join(os.getcwd(),"logs",LOG_FILE)
8
+ os.makedirs(logs_path,exist_ok=True)
9
+
10
+ LOG_FLE_PATH=os.path.join(logs_path,LOG_FILE)
11
+
12
+ logging.basicConfig(
13
+ filename=LOG_FLE_PATH,
14
+ format="[ %(asctime)s ] %(lineno)d %(name)s - %(levelname)s - %(message)s",
15
+ level=logging.INFO,
16
+ )
networksecurity/pipeline/__init__.py ADDED
File without changes
networksecurity/pipeline/batch_prediction.py ADDED
File without changes
networksecurity/pipeline/training_pipeline.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, sys
2
+ from networksecurity.exception.exception import NetworkSecurityException
3
+ from networksecurity.logging.logger import logging
4
+
5
+ from networksecurity.components.data_ingestion import DataIngestion
6
+ from networksecurity.components.data_validation import DataValidation
7
+ from networksecurity.components.data_transformation import DataTransformation
8
+ from networksecurity.components.model_trainer import ModelTrainer
9
+ from networksecurity.constant.training_pipeline import TRAINING_BUCKET_NAME
10
+ from networksecurity.cloud.s3_syncer import S3Sync
11
+
12
+ from networksecurity.entity.config_entity import (
13
+ TrainingPipelineConfig,
14
+ DataIngestionConfig,
15
+ DataValidationConfig,
16
+ DataTransformationConfig,
17
+ ModelTrainerConfig,
18
+ )
19
+
20
+ from networksecurity.entity.artifact_entity import (
21
+ DataIngestionArtifact,
22
+ DataValidationArtifact,
23
+ DataTransformationArtifact,
24
+ ModelTrainerArtifact,
25
+ )
26
+
27
+ class TrainingPipeline:
28
+ def __init__(self):
29
+ try:
30
+ self.training_pipeline_config = TrainingPipelineConfig()
31
+ self.s3_sync = S3Sync()
32
+ except Exception as e:
33
+ raise NetworkSecurityException(e, sys)
34
+
35
+ def start_data_ingestion(self):
36
+ try:
37
+ logging.info("Starting data ingestion")
38
+ self.data_ingestion_config = DataIngestionConfig(
39
+ training_pipeline_config=self.training_pipeline_config
40
+ )
41
+ data_ingestion = DataIngestion(
42
+ data_ingestion_config=self.data_ingestion_config
43
+ )
44
+ data_ingestion_artifact = data_ingestion.initiate_data_ingestion()
45
+ logging.info(f"Data ingestion completed and artifact {data_ingestion_artifact}")
46
+ return data_ingestion_artifact
47
+ except Exception as e:
48
+ raise NetworkSecurityException(e, sys)
49
+
50
+ def start_data_validation(self, data_ingestion_artifact: DataIngestionArtifact):
51
+ try:
52
+ logging.info("Starting data validation")
53
+ self.data_validation_config = DataValidationConfig(
54
+ training_pipeline_config=self.training_pipeline_config
55
+ )
56
+ data_validation = DataValidation(
57
+ data_validation_config=self.data_validation_config,
58
+ data_ingestion_artifact=data_ingestion_artifact
59
+ )
60
+ data_validation_artifact = data_validation.initiate_data_validation()
61
+ logging.info(f"Data validation completed and artifact {data_validation_artifact}")
62
+ return data_validation_artifact
63
+ except Exception as e:
64
+ raise NetworkSecurityException(e, sys)
65
+
66
+ def start_data_transformation(self, data_validation_artifact: DataValidationArtifact):
67
+ try:
68
+ logging.info("Starting data transformation")
69
+ self.data_transformation_config = DataTransformationConfig(
70
+ training_pipeline_config=self.training_pipeline_config
71
+ )
72
+ data_transformation = DataTransformation(
73
+ data_transformation_config=self.data_transformation_config,
74
+ data_validation_artifact=data_validation_artifact
75
+ )
76
+ data_transformation_artifact = data_transformation.initiate_data_transformation()
77
+ logging.info(f"Data transformation completed and artifact {data_transformation_artifact}")
78
+ return data_transformation_artifact
79
+ except Exception as e:
80
+ raise NetworkSecurityException(e, sys)
81
+
82
+ def start_model_trainer(self, data_transformation_artifact: DataTransformationArtifact) -> ModelTrainerArtifact:
83
+ try:
84
+ logging.info("Starting model trainer")
85
+ self.model_trainer_config = ModelTrainerConfig(
86
+ training_pipeline_config=self.training_pipeline_config
87
+ )
88
+ model_trainer = ModelTrainer(
89
+ model_trainer_config=self.model_trainer_config,
90
+ data_transformation_artifact=data_transformation_artifact
91
+ )
92
+ model_trainer_artifact = model_trainer.initiate_model_trainer()
93
+ logging.info(f"Model trainer completed and artifact {model_trainer_artifact}")
94
+ return model_trainer_artifact
95
+ except Exception as e:
96
+ raise NetworkSecurityException(e, sys)
97
+
98
+ ## Local artifact is pushed to S3
99
+ def sync_artifact_dir_to_s3(self):
100
+ try:
101
+ aws_bucket_url = (
102
+ f"s3://{TRAINING_BUCKET_NAME}/artifact/"
103
+ f"{self.training_pipeline_config.timestamp}"
104
+ )
105
+
106
+ self.s3_sync.sync_folder_to_s3(
107
+ folder=self.training_pipeline_config.artifact_dir,
108
+ aws_bucket_url=aws_bucket_url
109
+ )
110
+ except Exception as e:
111
+ raise NetworkSecurityException(e, sys)
112
+
113
+
114
+ ## Local final_model is pushed to S3
115
+ def sync_saved_model_dir_to_s3(self):
116
+ try:
117
+ aws_bucket_url = (
118
+ f"s3://{TRAINING_BUCKET_NAME}/final_model/"
119
+ f"{self.training_pipeline_config.timestamp}"
120
+ )
121
+
122
+ self.s3_sync.sync_folder_to_s3(
123
+ folder=self.training_pipeline_config.model_dir,
124
+ aws_bucket_url=aws_bucket_url
125
+ )
126
+ except Exception as e:
127
+ raise NetworkSecurityException(e, sys)
128
+
129
+
130
+ def run_pipeline(self):
131
+ try:
132
+ data_ingestion_artifact = self.start_data_ingestion()
133
+ data_validation_artifact = self.start_data_validation(data_ingestion_artifact=data_ingestion_artifact)
134
+ data_transformation_artifact = self.start_data_transformation(data_validation_artifact=data_validation_artifact)
135
+ model_trainer_artifact = self.start_model_trainer(data_transformation_artifact=data_transformation_artifact)
136
+ logging.info("Training pipeline completed successfully")
137
+
138
+ # self.sync_artifact_dir_to_s3()
139
+ # self.sync_saved_model_dir_to_s3()
140
+
141
+ return model_trainer_artifact
142
+ except Exception as e:
143
+ raise NetworkSecurityException(e, sys)
networksecurity/utils/__init__.py ADDED
File without changes
networksecurity/utils/main_utils/__init__.py ADDED
File without changes
networksecurity/utils/main_utils/utils.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sklearn.metrics import r2_score
2
+ from sklearn.model_selection import GridSearchCV
3
+ import yaml
4
+ from networksecurity.exception.exception import NetworkSecurityException
5
+ from networksecurity.logging.logger import logging
6
+ import os,sys
7
+ import numpy as np
8
+ import dill
9
+ import pickle
10
+
11
+ def read_yaml_file(file_path: str) -> dict:
12
+ """
13
+ Reads a YAML file and returns its contents as a dictionary.
14
+
15
+ Args:
16
+ file_path (str): The path to the YAML file.
17
+ Returns:
18
+ dict: The contents of the YAML file.
19
+ """
20
+ try:
21
+ with open(file_path, 'rb') as yaml_file:
22
+ return yaml.safe_load(yaml_file)
23
+ except Exception as e:
24
+ raise NetworkSecurityException(e, sys)
25
+
26
+ def write_yaml_file(file_path: str, content: object, replace: bool = False) -> None:
27
+ try:
28
+ if replace:
29
+ if os.path.exists(file_path):
30
+ os.remove(file_path)
31
+ os.makedirs(os.path.dirname(file_path), exist_ok=True)
32
+ with open(file_path, 'w') as file:
33
+ yaml.dump(content, file)
34
+ except Exception as e:
35
+ raise NetworkSecurityException(e, sys)
36
+
37
+ def save_numpy_array_data(file_path: str, array: np.array):
38
+ """
39
+ Save numpy array data to file
40
+ file_path : str : file path to save the numpy array
41
+ array : np.array : numpy array data to be saved
42
+ """
43
+ try:
44
+ dir_path = os.path.dirname(file_path)
45
+ os.makedirs(dir_path, exist_ok=True)
46
+ with open(file_path, 'wb') as file_obj:
47
+ np.save(file_obj, array)
48
+ except Exception as e:
49
+ raise NetworkSecurityException(e, sys)
50
+
51
+ def save_object(file_path: str, obj: object) -> None:
52
+ try:
53
+ logging.info("Entered the save_object method of Main Utils")
54
+ os.makedirs(os.path.dirname(file_path), exist_ok=True)
55
+ with open(file_path, 'wb') as file_obj:
56
+ pickle.dump(obj, file_obj)
57
+ logging.info("Exited the save_object method of Main Utils")
58
+ except Exception as e:
59
+ raise NetworkSecurityException(e, sys)
60
+
61
+ def load_object(file_path: str) -> object:
62
+ try:
63
+ if not os.path.exists(file_path):
64
+ raise Exception(f"The file: {file_path} does not exist")
65
+ with open(file_path, 'rb') as file_obj:
66
+ print(file_obj)
67
+ return pickle.load(file_obj)
68
+ except Exception as e:
69
+ raise NetworkSecurityException(e, sys)
70
+
71
+ def load_numpy_array_data(file_path: str) -> np.array:
72
+ """
73
+ Load numpy array data from file
74
+ file_path : str : file path to load the numpy array
75
+ return : np.array : numpy array data loaded
76
+ """
77
+ try:
78
+ with open(file_path, 'rb') as file_obj:
79
+ return np.load(file_obj)
80
+ except Exception as e:
81
+ raise NetworkSecurityException(e, sys)
82
+
83
+ def evaluate_models(X_train, y_train, X_test, y_test, models: dict, params: dict) -> dict:
84
+ """
85
+ Evaluate multiple machine learning models and return their performance scores.
86
+
87
+ Args:
88
+ X_train: Training feature data.
89
+ y_train: Training target data.
90
+ X_test: Testing feature data.
91
+ y_test: Testing target data.
92
+ models (dict): A dictionary of model names and their corresponding model instances.
93
+ params (dict): A dictionary of model names and their corresponding hyperparameter grids.
94
+ Returns:
95
+ dict: A dictionary containing model names and their corresponding performance scores.
96
+ """
97
+ try:
98
+ report = {}
99
+ for i in range(len(list(models))):
100
+ model = list(models.values())[i]
101
+ param = params[list(models.keys())[i]]
102
+
103
+ gs = GridSearchCV(model, param, cv=3)
104
+ gs.fit(X_train, y_train)
105
+
106
+ model.set_params(**gs.best_params_)
107
+ model.fit(X_train, y_train)
108
+
109
+ y_train_pred = model.predict(X_train)
110
+ y_test_pred = model.predict(X_test)
111
+ train_model_score = r2_score(y_train, y_train_pred)
112
+ test_model_score = r2_score(y_test, y_test_pred)
113
+ report[list(models.keys())[i]] = test_model_score
114
+ return report
115
+
116
+ except Exception as e:
117
+ raise NetworkSecurityException(e, sys)
networksecurity/utils/ml_utils/__init__.py ADDED
File without changes
networksecurity/utils/ml_utils/metric/__init.py ADDED
File without changes
networksecurity/utils/ml_utils/metric/classfication_metric.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from networksecurity.entity.artifact_entity import ClassificationMetricArtifact
2
+ from networksecurity.exception.exception import NetworkSecurityException
3
+ from sklearn.metrics import precision_score, recall_score, f1_score
4
+ import sys
5
+
6
+ def get_classification_score(y_true, y_pred) -> ClassificationMetricArtifact:
7
+ try:
8
+ model_f1_score = f1_score(y_true, y_pred)
9
+ model_precision_score = precision_score(y_true, y_pred)
10
+ model_recall_score = recall_score(y_true, y_pred)
11
+
12
+ classification_metric= ClassificationMetricArtifact(
13
+ f1_score=model_f1_score,
14
+ precision_score=model_precision_score,
15
+ recall_score=model_recall_score
16
+ )
17
+ return classification_metric
18
+ except Exception as e:
19
+ raise NetworkSecurityException(e, sys)
networksecurity/utils/ml_utils/model/__init__.py ADDED
File without changes
networksecurity/utils/ml_utils/model/estimator.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from networksecurity.exception.exception import NetworkSecurityException
2
+ import sys,os
3
+ from networksecurity.constant.training_pipeline import SAVED_MODEL_DIR_NAME,MODEL_FILE_NAME
4
+ from networksecurity.logging.logger import logging
5
+
6
+ class NetworkModel:
7
+ def __init__(self,preprocessor,model):
8
+ """
9
+ Initialize the NetworkModel with preprocessor and model.
10
+
11
+ Args:
12
+ preprocessor: The preprocessing object.
13
+ model: The trained model.
14
+ """
15
+ try:
16
+ self.preprocessor = preprocessor
17
+ self.model = model
18
+ except Exception as e:
19
+ raise NetworkSecurityException(e, sys)
20
+
21
+ def predict(self, X):
22
+ """
23
+ Make predictions using the preprocessor and model.
24
+
25
+ Args:
26
+ X: The input data for prediction.
27
+ Returns:
28
+ The predictions made by the model.
29
+ """
30
+ try:
31
+ X_transform = self.preprocessor.transform(X)
32
+ y_hat = self.model.predict(X_transform)
33
+ return y_hat
34
+ except Exception as e:
35
+ raise NetworkSecurityException(e, sys)
push_data.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import json
4
+
5
+ from dotenv import load_dotenv
6
+ load_dotenv()
7
+
8
+ MONGO_DB_URL=os.getenv("MONGO_DB_URL")
9
+ #print(MONGO_DB_URL)
10
+
11
+ import certifi
12
+ ca=certifi.where()
13
+
14
+ import pandas as pd
15
+ import numpy as np
16
+ import pymongo
17
+ from networksecurity.exception.exception import NetworkSecurityException
18
+ from networksecurity.logging.logger import logging
19
+
20
+ class NeworkDataExtract():
21
+ def __init__(self):
22
+ try:
23
+ pass
24
+ except Exception as e:
25
+ raise NetworkSecurityException(e,sys)
26
+
27
+ def csv_to_json_converter(self,file_path):
28
+ try:
29
+ data=pd.read_csv(file_path)
30
+ data.reset_index(drop=True,inplace=True)
31
+ records=list(json.loads(data.T.to_json()).values())
32
+ return records
33
+ except Exception as e:
34
+ raise NetworkSecurityException(e,sys)
35
+
36
+ def inser_data_mongodb(self, records, database, collection):
37
+ try:
38
+ self.database = database
39
+ self.collection = collection
40
+ self.records = records
41
+
42
+ self.mongo_client = pymongo.MongoClient(MONGO_DB_URL)
43
+ self.database = self.mongo_client[self.database]
44
+
45
+ self.collection = self.database[self.collection]
46
+ self.collection.insert_many(self.records)
47
+ return (len(self.records))
48
+ except Exception as e:
49
+ raise NetworkSecurityException(e, sys)
50
+
51
+ if __name__ == "__main__":
52
+ FILE_PATH = "Network_data\phisingData.csv"
53
+ DATABASE = "Inderjeet"
54
+ Collection = "NetworkData"
55
+ networkobj = NeworkDataExtract()
56
+ records = networkobj.csv_to_json_converter(file_path=FILE_PATH)
57
+ print("Hogaye records load")
58
+ #print(records)
59
+ no_of_records = networkobj.inser_data_mongodb(records, DATABASE, Collection)
60
+ print(no_of_records)
61
+
requirements.txt ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ numpy
2
+ pandas
3
+ scikit-learn
4
+ matplotlib
5
+ seaborn
6
+ fastapi
7
+ uvicorn
8
+ pymongo
9
+ python-dotenv
10
+ mlflow
11
+ dagshub
12
+ requests
13
+ boto3
14
+ botocore
15
+ dill
16
+ joblib
17
+ flask
18
+ flask-cors
19
+ jinja2
20
+ markupsafe
21
+ itsdangerous
22
+ werkzeug
23
+ click
24
+ pytest
25
+ python-multipart
setup.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ The setup.py file is a build script for setuptools, used to package and distribute Python projects.
3
+ It typically contains metadata about the project, such as its name, version, author, and dependencies, as well as instructions on how to install the package.
4
+ '''
5
+ from setuptools import setup, find_packages
6
+ from typing import List
7
+
8
+ def get_requirements()-> List[str]:
9
+ requirement_lst=[]
10
+ """Reads the requirements.txt file and returns a list of dependencies."""
11
+ try:
12
+ with open('requirements.txt','r') as file:
13
+ lines=file.readlines()
14
+ for line in lines:
15
+ requirement=line.strip()
16
+ if requirement and requirement != '-e .':
17
+ requirement_lst.append(requirement)
18
+ except FileNotFoundError:
19
+ print("requirement.txt file not found")
20
+
21
+ return requirement_lst
22
+
23
+ setup(
24
+ name="Network Security",
25
+ version="0.0.1",
26
+ author="Inderjeet Singh",
27
+ packages=find_packages(),
28
+ install_requires=get_requirements()
29
+ )
static/css/style.css ADDED
@@ -0,0 +1,1456 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ============================================
2
+ Design System & Variables
3
+ ============================================ */
4
+
5
+ :root {
6
+ /* Colors */
7
+ --primary: #4f46e5; /* Indigo 600 */
8
+ --primary-dark: #4338ca;
9
+ --primary-light: #818cf8;
10
+
11
+ --secondary: #ec4899; /* Pink 500 */
12
+
13
+ --gray-50: #f9fafb;
14
+ --gray-100: #f3f4f6;
15
+ --gray-200: #e5e7eb;
16
+ --gray-300: #d1d5db;
17
+ --gray-400: #9ca3af;
18
+ --gray-500: #6b7280;
19
+ --gray-600: #4b5563;
20
+ --gray-700: #374151;
21
+ --gray-800: #1f2937;
22
+ --gray-900: #111827;
23
+
24
+ --white: #ffffff;
25
+
26
+ --success: #10b981; /* Emerald 500 */
27
+ --danger: #ef4444; /* Red 500 */
28
+ --warning: #f59e0b; /* Amber 500 */
29
+ --info: #3b82f6; /* Blue 500 */
30
+
31
+ /* Typography */
32
+ --font-sans: "Inter", system-ui, -apple-system, sans-serif;
33
+
34
+ /* Spacing & Layout */
35
+ --container-width: 1200px;
36
+ --header-height: 70px;
37
+
38
+ /* Effects */
39
+ --radius: 0.5rem;
40
+ --radius-lg: 1rem;
41
+ --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
42
+ --shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1),
43
+ 0 2px 4px -1px rgba(0, 0, 0, 0.06);
44
+ --shadow-md: 0 10px 15px -3px rgba(0, 0, 0, 0.1),
45
+ 0 4px 6px -2px rgba(0, 0, 0, 0.05);
46
+ --shadow-lg: 0 20px 25px -5px rgba(0, 0, 0, 0.1),
47
+ 0 10px 10px -5px rgba(0, 0, 0, 0.04);
48
+
49
+ --transition: all 0.3s ease;
50
+ }
51
+
52
+ /* ============================================
53
+ Reset & Base
54
+ ============================================ */
55
+
56
+ * {
57
+ margin: 0;
58
+ padding: 0;
59
+ box-sizing: border-box;
60
+ }
61
+
62
+ body {
63
+ font-family: var(--font-sans);
64
+ background-color: var(--gray-50);
65
+ color: var(--gray-800);
66
+ line-height: 1.6;
67
+ min-height: 100vh;
68
+ display: flex;
69
+ flex-direction: column;
70
+ }
71
+
72
+ h1,
73
+ h2,
74
+ h3,
75
+ h4,
76
+ h5,
77
+ h6 {
78
+ line-height: 1.2;
79
+ color: var(--gray-900);
80
+ }
81
+
82
+ a {
83
+ text-decoration: none;
84
+ color: inherit;
85
+ transition: var(--transition);
86
+ }
87
+
88
+ ul {
89
+ list-style: none;
90
+ }
91
+
92
+ /* ============================================
93
+ Layout
94
+ ============================================ */
95
+
96
+ .container {
97
+ max-width: var(--container-width);
98
+ margin: 0 auto;
99
+ padding: 0 1.5rem;
100
+ }
101
+
102
+ .main-content {
103
+ flex: 1;
104
+ padding: 3rem 0;
105
+ }
106
+
107
+ /* Header */
108
+ .header {
109
+ height: var(--header-height);
110
+ background: var(--white);
111
+ border-bottom: 1px solid var(--gray-200);
112
+ position: sticky;
113
+ top: 0;
114
+ z-index: 100;
115
+ }
116
+
117
+ .header-content {
118
+ display: flex;
119
+ align-items: center;
120
+ justify-content: space-between;
121
+ height: 100%;
122
+ }
123
+
124
+ .logo {
125
+ display: flex;
126
+ align-items: center;
127
+ gap: 0.75rem;
128
+ font-size: 1.25rem;
129
+ font-weight: 700;
130
+ color: var(--primary);
131
+ }
132
+
133
+ .logo i {
134
+ font-size: 1.5rem;
135
+ }
136
+
137
+ .nav-links {
138
+ display: flex;
139
+ gap: 2rem;
140
+ }
141
+
142
+ .nav-link {
143
+ display: flex;
144
+ align-items: center;
145
+ gap: 0.5rem;
146
+ color: var(--gray-600);
147
+ font-weight: 500;
148
+ font-size: 0.95rem;
149
+ }
150
+
151
+ .nav-link:hover {
152
+ color: var(--primary);
153
+ }
154
+
155
+ /* Footer */
156
+ .footer {
157
+ background: var(--white);
158
+ border-top: 1px solid var(--gray-200);
159
+ padding: 2rem 0;
160
+ margin-top: auto;
161
+ }
162
+
163
+ .footer-content {
164
+ display: flex;
165
+ justify-content: space-between;
166
+ align-items: center;
167
+ }
168
+
169
+ .footer-logo {
170
+ display: flex;
171
+ align-items: center;
172
+ gap: 0.5rem;
173
+ font-weight: 600;
174
+ margin-bottom: 0.5rem;
175
+ }
176
+
177
+ .footer-left p {
178
+ color: var(--gray-500);
179
+ font-size: 0.9rem;
180
+ }
181
+
182
+ .footer-tech {
183
+ display: flex;
184
+ gap: 1rem;
185
+ margin-top: 0.5rem;
186
+ }
187
+
188
+ .footer-tech span {
189
+ display: flex;
190
+ align-items: center;
191
+ gap: 0.25rem;
192
+ font-size: 0.8rem;
193
+ color: var(--gray-500);
194
+ background: var(--gray-100);
195
+ padding: 0.1rem 0.5rem;
196
+ border-radius: 999px;
197
+ }
198
+
199
+ .footer-right {
200
+ display: flex;
201
+ gap: 1.5rem;
202
+ font-size: 1.25rem;
203
+ color: var(--gray-400);
204
+ }
205
+
206
+ .footer-right a:hover {
207
+ color: var(--primary);
208
+ transform: translateY(-2px);
209
+ }
210
+
211
+ /* ============================================
212
+ Components
213
+ ============================================ */
214
+
215
+ /* Buttons */
216
+ .btn {
217
+ display: inline-flex;
218
+ align-items: center;
219
+ justify-content: center;
220
+ gap: 0.5rem;
221
+ padding: 0.75rem 1.5rem;
222
+ border-radius: var(--radius);
223
+ font-weight: 600;
224
+ cursor: pointer;
225
+ border: none;
226
+ transition: var(--transition);
227
+ }
228
+
229
+ .btn-sm {
230
+ padding: 0.4rem 0.8rem;
231
+ font-size: 0.875rem;
232
+ }
233
+
234
+ .btn-lg {
235
+ padding: 1rem 2rem;
236
+ font-size: 1.125rem;
237
+ }
238
+
239
+ .btn-block {
240
+ width: 100%;
241
+ }
242
+
243
+ .btn-primary {
244
+ background: var(--primary);
245
+ color: white;
246
+ box-shadow: 0 4px 6px -1px rgba(79, 70, 229, 0.4);
247
+ }
248
+
249
+ .btn-primary:hover {
250
+ background: var(--primary-dark);
251
+ transform: translateY(-2px);
252
+ box-shadow: 0 6px 8px -1px rgba(79, 70, 229, 0.5);
253
+ }
254
+
255
+ .btn-outline {
256
+ background: transparent;
257
+ border: 2px solid var(--primary);
258
+ color: var(--primary);
259
+ }
260
+
261
+ .btn-outline:hover {
262
+ background: var(--gray-50);
263
+ transform: translateY(-1px);
264
+ }
265
+
266
+ .btn-secondary {
267
+ background: var(--secondary);
268
+ color: white;
269
+ }
270
+
271
+ /* Cards */
272
+ .card {
273
+ background: var(--white);
274
+ border-radius: var(--radius-lg);
275
+ border: 1px solid var(--gray-200);
276
+ box-shadow: var(--shadow-sm);
277
+ transition: var(--transition);
278
+ height: 100%;
279
+ margin-bottom: 2rem;
280
+ }
281
+
282
+ .card:hover {
283
+ box-shadow: var(--shadow-md);
284
+ transform: translateY(-2px);
285
+ }
286
+
287
+ .card-header {
288
+ padding: 1.5rem;
289
+ border-bottom: 1px solid var(--gray-100);
290
+ display: flex;
291
+ align-items: center;
292
+ justify-content: space-between;
293
+ }
294
+
295
+ .card-header h2 {
296
+ font-size: 1.25rem;
297
+ font-weight: 600;
298
+ margin: 0;
299
+ display: flex;
300
+ align-items: center;
301
+ gap: 0.75rem;
302
+ }
303
+
304
+ .card-body {
305
+ padding: 1.5rem;
306
+ }
307
+
308
+ /* Forms */
309
+ .form-group {
310
+ margin-bottom: 1.5rem;
311
+ }
312
+
313
+ .form-label {
314
+ display: block;
315
+ font-weight: 600;
316
+ margin-bottom: 0.5rem;
317
+ color: var(--gray-700);
318
+ }
319
+
320
+ .form-control {
321
+ width: 100%;
322
+ padding: 0.75rem;
323
+ border: 1px solid var(--gray-300);
324
+ border-radius: var(--radius);
325
+ transition: var(--transition);
326
+ font-family: inherit;
327
+ }
328
+
329
+ .form-control:focus {
330
+ outline: none;
331
+ border-color: var(--primary);
332
+ box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
333
+ }
334
+
335
+ /* ============================================
336
+ Page Specific: Home
337
+ ============================================ */
338
+
339
+ /* Hero */
340
+ .hero {
341
+ background: radial-gradient(circle at top right, #e0e7ff, #f3f4f6);
342
+ padding: 5rem 0;
343
+ text-align: center;
344
+ }
345
+
346
+ .hero-content {
347
+ max-width: 800px;
348
+ margin: 0 auto;
349
+ }
350
+
351
+ .hero-badge {
352
+ display: inline-flex;
353
+ align-items: center;
354
+ gap: 0.5rem;
355
+ background: white;
356
+ padding: 0.5rem 1rem;
357
+ border-radius: 9999px;
358
+ font-size: 0.875rem;
359
+ font-weight: 600;
360
+ color: var(--primary);
361
+ box-shadow: var(--shadow-sm);
362
+ margin-bottom: 1.5rem;
363
+ }
364
+
365
+ .hero h1 {
366
+ font-size: 3.5rem;
367
+ font-weight: 800;
368
+ letter-spacing: -0.025em;
369
+ margin-bottom: 1.5rem;
370
+ background: linear-gradient(135deg, var(--gray-900) 50%, var(--primary));
371
+ -webkit-background-clip: text;
372
+ background-clip: text;
373
+ -webkit-text-fill-color: transparent;
374
+ }
375
+
376
+ .hero-subtitle {
377
+ font-size: 1.25rem;
378
+ color: var(--gray-600);
379
+ margin-bottom: 3rem;
380
+ line-height: 1.6;
381
+ }
382
+
383
+ .hero-stats {
384
+ display: grid;
385
+ grid-template-columns: repeat(4, 1fr);
386
+ gap: 1.5rem;
387
+ }
388
+
389
+ .stat-card {
390
+ background: white;
391
+ padding: 1.5rem;
392
+ border-radius: var(--radius-lg);
393
+ box-shadow: var(--shadow);
394
+ display: flex;
395
+ flex-direction: column;
396
+ align-items: center;
397
+ gap: 0.5rem;
398
+ }
399
+
400
+ .stat-icon {
401
+ font-size: 1.5rem;
402
+ color: var(--primary);
403
+ margin-bottom: 0.25rem;
404
+ }
405
+
406
+ .stat-value {
407
+ font-size: 1.5rem;
408
+ font-weight: 700;
409
+ color: var(--gray-900);
410
+ }
411
+
412
+ .stat-label {
413
+ font-size: 0.875rem;
414
+ color: var(--gray-500);
415
+ }
416
+
417
+ /* Upload Interface */
418
+ .upload-zone {
419
+ border: 2px dashed var(--gray-300);
420
+ border-radius: var(--radius-lg);
421
+ padding: 3rem 1.5rem;
422
+ background: var(--gray-50);
423
+ transition: var(--transition);
424
+ cursor: pointer;
425
+ position: relative;
426
+ margin-bottom: 1.5rem;
427
+ }
428
+
429
+ .upload-zone:hover,
430
+ .upload-zone.dragover {
431
+ border-color: var(--primary);
432
+ background: #eef2ff;
433
+ }
434
+
435
+ .upload-content {
436
+ display: flex;
437
+ flex-direction: column;
438
+ align-items: center;
439
+ gap: 0.75rem;
440
+ color: var(--gray-500);
441
+ }
442
+
443
+ .upload-content i {
444
+ font-size: 3rem;
445
+ color: var(--gray-400);
446
+ margin-bottom: 0.5rem;
447
+ }
448
+
449
+ .upload-content p {
450
+ font-weight: 600;
451
+ color: var(--gray-800);
452
+ margin: 0;
453
+ }
454
+
455
+ #file-input {
456
+ position: absolute;
457
+ width: 100%;
458
+ height: 100%;
459
+ top: 0;
460
+ left: 0;
461
+ opacity: 0;
462
+ cursor: pointer;
463
+ }
464
+
465
+ .file-info {
466
+ display: none;
467
+ align-items: center;
468
+ padding: 1rem;
469
+ background: #eff6ff;
470
+ border: 1px solid #bfdbfe;
471
+ border-radius: var(--radius);
472
+ color: #1e40af;
473
+ margin-bottom: 1.5rem;
474
+ }
475
+
476
+ .file-info i {
477
+ font-size: 1.5rem;
478
+ margin-right: 0.75rem;
479
+ }
480
+
481
+ .btn-remove {
482
+ margin-left: auto;
483
+ background: none;
484
+ border: none;
485
+ color: #60a5fa;
486
+ cursor: pointer;
487
+ padding: 0.25rem;
488
+ }
489
+
490
+ .btn-remove:hover {
491
+ color: #1d4ed8;
492
+ }
493
+
494
+ /* Features List */
495
+ .features-grid {
496
+ display: grid;
497
+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
498
+ gap: 2rem;
499
+ }
500
+
501
+ .feature-group h4 {
502
+ display: flex;
503
+ align-items: center;
504
+ gap: 0.5rem;
505
+ font-size: 1rem;
506
+ margin-bottom: 1rem;
507
+ color: var(--gray-700);
508
+ padding-bottom: 0.5rem;
509
+ border-bottom: 1px solid var(--gray-200);
510
+ }
511
+
512
+ .feature-group ul {
513
+ display: flex;
514
+ flex-direction: column;
515
+ gap: 0.5rem;
516
+ }
517
+
518
+ .feature-group li {
519
+ font-size: 0.875rem;
520
+ color: var(--gray-600);
521
+ display: flex;
522
+ align-items: center;
523
+ }
524
+
525
+ .feature-group li::before {
526
+ content: "•";
527
+ color: var(--primary);
528
+ margin-right: 0.5rem;
529
+ }
530
+
531
+ .feature-group code {
532
+ background: var(--gray-100);
533
+ padding: 0.1rem 0.3rem;
534
+ border-radius: 4px;
535
+ font-size: 0.8em;
536
+ color: var(--gray-800);
537
+ }
538
+
539
+ .feature-note {
540
+ background: #fffbeb;
541
+ border: 1px solid #fde68a;
542
+ border-radius: var(--radius);
543
+ padding: 1rem;
544
+ margin-top: 2rem;
545
+ display: flex;
546
+ align-items: center;
547
+ gap: 0.75rem;
548
+ color: #92400e;
549
+ font-size: 0.9rem;
550
+ }
551
+
552
+ /* ============================================
553
+ Rest of the file (Result Cards, Tables)
554
+ ============================================ */
555
+ /* ... (Appending the previous file content here in the tool calling) ... */
556
+
557
+ /* [PREVIOUSLY EXISTING STYLES BELOW] */
558
+
559
+ /* ============================================
560
+ Manual Input Page
561
+ ============================================ */
562
+
563
+ .manual-page .page-header {
564
+ text-align: center;
565
+ margin-bottom: 2rem;
566
+ }
567
+
568
+ .manual-page .page-header h1 {
569
+ font-size: 2rem;
570
+ color: var(--gray-900);
571
+ margin-bottom: 0.5rem;
572
+ }
573
+
574
+ .manual-page .page-header p {
575
+ color: var(--gray-600);
576
+ }
577
+
578
+ /* Result Card */
579
+ .result-card {
580
+ display: flex;
581
+ align-items: center;
582
+ gap: 1.5rem;
583
+ padding: 1.5rem 2rem;
584
+ border-radius: var(--radius-lg);
585
+ margin-bottom: 2rem;
586
+ animation: slideDown 0.3s ease;
587
+ }
588
+
589
+ .result-card.result-safe {
590
+ background: linear-gradient(135deg, #d1fae5, #a7f3d0);
591
+ border: 2px solid var(--success);
592
+ }
593
+
594
+ .result-card.result-danger {
595
+ background: linear-gradient(135deg, #fee2e2, #fecaca);
596
+ border: 2px solid var(--danger);
597
+ }
598
+
599
+ .result-icon {
600
+ font-size: 3rem;
601
+ }
602
+
603
+ .result-safe .result-icon {
604
+ color: var(--success);
605
+ }
606
+ .result-danger .result-icon {
607
+ color: var(--danger);
608
+ }
609
+
610
+ .result-content h2 {
611
+ font-size: 1.5rem;
612
+ margin-bottom: 0.25rem;
613
+ }
614
+
615
+ .result-action {
616
+ margin-left: auto;
617
+ }
618
+
619
+ /* Quick Actions */
620
+ .quick-actions {
621
+ display: flex;
622
+ gap: 0.75rem;
623
+ margin-bottom: 2rem;
624
+ flex-wrap: wrap;
625
+ }
626
+
627
+ /* Feature Groups */
628
+ .feature-groups {
629
+ display: flex;
630
+ flex-direction: column;
631
+ gap: 1.5rem;
632
+ }
633
+
634
+ .feature-group-card {
635
+ background: var(--white);
636
+ border-radius: var(--radius-lg);
637
+ box-shadow: var(--shadow-md);
638
+ overflow: hidden;
639
+ }
640
+
641
+ .group-header {
642
+ display: flex;
643
+ align-items: center;
644
+ gap: 0.75rem;
645
+ padding: 1rem 1.5rem;
646
+ background: var(--gray-50);
647
+ border-bottom: 1px solid var(--gray-200);
648
+ }
649
+
650
+ .group-header i {
651
+ color: var(--primary);
652
+ font-size: 1.25rem;
653
+ }
654
+
655
+ .group-header h3 {
656
+ font-size: 1rem;
657
+ font-weight: 600;
658
+ color: var(--gray-800);
659
+ }
660
+
661
+ .inputs-grid {
662
+ display: grid;
663
+ grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
664
+ gap: 1rem;
665
+ padding: 1.5rem;
666
+ }
667
+
668
+ .input-item {
669
+ display: flex;
670
+ flex-direction: column;
671
+ gap: 0.5rem;
672
+ }
673
+
674
+ .input-item label {
675
+ font-size: 0.8rem;
676
+ font-weight: 600;
677
+ color: var(--gray-700);
678
+ font-family: monospace;
679
+ }
680
+
681
+ /* Radio Button Group */
682
+ .radio-group {
683
+ display: flex;
684
+ gap: 0.5rem;
685
+ }
686
+
687
+ .radio-label {
688
+ flex: 1;
689
+ }
690
+
691
+ .radio-label input {
692
+ display: none;
693
+ }
694
+
695
+ .radio-btn {
696
+ display: block;
697
+ padding: 0.5rem;
698
+ text-align: center;
699
+ border-radius: var(--radius);
700
+ font-weight: 600;
701
+ font-size: 0.875rem;
702
+ cursor: pointer;
703
+ transition: var(--transition);
704
+ border: 2px solid transparent;
705
+ }
706
+
707
+ .radio-btn.danger {
708
+ background: #fef2f2;
709
+ color: var(--danger);
710
+ border-color: #fecaca;
711
+ }
712
+
713
+ .radio-btn.warning {
714
+ background: #fffbeb;
715
+ color: var(--warning);
716
+ border-color: #fde68a;
717
+ }
718
+
719
+ .radio-btn.success {
720
+ background: #f0fdf4;
721
+ color: var(--success);
722
+ border-color: #bbf7d0;
723
+ }
724
+
725
+ .radio-label input:checked + .radio-btn.danger {
726
+ background: var(--danger);
727
+ color: white;
728
+ border-color: var(--danger);
729
+ }
730
+
731
+ .radio-label input:checked + .radio-btn.warning {
732
+ background: var(--warning);
733
+ color: white;
734
+ border-color: var(--warning);
735
+ }
736
+
737
+ .radio-label input:checked + .radio-btn.success {
738
+ background: var(--success);
739
+ color: white;
740
+ border-color: var(--success);
741
+ }
742
+
743
+ /* Form Actions */
744
+ .form-actions {
745
+ text-align: center;
746
+ margin-top: 2rem;
747
+ }
748
+
749
+ /* Legend */
750
+ .legend-card {
751
+ background: var(--gray-100);
752
+ border-radius: var(--radius-lg);
753
+ padding: 1.5rem;
754
+ margin-top: 2rem;
755
+ }
756
+
757
+ .legend-card h4 {
758
+ display: flex;
759
+ align-items: center;
760
+ gap: 0.5rem;
761
+ margin-bottom: 1rem;
762
+ color: var(--gray-700);
763
+ }
764
+
765
+ .legend-items {
766
+ display: flex;
767
+ gap: 2rem;
768
+ flex-wrap: wrap;
769
+ }
770
+
771
+ .legend-item {
772
+ display: flex;
773
+ align-items: center;
774
+ gap: 0.75rem;
775
+ }
776
+
777
+ .legend-badge {
778
+ padding: 0.25rem 0.75rem;
779
+ border-radius: var(--radius);
780
+ font-weight: 600;
781
+ font-size: 0.875rem;
782
+ }
783
+
784
+ .legend-badge.danger {
785
+ background: var(--danger);
786
+ color: white;
787
+ }
788
+ .legend-badge.warning {
789
+ background: var(--warning);
790
+ color: white;
791
+ }
792
+ .legend-badge.success {
793
+ background: var(--success);
794
+ color: white;
795
+ }
796
+
797
+ /* ============================================
798
+ Model Comparison Table
799
+ ============================================ */
800
+
801
+ .models-table-container {
802
+ overflow-x: auto;
803
+ }
804
+
805
+ .models-table {
806
+ width: 100%;
807
+ border-collapse: collapse;
808
+ }
809
+
810
+ .models-table th,
811
+ .models-table td {
812
+ padding: 1rem;
813
+ text-align: left;
814
+ border-bottom: 1px solid var(--gray-200);
815
+ }
816
+
817
+ .models-table th {
818
+ background: var(--gray-50);
819
+ font-weight: 600;
820
+ font-size: 0.75rem;
821
+ text-transform: uppercase;
822
+ letter-spacing: 0.05em;
823
+ color: var(--gray-600);
824
+ }
825
+
826
+ .models-table tr.best-model {
827
+ background: linear-gradient(90deg, rgba(16, 185, 129, 0.1), transparent);
828
+ }
829
+
830
+ .model-name {
831
+ display: flex;
832
+ align-items: center;
833
+ gap: 0.5rem;
834
+ font-weight: 600;
835
+ }
836
+
837
+ .trophy-icon {
838
+ color: #fbbf24;
839
+ }
840
+
841
+ .metric-bar {
842
+ position: relative;
843
+ height: 24px;
844
+ background: var(--gray-100);
845
+ border-radius: var(--radius);
846
+ overflow: hidden;
847
+ min-width: 100px;
848
+ }
849
+
850
+ .metric-fill {
851
+ position: absolute;
852
+ left: 0;
853
+ top: 0;
854
+ height: 100%;
855
+ background: var(--primary);
856
+ opacity: 0.2;
857
+ transition: width 0.5s ease;
858
+ }
859
+
860
+ .metric-fill.f1 {
861
+ background: var(--success);
862
+ }
863
+ .metric-fill.precision {
864
+ background: var(--info);
865
+ }
866
+ .metric-fill.recall {
867
+ background: var(--secondary);
868
+ }
869
+
870
+ .metric-bar span {
871
+ position: relative;
872
+ z-index: 1;
873
+ display: flex;
874
+ align-items: center;
875
+ height: 100%;
876
+ padding: 0 0.75rem;
877
+ font-weight: 600;
878
+ font-size: 0.8rem;
879
+ }
880
+
881
+ .badge {
882
+ display: inline-flex;
883
+ align-items: center;
884
+ gap: 0.25rem;
885
+ padding: 0.25rem 0.75rem;
886
+ border-radius: 9999px;
887
+ font-size: 0.75rem;
888
+ font-weight: 600;
889
+ }
890
+
891
+ .badge-success {
892
+ background: rgba(16, 185, 129, 0.1);
893
+ color: var(--success);
894
+ }
895
+
896
+ .badge-secondary {
897
+ background: var(--gray-100);
898
+ color: var(--gray-600);
899
+ }
900
+
901
+ /* ============================================
902
+ Pipeline Steps
903
+ ============================================ */
904
+
905
+ .pipeline-steps {
906
+ display: flex;
907
+ align-items: flex-start;
908
+ justify-content: space-between;
909
+ gap: 0.5rem;
910
+ flex-wrap: wrap;
911
+ }
912
+
913
+ .pipeline-step {
914
+ flex: 1;
915
+ min-width: 140px;
916
+ text-align: center;
917
+ padding: 1rem;
918
+ position: relative;
919
+ }
920
+
921
+ .step-number {
922
+ position: absolute;
923
+ top: 0;
924
+ right: 1rem;
925
+ width: 24px;
926
+ height: 24px;
927
+ background: var(--primary);
928
+ color: white;
929
+ border-radius: 50%;
930
+ display: flex;
931
+ align-items: center;
932
+ justify-content: center;
933
+ font-size: 0.75rem;
934
+ font-weight: 700;
935
+ }
936
+
937
+ .step-icon {
938
+ width: 60px;
939
+ height: 60px;
940
+ margin: 0 auto 1rem;
941
+ background: linear-gradient(135deg, var(--primary), var(--secondary));
942
+ border-radius: var(--radius-lg);
943
+ display: flex;
944
+ align-items: center;
945
+ justify-content: center;
946
+ color: white;
947
+ font-size: 1.5rem;
948
+ }
949
+
950
+ .pipeline-step h4 {
951
+ font-size: 0.9rem;
952
+ margin-bottom: 0.5rem;
953
+ color: var(--gray-800);
954
+ }
955
+
956
+ .pipeline-step p {
957
+ font-size: 0.75rem;
958
+ color: var(--gray-500);
959
+ }
960
+
961
+ .pipeline-arrow {
962
+ display: flex;
963
+ align-items: center;
964
+ color: var(--gray-300);
965
+ font-size: 1.5rem;
966
+ padding-top: 2rem;
967
+ }
968
+
969
+ @media (max-width: 768px) {
970
+ .pipeline-arrow {
971
+ display: none;
972
+ }
973
+
974
+ .pipeline-steps {
975
+ flex-direction: column;
976
+ }
977
+
978
+ .pipeline-step {
979
+ width: 100%;
980
+ }
981
+ }
982
+
983
+ /* ============================================
984
+ Prediction Options
985
+ ============================================ */
986
+
987
+ .prediction-options {
988
+ margin-bottom: 3rem;
989
+ }
990
+
991
+ .section-title {
992
+ display: flex;
993
+ align-items: center;
994
+ gap: 0.75rem;
995
+ font-size: 1.25rem;
996
+ margin-bottom: 1.5rem;
997
+ color: var(--gray-800);
998
+ }
999
+
1000
+ .section-title i {
1001
+ color: var(--primary);
1002
+ }
1003
+
1004
+ .options-grid {
1005
+ display: grid;
1006
+ grid-template-columns: repeat(2, 1fr);
1007
+ gap: 2rem;
1008
+ }
1009
+
1010
+ @media (max-width: 768px) {
1011
+ .options-grid {
1012
+ grid-template-columns: 1fr;
1013
+ }
1014
+ }
1015
+
1016
+ .upload-card,
1017
+ .manual-card,
1018
+ .train-card {
1019
+ padding: 2rem;
1020
+ text-align: center;
1021
+ }
1022
+
1023
+ .train-card {
1024
+ grid-column: 1 / -1;
1025
+ }
1026
+
1027
+ .card-icon {
1028
+ width: 80px;
1029
+ height: 80px;
1030
+ margin: 0 auto 1.5rem;
1031
+ background: linear-gradient(135deg, var(--primary), var(--secondary));
1032
+ border-radius: 50%;
1033
+ display: flex;
1034
+ align-items: center;
1035
+ justify-content: center;
1036
+ color: white;
1037
+ font-size: 2rem;
1038
+ }
1039
+
1040
+ .upload-card,
1041
+ .manual-card,
1042
+ .train-card {
1043
+ padding: 2rem;
1044
+ text-align: center;
1045
+ }
1046
+
1047
+ .upload-card h3,
1048
+ .manual-card h3,
1049
+ .train-card h3 {
1050
+ font-size: 1.25rem;
1051
+ margin-bottom: 0.5rem;
1052
+ color: var(--gray-800);
1053
+ }
1054
+
1055
+ .upload-card p,
1056
+ .manual-card p,
1057
+ .train-card p {
1058
+ color: var(--gray-500);
1059
+ margin-bottom: 1.5rem;
1060
+ }
1061
+
1062
+ .manual-preview {
1063
+ background: var(--gray-50);
1064
+ border-radius: var(--radius);
1065
+ padding: 1rem;
1066
+ margin-bottom: 1.5rem;
1067
+ text-align: left;
1068
+ }
1069
+
1070
+ .feature-preview {
1071
+ display: flex;
1072
+ justify-content: space-between;
1073
+ padding: 0.5rem 0;
1074
+ border-bottom: 1px solid var(--gray-200);
1075
+ }
1076
+
1077
+ .feature-name {
1078
+ font-family: monospace;
1079
+ font-size: 0.8rem;
1080
+ color: var(--gray-700);
1081
+ }
1082
+
1083
+ .feature-values {
1084
+ font-size: 0.75rem;
1085
+ color: var(--gray-500);
1086
+ }
1087
+
1088
+ .more-features {
1089
+ text-align: center;
1090
+ padding-top: 0.75rem;
1091
+ color: var(--primary);
1092
+ font-size: 0.875rem;
1093
+ font-weight: 500;
1094
+ }
1095
+
1096
+ .btn-secondary {
1097
+ background: var(--secondary);
1098
+ color: white;
1099
+ }
1100
+
1101
+ .btn-secondary:hover {
1102
+ background: #7c3aed;
1103
+ }
1104
+
1105
+ /* ============================================
1106
+ Animations
1107
+ ============================================ */
1108
+
1109
+ @keyframes slideDown {
1110
+ from {
1111
+ opacity: 0;
1112
+ transform: translateY(-20px);
1113
+ }
1114
+ to {
1115
+ opacity: 1;
1116
+ transform: translateY(0);
1117
+ }
1118
+ }
1119
+
1120
+ /* ============================================
1121
+ Notifications
1122
+ ============================================ */
1123
+ .notification {
1124
+ position: fixed;
1125
+ top: 20px;
1126
+ right: 20px;
1127
+ background: white;
1128
+ padding: 1rem 1.5rem;
1129
+ border-radius: var(--radius);
1130
+ box-shadow: var(--shadow-lg);
1131
+ display: flex;
1132
+ align-items: center;
1133
+ gap: 0.75rem;
1134
+ z-index: 1000;
1135
+ transform: translateX(120%);
1136
+ transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
1137
+ border-left: 4px solid var(--info);
1138
+ max-width: 400px;
1139
+ }
1140
+
1141
+ .notification.show {
1142
+ transform: translateX(0);
1143
+ }
1144
+
1145
+ .notification-success {
1146
+ border-left-color: var(--success);
1147
+ }
1148
+ .notification-success i {
1149
+ color: var(--success);
1150
+ }
1151
+
1152
+ .notification-error {
1153
+ border-left-color: var(--danger);
1154
+ }
1155
+ .notification-error i {
1156
+ color: var(--danger);
1157
+ }
1158
+
1159
+ .notification-info {
1160
+ border-left-color: var(--info);
1161
+ }
1162
+ .notification-info i {
1163
+ color: var(--info);
1164
+ }
1165
+
1166
+ /* ============================================
1167
+ Modal
1168
+ ============================================ */
1169
+ .modal-overlay {
1170
+ position: fixed;
1171
+ top: 0;
1172
+ left: 0;
1173
+ width: 100%;
1174
+ height: 100%;
1175
+ background: rgba(0, 0, 0, 0.5);
1176
+ backdrop-filter: blur(4px);
1177
+ display: flex;
1178
+ justify-content: center;
1179
+ align-items: center;
1180
+ z-index: 2000;
1181
+ opacity: 0;
1182
+ visibility: hidden;
1183
+ transition: all 0.3s ease;
1184
+ }
1185
+
1186
+ .modal-overlay.show {
1187
+ opacity: 1;
1188
+ visibility: visible;
1189
+ }
1190
+
1191
+ .modal-content {
1192
+ background: white;
1193
+ padding: 2.5rem;
1194
+ border-radius: var(--radius-lg);
1195
+ box-shadow: var(--shadow-lg);
1196
+ max-width: 500px;
1197
+ width: 90%;
1198
+ text-align: center;
1199
+ position: relative;
1200
+ transform: scale(0.9);
1201
+ transition: transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
1202
+ }
1203
+
1204
+ .modal-overlay.show .modal-content {
1205
+ transform: scale(1);
1206
+ }
1207
+
1208
+ .close-modal {
1209
+ position: absolute;
1210
+ top: 1rem;
1211
+ right: 1rem;
1212
+ background: none;
1213
+ border: none;
1214
+ font-size: 1.5rem;
1215
+ color: var(--gray-400);
1216
+ cursor: pointer;
1217
+ transition: var(--transition);
1218
+ }
1219
+
1220
+ .close-modal:hover {
1221
+ color: var(--danger);
1222
+ transform: rotate(90deg);
1223
+ }
1224
+
1225
+ .modal-icon {
1226
+ font-size: 4rem;
1227
+ margin-bottom: 1.5rem;
1228
+ color: var(--success);
1229
+ }
1230
+
1231
+ .modal-title {
1232
+ font-size: 1.5rem;
1233
+ font-weight: 700;
1234
+ color: var(--gray-900);
1235
+ margin-bottom: 1rem;
1236
+ }
1237
+
1238
+ .modal-message {
1239
+ color: var(--gray-600);
1240
+ line-height: 1.6;
1241
+ margin-bottom: 2rem;
1242
+ }
1243
+
1244
+ .modal-actions {
1245
+ display: flex;
1246
+ justify-content: center;
1247
+ gap: 1rem;
1248
+ }
1249
+
1250
+ /* ============================================
1251
+ Results Page
1252
+ ============================================ */
1253
+ .results-header {
1254
+ display: flex;
1255
+ justify-content: space-between;
1256
+ align-items: center;
1257
+ margin-bottom: 2rem;
1258
+ flex-wrap: wrap;
1259
+ gap: 1rem;
1260
+ }
1261
+
1262
+ .results-title h1 {
1263
+ font-size: 2rem;
1264
+ margin-bottom: 0.5rem;
1265
+ display: flex;
1266
+ align-items: center;
1267
+ gap: 0.75rem;
1268
+ }
1269
+
1270
+ .results-title h1 i {
1271
+ color: var(--primary);
1272
+ }
1273
+
1274
+ .summary-grid {
1275
+ display: grid;
1276
+ grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
1277
+ gap: 1.5rem;
1278
+ margin-bottom: 2rem;
1279
+ }
1280
+
1281
+ .summary-card {
1282
+ background: white;
1283
+ padding: 1.5rem;
1284
+ border-radius: var(--radius);
1285
+ box-shadow: var(--shadow-sm);
1286
+ display: flex;
1287
+ align-items: center;
1288
+ gap: 1.5rem;
1289
+ position: relative;
1290
+ overflow: hidden;
1291
+ transition: var(--transition);
1292
+ }
1293
+
1294
+ .summary-card:hover {
1295
+ transform: translateY(-5px);
1296
+ box-shadow: var(--shadow-md);
1297
+ }
1298
+
1299
+ .summary-icon {
1300
+ width: 60px;
1301
+ height: 60px;
1302
+ border-radius: 50%;
1303
+ display: flex;
1304
+ align-items: center;
1305
+ justify-content: center;
1306
+ font-size: 1.5rem;
1307
+ flex-shrink: 0;
1308
+ }
1309
+
1310
+ .summary-card.total .summary-icon { background: var(--gray-100); color: var(--gray-600); }
1311
+ .summary-card.safe .summary-icon { background: #dcfce7; color: var(--success); }
1312
+ .summary-card.danger .summary-icon { background: #fee2e2; color: var(--danger); }
1313
+ .summary-card.threat .summary-icon { background: #e0e7ff; color: var(--primary); }
1314
+
1315
+ .summary-info {
1316
+ display: flex;
1317
+ flex-direction: column;
1318
+ }
1319
+
1320
+ .summary-value {
1321
+ font-size: 1.75rem;
1322
+ font-weight: 700;
1323
+ color: var(--gray-900);
1324
+ line-height: 1.2;
1325
+ }
1326
+
1327
+ .summary-label {
1328
+ font-size: 0.875rem;
1329
+ color: var(--gray-500);
1330
+ }
1331
+
1332
+ .summary-percent {
1333
+ position: absolute;
1334
+ top: 1rem;
1335
+ right: 1rem;
1336
+ font-size: 0.875rem;
1337
+ font-weight: 600;
1338
+ opacity: 0.8;
1339
+ }
1340
+
1341
+ .summary-card.safe .summary-percent { color: var(--success); }
1342
+ .summary-card.danger .summary-percent { color: var(--danger); }
1343
+
1344
+ /* Threat Visualization */
1345
+ .threat-visual {
1346
+ padding: 1rem 0;
1347
+ }
1348
+
1349
+ .threat-bar-container {
1350
+ height: 24px;
1351
+ background: var(--gray-100);
1352
+ border-radius: 12px;
1353
+ overflow: hidden;
1354
+ margin-bottom: 1.5rem;
1355
+ }
1356
+
1357
+ .threat-bar {
1358
+ display: flex;
1359
+ height: 100%;
1360
+ }
1361
+
1362
+ .threat-segment {
1363
+ display: flex;
1364
+ align-items: center;
1365
+ justify-content: center;
1366
+ color: white;
1367
+ font-size: 0.75rem;
1368
+ font-weight: 600;
1369
+ transition: width 1s ease-out;
1370
+ }
1371
+
1372
+ .threat-segment.safe { background: var(--success); }
1373
+ .threat-segment.danger { background: var(--danger); }
1374
+
1375
+ .threat-message {
1376
+ background: var(--gray-50);
1377
+ padding: 1rem;
1378
+ border-radius: var(--radius);
1379
+ }
1380
+
1381
+ .threat-message i {
1382
+
1383
+ font-size: 1.25rem;
1384
+ margin-right: 0.75rem;
1385
+ vertical-align: middle;
1386
+ }
1387
+
1388
+ .message-safe i { color: var(--success); }
1389
+ .message-warning i { color: var(--warning); }
1390
+ .message-danger i { color: var(--danger); }
1391
+
1392
+ /* Results Table */
1393
+ .table-wrapper {
1394
+ overflow-x: auto;
1395
+ }
1396
+
1397
+ .results-table {
1398
+ width: 100%;
1399
+ border-collapse: collapse;
1400
+ }
1401
+
1402
+ .results-table th,
1403
+ .results-table td {
1404
+ padding: 1rem;
1405
+ text-align: left;
1406
+ border-bottom: 1px solid var(--gray-200);
1407
+ }
1408
+
1409
+ .results-table th {
1410
+ background: var(--gray-50);
1411
+ font-weight: 600;
1412
+ color: var(--gray-700);
1413
+ white-space: nowrap;
1414
+ }
1415
+
1416
+ .results-table tr:hover {
1417
+ background: var(--gray-50);
1418
+ }
1419
+
1420
+ .results-table .col-index {
1421
+ width: 60px;
1422
+ color: var(--gray-400);
1423
+ }
1424
+
1425
+ .label-badge {
1426
+ display: inline-block;
1427
+ padding: 0.25rem 0.75rem;
1428
+ border-radius: 20px;
1429
+ font-size: 0.75rem;
1430
+ font-weight: 600;
1431
+ }
1432
+
1433
+ .label-badge.success { background: #dcfce7; color: var(--success); }
1434
+ .label-badge.danger { background: #fee2e2; color: var(--danger); }
1435
+
1436
+ .confidence-bar {
1437
+ display: flex;
1438
+ align-items: center;
1439
+ gap: 0.5rem;
1440
+ width: 120px;
1441
+ }
1442
+
1443
+ .confidence-fill {
1444
+ height: 6px;
1445
+ border-radius: 3px;
1446
+ background: var(--primary);
1447
+ flex-grow: 1;
1448
+ }
1449
+
1450
+ .bottom-actions {
1451
+ display: flex;
1452
+ justify-content: center;
1453
+ gap: 1.5rem;
1454
+ margin-top: 3rem;
1455
+ flex-wrap: wrap;
1456
+ }
static/js/main.js ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ============================================
2
+ // Network Security - Main JavaScript
3
+ // ============================================
4
+
5
+ document.addEventListener('DOMContentLoaded', function() {
6
+ initFileUpload();
7
+ initTrainingHandler();
8
+ initAnimations();
9
+ initDynamicWidths();
10
+ });
11
+
12
+ // ============================================
13
+ // Training Handler
14
+ // ============================================
15
+
16
+ function initTrainingHandler() {
17
+ const trainBtn = document.getElementById('train-btn');
18
+ if (!trainBtn) return;
19
+
20
+ // Create Modal HTML if not exists
21
+ if (!document.getElementById('success-modal')) {
22
+ const modalHtml = `
23
+ <div id="success-modal" class="modal-overlay">
24
+ <div class="modal-content">
25
+ <button class="close-modal">&times;</button>
26
+ <div class="modal-icon">
27
+ <i class="fas fa-check-circle"></i>
28
+ </div>
29
+ <h3 class="modal-title">Training Successful!</h3>
30
+ <p class="modal-message">
31
+ Model has been trained successfully. You can inspect the detailed metrics and experiments on DagsHub.
32
+ </p>
33
+ <div class="modal-actions">
34
+ <a href="https://dagshub.com/Inder-26/NetworkSecurity/experiments" target="_blank" class="btn btn-primary">
35
+ <i class="fas fa-external-link-alt"></i>
36
+ Check Experiments
37
+ </a>
38
+ </div>
39
+ </div>
40
+ </div>
41
+ `;
42
+ document.body.insertAdjacentHTML('beforeend', modalHtml);
43
+
44
+ // Modal Close Logic
45
+ document.querySelector('.close-modal').addEventListener('click', () => {
46
+ document.getElementById('success-modal').classList.remove('show');
47
+ // Optional: reload page when modal is closed to refresh any data
48
+ // window.location.reload();
49
+ });
50
+ }
51
+
52
+ trainBtn.addEventListener('click', async function() {
53
+ if (!confirm('Are you sure you want to start model training? This may take a few minutes.')) {
54
+ return;
55
+ }
56
+
57
+ const originalText = trainBtn.innerHTML;
58
+ trainBtn.disabled = true;
59
+ trainBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Training in Progress...';
60
+
61
+ try {
62
+ showNotification('Training started. Please wait...', 'info');
63
+
64
+ const response = await fetch('/api/train', {
65
+ method: 'POST'
66
+ });
67
+
68
+ const data = await response.json();
69
+
70
+ if (response.ok) {
71
+ // Show Modal
72
+ const modal = document.getElementById('success-modal');
73
+ modal.classList.add('show');
74
+
75
+ // Reset button
76
+ trainBtn.disabled = false;
77
+ trainBtn.innerHTML = originalText;
78
+
79
+ } else {
80
+ throw new Error(data.detail || 'Training failed');
81
+ }
82
+ } catch (error) {
83
+ console.error('Training Error:', error);
84
+ showNotification(`Training failed: ${error.message}`, 'error');
85
+ trainBtn.disabled = false;
86
+ trainBtn.innerHTML = originalText;
87
+ }
88
+ });
89
+ }
90
+
91
+ // ============================================
92
+ // File Upload Handling
93
+ // ============================================
94
+
95
+ function initFileUpload() {
96
+ const uploadZone = document.getElementById('upload-zone');
97
+ const fileInput = document.getElementById('file-input');
98
+ const fileInfo = document.getElementById('file-info');
99
+ const fileName = document.getElementById('file-name');
100
+ const removeBtn = document.getElementById('remove-file');
101
+ const submitBtn = document.getElementById('submit-btn');
102
+ const form = document.getElementById('upload-form');
103
+
104
+ if (!uploadZone) return;
105
+
106
+ // Drag and drop
107
+ ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
108
+ uploadZone.addEventListener(eventName, preventDefaults, false);
109
+ });
110
+
111
+ function preventDefaults(e) {
112
+ e.preventDefault();
113
+ e.stopPropagation();
114
+ }
115
+
116
+ ['dragenter', 'dragover'].forEach(eventName => {
117
+ uploadZone.addEventListener(eventName, () => {
118
+ uploadZone.classList.add('dragover');
119
+ }, false);
120
+ });
121
+
122
+ ['dragleave', 'drop'].forEach(eventName => {
123
+ uploadZone.addEventListener(eventName, () => {
124
+ uploadZone.classList.remove('dragover');
125
+ }, false);
126
+ });
127
+
128
+ uploadZone.addEventListener('drop', handleDrop, false);
129
+
130
+ function handleDrop(e) {
131
+ const dt = e.dataTransfer;
132
+ const files = dt.files;
133
+
134
+ if (files.length > 0) {
135
+ fileInput.files = files;
136
+ handleFileSelect(files[0]);
137
+ }
138
+ }
139
+
140
+ // File input change
141
+ fileInput.addEventListener('change', function(e) {
142
+ if (e.target.files.length > 0) {
143
+ handleFileSelect(e.target.files[0]);
144
+ }
145
+ });
146
+
147
+ function handleFileSelect(file) {
148
+ if (!file.name.endsWith('.csv')) {
149
+ showNotification('Please upload a CSV file', 'error');
150
+ return;
151
+ }
152
+
153
+ fileName.textContent = file.name;
154
+ uploadZone.style.display = 'none';
155
+ fileInfo.style.display = 'flex';
156
+ submitBtn.disabled = false;
157
+ }
158
+
159
+ // Remove file
160
+ if (removeBtn) {
161
+ removeBtn.addEventListener('click', function() {
162
+ fileInput.value = '';
163
+ uploadZone.style.display = 'block';
164
+ fileInfo.style.display = 'none';
165
+ submitBtn.disabled = true;
166
+ });
167
+ }
168
+
169
+ // Form submit
170
+ if (form) {
171
+ form.addEventListener('submit', function(e) {
172
+ submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Analyzing...';
173
+ submitBtn.disabled = true;
174
+ });
175
+ }
176
+ }
177
+
178
+ // ============================================
179
+ // Notifications
180
+ // ============================================
181
+
182
+ function showNotification(message, type = 'info') {
183
+ const notification = document.createElement('div');
184
+ notification.className = `notification notification-${type}`;
185
+ notification.innerHTML = `
186
+ <i class="fas fa-${type === 'error' ? 'exclamation-circle' : 'info-circle'}"></i>
187
+ <span>${message}</span>
188
+ `;
189
+
190
+ document.body.appendChild(notification);
191
+
192
+ setTimeout(() => {
193
+ notification.classList.add('show');
194
+ }, 100);
195
+
196
+ setTimeout(() => {
197
+ notification.classList.remove('show');
198
+ setTimeout(() => notification.remove(), 300);
199
+ }, 3000);
200
+ }
201
+
202
+ // ============================================
203
+ // Animations
204
+ // ============================================
205
+
206
+ function initAnimations() {
207
+ // Animate elements on scroll
208
+ const observerOptions = {
209
+ threshold: 0.1,
210
+ rootMargin: '0px 0px -50px 0px'
211
+ };
212
+
213
+ const observer = new IntersectionObserver((entries) => {
214
+ entries.forEach(entry => {
215
+ if (entry.isIntersecting) {
216
+ entry.target.classList.add('animate-in');
217
+ observer.unobserve(entry.target);
218
+ }
219
+ });
220
+ }, observerOptions);
221
+
222
+ document.querySelectorAll('.card').forEach(card => {
223
+ observer.observe(card);
224
+ });
225
+
226
+ // Animate metric circles
227
+ document.querySelectorAll('.metric-circle').forEach(circle => {
228
+ const progress = circle.style.getPropertyValue('--progress');
229
+ circle.style.setProperty('--progress', '0');
230
+
231
+ setTimeout(() => {
232
+ circle.style.transition = 'all 1s ease-out';
233
+ circle.style.setProperty('--progress', progress);
234
+ }, 300);
235
+ });
236
+ }
237
+
238
+ function initDynamicWidths() {
239
+ const dynamicElements = document.querySelectorAll('[data-width]');
240
+
241
+ dynamicElements.forEach(el => {
242
+ const width = el.getAttribute('data-width');
243
+ if (width) {
244
+ // Apply immediately if it's not an animated element, or let CSS transitions handle it
245
+ // We set it as a style property so the browser sees it as valid CSS
246
+ setTimeout(() => {
247
+ el.style.width = `${width}%`;
248
+ }, 100); // Small delay to ensure transitions work if present
249
+ }
250
+ });
251
+ }
252
+
253
+ // ============================================
254
+ // Utility Functions
255
+ // ============================================
256
+
257
+ function formatNumber(num) {
258
+ return new Intl.NumberFormat().format(num);
259
+ }
260
+
261
+ function debounce(func, wait) {
262
+ let timeout;
263
+ return function executedFunction(...args) {
264
+ const later = () => {
265
+ clearTimeout(timeout);
266
+ func(...args);
267
+ };
268
+ clearTimeout(timeout);
269
+ timeout = setTimeout(later, wait);
270
+ };
271
+ }
templates/index.html ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>{{ title }}</title>
7
+ <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
8
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
9
+ <link rel="stylesheet" href="/static/css/style.css">
10
+ </head>
11
+ <body>
12
+ <!-- Header -->
13
+ <header class="header">
14
+ <div class="container">
15
+ <div class="header-content">
16
+ <a href="/" class="logo">
17
+ <i class="fas fa-shield-alt"></i>
18
+ <span>Network Security</span>
19
+ </a>
20
+ <nav class="nav-links">
21
+ <a href="/manual" class="nav-link">
22
+ <i class="fas fa-keyboard"></i>
23
+ <span>Manual Input</span>
24
+ </a>
25
+ <a href="{{ github_url }}" target="_blank" class="nav-link">
26
+ <i class="fab fa-github"></i>
27
+ <span>GitHub</span>
28
+ </a>
29
+ <a href="{{ dagshub_url }}" target="_blank" class="nav-link">
30
+ <i class="fas fa-flask"></i>
31
+ <span>DagsHub</span>
32
+ </a>
33
+ </nav>
34
+ </div>
35
+ </div>
36
+ </header>
37
+
38
+ <!-- Hero Section -->
39
+ <section class="hero">
40
+ <div class="container">
41
+ <div class="hero-content">
42
+ <div class="hero-badge">
43
+ <i class="fas fa-robot"></i>
44
+ <span>ML-Powered Security</span>
45
+ </div>
46
+ <h1>🛡️ Phishing URL Detection</h1>
47
+ <p class="hero-subtitle">
48
+ Protect your network with AI-powered threat detection.
49
+ Analyze URLs using 30 security features and machine learning.
50
+ </p>
51
+ <div class="hero-stats">
52
+ <div class="stat-card">
53
+ <div class="stat-icon">
54
+ <i class="fas fa-brain"></i>
55
+ </div>
56
+ <div class="stat-info">
57
+ <span class="stat-value">{{ metrics.model_name }}</span>
58
+ <span class="stat-label">Best Model</span>
59
+ </div>
60
+ </div>
61
+ <div class="stat-card">
62
+ <div class="stat-icon">
63
+ <i class="fas fa-bullseye"></i>
64
+ </div>
65
+ <div class="stat-info">
66
+ <span class="stat-value">{{ "%.1f"|format(metrics.f1_score * 100) }}%</span>
67
+ <span class="stat-label">F1 Score</span>
68
+ </div>
69
+ </div>
70
+ <div class="stat-card">
71
+ <div class="stat-icon">
72
+ <i class="fas fa-columns"></i>
73
+ </div>
74
+ <div class="stat-info">
75
+ <span class="stat-value">{{ feature_count }}</span>
76
+ <span class="stat-label">Features</span>
77
+ </div>
78
+ </div>
79
+ <div class="stat-card">
80
+ <div class="stat-icon">
81
+ <i class="fas fa-layer-group"></i>
82
+ </div>
83
+ <div class="stat-info">
84
+ <span class="stat-value">5</span>
85
+ <span class="stat-label">ML Models</span>
86
+ </div>
87
+ </div>
88
+ </div>
89
+ </div>
90
+ </div>
91
+ </section>
92
+
93
+ <!-- Main Content -->
94
+ <main class="main-content">
95
+ <div class="container">
96
+
97
+ <!-- Prediction Options -->
98
+ <div class="prediction-options">
99
+ <h2 class="section-title">
100
+ <i class="fas fa-magic"></i>
101
+ Choose Prediction Method
102
+ </h2>
103
+ <div class="options-grid">
104
+ <!-- Train Model -->
105
+ <div class="card train-card">
106
+ <div class="card-icon">
107
+ <i class="fas fa-hammer"></i>
108
+ </div>
109
+ <h3>Train New Model</h3>
110
+ <p>Trigger a new training pipeline to update the model</p>
111
+ <button id="train-btn" class="btn btn-warning btn-block">
112
+ <i class="fas fa-play"></i>
113
+ Start Training
114
+ </button>
115
+ </div>
116
+
117
+ <!-- Upload CSV -->
118
+ <div class="card upload-card">
119
+ <div class="card-icon">
120
+ <i class="fas fa-file-upload"></i>
121
+ </div>
122
+ <h3>Batch Prediction</h3>
123
+ <p>Upload a CSV file containing URL features for bulk analysis</p>
124
+ <form id="upload-form" action="/predict" method="post" enctype="multipart/form-data">
125
+ <div id="upload-zone" class="upload-zone">
126
+ <div class="upload-content">
127
+ <i class="fas fa-cloud-upload-alt"></i>
128
+ <p>Drag & Drop CSV file here</p>
129
+ <span>or click to browse</span>
130
+ </div>
131
+ <input type="file" name="file" id="file-input" accept=".csv" required>
132
+ </div>
133
+ <div id="file-info" class="file-info">
134
+ <i class="fas fa-file-csv"></i>
135
+ <span id="file-name">filename.csv</span>
136
+ <button type="button" id="remove-file" class="btn-remove">
137
+ <i class="fas fa-times"></i>
138
+ </button>
139
+ </div>
140
+ <button type="submit" id="submit-btn" class="btn btn-primary btn-block" disabled>
141
+ <i class="fas fa-search"></i>
142
+ Analyze File
143
+ </button>
144
+ </form>
145
+ </div>
146
+
147
+ <!-- Manual Input -->
148
+ <div class="card manual-card">
149
+ <div class="card-icon">
150
+ <i class="fas fa-keyboard"></i>
151
+ </div>
152
+ <h3>Manual Input</h3>
153
+ <p>Enter URL features manually to check for phishing</p>
154
+ <div class="manual-preview">
155
+ <div class="feature-preview">
156
+ <span class="feature-name">having_IP_Address</span>
157
+ <span class="feature-values">-1 / 0 / 1</span>
158
+ </div>
159
+ <div class="feature-preview">
160
+ <span class="feature-name">URL_Length</span>
161
+ <span class="feature-values">-1 / 0 / 1</span>
162
+ </div>
163
+ <div class="feature-preview">
164
+ <span class="feature-name">SSLfinal_State</span>
165
+ <span class="feature-values">-1 / 0 / 1</span>
166
+ </div>
167
+ <div class="more-features">
168
+ <span>+ 27 more features</span>
169
+ </div>
170
+ </div>
171
+ <a href="/manual" class="btn btn-secondary btn-block">
172
+ <i class="fas fa-edit"></i>
173
+ Open Manual Input
174
+ </a>
175
+ </div>
176
+ </div>
177
+ </div>
178
+
179
+ <!-- Model Performance Comparison (Removed as per user request to reduce clutter) -->
180
+ <!-- Real-time stats are shown in the Hero section -->
181
+
182
+ <!-- Features Section -->
183
+ <div class="card features-card">
184
+ <div class="card-header">
185
+ <i class="fas fa-list-check"></i>
186
+ <h2>Required Features (30 Columns)</h2>
187
+ </div>
188
+ <div class="card-body">
189
+ <div class="features-grid">
190
+ <div class="feature-group">
191
+ <h4><i class="fas fa-link"></i> URL Structure</h4>
192
+ <ul>
193
+ <li><code>having_IP_Address</code></li>
194
+ <li><code>URL_Length</code></li>
195
+ <li><code>Shortining_Service</code></li>
196
+ <li><code>having_At_Symbol</code></li>
197
+ <li><code>double_slash_redirecting</code></li>
198
+ <li><code>Prefix_Suffix</code></li>
199
+ <li><code>having_Sub_Domain</code></li>
200
+ <li><code>Abnormal_URL</code></li>
201
+ </ul>
202
+ </div>
203
+ <div class="feature-group">
204
+ <h4><i class="fas fa-lock"></i> Security</h4>
205
+ <ul>
206
+ <li><code>SSLfinal_State</code></li>
207
+ <li><code>HTTPS_token</code></li>
208
+ <li><code>port</code></li>
209
+ <li><code>Favicon</code></li>
210
+ <li><code>Statistical_report</code></li>
211
+ </ul>
212
+ </div>
213
+ <div class="feature-group">
214
+ <h4><i class="fas fa-code"></i> Page Content</h4>
215
+ <ul>
216
+ <li><code>Request_URL</code></li>
217
+ <li><code>URL_of_Anchor</code></li>
218
+ <li><code>Links_in_tags</code></li>
219
+ <li><code>SFH</code></li>
220
+ <li><code>Submitting_to_email</code></li>
221
+ </ul>
222
+ </div>
223
+ <div class="feature-group">
224
+ <h4><i class="fas fa-mouse-pointer"></i> Page Behavior</h4>
225
+ <ul>
226
+ <li><code>Redirect</code></li>
227
+ <li><code>on_mouseover</code></li>
228
+ <li><code>RightClick</code></li>
229
+ <li><code>popUpWidnow</code></li>
230
+ <li><code>Iframe</code></li>
231
+ </ul>
232
+ </div>
233
+ <div class="feature-group">
234
+ <h4><i class="fas fa-globe"></i> Domain Info</h4>
235
+ <ul>
236
+ <li><code>Domain_registeration_length</code></li>
237
+ <li><code>age_of_domain</code></li>
238
+ <li><code>DNSRecord</code></li>
239
+ <li><code>web_traffic</code></li>
240
+ <li><code>Page_Rank</code></li>
241
+ <li><code>Google_Index</code></li>
242
+ <li><code>Links_pointing_to_page</code></li>
243
+ </ul>
244
+ </div>
245
+ </div>
246
+ <div class="feature-note">
247
+ <i class="fas fa-info-circle"></i>
248
+ <div>
249
+ <strong>Value Range:</strong> All features should be integers with values:
250
+ <code>-1</code> (Phishing indicator),
251
+ <code>0</code> (Suspicious), or
252
+ <code>1</code> (Legitimate indicator)
253
+ </div>
254
+ </div>
255
+ </div>
256
+ </div>
257
+
258
+ <!-- How It Works -->
259
+ <div class="card how-it-works-card">
260
+ <div class="card-header">
261
+ <i class="fas fa-cogs"></i>
262
+ <h2>How It Works</h2>
263
+ </div>
264
+ <div class="card-body">
265
+ <div class="pipeline-steps">
266
+ <div class="pipeline-step">
267
+ <div class="step-number">1</div>
268
+ <div class="step-icon"><i class="fas fa-database"></i></div>
269
+ <h4>Data Ingestion</h4>
270
+ <p>Raw data pulled from MongoDB and split into train/test sets</p>
271
+ </div>
272
+ <div class="pipeline-arrow"><i class="fas fa-arrow-right"></i></div>
273
+ <div class="pipeline-step">
274
+ <div class="step-number">2</div>
275
+ <div class="step-icon"><i class="fas fa-check-double"></i></div>
276
+ <h4>Validation</h4>
277
+ <p>Schema validation & KS drift detection</p>
278
+ </div>
279
+ <div class="pipeline-arrow"><i class="fas fa-arrow-right"></i></div>
280
+ <div class="pipeline-step">
281
+ <div class="step-number">3</div>
282
+ <div class="step-icon"><i class="fas fa-random"></i></div>
283
+ <h4>Transformation</h4>
284
+ <p>KNN Imputation & target mapping</p>
285
+ </div>
286
+ <div class="pipeline-arrow"><i class="fas fa-arrow-right"></i></div>
287
+ <div class="pipeline-step">
288
+ <div class="step-number">4</div>
289
+ <div class="step-icon"><i class="fas fa-robot"></i></div>
290
+ <h4>Model Training</h4>
291
+ <p>5 models evaluated, best selected by F1 score</p>
292
+ </div>
293
+ <div class="pipeline-arrow"><i class="fas fa-arrow-right"></i></div>
294
+ <div class="pipeline-step">
295
+ <div class="step-number">5</div>
296
+ <div class="step-icon"><i class="fas fa-rocket"></i></div>
297
+ <h4>Deployment</h4>
298
+ <p>Model served via FastAPI on Hugging Face</p>
299
+ </div>
300
+ </div>
301
+ </div>
302
+ </div>
303
+
304
+ </div>
305
+ </main>
306
+
307
+ <!-- Footer -->
308
+ <footer class="footer">
309
+ <div class="container">
310
+ <div class="footer-content">
311
+ <div class="footer-left">
312
+ <div class="footer-logo">
313
+ <i class="fas fa-shield-alt"></i>
314
+ <span>Network Security</span>
315
+ </div>
316
+ <p>Built with ❤️ by <strong>Inderjeet</strong></p>
317
+ <p class="footer-tech">
318
+ <span><i class="fab fa-python"></i> Python</span>
319
+ <span><i class="fas fa-bolt"></i> FastAPI</span>
320
+ <span><i class="fas fa-chart-line"></i> MLflow</span>
321
+ <span><i class="fas fa-database"></i> MongoDB</span>
322
+ </p>
323
+ </div>
324
+ <div class="footer-right">
325
+ <a href="https://github.com/Inder-26/NetworkSecurity" target="_blank" title="GitHub">
326
+ <i class="fab fa-github"></i>
327
+ </a>
328
+ <a href="https://dagshub.com/inder-26/NetworkSecurity" target="_blank" title="DagsHub">
329
+ <i class="fas fa-flask"></i>
330
+ </a>
331
+ <a href="https://www.linkedin.com/in/inderjeet-singh-26n/" target="_blank" title="LinkedIn">
332
+ <i class="fab fa-linkedin"></i>
333
+ </a>
334
+ </div>
335
+ </div>
336
+ </div>
337
+ </footer>
338
+
339
+ <script src="/static/js/main.js"></script>
340
+ </body>
341
+ </html>
templates/predict.html ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>{{ title }} - Network Security</title>
7
+ <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
8
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
9
+ <link rel="stylesheet" href="/static/css/style.css">
10
+ </head>
11
+ <body>
12
+ <!-- Header -->
13
+ <header class="header">
14
+ <div class="container">
15
+ <div class="header-content">
16
+ <a href="/" class="logo">
17
+ <i class="fas fa-shield-alt"></i>
18
+ <span>Network Security</span>
19
+ </a>
20
+ <nav class="nav-links">
21
+ <a href="/" class="nav-link">
22
+ <i class="fas fa-home"></i>
23
+ <span>Home</span>
24
+ </a>
25
+ <a href="{{ github_url }}" target="_blank" class="nav-link">
26
+ <i class="fab fa-github"></i>
27
+ <span>GitHub</span>
28
+ </a>
29
+ <a href="{{ dagshub_url }}" target="_blank" class="nav-link">
30
+ <i class="fas fa-flask"></i>
31
+ <span>DagsHub</span>
32
+ </a>
33
+ </nav>
34
+ </div>
35
+ </div>
36
+ </header>
37
+
38
+ <main class="main-content results-page">
39
+ <div class="container">
40
+
41
+ <!-- Results Header -->
42
+ <div class="results-header">
43
+ <div class="results-title">
44
+ <h1><i class="fas fa-chart-pie"></i> Prediction Results</h1>
45
+ <p>Analysis complete for {{ summary.total }} URLs</p>
46
+ </div>
47
+ <div class="results-actions">
48
+ <a href="/download/results/{{ output_filename }}" class="btn btn-primary">
49
+ <i class="fas fa-download"></i> Download CSV
50
+ </a>
51
+ <a href="/" class="btn btn-outline">
52
+ <i class="fas fa-plus"></i> New Analysis
53
+ </a>
54
+ </div>
55
+ </div>
56
+
57
+ <!-- Summary Cards -->
58
+ <div class="summary-grid">
59
+ <div class="summary-card total">
60
+ <div class="summary-icon">
61
+ <i class="fas fa-list-ol"></i>
62
+ </div>
63
+ <div class="summary-info">
64
+ <span class="summary-value">{{ summary.total }}</span>
65
+ <span class="summary-label">Total URLs Analyzed</span>
66
+ </div>
67
+ </div>
68
+
69
+ <div class="summary-card safe">
70
+ <div class="summary-icon">
71
+ <i class="fas fa-check-circle"></i>
72
+ </div>
73
+ <div class="summary-info">
74
+ <span class="summary-value">{{ summary.legitimate }}</span>
75
+ <span class="summary-label">Legitimate URLs</span>
76
+ </div>
77
+ <div class="summary-percent">{{ ((summary.legitimate / summary.total) * 100)|round(1) }}%</div>
78
+ </div>
79
+
80
+ <div class="summary-card danger">
81
+ <div class="summary-icon">
82
+ <i class="fas fa-exclamation-triangle"></i>
83
+ </div>
84
+ <div class="summary-info">
85
+ <span class="summary-value">{{ summary.phishing }}</span>
86
+ <span class="summary-label">Phishing URLs</span>
87
+ </div>
88
+ <div class="summary-percent">{{ summary.phishing_percent }}%</div>
89
+ </div>
90
+
91
+ <div class="summary-card threat">
92
+ <div class="summary-icon">
93
+ <i class="fas fa-shield-alt"></i>
94
+ </div>
95
+ <div class="summary-info">
96
+ <span class="summary-value">
97
+ {% if summary.phishing_percent < 20 %}Low
98
+ {% elif summary.phishing_percent < 50 %}Medium
99
+ {% else %}High
100
+ {% endif %}
101
+ </span>
102
+ <span class="summary-label">Threat Level</span>
103
+ </div>
104
+ </div>
105
+ </div>
106
+
107
+ <!-- Threat Visualization -->
108
+ <div class="card threat-card">
109
+ <div class="card-header">
110
+ <i class="fas fa-tachometer-alt"></i>
111
+ <h2>Threat Assessment</h2>
112
+ </div>
113
+ <div class="card-body">
114
+ <div class="threat-visual">
115
+ <div class="threat-bar-container">
116
+ <div class="threat-bar">
117
+ <div class="threat-segment safe" data-width="{{ ((summary.legitimate / summary.total) * 100)|round(1) }}">
118
+ <span>{{ summary.legitimate }} Safe</span>
119
+ </div>
120
+ <div class="threat-segment danger" data-width="{{ summary.phishing_percent }}">
121
+ <span>{{ summary.phishing }} Threats</span>
122
+ </div>
123
+ </div>
124
+ </div>
125
+ <div class="threat-message">
126
+ {% if summary.phishing_percent < 20 %}
127
+ <div class="message-safe">
128
+ <i class="fas fa-shield-alt"></i>
129
+ <p><strong>Low Risk:</strong> The majority of URLs appear to be legitimate. Continue with normal operations.</p>
130
+ </div>
131
+ {% elif summary.phishing_percent < 50 %}
132
+ <div class="message-warning">
133
+ <i class="fas fa-exclamation-circle"></i>
134
+ <p><strong>Moderate Risk:</strong> Some URLs show phishing characteristics. Review flagged URLs before accessing.</p>
135
+ </div>
136
+ {% else %}
137
+ <div class="message-danger">
138
+ <i class="fas fa-skull-crossbones"></i>
139
+ <p><strong>High Risk:</strong> Many URLs are potentially malicious. Avoid clicking on flagged links.</p>
140
+ </div>
141
+ {% endif %}
142
+ </div>
143
+ </div>
144
+ </div>
145
+ </div>
146
+
147
+ <!-- Results Table -->
148
+ <div class="card table-card">
149
+ <div class="card-header">
150
+ <i class="fas fa-table"></i>
151
+ <h2>Detailed Results</h2>
152
+ <span class="record-count">{{ summary.total }} records</span>
153
+ </div>
154
+ <div class="card-body">
155
+ <div class="table-wrapper">
156
+ <table class="results-table">
157
+ <thead>
158
+ <tr>
159
+ <th class="col-index">#</th>
160
+ {% for col in columns %}
161
+ <th>{{ col }}</th>
162
+ {% endfor %}
163
+ </tr>
164
+ </thead>
165
+ <tbody>
166
+ {% for row in results %}
167
+ <tr class="{{ 'row-danger' if row.Prediction == 1 else 'row-safe' }}">
168
+ <td class="col-index">{{ loop.index }}</td>
169
+ {% for col in columns %}
170
+ <td>
171
+ {% if col == 'Label' %}
172
+ <span class="label-badge {{ 'danger' if 'Phishing' in row[col] else 'success' }}">
173
+ {{ row[col] }}
174
+ </span>
175
+ {% elif col == 'Confidence' %}
176
+ <div class="confidence-bar">
177
+ <div class="confidence-fill" data-width="{{ row[col] }}"></div>
178
+ <span>{{ row[col] }}%</span>
179
+ </div>
180
+ {% elif col == 'Prediction' %}
181
+ <span class="prediction-value {{ 'danger' if row[col] == 1 else 'success' }}">
182
+ {{ row[col] }}
183
+ </span>
184
+ {% else %}
185
+ {{ row[col] }}
186
+ {% endif %}
187
+ </td>
188
+ {% endfor %}
189
+ </tr>
190
+ {% endfor %}
191
+ </tbody>
192
+ </table>
193
+ </div>
194
+ </div>
195
+ </div>
196
+
197
+ <!-- Actions -->
198
+ <div class="bottom-actions">
199
+ <a href="/" class="btn btn-primary btn-lg">
200
+ <i class="fas fa-redo"></i> Analyze More URLs
201
+ </a>
202
+ <a href="/download/results/{{ output_filename }}" class="btn btn-outline btn-lg">
203
+ <i class="fas fa-file-csv"></i> Export Full Report
204
+ </a>
205
+ <a href="/manual" class="btn btn-outline btn-lg">
206
+ <i class="fas fa-keyboard"></i> Try Manual Input
207
+ </a>
208
+ </div>
209
+
210
+ </div>
211
+ </main>
212
+
213
+ <!-- Footer -->
214
+ <footer class="footer">
215
+ <div class="container">
216
+ <div class="footer-content">
217
+ <div class="footer-left">
218
+ <p>Built with ❤️ by <strong>Inderjeet</strong></p>
219
+ </div>
220
+ <div class="footer-right">
221
+ <a href="{{ github_url }}" target="_blank"><i class="fab fa-github"></i></a>
222
+ <a href="{{ dagshub_url }}" target="_blank"><i class="fas fa-flask"></i></a>
223
+ </div>
224
+ </div>
225
+ </div>
226
+ </footer>
227
+
228
+ <script src="/static/js/main.js"></script>
229
+ </body>
230
+ </html>
templates/single_predict.html ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>{{ title }} - Network Security</title>
7
+ <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
8
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
9
+ <link rel="stylesheet" href="/static/css/style.css">
10
+ </head>
11
+ <body>
12
+ <!-- Header -->
13
+ <header class="header">
14
+ <div class="container">
15
+ <div class="header-content">
16
+ <a href="/" class="logo">
17
+ <i class="fas fa-shield-alt"></i>
18
+ <span>Network Security</span>
19
+ </a>
20
+ <nav class="nav-links">
21
+ <a href="/" class="nav-link">
22
+ <i class="fas fa-home"></i>
23
+ <span>Home</span>
24
+ </a>
25
+ <a href="{{ github_url }}" target="_blank" class="nav-link">
26
+ <i class="fab fa-github"></i>
27
+ <span>GitHub</span>
28
+ </a>
29
+ <a href="{{ dagshub_url }}" target="_blank" class="nav-link">
30
+ <i class="fas fa-flask"></i>
31
+ <span>DagsHub</span>
32
+ </a>
33
+ </nav>
34
+ </div>
35
+ </div>
36
+ </header>
37
+
38
+ <main class="main-content manual-page">
39
+ <div class="container">
40
+
41
+ <!-- Page Header -->
42
+ <div class="page-header">
43
+ <h1><i class="fas fa-keyboard"></i> Manual Feature Input</h1>
44
+ <p>Enter the 30 feature values to predict if a URL is phishing or legitimate</p>
45
+ </div>
46
+
47
+ <!-- Result Display (if prediction was made) -->
48
+ {% if result %}
49
+ <div class="result-card {{ 'result-danger' if result.is_threat else 'result-safe' }}">
50
+ <div class="result-icon">
51
+ {% if result.is_threat %}
52
+ <i class="fas fa-exclamation-triangle"></i>
53
+ {% else %}
54
+ <i class="fas fa-check-circle"></i>
55
+ {% endif %}
56
+ </div>
57
+ <div class="result-content">
58
+ <h2>{{ result.label }}</h2>
59
+ <p>Confidence: <strong>{{ result.confidence }}%</strong></p>
60
+ </div>
61
+ <div class="result-action">
62
+ <a href="/manual" class="btn btn-outline">
63
+ <i class="fas fa-redo"></i> New Prediction
64
+ </a>
65
+ </div>
66
+ </div>
67
+ {% endif %}
68
+
69
+ <!-- Input Form -->
70
+ <form id="manual-form" action="/predict/single" method="post" class="manual-form">
71
+
72
+ <!-- Quick Actions -->
73
+ <div class="quick-actions">
74
+ <button type="button" class="btn btn-outline btn-sm" onclick="fillSample('legitimate')">
75
+ <i class="fas fa-check"></i> Fill Legitimate Sample
76
+ </button>
77
+ <button type="button" class="btn btn-outline btn-sm" onclick="fillSample('phishing')">
78
+ <i class="fas fa-bug"></i> Fill Phishing Sample
79
+ </button>
80
+ <button type="button" class="btn btn-outline btn-sm" onclick="clearForm()">
81
+ <i class="fas fa-eraser"></i> Clear All
82
+ </button>
83
+ </div>
84
+
85
+ <!-- Feature Groups -->
86
+ <div class="feature-groups">
87
+
88
+ <!-- URL Structure -->
89
+ <div class="feature-group-card">
90
+ <div class="group-header">
91
+ <i class="fas fa-link"></i>
92
+ <h3>URL Structure</h3>
93
+ </div>
94
+ <div class="inputs-grid">
95
+ <div class="input-item">
96
+ <label for="having_IP_Address">having_IP_Address</label>
97
+ <div class="radio-group">
98
+ <label class="radio-label">
99
+ <input type="radio" name="having_IP_Address" value="-1" {{ 'checked' if input_values and input_values.having_IP_Address == -1 }}>
100
+ <span class="radio-btn danger">-1</span>
101
+ </label>
102
+ <label class="radio-label">
103
+ <input type="radio" name="having_IP_Address" value="0" {{ 'checked' if not input_values or input_values.having_IP_Address == 0 }}>
104
+ <span class="radio-btn warning">0</span>
105
+ </label>
106
+ <label class="radio-label">
107
+ <input type="radio" name="having_IP_Address" value="1" {{ 'checked' if input_values and input_values.having_IP_Address == 1 }}>
108
+ <span class="radio-btn success">1</span>
109
+ </label>
110
+ </div>
111
+ </div>
112
+ <div class="input-item">
113
+ <label for="URL_Length">URL_Length</label>
114
+ <div class="radio-group">
115
+ <label class="radio-label">
116
+ <input type="radio" name="URL_Length" value="-1" {{ 'checked' if input_values and input_values.URL_Length == -1 }}>
117
+ <span class="radio-btn danger">-1</span>
118
+ </label>
119
+ <label class="radio-label">
120
+ <input type="radio" name="URL_Length" value="0" {{ 'checked' if not input_values or input_values.URL_Length == 0 }}>
121
+ <span class="radio-btn warning">0</span>
122
+ </label>
123
+ <label class="radio-label">
124
+ <input type="radio" name="URL_Length" value="1" {{ 'checked' if input_values and input_values.URL_Length == 1 }}>
125
+ <span class="radio-btn success">1</span>
126
+ </label>
127
+ </div>
128
+ </div>
129
+ <div class="input-item">
130
+ <label for="Shortining_Service">Shortining_Service</label>
131
+ <div class="radio-group">
132
+ <label class="radio-label">
133
+ <input type="radio" name="Shortining_Service" value="-1">
134
+ <span class="radio-btn danger">-1</span>
135
+ </label>
136
+ <label class="radio-label">
137
+ <input type="radio" name="Shortining_Service" value="0" checked>
138
+ <span class="radio-btn warning">0</span>
139
+ </label>
140
+ <label class="radio-label">
141
+ <input type="radio" name="Shortining_Service" value="1">
142
+ <span class="radio-btn success">1</span>
143
+ </label>
144
+ </div>
145
+ </div>
146
+ <div class="input-item">
147
+ <label for="having_At_Symbol">having_At_Symbol</label>
148
+ <div class="radio-group">
149
+ <label class="radio-label">
150
+ <input type="radio" name="having_At_Symbol" value="-1">
151
+ <span class="radio-btn danger">-1</span>
152
+ </label>
153
+ <label class="radio-label">
154
+ <input type="radio" name="having_At_Symbol" value="0" checked>
155
+ <span class="radio-btn warning">0</span>
156
+ </label>
157
+ <label class="radio-label">
158
+ <input type="radio" name="having_At_Symbol" value="1">
159
+ <span class="radio-btn success">1</span>
160
+ </label>
161
+ </div>
162
+ </div>
163
+ <div class="input-item">
164
+ <label for="double_slash_redirecting">double_slash_redirecting</label>
165
+ <div class="radio-group">
166
+ <label class="radio-label">
167
+ <input type="radio" name="double_slash_redirecting" value="-1">
168
+ <span class="radio-btn danger">-1</span>
169
+ </label>
170
+ <label class="radio-label">
171
+ <input type="radio" name="double_slash_redirecting" value="0" checked>
172
+ <span class="radio-btn warning">0</span>
173
+ </label>
174
+ <label class="radio-label">
175
+ <input type="radio" name="double_slash_redirecting" value="1">
176
+ <span class="radio-btn success">1</span>
177
+ </label>
178
+ </div>
179
+ </div>
180
+ <div class="input-item">
181
+ <label for="Prefix_Suffix">Prefix_Suffix</label>
182
+ <div class="radio-group">
183
+ <label class="radio-label">
184
+ <input type="radio" name="Prefix_Suffix" value="-1">
185
+ <span class="radio-btn danger">-1</span>
186
+ </label>
187
+ <label class="radio-label">
188
+ <input type="radio" name="Prefix_Suffix" value="0" checked>
189
+ <span class="radio-btn warning">0</span>
190
+ </label>
191
+ <label class="radio-label">
192
+ <input type="radio" name="Prefix_Suffix" value="1">
193
+ <span class="radio-btn success">1</span>
194
+ </label>
195
+ </div>
196
+ </div>
197
+ <div class="input-item">
198
+ <label for="having_Sub_Domain">having_Sub_Domain</label>
199
+ <div class="radio-group">
200
+ <label class="radio-label">
201
+ <input type="radio" name="having_Sub_Domain" value="-1">
202
+ <span class="radio-btn danger">-1</span>
203
+ </label>
204
+ <label class="radio-label">
205
+ <input type="radio" name="having_Sub_Domain" value="0" checked>
206
+ <span class="radio-btn warning">0</span>
207
+ </label>
208
+ <label class="radio-label">
209
+ <input type="radio" name="having_Sub_Domain" value="1">
210
+ <span class="radio-btn success">1</span>
211
+ </label>
212
+ </div>
213
+ </div>
214
+ <div class="input-item">
215
+ <label for="Abnormal_URL">Abnormal_URL</label>
216
+ <div class="radio-group">
217
+ <label class="radio-label">
218
+ <input type="radio" name="Abnormal_URL" value="-1">
219
+ <span class="radio-btn danger">-1</span>
220
+ </label>
221
+ <label class="radio-label">
222
+ <input type="radio" name="Abnormal_URL" value="0" checked>
223
+ <span class="radio-btn warning">0</span>
224
+ </label>
225
+ <label class="radio-label">
226
+ <input type="radio" name="Abnormal_URL" value="1">
227
+ <span class="radio-btn success">1</span>
228
+ </label>
229
+ </div>
230
+ </div>
231
+ </div>
232
+ </div>
233
+
234
+ <!-- Security Features -->
235
+ <div class="feature-group-card">
236
+ <div class="group-header">
237
+ <i class="fas fa-lock"></i>
238
+ <h3>Security Features</h3>
239
+ </div>
240
+ <div class="inputs-grid">
241
+ {% for feature in ['SSLfinal_State', 'HTTPS_token', 'port', 'Favicon', 'Statistical_report'] %}
242
+ <div class="input-item">
243
+ <label for="{{ feature }}">{{ feature }}</label>
244
+ <div class="radio-group">
245
+ <label class="radio-label">
246
+ <input type="radio" name="{{ feature }}" value="-1">
247
+ <span class="radio-btn danger">-1</span>
248
+ </label>
249
+ <label class="radio-label">
250
+ <input type="radio" name="{{ feature }}" value="0" checked>
251
+ <span class="radio-btn warning">0</span>
252
+ </label>
253
+ <label class="radio-label">
254
+ <input type="radio" name="{{ feature }}" value="1">
255
+ <span class="radio-btn success">1</span>
256
+ </label>
257
+ </div>
258
+ </div>
259
+ {% endfor %}
260
+ </div>
261
+ </div>
262
+
263
+ <!-- Page Content Features -->
264
+ <div class="feature-group-card">
265
+ <div class="group-header">
266
+ <i class="fas fa-code"></i>
267
+ <h3>Page Content</h3>
268
+ </div>
269
+ <div class="inputs-grid">
270
+ {% for feature in ['Request_URL', 'URL_of_Anchor', 'Links_in_tags', 'SFH', 'Submitting_to_email'] %}
271
+ <div class="input-item">
272
+ <label for="{{ feature }}">{{ feature }}</label>
273
+ <div class="radio-group">
274
+ <label class="radio-label">
275
+ <input type="radio" name="{{ feature }}" value="-1">
276
+ <span class="radio-btn danger">-1</span>
277
+ </label>
278
+ <label class="radio-label">
279
+ <input type="radio" name="{{ feature }}" value="0" checked>
280
+ <span class="radio-btn warning">0</span>
281
+ </label>
282
+ <label class="radio-label">
283
+ <input type="radio" name="{{ feature }}" value="1">
284
+ <span class="radio-btn success">1</span>
285
+ </label>
286
+ </div>
287
+ </div>
288
+ {% endfor %}
289
+ </div>
290
+ </div>
291
+
292
+ <!-- Page Behavior Features -->
293
+ <div class="feature-group-card">
294
+ <div class="group-header">
295
+ <i class="fas fa-mouse-pointer"></i>
296
+ <h3>Page Behavior</h3>
297
+ </div>
298
+ <div class="inputs-grid">
299
+ {% for feature in ['Redirect', 'on_mouseover', 'RightClick', 'popUpWidnow', 'Iframe'] %}
300
+ <div class="input-item">
301
+ <label for="{{ feature }}">{{ feature }}</label>
302
+ <div class="radio-group">
303
+ <label class="radio-label">
304
+ <input type="radio" name="{{ feature }}" value="-1">
305
+ <span class="radio-btn danger">-1</span>
306
+ </label>
307
+ <label class="radio-label">
308
+ <input type="radio" name="{{ feature }}" value="0" checked>
309
+ <span class="radio-btn warning">0</span>
310
+ </label>
311
+ <label class="radio-label">
312
+ <input type="radio" name="{{ feature }}" value="1">
313
+ <span class="radio-btn success">1</span>
314
+ </label>
315
+ </div>
316
+ </div>
317
+ {% endfor %}
318
+ </div>
319
+ </div>
320
+
321
+ <!-- Domain Features -->
322
+ <div class="feature-group-card">
323
+ <div class="group-header">
324
+ <i class="fas fa-globe"></i>
325
+ <h3>Domain Information</h3>
326
+ </div>
327
+ <div class="inputs-grid">
328
+ {% for feature in ['Domain_registeration_length', 'age_of_domain', 'DNSRecord', 'web_traffic', 'Page_Rank', 'Google_Index', 'Links_pointing_to_page'] %}
329
+ <div class="input-item">
330
+ <label for="{{ feature }}">{{ feature }}</label>
331
+ <div class="radio-group">
332
+ <label class="radio-label">
333
+ <input type="radio" name="{{ feature }}" value="-1">
334
+ <span class="radio-btn danger">-1</span>
335
+ </label>
336
+ <label class="radio-label">
337
+ <input type="radio" name="{{ feature }}" value="0" checked>
338
+ <span class="radio-btn warning">0</span>
339
+ </label>
340
+ <label class="radio-label">
341
+ <input type="radio" name="{{ feature }}" value="1">
342
+ <span class="radio-btn success">1</span>
343
+ </label>
344
+ </div>
345
+ </div>
346
+ {% endfor %}
347
+ </div>
348
+ </div>
349
+
350
+ </div>
351
+
352
+ <!-- Submit Button -->
353
+ <div class="form-actions">
354
+ <button type="submit" class="btn btn-primary btn-lg">
355
+ <i class="fas fa-search"></i>
356
+ Predict URL Safety
357
+ </button>
358
+ </div>
359
+
360
+ </form>
361
+
362
+ <!-- Legend -->
363
+ <div class="legend-card">
364
+ <h4><i class="fas fa-info-circle"></i> Value Legend</h4>
365
+ <div class="legend-items">
366
+ <div class="legend-item">
367
+ <span class="legend-badge danger">-1</span>
368
+ <span>Indicates phishing characteristic</span>
369
+ </div>
370
+ <div class="legend-item">
371
+ <span class="legend-badge warning">0</span>
372
+ <span>Suspicious / Unknown</span>
373
+ </div>
374
+ <div class="legend-item">
375
+ <span class="legend-badge success">1</span>
376
+ <span>Indicates legitimate characteristic</span>
377
+ </div>
378
+ </div>
379
+ </div>
380
+
381
+ </div>
382
+ </main>
383
+
384
+ <!-- Footer -->
385
+ <footer class="footer">
386
+ <div class="container">
387
+ <div class="footer-content">
388
+ <div class="footer-left">
389
+ <p>Built with ❤️ by <strong>Inderjeet</strong></p>
390
+ </div>
391
+ <div class="footer-right">
392
+ <a href="{{ github_url }}" target="_blank"><i class="fab fa-github"></i></a>
393
+ <a href="{{ dagshub_url }}" target="_blank"><i class="fas fa-flask"></i></a>
394
+ </div>
395
+ </div>
396
+ </div>
397
+ </footer>
398
+
399
+ <script src="/static/js/main.js"></script>
400
+ <script>
401
+ // Sample data for quick fill
402
+ const samples = {
403
+ legitimate: {
404
+ having_IP_Address: 1, URL_Length: 1, Shortining_Service: 1, having_At_Symbol: 1,
405
+ double_slash_redirecting: 1, Prefix_Suffix: 1, having_Sub_Domain: 1, SSLfinal_State: 1,
406
+ Domain_registeration_length: 1, Favicon: 1, port: 1, HTTPS_token: 1, Request_URL: 1,
407
+ URL_of_Anchor: 1, Links_in_tags: 1, SFH: 1, Submitting_to_email: 1, Abnormal_URL: 1,
408
+ Redirect: 0, on_mouseover: 1, RightClick: 1, popUpWidnow: 1, Iframe: 1, age_of_domain: 1,
409
+ DNSRecord: 1, web_traffic: 1, Page_Rank: 1, Google_Index: 1, Links_pointing_to_page: 1,
410
+ Statistical_report: 1
411
+ },
412
+ phishing: {
413
+ having_IP_Address: -1, URL_Length: -1, Shortining_Service: -1, having_At_Symbol: -1,
414
+ double_slash_redirecting: -1, Prefix_Suffix: -1, having_Sub_Domain: -1, SSLfinal_State: -1,
415
+ Domain_registeration_length: -1, Favicon: -1, port: -1, HTTPS_token: -1, Request_URL: -1,
416
+ URL_of_Anchor: -1, Links_in_tags: -1, SFH: -1, Submitting_to_email: -1, Abnormal_URL: -1,
417
+ Redirect: 0, on_mouseover: -1, RightClick: -1, popUpWidnow: -1, Iframe: -1, age_of_domain: -1,
418
+ DNSRecord: -1, web_traffic: -1, Page_Rank: -1, Google_Index: -1, Links_pointing_to_page: -1,
419
+ Statistical_report: -1
420
+ }
421
+ };
422
+
423
+ function fillSample(type) {
424
+ const data = samples[type];
425
+ for (const [name, value] of Object.entries(data)) {
426
+ const radio = document.querySelector(`input[name="${name}"][value="${value}"]`);
427
+ if (radio) radio.checked = true;
428
+ }
429
+ }
430
+
431
+ function clearForm() {
432
+ document.querySelectorAll('input[value="0"]').forEach(radio => radio.checked = true);
433
+ }
434
+ </script>
435
+ </body>
436
+ </html>
test.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import os
3
+ import pandas as pd
4
+ import io
5
+
6
+ BASE_URL = "http://127.0.0.1:8000"
7
+
8
+ def print_status(component, status, message=""):
9
+ symbol = "✅" if status else "❌"
10
+ print(f"{symbol} {component}: {message}")
11
+
12
+ def test_health():
13
+ try:
14
+ response = requests.get(f"{BASE_URL}/")
15
+ if response.status_code == 200:
16
+ print_status("Health Check", True, "Server is reachable")
17
+ else:
18
+ print_status("Health Check", False, f"Status Code {response.status_code}")
19
+ except Exception as e:
20
+ print_status("Health Check", False, f"Connection Failed: {str(e)}")
21
+
22
+ def test_training():
23
+ print("\n[ Testing Training Endpoint ]")
24
+ try:
25
+ # Note: This might take a while if actual training happens
26
+ response = requests.post(f"{BASE_URL}/api/train")
27
+ if response.status_code == 200:
28
+ data = response.json()
29
+ print_status("Training", True, data.get("message", "Training started"))
30
+ else:
31
+ print_status("Training", False, f"Failed with {response.status_code}: {response.text}")
32
+ except Exception as e:
33
+ print_status("Training", False, str(e))
34
+
35
+ def test_single_prediction():
36
+ print("\n[ Testing Single Prediction ]")
37
+ # Sample legitimate-looking data (mostly 1s or 0s depending on feature encoding)
38
+ data = {
39
+ "having_IP_Address": 1,
40
+ "URL_Length": 1,
41
+ "Shortining_Service": 1,
42
+ "having_At_Symbol": 1,
43
+ "double_slash_redirecting": 1,
44
+ "Prefix_Suffix": 1,
45
+ "having_Sub_Domain": 1,
46
+ "SSLfinal_State": 1,
47
+ "Domain_registeration_length": 1,
48
+ "Favicon": 1,
49
+ "port": 1,
50
+ "HTTPS_token": 0,
51
+ "Request_URL": 1,
52
+ "URL_of_Anchor": 1,
53
+ "Links_in_tags": 1,
54
+ "SFH": 1,
55
+ "Submitting_to_email": 1,
56
+ "Abnormal_URL": 1,
57
+ "Redirect": 1,
58
+ "on_mouseover": 1,
59
+ "RightClick": 1,
60
+ "popUpWidnow": 1,
61
+ "Iframe": 1,
62
+ "age_of_domain": 1,
63
+ "DNSRecord": 1,
64
+ "web_traffic": 1,
65
+ "Page_Rank": 1,
66
+ "Google_Index": 1,
67
+ "Links_pointing_to_page": 1,
68
+ "Statistical_report": 1
69
+ }
70
+
71
+ try:
72
+ response = requests.post(f"{BASE_URL}/api/predict/single", data=data)
73
+ if response.status_code == 200:
74
+ result = response.json()
75
+ print_status("Single Predict", True, f"Prediction: {result.get('prediction')} (Safe: {result.get('is_safe')})")
76
+ else:
77
+ print_status("Single Predict", False, f"Status {response.status_code}: {response.text}")
78
+ except Exception as e:
79
+ print_status("Single Predict", False, str(e))
80
+
81
+ def test_batch_prediction():
82
+ print("\n[ Testing Batch Prediction ]")
83
+ # Create dummy CSV
84
+ df = pd.DataFrame([{
85
+ "having_IP_Address": 1, "URL_Length": 1, "Shortining_Service": 1, "having_At_Symbol": 1,
86
+ "double_slash_redirecting": 1, "Prefix_Suffix": 1, "having_Sub_Domain": 1, "SSLfinal_State": 1,
87
+ "Domain_registeration_length": 1, "Favicon": 1, "port": 1, "HTTPS_token": 1, "Request_URL": 1,
88
+ "URL_of_Anchor": 1, "Links_in_tags": 1, "SFH": 1, "Submitting_to_email": 1, "Abnormal_URL": 1,
89
+ "Redirect": 1, "on_mouseover": 1, "RightClick": 1, "popUpWidnow": 1, "Iframe": 1, "age_of_domain": 1,
90
+ "DNSRecord": 1, "web_traffic": 1, "Page_Rank": 1, "Google_Index": 1, "Links_pointing_to_page": 1,
91
+ "Statistical_report": 1
92
+ }] * 5) # 5 rows
93
+
94
+ csv_buffer = io.StringIO()
95
+ df.to_csv(csv_buffer, index=False)
96
+ csv_buffer.seek(0)
97
+
98
+ files = {'file': ('test_batch.csv', csv_buffer.getvalue(), 'text/csv')}
99
+
100
+ try:
101
+ response = requests.post(f"{BASE_URL}/predict", files=files)
102
+ if response.status_code == 200:
103
+ # It returns a template, so checking text length or specific marker
104
+ if "Prediction Results" in response.text or "table" in response.text:
105
+ print_status("Batch Predict", True, "Received HTML response with results")
106
+ else:
107
+ print_status("Batch Predict", True, f"Response received (Length: {len(response.text)})")
108
+ else:
109
+ print_status("Batch Predict", False, f"Status {response.status_code}")
110
+ except Exception as e:
111
+ print_status("Batch Predict", False, str(e))
112
+
113
+ if __name__ == "__main__":
114
+ print("🚀 Starting Unified Verification...")
115
+ test_health()
116
+ test_training()
117
+ test_single_prediction()
118
+ test_batch_prediction()
119
+ print("\n✨ Verification Complete")
valid_data/test.csv ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ having_IP_Address,URL_Length,Shortining_Service,having_At_Symbol,double_slash_redirecting,Prefix_Suffix,having_Sub_Domain,SSLfinal_State,Domain_registeration_length,Favicon,port,HTTPS_token,Request_URL,URL_of_Anchor,Links_in_tags,SFH,Submitting_to_email,Abnormal_URL,Redirect,on_mouseover,RightClick,popUpWidnow,Iframe,age_of_domain,DNSRecord,web_traffic,Page_Rank,Google_Index,Links_pointing_to_page,Statistical_report
2
+ 1,-1,1,1,1,-1,1,1,1,1,1,-1,-1,1,1,0,1,1,0,1,1,1,1,1,1,-1,-1,1,1,1
3
+ -1,-1,-1,1,-1,1,1,1,-1,1,1,-1,1,1,0,1,1,-1,0,1,1,1,1,-1,-1,1,1,-1,1,1
4
+ -1,-1,-1,1,-1,-1,0,0,1,1,1,-1,-1,-1,1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,0,1
5
+ -1,-1,1,1,1,-1,1,1,1,1,1,1,-1,0,1,1,1,1,0,1,1,1,1,1,1,1,-1,1,1,1
6
+ 1,1,1,1,1,-1,0,-1,-1,1,1,1,1,0,0,1,1,1,0,1,1,1,1,-1,1,1,-1,1,0,1
7
+ 1,-1,1,1,1,1,0,-1,-1,1,1,1,1,0,0,-1,1,1,0,1,1,1,1,1,1,1,-1,1,0,1
8
+ 1,1,1,1,1,-1,0,1,-1,-1,1,1,1,0,-1,1,1,1,0,-1,1,-1,1,-1,1,1,-1,1,0,1
9
+ 1,-1,1,1,1,-1,-1,-1,1,1,1,1,-1,-1,0,-1,1,1,0,1,1,1,1,-1,-1,-1,-1,1,0,1
10
+ 1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,-1,0,0,0,-1,1,0,-1,1,-1,-1,1,1,1,-1,1,0,1
11
+ 1,1,1,1,1,-1,0,-1,-1,1,1,1,1,-1,0,1,1,1,0,1,1,1,1,-1,-1,-1,-1,1,0,1
12
+ 1,-1,1,1,1,-1,-1,1,1,1,1,1,-1,0,-1,-1,1,1,0,1,1,1,1,1,1,1,-1,1,0,1
13
+ -1,1,-1,1,1,-1,0,1,-1,1,1,1,1,0,1,-1,1,1,0,1,1,1,1,1,1,1,-1,1,0,1
verify_mongo.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ import sys
4
+ from dotenv import load_dotenv
5
+ from pymongo.mongo_client import MongoClient
6
+
7
+ # Load environment variables
8
+ load_dotenv()
9
+
10
+ mongo_url = os.getenv("MONGO_DB_URL")
11
+
12
+ print(f"Checking connection for URL: {mongo_url[:20]}..." if mongo_url else "No MONGO_DB_URL found in .env")
13
+
14
+ if not mongo_url:
15
+ print("❌ MONGO_DB_URL is not set in .env")
16
+ sys.exit(1)
17
+
18
+ try:
19
+ client = MongoClient(mongo_url, serverSelectionTimeoutMS=5000)
20
+ # Send a ping to confirm a successful connection
21
+ client.admin.command('ping')
22
+ print("✅ Successfully connected to MongoDB!")
23
+
24
+ # List databases to be sure
25
+ dbs = client.list_database_names()
26
+ print(f" Databases found: {dbs}")
27
+
28
+ except Exception as e:
29
+ print(f"❌ Connection Failed: {e}")