Ujeshhh commited on
Commit
dd8c606
·
verified ·
1 Parent(s): 0c7b7ad

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -58
app.py CHANGED
@@ -1,58 +1,42 @@
1
- import gradio as gr
2
- import pandas as pd
3
- import joblib
4
- import seaborn as sns
5
- import matplotlib.pyplot as plt
6
-
7
- # Load trained model & feature order
8
- model = joblib.load('anomaly_detector_rf_model.pkl')
9
- feature_order = joblib.load('feature_order.pkl')
10
-
11
-
12
- # Function to make predictions
13
- def detect_anomalies(file):
14
- # Read uploaded CSV
15
- df = pd.read_csv(file)
16
-
17
- # Ensure correct feature order
18
- df = df[feature_order]
19
-
20
- # Get predictions (0 = Normal, 1 = Anomalous)
21
- df['Prediction'] = model.predict(df)
22
-
23
- # Count anomalies
24
- anomaly_count = df['Prediction'].sum()
25
- total = len(df)
26
-
27
- # Visualization
28
- plt.figure(figsize=(5, 3))
29
- sns.countplot(x=df['Prediction'], palette=['green', 'red'])
30
- plt.xticks([0, 1], ["Normal", "Anomalous"])
31
- plt.title("Anomaly Distribution")
32
- plt.xlabel("Transaction Type")
33
- plt.ylabel("Count")
34
- plt.tight_layout()
35
-
36
- # Save the plot
37
- plot_path = "anomaly_plot.png"
38
- plt.savefig(plot_path)
39
-
40
- # Return table and plot
41
- return df.head(), f"Detected {anomaly_count} anomalies out of {total} transactions.", plot_path
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)