Anomaly / app.py
Ujeshhh's picture
Upload 10 files
d16c0f6 verified
raw
history blame
1.6 kB
import gradio as gr
import pandas as pd
import joblib
import seaborn as sns
import matplotlib.pyplot as plt
# Load trained model & feature order
model = joblib.load('anomaly_detector_rf_model.pkl')
feature_order = joblib.load('feature_order.pkl')
# Function to make predictions
def detect_anomalies(file):
# Read uploaded CSV
df = pd.read_csv(file)
# Ensure correct feature order
df = df[feature_order]
# Get predictions (0 = Normal, 1 = Anomalous)
df['Prediction'] = model.predict(df)
# Count anomalies
anomaly_count = df['Prediction'].sum()
total = len(df)
# Visualization
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()
# Save the plot
plot_path = "anomaly_plot.png"
plt.savefig(plot_path)
# Return table and plot
return df.head(), f"Detected {anomaly_count} anomalies out of {total} transactions.", plot_path
# Gradio Interface
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."
)
# Launch app
interface.launch()