sibikrish commited on
Commit
d219831
·
verified ·
1 Parent(s): 8141232

Upload folder using huggingface_hub

Browse files
.dockerignore ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ignore Python cache files
2
+ __pycache__
3
+ *.pyc
4
+ *.pyo
5
+ *.pyd
6
+
7
+ # Ignore virtual environment directories
8
+ venv/
9
+ env/
10
+ .venv/
11
+ .env/
12
+
13
+ # Ignore system files
14
+ .DS_Store
15
+ Thumbs.db
16
+
17
+
18
+ # Ignore logs and temp files
19
+ *.log
20
+ *.tmp
21
+
22
+
23
+ # Ignore data directories
24
+ data/
25
+ datasets/
.gitattributes CHANGED
@@ -1,35 +1,5 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
+ # Auto detect text files and perform LF normalization
2
+ * text=auto
3
+ *.nc filter=lfs diff=lfs merge=lfs -text
4
+ *.csv filter=lfs diff=lfs merge=lfs -text
5
+ *.pkl filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.gitignore ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
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
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
110
+ .pdm.toml
111
+ .pdm-python
112
+ .pdm-build/
113
+
114
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
115
+ __pypackages__/
116
+
117
+ # Celery stuff
118
+ celerybeat-schedule
119
+ celerybeat.pid
120
+
121
+ # SageMath parsed files
122
+ *.sage.py
123
+
124
+ # Environments
125
+ .env
126
+ .venv
127
+ env/
128
+ venv/
129
+ ENV/
130
+ env.bak/
131
+ venv.bak/
132
+
133
+ # Spyder project settings
134
+ .spyderproject
135
+ .spyproject
136
+
137
+ # Rope project settings
138
+ .ropeproject
139
+
140
+ # mkdocs documentation
141
+ /site
142
+
143
+ # mypy
144
+ .mypy_cache/
145
+ .dmypy.json
146
+ dmypy.json
147
+
148
+ # Pyre type checker
149
+ .pyre/
150
+
151
+ # pytype static type analyzer
152
+ .pytype/
153
+
154
+ # Cython debug symbols
155
+ cython_debug/
156
+
157
+ # PyCharm
158
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
159
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
161
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
162
+ #.idea/
.pre-commit-config.yaml ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ repos:
2
+ - repo: https://github.com/pre-commit/pre-commit-hooks
3
+ rev: v4.4.0
4
+ hooks:
5
+ - id: trailing-whitespace
6
+ - id: end-of-file-fixer
7
+ - id: check-larger-file
8
+ - id: check-yaml
9
+
10
+ - repo: https://github.com/psf/black
11
+ rev: 22.3.0
12
+ hooks:
13
+ - id: black
14
+ language_version: python3
15
+
16
+ - repo: https://gitlab.com/pycqa/flake8
17
+ rev: 3.9.2
18
+ hooks:
19
+ - id: flake8
20
+
21
+ - repo: https://github.com/pre-commit/mirrors-mypy
22
+ rev: v0.812
23
+ hooks:
24
+ - id: mypy
25
+
26
+ - repo: https://github.com/pre-commit/mirrors-pylint
27
+ rev: v2.6.0
28
+ hooks:
29
+ - id: pylint
30
+ additional_dependencies: ['pylint-django']
Dockerfile ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.9-slim
2
+
3
+ # Set environment variables
4
+ ENV PYTHONDONTWRITEBYTECODE 1
5
+ ENV PYTHONUNBUFFERED 1
6
+
7
+ # Set the working directory in the container
8
+ WORKDIR /app
9
+
10
+ # Copy the requirements file and install dependencies
11
+ COPY requirements.txt .
12
+ RUN pip install --no-cache-dir -r requirements.txt
13
+
14
+ # Copy all application files into the container
15
+ COPY . .
16
+
17
+ # Expose the ports for both FastAPI and Gradio
18
+ EXPOSE 8000
19
+ EXPOSE 7860
20
+
21
+ # Command to run both FastAPI and Gradio servers
22
+ <<<<<<< Updated upstream
23
+ CMD ["python", "gradio_app.py","&&","uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
24
+
25
+ =======
26
+ CMD ["python", "gradio_app.py","&&","uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
27
+ >>>>>>> Stashed changes
Encoder/WOEEncoder.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bbf100c787c2a3596c11e46d84342a81a304602bdbc3039ad0135e8048abce65
3
+ size 54953
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Sibi krish
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 CHANGED
@@ -1,13 +1,236 @@
1
- ---
2
- title: Creditcard Fraud Detection
3
- emoji: 🏃
4
- colorFrom: purple
5
- colorTo: gray
6
- sdk: gradio
7
- sdk_version: 4.37.1
8
- app_file: app.py
9
- pinned: false
10
- license: mit
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Creditcard-Fraud-Detection
3
+ app_file: gradio_app.py
4
+ sdk: gradio
5
+ sdk_version: 4.36.1
6
+ ---
7
+
8
+ <!-- markdownlint-disable -->
9
+ <p align="center">
10
+ <a href = "https://github.com/Sibikrish3000/Creditcard-Fraud-Detection" > <img src = "https://github.com/Sibikrish3000/Creditcard-Fraud-Detection/blob/main/static/images/creditcard1.jpg?raw=true" alt = "fraud detection image" width=500 height=280> </a>
11
+ </p>
12
+ <h1 align="center"> Credit Card Fraud Detection Application </h1>
13
+
14
+ <p align="center">
15
+ This application leverages machine learning to detect fraudulent credit card transactions.
16
+ </p>
17
+
18
+ <p align="center">
19
+ <a href="https://github.com/Sibikrish3000/Creditcard-Fraud-Detection/blob/main/LICENSE"><img src="https://img.shields.io/github/license/Sibikrish3000/Creditcard-Fraud-Detection" alt="GitHub license"></a>
20
+ <a href="https://github.com/Sibikrish3000/Creditcard-Fraud-Detection/stargazers"><img src="https://img.shields.io/github/stars/Sibikrish3000/Creditcard-Fraud-Detection?style=social" alt="GitHub stars"></a>
21
+ <a href="https://github.com/Sibikrish3000/Creditcard-Fraud-Detection/issues"><img src="https://img.shields.io/github/issues/Sibikrish3000/Creditcard-Fraud-Detection" alt="GitHub issues"></a>
22
+ <a href="https://github.com/Sibikrish3000/Creditcard-Fraud-Detection/actions/workflows/quality.yml"><img src="https://github.com/Sibikrish3000/Creditcard-Fraud-Detection/actions/workflows/quality.yml/badge.svg" alt="Code Quality"></a>
23
+ </p>
24
+ <p align="center">
25
+ <a href="https://scikit-learn.org/"><img src=https://img.shields.io/badge/sklearn-darkorange.svg?style=flat&logo=scikit-learn&logoColor=white alt="sklearn"></a>
26
+ <a href="https://www.python.org"><img src="https://img.shields.io/badge/Python-darkblue.svg?style=flat&logo=python&logoColor=white" alt="language"></a>
27
+ <a href="https://fastapi.tiangolo.com/" ><img src="https://img.shields.io/badge/FastAPI-darkgreen.svg?style=flat&logo=fastapi&logoColor=white " alt="fastapi"></a> <a href="https://hub.docker.com/repository/docker/sibikrish3000/creditcard-fraud-detection/"><img src="https://img.shields.io/badge/Docker-blue?style=flat&logo=docker&logoColor=white" alt= "docker"></a>
28
+
29
+
30
+
31
+
32
+
33
+ </p>
34
+
35
+
36
+ This project contains a Fraud Detection application that includes a FastAPI server for the backend and a Gradio interface for the frontend. The application can predict if a transaction is fraudulent using either XGBoost or RandomForest models.
37
+
38
+ [Dataset](https://www.kaggle.com/datasets/kartik2112/fraud-detection)
39
+ ## Overview
40
+
41
+ 1. **FastAPI Backend**: Handles prediction requests using machine learning models.
42
+ 2. **Gradio Frontend**: Provides a user-friendly web interface for users to input transaction details and get predictions.
43
+
44
+
45
+ ## Project Structure
46
+
47
+ ```
48
+
49
+ /Creditcard-Fraud-Detection
50
+
51
+ ├──/model
52
+ │ ├── xgboost.pkl
53
+ │ └── randomforest.pkl
54
+ ├──/Encoder
55
+ │ └── WOEEncoder.pkl
56
+
57
+ ├──/static
58
+ │ └──/images
59
+ │ ├── github.svg
60
+ │ └── api.png
61
+
62
+ ├── app.py
63
+ ├── gradio_app.py
64
+ ├── docker_app.py
65
+ ├── Dockerfile
66
+ ├── docker-compose.yml
67
+ ├── requirements.txt
68
+ ├── features.py
69
+
70
+ ````
71
+
72
+ - `app.py`: Defines the FastAPI application.
73
+ - `gradio_app.py`: Defines the Gradio interface.
74
+ - `docker_app.py`: Gradio interface for docker
75
+ - `Dockerfile`: Dockerfile for building the Docker image.
76
+ - `docker-compose.yml`: Docker Compose file for orchestrating the services.
77
+ - `requirements.txt`: List of dependencies.
78
+ - `features.py`: List of features.
79
+ - `model/`: Directory containing pre-trained machine learning models.
80
+ - `Encoder/`: Directory containing encoders used for data preprocessing.
81
+ - `static/`: Directory containing static files such as images used in the interface.
82
+
83
+ ## Getting Started
84
+
85
+ ### Prerequisites
86
+
87
+ - Docker
88
+ - Docker Compose
89
+
90
+ ### Installation
91
+
92
+ **Clone the repository:**
93
+
94
+ ```bash
95
+ git clone https://github.com/Sibikrish3000/Creditcard-Fraud-Detection.git
96
+ cd Creditcard-Fraud-Detection
97
+ ```
98
+ ```
99
+ git install lfs
100
+ git lfs ls-files
101
+ ```
102
+ ```
103
+ git lfs pull
104
+ ```
105
+
106
+
107
+ ## Running Locally
108
+
109
+ ### Using Docker Compose
110
+
111
+ 1. Build and start the containers:
112
+ ```sh
113
+ docker network create AIservice
114
+ ```
115
+ ```sh
116
+ docker-compose up --build
117
+ ```
118
+
119
+ 2. Access the Gradio interface at [http://localhost:7860](http://localhost:7860).
120
+
121
+ ### Using Docker image
122
+
123
+ ```sh
124
+ docker network create AIservice
125
+ ```
126
+ ```sh
127
+ docker pull sibikrish/creditcard-fraud-detection:latest
128
+ docker run sibikrish/creditcard-fraud-detection:latest #or
129
+ docker run -d -p 7860:7860 sibikrish/creditcard-fraud-detection:latest
130
+ ```
131
+
132
+ ### Manually
133
+
134
+ To run the application locally without Docker, ensure you have Python installed and follow these steps:
135
+
136
+ 1. **Install the dependencies:**
137
+
138
+ ```bash
139
+ pip install -r requirements.txt
140
+ ```
141
+
142
+ 2. **Run the FastAPI server:**
143
+
144
+ ```bash
145
+ uvicorn app:app --host 0.0.0.0 --port 8000
146
+ ```
147
+
148
+ 3. **Run the Gradio interface:**
149
+
150
+ ```bash
151
+ python gradio_app.py
152
+ ```
153
+
154
+ ## Development
155
+ ### Running in a Gitpod Cloud Environment
156
+
157
+ **Click the button below to start a new development environment:**
158
+
159
+ [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/Sibikrish3000/Creditcard-Fraud-Detection)
160
+ ## Deployment
161
+
162
+ ### Using Vercel
163
+
164
+ 1. Create a `vercel.json` file in the project root:
165
+ ```json
166
+ {
167
+ "version": 2,
168
+ "builds": [
169
+ { "src": "app.py", "use": "@vercel/python" },
170
+ { "src": "gradio_app.py", "use": "@vercel/python" }
171
+ ],
172
+ "routes": [
173
+ { "src": "/api/(.*)", "dest": "app.py" },
174
+ { "src": "/(.*)", "dest": "gradio_app.py" }
175
+ ]
176
+ }
177
+ ```
178
+
179
+ 2. Deploy using the Vercel CLI:
180
+ ```sh
181
+ vercel
182
+ ```
183
+
184
+
185
+
186
+ ## Usage
187
+
188
+ 1. **Access the Gradio Interface:**
189
+
190
+ Open your web browser and navigate to `http://localhost:7860` to access the Gradio interface.
191
+
192
+ - **Inputs**: Users can input transaction details such as credit card frequency, job, age, gender, category, distance, hour, hours difference between transactions, amount, and choose a model.
193
+ - **Output**: The application returns a prediction indicating whether the transaction is legitimate or fraudulent.
194
+ - **Flag Option**: Users can enable a flag option to provide feedback on incorrect or suspicious predictions.
195
+
196
+
197
+ 2. **Access the FastAPI Documentation:**
198
+
199
+ Open your web browser and navigate to `http://localhost:8000/docs` to access the FastAPI documentation.
200
+
201
+ ### API Endpoints
202
+
203
+ - **POST /predict**
204
+
205
+ Predict if a transaction is fraudulent.
206
+
207
+ **Request:**
208
+
209
+ ```json
210
+ {
211
+ "cc_freq": int,
212
+ "cc_freq_class": int,
213
+ "job": str,
214
+ "age": int,
215
+ "gender_M": int,
216
+ "category": str,
217
+ "distance_km": float,
218
+ "hour": str,
219
+ "hours_diff_bet_trans": float,
220
+ "amt": float
221
+ }
222
+ ```
223
+
224
+ **Response:**
225
+
226
+ ```json
227
+ {
228
+ "prediction": 0 for legitimate, 1 for fraudulent
229
+ }
230
+ ```
231
+
232
+ ## License
233
+
234
+ This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
235
+
236
+
about.md ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Credit Card Fraud Detection App built with Gradio, FastAPI, and Docker
2
+
3
+ This Credit Card Fraud Detection App leverages Machine Learning models served as an API to identify potentially fraudulent credit card transactions, empowering users to assess transaction legitimacy based on various input features including credit card frequency, job, age, gender, category, distance, hour, hours difference between transactions, amount, and model choice (XGBoost or RandomForest).
4
+ ### Features:
5
+
6
+ 1. **FastAPI Backend**: The backend of the application is implemented using FastAPI, a modern web framework for building APIs with Python. It exposes an endpoint `/predict` that accepts POST requests with transaction data and returns predictions.
7
+
8
+ 2. **Gradio Frontend**: The frontend of the application is implemented using Gradio, a Python library that allows for the creation of customizable UI components for machine learning models. Users interact with the application through a user-friendly interface where they can input transaction details and receive predictions.
9
+
10
+ 3. **Models**: The utilization of both XGBoost and RandomForest models ensures robust prediction capabilities, leveraging powerful machine learning algorithms widely recognized for their effectiveness in classification and regression tasks.
11
+
12
+ 4. **Flagging Option**: Users can flag examples in the interface, providing feedback on predictions that seem incorrect or suspicious. This functionality allows for continuous improvement of the model.
13
+
14
+ ### Usage:
15
+
16
+ - Users can run the application locally by executing the provided Python script.
17
+ - They can interact with the application through the Gradio interface in their web browser, inputting transaction details and receiving predictions.
18
+ - The application provides predictions in real-time, leveraging machine learning models trained on historical transaction data.
19
+
20
+ ### Deployment:
21
+
22
+ - The application can be deployed locally or on a cloud platform using Docker. Docker containers encapsulate both the FastAPI backend and the Gradio frontend, making deployment straightforward.
23
+ - Additionally, the application can be deployed to a serverless platform like Vercel or Heroku, leveraging their respective deployment methods.
24
+
25
+ ### Future Improvements:
26
+
27
+ 1. Enhance model performance by fine-tuning hyperparameters or using more sophisticated models.
28
+ 2. Add more features to improve prediction accuracy.
29
+ 3. Implement user authentication and authorization for secure access to the application.
30
+ 4. Integrate with a database to store flagged examples for analysis and model improvement.
31
+
32
+ ### Development:
33
+
34
+ - Developers can extend and enhance the application by adding new features, improving model accuracy, or optimizing performance.
35
+ - The codebase is modular and well-structured, facilitating easy maintenance and collaboration among developers.
36
+
37
+ Overall, this Fraud Detection application provides a practical solution for identifying potentially fraudulent transactions, helping businesses and organizations mitigate financial risks.
38
+
39
+ ## License
40
+
41
+ This project is licensed under the MIT License. See the [LICENSE](https://github.com/Sibikrish3000/Creditcard-Fraud-Detection/blob/main/LICENSE) file for details.
42
+
43
+ The Jupyter notebook, trained model, and accompanying documentation, including Dockerfiles, FastAPI script, and Gradio Interface script, can be accessed through the GitHub repository linked below:
44
+
45
+ [GitHub Repository](https://github.com/Sibikrish3000/Creditcard-Fraud-Detection)
46
+
47
+ [![size](https://img.shields.io/github/repo-size/Sibikrish3000/Creditcard-Fraud-Detection)](https://github.com/Sibikrish3000/Creditcard-Fraud-Detection)
48
+
49
+ Please feel free to explore and utilize these resources for credit card fraud detection purposes.
50
+
51
+ ### [@Sibi Krishnamoorthy](https://sibikrish3000.github.io/portfolio/)
52
+ ___
53
+
54
+ <h5 align="center">
55
+ Sibi Krishnamoorthy
56
+ </h5><p align="center">
57
+ A Data Science student with a passion for Machine Learning and Artificial intelligence
58
+ </p><p style="color:teal" align="center">
59
+ &copy Sibikrish. All rights reserved 2024
60
+ </p>
61
+
62
+
app.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI,Query
2
+ from fastapi.responses import HTMLResponse
3
+ from fastapi.staticfiles import StaticFiles
4
+ from pydantic import BaseModel
5
+ import warnings
6
+ warnings.filterwarnings('ignore')
7
+ import joblib
8
+ import uvicorn
9
+
10
+ app = FastAPI(title="Credit Card Fraud Detection API",
11
+ description="""An API that utilises a Machine Learning model that detects a credit card transaction fraudulent""",
12
+ version="1.0.0", debug=True)
13
+ app.mount("/static", StaticFiles(directory="static"), name="static")
14
+
15
+ xgb_model = joblib.load('./model/xgb_model.pkl')
16
+ rf_model = joblib.load('./model/rf_model.pkl')
17
+ enc = joblib.load('./Encoder/WOEEncoder.pkl')
18
+
19
+
20
+ @app.get('/',response_class=HTMLResponse)
21
+ def running():
22
+ text='''
23
+ <html>
24
+ <head>
25
+ <link rel="icon" type="image/x-icon" href="static/images/api.png">
26
+ <title>Credit Card Fraud Detection API</title>
27
+ </head>
28
+ <body>
29
+ <div>
30
+ <h1>Credit Card Fraud Detection API</h1>
31
+ <a href="https://github.com/Sibikrish3000/">Github repository</a>
32
+ </div>
33
+ </body>
34
+ </html>
35
+ '''
36
+ return text
37
+
38
+ class fraudinput(BaseModel):
39
+ cc_freq:int
40
+ cc_freq_class:int
41
+ job:str
42
+ age:int
43
+ gender_M:int
44
+ category:str
45
+ distance_km:float
46
+ hour:str
47
+ hours_diff_bet_trans:int
48
+ amt:float
49
+ @app.post('/predict')
50
+ async def predict(data: fraudinput,model:str =Query(...)):
51
+ print('data: %s' % data)
52
+ data=data.dict()
53
+ enc_data=enc.transform([data])
54
+ print('model:'+model)
55
+ if model == 'xgboost':
56
+ prediction=xgb_model.predict(enc_data)
57
+ elif model == 'randomforest':
58
+ prediction=rf_model.predict(enc_data)
59
+ else:
60
+ return {'error': 'Invalid model selected'}
61
+ print("prediction:",prediction[0])
62
+ return {"prediction":int(prediction[0])}
63
+
64
+ #if __name__ == '__main__':
65
+ #uvicorn.run(app, host='127.0.0.1', port=8000)
66
+
67
+
68
+
69
+ #uvicorn.run(app, host="0.0.0.0", port=8000)
70
+
71
+
docker-compose.yml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ gradio:
5
+ build:
6
+ context: .
7
+ dockerfile: Dockerfile
8
+ ports:
9
+ - "7860:7860"
10
+ environment:
11
+ - PYTHONUNBUFFERED=1
12
+ command: python gradio_app.py
13
+ api:
14
+ build:
15
+ context: .
16
+ dockerfile: Dockerfile
17
+ ports:
18
+ - "8000:8000"
19
+ environment:
20
+ - PYTHONUNBUFFERED=1
21
+ command: uvicorn app:app --host 0.0.0.0 --port 8000
22
+ <<<<<<< Updated upstream
23
+ =======
24
+
25
+ >>>>>>> Stashed changes
docker_app.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import gradio as gr
3
+ import requests
4
+ from features import category_names,job_names
5
+ from PIL import Image
6
+ #import uvicorn
7
+ #import threading
8
+ #from app import app
9
+ #import psutil
10
+
11
+
12
+ def close_port(port):
13
+ for conn in psutil.net_connections(kind='inet'):
14
+ if conn.laddr.port == port:
15
+ print(f"Closing port {port} by terminating PID {conn.pid}")
16
+ process = psutil.Process(conn.pid)
17
+ process.terminate()
18
+
19
+
20
+ """
21
+ def run_fastapi():
22
+ try:
23
+ uvicorn.run(app, host="0.0.0.0", port=8000)
24
+ except Exception as e:
25
+ print(f'Error running fastapi:{e}')
26
+ close_port(8000)
27
+
28
+
29
+ fastapi_thread = threading.Thread(target=run_fastapi)
30
+ fastapi_thread.daemon = True
31
+ fastapi_thread.start()
32
+ time.sleep(2)
33
+ """
34
+
35
+ def predict_fraud(cc_freq, job, age, gender_M, category, distance_km, hour, hours_diff_bet_trans, amt, model):
36
+ def map_time_of_day(hour):
37
+ if 0 <= hour <= 4:
38
+ return 'night'
39
+ elif 5 <= hour <= 11:
40
+ return 'morning'
41
+ elif 12 <= hour <= 20:
42
+ return 'afternoon'
43
+ else:
44
+ return 'night'
45
+
46
+ def cc_freq_classes(x):
47
+ for idx, val in enumerate(list(range(800, 10000, 800))):
48
+ if x < val:
49
+ return idx + 1
50
+
51
+ cc_freq_class=cc_freq_classes(cc_freq)
52
+ hour = map_time_of_day(hour)
53
+
54
+ input_data = {
55
+ 'cc_freq': cc_freq,
56
+ 'cc_freq_class': cc_freq_class,
57
+ 'job': job,
58
+ 'age': age,
59
+ 'gender_M': 1 if gender_M == 'Male' else 0,
60
+ 'category': category,
61
+ 'distance_km': distance_km,
62
+ 'hour': hour,
63
+ 'hours_diff_bet_trans': hours_diff_bet_trans,
64
+ 'amt': amt
65
+ }
66
+
67
+ try:
68
+ response = requests.post(f'http://0.0.0.0:8000/predict?model={model.lower()}', json=input_data)
69
+ response.raise_for_status()
70
+ if response.status_code == 200:
71
+ prediction = response.json()
72
+ return 'This Transaction is legitimate.' if prediction['prediction'] == 0 else 'This Transaction is not legitimate.'
73
+ except requests.exceptions.RequestException as e:
74
+ return f"Error: {e}"
75
+
76
+ # Define the input components
77
+ theme = gr.themes.Base(
78
+ primary_hue="teal",
79
+ neutral_hue="sky",
80
+ radius_size="lg",
81
+ ).set(
82
+ body_text_weight='300',
83
+ shadow_drop_lg='*button_shadow_hover',
84
+ shadow_inset='*shadow_drop_lg'
85
+ )
86
+
87
+ js= """
88
+ function createGradioAnimation() {
89
+ var container = document.createElement('div');
90
+ container.id = 'gradio-animation';
91
+ container.style.fontSize = '2em';
92
+ container.style.fontWeight = 'bold';
93
+ container.style.textAlign = 'center';
94
+ container.style.marginBottom = '20px';
95
+
96
+ var text = 'Credit Card Fraud Detection';
97
+ var totalDuration = 2000; // Total duration for the whole animation
98
+ var animationDelay = totalDuration / text.length; // Delay between each letter animation
99
+
100
+ for (var i = 0; i < text.length; i++) {
101
+ (function(i){
102
+ setTimeout(function(){
103
+ var letter = document.createElement('span');
104
+ letter.style.opacity = '0';
105
+ letter.style.transition = 'opacity 0.7s ease-in-out'; // Smoother transition
106
+ letter.innerText = text[i];
107
+
108
+ container.appendChild(letter);
109
+
110
+ setTimeout(function() {
111
+ letter.style.opacity = '1';
112
+ }, 50);
113
+ }, i * animationDelay); // Use calculated delay
114
+ })(i);
115
+ }
116
+
117
+ var gradioContainer = document.querySelector('.gradio-container');
118
+ gradioContainer.insertBefore(container, gradioContainer.firstChild);
119
+
120
+ return 'Animation created';
121
+ }
122
+
123
+ """
124
+
125
+ callback = gr.CSVLogger()
126
+ default_img=Image.open('static/images/creditcard.jpg')
127
+ with gr.Blocks(theme=theme,js=js) as interface:
128
+
129
+ gr.Image( value=default_img,show_download_button=False)
130
+ with gr.Tab('predict',):
131
+ with gr.Row():
132
+ with gr.Column():
133
+ cc_freq = gr.Number(label="Credit Card Frequency")
134
+ job = gr.Dropdown(job_names, label="Job")
135
+ age = gr.Slider(minimum=0, maximum=100, step=1, label="Age")
136
+ gender_M = gr.Radio(['Male', 'Female'], label="Gender")
137
+ category = gr.Dropdown(category_names, label="Category")
138
+ distance_km = gr.Number(label="Distance (km)")
139
+ hour = gr.Slider(minimum=0, maximum=24, step=1, label="Hour")
140
+ hours_diff_bet_trans = gr.Number(label="Hours Difference Between Transactions")
141
+ amt = gr.Number(label="Amount")
142
+ model_choice = gr.Radio(['XGBoost', 'RandomForest'], label="Choose Model", )
143
+ with gr.Column():
144
+ output = gr.Label(label="Prediction")
145
+ with gr.Row():
146
+ predict_button = gr.Button("Predict")
147
+ flag_button = gr.Button('Flag')
148
+
149
+ callback.setup([cc_freq, job, age, gender_M, category, distance_km, hour, hours_diff_bet_trans, amt, model_choice],
150
+ "log")
151
+
152
+ predict_button.click(fn=predict_fraud,
153
+ inputs=[cc_freq, job, age, gender_M, category, distance_km, hour, hours_diff_bet_trans, amt,
154
+ model_choice], outputs=output)
155
+ flag_button.click(lambda *args: callback.flag(args),
156
+ [cc_freq, job, age, gender_M, category, distance_km, hour, hours_diff_bet_trans, amt,
157
+ model_choice], None, preprocess=False)
158
+ with gr.Tab('About'):
159
+ with open('about.md', 'r') as about:
160
+ gr.Markdown(about.read(),line_breaks=True,header_links=True)
161
+
162
+
163
+
164
+ if __name__ == "__main__":
165
+ interface.launch(share=True)
features.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ =['category_names','job_names']
2
+ category_names=['misc_net', 'gas_transport', 'kids_pets', 'home', 'shopping_net',
3
+ 'food_dining', 'personal_care', 'grocery_pos', 'entertainment',
4
+ 'shopping_pos', 'misc_pos', 'travel', 'health_fitness',
5
+ 'grocery_net']
6
+
7
+ job_names=['Information systems manager', 'Secondary school teacher',
8
+ "Barrister's clerk", "Politician's assistant",
9
+ 'Horticulturist, commercial', 'Programmer, applications',
10
+ 'Television camera operator', 'Call centre manager',
11
+ 'Chief Marketing Officer', 'Buyer, industrial',
12
+ 'Armed forces logistics/support/administrative officer',
13
+ 'Pilot, airline', 'Therapist, horticultural', 'Dancer',
14
+ 'Ceramics designer', 'Naval architect', 'Engineer, agricultural',
15
+ 'Health service manager', 'Sport and exercise psychologist',
16
+ 'Forensic psychologist', 'Exhibition designer',
17
+ "Nurse, children's", 'Soil scientist', 'Prison officer',
18
+ 'Economist', 'Copywriter, advertising', 'Television floor manager',
19
+ 'Lecturer, higher education', 'Sales professional, IT',
20
+ 'Exhibitions officer, museum/gallery', 'Freight forwarder',
21
+ 'Engineering geologist', 'Surveyor, hydrographic',
22
+ 'Trade mark attorney', 'Public relations account executive',
23
+ 'Engineer, site', 'Race relations officer', 'Podiatrist',
24
+ 'Clothing/textile technologist', 'Retail merchandiser',
25
+ 'Engineer, civil (contracting)', 'Make',
26
+ 'Advertising account executive',
27
+ 'Armed forces training and education officer',
28
+ 'Special educational needs teacher', 'Special effects artist',
29
+ 'Corporate investment banker', 'Immunologist', 'Barrister',
30
+ 'Designer, interior/spatial', 'Early years teacher',
31
+ 'Chief Executive Officer', 'Mechanical engineer',
32
+ 'Administrator, education', 'Engineer, electronics',
33
+ 'Estate manager/land agent', 'Television/film/video producer',
34
+ 'Chiropodist', 'Senior tax professional/tax inspector',
35
+ 'Airline pilot', 'Engineer, petroleum', 'Materials engineer',
36
+ 'Civil engineer, contracting', 'Sales executive',
37
+ 'Editor, film/video', 'Marketing executive',
38
+ 'Historic buildings inspector/conservation officer',
39
+ 'Higher education careers adviser', 'Chief Financial Officer',
40
+ 'Editor, commissioning', 'Financial trader', 'Animal nutritionist',
41
+ 'Further education lecturer', 'Clinical research associate',
42
+ 'Writer', 'Air traffic controller', 'Engineer, automotive',
43
+ 'Tourism officer', 'Designer, industrial/product',
44
+ 'Broadcast presenter', 'Quarry manager',
45
+ 'Careers information officer', 'Cartographer',
46
+ 'Petroleum engineer', 'Aid worker', 'Database administrator',
47
+ 'Technical brewer', 'Educational psychologist',
48
+ 'Engineer, building services', 'Agricultural consultant',
49
+ 'Scientist, biomedical', 'Probation officer',
50
+ 'Conservation officer, historic buildings', 'Physiotherapist',
51
+ 'Equality and diversity officer', 'Quantity surveyor',
52
+ 'Occupational hygienist', 'Academic librarian', 'Air broker',
53
+ 'Catering manager', 'Licensed conveyancer', 'Pharmacist, hospital',
54
+ 'Television production assistant', 'Insurance underwriter',
55
+ 'English as a second language teacher', 'Music tutor',
56
+ 'Programmer, multimedia', 'Therapist, art', 'Financial adviser',
57
+ 'Media planner', 'Land/geomatics surveyor', 'Architect',
58
+ 'Set designer', 'Lawyer', 'Administrator, arts', 'Tax adviser',
59
+ 'Drilling engineer', 'Administrator',
60
+ 'Community education officer', 'IT trainer', 'IT consultant',
61
+ 'Journalist, newspaper', 'Psychologist, forensic', 'Site engineer',
62
+ 'Curator', 'Film/video editor', 'Investment banker, corporate',
63
+ 'Geochemist', 'Professor Emeritus', 'Chemical engineer',
64
+ 'Fine artist', 'Pension scheme manager', 'Systems developer',
65
+ 'Firefighter', 'Learning disability nurse', 'Network engineer',
66
+ 'Sales promotion account executive', 'Child psychotherapist',
67
+ 'Building surveyor', 'Energy engineer', 'Human resources officer',
68
+ 'Metallurgist', 'Pharmacist, community', 'Tour manager',
69
+ 'Paramedic', 'Arboriculturist', 'Dispensing optician',
70
+ 'Engineer, production', 'Engineer, control and instrumentation',
71
+ 'Embryologist, clinical', 'Paediatric nurse', 'Radio producer',
72
+ 'Applications developer', 'Local government officer',
73
+ 'Chief Strategy Officer', 'Sub', 'Orthoptist', 'Lexicographer',
74
+ 'Press sub', 'Chief Operating Officer', 'Geoscientist',
75
+ 'Environmental consultant', 'Commissioning editor',
76
+ 'Cytogeneticist', 'Chartered legal executive (England and Wales)',
77
+ 'Civil Service fast streamer', 'Presenter, broadcasting',
78
+ 'Fitness centre manager', 'Development worker, community',
79
+ 'Wellsite geologist', 'Ambulance person', 'Psychotherapist',
80
+ 'Gaffer', 'Radio broadcast assistant',
81
+ 'Training and development officer', 'Seismic interpreter',
82
+ 'Counsellor', 'Librarian, public', 'Personnel officer',
83
+ 'Magazine features editor', 'Horticultural consultant',
84
+ 'Buyer, retail', 'Aeronautical engineer',
85
+ 'Education officer, museum', 'Scientist, research (medical)',
86
+ 'Toxicologist', 'Town planner', 'Scientist, research (maths)',
87
+ 'Jewellery designer', 'Hotel manager', 'Facilities manager',
88
+ 'Plant breeder/geneticist', 'Civil Service administrator',
89
+ 'Occupational therapist', 'Diagnostic radiographer',
90
+ 'Conservator, museum/gallery', 'Intelligence analyst',
91
+ 'Warden/ranger', 'Animal technologist', 'Furniture designer',
92
+ 'Claims inspector/assessor', 'Industrial/product designer',
93
+ 'Glass blower/designer', 'Armed forces technical officer',
94
+ 'Nature conservation officer', 'Manufacturing engineer',
95
+ 'Exercise physiologist', 'Designer, textile',
96
+ 'Geophysicist/field seismologist', 'Surveyor, land/geomatics',
97
+ 'Risk analyst', 'Development worker, international aid',
98
+ 'Audiological scientist', 'Hydrologist', 'Engineer, land',
99
+ 'Engineer, biomedical', 'Teacher, secondary school',
100
+ 'Building control surveyor',
101
+ 'English as a foreign language teacher', 'Leisure centre manager',
102
+ 'Emergency planning/management officer', 'Chartered accountant',
103
+ 'Chartered public finance accountant', 'Public affairs consultant',
104
+ 'Control and instrumentation engineer',
105
+ 'Trading standards officer', 'Archaeologist',
106
+ 'Designer, exhibition/display', 'Engineer, maintenance',
107
+ 'Insurance broker', 'Research scientist (physical sciences)',
108
+ 'Science writer', 'Psychiatrist', 'Video editor',
109
+ 'Horticultural therapist', 'Advertising account planner',
110
+ 'Music therapist', 'Physiological scientist',
111
+ 'Teacher, primary school', 'Doctor, general practice',
112
+ 'Physicist, medical', 'Dealer', 'Therapist, occupational',
113
+ 'Futures trader', 'Accountant, chartered public finance',
114
+ 'Electrical engineer', 'Commercial horticulturist',
115
+ 'Pensions consultant', 'Records manager', 'Doctor, hospital',
116
+ 'Engineer, broadcasting (operations)', 'Colour technologist',
117
+ 'Environmental health practitioner', 'Theatre manager',
118
+ 'Comptroller', 'Optician, dispensing',
119
+ 'Social research officer, government',
120
+ 'Production assistant, radio', 'Community pharmacist',
121
+ 'Production engineer', 'Regulatory affairs officer',
122
+ 'Statistician', 'Administrator, local government',
123
+ 'Telecommunications researcher', 'Research scientist (medical)',
124
+ 'Administrator, charities/voluntary organisations',
125
+ 'General practice doctor', 'Rural practice surveyor',
126
+ 'Education administrator', 'Multimedia programmer',
127
+ 'Heritage manager', 'TEFL teacher', 'Phytotherapist',
128
+ 'Museum education officer', 'Designer, ceramics/pottery',
129
+ 'Mudlogger', 'Police officer', 'Research officer, trade union',
130
+ 'Retail buyer', 'Accounting technician',
131
+ 'Dance movement psychotherapist', 'Theatre director',
132
+ 'Waste management officer', 'Web designer', 'Nurse, mental health',
133
+ 'Herpetologist', 'Tourist information centre manager',
134
+ 'Radiographer, therapeutic', 'Designer, jewellery',
135
+ 'Scientist, physiological', 'Investment analyst',
136
+ 'Insurance risk surveyor', 'Teacher, special educational needs',
137
+ 'Product designer', 'Librarian, academic', 'Mining engineer',
138
+ 'Stage manager', 'Investment banker, operational',
139
+ 'Geneticist, molecular', 'Medical physicist',
140
+ 'Product/process development scientist',
141
+ 'Arts development officer', 'Charity fundraiser', 'Land',
142
+ 'Teaching laboratory technician', 'Acupuncturist',
143
+ 'Transport planner', 'Forest/woodland manager', 'Charity officer',
144
+ 'Herbalist', 'Industrial buyer', 'Medical sales representative',
145
+ 'Landscape architect', 'Teacher, early years/pre',
146
+ 'Event organiser', 'Conservator, furniture',
147
+ 'Hydrographic surveyor', 'Producer, radio',
148
+ 'Psychologist, counselling', 'Designer, furniture',
149
+ 'Theme park manager', 'Hospital pharmacist',
150
+ 'Volunteer coordinator', 'Pathologist',
151
+ 'Psychologist, sport and exercise', 'Health visitor',
152
+ 'Programme researcher, broadcasting/film/video',
153
+ 'Counselling psychologist', 'Operations geologist',
154
+ 'Chief of Staff', 'Engineer, communications', 'Engineer, mining',
155
+ 'Biochemist, clinical',
156
+ 'Scientist, clinical (histocompatibility and immunogenetics)',
157
+ 'Medical secretary', 'Hospital doctor', 'Location manager',
158
+ 'Mental health nurse', 'Scientist, audiological',
159
+ 'Careers adviser', 'Therapist, drama', 'Accountant, chartered',
160
+ 'Social researcher', 'Solicitor', 'Travel agency manager',
161
+ 'Scientist, marine', 'Artist', 'Surveyor, minerals',
162
+ 'Patent attorney', 'Chartered loss adjuster',
163
+ 'Scientific laboratory technician',
164
+ 'Interior and spatial designer', 'Medical technical officer',
165
+ 'Broadcast engineer', 'Fisheries officer', 'Engineer, water',
166
+ 'Commercial/residential surveyor', 'Engineer, structural',
167
+ 'Communications engineer',
168
+ 'Teacher, English as a foreign language', 'Magazine journalist',
169
+ 'Community development worker', 'Legal secretary', 'Optometrist',
170
+ 'Psychologist, clinical', 'Software engineer', 'Oncologist',
171
+ 'Research officer, political party', 'Information officer',
172
+ 'Cabin crew', 'Geologist, engineering',
173
+ 'Outdoor activities/education manager', 'Textile designer',
174
+ 'Learning mentor', 'Minerals surveyor', 'Clinical biochemist',
175
+ 'Maintenance engineer', 'Market researcher', 'Health physicist',
176
+ 'Biomedical engineer', 'Associate Professor',
177
+ 'Electronics engineer', 'Engineer, civil (consulting)',
178
+ 'Contractor', 'Engineer, materials', 'Visual merchandiser',
179
+ 'Production manager', 'Structural engineer',
180
+ 'Amenity horticulturist', 'Osteopath', 'Press photographer',
181
+ 'Purchasing manager', 'Camera operator', 'Advice worker',
182
+ 'Insurance claims handler', 'Furniture conservator/restorer',
183
+ 'Manufacturing systems engineer', 'Copy',
184
+ 'Lecturer, further education', 'Animator', 'Surveyor, mining',
185
+ 'Retail manager', 'Therapist, music', 'Primary school teacher',
186
+ 'Archivist', 'Health and safety adviser',
187
+ 'Research scientist (life sciences)', 'Veterinary surgeon',
188
+ 'Data scientist', 'Media buyer',
189
+ 'Museum/gallery exhibitions officer',
190
+ 'Health promotion specialist', 'Farm manager', 'Warehouse manager',
191
+ 'Surgeon', 'Illustrator', 'Biomedical scientist',
192
+ 'Logistics and distribution manager', 'Geologist, wellsite',
193
+ 'Operational investment banker', 'Private music teacher',
194
+ 'Occupational psychologist', 'Building services engineer',
195
+ 'Bookseller', 'Engineer, technical sales', 'Neurosurgeon',
196
+ 'Museum/gallery conservator', 'Garment/textile technologist',
197
+ 'Systems analyst', 'Therapist, sports', 'Art gallery manager',
198
+ 'Retail banker', 'Radiographer, diagnostic',
199
+ 'Editor, magazine features', 'Teacher, adult education',
200
+ 'Water engineer', 'Clinical cytogeneticist', 'Air cabin crew',
201
+ 'Oceanographer', 'Research scientist (maths)',
202
+ 'Psychotherapist, child', 'Public house manager',
203
+ 'Chief Technology Officer', 'Planning and development surveyor',
204
+ 'Pharmacologist', 'Scientist, research (physical sciences)',
205
+ 'Ecologist', 'Tree surgeon', 'Engineer, drilling', 'Art therapist',
206
+ 'Architectural technologist', 'Equities trader',
207
+ 'Production assistant, television', 'Field seismologist',
208
+ 'Musician', 'Designer, multimedia', 'Nutritional therapist',
209
+ 'Designer, television/film set', 'Tax inspector',
210
+ 'Public librarian', 'Loss adjuster, chartered',
211
+ 'Accountant, chartered certified', 'Merchandiser, retail',
212
+ 'Sports development officer', 'Interpreter', 'Homeopath',
213
+ 'Engineer, aeronautical', 'Analytical chemist', 'Energy manager',
214
+ 'Community arts worker', 'Management consultant',
215
+ 'Public relations officer', 'Ship broker', 'Chemist, analytical',
216
+ 'Environmental manager', 'Product manager',
217
+ 'Education officer, community', 'Field trials officer',
218
+ 'Restaurant manager, fast food', 'Broadcast journalist',
219
+ 'Secretary/administrator', 'Company secretary',
220
+ 'Sports administrator', 'Producer, television/film/video',
221
+ 'Barista', 'Advertising copywriter', 'Immigration officer',
222
+ 'Hydrogeologist', 'Clinical psychologist', 'Solicitor, Scotland',
223
+ 'Contracting civil engineer', 'Engineer, manufacturing',
224
+ 'Psychiatric nurse', 'Water quality scientist',
225
+ 'Surveyor, rural practice', 'Environmental education officer',
226
+ 'Operational researcher']
gradio_app.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import threading
3
+ import uvicorn
4
+ import gradio as gr
5
+ import requests
6
+ from features import job_names,category_names
7
+ from app import app
8
+ import psutil
9
+ from PIL import Image
10
+
11
+
12
+ def close_port(port):
13
+ for conn in psutil.net_connections(kind='inet'):
14
+ if conn.laddr.port == port:
15
+ print(f"Closing port {port} by terminating PID {conn.pid}")
16
+ process = psutil.Process(conn.pid)
17
+ process.terminate()
18
+
19
+
20
+ def run_fastapi():
21
+ try:
22
+ uvicorn.run(app, host="0.0.0.0", port=8000)
23
+ except Exception as e:
24
+ print(f'Error running fastapi:{e}')
25
+ close_port(8000)
26
+
27
+
28
+ fastapi_thread = threading.Thread(target=run_fastapi)
29
+ fastapi_thread.daemon = True
30
+ fastapi_thread.start()
31
+ time.sleep(2)
32
+
33
+ def predict_fraud(cc_freq, job, age, gender_M, category, distance_km, hour, hours_diff_bet_trans, amt, model):
34
+ def map_time_of_day(hour):
35
+ if 0 <= hour <= 4:
36
+ return 'night'
37
+ elif 5 <= hour <= 11:
38
+ return 'morning'
39
+ elif 12 <= hour <= 20:
40
+ return 'afternoon'
41
+ else:
42
+ return 'night'
43
+
44
+ def cc_freq_classes(x):
45
+ for idx, val in enumerate(list(range(800, 10000, 800))):
46
+ if x < val:
47
+ return idx + 1
48
+
49
+ cc_freq_class=cc_freq_classes(cc_freq)
50
+ hour = map_time_of_day(hour)
51
+
52
+ input_data = {
53
+ 'cc_freq': cc_freq,
54
+ 'cc_freq_class': cc_freq_class,
55
+ 'job': job,
56
+ 'age': age,
57
+ 'gender_M': 1 if gender_M == 'Male' else 0,
58
+ 'category': category,
59
+ 'distance_km': distance_km,
60
+ 'hour': hour,
61
+ 'hours_diff_bet_trans': hours_diff_bet_trans,
62
+ 'amt': amt
63
+ }
64
+
65
+ try:
66
+ response = requests.post(f'http://0.0.0.0:8000/predict?model={model.lower()}', json=input_data)
67
+ response.raise_for_status()
68
+ if response.status_code == 200:
69
+ prediction = response.json()
70
+ return 'This Transaction is legitimate.' if prediction['prediction'] == 0 else 'This Transaction is not legitimate.'
71
+ except requests.exceptions.RequestException as e:
72
+ return f"Error: {e}"
73
+
74
+ theme = gr.themes.Base(
75
+ primary_hue="teal",
76
+ neutral_hue="sky",
77
+ radius_size="lg",
78
+ ).set(
79
+ body_text_weight='300',
80
+ shadow_drop_lg='*button_shadow_hover',
81
+ shadow_inset='*shadow_drop_lg'
82
+ )
83
+
84
+ js= """
85
+ function createGradioAnimation() {
86
+ var container = document.createElement('div');
87
+ container.id = 'gradio-animation';
88
+ container.style.fontSize = '2em';
89
+ container.style.fontWeight = 'bold';
90
+ container.style.textAlign = 'center';
91
+ container.style.marginBottom = '20px';
92
+
93
+ var text = 'Credit Card Fraud Detection';
94
+ var totalDuration = 2000; // Total duration for the whole animation
95
+ var animationDelay = totalDuration / text.length; // Delay between each letter animation
96
+
97
+ for (var i = 0; i < text.length; i++) {
98
+ (function(i){
99
+ setTimeout(function(){
100
+ var letter = document.createElement('span');
101
+ letter.style.opacity = '0';
102
+ letter.style.transition = 'opacity 0.7s ease-in-out'; // Smoother transition
103
+ letter.innerText = text[i];
104
+
105
+ container.appendChild(letter);
106
+
107
+ setTimeout(function() {
108
+ letter.style.opacity = '1';
109
+ }, 50);
110
+ }, i * animationDelay); // Use calculated delay
111
+ })(i);
112
+ }
113
+
114
+ var gradioContainer = document.querySelector('.gradio-container');
115
+ gradioContainer.insertBefore(container, gradioContainer.firstChild);
116
+
117
+ return 'Animation created';
118
+ }
119
+
120
+ """
121
+
122
+ callback = gr.CSVLogger()
123
+ default_img=Image.open('static/images/creditcard.jpg')
124
+ with gr.Blocks(theme=theme,js=js) as interface:
125
+
126
+ gr.Image( value=default_img,show_download_button=False)
127
+ with gr.Tab('predict',):
128
+ with gr.Row():
129
+ with gr.Column():
130
+ cc_freq = gr.Number(label="Credit Card Frequency")
131
+ job = gr.Dropdown(job_names, label="Job")
132
+ age = gr.Slider(minimum=0, maximum=100, step=1, label="Age")
133
+ gender_M = gr.Radio(['Male', 'Female'], label="Gender")
134
+ category = gr.Dropdown(category_names, label="Category")
135
+ distance_km = gr.Number(label="Distance (km)")
136
+ hour = gr.Slider(minimum=0, maximum=24, step=1, label="Hour")
137
+ hours_diff_bet_trans = gr.Number(label="Hours Difference Between Transactions")
138
+ amt = gr.Number(label="Amount")
139
+ model_choice = gr.Radio(['XGBoost', 'RandomForest'], label="Choose Model", )
140
+ with gr.Column():
141
+ output = gr.Label(label="Prediction")
142
+ with gr.Row():
143
+ predict_button = gr.Button("Predict")
144
+ flag_button = gr.Button('Flag')
145
+
146
+ callback.setup([cc_freq, job, age, gender_M, category, distance_km, hour, hours_diff_bet_trans, amt, model_choice],
147
+ "log")
148
+
149
+ predict_button.click(fn=predict_fraud,
150
+ inputs=[cc_freq, job, age, gender_M, category, distance_km, hour, hours_diff_bet_trans, amt,
151
+ model_choice], outputs=output)
152
+ flag_button.click(lambda *args: callback.flag(args),
153
+ [cc_freq, job, age, gender_M, category, distance_km, hour, hours_diff_bet_trans, amt,
154
+ model_choice], None, preprocess=False)
155
+ with gr.Tab('About'):
156
+ with open('about.md', 'r') as about:
157
+ gr.Markdown(about.read(),line_breaks=True,header_links=True)
158
+
159
+
160
+
161
+ if __name__ == "__main__":
162
+ interface.launch(share=True)
163
+
164
+ fastapi_thread.join()
log/log.csv ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Credit Card Frequency,Job,Age,Gender,Category,Distance (km),Hour,Hours Difference Between Transactions,Amount,Choose Model,flag,username,timestamp
2
+ 0,,0,,,0,0,0,0,,,,2024-06-25 21:41:43.449715
3
+ 0,,0,,,0,0,0,0,,,,2024-06-25 21:41:44.328213
4
+ 75,Secondary school teacher,54,Female,shopping_net,75,9,90,20,RandomForest,,,2024-06-25 21:42:48.591947
5
+ 75,Secondary school teacher,54,Female,shopping_net,75,9,90,20,RandomForest,,,2024-06-25 21:42:49.917615
6
+ 75,Secondary school teacher,54,Female,shopping_net,75,9,90,20,RandomForest,,,2024-06-25 21:42:52.306206
7
+ 75,Secondary school teacher,54,Female,shopping_net,75,9,90,20,RandomForest,,,2024-06-25 21:42:53.084280
8
+ 75,Secondary school teacher,54,Female,shopping_net,75,9,90,20,RandomForest,,,2024-06-25 21:42:53.365504
9
+ 75,Secondary school teacher,54,Female,shopping_net,75,9,90,20,RandomForest,,,2024-06-25 21:42:53.880258
10
+ 75,Secondary school teacher,54,Female,shopping_net,75,9,90,20,RandomForest,,,2024-06-25 21:42:54.532432
11
+ 75,Secondary school teacher,54,Female,shopping_net,75,9,90,20,RandomForest,,,2024-06-25 21:43:01.396615
12
+ 77,Politician's assistant,40,Female,shopping_net,88,4,44,33,RandomForest,,,2024-06-25 22:01:15.956971
13
+ 77,Secondary school teacher,47,Female,misc_net,88,9,28,99,XGBoost,,,2024-06-25 22:08:35.317144
14
+ 77,Television camera operator,37,Female,travel,888,24,90,9999,XGBoost,,,2024-06-26 13:59:42.520861
15
+ 77,Television camera operator,37,Female,travel,888,24,90,9999,XGBoost,,,2024-06-26 13:59:44.857070
model/rf_model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cfafbf7714e7b665842d4e00a46cd97e443ad66e6a2c24c73cf90bdf9f7f8cfc
3
+ size 151012655
model/xgb_model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a0ce769e8a1638c08684bae396e421d6af243b607bfedcbbf767eed8c2920dea
3
+ size 386191
notebook/Credit card fraud detection.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ pillow
2
+ fastapi
3
+ uvicorn
4
+ gradio
5
+ requests
6
+ psutil
7
+ numpy
8
+ joblib
9
+ xgboost
10
+ category-encoders
11
+ scikit-learn
static/images/api.png ADDED
static/images/api1.png ADDED
static/images/creditcard.jpg ADDED
static/images/creditcard1.jpg ADDED