|
import gradio as gr |
|
import pandas as pd |
|
import matplotlib.pyplot as plt |
|
import seaborn as sns |
|
import os |
|
import uuid |
|
import joblib |
|
|
|
|
|
model = joblib.load("anomaly_detector_rf_model.pkl") |
|
|
|
|
|
expected_features = ["amount"] |
|
|
|
def detect_anomalies(df): |
|
df = df.copy() |
|
df['is_anomalous'] = model.predict(df[expected_features]) |
|
anomalies = df[df['is_anomalous'] == 1] |
|
|
|
|
|
csv_filename = f"/tmp/anomalies_{uuid.uuid4().hex}.csv" |
|
anomalies.to_csv(csv_filename, index=False) |
|
|
|
return ( |
|
anomalies[["transaction_id", "merchant", "location", "amount", "is_anomalous"]], |
|
csv_filename |
|
) |
|
|
|
def generate_summary(df): |
|
total_transactions = len(df) |
|
total_anomalies = df['is_anomalous'].sum() |
|
percent_anomalies = round((total_anomalies / total_transactions) * 100, 2) |
|
return f"Total Transactions: {total_transactions}\nTotal Anomalies: {total_anomalies}\nAnomaly Rate: {percent_anomalies}%" |
|
|
|
def generate_charts(df): |
|
fig, ax = plt.subplots(1, 2, figsize=(12, 5)) |
|
|
|
|
|
sns.histplot(df['amount'], bins=30, ax=ax[0], kde=True) |
|
ax[0].set_title('Transaction Amount Distribution') |
|
|
|
|
|
anomaly_counts = df[df['is_anomalous'] == 1]['merchant'].value_counts().nlargest(10) |
|
sns.barplot(x=anomaly_counts.values, y=anomaly_counts.index, ax=ax[1]) |
|
ax[1].set_title('Top 10 Merchants with Anomalies') |
|
|
|
plt.tight_layout() |
|
chart_path = f"/tmp/chart_{uuid.uuid4().hex}.png" |
|
plt.savefig(chart_path) |
|
plt.close() |
|
return chart_path |
|
|
|
def app_interface(file): |
|
df = pd.read_csv(file.name) |
|
anomalies, csv_path = detect_anomalies(df) |
|
summary = generate_summary(df) |
|
chart_path = generate_charts(df) |
|
return anomalies, summary, chart_path, csv_path |
|
|
|
with gr.Blocks(theme=gr.themes.Soft()) as demo: |
|
gr.Markdown(""" |
|
# π Elder Financial Abuse Detection Tool |
|
Upload a transaction dataset to identify potential financial abuse patterns in elderly individuals. |
|
""") |
|
|
|
with gr.Row(): |
|
file_input = gr.File(label="π Upload Transaction CSV") |
|
analyze_btn = gr.Button("π Analyze") |
|
|
|
with gr.Row(): |
|
anomalies_output = gr.Dataframe(label="β οΈ Detected Anomalies", wrap=True) |
|
summary_output = gr.Textbox(label="π Summary") |
|
|
|
chart_output = gr.Image(label="π Analysis Charts") |
|
csv_download = gr.File(label="π Download Anomalies CSV") |
|
|
|
analyze_btn.click( |
|
fn=app_interface, |
|
inputs=[file_input], |
|
outputs=[anomalies_output, summary_output, chart_output, csv_download] |
|
) |
|
|
|
demo.launch() |