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c6287b
 
 
 
 
 
 
 
0e828f7
6c6287b
 
 
 
0e828f7
6c6287b
 
 
 
 
 
 
0e828f7
6c6287b
 
 
0e828f7
6c6287b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e828f7
6c6287b
0e828f7
6c6287b
 
 
 
 
 
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
import pandas as pd
import numpy as np
import torch
import torch.nn as nn
from transformers import BertTokenizer, BertModel
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.ensemble import IsolationForest
import gradio as gr
import warnings
warnings.filterwarnings('ignore')

class FraudDetectionTester:
    def __init__(self, model_path='fraud_detection_model.pth'):
        """Initialize the fraud detection tester"""
        self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
        self.tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
        self.model_path = model_path
        self.model = None
        self.scaler = None
        self.label_encoder = None
        self.isolation_forest = None
        
        # Load the model
        self.load_model()
    
    def create_bert_fraud_model(self, numerical_features_dim):
        """Recreate the BERT fraud detection model architecture"""
        
        class BERTFraudDetector(nn.Module):
            def __init__(self, bert_model_name, numerical_features_dim, dropout_rate=0.3):
                super(BERTFraudDetector, self).__init__()
                
                # BERT for text processing
                self.bert = BertModel.from_pretrained(bert_model_name)
                
                # Freeze BERT parameters for faster training (optional)
                for param in self.bert.parameters():
                    param.requires_grad = False
                
                # Unfreeze last few layers for fine-tuning
                for param in self.bert.encoder.layer[-2:].parameters():
                    param.requires_grad = True
                
                # Feature processing layers
                self.text_projection = nn.Linear(self.bert.config.hidden_size, 256)
                self.numerical_projection = nn.Linear(numerical_features_dim, 256)
                
                # Anomaly detection features
                self.anomaly_detector = nn.Sequential(
                    nn.Linear(256, 128),
                    nn.ReLU(),
                    nn.Dropout(dropout_rate),
                    nn.Linear(128, 64),
                    nn.ReLU(),
                    nn.Linear(64, 1)
                )
                
                # Combined classifier
                self.classifier = nn.Sequential(
                    nn.Linear(512 + 1, 256),  # 256 + 256 + 1 (anomaly score)
                    nn.ReLU(),
                    nn.Dropout(dropout_rate),
                    nn.Linear(256, 128),
                    nn.ReLU(),
                    nn.Dropout(dropout_rate),
                    nn.Linear(128, 64),
                    nn.ReLU(),
                    nn.Linear(64, 1),
                    nn.Sigmoid()
                )
                
            def forward(self, input_ids, attention_mask, numerical_features):
                # Process text with BERT
                bert_output = self.bert(input_ids=input_ids, attention_mask=attention_mask)
                text_features = self.text_projection(bert_output.pooler_output)
                
                # Process numerical features
                numerical_features = self.numerical_projection(numerical_features)
                
                # Anomaly detection
                anomaly_score = self.anomaly_detector(numerical_features)
                
                # Combine all features
                combined_features = torch.cat([text_features, numerical_features, anomaly_score], dim=1)
                
                # Final classification
                fraud_probability = self.classifier(combined_features)
                
                return fraud_probability.squeeze(), anomaly_score.squeeze()
        
        return BERTFraudDetector('bert-base-uncased', numerical_features_dim)
    
    def load_model(self):
        """Load the pre-trained fraud detection model"""
        try:
            print(f"πŸ”„ Loading model from {self.model_path}...")
            
            # Add safe globals for sklearn objects
            torch.serialization.add_safe_globals([
                StandardScaler,
                LabelEncoder, 
                IsolationForest
            ])
            
            checkpoint = torch.load(self.model_path, map_location=self.device, weights_only=False)
            
            # Load preprocessing objects
            self.scaler = checkpoint['scaler']
            self.label_encoder = checkpoint['label_encoder']
            self.isolation_forest = checkpoint['isolation_forest']
            
            # Create and load model
            numerical_features_dim = 14  # Same as training
            self.model = self.create_bert_fraud_model(numerical_features_dim)
            self.model.load_state_dict(checkpoint['model_state_dict'])
            self.model.to(self.device)
            self.model.eval()
            
            print("βœ… Model loaded successfully!")
            
        except FileNotFoundError:
            print(f"❌ Error: Model file '{self.model_path}' not found!")
            print("Make sure you have trained and saved the model first.")
            raise
        except Exception as e:
            print(f"❌ Error loading model: {str(e)}")
            raise
    
    def tokenize_descriptions(self, descriptions, max_length=128):
        """Tokenize transaction descriptions for BERT"""
        if hasattr(descriptions, 'tolist'):
            descriptions = descriptions.tolist()
        elif isinstance(descriptions, str):
            descriptions = [descriptions]
        elif not isinstance(descriptions, list):
            descriptions = list(descriptions)
        
        descriptions = [str(desc) for desc in descriptions]
        
        encoded = self.tokenizer(
            descriptions,
            truncation=True,
            padding=True,
            max_length=max_length,
            return_tensors='pt'
        )
        
        return encoded['input_ids'], encoded['attention_mask']
    
    def preprocess_single_transaction(self, transaction):
        """Preprocess a single transaction for prediction"""
        if isinstance(transaction, dict):
            df = pd.DataFrame([transaction])
        else:
            df = pd.DataFrame(transaction)
        
        # Feature engineering
        df['amount_log'] = np.log1p(df['amount'])
        df['is_weekend'] = (df['day_of_week'] >= 5).astype(int)
        df['is_night'] = ((df['hour'] >= 22) | (df['hour'] <= 6)).astype(int)
        df['high_frequency'] = (df['transaction_count_1h'] > 3).astype(int)
        df['amount_deviation'] = abs(df['amount'] - df['avg_amount_1h']) / (df['avg_amount_1h'] + 1)
        
        # Handle unknown categories
        try:
            df['merchant_category_encoded'] = self.label_encoder.transform(df['merchant_category'])
        except ValueError:
            df['merchant_category_encoded'] = 0
        
        # Prepare numerical features
        numerical_features = ['amount_log', 'hour', 'day_of_week', 'days_since_last_transaction',
                            'transaction_count_1h', 'transaction_count_24h', 'avg_amount_1h',
                            'location_risk_score', 'account_age_days', 'merchant_category_encoded',
                            'is_weekend', 'is_night', 'high_frequency', 'amount_deviation']
        
        X_numerical = self.scaler.transform(df[numerical_features])
        
        # Process text
        df['processed_description'] = df['description'].astype(str).str.lower().str.replace(r'[^\w\s]', '', regex=True)
        
        return df, X_numerical
    
    def predict_fraud(self, transaction):
        """Predict fraud for a single transaction"""
        try:
            # Preprocess transaction
            df, X_numerical = self.preprocess_single_transaction(transaction)
            
            # Tokenize description
            processed_descriptions = df['processed_description'].tolist()
            input_ids, attention_masks = self.tokenize_descriptions(processed_descriptions)
            
            # Make prediction
            with torch.no_grad():
                batch_num = torch.tensor(X_numerical).float().to(self.device)
                batch_ids = input_ids.to(self.device)
                batch_masks = attention_masks.to(self.device)
                
                fraud_prob, anomaly_score = self.model(batch_ids, batch_masks, batch_num)
                
                # Get isolation forest prediction
                isolation_pred = self.isolation_forest.decision_function(X_numerical)
                
                # Handle single prediction
                if isinstance(fraud_prob, torch.Tensor):
                    if fraud_prob.dim() == 0:
                        fraud_prob_val = fraud_prob.item()
                        anomaly_score_val = anomaly_score.item()
                    else:
                        fraud_prob_val = fraud_prob[0].item()
                        anomaly_score_val = anomaly_score[0].item()
                else:
                    fraud_prob_val = float(fraud_prob)
                    anomaly_score_val = float(anomaly_score)
                
                # Combine predictions
                combined_score = (0.6 * fraud_prob_val + 
                                0.3 * (1 - (isolation_pred[0] + 0.5)) + 
                                0.1 * anomaly_score_val)
            
            return {
                'fraud_probability': float(combined_score),
                'is_fraud_predicted': bool(combined_score > 0.5),
                'risk_level': self.get_risk_level(combined_score),
                'anomaly_score': float(anomaly_score_val),
                'bert_score': float(fraud_prob_val),
                'isolation_score': float(isolation_pred[0])
            }
            
        except Exception as e:
            return {'error': str(e)}
    
    def get_risk_level(self, score):
        """Determine risk level based on fraud probability"""
        if score > 0.8:
            return 'CRITICAL'
        elif score > 0.6:
            return 'HIGH'
        elif score > 0.4:
            return 'MEDIUM'
        elif score > 0.2:
            return 'LOW'
        else:
            return 'MINIMAL'

# Initialize the fraud detection model
print("Initializing fraud detection model...")
try:
    fraud_detector = FraudDetectionTester('fraud_detection_model.pth')
    model_loaded = True
except Exception as e:
    print(f"Failed to load model: {e}")
    model_loaded = False

def predict_transaction_fraud(
    transaction_id,
    amount,
    merchant_category,
    description,
    hour,
    day_of_week,
    days_since_last_transaction,
    transaction_count_1h,
    transaction_count_24h,
    avg_amount_1h,
    location_risk_score,
    account_age_days
):
    """Gradio interface function for fraud prediction"""
    
    if not model_loaded:
        return "❌ Model not loaded. Please ensure 'fraud_detection_model.pth' is available.", "", "", "", "", ""
    
    # Create transaction dictionary
    transaction = {
        'transaction_id': transaction_id,
        'amount': amount,
        'merchant_category': merchant_category,
        'description': description,
        'hour': hour,
        'day_of_week': day_of_week,
        'days_since_last_transaction': days_since_last_transaction,
        'transaction_count_1h': transaction_count_1h,
        'transaction_count_24h': transaction_count_24h,
        'avg_amount_1h': avg_amount_1h,
        'location_risk_score': location_risk_score,
        'account_age_days': account_age_days
    }
    
    # Get prediction
    result = fraud_detector.predict_fraud(transaction)
    
    if 'error' in result:
        return f"❌ Error: {result['error']}", "", "", "", "", ""
    
    # Format results
    fraud_prob = result['fraud_probability']
    prediction = "🚨 FRAUD DETECTED" if result['is_fraud_predicted'] else "βœ… LEGITIMATE"
    risk_level = result['risk_level']
    
    # Create risk meter visualization
    risk_bar = "β–ˆ" * int(fraud_prob * 20) + "β–‘" * (20 - int(fraud_prob * 20))
    risk_meter = f"[{risk_bar}] {fraud_prob*100:.1f}%"
    
    # Detailed scores
    detailed_scores = f"""
πŸ€– BERT Score: {result['bert_score']:.4f}
🏝️ Isolation Score: {result['isolation_score']:.4f}
πŸ” Anomaly Score: {result['anomaly_score']:.4f}
    """
    
    # Summary
    summary = f"""
πŸ’° Amount: ${amount:.2f}
πŸͺ Category: {merchant_category}
πŸ“ Description: {description}
🎯 Fraud Probability: {fraud_prob:.4f} ({fraud_prob*100:.2f}%)
πŸ“Š Risk Level: {risk_level}
    """
    
    return prediction, f"{fraud_prob:.4f}", risk_level, risk_meter, detailed_scores, summary

def load_sample_transaction(sample_type):
    """Load predefined sample transactions"""
    samples = {
        "Normal Grocery Purchase": {
            'transaction_id': 'NORMAL_001',
            'amount': 45.67,
            'merchant_category': 'grocery',
            'description': 'WALMART SUPERCENTER CA 1234',
            'hour': 14,
            'day_of_week': 2,
            'days_since_last_transaction': 1.0,
            'transaction_count_1h': 1,
            'transaction_count_24h': 3,
            'avg_amount_1h': 50.0,
            'location_risk_score': 0.1,
            'account_age_days': 730
        },
        "Suspicious High Amount": {
            'transaction_id': 'SUSPICIOUS_001',
            'amount': 2999.99,
            'merchant_category': 'online',
            'description': 'SUSPICIOUS ELECTRONICS STORE XX 9999',
            'hour': 3,
            'day_of_week': 6,
            'days_since_last_transaction': 60.0,
            'transaction_count_1h': 12,
            'transaction_count_24h': 25,
            'avg_amount_1h': 150.0,
            'location_risk_score': 0.95,
            'account_age_days': 15
        },
        "Coffee Shop Purchase": {
            'transaction_id': 'COFFEE_001',
            'amount': 8.50,
            'merchant_category': 'restaurant',
            'description': 'STARBUCKS COFFEE NY 5678',
            'hour': 8,
            'day_of_week': 1,
            'days_since_last_transaction': 0.5,
            'transaction_count_1h': 1,
            'transaction_count_24h': 4,
            'avg_amount_1h': 8.50,
            'location_risk_score': 0.2,
            'account_age_days': 1095
        },
        "Foreign ATM Withdrawal": {
            'transaction_id': 'ATM_001',
            'amount': 500.00,
            'merchant_category': 'atm',
            'description': 'ATM WITHDRAWAL FOREIGN COUNTRY 0000',
            'hour': 23,
            'day_of_week': 0,
            'days_since_last_transaction': 0.1,
            'transaction_count_1h': 5,
            'transaction_count_24h': 8,
            'avg_amount_1h': 200.0,
            'location_risk_score': 0.8,
            'account_age_days': 365
        }
    }
    
    if sample_type in samples:
        sample = samples[sample_type]
        return (
            sample['transaction_id'],
            sample['amount'],
            sample['merchant_category'],
            sample['description'],
            sample['hour'],
            sample['day_of_week'],
            sample['days_since_last_transaction'],
            sample['transaction_count_1h'],
            sample['transaction_count_24h'],
            sample['avg_amount_1h'],
            sample['location_risk_score'],
            sample['account_age_days']
        )
    return [""] * 12

# Create Gradio interface
with gr.Blocks(title="🚨 Fraud Detection System", theme=gr.themes.Soft()) as demo:
    gr.Markdown("""
    # 🚨 Advanced Fraud Detection System
    ### Powered by BERT and Machine Learning
    
    This system analyzes financial transactions using advanced AI to detect potential fraud.
    Enter transaction details below or use sample transactions to test the system.
    """)
    
    with gr.Row():
        with gr.Column(scale=2):
            gr.Markdown("## πŸ“‹ Transaction Details")
            
            # Sample transaction selector
            with gr.Row():
                sample_dropdown = gr.Dropdown(
                    choices=["Normal Grocery Purchase", "Suspicious High Amount", "Coffee Shop Purchase", "Foreign ATM Withdrawal"],
                    label="🎯 Load Sample Transaction",
                    value="Normal Grocery Purchase"
                )
                load_sample_btn = gr.Button("πŸ“₯ Load Sample", variant="secondary")
            
            # Transaction inputs
            with gr.Row():
                transaction_id = gr.Textbox(label="Transaction ID", value="TEST_001")
                amount = gr.Number(label="πŸ’° Amount ($)", value=45.67, minimum=0)
            
            with gr.Row():
                merchant_category = gr.Dropdown(
                    choices=["grocery", "restaurant", "gas_station", "retail", "online", "atm", "pharmacy", "entertainment"],
                    label="πŸͺ Merchant Category",
                    value="grocery"
                )
                description = gr.Textbox(label="πŸ“ Transaction Description", value="WALMART SUPERCENTER CA 1234")
            
            with gr.Row():
                hour = gr.Slider(label="πŸ• Hour of Day", minimum=0, maximum=23, value=14, step=1)
                day_of_week = gr.Slider(label="πŸ“… Day of Week (0=Mon, 6=Sun)", minimum=0, maximum=6, value=2, step=1)
            
            with gr.Row():
                days_since_last = gr.Number(label="πŸ“† Days Since Last Transaction", value=1.0, minimum=0)
                transaction_count_1h = gr.Number(label="πŸ”’ Transactions (1h)", value=1, minimum=0)
            
            with gr.Row():
                transaction_count_24h = gr.Number(label="πŸ”’ Transactions (24h)", value=3, minimum=0)
                avg_amount_1h = gr.Number(label="πŸ’΅ Avg Amount (1h)", value=50.0, minimum=0)
            
            with gr.Row():
                location_risk_score = gr.Slider(label="πŸ“ Location Risk Score", minimum=0, maximum=1, value=0.1, step=0.01)
                account_age_days = gr.Number(label="πŸ‘€ Account Age (days)", value=730, minimum=0)
            
            predict_btn = gr.Button("πŸ” Analyze Transaction", variant="primary", size="lg")
        
        with gr.Column(scale=1):
            gr.Markdown("## πŸ“Š Fraud Analysis Results")
            
            prediction_output = gr.Textbox(label="🎯 Prediction", interactive=False)
            fraud_prob_output = gr.Textbox(label="πŸ“ˆ Fraud Probability", interactive=False)
            risk_level_output = gr.Textbox(label="⚠️ Risk Level", interactive=False)
            risk_meter_output = gr.Textbox(label="πŸ“Š Risk Meter", interactive=False, font_family="monospace")
            detailed_scores_output = gr.Textbox(label="πŸ” Detailed Scores", interactive=False, lines=4)
            summary_output = gr.Textbox(label="πŸ“‹ Summary", interactive=False, lines=6)
    
    # Event handlers
    predict_btn.click(
        fn=predict_transaction_fraud,
        inputs=[
            transaction_id, amount, merchant_category, description, hour, day_of_week,
            days_since_last, transaction_count_1h, transaction_count_24h, avg_amount_1h,
            location_risk_score, account_age_days
        ],
        outputs=[
            prediction_output, fraud_prob_output, risk_level_output, 
            risk_meter_output, detailed_scores_output, summary_output
        ]
    )
    
    load_sample_btn.click(
        fn=load_sample_transaction,
        inputs=[sample_dropdown],
        outputs=[
            transaction_id, amount, merchant_category, description, hour, day_of_week,
            days_since_last, transaction_count_1h, transaction_count_24h, avg_amount_1h,
            location_risk_score, account_age_days
        ]
    )
    
    gr.Markdown("""
    ---
    ### πŸ“– How to Use:
    1. **Load Sample**: Choose a predefined sample transaction to quickly test the system
    2. **Enter Details**: Fill in transaction information manually or modify loaded samples
    3. **Analyze**: Click "Analyze Transaction" to get fraud detection results
    
    ### 🎯 Understanding Results:
    - **Fraud Probability**: Higher values indicate higher fraud risk (0-1 scale)
    - **Risk Levels**: MINIMAL β†’ LOW β†’ MEDIUM β†’ HIGH β†’ CRITICAL
    - **Risk Meter**: Visual representation of fraud probability
    - **Detailed Scores**: Individual model component scores
    
    ### ⚠️ Model Requirements:
    Ensure `fraud_detection_model.pth` is available in the same directory as this script.
    """)

# Launch the interface
if __name__ == "__main__":
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        debug=True
    )