Spaces:
Sleeping
Sleeping
File size: 6,597 Bytes
2e07357 | 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 184 185 186 187 188 189 190 191 192 193 194 195 | """
Fraud network (ring) generation for Task 3 using networkx.
Generates complex fraud ring topologies:
- Simple cliques (3-5 ads fully connected)
- Chain structures (A-B via payment, B-C via creative — transitive reasoning required)
- Hub-and-spoke (one master account linked to satellites)
Individual ads in a ring may look borderline; the signal is in the connections.
Each edge in the graph carries the signal type that connects the two ads.
"""
from __future__ import annotations
import random
from dataclasses import dataclass, field
from typing import Dict, List, Set, Tuple
import networkx as nx
@dataclass
class FraudRing:
ring_id: str
member_ad_ids: List[str]
shared_signals: Dict[str, str] # signal_type -> shared_value
topology: str = "clique" # clique, chain, hub_spoke
@property
def size(self) -> int:
return len(self.member_ad_ids)
_RING_TOPOLOGIES = ["clique", "chain", "hub_spoke"]
_SIGNAL_POOL_KEYS = ["payment_method", "domain_registrar", "creative_template", "targeting_overlap"]
_REGISTRAR_CHOICES = ["Njalla (privacy)", "Epik", "NameSilo", "Tucows (privacy proxy)"]
_TARGETING_CHOICES = [
"Men 25-45, crypto+investing, US+UK+AU",
"Adults 18-35, tech+gaming, worldwide",
"Women 25-55, health+beauty, US+CA",
"Adults 30-60, finance+real-estate, US+UK",
"Adults 20-40, e-commerce+dropshipping, US+EU",
]
def _make_signal_pool(rng: random.Random, ring_index: int) -> Dict[str, str]:
"""Generate a pool of shared signal values for one ring."""
return {
"payment_method": f"pmt_ring_{rng.randint(10000, 99999)}",
"domain_registrar": rng.choice(_REGISTRAR_CHOICES),
"creative_template": f"tmpl_{rng.randint(1000, 9999)}",
"targeting_overlap": rng.choice(_TARGETING_CHOICES),
}
def generate_fraud_networks(
rng: random.Random,
n_rings: int,
available_fraud_ad_ids: List[str],
) -> Tuple[List[FraudRing], Dict[str, List[str]]]:
"""
Generate fraud ring structures with complex topologies.
Returns:
rings: list of FraudRing objects
ad_to_rings: mapping from ad_id to list of ring_ids it belongs to
"""
G = nx.Graph()
rings: List[FraudRing] = []
ad_to_rings: Dict[str, List[str]] = {}
remaining = list(available_fraud_ad_ids)
rng.shuffle(remaining)
for i in range(n_rings):
if len(remaining) < 3:
break
ring_size = rng.randint(3, min(5, len(remaining)))
members = remaining[:ring_size]
remaining = remaining[ring_size:]
topology = rng.choice(_RING_TOPOLOGIES)
signal_pool = _make_signal_pool(rng, i)
signal_keys = list(_SIGNAL_POOL_KEYS)
rng.shuffle(signal_keys)
n_shared = rng.randint(2, len(signal_keys))
shared_signals = {k: signal_pool[k] for k in signal_keys[:n_shared]}
_add_edges_for_topology(G, members, shared_signals, topology, rng)
ring_id = f"ring_{i}"
ring = FraudRing(
ring_id=ring_id,
member_ad_ids=members,
shared_signals=shared_signals,
topology=topology,
)
rings.append(ring)
for ad_id in members:
ad_to_rings.setdefault(ad_id, []).append(ring_id)
G.add_node(ad_id, ring_id=ring_id)
# Optionally create bridge nodes between rings for extra complexity
if len(rings) >= 2 and remaining:
_add_bridge_ads(G, rings, remaining, ad_to_rings, rng)
return rings, ad_to_rings
def _add_edges_for_topology(
G: nx.Graph,
members: List[str],
shared_signals: Dict[str, str],
topology: str,
rng: random.Random,
) -> None:
"""Add edges to the graph based on the ring topology."""
signal_types = list(shared_signals.keys())
if topology == "clique":
for i, a in enumerate(members):
for b in members[i + 1:]:
signal = rng.choice(signal_types)
G.add_edge(a, b, signal_type=signal, signal_value=shared_signals[signal])
elif topology == "chain":
for idx in range(len(members) - 1):
signal = signal_types[idx % len(signal_types)]
G.add_edge(
members[idx], members[idx + 1],
signal_type=signal, signal_value=shared_signals[signal],
)
elif topology == "hub_spoke":
hub = members[0]
for spoke in members[1:]:
signal = rng.choice(signal_types)
G.add_edge(hub, spoke, signal_type=signal, signal_value=shared_signals[signal])
def _add_bridge_ads(
G: nx.Graph,
rings: List[FraudRing],
remaining: List[str],
ad_to_rings: Dict[str, List[str]],
rng: random.Random,
) -> None:
"""Optionally link two rings via a shared bridge ad from the remaining pool."""
if len(remaining) < 1 or len(rings) < 2:
return
bridge_ad = remaining.pop(0)
r1, r2 = rings[0], rings[1]
bridge_to_r1 = rng.choice(r1.member_ad_ids)
bridge_to_r2 = rng.choice(r2.member_ad_ids)
r1.member_ad_ids.append(bridge_ad)
ad_to_rings.setdefault(bridge_ad, []).extend([r1.ring_id, r2.ring_id])
sig_key = rng.choice(list(r1.shared_signals.keys()))
G.add_edge(bridge_ad, bridge_to_r1, signal_type=sig_key, signal_value=r1.shared_signals[sig_key])
sig_key2 = rng.choice(list(r2.shared_signals.keys()))
G.add_edge(bridge_ad, bridge_to_r2, signal_type=sig_key2, signal_value=r2.shared_signals[sig_key2])
def get_ring_shared_signal_text(ring: FraudRing) -> str:
"""Describe the shared signals in a ring (for grader/debug use)."""
lines = [f"Fraud Ring {ring.ring_id} ({ring.size} members, topology={ring.topology}):"]
lines.append(f" Members: {', '.join(ring.member_ad_ids)}")
lines.append(" Shared signals:")
for signal_type, value in ring.shared_signals.items():
lines.append(f" - {signal_type}: {value}")
return "\n".join(lines)
def build_ground_truth_graph(rings: List[FraudRing]) -> nx.Graph:
"""Reconstruct the full ground truth network graph from rings.
Used by graders to compute the expected set of edges.
"""
G = nx.Graph()
for ring in rings:
for i, a in enumerate(ring.member_ad_ids):
G.add_node(a, ring_id=ring.ring_id)
for b in ring.member_ad_ids[i + 1:]:
G.add_edge(a, b, ring_id=ring.ring_id)
return G
|