File size: 4,059 Bytes
b55cfa1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import streamlit as st
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
import random

# --- DSA: MERGE SORT IMPLEMENTATION (Requirement 2) ---
def merge_sort(df, column):
    if len(df) <= 1:
        return df
    mid = len(df) // 2
    left = merge_sort(df.iloc[:mid], column)
    right = merge_sort(df.iloc[mid:], column)
    return merge_left_right(left, right, column)

def merge_left_right(left, right, column):
    result = []
    i = j = 0
    while i < len(left) and j < len(right):
        if left.iloc[i][column] > right.iloc[j][column]: # Sort descending
            result.append(left.iloc[i])
            i += 1
        else:
            result.append(right.iloc[j])
            j += 1
    result.extend(left.iloc[i:].to_dict('records'))
    result.extend(right.iloc[j:].to_dict('records'))
    return pd.DataFrame(result)

# --- APP LAYOUT ---
st.title("🛡️ DSA Fraud Detection System")

# Requirement 1 & 6: Data Handling
st.subheader("Step 1: Data Input")
uploaded_file = st.file_uploader("Choose a CSV file", type="csv")

# Bypassing the 403 error by allowing internal generation
if st.button("No CSV? Generate 1000 Synthetic Transactions"):
    users = [f"User_{i}" for i in range(1, 51)]
    data = []
    for _ in range(1000):
        s, r = random.sample(users, 2)
        data.append({"Sender": s, "Receiver": r, "Amount": random.randint(10, 5000)})
    df = pd.DataFrame(data)
    st.session_state['df'] = df
    st.success("1000 Transactions Generated!")

if uploaded_file is not None:
    st.session_state['df'] = pd.read_csv(uploaded_file)

if 'df' in st.session_state:
    df = st.session_state['df']
    st.write("Current Data Preview (First 5 rows):", df.head())

    # --- USER SETTINGS (THRESHOLDS) ---
    st.divider()
    col1, col2 = st.columns(2)
    with col1:
        amount_threshold = st.number_input("Amount Threshold ($)", value=4000)
    with col2:
        freq_threshold = st.number_input("Max Transactions per User", value=10)
    
    blacklist_input = st.text_input("Blacklisted Users (comma separated)", "User_5, User_13")
    blacklist = [x.strip() for x in blacklist_input.split(",")]

    if st.button("Run Fraud Analysis"):
        st.divider()
        
        # --- 2. SORTING & THRESHOLD (Requirement 2) ---
        st.subheader("1. High-Value Suspicious Transactions")
        sorted_df = merge_sort(df, 'Amount')
        high_value = sorted_df[sorted_df['Amount'] > amount_threshold]
        st.write(f"Found {len(high_value)} transactions crossing the ${amount_threshold} limit.")
        st.dataframe(high_value)

        # --- 3. MAX TRANSACTIONS (HASH MAP SEARCH - Requirement 3) ---
        st.subheader("2. High-Frequency User Analysis")
        user_counts = {}
        for user in df['Sender']:
            user_counts[user] = user_counts.get(user, 0) + 1
        
        suspicious_users = [u for u, c in user_counts.items() if c > freq_threshold]
        if suspicious_users:
            st.warning(f"Users exceeding {freq_threshold} transactions: {suspicious_users}")
        else:
            st.success("No users exceeded the frequency threshold.")

        # --- 4. BLACKLIST CHECK (Requirement 4) ---
        st.subheader("3. Blacklisted Fraud Detection")
        blacklist_fraud = high_value[high_value['Sender'].isin(blacklist)]
        if not blacklist_fraud.empty:
            st.error("⚠️ CRITICAL: Blacklisted users found in high-value transactions!")
            st.table(blacklist_fraud)
        else:
            st.info("No blacklisted users found in high-value transactions.")

        # --- 7. GRAPH THEORY (Requirement 7) ---
        st.subheader("4. Transaction Network Visualization")
        
        G = nx.from_pandas_edgelist(df.head(50), 'Sender', 'Receiver', create_using=nx.DiGraph())
        fig, ax = plt.subplots()
        nx.draw(G, with_labels=True, node_color='orange', node_size=700, font_size=8, ax=ax)
        st.pyplot(fig)
        
        st.caption(f"Analysis completed using Merge Sort O(N log N) and Hash Map O(N).")