|
import gradio as gr
|
|
import pandas as pd
|
|
import joblib
|
|
import seaborn as sns
|
|
import matplotlib.pyplot as plt
|
|
|
|
|
|
model = joblib.load('anomaly_detector_rf_model.pkl')
|
|
feature_order = joblib.load('feature_order.pkl')
|
|
|
|
|
|
|
|
def detect_anomalies(file):
|
|
|
|
df = pd.read_csv(file)
|
|
|
|
|
|
df = df[feature_order]
|
|
|
|
|
|
df['Prediction'] = model.predict(df)
|
|
|
|
|
|
anomaly_count = df['Prediction'].sum()
|
|
total = len(df)
|
|
|
|
|
|
plt.figure(figsize=(5, 3))
|
|
sns.countplot(x=df['Prediction'], palette=['green', 'red'])
|
|
plt.xticks([0, 1], ["Normal", "Anomalous"])
|
|
plt.title("Anomaly Distribution")
|
|
plt.xlabel("Transaction Type")
|
|
plt.ylabel("Count")
|
|
plt.tight_layout()
|
|
|
|
|
|
plot_path = "anomaly_plot.png"
|
|
plt.savefig(plot_path)
|
|
|
|
|
|
return df.head(), f"Detected {anomaly_count} anomalies out of {total} transactions.", plot_path
|
|
|
|
|
|
|
|
interface = gr.Interface(
|
|
fn=detect_anomalies,
|
|
inputs=gr.File(label="Upload Transaction CSV"),
|
|
outputs=[
|
|
gr.Dataframe(label="Predictions"),
|
|
gr.Text(label="Summary"),
|
|
gr.Image(label="Anomaly Chart")
|
|
],
|
|
title="Financial Anomaly Detector",
|
|
description="Upload a CSV file with transactions, and the model will detect suspicious activities."
|
|
)
|
|
|
|
|
|
interface.launch()
|
|
|