Spaces:
Sleeping
Sleeping
import streamlit as st | |
import pandas as pd | |
import joblib | |
import json | |
from datetime import datetime | |
# Load trained model | |
iso_forest = joblib.load("isolation_forest_model.pkl") | |
# Load location mapping | |
with open("location_mapping.json", "r") as f: | |
location_mapping = json.load(f) | |
# Manual mapping for categorical variables | |
transaction_type_mapping = {"Debit": 0, "Credit": 1} | |
channel_mapping = {"ATM": 0, "Online": 1, "Branch": 2} | |
day_of_week_mapping = {"Monday": 0, "Tuesday": 1, "Wednesday": 2, "Thursday": 3, "Friday": 4, "Saturday": 5, "Sunday": 6} | |
st.title("Anomaly Detection for Bank Transactions") | |
# User inputs | |
date = st.date_input("Select Transaction Date") | |
time = st.time_input("Select Transaction Time") | |
location = st.selectbox("Select Location", options=list(location_mapping.keys())) | |
transaction_type = st.radio("Transaction Type", options=["Debit", "Credit"]) | |
channel = st.radio("Transaction Channel", options=["ATM", "Online", "Branch"]) | |
transaction_duration = st.slider("Transaction Duration (seconds)", min_value=0, max_value=600, value=30) | |
login_attempts = st.number_input("Login Attempts", min_value=0) | |
transaction_amount = st.number_input("Transaction Amount", min_value=0.0, format="%.2f") | |
if st.button("Check for Anomaly"): | |
# Convert date to day of the week | |
day_of_week = day_of_week_mapping[date.strftime('%A')] | |
# Convert time to total seconds since midnight | |
total_seconds = time.hour * 3600 + time.minute * 60 | |
# Convert categorical values to numeric | |
location_encoded = location_mapping.get(location, -1) # Default to -1 if not found | |
transaction_type_encoded = transaction_type_mapping[transaction_type] | |
channel_encoded = channel_mapping[channel] | |
# Ensure the order of features matches training | |
input_data = pd.DataFrame([[ | |
transaction_type_encoded, location_encoded, channel_encoded, total_seconds, | |
transaction_duration, login_attempts, day_of_week, transaction_amount # <-- Corrected order | |
]], columns=[ | |
"TransactionType", "Location", "Channel", "Time", | |
"TransactionDuration", "LoginAttempts", "DayOfWeek", "TransactionAmount" # <-- Corrected order | |
]) | |
# Predict anomaly | |
prediction = iso_forest.predict(input_data)[0] | |
anomaly_label = "Anomalous" if prediction == -1 else "Normal" | |
# Display result | |
st.write(f"### The transaction is: **{anomaly_label}**") |