File size: 1,596 Bytes
d16c0f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()