jarif commited on
Commit
a12ca3f
·
verified ·
1 Parent(s): c50d496

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +327 -320
src/streamlit_app.py CHANGED
@@ -1,321 +1,328 @@
1
- import streamlit as st
2
- import pandas as pd
3
- import numpy as np
4
- import torch
5
- import torch.nn as nn
6
- import torch.nn.functional as F
7
- from torch_geometric.nn import GATConv
8
- from torch_geometric.data import Data
9
- import os
10
-
11
- # Define FraudGNN class
12
- class FraudGNN(nn.Module):
13
- def __init__(self, input_dim, hidden_dim, output_dim):
14
- super(FraudGNN, self).__init__()
15
- self.conv1 = GATConv(input_dim, hidden_dim, heads=4, dropout=0.3)
16
- self.conv2 = GATConv(hidden_dim * 4, hidden_dim, heads=1, dropout=0.3)
17
- self.fc = nn.Linear(hidden_dim, output_dim)
18
-
19
- def forward(self, data):
20
- x, edge_index = data.x, data.edge_index
21
- x = F.relu(self.conv1(x, edge_index))
22
- x = F.dropout(x, p=0.3, training=self.training)
23
- x = F.relu(self.conv2(x, edge_index))
24
- x = self.fc(x)
25
- return torch.sigmoid(x).squeeze()
26
-
27
- # Device configuration
28
- device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
29
-
30
- # Load model and threshold
31
- try:
32
- model_path = 'fraud_gnn_model.pth'
33
- threshold_path = 'optimal_threshold.txt'
34
-
35
- if not os.path.exists(model_path):
36
- raise FileNotFoundError(f"Model file {model_path} not found.")
37
- if not os.path.exists(threshold_path):
38
- raise FileNotFoundError(f"Threshold file {threshold_path} not found.")
39
-
40
- model = FraudGNN(input_dim=7, hidden_dim=16, output_dim=1).to(device)
41
- model.load_state_dict(torch.load(model_path, map_location=device))
42
- model.eval()
43
-
44
- with open(threshold_path, 'r') as f:
45
- threshold = float(f.read())
46
- except Exception as e:
47
- st.error(f"Error loading model or threshold: {e}")
48
- model = None
49
- threshold = 0.5
50
-
51
- # City and state mappings
52
- city_mapping = {
53
- 'Atlanta': 0, 'Bronx': 1, 'Brooklyn': 2, 'Chicago': 3, 'Dallas': 4, 'Houston': 5,
54
- 'Indianapolis': 6, 'Las Vegas': 7, 'Los Angeles': 8, 'Louisville': 9, 'Miami': 10,
55
- 'Minneapolis': 11, 'New York': 12, 'ONLINE': 13, 'Orlando': 14, 'Philadelphia': 15,
56
- 'San Antonio': 16, 'San Diego': 17, 'San Francisco': 18, 'Tucson': 19, 'other': 20
57
- }
58
- state_mapping = {
59
- 'AK': 0, 'AL': 1, 'AR': 2, 'AZ': 3, 'Algeria': 4, 'Antigua and Barbuda': 5, 'Argentina': 6,
60
- 'Aruba': 7, 'Australia': 8, 'Austria': 9, 'Azerbaijan': 10, 'Bahrain': 11, 'Bangladesh': 12,
61
- 'Barbados': 13, 'Belarus': 14, 'Belgium': 15, 'Belize': 16, 'Bosnia and Herzegovina': 17,
62
- 'Brazil': 18, 'CA': 19, 'CO': 20, 'CT': 21, 'Cabo Verde': 22, 'Cambodia': 23, 'Canada': 24,
63
- 'Central African Republic': 25, 'Chile': 26, 'China': 27, 'Colombia': 28, 'Costa Rica': 29,
64
- "Cote d'Ivoire": 30, 'Croatia': 31, 'Czech Republic': 32, 'DC': 33, 'DE': 34, 'Denmark': 35,
65
- 'Dominica': 36, 'Dominican Republic': 37, 'East Timor (Timor-Leste)': 38, 'Ecuador': 39,
66
- 'Egypt': 40, 'Eritrea': 41, 'Estonia': 42, 'FL': 43, 'Fiji': 44, 'Finland': 45, 'France': 46,
67
- 'GA': 47, 'Georgia': 48, 'Germany': 49, 'Ghana': 50, 'Greece': 51, 'Guatemala': 52,
68
- 'Guyana': 53, 'HI': 54, 'Haiti': 55, 'Honduras': 56, 'Hong Kong': 57, 'Hungary': 58,
69
- 'IA': 59, 'ID': 60, 'IL': 61, 'IN': 62, 'Iceland': 63, 'India': 64, 'Indonesia': 65,
70
- 'Ireland': 66, 'Israel': 67, 'Italy': 68, 'Jamaica': 69, 'Japan': 70, 'Jordan': 71,
71
- 'KS': 72, 'KY': 73, 'Kenya': 74, 'Kosovo': 75, 'Kuwait': 76, 'LA': 77, 'Latvia': 78,
72
- 'Lebanon': 79, 'Liberia': 80, 'Lithuania': 81, 'Luxembourg': 82, 'MA': 83, 'MD': 84,
73
- 'ME': 85, 'MI': 86, 'MN': 87, 'MO': 88, 'MS': 89, 'MT': 90, 'Macedonia': 91,
74
- 'Malaysia': 92, 'Malta': 93, 'Mexico': 94, 'Moldova': 95, 'Monaco': 96, 'Morocco': 97,
75
- 'Mozambique': 98, 'Myanmar (Burma)': 99, 'NC': 100, 'ND': 101, 'NE': 102, 'NH': 103,
76
- 'NJ': 104, 'NM': 105, 'NV': 106, 'NY': 107, 'Nauru': 108, 'Netherlands': 109,
77
- 'New Zealand': 110, 'Nicaragua': 111, 'Niger': 112, 'Nigeria': 113, 'Norway': 114,
78
- 'OH': 115, 'OK': 116, 'OR': 117, 'Oman': 118, 'PA': 119, 'Pakistan': 120, 'Panama': 121,
79
- 'Peru': 122, 'Philippines': 123, 'Poland': 124, 'Portugal': 125, 'RI': 126, 'Romania': 127,
80
- 'Russia': 128, 'SC': 129, 'SD': 130, 'Saudi Arabia': 131, 'Senegal': 132, 'Serbia': 133,
81
- 'Seychelles': 134, 'Singapore': 135, 'Slovakia': 136, 'Slovenia': 137, 'Somalia': 138,
82
- 'South Africa': 139, 'South Korea': 140, 'Spain': 141, 'Sri Lanka': 142, 'Sudan': 143,
83
- 'Suriname': 144, 'Sweden': 145, 'Switzerland': 146, 'Syria': 147, 'TN': 148, 'TX': 149,
84
- 'Taiwan': 150, 'Thailand': 151, 'The Bahamas': 152, 'Tunisia': 153, 'Turkey': 154,
85
- 'Tuvalu': 155, 'UT': 156, 'Uganda': 157, 'Ukraine': 158, 'United Arab Emirates': 159,
86
- 'United Kingdom': 160, 'Uruguay': 161, 'Uzbekistan': 162, 'VA': 163, 'VT': 164,
87
- 'Vatican City': 165, 'Vietnam': 166, 'WA': 167, 'WI': 168, 'WV': 169, 'WY': 170,
88
- 'Yemen': 171, 'Zimbabwe': 172
89
- }
90
-
91
- def predict_fraud(transactions):
92
- try:
93
- df = pd.DataFrame(transactions, columns=[
94
- 'Zipcode', 'Merchant_State_Code', 'User_Frequency_Per_Day',
95
- 'Time_Difference_Hours', 'Merchant_Category_Code',
96
- 'Merchant_City_Code', 'Transaction_Amount'
97
- ])
98
- node_features = torch.tensor(df.values, dtype=torch.float).to(device)
99
-
100
- edge_index = torch.empty((2, 0), dtype=torch.long).to(device)
101
-
102
- if len(df) > 1:
103
- zipcodes = node_features[:, 0].cpu().numpy()
104
- edge_list = []
105
- zipcode_threshold = 1000
106
- for i in range(len(df)):
107
- for j in range(i + 1, len(df)):
108
- if abs(zipcodes[i] - zipcodes[j]) < zipcode_threshold:
109
- edge_list.append([i, j])
110
- edge_list.append([j, i])
111
- if edge_list:
112
- edge_index = torch.tensor(edge_list, dtype=torch.long).t().contiguous().to(device)
113
-
114
- graph_data = Data(x=node_features, edge_index=edge_index).to(device)
115
-
116
- if model is None:
117
- raise ValueError("Model not loaded. Check if fraud_gnn_model.pth exists.")
118
-
119
- with torch.no_grad():
120
- out = model(graph_data)
121
- out = torch.atleast_1d(out)
122
- pred_binary = (out > threshold).float().cpu().numpy()
123
- pred_proba = out.cpu().numpy()
124
- pred_binary = np.atleast_1d(pred_binary)
125
- pred_proba = np.atleast_1d(pred_proba)
126
-
127
- return pred_binary, pred_proba
128
- except Exception as e:
129
- st.error(f"Error in predict_fraud: {e}")
130
- return None, None
131
-
132
- # Custom CSS for eye-catching design with further reduced form height
133
- st.markdown("""
134
- <style>
135
- @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap');
136
- @import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css');
137
-
138
- @keyframes glow {
139
- 0% { box-shadow: 0 0 5px rgba(52, 152, 219, 0.5); }
140
- 50% { box-shadow: 0 0 15px rgba(52, 152, 219, 0.8); }
141
- 100% { box-shadow: 0 0 5px rgba(52, 152, 219, 0.5); }
142
- }
143
- @keyframes icon-pulse {
144
- 0% { transform: scale(1); }
145
- 50% { transform: scale(1.1); }
146
- 100% { transform: scale(1); }
147
- }
148
-
149
- .stApp {
150
- background: #ffffff;
151
- max-width: 400px;
152
- margin: 10px auto;
153
- padding: 10px;
154
- font-family: 'Poppins', sans-serif;
155
- border-radius: 10px;
156
- box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
157
- border: 2px solid transparent;
158
- animation: glow 3s infinite;
159
- }
160
- /* Alternative Pastel Gradient Design (uncomment to use) */
161
- /*
162
- .stApp {
163
- background: linear-gradient(135deg, #e6f0fa, #f3e5f5);
164
- max-width: 400px;
165
- margin: 10px auto;
166
- padding: 10px;
167
- font-family: 'Poppins', sans-serif;
168
- border-radius: 10px;
169
- box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
170
- border: 2px solid transparent;
171
- animation: glow 3s infinite;
172
- }
173
- */
174
- .stTextInput > div > div > input, .stNumberInput > div > div > input, .stSelectbox > div > div > select {
175
- padding: 5px;
176
- border: 1px solid #ddd;
177
- border-radius: 5px;
178
- font-size: 0.8rem;
179
- background: #f9f9f9;
180
- transition: border-color 0.3s, box-shadow 0.3s;
181
- }
182
- .stTextInput > div > div > input:focus, .stNumberInput > div > div > input:focus, .stSelectbox > div > div > select:focus {
183
- outline: none;
184
- border-color: #3498db;
185
- box-shadow: 0 0 6px rgba(52, 152, 219, 0.7);
186
- }
187
- .stSelectbox > div > div > select {
188
- appearance: none;
189
- background: #f9f9f9 url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 24 24"><path fill="%23333" d="M7 10l5 5 5-5z"/></svg>') no-repeat right 8px center;
190
- }
191
- .stButton > button {
192
- padding: 6px;
193
- background: linear-gradient(45deg, #3498db, #ff6f61);
194
- color: white;
195
- border: none;
196
- border-radius: 5px;
197
- font-size: 0.85rem;
198
- font-weight: 600;
199
- width: 100%;
200
- transition: transform 0.2s, box-shadow 0.3s;
201
- }
202
- .stButton > button:hover {
203
- transform: translateY(-2px);
204
- box-shadow: 0 4px 12px rgba(255, 111, 97, 0.5);
205
- }
206
- .stButton > button:active {
207
- transform: translateY(0);
208
- }
209
- .result-box {
210
- background: #f1f3f5;
211
- padding: 8px;
212
- border-radius: 6px;
213
- text-align: center;
214
- margin-top: 8px;
215
- border: 1px solid #ddd;
216
- animation: glow 3s infinite;
217
- }
218
- .result-box h2 {
219
- font-size: 1rem;
220
- color: #2c3e50;
221
- margin-bottom: 4px;
222
- }
223
- .result-box p {
224
- font-size: 0.8rem;
225
- color: #7f8c8d;
226
- }
227
- .fa-shield-alt {
228
- animation: icon-pulse 2s infinite;
229
- }
230
- .form-label {
231
- font-weight: 600;
232
- font-size: 0.75rem;
233
- color: #2c3e50;
234
- margin-bottom: 3px;
235
- display: flex;
236
- align-items: center;
237
- }
238
- .form-label i {
239
- color: #ff6f61;
240
- margin-right: 5px;
241
- transition: color 0.3s;
242
- }
243
- .form-label i:hover {
244
- color: #3498db;
245
- }
246
- .stForm {
247
- display: flex;
248
- flex-direction: column;
249
- gap: 6px;
250
- }
251
- </style>
252
- """, unsafe_allow_html=True)
253
-
254
- # Streamlit UI
255
- st.markdown("""
256
- <h1 style='text-align: center; color: #2c3e50; font-size: 1.5rem; margin-bottom: 8px;'>
257
- <i class='fas fa-shield-alt' style='color: #ff6f61; margin-right: 8px;'></i>
258
- FraudShield
259
- </h1>
260
- <p style='text-align: center; font-size: 0.8rem; color: #555; margin-bottom: 8px; line-height: 1.4;'>
261
- Enter transaction details to detect fraud. Provide accurate zip code, merchant details, and amount.
262
- </p>
263
- """, unsafe_allow_html=True)
264
-
265
- with st.form(key="fraud_form"):
266
- st.markdown("<div class='form-label'><i class='fas fa-map-marker-alt'></i>Zipcode</div>", unsafe_allow_html=True)
267
- zipcode = st.number_input("", value=91750.0, step=0.01, format="%.2f", key="zipcode")
268
-
269
- st.markdown("<div class='form-label'><i class='fas fa-globe'></i>Merchant State</div>", unsafe_allow_html=True)
270
- merchant_state = st.selectbox("", sorted(state_mapping.keys()), index=sorted(state_mapping.keys()).index("TX"), key="state")
271
-
272
- st.markdown("<div class='form-label'><i class='fas fa-user-clock'></i>User Frequency Per Day</div>", unsafe_allow_html=True)
273
- user_freq = st.number_input("", value=1.0, step=0.01, format="%.2f", key="freq")
274
-
275
- st.markdown("<div class='form-label'><i class='fas fa-hourglass-half'></i>Time Difference (Hours)</div>", unsafe_allow_html=True)
276
- time_diff = st.number_input("", value=16601.95, step=0.01, format="%.2f", key="time")
277
-
278
- st.markdown("<div class='form-label'><i class='fas fa-store'></i>Merchant Category Code</div>", unsafe_allow_html=True)
279
- merchant_category = st.number_input("", value=5912.0, step=0.01, format="%.2f", key="category")
280
-
281
- st.markdown("<div class='form-label'><i class='fas fa-city'></i>Merchant City</div>", unsafe_allow_html=True)
282
- merchant_city = st.selectbox("", sorted(city_mapping.keys()), index=sorted(city_mapping.keys()).index("Houston"), key="city")
283
-
284
- st.markdown("<div class='form-label'><i class='fas fa-dollar-sign'></i>Transaction Amount</div>", unsafe_allow_html=True)
285
- transaction_amount = st.number_input("", value=128.35, step=0.01, format="%.2f", key="amount")
286
-
287
- submit_button = st.form_submit_button("Predict Fraud", use_container_width=True)
288
-
289
- if submit_button:
290
- try:
291
- if not all([zipcode, user_freq, time_diff, merchant_category, transaction_amount]):
292
- st.error("All fields are required.")
293
- elif merchant_state not in state_mapping:
294
- st.error(f"Invalid Merchant State: {merchant_state}")
295
- elif merchant_city not in city_mapping:
296
- st.error(f"Invalid Merchant City: {merchant_city}")
297
- else:
298
- transaction = {
299
- 'Zipcode': float(zipcode),
300
- 'Merchant_State_Code': int(state_mapping[merchant_state]),
301
- 'User_Frequency_Per_Day': float(user_freq),
302
- 'Time_Difference_Hours': float(time_diff),
303
- 'Merchant_Category_Code': float(merchant_category),
304
- 'Merchant_City_Code': int(city_mapping[merchant_city]),
305
- 'Transaction_Amount': float(transaction_amount)
306
- }
307
- transactions = [list(transaction.values())]
308
- predictions, probabilities = predict_fraud(transactions)
309
-
310
- if predictions is None or probabilities is None:
311
- st.error("Prediction failed. Check server logs for details.")
312
- else:
313
- result = 'Fraud' if predictions[0] == 1 else 'Not Fraud'
314
- st.markdown(f"""
315
- <div class='result-box'>
316
- <h2>Transaction: {result}</h2>
317
- <p>Probability of Fraud: {probabilities[0]:.4f}</p>
318
- </div>
319
- """, unsafe_allow_html=True)
320
- except Exception as e:
 
 
 
 
 
 
 
321
  st.error(f"Error: Invalid input - {str(e)}")
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ from torch_geometric.nn import GATConv
8
+ from torch_geometric.data import Data
9
+ import os
10
+
11
+ # Define FraudGNN class
12
+ class FraudGNN(nn.Module):
13
+ def __init__(self, input_dim, hidden_dim, output_dim):
14
+ super(FraudGNN, self).__init__()
15
+ self.conv1 = GATConv(input_dim, hidden_dim, heads=4, dropout=0.3)
16
+ self.conv2 = GATConv(hidden_dim * 4, hidden_dim, heads=1, dropout=0.3)
17
+ self.fc = nn.Linear(hidden_dim, output_dim)
18
+
19
+ def forward(self, data):
20
+ x, edge_index = data.x, data.edge_index
21
+ x = F.relu(self.conv1(x, edge_index))
22
+ x = F.dropout(x, p=0.3, training=self.training)
23
+ x = F.relu(self.conv2(x, edge_index))
24
+ x = self.fc(x)
25
+ return torch.sigmoid(x).squeeze()
26
+
27
+ # Device configuration
28
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
29
+
30
+ # Load model and threshold
31
+ try:
32
+ # Adjust paths for Hugging Face Spaces (relative to repository root)
33
+ model_path = os.path.join(os.path.dirname(__file__), '..', 'fraud_gnn_model.pth')
34
+ threshold_path = os.path.join(os.path.dirname(__file__), '..', 'optimal_threshold.txt')
35
+
36
+ # Alternative: If model files are in a 'models' folder
37
+ # model_path = os.path.join(os.path.dirname(__file__), '..', 'models', 'fraud_gnn_model.pth')
38
+ # threshold_path = os.path.join(os.path.dirname(__file__), '..', 'models', 'optimal_threshold.txt')
39
+
40
+ if not os.path.exists(model_path):
41
+ raise FileNotFoundError(f"Model file not found at {model_path}")
42
+ if not os.path.exists(threshold_path):
43
+ raise FileNotFoundError(f"Threshold file not found at {threshold_path}")
44
+
45
+ model = FraudGNN(input_dim=7, hidden_dim=16, output_dim=1).to(device)
46
+ model.load_state_dict(torch.load(model_path, map_location=device))
47
+ model.eval()
48
+
49
+ with open(threshold_path, 'r') as f:
50
+ threshold = float(f.read())
51
+ except FileNotFoundError as e:
52
+ st.error(f"Error: {e}. Please ensure model and threshold files are uploaded to the repository root.")
53
+ st.stop()
54
+ except Exception as e:
55
+ st.error(f"Error loading model or threshold: {e}")
56
+ st.stop()
57
+
58
+ # City and state mappings (unchanged)
59
+ city_mapping = {
60
+ 'Atlanta': 0, 'Bronx': 1, 'Brooklyn': 2, 'Chicago': 3, 'Dallas': 4, 'Houston': 5,
61
+ 'Indianapolis': 6, 'Las Vegas': 7, 'Los Angeles': 8, 'Louisville': 9, 'Miami': 10,
62
+ 'Minneapolis': 11, 'New York': 12, 'ONLINE': 13, 'Orlando': 14, 'Philadelphia': 15,
63
+ 'San Antonio': 16, 'San Diego': 17, 'San Francisco': 18, 'Tucson': 19, 'other': 20
64
+ }
65
+ state_mapping = {
66
+ 'AK': 0, 'AL': 1, 'AR': 2, 'AZ': 3, 'Algeria': 4, 'Antigua and Barbuda': 5, 'Argentina': 6,
67
+ 'Aruba': 7, 'Australia': 8, 'Austria': 9, 'Azerbaijan': 10, 'Bahrain': 11, 'Bangladesh': 12,
68
+ 'Barbados': 13, 'Belarus': 14, 'Belgium': 15, 'Belize': 16, 'Bosnia and Herzegovina': 17,
69
+ 'Brazil': 18, 'CA': 19, 'CO': 20, 'CT': 21, 'Cabo Verde': 22, 'Cambodia': 23, 'Canada': 24,
70
+ 'Central African Republic': 25, 'Chile': 26, 'China': 27, 'Colombia': 28, 'Costa Rica': 29,
71
+ "Cote d'Ivoire": 30, 'Croatia': 31, 'Czech Republic': 32, 'DC': 33, 'DE': 34, 'Denmark': 35,
72
+ 'Dominica': 36, 'Dominican Republic': 37, 'East Timor (Timor-Leste)': 38, 'Ecuador': 39,
73
+ 'Egypt': 40, 'Eritrea': 41, 'Estonia': 42, 'FL': 43, 'Fiji': 44, 'Finland': 45, 'France': 46,
74
+ 'GA': 47, 'Georgia': 48, 'Germany': 49, 'Ghana': 50, 'Greece': 51, 'Guatemala': 52,
75
+ 'Guyana': 53, 'HI': 54, 'Haiti': 55, 'Honduras': 56, 'Hong Kong': 57, 'Hungary': 58,
76
+ 'IA': 59, 'ID': 60, 'IL': 61, 'IN': 62, 'Iceland': 63, 'India': 64, 'Indonesia': 65,
77
+ 'Ireland': 66, 'Israel': 67, 'Italy': 68, 'Jamaica': 69, 'Japan': 70, 'Jordan': 71,
78
+ 'KS': 72, 'KY': 73, 'Kenya': 74, 'Kosovo': 75, 'Kuwait': 76, 'LA': 77, 'Latvia': 78,
79
+ 'Lebanon': 79, 'Liberia': 80, 'Lithuania': 81, 'Luxembourg': 82, 'MA': 83, 'MD': 84,
80
+ 'ME': 85, 'MI': 86, 'MN': 87, 'MO': 88, 'MS': 89, 'MT': 90, 'Macedonia': 91,
81
+ 'Malaysia': 92, 'Malta': 93, 'Mexico': 94, 'Moldova': 95, 'Monaco': 96, 'Morocco': 97,
82
+ 'Mozambique': 98, 'Myanmar (Burma)': 99, 'NC': 100, 'ND': 101, 'NE': 102, 'NH': 103,
83
+ 'NJ': 104, 'NM': 105, 'NV': 106, 'NY': 107, 'Nauru': 108, 'Netherlands': 109,
84
+ 'New Zealand': 110, 'Nicaragua': 111, 'Niger': 112, 'Nigeria': 113, 'Norway': 114,
85
+ 'OH': 115, 'OK': 116, 'OR': 117, 'Oman': 118, 'PA': 119, 'Pakistan': 120, 'Panama': 121,
86
+ 'Peru': 122, 'Philippines': 123, 'Poland': 124, 'Portugal': 125, 'RI': 126, 'Romania': 127,
87
+ 'Russia': 128, 'SC': 129, 'SD': 130, 'Saudi Arabia': 131, 'Senegal': 132, 'Serbia': 133,
88
+ 'Seychelles': 134, 'Singapore': 135, 'Slovakia': 136, 'Slovenia': 137, 'Somalia': 138,
89
+ 'South Africa': 139, 'South Korea': 140, 'Spain': 141, 'Sri Lanka': 142, 'Sudan': 143,
90
+ 'Suriname': 144, 'Sweden': 145, 'Switzerland': 146, 'Syria': 147, 'TN': 148, 'TX': 149,
91
+ 'Taiwan': 150, 'Thailand': 151, 'The Bahamas': 152, 'Tunisia': 153, 'Turkey': 154,
92
+ 'Tuvalu': 155, 'UT': 156, 'Uganda': 157, 'Ukraine': 158, 'United Arab Emirates': 159,
93
+ 'United Kingdom': 160, 'Uruguay': 161, 'Uzbekistan': 162, 'VA': 163, 'VT': 164,
94
+ 'Vatican City': 165, 'Vietnam': 166, 'WA': 167, 'WI': 168, 'WV': 169, 'WY': 170,
95
+ 'Yemen': 171, 'Zimbabwe': 172
96
+ }
97
+
98
+ def predict_fraud(transactions):
99
+ try:
100
+ df = pd.DataFrame(transactions, columns=[
101
+ 'Zipcode', 'Merchant_State_Code', 'User_Frequency_Per_Day',
102
+ 'Time_Difference_Hours', 'Merchant_Category_Code',
103
+ 'Merchant_City_Code', 'Transaction_Amount'
104
+ ])
105
+ node_features = torch.tensor(df.values, dtype=torch.float).to(device)
106
+
107
+ edge_index = torch.empty((2, 0), dtype=torch.long).to(device)
108
+
109
+ if len(df) > 1:
110
+ zipcodes = node_features[:, 0].cpu().numpy()
111
+ edge_list = []
112
+ zipcode_threshold = 1000
113
+ for i in range(len(df)):
114
+ for j in range(i + 1, len(df)):
115
+ if abs(zipcodes[i] - zipcodes[j]) < zipcode_threshold:
116
+ edge_list.append([i, j])
117
+ edge_list.append([j, i])
118
+ if edge_list:
119
+ edge_index = torch.tensor(edge_list, dtype=torch.long).t().contiguous().to(device)
120
+
121
+ graph_data = Data(x=node_features, edge_index=edge_index).to(device)
122
+
123
+ if model is None:
124
+ raise ValueError("Model not loaded. Check if fraud_gnn_model.pth exists.")
125
+
126
+ with torch.no_grad():
127
+ out = model(graph_data)
128
+ out = torch.atleast_1d(out)
129
+ pred_binary = (out > threshold).float().cpu().numpy()
130
+ pred_proba = out.cpu().numpy()
131
+ pred_binary = np.atleast_1d(pred_binary)
132
+ pred_proba = np.atleast_1d(pred_proba)
133
+
134
+ return pred_binary, pred_proba
135
+ except Exception as e:
136
+ st.error(f"Error in predict_fraud: {e}")
137
+ return None, None
138
+
139
+ # Custom CSS for highly compact, eye-catching design
140
+ st.markdown("""
141
+ <style>
142
+ @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap');
143
+ @import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css');
144
+
145
+ @keyframes glow {
146
+ 0% { box-shadow: 0 0 5px rgba(52, 152, 219, 0.5); }
147
+ 50% { box-shadow: 0 0 15px rgba(52, 152, 219, 0.8); }
148
+ 100% { box-shadow: 0 0 5px rgba(52, 152, 219, 0.5); }
149
+ }
150
+ @keyframes icon-pulse {
151
+ 0% { transform: scale(1); }
152
+ 50% { transform: scale(1.1); }
153
+ 100% { transform: scale(1); }
154
+ }
155
+
156
+ .stApp {
157
+ background: #ffffff;
158
+ max-width: 400px;
159
+ margin: 10px auto;
160
+ padding: 10px;
161
+ font-family: 'Poppins', sans-serif;
162
+ border-radius: 10px;
163
+ box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
164
+ border: 2px solid transparent;
165
+ animation: glow 3s infinite;
166
+ }
167
+ /* Alternative Pastel Gradient Design (uncomment to use) */
168
+ /*
169
+ .stApp {
170
+ background: linear-gradient(135deg, #e6f0fa, #f3e5f5);
171
+ max-width: 400px;
172
+ margin: 10px auto;
173
+ padding: 10px;
174
+ font-family: 'Poppins', sans-serif;
175
+ border-radius: 10px;
176
+ box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
177
+ border: 2px solid transparent;
178
+ animation: glow 3s infinite;
179
+ }
180
+ */
181
+ .stTextInput > div > div > input, .stNumberInput > div > div > input, .stSelectbox > div > div > select {
182
+ padding: 5px;
183
+ border: 1px solid #ddd;
184
+ border-radius: 5px;
185
+ font-size: 0.8rem;
186
+ background: #f9f9f9;
187
+ transition: border-color 0.3s, box-shadow 0.3s;
188
+ }
189
+ .stTextInput > div > div > input:focus, .stNumberInput > div > div > input:focus, .stSelectbox > div > div > select:focus {
190
+ outline: none;
191
+ border-color: #3498db;
192
+ box-shadow: 0 0 6px rgba(52, 152, 219, 0.7);
193
+ }
194
+ .stSelectbox > div > div > select {
195
+ appearance: none;
196
+ background: #f9f9f9 url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 24 24"><path fill="%23333" d="M7 10l5 5 5-5z"/></svg>') no-repeat right 8px center;
197
+ }
198
+ .stButton > button {
199
+ padding: 6px;
200
+ background: linear-gradient(45deg, #3498db, #ff6f61);
201
+ color: white;
202
+ border: none;
203
+ border-radius: 5px;
204
+ font-size: 0.85rem;
205
+ font-weight: 600;
206
+ width: 100%;
207
+ transition: transform 0.2s, box-shadow 0.3s;
208
+ }
209
+ .stButton > button:hover {
210
+ transform: translateY(-2px);
211
+ box-shadow: 0 4px 12px rgba(255, 111, 97, 0.5);
212
+ }
213
+ .stButton > button:active {
214
+ transform: translateY(0);
215
+ }
216
+ .result-box {
217
+ background: #f1f3f5;
218
+ padding: 8px;
219
+ border-radius: 6px;
220
+ text-align: center;
221
+ margin-top: 8px;
222
+ border: 1px solid #ddd;
223
+ animation: glow 3s infinite;
224
+ }
225
+ .result-box h2 {
226
+ font-size: 1rem;
227
+ color: #2c3e50;
228
+ margin-bottom: 4px;
229
+ }
230
+ .result-box p {
231
+ font-size: 0.8rem;
232
+ color: #7f8c8d;
233
+ }
234
+ .fa-shield-alt {
235
+ animation: icon-pulse 2s infinite;
236
+ }
237
+ .form-label {
238
+ font-weight: 600;
239
+ font-size: 0.75rem;
240
+ color: #2c3e50;
241
+ margin-bottom: 3px;
242
+ display: flex;
243
+ align-items: center;
244
+ }
245
+ .form-label i {
246
+ color: #ff6f61;
247
+ margin-right: 5px;
248
+ transition: color 0.3s;
249
+ }
250
+ .form-label i:hover {
251
+ color: #3498db;
252
+ }
253
+ .stForm {
254
+ display: flex;
255
+ flex-direction: column;
256
+ gap: 6px;
257
+ }
258
+ </style>
259
+ """, unsafe_allow_html=True)
260
+
261
+ # Streamlit UI
262
+ st.markdown("""
263
+ <h1 style='text-align: center; color: #2c3e50; font-size: 1.5rem; margin-bottom: 8px;'>
264
+ <i class='fas fa-shield-alt' style='color: #ff6f61; margin-right: 8px;'></i>
265
+ FraudShield
266
+ </h1>
267
+ <p style='text-align: center; font-size: 0.8rem; color: #555; margin-bottom: 8px; line-height: 1.4;'>
268
+ Enter transaction details to detect fraud. Provide accurate zip code, merchant details, and amount.
269
+ </p>
270
+ """, unsafe_allow_html=True)
271
+
272
+ with st.form(key="fraud_form"):
273
+ st.markdown("<div class='form-label'><i class='fas fa-map-marker-alt'></i>Zipcode</div>", unsafe_allow_html=True)
274
+ zipcode = st.number_input("", value=91750.0, step=0.01, format="%.2f", key="zipcode")
275
+
276
+ st.markdown("<div class='form-label'><i class='fas fa-globe'></i>Merchant State</div>", unsafe_allow_html=True)
277
+ merchant_state = st.selectbox("", sorted(state_mapping.keys()), index=sorted(state_mapping.keys()).index("TX"), key="state")
278
+
279
+ st.markdown("<div class='form-label'><i class='fas fa-user-clock'></i>User Frequency Per Day</div>", unsafe_allow_html=True)
280
+ user_freq = st.number_input("", value=1.0, step=0.01, format="%.2f", key="freq")
281
+
282
+ st.markdown("<div class='form-label'><i class='fas fa-hourglass-half'></i>Time Difference (Hours)</div>", unsafe_allow_html=True)
283
+ time_diff = st.number_input("", value=16601.95, step=0.01, format="%.2f", key="time")
284
+
285
+ st.markdown("<div class='form-label'><i class='fas fa-store'></i>Merchant Category Code</div>", unsafe_allow_html=True)
286
+ merchant_category = st.number_input("", value=5912.0, step=0.01, format="%.2f", key="category")
287
+
288
+ st.markdown("<div class='form-label'><i class='fas fa-city'></i>Merchant City</div>", unsafe_allow_html=True)
289
+ merchant_city = st.selectbox("", sorted(city_mapping.keys()), index=sorted(city_mapping.keys()).index("Houston"), key="city")
290
+
291
+ st.markdown("<div class='form-label'><i class='fas fa-dollar-sign'></i>Transaction Amount</div>", unsafe_allow_html=True)
292
+ transaction_amount = st.number_input("", value=128.35, step=0.01, format="%.2f", key="amount")
293
+
294
+ submit_button = st.form_submit_button("Predict Fraud", use_container_width=True)
295
+
296
+ if submit_button:
297
+ try:
298
+ if not all([zipcode, user_freq, time_diff, merchant_category, transaction_amount]):
299
+ st.error("All fields are required.")
300
+ elif merchant_state not in state_mapping:
301
+ st.error(f"Invalid Merchant State: {merchant_state}")
302
+ elif merchant_city not in city_mapping:
303
+ st.error(f"Invalid Merchant City: {merchant_city}")
304
+ else:
305
+ transaction = {
306
+ 'Zipcode': float(zipcode),
307
+ 'Merchant_State_Code': int(state_mapping[merchant_state]),
308
+ 'User_Frequency_Per_Day': float(user_freq),
309
+ 'Time_Difference_Hours': float(time_diff),
310
+ 'Merchant_Category_Code': float(merchant_category),
311
+ 'Merchant_City_Code': int(city_mapping[merchant_city]),
312
+ 'Transaction_Amount': float(transaction_amount)
313
+ }
314
+ transactions = [list(transaction.values())]
315
+ predictions, probabilities = predict_fraud(transactions)
316
+
317
+ if predictions is None or probabilities is None:
318
+ st.error("Prediction failed. Check server logs for details.")
319
+ else:
320
+ result = 'Fraud' if predictions[0] == 1 else 'Not Fraud'
321
+ st.markdown(f"""
322
+ <div class='result-box'>
323
+ <h2>Transaction: {result}</h2>
324
+ <p>Probability of Fraud: {probabilities[0]:.4f}</p>
325
+ </div>
326
+ """, unsafe_allow_html=True)
327
+ except Exception as e:
328
  st.error(f"Error: Invalid input - {str(e)}")