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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import numpy as np
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
import seaborn as sns
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
from sklearn.metrics import confusion_matrix, precision_score, recall_score
|
| 8 |
+
|
| 9 |
+
# Sample data preparation (in a real scenario, you would load your data)
|
| 10 |
+
# Converting your sample data to a DataFrame
|
| 11 |
+
data = {
|
| 12 |
+
'transaction_amount': [2500, 799, 9338, 11749, 8999, 1500, 3000, 4000, 300, 5000, 24990],
|
| 13 |
+
'transaction_date': ['01-11-2024 16:08', '01-11-2024 16:15', '02-11-2024 14:43', '03-11-2024 11:14',
|
| 14 |
+
'04-11-2024 12:54', '06-11-2024 08:36', '06-11-2024 08:56', '06-11-2024 09:08',
|
| 15 |
+
'06-11-2024 09:29', '06-11-2024 13:05', '06-11-2024 15:12'],
|
| 16 |
+
'transaction_channel': ['mobile', 'mobile', 'mobile', 'mobile', 'mobile', 'W', 'W', 'W', 'W', 'W', 'mobile'],
|
| 17 |
+
'is_fraud': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
|
| 18 |
+
'transaction_payment_mode_anonymous': [10, 10, 2, 6, 2, 10, 10, 10, 10, 10, 2],
|
| 19 |
+
'payment_gateway_bank_anonymous': [6, 6, 6, 58, 6, 6, 6, 6, 6, 6, 6],
|
| 20 |
+
'payer_browser_anonymous': [1833, 1833, 2766, 3378, 2766, 3212, 3212, 3212, 3212, 3212, 2721],
|
| 21 |
+
'transaction_id_anonymous': ['ANON_9629', 'ANON_9764', 'ANON_27514', 'ANON_41176', 'ANON_66597',
|
| 22 |
+
'ANON_134329', 'ANON_134618', 'ANON_134815', 'ANON_135218',
|
| 23 |
+
'ANON_147464', 'ANON_155578'],
|
| 24 |
+
'payee_id_anonymous': ['ANON_47', 'ANON_47', 'ANON_265', 'ANON_8', 'ANON_265', 'ANON_12',
|
| 25 |
+
'ANON_12', 'ANON_12', 'ANON_12', 'ANON_12', 'ANON_265']
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
df = pd.DataFrame(data)
|
| 29 |
+
|
| 30 |
+
# Convert date strings to datetime objects
|
| 31 |
+
df['transaction_date'] = pd.to_datetime(df['transaction_date'], format='%d-%m-%Y %H:%M')
|
| 32 |
+
|
| 33 |
+
# Add simulated predicted fraud and reported fraud columns
|
| 34 |
+
# In a real scenario, these would come from your model and reports
|
| 35 |
+
np.random.seed(42)
|
| 36 |
+
df['is_fraud_predicted'] = np.random.choice([0, 1], size=len(df), p=[0.3, 0.7])
|
| 37 |
+
df['is_fraud_reported'] = np.random.choice([0, 1], size=len(df), p=[0.4, 0.6])
|
| 38 |
+
|
| 39 |
+
def filter_data(start_date, end_date, payer_id, payee_id, transaction_id):
|
| 40 |
+
filtered_df = df.copy()
|
| 41 |
+
|
| 42 |
+
# Convert string dates to datetime for comparison
|
| 43 |
+
start_date = pd.to_datetime(start_date)
|
| 44 |
+
end_date = pd.to_datetime(end_date)
|
| 45 |
+
|
| 46 |
+
# Apply filters
|
| 47 |
+
filtered_df = filtered_df[(filtered_df['transaction_date'] >= start_date) &
|
| 48 |
+
(filtered_df['transaction_date'] <= end_date)]
|
| 49 |
+
|
| 50 |
+
if payer_id:
|
| 51 |
+
filtered_df = filtered_df[filtered_df['transaction_id_anonymous'] == payer_id]
|
| 52 |
+
|
| 53 |
+
if payee_id:
|
| 54 |
+
filtered_df = filtered_df[filtered_df['payee_id_anonymous'] == payee_id]
|
| 55 |
+
|
| 56 |
+
if transaction_id:
|
| 57 |
+
filtered_df = filtered_df[filtered_df['transaction_id_anonymous'] == transaction_id]
|
| 58 |
+
|
| 59 |
+
return filtered_df
|
| 60 |
+
|
| 61 |
+
def create_comparison_chart(dimension, filtered_df):
|
| 62 |
+
if filtered_df.empty:
|
| 63 |
+
return plt.figure()
|
| 64 |
+
|
| 65 |
+
plt.figure(figsize=(10, 6))
|
| 66 |
+
|
| 67 |
+
if dimension == 'Transaction Channel':
|
| 68 |
+
group_col = 'transaction_channel'
|
| 69 |
+
elif dimension == 'Transaction Payment Mode':
|
| 70 |
+
group_col = 'transaction_payment_mode_anonymous'
|
| 71 |
+
elif dimension == 'Payment Gateway Bank':
|
| 72 |
+
group_col = 'payment_gateway_bank_anonymous'
|
| 73 |
+
elif dimension == 'Payer ID':
|
| 74 |
+
group_col = 'transaction_id_anonymous'
|
| 75 |
+
elif dimension == 'Payee ID':
|
| 76 |
+
group_col = 'payee_id_anonymous'
|
| 77 |
+
else:
|
| 78 |
+
return plt.figure()
|
| 79 |
+
|
| 80 |
+
# Group by the selected dimension and count predicted and reported frauds
|
| 81 |
+
predicted = filtered_df.groupby(group_col)['is_fraud_predicted'].sum()
|
| 82 |
+
reported = filtered_df.groupby(group_col)['is_fraud_reported'].sum()
|
| 83 |
+
|
| 84 |
+
# Create a DataFrame for plotting
|
| 85 |
+
plot_df = pd.DataFrame({
|
| 86 |
+
'Predicted Fraud': predicted,
|
| 87 |
+
'Reported Fraud': reported
|
| 88 |
+
})
|
| 89 |
+
|
| 90 |
+
# Plot
|
| 91 |
+
plot_df.plot(kind='bar', figsize=(10, 6))
|
| 92 |
+
plt.title(f'Fraud Comparison by {dimension}')
|
| 93 |
+
plt.ylabel('Count')
|
| 94 |
+
plt.xlabel(dimension)
|
| 95 |
+
plt.tight_layout()
|
| 96 |
+
|
| 97 |
+
return plt
|
| 98 |
+
|
| 99 |
+
def create_time_series(filtered_df, granularity):
|
| 100 |
+
if filtered_df.empty:
|
| 101 |
+
return plt.figure()
|
| 102 |
+
|
| 103 |
+
plt.figure(figsize=(12, 6))
|
| 104 |
+
|
| 105 |
+
# Set the time grouping based on granularity
|
| 106 |
+
if granularity == 'Day':
|
| 107 |
+
time_group = filtered_df['transaction_date'].dt.date
|
| 108 |
+
elif granularity == 'Hour':
|
| 109 |
+
time_group = filtered_df['transaction_date'].dt.strftime('%Y-%m-%d %H')
|
| 110 |
+
elif granularity == 'Minute':
|
| 111 |
+
time_group = filtered_df['transaction_date'].dt.strftime('%Y-%m-%d %H:%M')
|
| 112 |
+
else:
|
| 113 |
+
return plt.figure()
|
| 114 |
+
|
| 115 |
+
# Group by time and count predicted and reported frauds
|
| 116 |
+
predicted = filtered_df.groupby(time_group)['is_fraud_predicted'].sum()
|
| 117 |
+
reported = filtered_df.groupby(time_group)['is_fraud_reported'].sum()
|
| 118 |
+
|
| 119 |
+
# Plot
|
| 120 |
+
plt.plot(predicted.index, predicted.values, 'b-', label='Predicted Fraud')
|
| 121 |
+
plt.plot(reported.index, reported.values, 'r-', label='Reported Fraud')
|
| 122 |
+
plt.title('Fraud Trend Over Time')
|
| 123 |
+
plt.ylabel('Count')
|
| 124 |
+
plt.xlabel('Time')
|
| 125 |
+
plt.legend()
|
| 126 |
+
plt.xticks(rotation=45)
|
| 127 |
+
plt.tight_layout()
|
| 128 |
+
|
| 129 |
+
return plt
|
| 130 |
+
|
| 131 |
+
def calculate_metrics(filtered_df):
|
| 132 |
+
if filtered_df.empty:
|
| 133 |
+
return None, 0, 0
|
| 134 |
+
|
| 135 |
+
# Calculate confusion matrix
|
| 136 |
+
cm = confusion_matrix(filtered_df['is_fraud'], filtered_df['is_fraud_predicted'])
|
| 137 |
+
|
| 138 |
+
# Calculate precision and recall
|
| 139 |
+
precision = precision_score(filtered_df['is_fraud'], filtered_df['is_fraud_predicted'], zero_division=0)
|
| 140 |
+
recall = recall_score(filtered_df['is_fraud'], filtered_df['is_fraud_predicted'], zero_division=0)
|
| 141 |
+
|
| 142 |
+
# Create confusion matrix plot
|
| 143 |
+
plt.figure(figsize=(6, 5))
|
| 144 |
+
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',
|
| 145 |
+
xticklabels=['Not Fraud', 'Fraud'],
|
| 146 |
+
yticklabels=['Not Fraud', 'Fraud'])
|
| 147 |
+
plt.ylabel('Actual')
|
| 148 |
+
plt.xlabel('Predicted')
|
| 149 |
+
plt.title('Confusion Matrix')
|
| 150 |
+
|
| 151 |
+
return plt, precision, recall
|
| 152 |
+
|
| 153 |
+
def update_interface(start_date, end_date, payer_id, payee_id, transaction_id, dimension, time_granularity):
|
| 154 |
+
# Filter data based on inputs
|
| 155 |
+
filtered_df = filter_data(start_date, end_date, payer_id, payee_id, transaction_id)
|
| 156 |
+
|
| 157 |
+
# Create comparison chart
|
| 158 |
+
comparison_chart = create_comparison_chart(dimension, filtered_df)
|
| 159 |
+
|
| 160 |
+
# Create time series chart
|
| 161 |
+
time_series = create_time_series(filtered_df, time_granularity)
|
| 162 |
+
|
| 163 |
+
# Calculate evaluation metrics
|
| 164 |
+
confusion_matrix_plot, precision, recall = calculate_metrics(filtered_df)
|
| 165 |
+
|
| 166 |
+
# Format the filtered dataframe for display
|
| 167 |
+
display_df = filtered_df.copy()
|
| 168 |
+
display_df['transaction_date'] = display_df['transaction_date'].dt.strftime('%Y-%m-%d %H:%M')
|
| 169 |
+
|
| 170 |
+
return (display_df.to_dict('records'),
|
| 171 |
+
comparison_chart,
|
| 172 |
+
time_series,
|
| 173 |
+
confusion_matrix_plot,
|
| 174 |
+
f"Precision: {precision:.4f}",
|
| 175 |
+
f"Recall: {recall:.4f}")
|
| 176 |
+
|
| 177 |
+
# Define the Gradio interface
|
| 178 |
+
with gr.Blocks() as demo:
|
| 179 |
+
gr.Markdown("# Fraud Transaction Analysis Dashboard")
|
| 180 |
+
|
| 181 |
+
with gr.Row():
|
| 182 |
+
with gr.Column():
|
| 183 |
+
start_date = gr.Textbox(label="Start Date (YYYY-MM-DD)", value="2024-11-01")
|
| 184 |
+
end_date = gr.Textbox(label="End Date (YYYY-MM-DD)", value="2024-11-06")
|
| 185 |
+
|
| 186 |
+
with gr.Column():
|
| 187 |
+
payer_id = gr.Textbox(label="Payer ID")
|
| 188 |
+
payee_id = gr.Textbox(label="Payee ID")
|
| 189 |
+
transaction_id = gr.Textbox(label="Transaction ID")
|
| 190 |
+
|
| 191 |
+
with gr.Row():
|
| 192 |
+
dimension = gr.Dropdown(
|
| 193 |
+
["Transaction Channel", "Transaction Payment Mode", "Payment Gateway Bank", "Payer ID", "Payee ID"],
|
| 194 |
+
label="Comparison Dimension",
|
| 195 |
+
value="Transaction Channel"
|
| 196 |
+
)
|
| 197 |
+
time_granularity = gr.Dropdown(
|
| 198 |
+
["Day", "Hour", "Minute"],
|
| 199 |
+
label="Time Granularity",
|
| 200 |
+
value="Day"
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
update_button = gr.Button("Update Dashboard")
|
| 204 |
+
|
| 205 |
+
with gr.Row():
|
| 206 |
+
gr.Markdown("## Transaction Data")
|
| 207 |
+
|
| 208 |
+
data_table = gr.DataFrame()
|
| 209 |
+
|
| 210 |
+
with gr.Row():
|
| 211 |
+
with gr.Column():
|
| 212 |
+
gr.Markdown("## Fraud Comparison by Dimension")
|
| 213 |
+
comparison_plot = gr.Plot()
|
| 214 |
+
|
| 215 |
+
with gr.Column():
|
| 216 |
+
gr.Markdown("## Fraud Trend Over Time")
|
| 217 |
+
time_series_plot = gr.Plot()
|
| 218 |
+
|
| 219 |
+
with gr.Row():
|
| 220 |
+
gr.Markdown("## Model Evaluation")
|
| 221 |
+
|
| 222 |
+
with gr.Row():
|
| 223 |
+
with gr.Column():
|
| 224 |
+
confusion_matrix_plot = gr.Plot()
|
| 225 |
+
|
| 226 |
+
with gr.Column():
|
| 227 |
+
precision_text = gr.Textbox(label="Precision")
|
| 228 |
+
recall_text = gr.Textbox(label="Recall")
|
| 229 |
+
|
| 230 |
+
update_button.click(
|
| 231 |
+
update_interface,
|
| 232 |
+
inputs=[start_date, end_date, payer_id, payee_id, transaction_id, dimension, time_granularity],
|
| 233 |
+
outputs=[data_table, comparison_plot, time_series_plot, confusion_matrix_plot, precision_text, recall_text]
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
# Launch the app
|
| 237 |
+
if __name__ == "__main__":
|
| 238 |
+
demo.launch()
|