File size: 5,270 Bytes
372c2d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
"""
PyVis Graph Visualiser
Builds interactive network visualisations for account investigation.
"""
import json
import tempfile
import os
import streamlit.components.v1 as components
import pandas as pd
import networkx as nx
from pyvis.network import Network

# Constants
NODE_SIZE_CENTER = 35
NODE_SIZE_HIGH_RISK = 22
NODE_SIZE_NORMAL = 14
NODE_SIZE_HIGH_PAGERANK = 26
EDGE_WIDTH_MAX = 8
EDGE_WIDTH_SCALE = 1_000_000
PAGERANK_TOP_PCT = 0.01
PHYSICS_GRAVITY = -50
PHYSICS_SPRING = 100
PHYSICS_ITERATIONS = 150

# Color palette
COLOR_CENTER = '#FFD700'       # Gold for center node
COLOR_FRAUD = '#FF4136'        # Red for confirmed fraud
COLOR_HIGH_PR = '#FF851B'      # Orange for high PageRank
COLOR_NORMAL = '#0074D9'       # Blue for normal
COLOR_FRAUD_EDGE = '#FF4136'   # Red for fraudulent edges
COLOR_NORMAL_EDGE = '#AAAAAA'  # Grey for normal edges

PHYSICS_OPTIONS = json.dumps({
    "nodes": {"borderWidth": 2, "shadow": True},
    "edges": {
        "smooth": {"type": "curvedCW", "roundness": 0.2},
        "shadow": True,
        "arrows": {"to": {"enabled": True, "scaleFactor": 0.8}},
    },
    "physics": {
        "forceAtlas2Based": {
            "gravitationalConstant": PHYSICS_GRAVITY,
            "springLength": PHYSICS_SPRING,
        },
        "solver": "forceAtlas2Based",
        "stabilization": {"iterations": PHYSICS_ITERATIONS},
    },
    "interaction": {"hover": True, "tooltipDelay": 100},
})


def build_pyvis_graph(
    subgraph: nx.DiGraph,
    df: pd.DataFrame,
    center_node: str,
    fraud_accounts: set,
    pagerank_scores: dict,
    louvain_partition: dict,
) -> Network:
    """
    Build an interactive PyVis network from a NetworkX subgraph.

    Nodes are sized and colored based on their role (center, fraud, high-PR, normal).
    Edges are scaled by transaction amount and colored by fraud status.

    Returns:
        A pyvis.network.Network instance ready for rendering.
    """
    net = Network(
        height='570px',
        width='100%',
        directed=True,
        notebook=False,
    )

    net.set_options(PHYSICS_OPTIONS)

    # Compute pagerank threshold for highlighting top nodes
    all_pr = sorted(pagerank_scores.values(), reverse=True)
    top_n = max(1, int(len(all_pr) * PAGERANK_TOP_PCT))
    pagerank_threshold = all_pr[min(top_n, len(all_pr) - 1)]

    # --- Add nodes ---
    for node in subgraph.nodes():
        node_data = subgraph.nodes[node]
        is_center = (node == center_node)
        is_fraud = node in fraud_accounts
        is_high_pr = pagerank_scores.get(node, 0) >= pagerank_threshold

        # Size and shape
        if is_center:
            size = NODE_SIZE_CENTER
            shape = 'star'
            color = COLOR_CENTER
        elif is_high_pr:
            size = NODE_SIZE_HIGH_PAGERANK
            shape = 'diamond'
            color = COLOR_HIGH_PR
        elif is_fraud:
            size = NODE_SIZE_HIGH_RISK
            shape = 'dot'
            color = COLOR_FRAUD
        else:
            size = NODE_SIZE_NORMAL
            shape = 'dot'
            color = COLOR_NORMAL

        # Tooltip
        total_sent = node_data.get('total_sent', 0)
        total_received = node_data.get('total_received', 0)
        count_sent = node_data.get('count_sent', 0)
        community = louvain_partition.get(node, 'N/A')
        status = 'FLAGGED' if is_fraud else 'Normal'

        tooltip = (
            f"Account: {node}\n"
            f"Total Sent: {total_sent:,.0f}\n"
            f"Total Received: {total_received:,.0f}\n"
            f"Transactions: {count_sent}\n"
            f"Community: {community}\n"
            f"Status: {status}"
        )

        label = str(node)[:12]

        net.add_node(
            str(node),
            label=label,
            size=size,
            shape=shape,
            color=color,
            title=tooltip,
            borderWidth=2,
            borderWidthSelected=4,
        )

    # --- Add edges ---
    for src, tgt, data in subgraph.edges(data=True):
        amount = data.get('amount', 0)
        is_fraud_edge = data.get('is_laundering', 0) == 1

        edge_width = min(amount / EDGE_WIDTH_SCALE, EDGE_WIDTH_MAX)
        edge_width = max(edge_width, 0.5)

        edge_color = COLOR_FRAUD_EDGE if is_fraud_edge else COLOR_NORMAL_EDGE

        tooltip = (
            f"Amount: {amount:,.0f}\n"
            f"Channel: {data.get('payment_type', '')}\n"
            f"Suspicious: {'Yes' if is_fraud_edge else 'No'}"
        )

        net.add_edge(
            str(src),
            str(tgt),
            value=edge_width,
            title=tooltip,
            color=edge_color,
            arrows='to',
        )

    return net


def render_pyvis(net: Network) -> None:
    """
    Render a PyVis network inside a Streamlit app using an HTML component.
    """
    with tempfile.NamedTemporaryFile(delete=False, suffix='.html', mode='w') as f:
        tmp_path = f.name
    net.save_graph(tmp_path)
    with open(tmp_path, 'r') as f:
        html_content = f.read()
    os.unlink(tmp_path)
    components.html(html_content, height=580, scrolling=False)


def save_pyvis_html(net: Network, path: str) -> None:
    """
    Save a PyVis network to an HTML file on disk.
    """
    net.save_graph(path)