Update app.py
Browse files
app.py
CHANGED
@@ -1,58 +1,42 @@
|
|
1 |
-
import
|
2 |
-
import
|
3 |
-
import
|
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 |
-
# Gradio Interface
|
45 |
-
interface = gr.Interface(
|
46 |
-
fn=detect_anomalies,
|
47 |
-
inputs=gr.File(label="Upload Transaction CSV"),
|
48 |
-
outputs=[
|
49 |
-
gr.Dataframe(label="Predictions"),
|
50 |
-
gr.Text(label="Summary"),
|
51 |
-
gr.Image(label="Anomaly Chart")
|
52 |
-
],
|
53 |
-
title="Financial Anomaly Detector",
|
54 |
-
description="Upload a CSV file with transactions, and the model will detect suspicious activities."
|
55 |
-
)
|
56 |
-
|
57 |
-
# Launch app
|
58 |
-
interface.launch()
|
|
|
1 |
+
import pandas as pd
|
2 |
+
import joblib
|
3 |
+
import gradio as gr
|
4 |
+
|
5 |
+
# Load the trained model
|
6 |
+
model = joblib.load("anomaly_detector_rf_model.pkl")
|
7 |
+
|
8 |
+
# Define feature columns (exclude non-numeric ones if needed)
|
9 |
+
feature_cols = ['hour', 'day_of_week', 'is_weekend', 'amount_zscore', 'log_amount',
|
10 |
+
'type_atm_withdrawal', 'type_credit', 'type_debit', 'merchant_encoded']
|
11 |
+
|
12 |
+
def detect_anomalies(file_path):
|
13 |
+
# Read the dataset
|
14 |
+
df = pd.read_csv(file_path)
|
15 |
+
|
16 |
+
# Ensure all features exist in the dataframe
|
17 |
+
if not all(col in df.columns for col in feature_cols):
|
18 |
+
missing_cols = [col for col in feature_cols if col not in df.columns]
|
19 |
+
return f"Missing columns in dataset: {missing_cols}"
|
20 |
+
|
21 |
+
# Make predictions
|
22 |
+
df['is_anomalous'] = model.predict(df[feature_cols])
|
23 |
+
|
24 |
+
# Filter anomalous transactions
|
25 |
+
anomalies = df[df['is_anomalous'] == 1][['transaction_id', 'merchant', 'location', 'amount']]
|
26 |
+
|
27 |
+
# Save to a new CSV
|
28 |
+
anomalies.to_csv("predicted_anomalies.csv", index=False)
|
29 |
+
|
30 |
+
return anomalies
|
31 |
+
|
32 |
+
# Gradio Interface
|
33 |
+
interface = gr.Interface(
|
34 |
+
fn=detect_anomalies,
|
35 |
+
inputs=gr.File(label="Upload CSV File"),
|
36 |
+
outputs=gr.Dataframe(label="Predicted Anomalies"),
|
37 |
+
title="Anomaly Detection System",
|
38 |
+
description="Upload a transaction dataset to detect anomalies."
|
39 |
+
)
|
40 |
+
|
41 |
+
if __name__ == "__main__":
|
42 |
+
interface.launch(share=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|