File size: 5,514 Bytes
2c61e97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
import streamlit as st
import joblib
import pandas as pd
import numpy as np
from datetime import datetime

# ---------------- Page Configuration ----------------
st.set_page_config(
    page_title="๐Ÿ›ก๏ธ Fraud Detection",
    page_icon="๐Ÿ›ก๏ธ",
    layout="wide",
    initial_sidebar_state="expanded"
)

# ---------------- Custom Styling ----------------
st.markdown("""
    <style>
    .title {
        text-align: center;
        font-size: 2.5rem;
        font-weight: 700;
        color: #222831;
        margin-bottom: 10px;
    }
    .subheader {
        text-align: center;
        font-size: 1.2rem;
        color: #393E46;
        margin-bottom: 30px;
    }
    .section {
        background-color: #f1f5f9;
        padding: 1.5rem;
        border-radius: 10px;
        margin-top: 1rem;
    }
    .prediction {
        padding: 1rem;
        margin: 1rem 0;
        # background-color: #e0f7fa;
        border-left: 8px solid #00796b;
        border-radius: 6px;
    }
    .fraud {
        border-left-color: #c62828;
        # background-color: #ffebee;
    }
    </style>
""", unsafe_allow_html=True)

# ---------------- Load Models and Encoders ----------------
@st.cache_resource
def load_artifacts():
    scaler = joblib.load('scaler.pkl')
    encoders = joblib.load('label_encoders.pkl')
    models = {
        'Logistic Regression': joblib.load('Logistic Regression_model.pkl'),
        'Decision Tree': joblib.load('Decision Tree_model.pkl'),
        'Random Forest': joblib.load('Random Forest_model.pkl'),
        'XGBoost': joblib.load('xgboost_model.pkl')
    }
    return scaler, encoders, models

scaler, encoders, models = load_artifacts()

feature_order = [
    'cc_num', 'merchant', 'category', 'amt', 'gender', 'city', 'state', 'zip', 'lat', 'long',
    'city_pop', 'job', 'unix_time', 'merch_lat', 'merch_long', 'trans_hour', 'trans_day_of_week'
]

categorical_cols = ['merchant', 'category', 'gender', 'city', 'state', 'job']

# ---------------- Header ----------------
st.markdown('<div class="title">๐Ÿ›ก๏ธ Credit Card Fraud Detection</div>', unsafe_allow_html=True)
st.markdown('<div class="subheader">Predict whether a transaction is fraudulent using pre-trained ML models</div>', unsafe_allow_html=True)

# ---------------- Input Form ----------------
with st.form("fraud_form"):
    st.markdown("### ๐Ÿ“ Transaction Details")
    col1, col2 = st.columns(2)

    with col1:
        cc_num = st.number_input("๐Ÿ’ณ Credit Card Number", value=123456789.0)
        amt = st.number_input("๐Ÿ’ฐ Transaction Amount", value=100.0)
        zip_code = st.number_input("๐Ÿ“ฎ ZIP Code", value=10001.0)
        lat = st.number_input("๐ŸŒ Latitude", value=40.0)
        long = st.number_input("๐ŸŒ Longitude", value=-75.0)
        city_pop = st.number_input("๐Ÿ™๏ธ City Population", value=8500000.0)

    with col2:
        unix_time = st.number_input("๐Ÿ•’ Unix Timestamp", value=float(datetime.now().timestamp()))
        merch_lat = st.number_input("๐Ÿช Merchant Latitude", value=40.0)
        merch_long = st.number_input("๐Ÿช Merchant Longitude", value=-75.0)
        trans_hour = st.slider("โฐ Transaction Hour", 0, 23, 12)
        trans_day = st.slider("๐Ÿ“… Day of Week", 0, 6, 3)

    st.markdown("### ๐Ÿ”ค Categorical Details")
    merchant = st.text_input("Merchant", value="fraud_Rippin, Kub and Mann")
    category = st.selectbox("Category", encoders['category'].classes_.tolist())
    gender = st.selectbox("Gender", encoders['gender'].classes_.tolist())
    city = st.text_input("City", value="New York")
    state = st.selectbox("State", encoders['state'].classes_.tolist())
    job = st.selectbox("Job", encoders['job'].classes_.tolist())

    submit = st.form_submit_button("๐Ÿ” Predict")

# ---------------- Prediction Section ----------------
if submit:
    try:
        sample_input = {
            'cc_num': cc_num,
            'merchant': encoders['merchant'].transform([merchant])[0] if merchant in encoders['merchant'].classes_ else 0,
            'category': encoders['category'].transform([category])[0],
            'amt': amt,
            'gender': encoders['gender'].transform([gender])[0],
            'city': encoders['city'].transform([city])[0] if city in encoders['city'].classes_ else 0,
            'state': encoders['state'].transform([state])[0],
            'zip': zip_code,
            'lat': lat,
            'long': long,
            'city_pop': city_pop,
            'job': encoders['job'].transform([job])[0],
            'unix_time': unix_time,
            'merch_lat': merch_lat,
            'merch_long': merch_long,
            'trans_hour': trans_hour,
            'trans_day_of_week': trans_day
        }

        input_df = pd.DataFrame([sample_input], columns=feature_order)
        input_scaled = scaler.transform(input_df)

        st.markdown("### ๐Ÿ“Š Prediction Results")
        for name, model in models.items():
            pred = model.predict(input_scaled)[0]
            prob = model.predict_proba(input_scaled)[0][1]
            fraud = pred == 1

            css_class = "fraud prediction" if fraud else "prediction"
            label = "๐Ÿšจ Fraudulent" if fraud else "โœ… Legitimate"

            st.markdown(f"""
                <div class="{css_class}">
                    <strong>{name}</strong><br>
                    {label} โ€” <b>{prob:.2%}</b> probability of fraud
                </div>
            """, unsafe_allow_html=True)

    except Exception as e:
        st.error(f"Prediction failed: {e}")