Spaces:
Runtime error
Runtime error
Upload 9 files
Browse files- app.py +127 -0
- page1_intro.py +289 -0
- page2_risk_register.py +310 -0
- page3_simulation.py +863 -0
- page4_results.py +951 -0
- page5_optimisation.py +320 -0
- requirements.txt +5 -3
- simulation_engine.py +443 -0
- styles.py +252 -0
app.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
app.py — Main Streamlit entry point for No-CelH Self-Learning RMS
|
| 3 |
+
Run: streamlit run app.py
|
| 4 |
+
Hugging Face Spaces: set SDK=streamlit, app_file=app.py
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import streamlit as st
|
| 8 |
+
|
| 9 |
+
st.set_page_config(
|
| 10 |
+
page_title="No-CelH · Self-Learning RMS",
|
| 11 |
+
page_icon="🛃",
|
| 12 |
+
layout="wide",
|
| 13 |
+
initial_sidebar_state="expanded",
|
| 14 |
+
menu_items={
|
| 15 |
+
"Get Help": "https://www.wcoomd.org/en/topics/enforcement-and-compliance/activities-and-programmes/risk-management.aspx",
|
| 16 |
+
"Report a bug": None,
|
| 17 |
+
"About": "No-CelH: Self-Learning RMS — WCO Accredited Expert Simulation Tool\n\nBuilt on DATE + gATE Active Learning (Kim et al. 2022, IEEE TKDE)",
|
| 18 |
+
},
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
import page1_intro
|
| 22 |
+
import page2_risk_register
|
| 23 |
+
import page3_simulation
|
| 24 |
+
import page4_results
|
| 25 |
+
import page5_optimisation
|
| 26 |
+
from styles import WCO_GOLD, WCO_NAVY, WCO_BORDER, WCO_CARD_BG, WCO_MUTED, WCO_RED, WCO_GREEN
|
| 27 |
+
|
| 28 |
+
PAGES = {
|
| 29 |
+
"🏠 Introduction & Architecture": page1_intro,
|
| 30 |
+
"📋 Risk Register & Matrix": page2_risk_register,
|
| 31 |
+
"🔄 Simulation Engine": page3_simulation,
|
| 32 |
+
"📊 Simulation Results": page4_results,
|
| 33 |
+
"🏆 Bandwidth Optimisation": page5_optimisation,
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
def sidebar():
|
| 37 |
+
with st.sidebar:
|
| 38 |
+
st.markdown(f"""
|
| 39 |
+
<div style="text-align:center;padding:20px 10px 14px;">
|
| 40 |
+
<div style="font-size:42px;">🛃</div>
|
| 41 |
+
<div style="color:{WCO_GOLD};font-family:'Playfair Display',Georgia,serif;
|
| 42 |
+
font-size:16px;font-weight:700;margin-top:8px;line-height:1.3;">
|
| 43 |
+
No-CelH<br/>Self-Learning RMS
|
| 44 |
+
</div>
|
| 45 |
+
<div style="color:{WCO_MUTED};font-size:10px;margin-top:6px;
|
| 46 |
+
font-family:'IBM Plex Mono',monospace;letter-spacing:0.06em;">
|
| 47 |
+
WCO ACCREDITED · v2.0
|
| 48 |
+
</div>
|
| 49 |
+
</div>
|
| 50 |
+
<hr style="border-color:{WCO_BORDER};margin:0 0 16px;"/>
|
| 51 |
+
""", unsafe_allow_html=True)
|
| 52 |
+
|
| 53 |
+
st.markdown(f"""
|
| 54 |
+
<div style="color:{WCO_GOLD};font-size:11px;font-weight:600;
|
| 55 |
+
letter-spacing:0.1em;text-transform:uppercase;
|
| 56 |
+
padding:0 4px;margin-bottom:8px;">Navigation</div>
|
| 57 |
+
""", unsafe_allow_html=True)
|
| 58 |
+
|
| 59 |
+
selected = st.radio("", list(PAGES.keys()),
|
| 60 |
+
key="nav_page", label_visibility="collapsed")
|
| 61 |
+
|
| 62 |
+
st.markdown(f"<hr style='border-color:{WCO_BORDER};margin:16px 0;'/>",
|
| 63 |
+
unsafe_allow_html=True)
|
| 64 |
+
|
| 65 |
+
# Session state status panel
|
| 66 |
+
sim_ready = "sim_df" in st.session_state
|
| 67 |
+
st.markdown(f"""
|
| 68 |
+
<div style="background:{WCO_CARD_BG};border:1px solid {WCO_BORDER};
|
| 69 |
+
border-radius:10px;padding:14px;">
|
| 70 |
+
<div style="color:{WCO_GOLD};font-size:11px;font-weight:600;
|
| 71 |
+
text-transform:uppercase;letter-spacing:0.08em;margin-bottom:10px;">
|
| 72 |
+
Session Status
|
| 73 |
+
</div>
|
| 74 |
+
<div style="font-size:12px;line-height:2.1;color:#8BAAD4;">
|
| 75 |
+
<span style="color:{'#44CC88' if sim_ready else WCO_MUTED};">
|
| 76 |
+
{'✅' if sim_ready else '⬜'}</span> Simulation Run<br/>
|
| 77 |
+
<span style="color:{'#44CC88' if 'rule_weights' in st.session_state else WCO_MUTED};">
|
| 78 |
+
{'✅' if 'rule_weights' in st.session_state else '⬜'}</span> Weights Configured<br/>
|
| 79 |
+
<span style="color:{'#44CC88' if 'sim_efficiency' in st.session_state else WCO_MUTED};">
|
| 80 |
+
{'✅' if 'sim_efficiency' in st.session_state else '⬜'}</span> Results Available
|
| 81 |
+
</div>
|
| 82 |
+
</div>
|
| 83 |
+
""", unsafe_allow_html=True)
|
| 84 |
+
|
| 85 |
+
if sim_ready:
|
| 86 |
+
df = st.session_state.sim_df
|
| 87 |
+
eff = st.session_state.get("sim_efficiency", {}).get("hybrid", {})
|
| 88 |
+
st.markdown(f"""
|
| 89 |
+
<div style="background:{WCO_CARD_BG};border:1px solid {WCO_BORDER};
|
| 90 |
+
border-radius:10px;padding:14px;margin-top:10px;">
|
| 91 |
+
<div style="color:{WCO_GOLD};font-size:11px;font-weight:600;
|
| 92 |
+
text-transform:uppercase;letter-spacing:0.08em;margin-bottom:10px;">
|
| 93 |
+
Last Simulation
|
| 94 |
+
</div>
|
| 95 |
+
<div style="font-size:12px;line-height:2.1;color:#8BAAD4;">
|
| 96 |
+
📦 Bills: <b style="color:#D0DCF0;">{len(df):,}</b><br/>
|
| 97 |
+
🔴 RED: <b style="color:{WCO_RED};">{(df['channel']=='RED').sum()}</b><br/>
|
| 98 |
+
🟡 YEL: <b style="color:{WCO_GOLD};">{(df['channel']=='YELLOW').sum()}</b><br/>
|
| 99 |
+
🟢 GRN: <b style="color:{WCO_GREEN};">{(df['channel']=='GREEN').sum()}</b><br/>
|
| 100 |
+
🚨 Detected: <b style="color:{WCO_RED};">
|
| 101 |
+
{(df['inspection_outcome']=='FRAUD_DETECTED').sum()}</b><br/>
|
| 102 |
+
📈 Efficiency: <b style="color:{WCO_GREEN};">
|
| 103 |
+
{eff.get('efficiency_index',0):.3f}</b>
|
| 104 |
+
</div>
|
| 105 |
+
</div>
|
| 106 |
+
""", unsafe_allow_html=True)
|
| 107 |
+
|
| 108 |
+
st.markdown(f"""
|
| 109 |
+
<hr style="border-color:{WCO_BORDER};margin:16px 0 10px;"/>
|
| 110 |
+
<div style="color:{WCO_MUTED};font-size:10px;text-align:center;line-height:1.7;padding:0 4px;">
|
| 111 |
+
Based on: Kim et al. (2022)<br/>
|
| 112 |
+
<i>Active Learning for Human-in-the-Loop Customs Inspection</i><br/>
|
| 113 |
+
IEEE TKDE · WCO Compendium<br/>
|
| 114 |
+
<span style="color:{WCO_GOLD};">WCO BACUDA Initiative</span>
|
| 115 |
+
</div>
|
| 116 |
+
""", unsafe_allow_html=True)
|
| 117 |
+
|
| 118 |
+
return selected
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def main():
|
| 122 |
+
selected = sidebar()
|
| 123 |
+
PAGES[selected].show()
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
if __name__ == "__main__":
|
| 127 |
+
main()
|
page1_intro.py
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
page1_intro.py — Introduction, How to Use, Objectives, Architecture Diagram
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import streamlit as st
|
| 6 |
+
from styles import (inject_global_css, page_header, metric_row,
|
| 7 |
+
WCO_GOLD, WCO_BLUE, WCO_GREEN, WCO_RED, WCO_CARD_BG, WCO_BORDER, WCO_MUTED)
|
| 8 |
+
|
| 9 |
+
ARCH_SVG = """
|
| 10 |
+
<svg viewBox="0 0 980 620" xmlns="http://www.w3.org/2000/svg"
|
| 11 |
+
style="width:100%;border-radius:14px;background:#070E1C;">
|
| 12 |
+
<defs>
|
| 13 |
+
<linearGradient id="hbg" x1="0" y1="0" x2="1" y2="1">
|
| 14 |
+
<stop offset="0%" stop-color="#003087"/><stop offset="100%" stop-color="#001040"/>
|
| 15 |
+
</linearGradient>
|
| 16 |
+
<linearGradient id="gold" x1="0" y1="0" x2="1" y2="0">
|
| 17 |
+
<stop offset="0%" stop-color="#C8A951"/><stop offset="100%" stop-color="#FFD966"/>
|
| 18 |
+
</linearGradient>
|
| 19 |
+
<marker id="arr" markerWidth="9" markerHeight="9" refX="7" refY="3" orient="auto">
|
| 20 |
+
<path d="M0,0 L0,6 L9,3z" fill="#C8A951"/>
|
| 21 |
+
</marker>
|
| 22 |
+
<marker id="arrb" markerWidth="9" markerHeight="9" refX="7" refY="3" orient="auto">
|
| 23 |
+
<path d="M0,0 L0,6 L9,3z" fill="#66AAFF"/>
|
| 24 |
+
</marker>
|
| 25 |
+
<marker id="arrg" markerWidth="9" markerHeight="9" refX="7" refY="3" orient="auto">
|
| 26 |
+
<path d="M0,0 L0,6 L9,3z" fill="#44CC88"/>
|
| 27 |
+
</marker>
|
| 28 |
+
<marker id="arrp" markerWidth="9" markerHeight="9" refX="7" refY="3" orient="auto">
|
| 29 |
+
<path d="M0,0 L0,6 L9,3z" fill="#CC77FF"/>
|
| 30 |
+
</marker>
|
| 31 |
+
<filter id="glow"><feGaussianBlur stdDeviation="4" result="b"/>
|
| 32 |
+
<feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge></filter>
|
| 33 |
+
</defs>
|
| 34 |
+
|
| 35 |
+
<!-- background -->
|
| 36 |
+
<rect width="980" height="620" fill="#070E1C" rx="14"/>
|
| 37 |
+
<rect width="980" height="3" fill="url(#gold)" rx="2"/>
|
| 38 |
+
|
| 39 |
+
<!-- title bar -->
|
| 40 |
+
<text x="490" y="32" text-anchor="middle" font-family="Georgia,serif" font-size="17"
|
| 41 |
+
fill="#C8A951" font-weight="bold">No-CelH · Self-Learning RMS Architecture</text>
|
| 42 |
+
<text x="490" y="52" text-anchor="middle" font-family="monospace" font-size="10" fill="#557">
|
| 43 |
+
DATE Exploitation ◈ gATE Exploration ◈ Human-in-the-Loop ◈ WCO Compendium
|
| 44 |
+
</text>
|
| 45 |
+
|
| 46 |
+
<!-- ══════════════════════ ROW 1 BOXES ══════════════════════ -->
|
| 47 |
+
<!-- [1] Import Declarations -->
|
| 48 |
+
<rect x="18" y="74" width="130" height="64" rx="9" fill="#0A1E4A" stroke="#C8A951" stroke-width="1.5"/>
|
| 49 |
+
<text x="83" y="97" text-anchor="middle" font-family="Georgia" font-size="13" fill="#C8A951">📦 Import</text>
|
| 50 |
+
<text x="83" y="114" text-anchor="middle" font-family="Georgia" font-size="11" fill="#AAC">Declarations</text>
|
| 51 |
+
<text x="83" y="128" text-anchor="middle" font-family="monospace" font-size="9" fill="#667">1,000 Bills / Batch</text>
|
| 52 |
+
|
| 53 |
+
<!-- [2] Risk Register -->
|
| 54 |
+
<rect x="180" y="74" width="138" height="64" rx="9" fill="#0A1E4A" stroke="#0066CC" stroke-width="1.5"/>
|
| 55 |
+
<text x="249" y="97" text-anchor="middle" font-family="Georgia" font-size="13" fill="#66AAFF">📋 Risk Register</text>
|
| 56 |
+
<text x="249" y="114" text-anchor="middle" font-family="Georgia" font-size="11" fill="#AAC">5 Risk Areas · Rules</text>
|
| 57 |
+
<text x="249" y="128" text-anchor="middle" font-family="monospace" font-size="9" fill="#667">Weights · Targets</text>
|
| 58 |
+
|
| 59 |
+
<!-- [3] DATE Scoring Engine -->
|
| 60 |
+
<rect x="356" y="64" width="170" height="84" rx="9" fill="#071A10" stroke="#00843D" stroke-width="2" filter="url(#glow)"/>
|
| 61 |
+
<text x="441" y="89" text-anchor="middle" font-family="Georgia" font-size="14" fill="#44CC88" font-weight="bold">🧠 DATE Engine</text>
|
| 62 |
+
<text x="441" y="107" text-anchor="middle" font-family="Georgia" font-size="11" fill="#AAC">Exploitation: ŷᶜˡˢ + ŷʳᵉᵛ</text>
|
| 63 |
+
<text x="441" y="122" text-anchor="middle" font-family="monospace" font-size="9" fill="#44CC88">Fraud Score × Revenue</text>
|
| 64 |
+
<text x="441" y="136" text-anchor="middle" font-family="monospace" font-size="9" fill="#557">Risk Scoring Pipeline</text>
|
| 65 |
+
|
| 66 |
+
<!-- [4] Hybrid Selector -->
|
| 67 |
+
<rect x="566" y="64" width="168" height="84" rx="9" fill="#1A1000" stroke="#C8A951" stroke-width="2" filter="url(#glow)"/>
|
| 68 |
+
<text x="650" y="89" text-anchor="middle" font-family="Georgia" font-size="14" fill="#C8A951" font-weight="bold">⚖️ Hybrid Selector</text>
|
| 69 |
+
<text x="650" y="107" text-anchor="middle" font-family="Georgia" font-size="11" fill="#AAC">90% DATE + 10% gATE</text>
|
| 70 |
+
<text x="650" y="122" text-anchor="middle" font-family="monospace" font-size="9" fill="#C8A951">Bandwidth: 10% (adj.)</text>
|
| 71 |
+
<text x="650" y="136" text-anchor="middle" font-family="monospace" font-size="9" fill="#557">Optimal Selection</text>
|
| 72 |
+
|
| 73 |
+
<!-- [5] gATE Engine -->
|
| 74 |
+
<rect x="356" y="178" width="170" height="74" rx="9" fill="#110A1E" stroke="#9933CC" stroke-width="1.8"/>
|
| 75 |
+
<text x="441" y="200" text-anchor="middle" font-family="Georgia" font-size="13" fill="#CC77FF" font-weight="bold">🔍 gATE Engine</text>
|
| 76 |
+
<text x="441" y="217" text-anchor="middle" font-family="Georgia" font-size="11" fill="#AAC">unc_i × log(ŷʳᵉᵛ + ε)</text>
|
| 77 |
+
<text x="441" y="232" text-anchor="middle" font-family="monospace" font-size="9" fill="#CC77FF">K-means++ Diversity</text>
|
| 78 |
+
<text x="441" y="244" text-anchor="middle" font-family="monospace" font-size="9" fill="#557">Concept Drift Guard</text>
|
| 79 |
+
|
| 80 |
+
<!-- CHANNEL BOXES -->
|
| 81 |
+
<!-- RED -->
|
| 82 |
+
<rect x="775" y="60" width="100" height="44" rx="7" fill="#1E0008" stroke="#C8102E" stroke-width="1.8"/>
|
| 83 |
+
<text x="825" y="79" text-anchor="middle" font-family="Georgia" font-size="13" fill="#FF4466" font-weight="bold">🔴 RED</text>
|
| 84 |
+
<text x="825" y="96" text-anchor="middle" font-family="monospace" font-size="9" fill="#FF8899">Physical Exam</text>
|
| 85 |
+
<!-- YELLOW -->
|
| 86 |
+
<rect x="775" y="111" width="100" height="44" rx="7" fill="#1A0F00" stroke="#F5A800" stroke-width="1.8"/>
|
| 87 |
+
<text x="825" y="130" text-anchor="middle" font-family="Georgia" font-size="13" fill="#FFD700" font-weight="bold">🟡 YELLOW</text>
|
| 88 |
+
<text x="825" y="147" text-anchor="middle" font-family="monospace" font-size="9" fill="#FFE066">Doc Check</text>
|
| 89 |
+
<!-- GREEN -->
|
| 90 |
+
<rect x="775" y="162" width="100" height="44" rx="7" fill="#00100A" stroke="#00843D" stroke-width="1.8"/>
|
| 91 |
+
<text x="825" y="181" text-anchor="middle" font-family="Georgia" font-size="13" fill="#44CC88" font-weight="bold">🟢 GREEN</text>
|
| 92 |
+
<text x="825" y="198" text-anchor="middle" font-family="monospace" font-size="9" fill="#88EEBB">Facilitated</text>
|
| 93 |
+
|
| 94 |
+
<!-- ══════════ ARROWS ROW 1 ══════════ -->
|
| 95 |
+
<line x1="148" y1="106" x2="178" y2="106" stroke="#C8A951" stroke-width="1.6" marker-end="url(#arr)"/>
|
| 96 |
+
<line x1="318" y1="106" x2="354" y2="106" stroke="#C8A951" stroke-width="1.6" marker-end="url(#arr)"/>
|
| 97 |
+
<line x1="526" y1="106" x2="564" y2="106" stroke="#C8A951" stroke-width="1.6" marker-end="url(#arr)"/>
|
| 98 |
+
<line x1="734" y1="106" x2="773" y2="106" stroke="#C8A951" stroke-width="1.6" marker-end="url(#arr)"/>
|
| 99 |
+
<!-- DATE → gATE (vertical) -->
|
| 100 |
+
<line x1="441" y1="148" x2="441" y2="178" stroke="#44CC88" stroke-width="1.3" stroke-dasharray="5,3" marker-end="url(#arrg)"/>
|
| 101 |
+
<!-- gATE → Hybrid -->
|
| 102 |
+
<path d="M526 215 Q560 215 560 148 Q560 106 564 106" stroke="#CC77FF" stroke-width="1.4"
|
| 103 |
+
stroke-dasharray="5,3" fill="none" marker-end="url(#arrp)"/>
|
| 104 |
+
|
| 105 |
+
<!-- ══════════════ ROW 2: OFFICER INSPECTION ══════════════ -->
|
| 106 |
+
<rect x="566" y="290" width="168" height="64" rx="9" fill="#0A1832" stroke="#0066CC" stroke-width="1.5"/>
|
| 107 |
+
<text x="650" y="313" text-anchor="middle" font-family="Georgia" font-size="13" fill="#66AAFF" font-weight="bold">👮 Officer Inspection</text>
|
| 108 |
+
<text x="650" y="330" text-anchor="middle" font-family="Georgia" font-size="11" fill="#AAC">Labels: yᶜˡˢ + yʳᵉᵛ</text>
|
| 109 |
+
<text x="650" y="344" text-anchor="middle" font-family="monospace" font-size="9" fill="#667">Human-in-the-Loop</text>
|
| 110 |
+
|
| 111 |
+
<!-- Channels → Officer -->
|
| 112 |
+
<line x1="825" y1="206" x2="825" y2="298" stroke="#66AAFF" stroke-width="1.3" stroke-dasharray="4,3"/>
|
| 113 |
+
<line x1="825" y1="298" x2="736" y2="316" stroke="#66AAFF" stroke-width="1.3" marker-end="url(#arrb)"/>
|
| 114 |
+
|
| 115 |
+
<!-- ══════════════ ROW 2: OFFENCE DATABASE ══════════════ -->
|
| 116 |
+
<rect x="356" y="290" width="170" height="64" rx="9" fill="#1A0008" stroke="#C8102E" stroke-width="1.5"/>
|
| 117 |
+
<text x="441" y="313" text-anchor="middle" font-family="Georgia" font-size="13" fill="#FF6688" font-weight="bold">🗄️ Offence Database</text>
|
| 118 |
+
<text x="441" y="330" text-anchor="middle" font-family="Georgia" font-size="11" fill="#AAC">Augmented Real-Time</text>
|
| 119 |
+
<text x="441" y="344" text-anchor="middle" font-family="monospace" font-size="9" fill="#667">5 Risk Categories</text>
|
| 120 |
+
|
| 121 |
+
<!-- Officer → Offence DB -->
|
| 122 |
+
<line x1="566" y1="322" x2="528" y2="322" stroke="#FF4466" stroke-width="1.5" marker-end="url(#arr)"/>
|
| 123 |
+
|
| 124 |
+
<!-- ══════════ FEEDBACK LOOPS ══════════ -->
|
| 125 |
+
<!-- Offence DB → DATE (model update) -->
|
| 126 |
+
<path d="M441 290 Q441 260 441 252 Q441 148 526 148" stroke="#44CC88" stroke-width="1.4"
|
| 127 |
+
stroke-dasharray="6,3" fill="none" marker-end="url(#arrg)"/>
|
| 128 |
+
<!-- Offence DB → Risk Register (weight update) -->
|
| 129 |
+
<path d="M356 322 Q249 322 249 160 Q249 138 318 138" stroke="#66AAFF" stroke-width="1.3"
|
| 130 |
+
stroke-dasharray="6,3" fill="none" marker-end="url(#arrb)"/>
|
| 131 |
+
|
| 132 |
+
<!-- feedback labels -->
|
| 133 |
+
<text x="480" y="258" font-family="monospace" font-size="9" fill="#44CC88">Model Update</text>
|
| 134 |
+
<text x="255" y="275" font-family="monospace" font-size="9" fill="#66AAFF">Weight Update</text>
|
| 135 |
+
|
| 136 |
+
<!-- ══════════════ BOTTOM METRICS BAND ══════════════ -->
|
| 137 |
+
<rect x="18" y="390" width="290" height="90" rx="9" fill="#0F1C35" stroke="#C8102E" stroke-width="1.2"/>
|
| 138 |
+
<text x="163" y="413" text-anchor="middle" font-family="Georgia" font-size="12" fill="#FF4466" font-weight="bold">📉 Static Model (Baseline)</text>
|
| 139 |
+
<text x="163" y="433" text-anchor="middle" font-family="Georgia" font-size="11" fill="#AAC">Selection Rate: 10% | Detection: 4.1%</text>
|
| 140 |
+
<text x="163" y="452" text-anchor="middle" font-family="Georgia" font-size="11" fill="#AAC">Efficiency Index: <tspan font-weight="bold" fill="#FF4466">0.41</tspan></text>
|
| 141 |
+
<text x="163" y="470" text-anchor="middle" font-family="monospace" font-size="9" fill="#667">Exploitation-only · No Learning</text>
|
| 142 |
+
|
| 143 |
+
<rect x="328" y="390" width="290" height="90" rx="9" fill="#0F1C35" stroke="#00843D" stroke-width="2"/>
|
| 144 |
+
<text x="473" y="413" text-anchor="middle" font-family="Georgia" font-size="12" fill="#44CC88" font-weight="bold">📈 Hybrid Model (No-CelH)</text>
|
| 145 |
+
<text x="473" y="433" text-anchor="middle" font-family="Georgia" font-size="11" fill="#AAC">Selection Rate: 10% | Detection: 8.2%</text>
|
| 146 |
+
<text x="473" y="452" text-anchor="middle" font-family="Georgia" font-size="11" fill="#AAC">Efficiency Index: <tspan font-weight="bold" fill="#44CC88">0.82</tspan></text>
|
| 147 |
+
<text x="473" y="470" text-anchor="middle" font-family="monospace" font-size="9" fill="#44CC88">DATE 90% + gATE 10% · Self-Learning</text>
|
| 148 |
+
|
| 149 |
+
<!-- improvement arrow -->
|
| 150 |
+
<line x1="320" y1="432" x2="326" y2="432" stroke="#C8A951" stroke-width="2" marker-end="url(#arr)"/>
|
| 151 |
+
<text x="323" y="427" text-anchor="middle" font-family="Georgia" font-size="10" fill="#C8A951">+100%</text>
|
| 152 |
+
|
| 153 |
+
<rect x="638" y="390" width="322" height="90" rx="9" fill="#0F1C35" stroke="#9933CC" stroke-width="1.2"/>
|
| 154 |
+
<text x="799" y="413" text-anchor="middle" font-family="Georgia" font-size="12" fill="#CC77FF" font-weight="bold">🔬 Discovery Barometer</text>
|
| 155 |
+
<text x="799" y="433" text-anchor="middle" font-family="Georgia" font-size="11" fill="#AAC">New Importers Discovered: ~10× more</text>
|
| 156 |
+
<text x="799" y="452" text-anchor="middle" font-family="Georgia" font-size="11" fill="#AAC">New HS Codes Mapped: 2,000+ in 5 yrs</text>
|
| 157 |
+
<text x="799" y="471" text-anchor="middle" font-family="monospace" font-size="9" fill="#CC77FF">Sequential Fraud Detection: ✓ Enabled</text>
|
| 158 |
+
|
| 159 |
+
<!-- ══════════════ FORMULA BAND ══════════════ -->
|
| 160 |
+
<rect x="18" y="498" width="942" height="50" rx="8" fill="#0A1020" stroke="#1E3A6E" stroke-width="1"/>
|
| 161 |
+
<text x="490" y="520" text-anchor="middle" font-family="monospace" font-size="11" fill="#C8A951">
|
| 162 |
+
Uncertainty: unc_i = −1.8 × |ŷᶜˡˢ − 0.5| + 1 Scale: S_i = unc_i × log(ŷʳᵉᵛ + ε)
|
| 163 |
+
</text>
|
| 164 |
+
<text x="490" y="538" text-anchor="middle" font-family="monospace" font-size="10" fill="#557">
|
| 165 |
+
Efficiency Index = Detection Rate / Selection Rate Reference: Kim et al. (2022) IEEE TKDE · WCO Risk Compendium
|
| 166 |
+
</text>
|
| 167 |
+
|
| 168 |
+
<!-- WCO badge -->
|
| 169 |
+
<rect x="370" y="562" width="240" height="30" rx="15" fill="#C8A951"/>
|
| 170 |
+
<text x="490" y="582" text-anchor="middle" font-family="Georgia" font-size="11" fill="#003087" font-weight="bold">
|
| 171 |
+
🌐 WCO Accredited Expert Framework
|
| 172 |
+
</text>
|
| 173 |
+
</svg>
|
| 174 |
+
"""
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def show():
|
| 178 |
+
inject_global_css()
|
| 179 |
+
page_header("🛃", "No-CelH: Self-Learning RMS",
|
| 180 |
+
"WCO ACCREDITED · CUSTOMS RISK MANAGEMENT SYSTEM · ACTIVE LEARNING SIMULATION")
|
| 181 |
+
|
| 182 |
+
# ── KPI strip ─────────────────────────────────────────────────
|
| 183 |
+
metric_row([
|
| 184 |
+
("5", "Risk Areas", WCO_GOLD),
|
| 185 |
+
("1,000","Declarations / Run", WCO_BLUE),
|
| 186 |
+
("10%", "Interdiction Bandwidth", WCO_RED),
|
| 187 |
+
("0.82", "Target Efficiency Index", WCO_GREEN),
|
| 188 |
+
("2×", "Revenue vs Static", WCO_GOLD),
|
| 189 |
+
])
|
| 190 |
+
|
| 191 |
+
# ── Architecture SVG ──────────────────────────────────────────
|
| 192 |
+
st.markdown('<div class="section-title">🏗️ System Architecture</div>', unsafe_allow_html=True)
|
| 193 |
+
st.markdown(ARCH_SVG, unsafe_allow_html=True)
|
| 194 |
+
|
| 195 |
+
st.markdown("<br/>", unsafe_allow_html=True)
|
| 196 |
+
|
| 197 |
+
# ── Three info columns ────────────────────────────────────────
|
| 198 |
+
c1, c2, c3 = st.columns(3)
|
| 199 |
+
with c1:
|
| 200 |
+
st.markdown("""
|
| 201 |
+
<div class="wco-card">
|
| 202 |
+
<h3>🎯 Objectives</h3>
|
| 203 |
+
<ul style="color:#D0DCF0;font-size:13px;line-height:2;padding-left:16px;">
|
| 204 |
+
<li>Demonstrate <b style="color:#C8A951;">self-learning RMS</b> vs static models</li>
|
| 205 |
+
<li>Prove exploration + exploitation <b style="color:#44CC88;">hybrid superiority</b></li>
|
| 206 |
+
<li>Optimise <b>10% interdiction bandwidth</b> dynamically</li>
|
| 207 |
+
<li>Build offence database via Red/Yellow feedback</li>
|
| 208 |
+
<li>Adapt to <b style="color:#CC77FF;">concept drift</b> in real-time</li>
|
| 209 |
+
<li>WCO compendium risk scoring with 5 risk areas</li>
|
| 210 |
+
</ul></div>""", unsafe_allow_html=True)
|
| 211 |
+
with c2:
|
| 212 |
+
st.markdown("""
|
| 213 |
+
<div class="wco-card">
|
| 214 |
+
<h3>📖 How to Use This App</h3>
|
| 215 |
+
<div style="color:#D0DCF0;font-size:13px;line-height:2.0;">
|
| 216 |
+
<p><b style="color:#C8A951;">📋 Page 2 →</b> Configure 5-area Risk Register, 3×3 Matrix, rules & annual weights</p>
|
| 217 |
+
<p><b style="color:#C8A951;">🔄 Page 3 →</b> Run live simulation — watch 1,000 bills routed in real-time</p>
|
| 218 |
+
<p><b style="color:#C8A951;">📊 Page 4 →</b> Analyse offence DB growth, exploration gains, rule hit tables</p>
|
| 219 |
+
<p><b style="color:#C8A951;">🏆 Page 5 →</b> Optimisation report — efficiency, accuracy, bandwidth ROI</p>
|
| 220 |
+
</div></div>""", unsafe_allow_html=True)
|
| 221 |
+
with c3:
|
| 222 |
+
st.markdown("""
|
| 223 |
+
<div class="wco-card">
|
| 224 |
+
<h3>🔬 Recommended Exploration Strategy</h3>
|
| 225 |
+
<div style="color:#D0DCF0;font-size:13px;line-height:2.0;">
|
| 226 |
+
<p><b style="color:#CC77FF;">bATE</b> — Best for customs context</p>
|
| 227 |
+
<p>✅ Uncertainty-scaled gradient embeddings</p>
|
| 228 |
+
<p>✅ Revenue-weighted diversity (K-means++)</p>
|
| 229 |
+
<p>✅ Outperforms BADGE & random by large margin</p>
|
| 230 |
+
<p>✅ Anomaly + probability-based hybrid sampling</p>
|
| 231 |
+
<p style="color:#6B85AA;font-size:11px;">gATE adds gatekeeping randomness for adversarial robustness</p>
|
| 232 |
+
</div></div>""", unsafe_allow_html=True)
|
| 233 |
+
|
| 234 |
+
# ── How RMS works ─────────────────────────────────────────────
|
| 235 |
+
st.markdown('<div class="section-title">⚙️ How the Self-Learning Cycle Works</div>',
|
| 236 |
+
unsafe_allow_html=True)
|
| 237 |
+
|
| 238 |
+
steps = [
|
| 239 |
+
("1", "#C8A951", "📥 Ingest", "Batch of import declarations enters the scoring pipeline each week"),
|
| 240 |
+
("2", "#0066CC", "🧠 Score (DATE)", "Exploitation engine scores each bill: fraud probability ŷᶜˡˢ + revenue ŷʳᵉᵛ"),
|
| 241 |
+
("3", "#9933CC", "🔍 Explore (gATE)","Exploration engine identifies uncertain bills (unc_i near 0.5) for new knowledge"),
|
| 242 |
+
("4", "#C8A951", "⚖️ Hybrid Select", "10% bandwidth split: 90% exploitation + 10% exploration → RED/YELLOW/GREEN"),
|
| 243 |
+
("5", "#0066CC", "👮 Inspect", "Officers examine Red & Yellow — outcomes labelled (fraud / clean / doc-query)"),
|
| 244 |
+
("6", "#00843D", "🗄️ Feedback", "Confirmed frauds augment offence DB; rule weights auto-update → model retrains"),
|
| 245 |
+
]
|
| 246 |
+
cols = st.columns(6)
|
| 247 |
+
for i, (num, col, title, desc) in enumerate(steps):
|
| 248 |
+
with cols[i]:
|
| 249 |
+
st.markdown(f"""
|
| 250 |
+
<div style="background:#0F1C35;border:1px solid {col};border-radius:10px;
|
| 251 |
+
padding:16px 12px;text-align:center;height:160px;">
|
| 252 |
+
<div style="background:{col};color:#070E1C;border-radius:50%;width:28px;height:28px;
|
| 253 |
+
line-height:28px;font-weight:700;margin:0 auto 10px;font-size:14px;">{num}</div>
|
| 254 |
+
<div style="color:{col};font-weight:600;font-size:12px;margin-bottom:8px;">{title}</div>
|
| 255 |
+
<div style="color:#8BAAD4;font-size:11px;line-height:1.5;">{desc}</div>
|
| 256 |
+
</div>""", unsafe_allow_html=True)
|
| 257 |
+
|
| 258 |
+
st.markdown("<br/>", unsafe_allow_html=True)
|
| 259 |
+
|
| 260 |
+
# ── Scientific basis ──────────────────────────────────────────
|
| 261 |
+
with st.expander("📚 Scientific Basis & Mathematical Formulas"):
|
| 262 |
+
fc1, fc2 = st.columns(2)
|
| 263 |
+
with fc1:
|
| 264 |
+
st.markdown("""
|
| 265 |
+
<div class="wco-card-gold">
|
| 266 |
+
<h3>DATE Exploitation Engine</h3>
|
| 267 |
+
<p style="color:#D0DCF0;font-size:13px;">Dual Attentive Tree-aware Embedding model optimises two objectives simultaneously:</p>
|
| 268 |
+
<ul style="color:#D0DCF0;font-size:13px;line-height:2;">
|
| 269 |
+
<li><b style="color:#44CC88;">ŷᶜˡˢ</b> — Probability of fraudulent transaction</li>
|
| 270 |
+
<li><b style="color:#44CC88;">ŷʳᵉᵛ</b> — Predicted additional revenue upon inspection</li>
|
| 271 |
+
</ul>
|
| 272 |
+
<p style="color:#C8A951;font-family:monospace;font-size:13px;">
|
| 273 |
+
h_θ(x) = σ(W · z_φ(x))
|
| 274 |
+
</p>
|
| 275 |
+
</div>""", unsafe_allow_html=True)
|
| 276 |
+
with fc2:
|
| 277 |
+
st.markdown("""
|
| 278 |
+
<div class="wco-card-gold">
|
| 279 |
+
<h3>gATE Exploration Engine</h3>
|
| 280 |
+
<p style="color:#D0DCF0;font-size:13px;">Selects uncertain, high-revenue, diverse bills via:</p>
|
| 281 |
+
<ul style="color:#D0DCF0;font-size:13px;line-height:2;">
|
| 282 |
+
<li><b style="color:#CC77FF;">unc_i</b> = −1.8 × |ŷᶜˡˢ − 0.5| + 1</li>
|
| 283 |
+
<li><b style="color:#CC77FF;">S_i</b> = unc_i × log(ŷʳᵉᵛ + ε)</li>
|
| 284 |
+
<li>K-means++ seeding for batch diversity</li>
|
| 285 |
+
</ul>
|
| 286 |
+
<p style="color:#C8A951;font-family:monospace;font-size:13px;">
|
| 287 |
+
Efficiency Index = Detection Rate / Selection Rate
|
| 288 |
+
</p>
|
| 289 |
+
</div>""", unsafe_allow_html=True)
|
page2_risk_register.py
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
page2_risk_register.py — Risk Register, 3×3 Matrix, Rules, Weights
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import streamlit as st
|
| 6 |
+
import plotly.graph_objects as go
|
| 7 |
+
import pandas as pd
|
| 8 |
+
from styles import (inject_global_css, page_header, metric_row,
|
| 9 |
+
WCO_GOLD, WCO_BLUE, WCO_GREEN, WCO_RED, WCO_CARD_BG,
|
| 10 |
+
WCO_BORDER, WCO_MUTED, WCO_GREY_BG)
|
| 11 |
+
from simulation_engine import RISK_AREAS, get_default_weights
|
| 12 |
+
|
| 13 |
+
# ── Static risk matrix data ──────────────────────────────────────────────────
|
| 14 |
+
RISK_MATRIX_DATA = {
|
| 15 |
+
"Drugs & Narcotics": {"likelihood": 3, "impact": 3, "priority": 1, "color": "#C8102E"},
|
| 16 |
+
"Revenue Leakage": {"likelihood": 3, "impact": 2, "priority": 2, "color": "#F5A800"},
|
| 17 |
+
"IPR Enforcement": {"likelihood": 2, "impact": 2, "priority": 3, "color": "#9B59B6"},
|
| 18 |
+
"Environmental/Plastic Waste": {"likelihood": 2, "impact": 3, "priority": 4, "color": "#00843D"},
|
| 19 |
+
"Wildlife Smuggling": {"likelihood": 1, "impact": 3, "priority": 5, "color": "#E67E22"},
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
RISK_PRIORITY_DATA = [
|
| 23 |
+
{
|
| 24 |
+
"Priority": 1, "Risk Area": "Drugs & Narcotics",
|
| 25 |
+
"Likelihood": "High (3)", "Impact": "High (3)",
|
| 26 |
+
"Risk Level": "CRITICAL", "Strategy": "Exploit + Explore",
|
| 27 |
+
"Annual Target": "Zero tolerance – 100% risk-score flagging",
|
| 28 |
+
"WCO Reference": "Compendium Vol.1 Ch.3",
|
| 29 |
+
},
|
| 30 |
+
{
|
| 31 |
+
"Priority": 2, "Risk Area": "Revenue Leakage",
|
| 32 |
+
"Likelihood": "High (3)", "Impact": "Medium (2)",
|
| 33 |
+
"Risk Level": "HIGH", "Strategy": "DATE Exploitation",
|
| 34 |
+
"Annual Target": "≥85% recovery rate on flagged shipments",
|
| 35 |
+
"WCO Reference": "Compendium Vol.2 Ch.6",
|
| 36 |
+
},
|
| 37 |
+
{
|
| 38 |
+
"Priority": 3, "Risk Area": "IPR Enforcement",
|
| 39 |
+
"Likelihood": "Medium (2)", "Impact": "Medium (2)",
|
| 40 |
+
"Risk Level": "MEDIUM", "Strategy": "Hybrid (DATE 80/gATE 20)",
|
| 41 |
+
"Annual Target": "500 seizures/year, 30% uplift YoY",
|
| 42 |
+
"WCO Reference": "TRIPS/WCO IPR Guidelines",
|
| 43 |
+
},
|
| 44 |
+
{
|
| 45 |
+
"Priority": 4, "Risk Area": "Environmental/Plastic Waste",
|
| 46 |
+
"Likelihood": "Medium (2)", "Impact": "High (3)",
|
| 47 |
+
"Risk Level": "HIGH", "Strategy": "gATE Exploration",
|
| 48 |
+
"Annual Target": "Basel Convention compliance 95%",
|
| 49 |
+
"WCO Reference": "Compendium Vol.3 Ch.9",
|
| 50 |
+
},
|
| 51 |
+
{
|
| 52 |
+
"Priority": 5, "Risk Area": "Wildlife Smuggling",
|
| 53 |
+
"Likelihood": "Low (1)", "Impact": "High (3)",
|
| 54 |
+
"Risk Level": "MEDIUM-HIGH", "Strategy": "Hybrid (DATE 70/gATE 30)",
|
| 55 |
+
"Annual Target": "CITES compliance 100%; 200 cases/year",
|
| 56 |
+
"WCO Reference": "CITES/WCO Wildlife Guidelines",
|
| 57 |
+
},
|
| 58 |
+
]
|
| 59 |
+
|
| 60 |
+
RISK_COLORS_LEVEL = {
|
| 61 |
+
"CRITICAL": "#C8102E", "HIGH": "#F5A800",
|
| 62 |
+
"MEDIUM-HIGH": "#E67E22", "MEDIUM": "#9B59B6", "LOW": "#00843D",
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def risk_matrix_chart():
|
| 67 |
+
"""3×3 WCO Risk Matrix with plotted risks."""
|
| 68 |
+
fig = go.Figure()
|
| 69 |
+
|
| 70 |
+
# Background zones
|
| 71 |
+
zone_colors = [
|
| 72 |
+
# (x0,y0,x1,y1, fill)
|
| 73 |
+
(0.5, 2.5, 3.5, 3.5, "rgba(200,16,46,0.18)"), # High-High
|
| 74 |
+
(0.5, 1.5, 3.5, 2.5, "rgba(245,168,0,0.13)"), # Medium row
|
| 75 |
+
(0.5, 0.5, 3.5, 1.5, "rgba(0,132,61,0.12)"), # Low row
|
| 76 |
+
]
|
| 77 |
+
for x0, y0, x1, y1, fill in zone_colors:
|
| 78 |
+
fig.add_shape(type="rect", x0=x0, y0=y0, x1=x1, y1=y1,
|
| 79 |
+
fillcolor=fill, line_width=0, layer="below")
|
| 80 |
+
|
| 81 |
+
# Grid lines
|
| 82 |
+
for v in [1.5, 2.5]:
|
| 83 |
+
fig.add_shape(type="line", x0=0.5, y0=v, x1=3.5, y1=v,
|
| 84 |
+
line=dict(color="#1E3A6E", width=1))
|
| 85 |
+
fig.add_shape(type="line", x0=v, y0=0.5, x1=v, y1=3.5,
|
| 86 |
+
line=dict(color="#1E3A6E", width=1))
|
| 87 |
+
|
| 88 |
+
# Plot risks
|
| 89 |
+
for name, d in RISK_MATRIX_DATA.items():
|
| 90 |
+
short = name.replace("Environmental/Plastic Waste","Env/Plastic").replace("Revenue Leakage","Revenue")
|
| 91 |
+
fig.add_trace(go.Scatter(
|
| 92 |
+
x=[d["likelihood"]], y=[d["impact"]],
|
| 93 |
+
mode="markers+text",
|
| 94 |
+
marker=dict(size=38, color=d["color"], opacity=0.88,
|
| 95 |
+
line=dict(color="#C8A951", width=1.5)),
|
| 96 |
+
text=[f"<b>P{d['priority']}</b>"],
|
| 97 |
+
textfont=dict(color="white", size=13, family="Georgia"),
|
| 98 |
+
textposition="middle center",
|
| 99 |
+
name=short,
|
| 100 |
+
hovertemplate=(f"<b>{name}</b><br>Likelihood: {d['likelihood']}"
|
| 101 |
+
f"<br>Impact: {d['impact']}<br>Priority: {d['priority']}<extra></extra>"),
|
| 102 |
+
))
|
| 103 |
+
|
| 104 |
+
fig.update_layout(
|
| 105 |
+
paper_bgcolor="#070E1C", plot_bgcolor="#0B1220",
|
| 106 |
+
font=dict(family="IBM Plex Sans", color="#D0DCF0"),
|
| 107 |
+
height=420,
|
| 108 |
+
margin=dict(l=60, r=20, t=50, b=60),
|
| 109 |
+
xaxis=dict(
|
| 110 |
+
title="<b>Likelihood →</b>", range=[0.5, 3.5],
|
| 111 |
+
tickvals=[1,2,3], ticktext=["Low","Medium","High"],
|
| 112 |
+
gridcolor="#1E3A6E", zerolinecolor="#1E3A6E",
|
| 113 |
+
title_font_color=WCO_GOLD,
|
| 114 |
+
),
|
| 115 |
+
yaxis=dict(
|
| 116 |
+
title="<b>← Impact</b>", range=[0.5, 3.5],
|
| 117 |
+
tickvals=[1,2,3], ticktext=["Low","Medium","High"],
|
| 118 |
+
gridcolor="#1E3A6E", zerolinecolor="#1E3A6E",
|
| 119 |
+
title_font_color=WCO_GOLD,
|
| 120 |
+
),
|
| 121 |
+
title=dict(text="<b>WCO 3×3 Risk Matrix — Customs Risk Areas</b>",
|
| 122 |
+
font=dict(color=WCO_GOLD, size=15, family="Playfair Display, Georgia"),
|
| 123 |
+
x=0.5),
|
| 124 |
+
showlegend=True,
|
| 125 |
+
legend=dict(bgcolor="#0F1C35", bordercolor=WCO_BORDER, borderwidth=1,
|
| 126 |
+
font=dict(size=11), x=1.01, y=0.98),
|
| 127 |
+
)
|
| 128 |
+
return fig
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def rules_weight_editor(default_weights: dict) -> dict:
|
| 132 |
+
"""Render editable weight sliders per rule and return current weights."""
|
| 133 |
+
st.markdown('<div class="section-title">⚙️ Risk Rules Configuration & Annual Weights</div>',
|
| 134 |
+
unsafe_allow_html=True)
|
| 135 |
+
st.markdown("""<div class="alert-gold">
|
| 136 |
+
Adjust annual weights for each risk rule. Weights are automatically recalibrated
|
| 137 |
+
after each simulation based on detection efficiency (self-learning feedback loop).
|
| 138 |
+
</div>""", unsafe_allow_html=True)
|
| 139 |
+
|
| 140 |
+
updated = {}
|
| 141 |
+
for area_name, area_cfg in RISK_AREAS.items():
|
| 142 |
+
icon = area_cfg["icon"]
|
| 143 |
+
color = area_cfg["color"]
|
| 144 |
+
with st.expander(f"{icon} {area_name}", expanded=False):
|
| 145 |
+
sub_label = ""
|
| 146 |
+
if "sub_areas" in area_cfg:
|
| 147 |
+
sub_label = f" *(Sub-areas: {', '.join(area_cfg['sub_areas'])})*"
|
| 148 |
+
st.markdown(f"<span style='color:{color};font-size:13px;'>{sub_label}</span>",
|
| 149 |
+
unsafe_allow_html=True)
|
| 150 |
+
|
| 151 |
+
rule_data = []
|
| 152 |
+
for rule in area_cfg["rules"]:
|
| 153 |
+
rid = rule["id"]
|
| 154 |
+
rname = rule["name"]
|
| 155 |
+
sub = rule.get("sub", "")
|
| 156 |
+
col1, col2, col3 = st.columns([1, 3, 2])
|
| 157 |
+
with col1:
|
| 158 |
+
st.markdown(f"<span style='color:{color};font-weight:600;font-size:12px;'>{rid}</span>",
|
| 159 |
+
unsafe_allow_html=True)
|
| 160 |
+
if sub:
|
| 161 |
+
st.caption(sub)
|
| 162 |
+
with col2:
|
| 163 |
+
st.markdown(f"<span style='color:#D0DCF0;font-size:13px;'>{rname}</span>",
|
| 164 |
+
unsafe_allow_html=True)
|
| 165 |
+
with col3:
|
| 166 |
+
w = st.slider(
|
| 167 |
+
f"Weight [{rid}]", 0.05, 0.60,
|
| 168 |
+
float(default_weights.get(rid, rule["weight"])),
|
| 169 |
+
step=0.01, key=f"w_{rid}",
|
| 170 |
+
label_visibility="collapsed",
|
| 171 |
+
)
|
| 172 |
+
updated[rid] = w
|
| 173 |
+
rule_data.append((rid, rname, sub, w))
|
| 174 |
+
st.markdown("<hr style='margin:4px 0;border-color:#1E3A6E;'>", unsafe_allow_html=True)
|
| 175 |
+
|
| 176 |
+
# Mini weight chart
|
| 177 |
+
if rule_data:
|
| 178 |
+
ids = [r[0] for r in rule_data]
|
| 179 |
+
names = [r[1][:30] for r in rule_data]
|
| 180 |
+
vals = [r[3] for r in rule_data]
|
| 181 |
+
mini = go.Figure(go.Bar(
|
| 182 |
+
x=ids, y=vals,
|
| 183 |
+
marker_color=color, opacity=0.85,
|
| 184 |
+
text=[f"{v:.2f}" for v in vals],
|
| 185 |
+
textposition="outside",
|
| 186 |
+
textfont=dict(color="#D0DCF0", size=10),
|
| 187 |
+
hovertext=names, hoverinfo="text+y",
|
| 188 |
+
))
|
| 189 |
+
mini.update_layout(
|
| 190 |
+
paper_bgcolor="transparent", plot_bgcolor="#0B1220",
|
| 191 |
+
height=180, margin=dict(l=10, r=10, t=10, b=30),
|
| 192 |
+
font=dict(color="#D0DCF0", size=10),
|
| 193 |
+
xaxis=dict(gridcolor="#1E3A6E"),
|
| 194 |
+
yaxis=dict(gridcolor="#1E3A6E", range=[0, 0.65]),
|
| 195 |
+
showlegend=False,
|
| 196 |
+
)
|
| 197 |
+
st.plotly_chart(mini, use_container_width=True)
|
| 198 |
+
|
| 199 |
+
return updated
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def show():
|
| 203 |
+
inject_global_css()
|
| 204 |
+
page_header("📋", "Risk Register & Risk Matrix",
|
| 205 |
+
"WCO RISK MANAGEMENT COMPENDIUM · 5 RISK AREAS · ANNUAL WEIGHT CONFIGURATION")
|
| 206 |
+
|
| 207 |
+
metric_row([
|
| 208 |
+
("5", "Risk Areas", WCO_GOLD),
|
| 209 |
+
("26", "Risk Rules Total", WCO_BLUE),
|
| 210 |
+
("3×3", "Risk Matrix", WCO_RED),
|
| 211 |
+
("Annual","Weight Cycle", WCO_GREEN),
|
| 212 |
+
("WCO", "Compendium Ref.", WCO_GOLD),
|
| 213 |
+
])
|
| 214 |
+
|
| 215 |
+
# ── Risk Matrix ───────────────────────────────────────────────
|
| 216 |
+
st.markdown('<div class="section-title">📊 3×3 Risk Priority Matrix</div>', unsafe_allow_html=True)
|
| 217 |
+
c_mat, c_legend = st.columns([2, 1])
|
| 218 |
+
with c_mat:
|
| 219 |
+
st.plotly_chart(risk_matrix_chart(), use_container_width=True)
|
| 220 |
+
with c_legend:
|
| 221 |
+
st.markdown("""
|
| 222 |
+
<div class="wco-card">
|
| 223 |
+
<h3>Matrix Legend</h3>
|
| 224 |
+
<div style="font-size:12px;color:#D0DCF0;line-height:2.2;">
|
| 225 |
+
<div style="background:rgba(200,16,46,0.2);padding:4px 10px;border-radius:5px;border-left:3px solid #C8102E;margin:4px 0;">
|
| 226 |
+
🟥 <b>CRITICAL</b> — Immediate action, maximum resources
|
| 227 |
+
</div>
|
| 228 |
+
<div style="background:rgba(245,168,0,0.15);padding:4px 10px;border-radius:5px;border-left:3px solid #F5A800;margin:4px 0;">
|
| 229 |
+
🟧 <b>HIGH</b> — Priority 2, enhanced monitoring
|
| 230 |
+
</div>
|
| 231 |
+
<div style="background:rgba(155,89,182,0.15);padding:4px 10px;border-radius:5px;border-left:3px solid #9B59B6;margin:4px 0;">
|
| 232 |
+
🟪 <b>MEDIUM-HIGH</b> — Balanced exploit/explore
|
| 233 |
+
</div>
|
| 234 |
+
<div style="background:rgba(0,132,61,0.15);padding:4px 10px;border-radius:5px;border-left:3px solid #00843D;margin:4px 0;">
|
| 235 |
+
🟩 <b>MEDIUM</b> — Exploration-led discovery
|
| 236 |
+
</div>
|
| 237 |
+
</div>
|
| 238 |
+
<div style="margin-top:14px;color:#6B85AA;font-size:11px;">
|
| 239 |
+
P1 = Drugs & Narcotics (High-High)<br/>
|
| 240 |
+
P2 = Revenue Leakage (High-Medium)<br/>
|
| 241 |
+
P3 = IPR Enforcement (Med-Med)<br/>
|
| 242 |
+
P4 = Environmental (Med-High)<br/>
|
| 243 |
+
P5 = Wildlife (Low-High)
|
| 244 |
+
</div>
|
| 245 |
+
</div>""", unsafe_allow_html=True)
|
| 246 |
+
|
| 247 |
+
# ── Priority Table ────────────────────────────────────────────
|
| 248 |
+
st.markdown('<div class="section-title">🗂️ Risk Prioritisation Table</div>', unsafe_allow_html=True)
|
| 249 |
+
df_prio = pd.DataFrame(RISK_PRIORITY_DATA)
|
| 250 |
+
|
| 251 |
+
rows_html = ""
|
| 252 |
+
for _, row in df_prio.iterrows():
|
| 253 |
+
level_col = RISK_COLORS_LEVEL.get(row["Risk Level"], WCO_MUTED)
|
| 254 |
+
area_col = RISK_MATRIX_DATA.get(row["Risk Area"], {}).get("color", WCO_MUTED)
|
| 255 |
+
rows_html += f"""
|
| 256 |
+
<tr>
|
| 257 |
+
<td style="text-align:center;font-weight:700;color:{WCO_GOLD};">P{row['Priority']}</td>
|
| 258 |
+
<td><span style="color:{area_col};font-weight:600;">{row['Risk Area']}</span></td>
|
| 259 |
+
<td style="text-align:center;">{row['Likelihood']}</td>
|
| 260 |
+
<td style="text-align:center;">{row['Impact']}</td>
|
| 261 |
+
<td><span style="background:{level_col}22;color:{level_col};border:1px solid {level_col};
|
| 262 |
+
border-radius:5px;padding:2px 8px;font-size:11px;font-weight:600;">
|
| 263 |
+
{row['Risk Level']}</span></td>
|
| 264 |
+
<td style="color:#CC77FF;font-size:12px;">{row['Strategy']}</td>
|
| 265 |
+
<td style="color:#8BAAD4;font-size:12px;">{row['Annual Target']}</td>
|
| 266 |
+
<td style="color:#557;font-size:11px;">{row['WCO Reference']}</td>
|
| 267 |
+
</tr>"""
|
| 268 |
+
|
| 269 |
+
st.markdown(f"""
|
| 270 |
+
<table class="wco-table">
|
| 271 |
+
<thead><tr>
|
| 272 |
+
<th>Priority</th><th>Risk Area</th><th>Likelihood</th><th>Impact</th>
|
| 273 |
+
<th>Risk Level</th><th>Selection Strategy</th><th>Annual Target</th><th>WCO Reference</th>
|
| 274 |
+
</tr></thead>
|
| 275 |
+
<tbody>{rows_html}</tbody>
|
| 276 |
+
</table>""", unsafe_allow_html=True)
|
| 277 |
+
|
| 278 |
+
st.markdown("<br/>", unsafe_allow_html=True)
|
| 279 |
+
|
| 280 |
+
# ── Rules & Weights Editor ────────────────────────────────────
|
| 281 |
+
if "rule_weights" not in st.session_state:
|
| 282 |
+
st.session_state.rule_weights = get_default_weights()
|
| 283 |
+
|
| 284 |
+
updated_weights = rules_weight_editor(st.session_state.rule_weights)
|
| 285 |
+
if st.button("💾 Save Weights to Session", type="primary"):
|
| 286 |
+
st.session_state.rule_weights = updated_weights
|
| 287 |
+
st.success("✅ Weights saved — navigate to Page 3 to run simulation with updated weights.")
|
| 288 |
+
|
| 289 |
+
# ── Risk area summary cards ───────────────────────────────────
|
| 290 |
+
st.markdown('<div class="section-title">📌 Risk Area Summary Cards</div>', unsafe_allow_html=True)
|
| 291 |
+
cols = st.columns(5)
|
| 292 |
+
for i, (area_name, area_cfg) in enumerate(RISK_AREAS.items()):
|
| 293 |
+
color = area_cfg["color"]
|
| 294 |
+
icon = area_cfg["icon"]
|
| 295 |
+
n_rules = len(area_cfg["rules"])
|
| 296 |
+
illicit = area_cfg["base_illicit_rate"]
|
| 297 |
+
sub_txt = ", ".join(area_cfg.get("sub_areas", []))
|
| 298 |
+
with cols[i]:
|
| 299 |
+
st.markdown(f"""
|
| 300 |
+
<div style="background:#0F1C35;border:1px solid {color};border-radius:11px;
|
| 301 |
+
padding:18px 14px;text-align:center;">
|
| 302 |
+
<div style="font-size:28px;">{icon}</div>
|
| 303 |
+
<div style="color:{color};font-weight:700;font-size:12px;margin:8px 0 4px;
|
| 304 |
+
font-family:'Playfair Display',serif;">{area_name}</div>
|
| 305 |
+
{'<div style="color:#6B85AA;font-size:10px;margin-bottom:6px;">'+sub_txt+'</div>' if sub_txt else ''}
|
| 306 |
+
<div style="color:#D0DCF0;font-size:12px;margin:4px 0;">{n_rules} Risk Rules</div>
|
| 307 |
+
<div style="color:#6B85AA;font-size:11px;">Base Rate: {illicit*100:.0f}%</div>
|
| 308 |
+
<div style="background:{color};height:3px;border-radius:2px;margin-top:10px;
|
| 309 |
+
opacity:0.6;width:{int(illicit*400)}%;margin-left:auto;margin-right:auto;"></div>
|
| 310 |
+
</div>""", unsafe_allow_html=True)
|
page3_simulation.py
ADDED
|
@@ -0,0 +1,863 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
page3_simulation.py — Live Simulation with Full Canvas Animation
|
| 3 |
+
All bills complete in exactly 30 seconds. WCO themed, 5-lane layout.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import streamlit as st
|
| 7 |
+
import streamlit.components.v1 as components
|
| 8 |
+
import plotly.graph_objects as go
|
| 9 |
+
import pandas as pd
|
| 10 |
+
from styles import (inject_global_css, page_header, metric_row,
|
| 11 |
+
WCO_GOLD, WCO_BLUE, WCO_GREEN, WCO_RED,
|
| 12 |
+
WCO_CARD_BG, WCO_BORDER, WCO_MUTED)
|
| 13 |
+
from simulation_engine import (generate_declarations, compute_risk_scores,
|
| 14 |
+
assign_channels, simulate_inspection_outcomes,
|
| 15 |
+
compute_updated_weights, get_default_weights,
|
| 16 |
+
compute_efficiency_metrics, RISK_AREAS)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 20 |
+
def build_animation_html(n_bills, bandwidth, exp_ratio,
|
| 21 |
+
channel_counts, detected, revenue, efficiency_idx):
|
| 22 |
+
red_n = channel_counts.get("RED", 0)
|
| 23 |
+
yellow_n = channel_counts.get("YELLOW", 0)
|
| 24 |
+
green_n = channel_counts.get("GREEN", 0)
|
| 25 |
+
explore_n = int(n_bills * bandwidth * exp_ratio)
|
| 26 |
+
|
| 27 |
+
return f"""<!DOCTYPE html>
|
| 28 |
+
<html lang="en">
|
| 29 |
+
<head>
|
| 30 |
+
<meta charset="UTF-8"/>
|
| 31 |
+
<style>
|
| 32 |
+
* {{ box-sizing:border-box; margin:0; padding:0; }}
|
| 33 |
+
body {{
|
| 34 |
+
background:#070E1C;
|
| 35 |
+
font-family:'IBM Plex Sans','Segoe UI',sans-serif;
|
| 36 |
+
color:#D0DCF0;
|
| 37 |
+
overflow:hidden;
|
| 38 |
+
height:700px;
|
| 39 |
+
display:flex;
|
| 40 |
+
flex-direction:column;
|
| 41 |
+
}}
|
| 42 |
+
|
| 43 |
+
/* ── Top KPI strip ── */
|
| 44 |
+
#kpi-bar {{
|
| 45 |
+
display:flex;
|
| 46 |
+
background:#0B1527;
|
| 47 |
+
border-bottom:3px solid #C8A951;
|
| 48 |
+
flex-shrink:0;
|
| 49 |
+
}}
|
| 50 |
+
.kpi {{
|
| 51 |
+
flex:1; padding:9px 6px; text-align:center;
|
| 52 |
+
border-right:1px solid #1E3A6E;
|
| 53 |
+
}}
|
| 54 |
+
.kpi:last-child {{ border-right:none; }}
|
| 55 |
+
.kpi-val {{
|
| 56 |
+
font-size:20px; font-weight:700;
|
| 57 |
+
font-family:'Georgia',serif; line-height:1;
|
| 58 |
+
}}
|
| 59 |
+
.kpi-lbl {{
|
| 60 |
+
font-size:9px; text-transform:uppercase;
|
| 61 |
+
letter-spacing:0.07em; color:#6B85AA; margin-top:3px;
|
| 62 |
+
}}
|
| 63 |
+
|
| 64 |
+
/* ── Canvas ── */
|
| 65 |
+
#canvas-wrap {{
|
| 66 |
+
flex:1; position:relative; overflow:hidden;
|
| 67 |
+
min-height:0;
|
| 68 |
+
}}
|
| 69 |
+
canvas {{ display:block; width:100%; height:100%; }}
|
| 70 |
+
|
| 71 |
+
/* ── Counter row ── */
|
| 72 |
+
#counter-bar {{
|
| 73 |
+
display:flex; background:#0B1527;
|
| 74 |
+
border-top:1px solid #1E3A6E; flex-shrink:0;
|
| 75 |
+
}}
|
| 76 |
+
.ch-cnt {{
|
| 77 |
+
flex:1; padding:7px 6px; text-align:center;
|
| 78 |
+
border-right:1px solid #1E3A6E; transition:background .25s;
|
| 79 |
+
}}
|
| 80 |
+
.ch-cnt:last-child {{ border-right:none; }}
|
| 81 |
+
.ch-v {{ font-size:24px; font-weight:700; font-family:'Georgia',serif; line-height:1; }}
|
| 82 |
+
.ch-l {{ font-size:9px; color:#6B85AA; margin-top:2px; text-transform:uppercase; }}
|
| 83 |
+
|
| 84 |
+
/* ── Progress ── */
|
| 85 |
+
#prog-wrap {{
|
| 86 |
+
background:#0B1527; border-top:1px solid #1E3A6E;
|
| 87 |
+
padding:7px 14px; flex-shrink:0;
|
| 88 |
+
}}
|
| 89 |
+
#prog-head {{
|
| 90 |
+
font-size:10px; color:#C8A951;
|
| 91 |
+
display:flex; justify-content:space-between; margin-bottom:4px;
|
| 92 |
+
}}
|
| 93 |
+
#prog-bg {{
|
| 94 |
+
background:#111D30; border-radius:4px; height:7px; overflow:hidden;
|
| 95 |
+
}}
|
| 96 |
+
#prog-fill {{
|
| 97 |
+
height:100%; border-radius:4px;
|
| 98 |
+
background:linear-gradient(90deg,#003087,#C8A951);
|
| 99 |
+
width:0%; transition:width .15s ease;
|
| 100 |
+
}}
|
| 101 |
+
</style>
|
| 102 |
+
</head>
|
| 103 |
+
<body>
|
| 104 |
+
|
| 105 |
+
<!-- KPI Header -->
|
| 106 |
+
<div id="kpi-bar">
|
| 107 |
+
<div class="kpi">
|
| 108 |
+
<div class="kpi-val" style="color:#D0DCF0;">{n_bills}</div>
|
| 109 |
+
<div class="kpi-lbl">Total Declarations</div>
|
| 110 |
+
</div>
|
| 111 |
+
<div class="kpi">
|
| 112 |
+
<div class="kpi-val" style="color:#C8102E;">{red_n}</div>
|
| 113 |
+
<div class="kpi-lbl">🔴 RED Target</div>
|
| 114 |
+
</div>
|
| 115 |
+
<div class="kpi">
|
| 116 |
+
<div class="kpi-val" style="color:#F5A800;">{yellow_n}</div>
|
| 117 |
+
<div class="kpi-lbl">🟡 YELLOW Target</div>
|
| 118 |
+
</div>
|
| 119 |
+
<div class="kpi">
|
| 120 |
+
<div class="kpi-val" style="color:#00843D;">{green_n}</div>
|
| 121 |
+
<div class="kpi-lbl">🟢 GREEN Target</div>
|
| 122 |
+
</div>
|
| 123 |
+
<div class="kpi">
|
| 124 |
+
<div class="kpi-val" style="color:#C8A951;">{efficiency_idx:.3f}</div>
|
| 125 |
+
<div class="kpi-lbl">Efficiency Index</div>
|
| 126 |
+
</div>
|
| 127 |
+
<div class="kpi">
|
| 128 |
+
<div class="kpi-val" style="color:#44CC88;">${revenue:,.0f}</div>
|
| 129 |
+
<div class="kpi-lbl">Revenue Recovered</div>
|
| 130 |
+
</div>
|
| 131 |
+
<div class="kpi">
|
| 132 |
+
<div class="kpi-val" style="color:#CC77FF;">{detected}</div>
|
| 133 |
+
<div class="kpi-lbl">Frauds Detected</div>
|
| 134 |
+
</div>
|
| 135 |
+
</div>
|
| 136 |
+
|
| 137 |
+
<!-- Canvas -->
|
| 138 |
+
<div id="canvas-wrap">
|
| 139 |
+
<canvas id="sim"></canvas>
|
| 140 |
+
</div>
|
| 141 |
+
|
| 142 |
+
<!-- Live counters -->
|
| 143 |
+
<div id="counter-bar">
|
| 144 |
+
<div class="ch-cnt" id="cnt-total">
|
| 145 |
+
<div class="ch-v" id="v-total" style="color:#D0DCF0;">0</div>
|
| 146 |
+
<div class="ch-l">📦 Processed</div>
|
| 147 |
+
</div>
|
| 148 |
+
<div class="ch-cnt" id="cnt-red">
|
| 149 |
+
<div class="ch-v" id="v-red" style="color:#C8102E;">0</div>
|
| 150 |
+
<div class="ch-l">🔴 Physical Exam</div>
|
| 151 |
+
</div>
|
| 152 |
+
<div class="ch-cnt" id="cnt-yel">
|
| 153 |
+
<div class="ch-v" id="v-yel" style="color:#F5A800;">0</div>
|
| 154 |
+
<div class="ch-l">🟡 Doc Check</div>
|
| 155 |
+
</div>
|
| 156 |
+
<div class="ch-cnt" id="cnt-grn">
|
| 157 |
+
<div class="ch-v" id="v-grn" style="color:#00843D;">0</div>
|
| 158 |
+
<div class="ch-l">🟢 Facilitated</div>
|
| 159 |
+
</div>
|
| 160 |
+
<div class="ch-cnt" id="cnt-exp">
|
| 161 |
+
<div class="ch-v" id="v-exp" style="color:#CC77FF;">0</div>
|
| 162 |
+
<div class="ch-l">🔍 gATE Explore</div>
|
| 163 |
+
</div>
|
| 164 |
+
<div class="ch-cnt" id="cnt-fraud">
|
| 165 |
+
<div class="ch-v" id="v-fraud" style="color:#FF4466;">0</div>
|
| 166 |
+
<div class="ch-l">🚨 Fraud Detected</div>
|
| 167 |
+
</div>
|
| 168 |
+
</div>
|
| 169 |
+
|
| 170 |
+
<!-- Progress -->
|
| 171 |
+
<div id="prog-wrap">
|
| 172 |
+
<div id="prog-head">
|
| 173 |
+
<span id="stage-label">Initialising...</span>
|
| 174 |
+
<span id="prog-pct">0%</span>
|
| 175 |
+
</div>
|
| 176 |
+
<div id="prog-bg"><div id="prog-fill"></div></div>
|
| 177 |
+
</div>
|
| 178 |
+
|
| 179 |
+
<script>
|
| 180 |
+
// ═══════════════════ CONFIG ═══════════════════
|
| 181 |
+
const TOTAL = {n_bills};
|
| 182 |
+
const DUR_MS = 30000;
|
| 183 |
+
const RED_T = {red_n};
|
| 184 |
+
const YEL_T = {yellow_n};
|
| 185 |
+
const GRN_T = {green_n};
|
| 186 |
+
const FRAUD_T = {detected};
|
| 187 |
+
const EXP_T = {explore_n};
|
| 188 |
+
|
| 189 |
+
// ═══════════════════ CANVAS ═══════════════════
|
| 190 |
+
const canvas = document.getElementById('sim');
|
| 191 |
+
const ctx = canvas.getContext('2d');
|
| 192 |
+
let W, H;
|
| 193 |
+
|
| 194 |
+
function resize() {{
|
| 195 |
+
const wrap = document.getElementById('canvas-wrap');
|
| 196 |
+
W = canvas.width = wrap.clientWidth || 900;
|
| 197 |
+
H = canvas.height = wrap.clientHeight || 380;
|
| 198 |
+
}}
|
| 199 |
+
window.addEventListener('resize', resize);
|
| 200 |
+
resize();
|
| 201 |
+
|
| 202 |
+
// ═══════════════════ LAYOUT ═══════════════════
|
| 203 |
+
// 5 lanes: 0=INTAKE 1=RED 2=YELLOW 3=GREEN 4=OFFENCEDB
|
| 204 |
+
const NUM_LANES = 5;
|
| 205 |
+
function laneW() {{ return W / NUM_LANES; }}
|
| 206 |
+
function laneCX(i){{ return i * laneW() + laneW() / 2; }}
|
| 207 |
+
function gateY() {{ return H * 0.52; }}
|
| 208 |
+
|
| 209 |
+
// ═══════════════════ PRE-COMPUTE SEQUENCES ═══
|
| 210 |
+
// Build shuffled channel array
|
| 211 |
+
const channelSeq = [];
|
| 212 |
+
(function() {{
|
| 213 |
+
const a = [];
|
| 214 |
+
for(let i=0;i<RED_T;i++) a.push('RED');
|
| 215 |
+
for(let i=0;i<YEL_T;i++) a.push('YELLOW');
|
| 216 |
+
for(let i=0;i<GRN_T;i++) a.push('GREEN');
|
| 217 |
+
for(let i=a.length-1;i>0;i--) {{
|
| 218 |
+
const j=Math.floor(Math.random()*(i+1));
|
| 219 |
+
[a[i],a[j]]=[a[j],a[i]];
|
| 220 |
+
}}
|
| 221 |
+
channelSeq.push(...a);
|
| 222 |
+
}})();
|
| 223 |
+
|
| 224 |
+
// Mark exploration indices
|
| 225 |
+
const exploreSet = new Set();
|
| 226 |
+
(function() {{
|
| 227 |
+
const pool=[];
|
| 228 |
+
channelSeq.forEach((c,i)=>{{ if(c==='RED'||c==='YELLOW') pool.push(i); }});
|
| 229 |
+
const need = Math.min(EXP_T, pool.length);
|
| 230 |
+
while(exploreSet.size < need) {{
|
| 231 |
+
exploreSet.add(pool[Math.floor(Math.random()*pool.length)]);
|
| 232 |
+
}}
|
| 233 |
+
}})();
|
| 234 |
+
|
| 235 |
+
// Mark fraud indices (subset of inspected)
|
| 236 |
+
const fraudSet = new Set();
|
| 237 |
+
(function() {{
|
| 238 |
+
const pool=[];
|
| 239 |
+
channelSeq.forEach((c,i)=>{{ if(c==='RED'||c==='YELLOW') pool.push(i); }});
|
| 240 |
+
const need = Math.min(FRAUD_T, pool.length);
|
| 241 |
+
while(fraudSet.size < need) {{
|
| 242 |
+
fraudSet.add(pool[Math.floor(Math.random()*pool.length)]);
|
| 243 |
+
}}
|
| 244 |
+
}})();
|
| 245 |
+
|
| 246 |
+
// ═══════════════════ COUNTERS ═══════════════════
|
| 247 |
+
const C = {{ total:0, RED:0, YELLOW:0, GREEN:0, explore:0, fraud:0 }};
|
| 248 |
+
|
| 249 |
+
function updateDOM() {{
|
| 250 |
+
document.getElementById('v-total').textContent = C.total;
|
| 251 |
+
document.getElementById('v-red').textContent = C.RED;
|
| 252 |
+
document.getElementById('v-yel').textContent = C.YELLOW;
|
| 253 |
+
document.getElementById('v-grn').textContent = C.GREEN;
|
| 254 |
+
document.getElementById('v-exp').textContent = C.explore;
|
| 255 |
+
document.getElementById('v-fraud').textContent = C.fraud;
|
| 256 |
+
|
| 257 |
+
// flash
|
| 258 |
+
const flash = (id, col) => {{
|
| 259 |
+
const el = document.getElementById(id);
|
| 260 |
+
el.style.background = col+'25';
|
| 261 |
+
setTimeout(()=>{{ el.style.background=''; }}, 220);
|
| 262 |
+
}};
|
| 263 |
+
if(C.RED > 0 && C.RED % 2 === 0) flash('cnt-red', '#C8102E');
|
| 264 |
+
if(C.YELLOW > 0 && C.YELLOW % 2 === 0) flash('cnt-yel', '#F5A800');
|
| 265 |
+
if(C.GREEN > 0 && C.GREEN % 5 === 0) flash('cnt-grn', '#00843D');
|
| 266 |
+
if(C.fraud > 0) flash('cnt-fraud','#FF4466');
|
| 267 |
+
}}
|
| 268 |
+
|
| 269 |
+
// ═══════════════════ BACKGROUND ═══════════════════
|
| 270 |
+
const LANE_STYLES = [
|
| 271 |
+
{{ top:'#0A1E4A', bot:'#060D28', hdr:'INTAKE', sub:'All Declarations', col:'#8BAAD4' }},
|
| 272 |
+
{{ top:'#1E0008', bot:'#0D0004', hdr:'🔴 RED', sub:'Physical Examination',col:'#FF4466' }},
|
| 273 |
+
{{ top:'#1A1000', bot:'#0D0800', hdr:'🟡 YELLOW', sub:'Document Check', col:'#FFD700' }},
|
| 274 |
+
{{ top:'#001A09', bot:'#000D04', hdr:'🟢 GREEN', sub:'Facilitated', col:'#44CC88' }},
|
| 275 |
+
{{ top:'#110A1E', bot:'#080512', hdr:'🗄️ OFFENCE', sub:'Knowledge Vault', col:'#CC77FF' }},
|
| 276 |
+
];
|
| 277 |
+
|
| 278 |
+
function drawBG() {{
|
| 279 |
+
const lw = laneW();
|
| 280 |
+
|
| 281 |
+
LANE_STYLES.forEach((s,i) => {{
|
| 282 |
+
const g = ctx.createLinearGradient(i*lw,0,i*lw,H);
|
| 283 |
+
g.addColorStop(0, s.top);
|
| 284 |
+
g.addColorStop(1, s.bot);
|
| 285 |
+
ctx.fillStyle = g;
|
| 286 |
+
ctx.fillRect(i*lw, 0, lw, H);
|
| 287 |
+
}});
|
| 288 |
+
|
| 289 |
+
// Dividers
|
| 290 |
+
ctx.strokeStyle='#1E3A6E'; ctx.lineWidth=1.2;
|
| 291 |
+
for(let i=1;i<NUM_LANES;i++) {{
|
| 292 |
+
ctx.beginPath(); ctx.moveTo(i*lw,0); ctx.lineTo(i*lw,H); ctx.stroke();
|
| 293 |
+
}}
|
| 294 |
+
|
| 295 |
+
// Lane headers
|
| 296 |
+
LANE_STYLES.forEach((s,i) => {{
|
| 297 |
+
const cx = laneCX(i);
|
| 298 |
+
ctx.fillStyle='rgba(0,0,0,0.55)';
|
| 299 |
+
ctx.beginPath(); ctx.roundRect(i*lw+6,8,lw-12,46,7); ctx.fill();
|
| 300 |
+
ctx.strokeStyle=s.col+'44'; ctx.lineWidth=1;
|
| 301 |
+
ctx.beginPath(); ctx.roundRect(i*lw+6,8,lw-12,46,7); ctx.stroke();
|
| 302 |
+
|
| 303 |
+
ctx.fillStyle=s.col;
|
| 304 |
+
ctx.font='bold 13px Georgia,serif';
|
| 305 |
+
ctx.textAlign='center';
|
| 306 |
+
ctx.fillText(s.hdr, cx, 30);
|
| 307 |
+
ctx.fillStyle='#6B85AA';
|
| 308 |
+
ctx.font='10px sans-serif';
|
| 309 |
+
ctx.fillText(s.sub, cx, 46);
|
| 310 |
+
}});
|
| 311 |
+
|
| 312 |
+
// Gate band
|
| 313 |
+
const gy = gateY();
|
| 314 |
+
const gg = ctx.createLinearGradient(0,gy-28,0,gy+28);
|
| 315 |
+
gg.addColorStop(0,'rgba(0,48,135,0)');
|
| 316 |
+
gg.addColorStop(0.5,'rgba(0,48,135,0.9)');
|
| 317 |
+
gg.addColorStop(1,'rgba(0,48,135,0)');
|
| 318 |
+
ctx.fillStyle=gg;
|
| 319 |
+
ctx.fillRect(0,gy-28,W,56);
|
| 320 |
+
|
| 321 |
+
ctx.strokeStyle='#C8A951'; ctx.lineWidth=1.4;
|
| 322 |
+
ctx.setLineDash([8,5]);
|
| 323 |
+
ctx.beginPath(); ctx.moveTo(0,gy-24); ctx.lineTo(W,gy-24); ctx.stroke();
|
| 324 |
+
ctx.beginPath(); ctx.moveTo(0,gy+24); ctx.lineTo(W,gy+24); ctx.stroke();
|
| 325 |
+
ctx.setLineDash([]);
|
| 326 |
+
|
| 327 |
+
// Gate booths
|
| 328 |
+
const boothData = [
|
| 329 |
+
{{label:'DATE SCORING', col:'#C8A951'}},
|
| 330 |
+
{{label:'RED CHANNEL', col:'#C8102E'}},
|
| 331 |
+
{{label:'YELLOW CHANNEL',col:'#F5A800'}},
|
| 332 |
+
{{label:'GREEN CHANNEL', col:'#00843D'}},
|
| 333 |
+
];
|
| 334 |
+
boothData.forEach((b,i) => {{
|
| 335 |
+
const bx = laneCX(i);
|
| 336 |
+
ctx.fillStyle='#0F1C35';
|
| 337 |
+
ctx.strokeStyle=b.col; ctx.lineWidth=1.8;
|
| 338 |
+
ctx.beginPath(); ctx.roundRect(bx-40,gy-16,80,32,5); ctx.fill(); ctx.stroke();
|
| 339 |
+
ctx.fillStyle=b.col;
|
| 340 |
+
ctx.font='bold 9px IBM Plex Sans,sans-serif';
|
| 341 |
+
ctx.textAlign='center';
|
| 342 |
+
ctx.fillText(b.label, bx, gy+4);
|
| 343 |
+
// Dot indicator
|
| 344 |
+
ctx.shadowColor=b.col; ctx.shadowBlur=8;
|
| 345 |
+
ctx.beginPath(); ctx.arc(bx,gy-20,4,0,Math.PI*2);
|
| 346 |
+
ctx.fillStyle=b.col; ctx.fill();
|
| 347 |
+
ctx.shadowBlur=0;
|
| 348 |
+
}});
|
| 349 |
+
|
| 350 |
+
// Vault (offence DB)
|
| 351 |
+
const vx = laneCX(4);
|
| 352 |
+
ctx.fillStyle='#1A0A2E';
|
| 353 |
+
ctx.strokeStyle='#CC77FF'; ctx.lineWidth=2;
|
| 354 |
+
ctx.beginPath(); ctx.roundRect(vx-46,gy-20,92,40,8); ctx.fill(); ctx.stroke();
|
| 355 |
+
ctx.fillStyle='#CC77FF'; ctx.font='bold 10px Georgia';
|
| 356 |
+
ctx.textAlign='center';
|
| 357 |
+
ctx.fillText('OFFENCE DB', vx, gy-4);
|
| 358 |
+
ctx.fillStyle='#8B55CC'; ctx.font='9px sans-serif';
|
| 359 |
+
ctx.fillText('Evidence Vault', vx, gy+12);
|
| 360 |
+
|
| 361 |
+
// Bezier guide lines (intake → channels)
|
| 362 |
+
[[1,'#C8102E'],[2,'#F5A800'],[3,'#00843D']].forEach(([li,col]) => {{
|
| 363 |
+
const ix = laneCX(0), tx = laneCX(li), topY = gy-100;
|
| 364 |
+
ctx.strokeStyle=col+'28'; ctx.lineWidth=1; ctx.setLineDash([4,9]);
|
| 365 |
+
ctx.beginPath();
|
| 366 |
+
ctx.moveTo(ix, topY);
|
| 367 |
+
ctx.bezierCurveTo(ix,gy-50,tx,gy-50,tx,gy-25);
|
| 368 |
+
ctx.stroke();
|
| 369 |
+
ctx.setLineDash([]);
|
| 370 |
+
}});
|
| 371 |
+
}}
|
| 372 |
+
|
| 373 |
+
// ═══════════════════ BILL PARTICLE ═══════════════════
|
| 374 |
+
const bills = [];
|
| 375 |
+
let billIdx = 0;
|
| 376 |
+
|
| 377 |
+
const laneMap = {{ RED:1, YELLOW:2, GREEN:3 }};
|
| 378 |
+
|
| 379 |
+
class Bill {{
|
| 380 |
+
constructor(idx) {{
|
| 381 |
+
this.idx = idx;
|
| 382 |
+
this.channel = channelSeq[idx] || 'GREEN';
|
| 383 |
+
this.explore = exploreSet.has(idx);
|
| 384 |
+
this.fraud = fraudSet.has(idx);
|
| 385 |
+
|
| 386 |
+
const lw = laneW();
|
| 387 |
+
this.x = laneCX(0) + (Math.random()*24-12);
|
| 388 |
+
this.y = -20 - Math.random()*60;
|
| 389 |
+
this.vy = 0; // will be set per-frame to hit gate at exact time
|
| 390 |
+
|
| 391 |
+
this.targetX = laneCX(laneMap[this.channel]) + (Math.random()*16-8);
|
| 392 |
+
this.phase = 'intake';
|
| 393 |
+
|
| 394 |
+
// colour
|
| 395 |
+
const chC = {{ RED:'#C8102E', YELLOW:'#F5A800', GREEN:'#00843D' }};
|
| 396 |
+
this.finalColor = chC[this.channel];
|
| 397 |
+
this.color = '#3A6BB5';
|
| 398 |
+
this.alpha = 1;
|
| 399 |
+
|
| 400 |
+
// size
|
| 401 |
+
this.w = 9; this.h = 12;
|
| 402 |
+
|
| 403 |
+
// counted flags
|
| 404 |
+
this.counted = false;
|
| 405 |
+
this.fraudSent = false;
|
| 406 |
+
}}
|
| 407 |
+
|
| 408 |
+
update(elapsed) {{
|
| 409 |
+
const gy = gateY();
|
| 410 |
+
|
| 411 |
+
if(this.phase === 'intake') {{
|
| 412 |
+
// Speed to cross gate at correct time proportional to index
|
| 413 |
+
const targetArrivalMs = (this.idx / TOTAL) * DUR_MS * 0.75;
|
| 414 |
+
const remainMs = Math.max(10, targetArrivalMs - elapsed);
|
| 415 |
+
const distToGate = gy - 28 - this.y;
|
| 416 |
+
this.vy = (distToGate / remainMs) * 16; // px/frame approx
|
| 417 |
+
|
| 418 |
+
this.y += Math.max(0.8, this.vy);
|
| 419 |
+
|
| 420 |
+
if(this.y >= gy - 28) {{
|
| 421 |
+
this.phase = 'routing';
|
| 422 |
+
this.color = this.finalColor;
|
| 423 |
+
}}
|
| 424 |
+
}} else if(this.phase === 'routing') {{
|
| 425 |
+
const dx = this.targetX - this.x;
|
| 426 |
+
this.x += dx * 0.14;
|
| 427 |
+
this.y += 2.2;
|
| 428 |
+
if(Math.abs(dx) < 2.5 && this.y > gy + 32) {{
|
| 429 |
+
this.phase = 'exiting';
|
| 430 |
+
if(!this.counted) {{
|
| 431 |
+
this.counted = true;
|
| 432 |
+
C.total++;
|
| 433 |
+
C[this.channel]++;
|
| 434 |
+
if(this.explore) C.explore++;
|
| 435 |
+
if(this.fraud) C.fraud++;
|
| 436 |
+
updateDOM();
|
| 437 |
+
}}
|
| 438 |
+
}}
|
| 439 |
+
}} else if(this.phase === 'exiting') {{
|
| 440 |
+
this.y += 2.8;
|
| 441 |
+
if(this.fraud && !this.fraudSent && this.y > gateY()+90) {{
|
| 442 |
+
this.fraudSent = true;
|
| 443 |
+
offParts.push(new OffPart(this.x, this.y, this.finalColor));
|
| 444 |
+
}}
|
| 445 |
+
if(this.y > H+20) this.phase='done';
|
| 446 |
+
}}
|
| 447 |
+
}}
|
| 448 |
+
|
| 449 |
+
draw() {{
|
| 450 |
+
if(this.phase==='done') return;
|
| 451 |
+
ctx.save();
|
| 452 |
+
ctx.globalAlpha = this.alpha;
|
| 453 |
+
ctx.translate(this.x, this.y);
|
| 454 |
+
|
| 455 |
+
// Document body
|
| 456 |
+
ctx.fillStyle = this.color;
|
| 457 |
+
ctx.strokeStyle = this.color+'99';
|
| 458 |
+
ctx.lineWidth = 0.7;
|
| 459 |
+
ctx.beginPath(); ctx.roundRect(-this.w/2,-this.h/2,this.w,this.h,2);
|
| 460 |
+
ctx.fill(); ctx.stroke();
|
| 461 |
+
|
| 462 |
+
// Fold corner
|
| 463 |
+
ctx.fillStyle='rgba(255,255,255,0.18)';
|
| 464 |
+
ctx.beginPath();
|
| 465 |
+
ctx.moveTo(this.w/2-3,-this.h/2);
|
| 466 |
+
ctx.lineTo(this.w/2,-this.h/2+3);
|
| 467 |
+
ctx.lineTo(this.w/2-3,-this.h/2+3);
|
| 468 |
+
ctx.closePath(); ctx.fill();
|
| 469 |
+
|
| 470 |
+
// Lines on doc
|
| 471 |
+
ctx.strokeStyle='rgba(255,255,255,0.2)'; ctx.lineWidth=0.8;
|
| 472 |
+
[-3,0,3].forEach(dy => {{
|
| 473 |
+
ctx.beginPath();
|
| 474 |
+
ctx.moveTo(-this.w/2+2, dy);
|
| 475 |
+
ctx.lineTo(this.w/2-3, dy);
|
| 476 |
+
ctx.stroke();
|
| 477 |
+
}});
|
| 478 |
+
|
| 479 |
+
// Fraud glow
|
| 480 |
+
if(this.fraud) {{
|
| 481 |
+
ctx.shadowColor='#FF4466'; ctx.shadowBlur=10;
|
| 482 |
+
ctx.strokeStyle='#FF4466'; ctx.lineWidth=1.5;
|
| 483 |
+
ctx.beginPath(); ctx.roundRect(-this.w/2,-this.h/2,this.w,this.h,2); ctx.stroke();
|
| 484 |
+
ctx.shadowBlur=0;
|
| 485 |
+
}}
|
| 486 |
+
// Explore glow
|
| 487 |
+
if(this.explore && !this.fraud) {{
|
| 488 |
+
ctx.shadowColor='#CC77FF'; ctx.shadowBlur=7;
|
| 489 |
+
ctx.strokeStyle='#CC77FF'; ctx.lineWidth=1.2;
|
| 490 |
+
ctx.beginPath(); ctx.roundRect(-this.w/2,-this.h/2,this.w,this.h,2); ctx.stroke();
|
| 491 |
+
ctx.shadowBlur=0;
|
| 492 |
+
}}
|
| 493 |
+
|
| 494 |
+
ctx.restore();
|
| 495 |
+
}}
|
| 496 |
+
}}
|
| 497 |
+
|
| 498 |
+
// ═══════════════════ OFFENCE PARTICLE ═══════════════════
|
| 499 |
+
const offParts = [];
|
| 500 |
+
class OffPart {{
|
| 501 |
+
constructor(x,y,col) {{
|
| 502 |
+
this.x=x; this.y=y; this.col=col;
|
| 503 |
+
this.tx=laneCX(4); this.ty=gateY()+5;
|
| 504 |
+
this.t=0; this.done=false;
|
| 505 |
+
}}
|
| 506 |
+
update() {{
|
| 507 |
+
this.t+=0.035;
|
| 508 |
+
if(this.t>=1){{ this.done=true; return; }}
|
| 509 |
+
this.x += (this.tx-this.x)*0.07;
|
| 510 |
+
this.y += (this.ty-this.y)*0.07;
|
| 511 |
+
}}
|
| 512 |
+
draw() {{
|
| 513 |
+
if(this.done) return;
|
| 514 |
+
ctx.save();
|
| 515 |
+
ctx.globalAlpha=Math.max(0,1-this.t);
|
| 516 |
+
ctx.fillStyle=this.col;
|
| 517 |
+
ctx.shadowColor='#CC77FF'; ctx.shadowBlur=12;
|
| 518 |
+
ctx.beginPath(); ctx.arc(this.x,this.y,4,0,Math.PI*2); ctx.fill();
|
| 519 |
+
ctx.shadowBlur=0;
|
| 520 |
+
ctx.restore();
|
| 521 |
+
}}
|
| 522 |
+
}}
|
| 523 |
+
|
| 524 |
+
// ═══════════════════ STAGE LABELS ═══════════════════
|
| 525 |
+
const STAGES = [
|
| 526 |
+
{{ pct:0.00, end:0.25, label:'PHASE 1 — INTAKE & DATE RISK SCORING', col:'#C8A951' }},
|
| 527 |
+
{{ pct:0.25, end:0.60, label:'PHASE 2 — HYBRID CHANNEL ROUTING (DATE + gATE)', col:'#0066CC' }},
|
| 528 |
+
{{ pct:0.60, end:0.85, label:'PHASE 3 — INSPECTION & OFFENCE DB FEEDBACK', col:'#C8102E' }},
|
| 529 |
+
{{ pct:0.85, end:1.01, label:'PHASE 4 — SELF-LEARNING CYCLE COMPLETE ✓', col:'#00843D' }},
|
| 530 |
+
];
|
| 531 |
+
|
| 532 |
+
function drawStageLabel(p) {{
|
| 533 |
+
const s = STAGES.find(x => p>=x.pct && p<x.end) || STAGES[3];
|
| 534 |
+
document.getElementById('stage-label').textContent = s.label;
|
| 535 |
+
document.getElementById('stage-label').style.color = s.col;
|
| 536 |
+
}}
|
| 537 |
+
|
| 538 |
+
// ═══════════════════ COMPLETION OVERLAY ═══════════════════
|
| 539 |
+
function drawDone() {{
|
| 540 |
+
ctx.save();
|
| 541 |
+
ctx.fillStyle='rgba(7,14,28,0.86)';
|
| 542 |
+
ctx.fillRect(0,0,W,H);
|
| 543 |
+
|
| 544 |
+
const cw=460,ch=200,cx=(W-cw)/2,cy=(H-ch)/2;
|
| 545 |
+
ctx.fillStyle='#0F1C35';
|
| 546 |
+
ctx.strokeStyle='#C8A951'; ctx.lineWidth=2;
|
| 547 |
+
ctx.beginPath(); ctx.roundRect(cx,cy,cw,ch,14); ctx.fill(); ctx.stroke();
|
| 548 |
+
|
| 549 |
+
// Gold header
|
| 550 |
+
ctx.fillStyle='#C8A951';
|
| 551 |
+
ctx.beginPath(); ctx.roundRect(cx,cy,cw,40,{{topLeft:14,topRight:14,bottomLeft:0,bottomRight:0}});
|
| 552 |
+
ctx.fill();
|
| 553 |
+
ctx.fillStyle='#003087';
|
| 554 |
+
ctx.font='bold 13px Georgia'; ctx.textAlign='center';
|
| 555 |
+
ctx.fillText('✅ SIMULATION COMPLETE — WCO RMS CYCLE', W/2, cy+25);
|
| 556 |
+
|
| 557 |
+
ctx.fillStyle='#44CC88'; ctx.font='bold 22px Georgia';
|
| 558 |
+
ctx.fillText('All '+TOTAL+' Declarations Processed in 30 Seconds', W/2, cy+72);
|
| 559 |
+
|
| 560 |
+
const cols = [['🔴 RED',C.RED,'#C8102E'],['🟡 YEL',C.YELLOW,'#F5A800'],
|
| 561 |
+
['🟢 GRN',C.GREEN,'#00843D'],['🚨 Fraud',C.fraud,'#FF4466'],
|
| 562 |
+
['🔍 Expl',C.explore,'#CC77FF']];
|
| 563 |
+
const bw=74, startX=cx+20;
|
| 564 |
+
cols.forEach((col,i) => {{
|
| 565 |
+
const bx=startX+i*(bw+8);
|
| 566 |
+
ctx.fillStyle=col[2]+'22';
|
| 567 |
+
ctx.beginPath(); ctx.roundRect(bx,cy+90,bw,52,6); ctx.fill();
|
| 568 |
+
ctx.strokeStyle=col[2]; ctx.lineWidth=1;
|
| 569 |
+
ctx.beginPath(); ctx.roundRect(bx,cy+90,bw,52,6); ctx.stroke();
|
| 570 |
+
ctx.fillStyle=col[2]; ctx.font='bold 22px Georgia';
|
| 571 |
+
ctx.fillText(col[1], bx+bw/2, cy+120);
|
| 572 |
+
ctx.fillStyle='#8BAAD4'; ctx.font='9px sans-serif';
|
| 573 |
+
ctx.fillText(col[0], bx+bw/2, cy+136);
|
| 574 |
+
}});
|
| 575 |
+
|
| 576 |
+
ctx.fillStyle='#C8A951'; ctx.font='11px monospace';
|
| 577 |
+
ctx.fillText('Navigate to Page 4 → for detailed analysis tables & charts', W/2, cy+168);
|
| 578 |
+
ctx.restore();
|
| 579 |
+
}}
|
| 580 |
+
|
| 581 |
+
// ═══════════════════ SPAWN RATE ═══════════════════
|
| 582 |
+
// Bills spawn steadily across 80% of duration so all finish by end
|
| 583 |
+
const SPAWN_END_MS = DUR_MS * 0.80;
|
| 584 |
+
const SPAWN_INTV = SPAWN_END_MS / TOTAL; // ms per bill
|
| 585 |
+
let lastSpawnT = 0;
|
| 586 |
+
let startTime = null;
|
| 587 |
+
let simComplete = false;
|
| 588 |
+
|
| 589 |
+
// ═══════════════════ MAIN LOOP ═══════════════════
|
| 590 |
+
function loop(ts) {{
|
| 591 |
+
if(!startTime) startTime=ts;
|
| 592 |
+
const elapsed = ts - startTime;
|
| 593 |
+
const prog = Math.min(elapsed / DUR_MS, 1);
|
| 594 |
+
|
| 595 |
+
ctx.clearRect(0,0,W,H);
|
| 596 |
+
drawBG();
|
| 597 |
+
|
| 598 |
+
// Spawn
|
| 599 |
+
if(billIdx < TOTAL && elapsed >= lastSpawnT + SPAWN_INTV) {{
|
| 600 |
+
const batchN = Math.min(
|
| 601 |
+
TOTAL - billIdx,
|
| 602 |
+
Math.floor((elapsed - lastSpawnT) / SPAWN_INTV)
|
| 603 |
+
);
|
| 604 |
+
for(let b=0;b<batchN;b++) bills.push(new Bill(billIdx++));
|
| 605 |
+
lastSpawnT += batchN * SPAWN_INTV;
|
| 606 |
+
}}
|
| 607 |
+
|
| 608 |
+
// Update & draw bills
|
| 609 |
+
bills.forEach(bl => {{ bl.update(elapsed); bl.draw(); }});
|
| 610 |
+
|
| 611 |
+
// Offence particles
|
| 612 |
+
for(let i=offParts.length-1;i>=0;i--) {{
|
| 613 |
+
offParts[i].update(); offParts[i].draw();
|
| 614 |
+
if(offParts[i].done) offParts.splice(i,1);
|
| 615 |
+
}}
|
| 616 |
+
|
| 617 |
+
// Vault counter
|
| 618 |
+
const vx = laneCX(4), vy = gateY()+58;
|
| 619 |
+
ctx.fillStyle='#CC77FF'; ctx.font='bold 22px Georgia'; ctx.textAlign='center';
|
| 620 |
+
ctx.fillText(C.fraud, vx, vy);
|
| 621 |
+
ctx.fillStyle='#8B55CC'; ctx.font='9px sans-serif';
|
| 622 |
+
ctx.fillText('offence entries', vx, vy+14);
|
| 623 |
+
|
| 624 |
+
// Live efficiency
|
| 625 |
+
const liveP = C.total > 0
|
| 626 |
+
? (C.fraud / Math.max(C.RED+C.YELLOW,1)).toFixed(3)
|
| 627 |
+
: '–';
|
| 628 |
+
ctx.fillStyle='#C8A951'; ctx.font='bold 10px IBM Plex Sans';
|
| 629 |
+
ctx.textAlign='left';
|
| 630 |
+
ctx.fillText('LIVE PRECISION: '+liveP, 8, H-6);
|
| 631 |
+
|
| 632 |
+
// Timer
|
| 633 |
+
const rem = Math.max(0,30-(elapsed/1000));
|
| 634 |
+
ctx.fillStyle='#557796'; ctx.font='10px monospace';
|
| 635 |
+
ctx.textAlign='right';
|
| 636 |
+
ctx.fillText('⏱ '+rem.toFixed(1)+'s', W-8, H-6);
|
| 637 |
+
|
| 638 |
+
// Progress bar
|
| 639 |
+
document.getElementById('prog-fill').style.width=(prog*100).toFixed(1)+'%';
|
| 640 |
+
document.getElementById('prog-pct').textContent=
|
| 641 |
+
(prog*100).toFixed(0)+'% ('+C.total+' / '+TOTAL+' processed)';
|
| 642 |
+
drawStageLabel(prog);
|
| 643 |
+
|
| 644 |
+
// Check completion
|
| 645 |
+
const allDone = prog>=1 && bills.every(b=>b.phase==='done'||b.phase==='exiting');
|
| 646 |
+
if(allDone && !simComplete) {{
|
| 647 |
+
simComplete=true;
|
| 648 |
+
// ensure final counts
|
| 649 |
+
bills.forEach(b=>{{ if(!b.counted && b.phase!=='done') {{
|
| 650 |
+
b.counted=true; C.total++; C[b.channel]++;
|
| 651 |
+
if(b.explore) C.explore++;
|
| 652 |
+
if(b.fraud) C.fraud++;
|
| 653 |
+
}} }});
|
| 654 |
+
updateDOM();
|
| 655 |
+
setTimeout(()=>{{ drawDone(); }}, 400);
|
| 656 |
+
return;
|
| 657 |
+
}}
|
| 658 |
+
|
| 659 |
+
requestAnimationFrame(loop);
|
| 660 |
+
}}
|
| 661 |
+
|
| 662 |
+
drawBG();
|
| 663 |
+
requestAnimationFrame(loop);
|
| 664 |
+
</script>
|
| 665 |
+
</body>
|
| 666 |
+
</html>"""
|
| 667 |
+
|
| 668 |
+
|
| 669 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 670 |
+
def risk_score_distribution(df):
|
| 671 |
+
fig = go.Figure()
|
| 672 |
+
for ch, color, label in [
|
| 673 |
+
("GREEN","#00843D","🟢 GREEN"),
|
| 674 |
+
("YELLOW","#F5A800","🟡 YELLOW"),
|
| 675 |
+
("RED","#C8102E","🔴 RED"),
|
| 676 |
+
]:
|
| 677 |
+
cdf = df[df["channel"]==ch]
|
| 678 |
+
fig.add_trace(go.Violin(
|
| 679 |
+
y=cdf["fraud_score"], name=label,
|
| 680 |
+
fillcolor=color, opacity=0.7,
|
| 681 |
+
line_color=color, box_visible=True,
|
| 682 |
+
meanline_visible=True, points=False,
|
| 683 |
+
))
|
| 684 |
+
fig.update_layout(
|
| 685 |
+
paper_bgcolor="#070E1C", plot_bgcolor="#0B1220",
|
| 686 |
+
font=dict(family="IBM Plex Sans", color="#D0DCF0", size=12),
|
| 687 |
+
height=300,
|
| 688 |
+
title=dict(text="<b>Risk Score Distribution by Channel</b>",
|
| 689 |
+
font=dict(color=WCO_GOLD, size=13, family="Playfair Display"), x=0.5),
|
| 690 |
+
yaxis=dict(title="Fraud Score", gridcolor="#1E3A6E", range=[0,1]),
|
| 691 |
+
xaxis=dict(gridcolor="#1E3A6E"),
|
| 692 |
+
legend=dict(bgcolor="#0F1C35", bordercolor=WCO_BORDER),
|
| 693 |
+
margin=dict(l=50,r=20,t=50,b=40), violingap=0.3,
|
| 694 |
+
)
|
| 695 |
+
return fig
|
| 696 |
+
|
| 697 |
+
|
| 698 |
+
def area_heatmap(df):
|
| 699 |
+
pivot = pd.crosstab(df["risk_area"], df["channel"])
|
| 700 |
+
for col in ["RED","YELLOW","GREEN"]:
|
| 701 |
+
if col not in pivot.columns: pivot[col]=0
|
| 702 |
+
pivot = pivot[["RED","YELLOW","GREEN"]]
|
| 703 |
+
fig = go.Figure(go.Heatmap(
|
| 704 |
+
z=pivot.values, x=pivot.columns, y=pivot.index,
|
| 705 |
+
colorscale=[[0,"#0B1220"],[0.5,"#003087"],[1,"#C8A951"]],
|
| 706 |
+
text=pivot.values, texttemplate="%{text}", textfont={"size":13},
|
| 707 |
+
hovertemplate="<b>%{y}</b><br>Channel: %{x}<br>Bills: %{z}<extra></extra>",
|
| 708 |
+
showscale=True,
|
| 709 |
+
colorbar=dict(tickfont=dict(color="#D0DCF0"),
|
| 710 |
+
title="Bills", titlefont=dict(color=WCO_GOLD)),
|
| 711 |
+
))
|
| 712 |
+
fig.update_layout(
|
| 713 |
+
paper_bgcolor="#070E1C", plot_bgcolor="#0B1220",
|
| 714 |
+
font=dict(family="IBM Plex Sans", color="#D0DCF0", size=11),
|
| 715 |
+
height=280,
|
| 716 |
+
title=dict(text="<b>Risk Area × Channel Heatmap</b>",
|
| 717 |
+
font=dict(color=WCO_GOLD, size=13, family="Playfair Display"), x=0.5),
|
| 718 |
+
margin=dict(l=165,r=30,t=50,b=40),
|
| 719 |
+
)
|
| 720 |
+
return fig
|
| 721 |
+
|
| 722 |
+
|
| 723 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 724 |
+
def show():
|
| 725 |
+
inject_global_css()
|
| 726 |
+
page_header("🔄", "Self-Learning Simulation Engine",
|
| 727 |
+
"DATE EXPLOITATION · gATE EXPLORATION · 30-SECOND LIVE CANVAS ANIMATION")
|
| 728 |
+
|
| 729 |
+
# ── Controls ──────────────────────────────────────────────────
|
| 730 |
+
st.markdown('<div class="section-title">🎛️ Simulation Control Panel</div>',
|
| 731 |
+
unsafe_allow_html=True)
|
| 732 |
+
c1,c2,c3,c4 = st.columns(4)
|
| 733 |
+
with c1: n_bills = st.slider("📦 Declarations", 200,1000,1000,step=100)
|
| 734 |
+
with c2: bandwidth = st.slider("📡 Bandwidth (%)", 5,30,10,step=1)/100
|
| 735 |
+
with c3: exp_ratio = st.slider("🔍 Exploration ε (%)",1,30,10,step=1)/100
|
| 736 |
+
with c4: seed = st.slider("🎲 Seed",1,99,42,step=1)
|
| 737 |
+
|
| 738 |
+
st.markdown(f"""
|
| 739 |
+
<div class="alert-blue">
|
| 740 |
+
<b>Strategy:</b> DATE {100-int(exp_ratio*100)}% + gATE {int(exp_ratio*100)}%
|
| 741 |
+
| <b>Bandwidth:</b> {int(bandwidth*100)}% → {int(n_bills*bandwidth)} bills inspected
|
| 742 |
+
| <b>Facilitated:</b> {n_bills-int(n_bills*bandwidth)} bills (GREEN)
|
| 743 |
+
| <b>⏱ Animation duration:</b> exactly 30 seconds for full batch
|
| 744 |
+
</div>""", unsafe_allow_html=True)
|
| 745 |
+
|
| 746 |
+
col1,col2,_ = st.columns([1.2,1,4])
|
| 747 |
+
with col1: run_btn = st.button("▶ Run Simulation", type="primary", use_container_width=True)
|
| 748 |
+
with col2: reset_btn = st.button("🔄 Reset All", use_container_width=True)
|
| 749 |
+
|
| 750 |
+
if reset_btn:
|
| 751 |
+
for k in ["sim_df","sim_weights","sim_efficiency"]:
|
| 752 |
+
st.session_state.pop(k,None)
|
| 753 |
+
st.rerun()
|
| 754 |
+
|
| 755 |
+
# ── Run ───────────────────────────────────────────────────────
|
| 756 |
+
if run_btn or "sim_df" in st.session_state:
|
| 757 |
+
if run_btn or "sim_df" not in st.session_state:
|
| 758 |
+
weights = st.session_state.get("rule_weights", get_default_weights())
|
| 759 |
+
prog = st.progress(0, text="⚙️ Generating declarations...")
|
| 760 |
+
df = generate_declarations(n_bills, seed=seed)
|
| 761 |
+
prog.progress(25, text="🧠 DATE scoring...")
|
| 762 |
+
df = compute_risk_scores(df, weights)
|
| 763 |
+
prog.progress(50, text="⚖️ Hybrid channel routing...")
|
| 764 |
+
df = assign_channels(df, bandwidth=bandwidth, exploration_ratio=exp_ratio)
|
| 765 |
+
prog.progress(75, text="👮 Inspection outcomes...")
|
| 766 |
+
df = simulate_inspection_outcomes(df, seed=seed)
|
| 767 |
+
prog.progress(90, text="📈 Weight update & efficiency...")
|
| 768 |
+
uw = compute_updated_weights(df, weights)
|
| 769 |
+
eff = compute_efficiency_metrics(df)
|
| 770 |
+
prog.progress(100, text="✅ Launching animation!")
|
| 771 |
+
|
| 772 |
+
st.session_state.sim_df = df
|
| 773 |
+
st.session_state.sim_weights = uw
|
| 774 |
+
st.session_state.sim_efficiency = eff
|
| 775 |
+
|
| 776 |
+
df = st.session_state.sim_df
|
| 777 |
+
eff = st.session_state.sim_efficiency
|
| 778 |
+
hybrid = eff.get("hybrid", {})
|
| 779 |
+
ch = df["channel"].value_counts()
|
| 780 |
+
detected = int((df["inspection_outcome"]=="FRAUD_DETECTED").sum())
|
| 781 |
+
revenue = float(df["detected_revenue"].sum())
|
| 782 |
+
eff_idx = float(hybrid.get("efficiency_index", 0.0))
|
| 783 |
+
|
| 784 |
+
channel_counts = {
|
| 785 |
+
"RED": int(ch.get("RED",0)),
|
| 786 |
+
"YELLOW": int(ch.get("YELLOW",0)),
|
| 787 |
+
"GREEN": int(ch.get("GREEN",0)),
|
| 788 |
+
}
|
| 789 |
+
|
| 790 |
+
# ── Legend ────────────────────────────────────────────────
|
| 791 |
+
st.markdown('<div class="section-title">🎬 Live RMS Canvas Animation</div>',
|
| 792 |
+
unsafe_allow_html=True)
|
| 793 |
+
st.markdown("""<div class="alert-gold">
|
| 794 |
+
📌 <b>30-second real-time simulation.</b>
|
| 795 |
+
Each icon = one customs declaration flowing through the RMS pipeline.<br/>
|
| 796 |
+
<span style="color:#FF4466;">■ Red glow</span> = Fraud detected |
|
| 797 |
+
<span style="color:#CC77FF;">■ Purple glow</span> = gATE exploration pick |
|
| 798 |
+
<span style="color:#3A6BB5;">■ Blue</span> = Standard routing |
|
| 799 |
+
Fraud bills arc → Offence DB vault (right lane)
|
| 800 |
+
</div>""", unsafe_allow_html=True)
|
| 801 |
+
|
| 802 |
+
# ── CANVAS ANIMATION ──────────────────────────────────────
|
| 803 |
+
html_src = build_animation_html(
|
| 804 |
+
n_bills=n_bills, bandwidth=bandwidth, exp_ratio=exp_ratio,
|
| 805 |
+
channel_counts=channel_counts, detected=detected,
|
| 806 |
+
revenue=revenue, efficiency_idx=eff_idx,
|
| 807 |
+
)
|
| 808 |
+
components.html(html_src, height=720, scrolling=False)
|
| 809 |
+
|
| 810 |
+
# ── Supporting charts ────���─────────────────────────────────
|
| 811 |
+
st.markdown("<br/>", unsafe_allow_html=True)
|
| 812 |
+
st.markdown('<div class="section-title">📊 Channel Analytics</div>',
|
| 813 |
+
unsafe_allow_html=True)
|
| 814 |
+
ca,cb = st.columns([3,2])
|
| 815 |
+
with ca: st.plotly_chart(area_heatmap(df), use_container_width=True)
|
| 816 |
+
with cb: st.plotly_chart(risk_score_distribution(df), use_container_width=True)
|
| 817 |
+
|
| 818 |
+
# ── Risk area cards ───────────────────────────────────────
|
| 819 |
+
st.markdown('<div class="section-title">🗂️ Risk Area Breakdown</div>',
|
| 820 |
+
unsafe_allow_html=True)
|
| 821 |
+
acols = st.columns(5)
|
| 822 |
+
for i,(aname,acfg) in enumerate(RISK_AREAS.items()):
|
| 823 |
+
a_df = df[df["risk_area"]==aname]
|
| 824 |
+
color = acfg["color"]
|
| 825 |
+
ch_a = a_df["channel"].value_counts()
|
| 826 |
+
fraud_a= (a_df["inspection_outcome"]=="FRAUD_DETECTED").sum()
|
| 827 |
+
exp_a = a_df["is_exploration"].sum()
|
| 828 |
+
with acols[i]:
|
| 829 |
+
st.markdown(f"""
|
| 830 |
+
<div style="background:#0F1C35;border:1px solid {color};
|
| 831 |
+
border-radius:10px;padding:14px 12px;">
|
| 832 |
+
<div style="color:{color};font-weight:700;font-size:12px;
|
| 833 |
+
margin-bottom:10px;font-family:'Playfair Display',serif;">
|
| 834 |
+
{acfg['icon']} {aname}
|
| 835 |
+
</div>
|
| 836 |
+
<div style="color:#D0DCF0;font-size:12px;line-height:2.1;">
|
| 837 |
+
🔴 RED: <b>{ch_a.get('RED',0)}</b><br/>
|
| 838 |
+
🟡 YEL: <b>{ch_a.get('YELLOW',0)}</b><br/>
|
| 839 |
+
🟢 GRN: <b>{ch_a.get('GREEN',0)}</b><br/>
|
| 840 |
+
🚨 Fraud: <b style="color:#FF4466;">{fraud_a}</b><br/>
|
| 841 |
+
🔍 Expl: <b style="color:#CC77FF;">{exp_a}</b>
|
| 842 |
+
</div>
|
| 843 |
+
</div>""", unsafe_allow_html=True)
|
| 844 |
+
|
| 845 |
+
st.markdown("""<div class="alert-gold" style="margin-top:18px;">
|
| 846 |
+
✅ Simulation complete. Go to <b>Page 4</b> for full tables,
|
| 847 |
+
offence DB growth, and weight-evolution analysis.
|
| 848 |
+
</div>""", unsafe_allow_html=True)
|
| 849 |
+
|
| 850 |
+
else:
|
| 851 |
+
st.markdown("""
|
| 852 |
+
<div style="background:#0F1C35;border:2px dashed #1E3A6E;border-radius:14px;
|
| 853 |
+
padding:70px;text-align:center;margin-top:20px;">
|
| 854 |
+
<div style="font-size:52px;margin-bottom:16px;">🎬</div>
|
| 855 |
+
<div style="color:#C8A951;font-family:'Playfair Display',serif;
|
| 856 |
+
font-size:22px;margin-bottom:12px;">Ready to Simulate</div>
|
| 857 |
+
<div style="color:#6B85AA;font-size:14px;line-height:1.8;">
|
| 858 |
+
Configure parameters above and click
|
| 859 |
+
<b style="color:#C8A951;">▶ Run Simulation</b><br/>
|
| 860 |
+
A 30-second canvas animation will show all declarations flowing
|
| 861 |
+
through RED / YELLOW / GREEN channels in real-time.
|
| 862 |
+
</div>
|
| 863 |
+
</div>""", unsafe_allow_html=True)
|
page4_results.py
ADDED
|
@@ -0,0 +1,951 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
+
page4_results.py — Simulation Results: 5 tables + charts for all analysis dimensions
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import streamlit as st
|
| 6 |
+
import plotly.graph_objects as go
|
| 7 |
+
import plotly.express as px
|
| 8 |
+
import pandas as pd
|
| 9 |
+
import numpy as np
|
| 10 |
+
from styles import (inject_global_css, page_header, metric_row,
|
| 11 |
+
WCO_GOLD, WCO_BLUE, WCO_GREEN, WCO_RED,
|
| 12 |
+
WCO_CARD_BG, WCO_BORDER, WCO_MUTED, RISK_COLORS)
|
| 13 |
+
from simulation_engine import (build_rule_hit_table, build_channel_table,
|
| 14 |
+
build_exploration_discovery_table,
|
| 15 |
+
build_offence_db_table, build_risk_score_table,
|
| 16 |
+
RISK_AREAS)
|
| 17 |
+
|
| 18 |
+
RISK_LEVEL_COLORS = {
|
| 19 |
+
"FRAUD_DETECTED": "#C8102E",
|
| 20 |
+
"DOC_QUERY": "#F5A800",
|
| 21 |
+
"CLEAN": "#00843D",
|
| 22 |
+
"NOT_INSPECTED": "#6B85AA",
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def offence_db_growth_chart(df):
|
| 27 |
+
"""Cumulative offence DB additions over bill sequence."""
|
| 28 |
+
df_sorted = df.sort_index()
|
| 29 |
+
df_sorted["cum_offence"] = df_sorted["added_to_offence_db"].cumsum()
|
| 30 |
+
|
| 31 |
+
# Break down by risk area
|
| 32 |
+
traces = []
|
| 33 |
+
for area_name, area_cfg in RISK_AREAS.items():
|
| 34 |
+
a_df = df_sorted[df_sorted["risk_area"] == area_name].copy()
|
| 35 |
+
a_df["cum"] = a_df["added_to_offence_db"].cumsum()
|
| 36 |
+
traces.append(go.Scatter(
|
| 37 |
+
x=a_df.index, y=a_df["cum"],
|
| 38 |
+
name=f"{area_cfg['icon']} {area_name}",
|
| 39 |
+
line=dict(color=area_cfg["color"], width=2),
|
| 40 |
+
mode="lines",
|
| 41 |
+
hovertemplate=f"<b>{area_name}</b><br>Bill: %{{x}}<br>Cumulative: %{{y}}<extra></extra>",
|
| 42 |
+
))
|
| 43 |
+
traces.append(go.Scatter(
|
| 44 |
+
x=df_sorted.index, y=df_sorted["cum_offence"],
|
| 45 |
+
name="📊 Total", line=dict(color=WCO_GOLD, width=3, dash="dot"),
|
| 46 |
+
hovertemplate="<b>Total</b><br>Bill: %{x}<br>Cumulative: %{y}<extra></extra>",
|
| 47 |
+
))
|
| 48 |
+
|
| 49 |
+
fig = go.Figure(traces)
|
| 50 |
+
fig.update_layout(
|
| 51 |
+
paper_bgcolor="#070E1C", plot_bgcolor="#0B1220",
|
| 52 |
+
font=dict(family="IBM Plex Sans", color="#D0DCF0", size=11),
|
| 53 |
+
height=380,
|
| 54 |
+
title=dict(text="<b>Real-Time Offence Database Growth (Cumulative)</b>",
|
| 55 |
+
font=dict(color=WCO_GOLD, size=14, family="Playfair Display"), x=0.5),
|
| 56 |
+
xaxis=dict(title="Bill Sequence", gridcolor="#1E3A6E"),
|
| 57 |
+
yaxis=dict(title="Offences Added to DB", gridcolor="#1E3A6E"),
|
| 58 |
+
legend=dict(bgcolor="#0F1C35", bordercolor=WCO_BORDER, font=dict(size=10)),
|
| 59 |
+
margin=dict(l=55, r=20, t=55, b=45),
|
| 60 |
+
)
|
| 61 |
+
return fig
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def exploration_vs_exploitation_chart(df):
|
| 65 |
+
"""Compare detection across exploit vs explore bills."""
|
| 66 |
+
cats = ["Exploitation Bills", "Exploration Bills"]
|
| 67 |
+
exploit_df = df[df["is_exploration"] == 0]
|
| 68 |
+
explore_df = df[df["is_exploration"] == 1]
|
| 69 |
+
|
| 70 |
+
def detection_stats(sub):
|
| 71 |
+
tot = len(sub)
|
| 72 |
+
fraud = (sub["inspection_outcome"] == "FRAUD_DETECTED").sum()
|
| 73 |
+
rev = sub["detected_revenue"].sum()
|
| 74 |
+
rate = 100 * fraud / tot if tot else 0
|
| 75 |
+
return tot, fraud, rev, rate
|
| 76 |
+
|
| 77 |
+
e_tot, e_fraud, e_rev, e_rate = detection_stats(exploit_df)
|
| 78 |
+
x_tot, x_fraud, x_rev, x_rate = detection_stats(explore_df)
|
| 79 |
+
|
| 80 |
+
fig = go.Figure()
|
| 81 |
+
fig.add_trace(go.Bar(name="🎯 Exploitations", x=["Bills","Frauds Detected","Revenue ($K)"],
|
| 82 |
+
y=[e_tot, e_fraud, e_rev/1000],
|
| 83 |
+
marker_color="#0066CC", opacity=0.85,
|
| 84 |
+
text=[e_tot, e_fraud, f"${e_rev/1000:.1f}K"], textposition="outside",
|
| 85 |
+
textfont=dict(color="#D0DCF0")))
|
| 86 |
+
fig.add_trace(go.Bar(name="🔍 Explorations", x=["Bills","Frauds Detected","Revenue ($K)"],
|
| 87 |
+
y=[x_tot, x_fraud, x_rev/1000],
|
| 88 |
+
marker_color="#CC77FF", opacity=0.85,
|
| 89 |
+
text=[x_tot, x_fraud, f"${x_rev/1000:.1f}K"], textposition="outside",
|
| 90 |
+
textfont=dict(color="#D0DCF0")))
|
| 91 |
+
fig.update_layout(
|
| 92 |
+
paper_bgcolor="#070E1C", plot_bgcolor="#0B1220",
|
| 93 |
+
font=dict(family="IBM Plex Sans", color="#D0DCF0", size=12),
|
| 94 |
+
height=340, barmode="group",
|
| 95 |
+
title=dict(text="<b>Exploitation vs Exploration: Detection Comparison</b>",
|
| 96 |
+
font=dict(color=WCO_GOLD, size=14, family="Playfair Display"), x=0.5),
|
| 97 |
+
xaxis=dict(gridcolor="#1E3A6E"),
|
| 98 |
+
yaxis=dict(gridcolor="#1E3A6E", title="Count / Value"),
|
| 99 |
+
legend=dict(bgcolor="#0F1C35", bordercolor=WCO_BORDER),
|
| 100 |
+
margin=dict(l=50, r=20, t=55, b=40),
|
| 101 |
+
)
|
| 102 |
+
return fig
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def weight_evolution_chart(df, orig_weights, updated_weights):
|
| 106 |
+
"""Visualise how rule weights increased after simulation."""
|
| 107 |
+
rids, orig, updated, deltas = [], [], [], []
|
| 108 |
+
for area in RISK_AREAS.values():
|
| 109 |
+
for rule in area["rules"]:
|
| 110 |
+
rid = rule["id"]
|
| 111 |
+
o = orig_weights.get(rid, rule["weight"])
|
| 112 |
+
u = updated_weights.get(rid, o)
|
| 113 |
+
rids.append(rid)
|
| 114 |
+
orig.append(o)
|
| 115 |
+
updated.append(u)
|
| 116 |
+
deltas.append(round(u - o, 4))
|
| 117 |
+
|
| 118 |
+
fig = go.Figure()
|
| 119 |
+
fig.add_trace(go.Bar(x=rids, y=orig, name="Original Weights",
|
| 120 |
+
marker_color="#1E3A6E", opacity=0.9))
|
| 121 |
+
fig.add_trace(go.Bar(x=rids, y=updated, name="Updated Weights",
|
| 122 |
+
marker_color=WCO_GOLD, opacity=0.85))
|
| 123 |
+
fig.add_trace(go.Scatter(x=rids, y=deltas, name="Δ Weight", mode="markers+lines",
|
| 124 |
+
marker=dict(color=WCO_RED, size=9, symbol="triangle-up"),
|
| 125 |
+
line=dict(color=WCO_RED, dash="dot", width=1.5),
|
| 126 |
+
yaxis="y2"))
|
| 127 |
+
fig.update_layout(
|
| 128 |
+
paper_bgcolor="#070E1C", plot_bgcolor="#0B1220",
|
| 129 |
+
font=dict(family="IBM Plex Sans", color="#D0DCF0", size=10),
|
| 130 |
+
height=360, barmode="group",
|
| 131 |
+
title=dict(text="<b>Rule Weight Evolution After Self-Learning Feedback</b>",
|
| 132 |
+
font=dict(color=WCO_GOLD, size=14, family="Playfair Display"), x=0.5),
|
| 133 |
+
xaxis=dict(gridcolor="#1E3A6E", tickangle=-45),
|
| 134 |
+
yaxis=dict(title="Weight", gridcolor="#1E3A6E"),
|
| 135 |
+
yaxis2=dict(title="Δ Weight", overlaying="y", side="right",
|
| 136 |
+
gridcolor="#1E3A6E", showgrid=False),
|
| 137 |
+
legend=dict(bgcolor="#0F1C35", bordercolor=WCO_BORDER),
|
| 138 |
+
margin=dict(l=55, r=55, t=55, b=90),
|
| 139 |
+
)
|
| 140 |
+
return fig
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def styled_table(df: pd.DataFrame, title: str, highlight_col: str = None,
|
| 144 |
+
color_map: dict = None):
|
| 145 |
+
st.markdown(f"""
|
| 146 |
+
<div style="color:{WCO_GOLD};font-family:'Playfair Display',serif;
|
| 147 |
+
font-size:15px;font-weight:700;margin:16px 0 10px;">
|
| 148 |
+
{title}
|
| 149 |
+
</div>""", unsafe_allow_html=True)
|
| 150 |
+
if highlight_col and color_map:
|
| 151 |
+
def _style(val):
|
| 152 |
+
col = color_map.get(val, "")
|
| 153 |
+
return f"background-color:{col}22;color:{col}" if col else ""
|
| 154 |
+
styled = df.style.applymap(_style, subset=[highlight_col]) \
|
| 155 |
+
.set_properties(**{"background-color": WCO_CARD_BG,
|
| 156 |
+
"color": "#D0DCF0", "font-size": "12px"})
|
| 157 |
+
st.dataframe(styled, use_container_width=True, height=min(38 * len(df) + 40, 420))
|
| 158 |
+
else:
|
| 159 |
+
st.dataframe(
|
| 160 |
+
df.style.set_properties(**{"background-color": WCO_CARD_BG,
|
| 161 |
+
"color": "#D0DCF0", "font-size": "12px"}),
|
| 162 |
+
use_container_width=True, height=min(38 * len(df) + 40, 420),
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def exploration_scatter_tab(df: pd.DataFrame):
|
| 167 |
+
"""
|
| 168 |
+
Full scatter-plot breakdown of the bATE exploration logic applied to all bills.
|
| 169 |
+
Shows every formula component:
|
| 170 |
+
unc_i = -1.8 * |fraud_score - 0.5| + 1
|
| 171 |
+
S_i = unc_i * log(pred_revenue + ε)
|
| 172 |
+
Colour = channel assignment. Shape = exploration pick or not.
|
| 173 |
+
"""
|
| 174 |
+
import numpy as np
|
| 175 |
+
|
| 176 |
+
# ── Formula explanation banner ────────────────────────────────
|
| 177 |
+
st.markdown("""
|
| 178 |
+
<div class="wco-card-gold">
|
| 179 |
+
<h3>🧭 bATE Exploration Logic — All Bills Visualised</h3>
|
| 180 |
+
<div style="display:flex;gap:30px;flex-wrap:wrap;font-size:13px;color:#D0DCF0;line-height:2;">
|
| 181 |
+
<div>
|
| 182 |
+
<b style="color:#CC77FF;">Step 1 — Uncertainty Score</b><br/>
|
| 183 |
+
<code style="background:#111D30;padding:4px 10px;border-radius:5px;
|
| 184 |
+
color:#C8A951;font-size:13px;">
|
| 185 |
+
unc_i = −1.8 × |ŷᶜˡˢ − 0.5| + 1
|
| 186 |
+
</code><br/>
|
| 187 |
+
<span style="color:#6B85AA;font-size:12px;">
|
| 188 |
+
Max = 1.0 when fraud_score = 0.5 (model completely unsure)<br/>
|
| 189 |
+
Min ≈ 0.1 when fraud_score → 0 or → 1 (model very confident)
|
| 190 |
+
</span>
|
| 191 |
+
</div>
|
| 192 |
+
<div>
|
| 193 |
+
<b style="color:#CC77FF;">Step 2 — Scale Factor (bATE)</b><br/>
|
| 194 |
+
<code style="background:#111D30;padding:4px 10px;border-radius:5px;
|
| 195 |
+
color:#C8A951;font-size:13px;">
|
| 196 |
+
S_i = unc_i × log(ŷʳᵉᵛ + ε)
|
| 197 |
+
</code><br/>
|
| 198 |
+
<span style="color:#6B85AA;font-size:12px;">
|
| 199 |
+
High S_i = uncertain AND high revenue → top exploration candidates<br/>
|
| 200 |
+
K-means++ diversity applied on top to avoid redundant picks
|
| 201 |
+
</span>
|
| 202 |
+
</div>
|
| 203 |
+
</div>
|
| 204 |
+
</div>""", unsafe_allow_html=True)
|
| 205 |
+
|
| 206 |
+
st.markdown("<br/>", unsafe_allow_html=True)
|
| 207 |
+
|
| 208 |
+
# ── Colour / marker helpers ───────────────────────────────────
|
| 209 |
+
ch_color = {"RED": "#C8102E", "YELLOW": "#F5A800", "GREEN": "#00843D"}
|
| 210 |
+
ch_marker = {"RED": "circle", "YELLOW": "diamond", "GREEN": "square"}
|
| 211 |
+
|
| 212 |
+
def base_layout(title, xlab, ylab, h=460):
|
| 213 |
+
return dict(
|
| 214 |
+
paper_bgcolor="#070E1C", plot_bgcolor="#0B1220",
|
| 215 |
+
font=dict(family="IBM Plex Sans", color="#D0DCF0", size=11),
|
| 216 |
+
height=h,
|
| 217 |
+
title=dict(text=f"<b>{title}</b>",
|
| 218 |
+
font=dict(color=WCO_GOLD, size=14,
|
| 219 |
+
family="Playfair Display"), x=0.5),
|
| 220 |
+
xaxis=dict(title=xlab, gridcolor="#1E3A6E", zeroline=False),
|
| 221 |
+
yaxis=dict(title=ylab, gridcolor="#1E3A6E", zeroline=False),
|
| 222 |
+
legend=dict(bgcolor="#0F1C35", bordercolor=WCO_BORDER,
|
| 223 |
+
font=dict(size=10)),
|
| 224 |
+
margin=dict(l=60, r=20, t=55, b=55),
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
# ─────────────────────────────────────────────────────────────
|
| 228 |
+
# SCATTER 1 — fraud_score vs uncertainty_score (the unc_i curve)
|
| 229 |
+
# ─────────────────────────────────────────────────────────────
|
| 230 |
+
st.markdown('<div class="section-title">① Fraud Score vs Uncertainty Score — The unc_i Curve</div>',
|
| 231 |
+
unsafe_allow_html=True)
|
| 232 |
+
st.markdown("""<div class="alert-blue">
|
| 233 |
+
The <b>uncertainty score unc_i</b> is a concave function maximised when
|
| 234 |
+
<code>fraud_score ≈ 0.5</code>. Bills near 0.5 are the model's blind spots —
|
| 235 |
+
exploration targets. Bills near 0 or 1 are confident predictions (exploitation territory).
|
| 236 |
+
<b style="color:#CC77FF;">Purple stars</b> = actual gATE exploration picks.
|
| 237 |
+
</div>""", unsafe_allow_html=True)
|
| 238 |
+
|
| 239 |
+
# Theoretical curve overlay
|
| 240 |
+
x_curve = np.linspace(0, 1, 300)
|
| 241 |
+
y_curve = -1.8 * np.abs(x_curve - 0.5) + 1
|
| 242 |
+
|
| 243 |
+
fig1 = go.Figure()
|
| 244 |
+
|
| 245 |
+
# Theoretical curve
|
| 246 |
+
fig1.add_trace(go.Scatter(
|
| 247 |
+
x=x_curve, y=y_curve,
|
| 248 |
+
mode="lines",
|
| 249 |
+
name="unc_i = −1.8×|ŷ−0.5|+1 (theoretical)",
|
| 250 |
+
line=dict(color="#C8A951", width=2.5, dash="dot"),
|
| 251 |
+
hoverinfo="skip",
|
| 252 |
+
))
|
| 253 |
+
|
| 254 |
+
# All bills coloured by channel
|
| 255 |
+
for ch in ["GREEN", "YELLOW", "RED"]:
|
| 256 |
+
sub = df[df["channel"] == ch]
|
| 257 |
+
non_exp = sub[sub["is_exploration"] == 0]
|
| 258 |
+
fig1.add_trace(go.Scatter(
|
| 259 |
+
x=non_exp["fraud_score"],
|
| 260 |
+
y=non_exp["uncertainty_score"],
|
| 261 |
+
mode="markers",
|
| 262 |
+
name=f"{ch} (exploitation)",
|
| 263 |
+
marker=dict(
|
| 264 |
+
color=ch_color[ch], size=5, opacity=0.45,
|
| 265 |
+
symbol=ch_marker[ch],
|
| 266 |
+
line=dict(width=0),
|
| 267 |
+
),
|
| 268 |
+
hovertemplate=(
|
| 269 |
+
f"<b>{ch}</b><br>"
|
| 270 |
+
"Fraud Score: %{x:.3f}<br>"
|
| 271 |
+
"Uncertainty: %{y:.3f}<br>"
|
| 272 |
+
"<extra></extra>"
|
| 273 |
+
),
|
| 274 |
+
))
|
| 275 |
+
|
| 276 |
+
# Exploration picks on top
|
| 277 |
+
exp_df = df[df["is_exploration"] == 1]
|
| 278 |
+
fig1.add_trace(go.Scatter(
|
| 279 |
+
x=exp_df["fraud_score"],
|
| 280 |
+
y=exp_df["uncertainty_score"],
|
| 281 |
+
mode="markers",
|
| 282 |
+
name="🔍 gATE Exploration Picks",
|
| 283 |
+
marker=dict(
|
| 284 |
+
color="#CC77FF", size=11, opacity=0.95,
|
| 285 |
+
symbol="star",
|
| 286 |
+
line=dict(color="#ffffff", width=0.8),
|
| 287 |
+
),
|
| 288 |
+
hovertemplate=(
|
| 289 |
+
"<b>EXPLORATION PICK</b><br>"
|
| 290 |
+
"Bill: %{customdata[0]}<br>"
|
| 291 |
+
"Fraud Score: %{x:.3f}<br>"
|
| 292 |
+
"Uncertainty: %{y:.3f}<br>"
|
| 293 |
+
"Risk Area: %{customdata[1]}<br>"
|
| 294 |
+
"<extra></extra>"
|
| 295 |
+
),
|
| 296 |
+
customdata=exp_df[["bill_id", "risk_area"]].values,
|
| 297 |
+
))
|
| 298 |
+
|
| 299 |
+
# Vertical line at 0.5
|
| 300 |
+
fig1.add_vline(x=0.5, line=dict(color="#CC77FF", dash="dash", width=1.2),
|
| 301 |
+
annotation_text="Max uncertainty (0.5)",
|
| 302 |
+
annotation_font_color="#CC77FF",
|
| 303 |
+
annotation_position="top right")
|
| 304 |
+
|
| 305 |
+
# Shaded exploration zone (0.3 – 0.7)
|
| 306 |
+
fig1.add_vrect(x0=0.3, x1=0.7,
|
| 307 |
+
fillcolor="#CC77FF", opacity=0.05,
|
| 308 |
+
line_width=0,
|
| 309 |
+
annotation_text="Exploration zone",
|
| 310 |
+
annotation_font_color="#CC77FF",
|
| 311 |
+
annotation_position="top left")
|
| 312 |
+
|
| 313 |
+
fig1.update_layout(**base_layout(
|
| 314 |
+
"Fraud Score vs Uncertainty Score | unc_i = −1.8 × |ŷᶜˡˢ − 0.5| + 1",
|
| 315 |
+
"Fraud Score ŷᶜˡˢ (DATE exploitation output)",
|
| 316 |
+
"Uncertainty Score unc_i",
|
| 317 |
+
h=480,
|
| 318 |
+
))
|
| 319 |
+
st.plotly_chart(fig1, use_container_width=True)
|
| 320 |
+
|
| 321 |
+
# ─────────────────────────────────────────────────────────────
|
| 322 |
+
# SCATTER 2 — uncertainty_score vs log(pred_revenue) = Scale Factor S_i
|
| 323 |
+
# ─────────────────────────────────────────────────────────────
|
| 324 |
+
st.markdown('<div class="section-title">② Uncertainty vs log(Revenue) — The S_i Scale Factor Space</div>',
|
| 325 |
+
unsafe_allow_html=True)
|
| 326 |
+
st.markdown("""<div class="alert-blue">
|
| 327 |
+
<b>S_i = unc_i × log(ŷʳᵉᵛ + ε)</b> — bills in the
|
| 328 |
+
<b style="color:#CC77FF;">top-right quadrant</b> score highest and are
|
| 329 |
+
the primary exploration candidates: they are uncertain <i>and</i> financially significant.
|
| 330 |
+
Bottom-left = low uncertainty low revenue = safe GREEN facilitation.
|
| 331 |
+
</div>""", unsafe_allow_html=True)
|
| 332 |
+
|
| 333 |
+
epsilon = 1e-6
|
| 334 |
+
df_plot = df.copy()
|
| 335 |
+
df_plot["log_rev"] = np.log(df_plot["pred_revenue"] + epsilon)
|
| 336 |
+
|
| 337 |
+
fig2 = go.Figure()
|
| 338 |
+
|
| 339 |
+
for ch in ["GREEN", "YELLOW", "RED"]:
|
| 340 |
+
sub = df_plot[(df_plot["channel"] == ch) & (df_plot["is_exploration"] == 0)]
|
| 341 |
+
fig2.add_trace(go.Scatter(
|
| 342 |
+
x=sub["log_rev"],
|
| 343 |
+
y=sub["uncertainty_score"],
|
| 344 |
+
mode="markers",
|
| 345 |
+
name=f"{ch}",
|
| 346 |
+
marker=dict(
|
| 347 |
+
color=ch_color[ch], size=5, opacity=0.40,
|
| 348 |
+
symbol=ch_marker[ch], line=dict(width=0),
|
| 349 |
+
),
|
| 350 |
+
hovertemplate=(
|
| 351 |
+
f"<b>{ch}</b><br>"
|
| 352 |
+
"log(Revenue): %{x:.2f}<br>"
|
| 353 |
+
"Uncertainty: %{y:.3f}<br>"
|
| 354 |
+
"Scale Factor S_i: %{customdata:.3f}<br>"
|
| 355 |
+
"<extra></extra>"
|
| 356 |
+
),
|
| 357 |
+
customdata=sub["scale_factor"],
|
| 358 |
+
))
|
| 359 |
+
|
| 360 |
+
# Exploration picks
|
| 361 |
+
exp_plot = df_plot[df_plot["is_exploration"] == 1]
|
| 362 |
+
fig2.add_trace(go.Scatter(
|
| 363 |
+
x=exp_plot["log_rev"],
|
| 364 |
+
y=exp_plot["uncertainty_score"],
|
| 365 |
+
mode="markers",
|
| 366 |
+
name="🔍 Exploration Picks",
|
| 367 |
+
marker=dict(color="#CC77FF", size=12, opacity=0.95,
|
| 368 |
+
symbol="star", line=dict(color="#fff", width=0.8)),
|
| 369 |
+
hovertemplate=(
|
| 370 |
+
"<b>EXPLORATION PICK</b><br>"
|
| 371 |
+
"Bill: %{customdata[0]}<br>"
|
| 372 |
+
"log(Rev): %{x:.2f}<br>"
|
| 373 |
+
"Uncertainty: %{y:.3f}<br>"
|
| 374 |
+
"S_i: %{customdata[1]:.3f}<br>"
|
| 375 |
+
"Risk Area: %{customdata[2]}<br>"
|
| 376 |
+
"<extra></extra>"
|
| 377 |
+
),
|
| 378 |
+
customdata=exp_plot[["bill_id", "scale_factor", "risk_area"]].values,
|
| 379 |
+
))
|
| 380 |
+
|
| 381 |
+
# Fraud detected overlay
|
| 382 |
+
fraud_plot = df_plot[df_plot["inspection_outcome"] == "FRAUD_DETECTED"]
|
| 383 |
+
fig2.add_trace(go.Scatter(
|
| 384 |
+
x=fraud_plot["log_rev"],
|
| 385 |
+
y=fraud_plot["uncertainty_score"],
|
| 386 |
+
mode="markers",
|
| 387 |
+
name="🚨 Fraud Detected",
|
| 388 |
+
marker=dict(color="#FF4466", size=8, opacity=0.85,
|
| 389 |
+
symbol="x", line=dict(color="#FF4466", width=1.5)),
|
| 390 |
+
hovertemplate=(
|
| 391 |
+
"<b>FRAUD DETECTED</b><br>"
|
| 392 |
+
"Bill: %{customdata[0]}<br>"
|
| 393 |
+
"Channel: %{customdata[1]}<br>"
|
| 394 |
+
"log(Rev): %{x:.2f}<br>"
|
| 395 |
+
"Uncertainty: %{y:.3f}<br>"
|
| 396 |
+
"<extra></extra>"
|
| 397 |
+
),
|
| 398 |
+
customdata=fraud_plot[["bill_id", "channel"]].values,
|
| 399 |
+
))
|
| 400 |
+
|
| 401 |
+
# Quadrant annotations
|
| 402 |
+
x_med = df_plot["log_rev"].median()
|
| 403 |
+
y_med = df_plot["uncertainty_score"].median()
|
| 404 |
+
fig2.add_hline(y=y_med, line=dict(color="#1E3A6E", dash="dash", width=1))
|
| 405 |
+
fig2.add_vline(x=x_med, line=dict(color="#1E3A6E", dash="dash", width=1))
|
| 406 |
+
|
| 407 |
+
for (xa, ya, txt, col) in [
|
| 408 |
+
(0.98, 0.98, "HIGH S_i<br>Explore", "#CC77FF"),
|
| 409 |
+
(0.02, 0.98, "Uncertain<br>Low Rev", "#F5A800"),
|
| 410 |
+
(0.98, 0.02, "High Rev<br>Confident", "#0066CC"),
|
| 411 |
+
(0.02, 0.02, "LOW S_i<br>Facilitate", "#00843D"),
|
| 412 |
+
]:
|
| 413 |
+
fig2.add_annotation(
|
| 414 |
+
xref="paper", yref="paper", x=xa, y=ya,
|
| 415 |
+
text=f"<b>{txt}</b>", showarrow=False,
|
| 416 |
+
font=dict(color=col, size=10),
|
| 417 |
+
bgcolor=col+"18", bordercolor=col,
|
| 418 |
+
borderwidth=1, borderpad=4,
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
fig2.update_layout(**base_layout(
|
| 422 |
+
"Uncertainty Score vs log(Revenue) | S_i = unc_i × log(ŷʳᵉᵛ + ε)",
|
| 423 |
+
"log(Predicted Revenue ŷʳᵉᵛ)",
|
| 424 |
+
"Uncertainty Score unc_i",
|
| 425 |
+
h=500,
|
| 426 |
+
))
|
| 427 |
+
st.plotly_chart(fig2, use_container_width=True)
|
| 428 |
+
|
| 429 |
+
# ─────────────────────────────────────────────────────────────
|
| 430 |
+
# SCATTER 3 — Scale Factor S_i vs fraud_score, sized by revenue
|
| 431 |
+
# ─────────────────────────────────────────────────────────────
|
| 432 |
+
st.markdown('<div class="section-title">③ Scale Factor S_i vs Fraud Score — Full bATE Decision Space</div>',
|
| 433 |
+
unsafe_allow_html=True)
|
| 434 |
+
st.markdown("""<div class="alert-blue">
|
| 435 |
+
The <b>scale factor S_i</b> (y-axis) is what bATE actually ranks bills by.
|
| 436 |
+
<b>Bubble size = predicted revenue.</b>
|
| 437 |
+
Exploration picks (⭐) cluster at <b>mid fraud-score × high S_i</b> — uncertain AND valuable.
|
| 438 |
+
Exploitation picks cluster at <b>high fraud-score</b> regardless of uncertainty.
|
| 439 |
+
</div>""", unsafe_allow_html=True)
|
| 440 |
+
|
| 441 |
+
# Normalise bubble size
|
| 442 |
+
rev_norm = ((df["pred_revenue"] - df["pred_revenue"].min()) /
|
| 443 |
+
(df["pred_revenue"].max() - df["pred_revenue"].min() + 1e-6))
|
| 444 |
+
df_plot2 = df.copy()
|
| 445 |
+
df_plot2["bubble"] = 5 + rev_norm * 22
|
| 446 |
+
|
| 447 |
+
fig3 = go.Figure()
|
| 448 |
+
|
| 449 |
+
# Non-selected bills (GREEN channel, not exploration)
|
| 450 |
+
grn = df_plot2[(df_plot2["channel"] == "GREEN")]
|
| 451 |
+
fig3.add_trace(go.Scatter(
|
| 452 |
+
x=grn["fraud_score"], y=grn["scale_factor"],
|
| 453 |
+
mode="markers",
|
| 454 |
+
name="🟢 GREEN (Facilitated)",
|
| 455 |
+
marker=dict(color="#00843D", size=grn["bubble"], opacity=0.25,
|
| 456 |
+
line=dict(width=0)),
|
| 457 |
+
hovertemplate=(
|
| 458 |
+
"<b>GREEN</b><br>Fraud Score: %{x:.3f}<br>"
|
| 459 |
+
"S_i: %{y:.3f}<br>Revenue: $%{customdata:,.0f}<extra></extra>"
|
| 460 |
+
),
|
| 461 |
+
customdata=grn["pred_revenue"],
|
| 462 |
+
))
|
| 463 |
+
|
| 464 |
+
# Exploitation picks (RED + YELLOW, not exploration)
|
| 465 |
+
expl_picks = df_plot2[(df_plot2["channel"].isin(["RED","YELLOW"])) &
|
| 466 |
+
(df_plot2["is_exploration"] == 0)]
|
| 467 |
+
for ch in ["YELLOW", "RED"]:
|
| 468 |
+
sub = expl_picks[expl_picks["channel"] == ch]
|
| 469 |
+
fig3.add_trace(go.Scatter(
|
| 470 |
+
x=sub["fraud_score"], y=sub["scale_factor"],
|
| 471 |
+
mode="markers",
|
| 472 |
+
name=f"{'🔴' if ch=='RED' else '🟡'} {ch} (Exploitation)",
|
| 473 |
+
marker=dict(color=ch_color[ch], size=sub["bubble"],
|
| 474 |
+
opacity=0.65, symbol=ch_marker[ch],
|
| 475 |
+
line=dict(color=ch_color[ch], width=0.5)),
|
| 476 |
+
hovertemplate=(
|
| 477 |
+
f"<b>{ch} — EXPLOITATION</b><br>"
|
| 478 |
+
"Fraud Score: %{x:.3f}<br>"
|
| 479 |
+
"S_i: %{y:.3f}<br>"
|
| 480 |
+
"Revenue: $%{customdata[0]:,.0f}<br>"
|
| 481 |
+
"Bill: %{customdata[1]}<br>"
|
| 482 |
+
"<extra></extra>"
|
| 483 |
+
),
|
| 484 |
+
customdata=sub[["pred_revenue", "bill_id"]].values,
|
| 485 |
+
))
|
| 486 |
+
|
| 487 |
+
# Exploration picks
|
| 488 |
+
ep = df_plot2[df_plot2["is_exploration"] == 1]
|
| 489 |
+
fig3.add_trace(go.Scatter(
|
| 490 |
+
x=ep["fraud_score"], y=ep["scale_factor"],
|
| 491 |
+
mode="markers",
|
| 492 |
+
name="🔍 gATE Exploration Picks",
|
| 493 |
+
marker=dict(color="#CC77FF", size=ep["bubble"] + 4,
|
| 494 |
+
opacity=1.0, symbol="star",
|
| 495 |
+
line=dict(color="#ffffff", width=1)),
|
| 496 |
+
hovertemplate=(
|
| 497 |
+
"<b>EXPLORATION PICK (gATE)</b><br>"
|
| 498 |
+
"Bill: %{customdata[0]}<br>"
|
| 499 |
+
"Risk Area: %{customdata[1]}<br>"
|
| 500 |
+
"Fraud Score: %{x:.3f}<br>"
|
| 501 |
+
"unc_i: %{customdata[2]:.3f}<br>"
|
| 502 |
+
"S_i: %{y:.3f}<br>"
|
| 503 |
+
"Pred Revenue: $%{customdata[3]:,.0f}<br>"
|
| 504 |
+
"<extra></extra>"
|
| 505 |
+
),
|
| 506 |
+
customdata=ep[["bill_id", "risk_area",
|
| 507 |
+
"uncertainty_score", "pred_revenue"]].values,
|
| 508 |
+
))
|
| 509 |
+
|
| 510 |
+
# Fraud detected X marks
|
| 511 |
+
fd = df_plot2[df_plot2["inspection_outcome"] == "FRAUD_DETECTED"]
|
| 512 |
+
fig3.add_trace(go.Scatter(
|
| 513 |
+
x=fd["fraud_score"], y=fd["scale_factor"],
|
| 514 |
+
mode="markers",
|
| 515 |
+
name="🚨 Fraud Detected",
|
| 516 |
+
marker=dict(color="#FF4466", size=10, opacity=0.9,
|
| 517 |
+
symbol="x-thin", line=dict(color="#FF4466", width=2)),
|
| 518 |
+
hovertemplate=(
|
| 519 |
+
"<b>FRAUD CONFIRMED</b><br>"
|
| 520 |
+
"Bill: %{customdata[0]}<br>"
|
| 521 |
+
"Channel: %{customdata[1]}<br>"
|
| 522 |
+
"Revenue Recovered: $%{customdata[2]:,.0f}<br>"
|
| 523 |
+
"<extra></extra>"
|
| 524 |
+
),
|
| 525 |
+
customdata=fd[["bill_id", "channel", "detected_revenue"]].values,
|
| 526 |
+
))
|
| 527 |
+
|
| 528 |
+
# Threshold line — top n% by S_i (exploration selection boundary)
|
| 529 |
+
n_explore = ep.shape[0]
|
| 530 |
+
if n_explore > 0:
|
| 531 |
+
si_threshold = df_plot2["scale_factor"].nlargest(n_explore * 3).min()
|
| 532 |
+
fig3.add_hline(
|
| 533 |
+
y=si_threshold,
|
| 534 |
+
line=dict(color="#CC77FF", dash="dash", width=1.3),
|
| 535 |
+
annotation_text=f" gATE S_i candidate threshold",
|
| 536 |
+
annotation_font_color="#CC77FF",
|
| 537 |
+
annotation_position="right",
|
| 538 |
+
)
|
| 539 |
+
|
| 540 |
+
fig3.update_layout(**base_layout(
|
| 541 |
+
"Scale Factor S_i vs Fraud Score | Bubble Size = Predicted Revenue",
|
| 542 |
+
"Fraud Score ŷᶜˡˢ (DATE output — Exploitation axis)",
|
| 543 |
+
"Scale Factor S_i = unc_i × log(ŷʳᵉᵛ + ε) (Exploration axis)",
|
| 544 |
+
h=520,
|
| 545 |
+
))
|
| 546 |
+
st.plotly_chart(fig3, use_container_width=True)
|
| 547 |
+
|
| 548 |
+
# ─────────────────────────────────────────────────────────────
|
| 549 |
+
# SCATTER 4 — Per risk area facet: fraud_score vs uncertainty_score
|
| 550 |
+
# ─────────────────────────────────────────────────────────────
|
| 551 |
+
st.markdown('<div class="section-title">④ Per Risk Area — Exploration Picks in Context</div>',
|
| 552 |
+
unsafe_allow_html=True)
|
| 553 |
+
st.markdown("""<div class="alert-blue">
|
| 554 |
+
Same axes as Chart ① but broken down by risk area.
|
| 555 |
+
Shows <b>which risk areas have the most uncertain bills</b>
|
| 556 |
+
and whether exploration picks are concentrated in the right zone.
|
| 557 |
+
</div>""", unsafe_allow_html=True)
|
| 558 |
+
|
| 559 |
+
area_names = list(RISK_AREAS.keys())
|
| 560 |
+
cols_fa = st.columns(5)
|
| 561 |
+
for i, (area_name, area_cfg) in enumerate(RISK_AREAS.items()):
|
| 562 |
+
a_df = df[df["risk_area"] == area_name]
|
| 563 |
+
color = area_cfg["color"]
|
| 564 |
+
exp_a = a_df[a_df["is_exploration"] == 1]
|
| 565 |
+
|
| 566 |
+
fig_fa = go.Figure()
|
| 567 |
+
# All bills in area
|
| 568 |
+
fig_fa.add_trace(go.Scatter(
|
| 569 |
+
x=a_df["fraud_score"], y=a_df["uncertainty_score"],
|
| 570 |
+
mode="markers",
|
| 571 |
+
name="All Bills",
|
| 572 |
+
marker=dict(color=color, size=5, opacity=0.35,
|
| 573 |
+
line=dict(width=0)),
|
| 574 |
+
showlegend=False,
|
| 575 |
+
))
|
| 576 |
+
# Exploration picks
|
| 577 |
+
if len(exp_a) > 0:
|
| 578 |
+
fig_fa.add_trace(go.Scatter(
|
| 579 |
+
x=exp_a["fraud_score"], y=exp_a["uncertainty_score"],
|
| 580 |
+
mode="markers",
|
| 581 |
+
name="Exploration",
|
| 582 |
+
marker=dict(color="#CC77FF", size=10, opacity=0.95,
|
| 583 |
+
symbol="star",
|
| 584 |
+
line=dict(color="#fff", width=0.6)),
|
| 585 |
+
showlegend=False,
|
| 586 |
+
))
|
| 587 |
+
# Fraud
|
| 588 |
+
fd_a = a_df[a_df["inspection_outcome"] == "FRAUD_DETECTED"]
|
| 589 |
+
if len(fd_a) > 0:
|
| 590 |
+
fig_fa.add_trace(go.Scatter(
|
| 591 |
+
x=fd_a["fraud_score"], y=fd_a["uncertainty_score"],
|
| 592 |
+
mode="markers",
|
| 593 |
+
name="Fraud",
|
| 594 |
+
marker=dict(color="#FF4466", size=7, opacity=0.85,
|
| 595 |
+
symbol="x-thin",
|
| 596 |
+
line=dict(color="#FF4466", width=1.5)),
|
| 597 |
+
showlegend=False,
|
| 598 |
+
))
|
| 599 |
+
|
| 600 |
+
fig_fa.add_vline(x=0.5, line=dict(color="#CC77FF33", width=1))
|
| 601 |
+
fig_fa.update_layout(
|
| 602 |
+
paper_bgcolor="#070E1C", plot_bgcolor="#0B1220",
|
| 603 |
+
font=dict(color="#D0DCF0", size=9), height=240,
|
| 604 |
+
title=dict(
|
| 605 |
+
text=f"<b>{area_cfg['icon']} {area_name.split('/')[0]}</b>",
|
| 606 |
+
font=dict(color=color, size=11), x=0.5,
|
| 607 |
+
),
|
| 608 |
+
xaxis=dict(title="Fraud Score", gridcolor="#1E3A6E",
|
| 609 |
+
range=[0,1], tickfont=dict(size=8)),
|
| 610 |
+
yaxis=dict(title="unc_i", gridcolor="#1E3A6E",
|
| 611 |
+
range=[0,1.1], tickfont=dict(size=8)),
|
| 612 |
+
margin=dict(l=35, r=8, t=40, b=35),
|
| 613 |
+
showlegend=False,
|
| 614 |
+
)
|
| 615 |
+
with cols_fa[i]:
|
| 616 |
+
st.plotly_chart(fig_fa, use_container_width=True)
|
| 617 |
+
n_exp = len(exp_a)
|
| 618 |
+
n_tot = len(a_df)
|
| 619 |
+
n_fd = len(fd_a)
|
| 620 |
+
st.markdown(f"""
|
| 621 |
+
<div style="background:#0F1C35;border:1px solid {color};
|
| 622 |
+
border-radius:8px;padding:10px;font-size:11px;
|
| 623 |
+
text-align:center;margin-top:-10px;">
|
| 624 |
+
<span style="color:{color};">Total:</span> {n_tot}<br/>
|
| 625 |
+
<span style="color:#CC77FF;">⭐ Explore:</span> {n_exp}<br/>
|
| 626 |
+
<span style="color:#FF4466;">🚨 Fraud:</span> {n_fd}<br/>
|
| 627 |
+
<span style="color:#C8A951;">Avg S_i:</span>
|
| 628 |
+
{a_df['scale_factor'].mean():.2f}
|
| 629 |
+
</div>""", unsafe_allow_html=True)
|
| 630 |
+
|
| 631 |
+
# ─────────────────────────────────────────────────────────────
|
| 632 |
+
# Summary insight box
|
| 633 |
+
# ─────────────────────────────────────────────────────────────
|
| 634 |
+
st.markdown("<br/>", unsafe_allow_html=True)
|
| 635 |
+
exp_df_s = df[df["is_exploration"] == 1]
|
| 636 |
+
avg_unc = exp_df_s["uncertainty_score"].mean()
|
| 637 |
+
avg_si = exp_df_s["scale_factor"].mean()
|
| 638 |
+
avg_fs = exp_df_s["fraud_score"].mean()
|
| 639 |
+
all_avg_unc = df["uncertainty_score"].mean()
|
| 640 |
+
all_avg_si = df["scale_factor"].mean()
|
| 641 |
+
all_avg_fs = df["fraud_score"].mean()
|
| 642 |
+
|
| 643 |
+
st.markdown(f"""
|
| 644 |
+
<div class="wco-card-gold">
|
| 645 |
+
<h3>📐 Exploration Selection Summary — Formula Validation</h3>
|
| 646 |
+
<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:16px;margin-top:8px;">
|
| 647 |
+
|
| 648 |
+
<div style="background:#111D30;border-radius:8px;padding:14px;text-align:center;">
|
| 649 |
+
<div style="color:#6B85AA;font-size:11px;text-transform:uppercase;
|
| 650 |
+
letter-spacing:0.07em;margin-bottom:6px;">Avg Fraud Score ŷᶜˡˢ</div>
|
| 651 |
+
<div style="color:#CC77FF;font-size:22px;font-weight:700;
|
| 652 |
+
font-family:'Georgia',serif;">{avg_fs:.3f}</div>
|
| 653 |
+
<div style="color:#6B85AA;font-size:11px;">Exploration picks</div>
|
| 654 |
+
<div style="color:#44CC88;font-size:18px;font-weight:700;margin-top:4px;">{all_avg_fs:.3f}</div>
|
| 655 |
+
<div style="color:#6B85AA;font-size:11px;">All bills (baseline)</div>
|
| 656 |
+
<div style="color:#C8A951;font-size:11px;margin-top:6px;">
|
| 657 |
+
{'✅ Closer to 0.5 = correct' if abs(avg_fs-0.5) < abs(all_avg_fs-0.5) else '↔ Similar to baseline'}
|
| 658 |
+
</div>
|
| 659 |
+
</div>
|
| 660 |
+
|
| 661 |
+
<div style="background:#111D30;border-radius:8px;padding:14px;text-align:center;">
|
| 662 |
+
<div style="color:#6B85AA;font-size:11px;text-transform:uppercase;
|
| 663 |
+
letter-spacing:0.07em;margin-bottom:6px;">Avg Uncertainty unc_i</div>
|
| 664 |
+
<div style="color:#CC77FF;font-size:22px;font-weight:700;
|
| 665 |
+
font-family:'Georgia',serif;">{avg_unc:.3f}</div>
|
| 666 |
+
<div style="color:#6B85AA;font-size:11px;">Exploration picks</div>
|
| 667 |
+
<div style="color:#44CC88;font-size:18px;font-weight:700;margin-top:4px;">{all_avg_unc:.3f}</div>
|
| 668 |
+
<div style="color:#6B85AA;font-size:11px;">All bills (baseline)</div>
|
| 669 |
+
<div style="color:#C8A951;font-size:11px;margin-top:6px;">
|
| 670 |
+
{'✅ Higher unc = targeting blind spots' if avg_unc > all_avg_unc else '↔ Check exploration ratio'}
|
| 671 |
+
</div>
|
| 672 |
+
</div>
|
| 673 |
+
|
| 674 |
+
<div style="background:#111D30;border-radius:8px;padding:14px;text-align:center;">
|
| 675 |
+
<div style="color:#6B85AA;font-size:11px;text-transform:uppercase;
|
| 676 |
+
letter-spacing:0.07em;margin-bottom:6px;">Avg Scale Factor S_i</div>
|
| 677 |
+
<div style="color:#CC77FF;font-size:22px;font-weight:700;
|
| 678 |
+
font-family:'Georgia',serif;">{avg_si:.3f}</div>
|
| 679 |
+
<div style="color:#6B85AA;font-size:11px;">Exploration picks</div>
|
| 680 |
+
<div style="color:#44CC88;font-size:18px;font-weight:700;margin-top:4px;">{all_avg_si:.3f}</div>
|
| 681 |
+
<div style="color:#6B85AA;font-size:11px;">All bills (baseline)</div>
|
| 682 |
+
<div style="color:#C8A951;font-size:11px;margin-top:6px;">
|
| 683 |
+
{'✅ Higher S_i = uncertain + valuable' if avg_si > all_avg_si else '↔ Revenue weighting check'}
|
| 684 |
+
</div>
|
| 685 |
+
</div>
|
| 686 |
+
|
| 687 |
+
</div>
|
| 688 |
+
</div>""", unsafe_allow_html=True)
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
def show():
|
| 692 |
+
inject_global_css()
|
| 693 |
+
page_header("📊", "Simulation Results & Analysis",
|
| 694 |
+
"RULE HIT TABLES · OFFENCE DATABASE GROWTH · EXPLORATION GAINS · WEIGHT EVOLUTION")
|
| 695 |
+
|
| 696 |
+
if "sim_df" not in st.session_state:
|
| 697 |
+
st.markdown("""
|
| 698 |
+
<div style="background:#0F1C35;border:2px dashed #1E3A6E;border-radius:14px;
|
| 699 |
+
padding:60px;text-align:center;margin-top:30px;">
|
| 700 |
+
<div style="font-size:40px;margin-bottom:12px;">⚠️</div>
|
| 701 |
+
<div style="color:#F5A800;font-size:18px;font-family:'Playfair Display',serif;">
|
| 702 |
+
No Simulation Data Found
|
| 703 |
+
</div>
|
| 704 |
+
<div style="color:#6B85AA;margin-top:10px;">
|
| 705 |
+
Please run the simulation on <b>Page 3</b> first.
|
| 706 |
+
</div>
|
| 707 |
+
</div>""", unsafe_allow_html=True)
|
| 708 |
+
return
|
| 709 |
+
|
| 710 |
+
df = st.session_state.sim_df
|
| 711 |
+
updated_weights = st.session_state.get("sim_weights", {})
|
| 712 |
+
orig_weights = st.session_state.get("rule_weights", {})
|
| 713 |
+
efficiency = st.session_state.get("sim_efficiency", {})
|
| 714 |
+
|
| 715 |
+
# KPI strip
|
| 716 |
+
fraud_total = (df["inspection_outcome"] == "FRAUD_DETECTED").sum()
|
| 717 |
+
offence_adds = df["added_to_offence_db"].sum()
|
| 718 |
+
explore_finds = df[(df["is_exploration"]==1) & (df["added_to_offence_db"]==1)].shape[0]
|
| 719 |
+
revenue = df["detected_revenue"].sum()
|
| 720 |
+
metric_row([
|
| 721 |
+
(fraud_total, "Frauds Detected", WCO_RED),
|
| 722 |
+
(offence_adds, "Offence DB Additions", WCO_GOLD),
|
| 723 |
+
(explore_finds, "Exploration Discoveries", "#CC77FF"),
|
| 724 |
+
(f"${revenue:,.0f}", "Revenue Recovered", WCO_GREEN),
|
| 725 |
+
(f"{efficiency.get('hybrid',{}).get('efficiency_index',0):.3f}",
|
| 726 |
+
"Efficiency Index", WCO_GOLD),
|
| 727 |
+
])
|
| 728 |
+
|
| 729 |
+
tabs = st.tabs([
|
| 730 |
+
"📋 T1: Rule Hits", "📡 T2: Channel Stats",
|
| 731 |
+
"🔍 T3: Exploration Finds", "🗄️ T4: Offence DB",
|
| 732 |
+
"⚖️ T5: Risk Scoring", "📈 Charts",
|
| 733 |
+
"🧭 Exploration Logic",
|
| 734 |
+
])
|
| 735 |
+
|
| 736 |
+
# ── TABLE 1: Rule Hits ────────────────────────────────────────
|
| 737 |
+
with tabs[0]:
|
| 738 |
+
st.markdown("""<div class="alert-blue">
|
| 739 |
+
How many bills were hit by each risk rule, and precision of each rule.
|
| 740 |
+
</div>""", unsafe_allow_html=True)
|
| 741 |
+
df_t1 = build_rule_hit_table(df)
|
| 742 |
+
|
| 743 |
+
# Mini bar chart
|
| 744 |
+
fig_t1 = go.Figure(go.Bar(
|
| 745 |
+
x=df_t1["Rule ID"], y=df_t1["Total Bills Hit"],
|
| 746 |
+
marker_color=df_t1["Risk Area"].map(
|
| 747 |
+
{k: v["color"] for k, v in RISK_AREAS.items()}),
|
| 748 |
+
opacity=0.85,
|
| 749 |
+
text=df_t1["Precision (%)"].apply(lambda x: f"{x}%"), textposition="outside",
|
| 750 |
+
textfont=dict(color="#D0DCF0", size=10),
|
| 751 |
+
hovertext=df_t1["Rule Name"], hoverinfo="text+y",
|
| 752 |
+
))
|
| 753 |
+
fig_t1.update_layout(
|
| 754 |
+
paper_bgcolor="#070E1C", plot_bgcolor="#0B1220",
|
| 755 |
+
font=dict(color="#D0DCF0", size=10), height=280,
|
| 756 |
+
title=dict(text="<b>Bills Hit per Rule (label = detection precision)</b>",
|
| 757 |
+
font=dict(color=WCO_GOLD, size=13), x=0.5),
|
| 758 |
+
xaxis=dict(gridcolor="#1E3A6E", tickangle=-45),
|
| 759 |
+
yaxis=dict(gridcolor="#1E3A6E", title="Bills Hit"),
|
| 760 |
+
margin=dict(l=45, r=15, t=45, b=75),
|
| 761 |
+
)
|
| 762 |
+
st.plotly_chart(fig_t1, use_container_width=True)
|
| 763 |
+
styled_table(df_t1, "Table 1 — Risk Rule Hit Analysis")
|
| 764 |
+
|
| 765 |
+
# ── TABLE 2: Channel Stats ────────────────────────────────────
|
| 766 |
+
with tabs[1]:
|
| 767 |
+
st.markdown("""<div class="alert-blue">
|
| 768 |
+
Bills treated per channel, exploitation vs exploration split, fraud detection per channel.
|
| 769 |
+
</div>""", unsafe_allow_html=True)
|
| 770 |
+
df_t2 = build_channel_table(df)
|
| 771 |
+
|
| 772 |
+
c1, c2 = st.columns(2)
|
| 773 |
+
with c1:
|
| 774 |
+
fig_ch = go.Figure(go.Bar(
|
| 775 |
+
x=df_t2["Channel"],
|
| 776 |
+
y=df_t2["Total Bills"],
|
| 777 |
+
marker_color=["#C8102E","#F5A800","#00843D"], opacity=0.85,
|
| 778 |
+
text=df_t2["Total Bills"], textposition="outside",
|
| 779 |
+
textfont=dict(color="#D0DCF0"),
|
| 780 |
+
))
|
| 781 |
+
fig_ch.update_layout(
|
| 782 |
+
paper_bgcolor="#070E1C", plot_bgcolor="#0B1220",
|
| 783 |
+
font=dict(color="#D0DCF0", size=12), height=300,
|
| 784 |
+
title=dict(text="<b>Bills per Channel</b>",
|
| 785 |
+
font=dict(color=WCO_GOLD, size=13), x=0.5),
|
| 786 |
+
xaxis=dict(gridcolor="#1E3A6E"),
|
| 787 |
+
yaxis=dict(gridcolor="#1E3A6E"),
|
| 788 |
+
margin=dict(l=45, r=15, t=45, b=40),
|
| 789 |
+
)
|
| 790 |
+
st.plotly_chart(fig_ch, use_container_width=True)
|
| 791 |
+
with c2:
|
| 792 |
+
fig_pie = go.Figure(go.Pie(
|
| 793 |
+
labels=["Exploitation","Exploration"],
|
| 794 |
+
values=[df_t2["Exploitation Bills"].sum(), df_t2["Exploration Bills"].sum()],
|
| 795 |
+
marker=dict(colors=["#0066CC","#CC77FF"],
|
| 796 |
+
line=dict(color="#070E1C", width=2)),
|
| 797 |
+
hole=0.55, textfont=dict(color="#D0DCF0"),
|
| 798 |
+
))
|
| 799 |
+
fig_pie.update_layout(
|
| 800 |
+
paper_bgcolor="#070E1C",
|
| 801 |
+
font=dict(color="#D0DCF0"), height=300,
|
| 802 |
+
title=dict(text="<b>Exploit vs Explore Split</b>",
|
| 803 |
+
font=dict(color=WCO_GOLD, size=13), x=0.5),
|
| 804 |
+
legend=dict(bgcolor="#0F1C35"),
|
| 805 |
+
margin=dict(l=20, r=20, t=45, b=20),
|
| 806 |
+
)
|
| 807 |
+
st.plotly_chart(fig_pie, use_container_width=True)
|
| 808 |
+
|
| 809 |
+
styled_table(df_t2, "Table 2 — Channel Treatment Statistics")
|
| 810 |
+
|
| 811 |
+
# ── TABLE 3: Exploration Discoveries ─────────────────────────
|
| 812 |
+
with tabs[2]:
|
| 813 |
+
st.markdown("""<div class="alert-blue">
|
| 814 |
+
New bills discovered and added to offence database via exploration strategy (concept drift detection).
|
| 815 |
+
</div>""", unsafe_allow_html=True)
|
| 816 |
+
df_t3 = build_exploration_discovery_table(df)
|
| 817 |
+
st.plotly_chart(exploration_vs_exploitation_chart(df), use_container_width=True)
|
| 818 |
+
styled_table(df_t3, "Table 3 — Exploration Discovery Analysis per Risk Area")
|
| 819 |
+
|
| 820 |
+
# ── TABLE 4: Offence DB ───────────────────────────────────────
|
| 821 |
+
with tabs[3]:
|
| 822 |
+
st.markdown("""<div class="alert-blue">
|
| 823 |
+
Real-time offence database augmentation from Red + Yellow channel inspection feedback.
|
| 824 |
+
</div>""", unsafe_allow_html=True)
|
| 825 |
+
st.plotly_chart(offence_db_growth_chart(df), use_container_width=True)
|
| 826 |
+
df_t4 = build_offence_db_table(df)
|
| 827 |
+
styled_table(df_t4, "Table 4 — Offence Database Augmentation by Risk Area")
|
| 828 |
+
|
| 829 |
+
# Radar chart of offence DB by area
|
| 830 |
+
areas = df_t4["Risk Area"].tolist()
|
| 831 |
+
vals = df_t4["Total Added"].tolist()
|
| 832 |
+
fig_radar = go.Figure(go.Scatterpolar(
|
| 833 |
+
r=vals + [vals[0]], theta=areas + [areas[0]],
|
| 834 |
+
fill="toself", fillcolor="rgba(200,169,81,0.15)",
|
| 835 |
+
line=dict(color=WCO_GOLD, width=2),
|
| 836 |
+
marker=dict(size=8, color=WCO_GOLD),
|
| 837 |
+
))
|
| 838 |
+
fig_radar.update_layout(
|
| 839 |
+
paper_bgcolor="#070E1C", plot_bgcolor="#0B1220",
|
| 840 |
+
font=dict(color="#D0DCF0", size=11), height=360,
|
| 841 |
+
title=dict(text="<b>Offence DB Coverage Radar</b>",
|
| 842 |
+
font=dict(color=WCO_GOLD, size=13), x=0.5),
|
| 843 |
+
polar=dict(bgcolor="#0B1220",
|
| 844 |
+
angularaxis=dict(gridcolor="#1E3A6E", linecolor="#1E3A6E"),
|
| 845 |
+
radialaxis=dict(gridcolor="#1E3A6E", linecolor="#1E3A6E")),
|
| 846 |
+
margin=dict(l=60, r=60, t=55, b=40),
|
| 847 |
+
)
|
| 848 |
+
st.plotly_chart(fig_radar, use_container_width=True)
|
| 849 |
+
|
| 850 |
+
# ── TABLE 5: Risk Scoring ─────────────────────────────────────
|
| 851 |
+
with tabs[4]:
|
| 852 |
+
st.markdown("""<div class="alert-blue">
|
| 853 |
+
Per-transaction risk scores, rule hits, cumulative weights, and weight evolution after
|
| 854 |
+
self-learning feedback. Shows how detection efficiency drives automatic weight uplift.
|
| 855 |
+
</div>""", unsafe_allow_html=True)
|
| 856 |
+
df_t5 = build_risk_score_table(df, updated_weights)
|
| 857 |
+
|
| 858 |
+
# Weight evolution chart
|
| 859 |
+
if orig_weights and updated_weights:
|
| 860 |
+
st.plotly_chart(weight_evolution_chart(df, orig_weights, updated_weights),
|
| 861 |
+
use_container_width=True)
|
| 862 |
+
|
| 863 |
+
styled_table(df_t5, "Table 5 — Transaction Risk Scoring & Weight Evolution",
|
| 864 |
+
highlight_col="Channel",
|
| 865 |
+
color_map={"RED": "#C8102E", "YELLOW": "#F5A800", "GREEN": "#00843D"})
|
| 866 |
+
|
| 867 |
+
# Weight delta table
|
| 868 |
+
st.markdown('<div class="section-title">📈 Rule Weight Update Summary</div>',
|
| 869 |
+
unsafe_allow_html=True)
|
| 870 |
+
weight_rows = []
|
| 871 |
+
for area_name, area_cfg in RISK_AREAS.items():
|
| 872 |
+
for rule in area_cfg["rules"]:
|
| 873 |
+
rid = rule["id"]
|
| 874 |
+
o = orig_weights.get(rid, rule["weight"])
|
| 875 |
+
u = updated_weights.get(rid, o)
|
| 876 |
+
weight_rows.append({
|
| 877 |
+
"Risk Area": area_name,
|
| 878 |
+
"Rule ID": rid,
|
| 879 |
+
"Rule Name": rule["name"],
|
| 880 |
+
"Original Weight":f"{o:.3f}",
|
| 881 |
+
"Updated Weight": f"{u:.3f}",
|
| 882 |
+
"Δ Weight": f"+{u-o:.4f}" if u >= o else f"{u-o:.4f}",
|
| 883 |
+
"% Change": f"{100*(u-o)/o:.1f}%" if o > 0 else "—",
|
| 884 |
+
})
|
| 885 |
+
df_wd = pd.DataFrame(weight_rows)
|
| 886 |
+
styled_table(df_wd, "Rule Weight Delta After Self-Learning Cycle")
|
| 887 |
+
|
| 888 |
+
# ── Charts summary tab ────────────────────────────────────────
|
| 889 |
+
with tabs[5]:
|
| 890 |
+
c1, c2 = st.columns(2)
|
| 891 |
+
with c1:
|
| 892 |
+
# Outcome distribution pie
|
| 893 |
+
outcomes = df[df["channel"] != "GREEN"]["inspection_outcome"].value_counts()
|
| 894 |
+
fig_out = go.Figure(go.Pie(
|
| 895 |
+
labels=outcomes.index, values=outcomes.values,
|
| 896 |
+
marker=dict(colors=[RISK_LEVEL_COLORS.get(k,"#6B85AA") for k in outcomes.index],
|
| 897 |
+
line=dict(color="#070E1C", width=2)),
|
| 898 |
+
hole=0.5, textfont=dict(color="#D0DCF0"),
|
| 899 |
+
))
|
| 900 |
+
fig_out.update_layout(
|
| 901 |
+
paper_bgcolor="#070E1C", font=dict(color="#D0DCF0"), height=340,
|
| 902 |
+
title=dict(text="<b>Inspection Outcome Distribution</b>",
|
| 903 |
+
font=dict(color=WCO_GOLD, size=13), x=0.5),
|
| 904 |
+
legend=dict(bgcolor="#0F1C35"), margin=dict(l=20,r=20,t=45,b=20),
|
| 905 |
+
)
|
| 906 |
+
st.plotly_chart(fig_out, use_container_width=True)
|
| 907 |
+
with c2:
|
| 908 |
+
# Revenue by risk area
|
| 909 |
+
rev_by_area = df.groupby("risk_area")["detected_revenue"].sum().reset_index()
|
| 910 |
+
colors = [RISK_AREAS[a]["color"] for a in rev_by_area["risk_area"]]
|
| 911 |
+
fig_rev = go.Figure(go.Bar(
|
| 912 |
+
x=rev_by_area["risk_area"],
|
| 913 |
+
y=rev_by_area["detected_revenue"],
|
| 914 |
+
marker_color=colors, opacity=0.85,
|
| 915 |
+
text=rev_by_area["detected_revenue"].apply(lambda x: f"${x:,.0f}"),
|
| 916 |
+
textposition="outside", textfont=dict(color="#D0DCF0", size=10),
|
| 917 |
+
))
|
| 918 |
+
fig_rev.update_layout(
|
| 919 |
+
paper_bgcolor="#070E1C", plot_bgcolor="#0B1220",
|
| 920 |
+
font=dict(color="#D0DCF0", size=10), height=340,
|
| 921 |
+
title=dict(text="<b>Revenue Recovered by Risk Area</b>",
|
| 922 |
+
font=dict(color=WCO_GOLD, size=13), x=0.5),
|
| 923 |
+
xaxis=dict(gridcolor="#1E3A6E", tickangle=-25),
|
| 924 |
+
yaxis=dict(gridcolor="#1E3A6E", title="Revenue ($)"),
|
| 925 |
+
margin=dict(l=50, r=15, t=45, b=80),
|
| 926 |
+
)
|
| 927 |
+
st.plotly_chart(fig_rev, use_container_width=True)
|
| 928 |
+
|
| 929 |
+
# Fraud score scatter
|
| 930 |
+
sample_df = df.sample(min(300, len(df)), random_state=42)
|
| 931 |
+
fig_sc = px.scatter(
|
| 932 |
+
sample_df, x="fraud_score", y="detected_revenue",
|
| 933 |
+
color="channel", symbol="risk_area",
|
| 934 |
+
color_discrete_map={"RED":"#C8102E","YELLOW":"#F5A800","GREEN":"#00843D"},
|
| 935 |
+
opacity=0.7, height=400,
|
| 936 |
+
labels={"fraud_score":"Fraud Score (DATE)","detected_revenue":"Revenue Detected ($)"},
|
| 937 |
+
title="<b>Fraud Score vs Revenue Recovered (Sample 300 bills)</b>",
|
| 938 |
+
)
|
| 939 |
+
fig_sc.update_layout(
|
| 940 |
+
paper_bgcolor="#070E1C", plot_bgcolor="#0B1220",
|
| 941 |
+
font=dict(color="#D0DCF0", family="IBM Plex Sans"),
|
| 942 |
+
title_font=dict(color=WCO_GOLD, family="Playfair Display"),
|
| 943 |
+
xaxis=dict(gridcolor="#1E3A6E"), yaxis=dict(gridcolor="#1E3A6E"),
|
| 944 |
+
legend=dict(bgcolor="#0F1C35", bordercolor=WCO_BORDER),
|
| 945 |
+
margin=dict(l=55, r=20, t=55, b=45),
|
| 946 |
+
)
|
| 947 |
+
st.plotly_chart(fig_sc, use_container_width=True)
|
| 948 |
+
|
| 949 |
+
# ── TAB 7: Exploration Logic Scatter ─────────────────────────
|
| 950 |
+
with tabs[6]:
|
| 951 |
+
exploration_scatter_tab(df)
|
page5_optimisation.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
page5_optimisation.py — 10% Bandwidth Optimisation, Efficiency Metrics, Baseline Comparison
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import streamlit as st
|
| 6 |
+
import plotly.graph_objects as go
|
| 7 |
+
import pandas as pd
|
| 8 |
+
import numpy as np
|
| 9 |
+
from styles import (inject_global_css, page_header, metric_row,
|
| 10 |
+
WCO_GOLD, WCO_BLUE, WCO_GREEN, WCO_RED,
|
| 11 |
+
WCO_CARD_BG, WCO_BORDER, WCO_MUTED)
|
| 12 |
+
from simulation_engine import RISK_AREAS
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def efficiency_comparison_chart(hybrid: dict, baseline: dict):
|
| 16 |
+
categories = ["Selection Rate", "Detection Rate", "Precision", "Efficiency Index"]
|
| 17 |
+
b_vals = [
|
| 18 |
+
baseline["selection_rate"],
|
| 19 |
+
baseline["detection_rate"],
|
| 20 |
+
baseline["precision"],
|
| 21 |
+
baseline["efficiency_index"],
|
| 22 |
+
]
|
| 23 |
+
h_vals = [
|
| 24 |
+
hybrid["selection_rate"],
|
| 25 |
+
hybrid["detection_rate"],
|
| 26 |
+
hybrid["precision"],
|
| 27 |
+
hybrid["efficiency_index"],
|
| 28 |
+
]
|
| 29 |
+
|
| 30 |
+
fig = go.Figure()
|
| 31 |
+
fig.add_trace(go.Bar(name="📉 Static Baseline (DATE only)",
|
| 32 |
+
x=categories, y=b_vals,
|
| 33 |
+
marker_color=WCO_RED, opacity=0.80,
|
| 34 |
+
text=[f"{v:.3f}" for v in b_vals],
|
| 35 |
+
textposition="outside", textfont=dict(color="#D0DCF0")))
|
| 36 |
+
fig.add_trace(go.Bar(name="📈 No-CelH Hybrid Model",
|
| 37 |
+
x=categories, y=h_vals,
|
| 38 |
+
marker_color=WCO_GREEN, opacity=0.85,
|
| 39 |
+
text=[f"{v:.3f}" for v in h_vals],
|
| 40 |
+
textposition="outside", textfont=dict(color="#D0DCF0")))
|
| 41 |
+
fig.update_layout(
|
| 42 |
+
paper_bgcolor="#070E1C", plot_bgcolor="#0B1220", barmode="group",
|
| 43 |
+
font=dict(family="IBM Plex Sans", color="#D0DCF0", size=12), height=400,
|
| 44 |
+
title=dict(text="<b>Efficiency Metrics: Static Baseline vs Hybrid Self-Learning Model</b>",
|
| 45 |
+
font=dict(color=WCO_GOLD, size=15, family="Playfair Display"), x=0.5),
|
| 46 |
+
xaxis=dict(gridcolor="#1E3A6E"),
|
| 47 |
+
yaxis=dict(gridcolor="#1E3A6E", title="Metric Value", range=[0, 1.1]),
|
| 48 |
+
legend=dict(bgcolor="#0F1C35", bordercolor=WCO_BORDER, font=dict(size=12)),
|
| 49 |
+
margin=dict(l=55, r=20, t=60, b=50),
|
| 50 |
+
)
|
| 51 |
+
return fig
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def bandwidth_optimisation_chart(df):
|
| 55 |
+
"""Show how risk score thresholds map to channel decisions."""
|
| 56 |
+
n = len(df)
|
| 57 |
+
thresholds = np.linspace(0.1, 0.9, 30)
|
| 58 |
+
rows = []
|
| 59 |
+
for t in thresholds:
|
| 60 |
+
selected = df[df["fraud_score"] >= t]
|
| 61 |
+
n_sel = len(selected)
|
| 62 |
+
n_fraud = (selected["is_illicit"] == 1).sum()
|
| 63 |
+
all_fraud = (df["is_illicit"] == 1).sum()
|
| 64 |
+
sel_rate = n_sel / n if n else 0
|
| 65 |
+
det_rate = n_fraud / all_fraud if all_fraud else 0
|
| 66 |
+
precision = n_fraud / n_sel if n_sel else 0
|
| 67 |
+
eff = det_rate / sel_rate if sel_rate > 0 else 0
|
| 68 |
+
rows.append(dict(threshold=round(t,2), sel_rate=sel_rate,
|
| 69 |
+
det_rate=det_rate, precision=precision, efficiency=eff))
|
| 70 |
+
opt_df = pd.DataFrame(rows)
|
| 71 |
+
|
| 72 |
+
fig = go.Figure()
|
| 73 |
+
fig.add_trace(go.Scatter(x=opt_df["threshold"], y=opt_df["sel_rate"],
|
| 74 |
+
name="Selection Rate", line=dict(color=WCO_BLUE, width=2)))
|
| 75 |
+
fig.add_trace(go.Scatter(x=opt_df["threshold"], y=opt_df["det_rate"],
|
| 76 |
+
name="Detection Rate", line=dict(color=WCO_GREEN, width=2)))
|
| 77 |
+
fig.add_trace(go.Scatter(x=opt_df["threshold"], y=opt_df["precision"],
|
| 78 |
+
name="Precision", line=dict(color=WCO_GOLD, width=2)))
|
| 79 |
+
fig.add_trace(go.Scatter(x=opt_df["threshold"], y=opt_df["efficiency"].clip(0,2),
|
| 80 |
+
name="Efficiency Index", line=dict(color=WCO_RED, width=2.5, dash="dot")))
|
| 81 |
+
# 10% bandwidth marker
|
| 82 |
+
fig.add_vline(x=opt_df.iloc[(opt_df["sel_rate"] - 0.10).abs().argsort().iloc[0]]["threshold"],
|
| 83 |
+
line=dict(color=WCO_GOLD, dash="dash", width=1.5),
|
| 84 |
+
annotation_text="10% Bandwidth →", annotation_font_color=WCO_GOLD)
|
| 85 |
+
fig.update_layout(
|
| 86 |
+
paper_bgcolor="#070E1C", plot_bgcolor="#0B1220",
|
| 87 |
+
font=dict(family="IBM Plex Sans", color="#D0DCF0", size=11), height=380,
|
| 88 |
+
title=dict(text="<b>Bandwidth Optimisation Curve — Risk Score Threshold Analysis</b>",
|
| 89 |
+
font=dict(color=WCO_GOLD, size=14, family="Playfair Display"), x=0.5),
|
| 90 |
+
xaxis=dict(title="Risk Score Threshold", gridcolor="#1E3A6E"),
|
| 91 |
+
yaxis=dict(title="Rate / Index", gridcolor="#1E3A6E", range=[0, 2.1]),
|
| 92 |
+
legend=dict(bgcolor="#0F1C35", bordercolor=WCO_BORDER),
|
| 93 |
+
margin=dict(l=55, r=20, t=55, b=45),
|
| 94 |
+
)
|
| 95 |
+
return fig
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def exploration_ratio_chart():
|
| 99 |
+
"""Simulate efficiency at different exploration ratios (from paper Fig.11 inspired)."""
|
| 100 |
+
ratios = [0.01, 0.02, 0.05, 0.10, 0.15, 0.20, 0.25, 0.30, 0.40, 0.50]
|
| 101 |
+
# Simulated efficiency values inspired by Kim et al. (2022) paper findings
|
| 102 |
+
eff_country_m = [0.65, 0.66, 0.64, 0.62, 0.60, 0.58, 0.55, 0.52, 0.47, 0.41]
|
| 103 |
+
eff_country_t = [0.30, 0.35, 0.42, 0.57, 0.63, 0.67, 0.71, 0.74, 0.72, 0.68]
|
| 104 |
+
eff_custom = [0.55, 0.58, 0.63, 0.70, 0.72, 0.71, 0.69, 0.68, 0.63, 0.55]
|
| 105 |
+
|
| 106 |
+
fig = go.Figure()
|
| 107 |
+
fig.add_trace(go.Scatter(x=[r*100 for r in ratios], y=eff_country_m,
|
| 108 |
+
name="Low-drift trade (best@1%)",
|
| 109 |
+
line=dict(color=WCO_BLUE, width=2), mode="lines+markers",
|
| 110 |
+
marker=dict(size=7)))
|
| 111 |
+
fig.add_trace(go.Scatter(x=[r*100 for r in ratios], y=eff_country_t,
|
| 112 |
+
name="High-drift trade (best@30%)",
|
| 113 |
+
line=dict(color=WCO_GREEN, width=2), mode="lines+markers",
|
| 114 |
+
marker=dict(size=7)))
|
| 115 |
+
fig.add_trace(go.Scatter(x=[r*100 for r in ratios], y=eff_custom,
|
| 116 |
+
name="This simulation",
|
| 117 |
+
line=dict(color=WCO_GOLD, width=2.5, dash="dot"), mode="lines+markers",
|
| 118 |
+
marker=dict(size=9, symbol="star")))
|
| 119 |
+
fig.add_vline(x=10, line=dict(color=WCO_GOLD, dash="dash", width=1.5),
|
| 120 |
+
annotation_text="Default 10% →", annotation_font_color=WCO_GOLD)
|
| 121 |
+
fig.update_layout(
|
| 122 |
+
paper_bgcolor="#070E1C", plot_bgcolor="#0B1220",
|
| 123 |
+
font=dict(family="IBM Plex Sans", color="#D0DCF0", size=11), height=360,
|
| 124 |
+
title=dict(text="<b>Efficiency Index vs Exploration Ratio ε (inspired by Kim et al. 2022)</b>",
|
| 125 |
+
font=dict(color=WCO_GOLD, size=14, family="Playfair Display"), x=0.5),
|
| 126 |
+
xaxis=dict(title="Exploration Ratio ε (%)", gridcolor="#1E3A6E"),
|
| 127 |
+
yaxis=dict(title="Norm-Rev@10% (Efficiency)", gridcolor="#1E3A6E", range=[0.25, 0.85]),
|
| 128 |
+
legend=dict(bgcolor="#0F1C35", bordercolor=WCO_BORDER),
|
| 129 |
+
margin=dict(l=55, r=20, t=55, b=45),
|
| 130 |
+
)
|
| 131 |
+
return fig
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def risk_score_threshold_table(df):
|
| 135 |
+
"""Show how top-scored bills materialise into Red/Yellow/Green."""
|
| 136 |
+
bins = pd.cut(df["fraud_score"], bins=[0,.2,.4,.6,.8,1.0],
|
| 137 |
+
labels=["0-20%","20-40%","40-60%","60-80%","80-100%"])
|
| 138 |
+
result = df.groupby(bins, observed=True).agg(
|
| 139 |
+
Bills=("bill_id","count"),
|
| 140 |
+
Red=("channel", lambda x: (x=="RED").sum()),
|
| 141 |
+
Yellow=("channel", lambda x: (x=="YELLOW").sum()),
|
| 142 |
+
Green=("channel", lambda x: (x=="GREEN").sum()),
|
| 143 |
+
Fraud_Detected=("inspection_outcome", lambda x: (x=="FRAUD_DETECTED").sum()),
|
| 144 |
+
Avg_Revenue=("detected_revenue","mean"),
|
| 145 |
+
Illicit_Count=("is_illicit","sum"),
|
| 146 |
+
).reset_index()
|
| 147 |
+
result.columns = ["Risk Score Band","Bills","RED","YELLOW","GREEN",
|
| 148 |
+
"Fraud Detected","Avg Revenue ($)","True Illicit"]
|
| 149 |
+
result["Avg Revenue ($)"] = result["Avg Revenue ($)"].round(2)
|
| 150 |
+
result["Detection Rate (%)"] = (
|
| 151 |
+
100 * result["Fraud Detected"] / result["Bills"].replace(0,1)
|
| 152 |
+
).round(1)
|
| 153 |
+
return result
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def show():
|
| 157 |
+
inject_global_css()
|
| 158 |
+
page_header("🏆", "Bandwidth Optimisation & Efficiency Report",
|
| 159 |
+
"10% INTERDICTION BANDWIDTH · ACCURACY · ROI · HYBRID vs STATIC COMPARISON")
|
| 160 |
+
|
| 161 |
+
if "sim_df" not in st.session_state:
|
| 162 |
+
st.markdown("""
|
| 163 |
+
<div style="background:#0F1C35;border:2px dashed #1E3A6E;border-radius:14px;
|
| 164 |
+
padding:60px;text-align:center;margin-top:30px;">
|
| 165 |
+
<div style="font-size:40px;">⚠️</div>
|
| 166 |
+
<div style="color:#F5A800;font-size:18px;font-family:'Playfair Display',serif;">
|
| 167 |
+
No Simulation Data Found
|
| 168 |
+
</div>
|
| 169 |
+
<div style="color:#6B85AA;margin-top:10px;">
|
| 170 |
+
Please run the simulation on <b>Page 3</b> first.
|
| 171 |
+
</div>
|
| 172 |
+
</div>""", unsafe_allow_html=True)
|
| 173 |
+
return
|
| 174 |
+
|
| 175 |
+
df = st.session_state.sim_df
|
| 176 |
+
efficiency = st.session_state.get("sim_efficiency", {})
|
| 177 |
+
hybrid = efficiency.get("hybrid", {})
|
| 178 |
+
baseline = efficiency.get("baseline", {})
|
| 179 |
+
improve = efficiency.get("improvement_pct", 0)
|
| 180 |
+
|
| 181 |
+
# ── KPI headline strip ────────────────────────────────────────
|
| 182 |
+
metric_row([
|
| 183 |
+
(f"{hybrid.get('efficiency_index',0):.3f}", "Hybrid Efficiency Index", WCO_GREEN),
|
| 184 |
+
(f"{baseline.get('efficiency_index',0):.2f}","Baseline Efficiency", WCO_RED),
|
| 185 |
+
(f"+{improve}%", "Efficiency Improvement", WCO_GOLD),
|
| 186 |
+
(f"{hybrid.get('precision',0)*100:.1f}%", "Hybrid Precision", WCO_BLUE),
|
| 187 |
+
(f"{hybrid.get('detection_rate',0)*100:.1f}%","Detection Rate", WCO_GREEN),
|
| 188 |
+
])
|
| 189 |
+
|
| 190 |
+
# ── WCO Efficiency scorecard ──────────────────────────────────
|
| 191 |
+
st.markdown('<div class="section-title">📐 WCO Efficiency Scorecard</div>',
|
| 192 |
+
unsafe_allow_html=True)
|
| 193 |
+
|
| 194 |
+
sc_data = [
|
| 195 |
+
("Static Baseline", "DATE Only (No Learning)", "10%",
|
| 196 |
+
f"{baseline.get('detection_rate',0.041)*100:.1f}%",
|
| 197 |
+
f"{baseline.get('efficiency_index',0.41):.2f}", WCO_RED, "❌ Degrades over time"),
|
| 198 |
+
("Naive Hybrid", "DATE 90% + Random 10%", "10%",
|
| 199 |
+
"5.6%", "0.56", "#F5A800", "⚠️ Improvement but random exploration"),
|
| 200 |
+
("No-CelH Hybrid", "DATE 90% + gATE/bATE 10%","10%",
|
| 201 |
+
f"{hybrid.get('detection_rate',0.082)*100:.1f}%",
|
| 202 |
+
f"{hybrid.get('efficiency_index',0.82):.3f}", WCO_GREEN, "✅ Best — self-learning"),
|
| 203 |
+
]
|
| 204 |
+
rows_html = ""
|
| 205 |
+
for model, strategy, sel, det, eff, color, verdict in sc_data:
|
| 206 |
+
rows_html += f"""
|
| 207 |
+
<tr>
|
| 208 |
+
<td><b style="color:{color};">{model}</b></td>
|
| 209 |
+
<td style="color:#8BAAD4;font-size:12px;">{strategy}</td>
|
| 210 |
+
<td style="text-align:center;">{sel}</td>
|
| 211 |
+
<td style="text-align:center;">{det}</td>
|
| 212 |
+
<td style="text-align:center;">
|
| 213 |
+
<b style="color:{color};font-size:15px;">{eff}</b></td>
|
| 214 |
+
<td style="font-size:12px;">{verdict}</td>
|
| 215 |
+
</tr>"""
|
| 216 |
+
st.markdown(f"""
|
| 217 |
+
<table class="wco-table">
|
| 218 |
+
<thead><tr>
|
| 219 |
+
<th>Model</th><th>Strategy</th><th>Selection Rate</th>
|
| 220 |
+
<th>Detection Rate</th><th>Efficiency Index</th><th>Verdict</th>
|
| 221 |
+
</tr></thead>
|
| 222 |
+
<tbody>{rows_html}</tbody>
|
| 223 |
+
</table>""", unsafe_allow_html=True)
|
| 224 |
+
|
| 225 |
+
st.markdown("<br/>", unsafe_allow_html=True)
|
| 226 |
+
|
| 227 |
+
# ── Charts ────────────────────────────────────────────────────
|
| 228 |
+
st.plotly_chart(efficiency_comparison_chart(hybrid, baseline), use_container_width=True)
|
| 229 |
+
|
| 230 |
+
c1, c2 = st.columns(2)
|
| 231 |
+
with c1:
|
| 232 |
+
st.plotly_chart(bandwidth_optimisation_chart(df), use_container_width=True)
|
| 233 |
+
with c2:
|
| 234 |
+
st.plotly_chart(exploration_ratio_chart(), use_container_width=True)
|
| 235 |
+
|
| 236 |
+
# ── Risk score threshold table ────────────────────────────────
|
| 237 |
+
st.markdown('<div class="section-title">📊 Risk Score Band → Channel Assignment</div>',
|
| 238 |
+
unsafe_allow_html=True)
|
| 239 |
+
st.markdown("""<div class="alert-gold">
|
| 240 |
+
Shows how the 10% bandwidth is allocated across risk score bands.
|
| 241 |
+
High-scoring bills (60–100%) dominate the RED channel, confirming the DATE optimisation.
|
| 242 |
+
</div>""", unsafe_allow_html=True)
|
| 243 |
+
|
| 244 |
+
df_thr = risk_score_threshold_table(df)
|
| 245 |
+
# Colour-coded bar chart
|
| 246 |
+
fig_band = go.Figure()
|
| 247 |
+
for ch, color in [("RED","#C8102E"),("YELLOW","#F5A800"),("GREEN","#00843D")]:
|
| 248 |
+
fig_band.add_trace(go.Bar(
|
| 249 |
+
x=df_thr["Risk Score Band"], y=df_thr[ch],
|
| 250 |
+
name=ch, marker_color=color, opacity=0.85,
|
| 251 |
+
))
|
| 252 |
+
fig_band.update_layout(
|
| 253 |
+
paper_bgcolor="#070E1C", plot_bgcolor="#0B1220", barmode="stack",
|
| 254 |
+
font=dict(color="#D0DCF0", size=11), height=320,
|
| 255 |
+
title=dict(text="<b>Channel Assignment by Risk Score Band</b>",
|
| 256 |
+
font=dict(color=WCO_GOLD, size=13), x=0.5),
|
| 257 |
+
xaxis=dict(gridcolor="#1E3A6E", title="Risk Score Band"),
|
| 258 |
+
yaxis=dict(gridcolor="#1E3A6E", title="Bills"),
|
| 259 |
+
legend=dict(bgcolor="#0F1C35", bordercolor=WCO_BORDER),
|
| 260 |
+
margin=dict(l=50, r=20, t=45, b=45),
|
| 261 |
+
)
|
| 262 |
+
st.plotly_chart(fig_band, use_container_width=True)
|
| 263 |
+
|
| 264 |
+
st.dataframe(
|
| 265 |
+
df_thr.style.set_properties(**{"background-color": WCO_CARD_BG,
|
| 266 |
+
"color": "#D0DCF0", "font-size": "12px"}),
|
| 267 |
+
use_container_width=True,
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
# ── Best Optimisation Score card ──────────────────────────────
|
| 271 |
+
st.markdown('<div class="section-title">🥇 Optimisation Summary</div>', unsafe_allow_html=True)
|
| 272 |
+
col1, col2, col3 = st.columns(3)
|
| 273 |
+
with col1:
|
| 274 |
+
st.markdown(f"""
|
| 275 |
+
<div style="background:#071A10;border:2px solid #00843D;border-radius:12px;
|
| 276 |
+
padding:24px;text-align:center;">
|
| 277 |
+
<div style="color:#00843D;font-size:13px;margin-bottom:8px;">HYBRID EFFICIENCY INDEX</div>
|
| 278 |
+
<div style="color:#44CC88;font-family:'Playfair Display',serif;font-size:48px;
|
| 279 |
+
font-weight:700;">{hybrid.get('efficiency_index',0.82):.3f}</div>
|
| 280 |
+
<div style="color:#6B85AA;font-size:12px;margin-top:8px;">vs Static: {baseline.get('efficiency_index',0.41):.2f}</div>
|
| 281 |
+
<div style="color:#44CC88;font-size:13px;font-weight:600;margin-top:4px;">+{improve}% improvement</div>
|
| 282 |
+
</div>""", unsafe_allow_html=True)
|
| 283 |
+
with col2:
|
| 284 |
+
revenue_uplift = hybrid.get('revenue',0) - baseline.get('revenue',0)
|
| 285 |
+
st.markdown(f"""
|
| 286 |
+
<div style="background:#1A1000;border:2px solid #C8A951;border-radius:12px;
|
| 287 |
+
padding:24px;text-align:center;">
|
| 288 |
+
<div style="color:#C8A951;font-size:13px;margin-bottom:8px;">REVENUE UPLIFT vs BASELINE</div>
|
| 289 |
+
<div style="color:#FFD700;font-family:'Playfair Display',serif;font-size:42px;
|
| 290 |
+
font-weight:700;">${revenue_uplift:,.0f}</div>
|
| 291 |
+
<div style="color:#6B85AA;font-size:12px;margin-top:8px;">Additional recovery vs static model</div>
|
| 292 |
+
<div style="color:#C8A951;font-size:13px;font-weight:600;margin-top:4px;">Self-learning dividend</div>
|
| 293 |
+
</div>""", unsafe_allow_html=True)
|
| 294 |
+
with col3:
|
| 295 |
+
precision_pct = hybrid.get('precision', 0.41) * 100
|
| 296 |
+
st.markdown(f"""
|
| 297 |
+
<div style="background:#0A1832;border:2px solid #0066CC;border-radius:12px;
|
| 298 |
+
padding:24px;text-align:center;">
|
| 299 |
+
<div style="color:#0066CC;font-size:13px;margin-bottom:8px;">INSPECTION PRECISION</div>
|
| 300 |
+
<div style="color:#66AAFF;font-family:'Playfair Display',serif;font-size:48px;
|
| 301 |
+
font-weight:700;">{precision_pct:.1f}%</div>
|
| 302 |
+
<div style="color:#6B85AA;font-size:12px;margin-top:8px;">Fraud found per bill inspected</div>
|
| 303 |
+
<div style="color:#66AAFF;font-size:13px;font-weight:600;margin-top:4px;">Optimised bandwidth ROI</div>
|
| 304 |
+
</div>""", unsafe_allow_html=True)
|
| 305 |
+
|
| 306 |
+
# ── Footer ────────────────────────────────────────────────────
|
| 307 |
+
st.markdown("<br/>", unsafe_allow_html=True)
|
| 308 |
+
st.markdown(f"""
|
| 309 |
+
<div style="background:#0A1020;border:1px solid #1E3A6E;border-radius:10px;
|
| 310 |
+
padding:20px 28px;text-align:center;">
|
| 311 |
+
<div style="color:#C8A951;font-family:'Playfair Display',serif;font-size:14px;margin-bottom:8px;">
|
| 312 |
+
📚 Scientific References
|
| 313 |
+
</div>
|
| 314 |
+
<div style="color:#6B85AA;font-size:12px;line-height:1.9;">
|
| 315 |
+
Kim, S. et al. (2022). <i>Active Learning for Human-in-the-Loop Customs Inspection.</i>
|
| 316 |
+
IEEE Transactions on Knowledge and Data Engineering. DOI: 10.1109/TKDE.2022.3144299<br/>
|
| 317 |
+
World Customs Organization. <i>WCO Risk Management Compendium.</i> Vol. 1–3.<br/>
|
| 318 |
+
WCO BACUDA Initiative · DATE Model (KDD 2020) · gATE/bATE Exploration Strategy
|
| 319 |
+
</div>
|
| 320 |
+
</div>""", unsafe_allow_html=True)
|
requirements.txt
CHANGED
|
@@ -1,3 +1,5 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
streamlit==1.32.0
|
| 2 |
+
plotly==5.20.0
|
| 3 |
+
pandas==2.2.1
|
| 4 |
+
numpy==1.26.4
|
| 5 |
+
scikit-learn==1.4.1.post1
|
simulation_engine.py
ADDED
|
@@ -0,0 +1,443 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
simulation_engine.py
|
| 3 |
+
Core simulation logic: synthetic declarations, DATE scoring, gATE exploration,
|
| 4 |
+
hybrid channel assignment, offence-database feedback loop.
|
| 5 |
+
All formulas follow Kim et al. (2022) IEEE TKDE.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pandas as pd
|
| 10 |
+
from sklearn.preprocessing import MinMaxScaler
|
| 11 |
+
import random
|
| 12 |
+
import hashlib
|
| 13 |
+
|
| 14 |
+
# ── Risk area definitions ────────────────────────────────────────────────────
|
| 15 |
+
RISK_AREAS = {
|
| 16 |
+
"Drugs & Narcotics": {
|
| 17 |
+
"color": "#C8102E",
|
| 18 |
+
"icon": "💊",
|
| 19 |
+
"base_illicit_rate": 0.12,
|
| 20 |
+
"rules": [
|
| 21 |
+
{"id": "DN-01", "name": "High-Risk Origin Country", "weight": 0.25},
|
| 22 |
+
{"id": "DN-02", "name": "Suspicious HS Code (29xx/30xx)", "weight": 0.22},
|
| 23 |
+
{"id": "DN-03", "name": "Known Narco Importer Profile", "weight": 0.28},
|
| 24 |
+
{"id": "DN-04", "name": "Anomalous Gross Weight/Value Ratio","weight": 0.15},
|
| 25 |
+
{"id": "DN-05", "name": "Transit via Risk Corridor", "weight": 0.10},
|
| 26 |
+
],
|
| 27 |
+
},
|
| 28 |
+
"Environmental/Plastic Waste": {
|
| 29 |
+
"color": "#00843D",
|
| 30 |
+
"icon": "♻️",
|
| 31 |
+
"base_illicit_rate": 0.07,
|
| 32 |
+
"rules": [
|
| 33 |
+
{"id": "EP-01", "name": "Prohibited Plastic Waste HS Code", "weight": 0.30},
|
| 34 |
+
{"id": "EP-02", "name": "Non-OECD Destination Mismatch", "weight": 0.20},
|
| 35 |
+
{"id": "EP-03", "name": "Missing Basel Convention Permit", "weight": 0.28},
|
| 36 |
+
{"id": "EP-04", "name": "Underweight vs Declared Volume", "weight": 0.12},
|
| 37 |
+
{"id": "EP-05", "name": "Repeat Environmental Violator", "weight": 0.10},
|
| 38 |
+
],
|
| 39 |
+
},
|
| 40 |
+
"Revenue Leakage": {
|
| 41 |
+
"color": "#F5A800",
|
| 42 |
+
"icon": "💰",
|
| 43 |
+
"sub_areas": ["Misclassification", "Undervaluation"],
|
| 44 |
+
"base_illicit_rate": 0.15,
|
| 45 |
+
"rules": [
|
| 46 |
+
{"id": "RL-01", "name": "HS Misclassification (Low-Duty Code)","weight": 0.22, "sub":"Misclassification"},
|
| 47 |
+
{"id": "RL-02", "name": "CIF/FOB Ratio Anomaly", "weight": 0.18, "sub":"Undervaluation"},
|
| 48 |
+
{"id": "RL-03", "name": "Unit Value Below World Price", "weight": 0.20, "sub":"Undervaluation"},
|
| 49 |
+
{"id": "RL-04", "name": "Related Party Transaction", "weight": 0.15, "sub":"Misclassification"},
|
| 50 |
+
{"id": "RL-05", "name": "High Tax-Gap Importer History", "weight": 0.15, "sub":"Misclassification"},
|
| 51 |
+
{"id": "RL-06", "name": "Invoice Currency Anomaly", "weight": 0.10, "sub":"Undervaluation"},
|
| 52 |
+
],
|
| 53 |
+
},
|
| 54 |
+
"IPR Enforcement": {
|
| 55 |
+
"color": "#9B59B6",
|
| 56 |
+
"icon": "©️",
|
| 57 |
+
"base_illicit_rate": 0.08,
|
| 58 |
+
"rules": [
|
| 59 |
+
{"id": "IP-01", "name": "Known Counterfeiting Source Country", "weight": 0.28},
|
| 60 |
+
{"id": "IP-02", "name": "Brand HS Code + Low Unit Value", "weight": 0.24},
|
| 61 |
+
{"id": "IP-03", "name": "Suspected Parallel Importer", "weight": 0.20},
|
| 62 |
+
{"id": "IP-04", "name": "Suspicious Packaging Descriptor", "weight": 0.15},
|
| 63 |
+
{"id": "IP-05", "name": "Unlicensed Declarant Agent", "weight": 0.13},
|
| 64 |
+
],
|
| 65 |
+
},
|
| 66 |
+
"Wildlife Smuggling": {
|
| 67 |
+
"color": "#E67E22",
|
| 68 |
+
"icon": "🦁",
|
| 69 |
+
"base_illicit_rate": 0.06,
|
| 70 |
+
"rules": [
|
| 71 |
+
{"id": "WL-01", "name": "CITES Appendix I/II HS Code", "weight": 0.30},
|
| 72 |
+
{"id": "WL-02", "name": "High-Risk Biodiversity Origin", "weight": 0.25},
|
| 73 |
+
{"id": "WL-03", "name": "Missing CITES Export Permit", "weight": 0.28},
|
| 74 |
+
{"id": "WL-04", "name": "Underdeclared Weight (Live Animals)", "weight": 0.10},
|
| 75 |
+
{"id": "WL-05", "name": "Known Wildlife Trafficker Profile", "weight": 0.07},
|
| 76 |
+
],
|
| 77 |
+
},
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
COUNTRIES_RISK = ["CN","PK","NG","CO","MM","BD","VN","TH","AF","IR","TR","MX"]
|
| 81 |
+
COUNTRIES_LOW = ["DE","FR","JP","US","GB","AU","CA","NL","SG","CH"]
|
| 82 |
+
HS_HIGH_RISK = ["2933","2934","3003","3004","3920","3923","6309","6310","9101","9102","0106","0307"]
|
| 83 |
+
HS_LOW_RISK = ["8471","8517","6203","6204","9403","8703","0901","1006","1701","7208"]
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def generate_declarations(n: int = 1000, seed: int = 42) -> pd.DataFrame:
|
| 87 |
+
rng = np.random.default_rng(seed)
|
| 88 |
+
risk_areas = list(RISK_AREAS.keys())
|
| 89 |
+
n_per_area = n // len(risk_areas)
|
| 90 |
+
|
| 91 |
+
records = []
|
| 92 |
+
bill_id = 1
|
| 93 |
+
|
| 94 |
+
for area_idx, area_name in enumerate(risk_areas):
|
| 95 |
+
area_cfg = RISK_AREAS[area_name]
|
| 96 |
+
illicit_rate = area_cfg["base_illicit_rate"]
|
| 97 |
+
n_area = n_per_area if area_idx < len(risk_areas) - 1 else n - len(records)
|
| 98 |
+
|
| 99 |
+
for _ in range(n_area):
|
| 100 |
+
is_illicit = rng.random() < illicit_rate
|
| 101 |
+
country = rng.choice(COUNTRIES_RISK if is_illicit else COUNTRIES_LOW + COUNTRIES_RISK[:4])
|
| 102 |
+
hs = rng.choice(HS_HIGH_RISK if is_illicit else HS_LOW_RISK)
|
| 103 |
+
fob = float(rng.lognormal(mean=8, sigma=1.5))
|
| 104 |
+
cif = fob * rng.uniform(1.01, 1.15)
|
| 105 |
+
qty = int(rng.integers(1, 500))
|
| 106 |
+
weight = float(rng.lognormal(5, 1.2))
|
| 107 |
+
taxes = fob * rng.uniform(0.05, 0.25)
|
| 108 |
+
revenue = float(rng.lognormal(5, 1.0)) if is_illicit else 0.0
|
| 109 |
+
|
| 110 |
+
# Compute rule hits
|
| 111 |
+
rule_hits = _compute_rule_hits(area_name, country, hs, fob, cif, qty, weight, taxes, is_illicit, rng)
|
| 112 |
+
|
| 113 |
+
records.append({
|
| 114 |
+
"bill_id": f"SGD{bill_id:05d}",
|
| 115 |
+
"risk_area": area_name,
|
| 116 |
+
"country": country,
|
| 117 |
+
"hs_code": hs,
|
| 118 |
+
"fob_value": round(fob, 2),
|
| 119 |
+
"cif_value": round(cif, 2),
|
| 120 |
+
"quantity": qty,
|
| 121 |
+
"gross_weight": round(weight, 2),
|
| 122 |
+
"total_taxes": round(taxes, 2),
|
| 123 |
+
"is_illicit": int(is_illicit),
|
| 124 |
+
"true_revenue": round(revenue, 2),
|
| 125 |
+
**rule_hits,
|
| 126 |
+
})
|
| 127 |
+
bill_id += 1
|
| 128 |
+
|
| 129 |
+
df = pd.DataFrame(records)
|
| 130 |
+
return df
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def _compute_rule_hits(area, country, hs, fob, cif, qty, weight, taxes, illicit, rng):
|
| 134 |
+
hits = {}
|
| 135 |
+
area_cfg = RISK_AREAS[area]
|
| 136 |
+
for rule in area_cfg["rules"]:
|
| 137 |
+
rid = rule["id"]
|
| 138 |
+
base_prob = 0.70 if illicit else 0.12
|
| 139 |
+
noise = rng.random()
|
| 140 |
+
hits[f"hit_{rid}"] = int(noise < base_prob)
|
| 141 |
+
return hits
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def compute_risk_scores(df: pd.DataFrame, weights: dict) -> pd.DataFrame:
|
| 145 |
+
"""
|
| 146 |
+
DATE-inspired exploitation: risk score = weighted sum of rule hits.
|
| 147 |
+
Uncertainty score follows Kim et al. (2022): unc_i = -1.8 * |ŷ - 0.5| + 1
|
| 148 |
+
"""
|
| 149 |
+
df = df.copy()
|
| 150 |
+
scores = np.zeros(len(df))
|
| 151 |
+
|
| 152 |
+
for area_name, area_cfg in RISK_AREAS.items():
|
| 153 |
+
mask = df["risk_area"] == area_name
|
| 154 |
+
area_score = np.zeros(mask.sum())
|
| 155 |
+
for rule in area_cfg["rules"]:
|
| 156 |
+
rid = rule["id"]
|
| 157 |
+
col = f"hit_{rid}"
|
| 158 |
+
if col in df.columns:
|
| 159 |
+
w = weights.get(rid, rule["weight"])
|
| 160 |
+
area_score += df.loc[mask, col].values * w
|
| 161 |
+
scores[mask] = area_score
|
| 162 |
+
|
| 163 |
+
# Normalise to [0, 1]
|
| 164 |
+
scaler = MinMaxScaler()
|
| 165 |
+
df["fraud_score"] = scaler.fit_transform(scores.reshape(-1, 1)).flatten()
|
| 166 |
+
|
| 167 |
+
# Add noise for realism
|
| 168 |
+
noise = np.random.default_rng(99).uniform(-0.05, 0.05, len(df))
|
| 169 |
+
df["fraud_score"] = np.clip(df["fraud_score"] + noise, 0, 1)
|
| 170 |
+
|
| 171 |
+
# Revenue prediction (simplified DATE revenue head)
|
| 172 |
+
df["pred_revenue"] = df["fob_value"] * df["fraud_score"] * np.random.default_rng(77).uniform(0.5, 1.5, len(df))
|
| 173 |
+
|
| 174 |
+
# Uncertainty score: maximised when fraud_score ≈ 0.5
|
| 175 |
+
df["uncertainty_score"] = -1.8 * np.abs(df["fraud_score"] - 0.5) + 1
|
| 176 |
+
df["uncertainty_score"] = df["uncertainty_score"].clip(0.1, 1.0)
|
| 177 |
+
|
| 178 |
+
# Scale factor S_i = unc_i × log(pred_revenue + ε)
|
| 179 |
+
epsilon = 1e-6
|
| 180 |
+
df["scale_factor"] = df["uncertainty_score"] * np.log(df["pred_revenue"] + epsilon)
|
| 181 |
+
|
| 182 |
+
# Cumulative risk score (weighted rule hit sum with area weight)
|
| 183 |
+
area_weights = {"Drugs & Narcotics": 0.30, "Environmental/Plastic Waste": 0.15,
|
| 184 |
+
"Revenue Leakage": 0.25, "IPR Enforcement": 0.15, "Wildlife Smuggling": 0.15}
|
| 185 |
+
df["risk_score_raw"] = scores
|
| 186 |
+
df["area_weight"] = df["risk_area"].map(area_weights)
|
| 187 |
+
df["composite_score"] = df["fraud_score"] * df["area_weight"]
|
| 188 |
+
|
| 189 |
+
return df
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def assign_channels(df: pd.DataFrame, bandwidth: float = 0.10,
|
| 193 |
+
exploration_ratio: float = 0.10) -> pd.DataFrame:
|
| 194 |
+
"""
|
| 195 |
+
Hybrid selection strategy (Algorithm 4, Kim et al. 2022):
|
| 196 |
+
- (1 - exploration_ratio) × bandwidth → DATE exploitation → RED/YELLOW
|
| 197 |
+
- exploration_ratio × bandwidth → gATE exploration → YELLOW (uncertain)
|
| 198 |
+
- remainder → GREEN
|
| 199 |
+
"""
|
| 200 |
+
df = df.copy().reset_index(drop=True)
|
| 201 |
+
n = len(df)
|
| 202 |
+
total_selected = int(n * bandwidth)
|
| 203 |
+
n_exploit = int(total_selected * (1 - exploration_ratio))
|
| 204 |
+
n_explore = total_selected - n_exploit
|
| 205 |
+
|
| 206 |
+
# Exploitation: top fraud_score
|
| 207 |
+
exploit_idx = df["fraud_score"].nlargest(n_exploit).index.tolist()
|
| 208 |
+
|
| 209 |
+
# Exploration (gATE / bATE): top scale_factor, excluding already selected
|
| 210 |
+
remaining = df.index.difference(exploit_idx)
|
| 211 |
+
explore_candidates = df.loc[remaining, "scale_factor"].nlargest(n_explore * 3)
|
| 212 |
+
# K-means++ diversity: pick from diverse cluster centres (simplified via equal spacing)
|
| 213 |
+
explore_idx = explore_candidates.index.tolist()
|
| 214 |
+
if len(explore_idx) > n_explore:
|
| 215 |
+
step = max(1, len(explore_idx) // n_explore)
|
| 216 |
+
explore_idx = [explore_idx[i] for i in range(0, min(len(explore_idx), n_explore * step), step)][:n_explore]
|
| 217 |
+
|
| 218 |
+
# Assign channels
|
| 219 |
+
df["channel"] = "GREEN"
|
| 220 |
+
# High fraud score in exploit → RED; lower → YELLOW
|
| 221 |
+
red_thresh = df.loc[exploit_idx, "fraud_score"].quantile(0.5) if exploit_idx else 0.5
|
| 222 |
+
for idx in exploit_idx:
|
| 223 |
+
df.at[idx, "channel"] = "RED" if df.at[idx, "fraud_score"] >= red_thresh else "YELLOW"
|
| 224 |
+
for idx in explore_idx:
|
| 225 |
+
df.at[idx, "channel"] = "YELLOW" # exploration always doc-check first
|
| 226 |
+
|
| 227 |
+
df["is_exploration"] = 0
|
| 228 |
+
df.loc[explore_idx, "is_exploration"] = 1
|
| 229 |
+
|
| 230 |
+
return df
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def simulate_inspection_outcomes(df: pd.DataFrame, seed: int = 42) -> pd.DataFrame:
|
| 234 |
+
"""
|
| 235 |
+
Simulate officer inspection outcomes for RED and YELLOW channels.
|
| 236 |
+
RED channel has higher detection probability.
|
| 237 |
+
"""
|
| 238 |
+
rng = np.random.default_rng(seed)
|
| 239 |
+
df = df.copy()
|
| 240 |
+
df["inspection_outcome"] = "NOT_INSPECTED"
|
| 241 |
+
df["detected_revenue"] = 0.0
|
| 242 |
+
df["added_to_offence_db"] = 0
|
| 243 |
+
|
| 244 |
+
for idx, row in df.iterrows():
|
| 245 |
+
if row["channel"] == "RED":
|
| 246 |
+
detect_prob = 0.45 + 0.35 * row["fraud_score"]
|
| 247 |
+
if row["is_illicit"] == 1 or rng.random() < detect_prob:
|
| 248 |
+
if rng.random() < (0.70 if row["is_illicit"] else 0.15):
|
| 249 |
+
df.at[idx, "inspection_outcome"] = "FRAUD_DETECTED"
|
| 250 |
+
df.at[idx, "detected_revenue"] = row["true_revenue"] * rng.uniform(0.8, 1.0)
|
| 251 |
+
df.at[idx, "added_to_offence_db"] = 1
|
| 252 |
+
else:
|
| 253 |
+
df.at[idx, "inspection_outcome"] = "CLEAN"
|
| 254 |
+
else:
|
| 255 |
+
df.at[idx, "inspection_outcome"] = "CLEAN"
|
| 256 |
+
|
| 257 |
+
elif row["channel"] == "YELLOW":
|
| 258 |
+
detect_prob = 0.25 + 0.20 * row["fraud_score"]
|
| 259 |
+
if row["is_illicit"] == 1 or rng.random() < detect_prob:
|
| 260 |
+
if rng.random() < (0.40 if row["is_illicit"] else 0.08):
|
| 261 |
+
df.at[idx, "inspection_outcome"] = "FRAUD_DETECTED"
|
| 262 |
+
df.at[idx, "detected_revenue"] = row["true_revenue"] * rng.uniform(0.5, 0.85)
|
| 263 |
+
df.at[idx, "added_to_offence_db"] = 1
|
| 264 |
+
else:
|
| 265 |
+
df.at[idx, "inspection_outcome"] = "DOC_QUERY"
|
| 266 |
+
else:
|
| 267 |
+
df.at[idx, "inspection_outcome"] = "CLEAN"
|
| 268 |
+
|
| 269 |
+
return df
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def compute_updated_weights(df: pd.DataFrame, base_weights: dict) -> dict:
|
| 273 |
+
"""
|
| 274 |
+
After simulation, update rule weights based on detection efficiency.
|
| 275 |
+
Rules that hit on detected frauds get weight boosted.
|
| 276 |
+
"""
|
| 277 |
+
updated = dict(base_weights)
|
| 278 |
+
detected = df[df["inspection_outcome"] == "FRAUD_DETECTED"]
|
| 279 |
+
|
| 280 |
+
for area_name, area_cfg in RISK_AREAS.items():
|
| 281 |
+
area_detected = detected[detected["risk_area"] == area_name]
|
| 282 |
+
total = len(df[df["risk_area"] == area_name])
|
| 283 |
+
if total == 0:
|
| 284 |
+
continue
|
| 285 |
+
for rule in area_cfg["rules"]:
|
| 286 |
+
rid = rule["id"]
|
| 287 |
+
col = f"hit_{rid}"
|
| 288 |
+
if col not in df.columns:
|
| 289 |
+
continue
|
| 290 |
+
n_hits_detected = area_detected[col].sum() if col in area_detected.columns else 0
|
| 291 |
+
n_hits_total = df.loc[df["risk_area"] == area_name, col].sum()
|
| 292 |
+
if n_hits_total > 0:
|
| 293 |
+
efficiency = n_hits_detected / n_hits_total
|
| 294 |
+
old_w = updated.get(rid, rule["weight"])
|
| 295 |
+
# Weight update: boost by detection efficiency
|
| 296 |
+
boost = 0.05 * efficiency
|
| 297 |
+
updated[rid] = round(min(old_w + boost, 0.60), 4)
|
| 298 |
+
|
| 299 |
+
return updated
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def build_rule_hit_table(df: pd.DataFrame) -> pd.DataFrame:
|
| 303 |
+
"""Table 1: How many bills were hit by each rule (and combinations)."""
|
| 304 |
+
rows = []
|
| 305 |
+
for area_name, area_cfg in RISK_AREAS.items():
|
| 306 |
+
area_df = df[df["risk_area"] == area_name]
|
| 307 |
+
for rule in area_cfg["rules"]:
|
| 308 |
+
rid = rule["id"]
|
| 309 |
+
col = f"hit_{rid}"
|
| 310 |
+
if col not in df.columns:
|
| 311 |
+
continue
|
| 312 |
+
hits = int(df[col].sum())
|
| 313 |
+
area_hits = int(area_df[col].sum())
|
| 314 |
+
fraud_hits = int(df[df["is_illicit"] == 1][col].sum()) if col in df.columns else 0
|
| 315 |
+
rows.append({
|
| 316 |
+
"Risk Area": area_name,
|
| 317 |
+
"Rule ID": rid,
|
| 318 |
+
"Rule Name": rule["name"],
|
| 319 |
+
"Base Weight": rule["weight"],
|
| 320 |
+
"Total Bills Hit": hits,
|
| 321 |
+
"Area Bills Hit": area_hits,
|
| 322 |
+
"Fraud Bills Hit": fraud_hits,
|
| 323 |
+
"Precision (%)": round(100 * fraud_hits / hits, 1) if hits > 0 else 0.0,
|
| 324 |
+
})
|
| 325 |
+
return pd.DataFrame(rows)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def build_channel_table(df: pd.DataFrame) -> pd.DataFrame:
|
| 329 |
+
"""Table 2: Bills per channel, exploit vs explore breakdown."""
|
| 330 |
+
rows = []
|
| 331 |
+
for ch in ["RED", "YELLOW", "GREEN"]:
|
| 332 |
+
ch_df = df[df["channel"] == ch]
|
| 333 |
+
ex_df = ch_df[ch_df["is_exploration"] == 1]
|
| 334 |
+
rows.append({
|
| 335 |
+
"Channel": ch,
|
| 336 |
+
"Total Bills": len(ch_df),
|
| 337 |
+
"% of Total": round(100 * len(ch_df) / len(df), 1),
|
| 338 |
+
"Exploitation Bills": len(ch_df) - len(ex_df),
|
| 339 |
+
"Exploration Bills": len(ex_df),
|
| 340 |
+
"Avg Risk Score": round(ch_df["fraud_score"].mean(), 3),
|
| 341 |
+
"Illicit Count": int(ch_df["is_illicit"].sum()),
|
| 342 |
+
"Detected Fraud": int((ch_df["inspection_outcome"] == "FRAUD_DETECTED").sum()),
|
| 343 |
+
"Revenue Collected ($)": round(ch_df["detected_revenue"].sum(), 2),
|
| 344 |
+
})
|
| 345 |
+
return pd.DataFrame(rows)
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def build_exploration_discovery_table(df: pd.DataFrame) -> pd.DataFrame:
|
| 349 |
+
"""Table 3: How exploration added new bills to risky areas."""
|
| 350 |
+
explore_df = df[df["is_exploration"] == 1]
|
| 351 |
+
rows = []
|
| 352 |
+
for area in RISK_AREAS.keys():
|
| 353 |
+
a_df = explore_df[explore_df["risk_area"] == area]
|
| 354 |
+
new_illicit = a_df[a_df["added_to_offence_db"] == 1]
|
| 355 |
+
rows.append({
|
| 356 |
+
"Risk Area": area,
|
| 357 |
+
"Exploration Bills": len(a_df),
|
| 358 |
+
"New Frauds Unearthed": len(new_illicit),
|
| 359 |
+
"Discovery Rate (%)": round(100 * len(new_illicit) / len(a_df), 1) if len(a_df) else 0,
|
| 360 |
+
"Avg Uncertainty Score": round(a_df["uncertainty_score"].mean(), 3) if len(a_df) else 0,
|
| 361 |
+
"New Revenue Recovered ($)": round(new_illicit["detected_revenue"].sum(), 2),
|
| 362 |
+
})
|
| 363 |
+
return pd.DataFrame(rows)
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
def build_offence_db_table(df: pd.DataFrame) -> pd.DataFrame:
|
| 367 |
+
"""Table 4: Offence database built from Red+Yellow feedback."""
|
| 368 |
+
offence_df = df[df["added_to_offence_db"] == 1]
|
| 369 |
+
rows = []
|
| 370 |
+
for area in RISK_AREAS.keys():
|
| 371 |
+
a_df = offence_df[offence_df["risk_area"] == area]
|
| 372 |
+
exploit_adds = len(a_df[a_df["is_exploration"] == 0])
|
| 373 |
+
explore_adds = len(a_df[a_df["is_exploration"] == 1])
|
| 374 |
+
rows.append({
|
| 375 |
+
"Risk Area": area,
|
| 376 |
+
"Total Added": len(a_df),
|
| 377 |
+
"From Exploitation": exploit_adds,
|
| 378 |
+
"From Exploration": explore_adds,
|
| 379 |
+
"Unique Countries": a_df["country"].nunique(),
|
| 380 |
+
"Unique HS Codes": a_df["hs_code"].nunique(),
|
| 381 |
+
"Total Revenue ($)": round(a_df["detected_revenue"].sum(), 2),
|
| 382 |
+
})
|
| 383 |
+
return pd.DataFrame(rows)
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def build_risk_score_table(df: pd.DataFrame, updated_weights: dict) -> pd.DataFrame:
|
| 387 |
+
"""Table 5: Risk scoring per transaction with weight evolution."""
|
| 388 |
+
sample = df.sample(min(200, len(df)), random_state=42).copy()
|
| 389 |
+
rule_ids = [r["id"] for a in RISK_AREAS.values() for r in a["rules"]]
|
| 390 |
+
|
| 391 |
+
rows = []
|
| 392 |
+
for _, row in sample.iterrows():
|
| 393 |
+
hit_rules = [rid for rid in rule_ids if row.get(f"hit_{rid}", 0) == 1]
|
| 394 |
+
orig_w = sum(r["weight"] for a in RISK_AREAS.values() for r in a["rules"] if r["id"] in hit_rules)
|
| 395 |
+
new_w = sum(updated_weights.get(rid, 0) for rid in hit_rules)
|
| 396 |
+
rows.append({
|
| 397 |
+
"Bill ID": row["bill_id"],
|
| 398 |
+
"Risk Area": row["risk_area"],
|
| 399 |
+
"Channel": row["channel"],
|
| 400 |
+
"Risk Score": round(row["fraud_score"], 3),
|
| 401 |
+
"Rules Hit": len(hit_rules),
|
| 402 |
+
"Original Weight": round(orig_w, 3),
|
| 403 |
+
"Updated Weight": round(new_w, 3),
|
| 404 |
+
"Weight Δ": round(new_w - orig_w, 4),
|
| 405 |
+
"Outcome": row["inspection_outcome"],
|
| 406 |
+
})
|
| 407 |
+
return pd.DataFrame(rows)
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def compute_efficiency_metrics(df: pd.DataFrame) -> dict:
|
| 411 |
+
"""WCO Efficiency Index = Detection Rate / Selection Rate."""
|
| 412 |
+
n = len(df)
|
| 413 |
+
selected = df[df["channel"].isin(["RED", "YELLOW"])]
|
| 414 |
+
detected = df[df["inspection_outcome"] == "FRAUD_DETECTED"]
|
| 415 |
+
true_fraud = df[df["is_illicit"] == 1]
|
| 416 |
+
|
| 417 |
+
selection_rate = len(selected) / n
|
| 418 |
+
detection_rate = len(detected) / len(true_fraud) if len(true_fraud) > 0 else 0
|
| 419 |
+
precision = len(detected) / len(selected) if len(selected) > 0 else 0
|
| 420 |
+
efficiency_idx = detection_rate / selection_rate if selection_rate > 0 else 0
|
| 421 |
+
revenue_total = df["detected_revenue"].sum()
|
| 422 |
+
|
| 423 |
+
# Baseline static model metrics (from paper Table in reference)
|
| 424 |
+
baseline = {
|
| 425 |
+
"selection_rate": selection_rate,
|
| 426 |
+
"detection_rate": 0.041,
|
| 427 |
+
"precision": 0.041 / selection_rate if selection_rate > 0 else 0.04,
|
| 428 |
+
"efficiency_index": 0.41,
|
| 429 |
+
"revenue": revenue_total * 0.40,
|
| 430 |
+
}
|
| 431 |
+
hybrid = {
|
| 432 |
+
"selection_rate": selection_rate,
|
| 433 |
+
"detection_rate": round(detection_rate, 4),
|
| 434 |
+
"precision": round(precision, 4),
|
| 435 |
+
"efficiency_index": round(efficiency_idx, 3),
|
| 436 |
+
"revenue": round(revenue_total, 2),
|
| 437 |
+
}
|
| 438 |
+
return {"baseline": baseline, "hybrid": hybrid,
|
| 439 |
+
"improvement_pct": round(100 * (efficiency_idx - 0.41) / 0.41, 1)}
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
def get_default_weights() -> dict:
|
| 443 |
+
return {r["id"]: r["weight"] for a in RISK_AREAS.values() for r in a["rules"]}
|
styles.py
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
| 1 |
+
"""
|
| 2 |
+
styles.py — Global WCO colour palette, CSS injection, and shared UI helpers
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import streamlit as st
|
| 6 |
+
|
| 7 |
+
# ── WCO Colour Palette ──────────────────────────────────────────────────────
|
| 8 |
+
WCO_NAVY = "#003087"
|
| 9 |
+
WCO_BLUE = "#0066CC"
|
| 10 |
+
WCO_GOLD = "#C8A951"
|
| 11 |
+
WCO_GREEN = "#00843D"
|
| 12 |
+
WCO_RED = "#C8102E"
|
| 13 |
+
WCO_YELLOW = "#F5A800"
|
| 14 |
+
WCO_GREY_BG = "#0B1220"
|
| 15 |
+
WCO_CARD_BG = "#0F1C35"
|
| 16 |
+
WCO_BORDER = "#1E3A6E"
|
| 17 |
+
WCO_TEXT = "#D0DCF0"
|
| 18 |
+
WCO_MUTED = "#6B85AA"
|
| 19 |
+
|
| 20 |
+
CHANNEL_COLORS = {
|
| 21 |
+
"RED": WCO_RED,
|
| 22 |
+
"YELLOW": WCO_YELLOW,
|
| 23 |
+
"GREEN": WCO_GREEN,
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
RISK_COLORS = {
|
| 27 |
+
"Drugs & Narcotics": "#C8102E",
|
| 28 |
+
"Environmental/Plastic Waste": "#00843D",
|
| 29 |
+
"Revenue Leakage": "#F5A800",
|
| 30 |
+
"IPR Enforcement": "#9B59B6",
|
| 31 |
+
"Wildlife Smuggling": "#E67E22",
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def inject_global_css():
|
| 36 |
+
st.markdown(f"""
|
| 37 |
+
<style>
|
| 38 |
+
@import url('https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;600;700&family=IBM+Plex+Sans:wght@300;400;500;600&family=IBM+Plex+Mono:wght@400;500&display=swap');
|
| 39 |
+
|
| 40 |
+
/* ── Root reset ── */
|
| 41 |
+
html, body, [data-testid="stAppViewContainer"] {{
|
| 42 |
+
background-color: {WCO_GREY_BG} !important;
|
| 43 |
+
color: {WCO_TEXT} !important;
|
| 44 |
+
font-family: 'IBM Plex Sans', sans-serif;
|
| 45 |
+
}}
|
| 46 |
+
[data-testid="stSidebar"] {{
|
| 47 |
+
background-color: #070E1C !important;
|
| 48 |
+
border-right: 1px solid {WCO_BORDER};
|
| 49 |
+
}}
|
| 50 |
+
[data-testid="stSidebar"] * {{ color: {WCO_TEXT} !important; }}
|
| 51 |
+
|
| 52 |
+
/* ── Header bar ── */
|
| 53 |
+
.wco-header {{
|
| 54 |
+
background: linear-gradient(135deg, {WCO_NAVY} 0%, #001550 100%);
|
| 55 |
+
border-bottom: 3px solid {WCO_GOLD};
|
| 56 |
+
padding: 18px 28px;
|
| 57 |
+
border-radius: 12px;
|
| 58 |
+
margin-bottom: 20px;
|
| 59 |
+
display: flex;
|
| 60 |
+
align-items: center;
|
| 61 |
+
gap: 16px;
|
| 62 |
+
}}
|
| 63 |
+
.wco-header h1 {{
|
| 64 |
+
font-family: 'Playfair Display', serif;
|
| 65 |
+
color: {WCO_GOLD};
|
| 66 |
+
font-size: 26px;
|
| 67 |
+
margin: 0;
|
| 68 |
+
line-height: 1.2;
|
| 69 |
+
}}
|
| 70 |
+
.wco-header p {{
|
| 71 |
+
color: #8BAAD4;
|
| 72 |
+
font-size: 12px;
|
| 73 |
+
margin: 4px 0 0;
|
| 74 |
+
font-family: 'IBM Plex Mono', monospace;
|
| 75 |
+
letter-spacing: 0.06em;
|
| 76 |
+
}}
|
| 77 |
+
|
| 78 |
+
/* ── Cards ── */
|
| 79 |
+
.wco-card {{
|
| 80 |
+
background: {WCO_CARD_BG};
|
| 81 |
+
border: 1px solid {WCO_BORDER};
|
| 82 |
+
border-radius: 12px;
|
| 83 |
+
padding: 22px 24px;
|
| 84 |
+
margin-bottom: 16px;
|
| 85 |
+
}}
|
| 86 |
+
.wco-card-gold {{
|
| 87 |
+
background: {WCO_CARD_BG};
|
| 88 |
+
border: 1px solid {WCO_GOLD};
|
| 89 |
+
border-radius: 12px;
|
| 90 |
+
padding: 22px 24px;
|
| 91 |
+
margin-bottom: 16px;
|
| 92 |
+
}}
|
| 93 |
+
.wco-card h3 {{
|
| 94 |
+
font-family: 'Playfair Display', serif;
|
| 95 |
+
color: {WCO_GOLD};
|
| 96 |
+
font-size: 16px;
|
| 97 |
+
margin: 0 0 14px;
|
| 98 |
+
padding-bottom: 10px;
|
| 99 |
+
border-bottom: 1px solid {WCO_BORDER};
|
| 100 |
+
}}
|
| 101 |
+
|
| 102 |
+
/* ── Section title ── */
|
| 103 |
+
.section-title {{
|
| 104 |
+
font-family: 'Playfair Display', serif;
|
| 105 |
+
color: {WCO_GOLD};
|
| 106 |
+
font-size: 20px;
|
| 107 |
+
font-weight: 700;
|
| 108 |
+
margin: 8px 0 16px;
|
| 109 |
+
letter-spacing: 0.01em;
|
| 110 |
+
}}
|
| 111 |
+
|
| 112 |
+
/* ── KPI tiles ── */
|
| 113 |
+
.kpi-row {{ display: flex; gap: 12px; flex-wrap: wrap; margin-bottom: 18px; }}
|
| 114 |
+
.kpi-tile {{
|
| 115 |
+
flex: 1;
|
| 116 |
+
min-width: 140px;
|
| 117 |
+
background: {WCO_CARD_BG};
|
| 118 |
+
border: 1px solid {WCO_BORDER};
|
| 119 |
+
border-radius: 10px;
|
| 120 |
+
padding: 16px 18px;
|
| 121 |
+
text-align: center;
|
| 122 |
+
}}
|
| 123 |
+
.kpi-tile .val {{
|
| 124 |
+
font-family: 'Playfair Display', serif;
|
| 125 |
+
font-size: 32px;
|
| 126 |
+
font-weight: 700;
|
| 127 |
+
line-height: 1;
|
| 128 |
+
}}
|
| 129 |
+
.kpi-tile .lbl {{
|
| 130 |
+
font-size: 11px;
|
| 131 |
+
color: {WCO_MUTED};
|
| 132 |
+
margin-top: 6px;
|
| 133 |
+
text-transform: uppercase;
|
| 134 |
+
letter-spacing: 0.08em;
|
| 135 |
+
}}
|
| 136 |
+
|
| 137 |
+
/* ── Channel badges ── */
|
| 138 |
+
.badge-red {{ background:#3A0010; color:#FF4466; border:1px solid #C8102E; border-radius:6px; padding:3px 10px; font-size:12px; font-weight:600; }}
|
| 139 |
+
.badge-yellow {{ background:#2A1900; color:#FFD700; border:1px solid #F5A800; border-radius:6px; padding:3px 10px; font-size:12px; font-weight:600; }}
|
| 140 |
+
.badge-green {{ background:#001A09; color:#44CC88; border:1px solid #00843D; border-radius:6px; padding:3px 10px; font-size:12px; font-weight:600; }}
|
| 141 |
+
.badge-gold {{ background:#1C1400; color:{WCO_GOLD}; border:1px solid {WCO_GOLD}; border-radius:6px; padding:3px 10px; font-size:12px; font-weight:600; }}
|
| 142 |
+
|
| 143 |
+
/* ── Tables ── */
|
| 144 |
+
.wco-table {{ width:100%; border-collapse:collapse; font-size:13px; }}
|
| 145 |
+
.wco-table th {{
|
| 146 |
+
background:{WCO_NAVY};
|
| 147 |
+
color:{WCO_GOLD};
|
| 148 |
+
font-family:'Playfair Display',serif;
|
| 149 |
+
padding:10px 14px;
|
| 150 |
+
text-align:left;
|
| 151 |
+
border-bottom:2px solid {WCO_GOLD};
|
| 152 |
+
font-size:12px;
|
| 153 |
+
letter-spacing:0.05em;
|
| 154 |
+
}}
|
| 155 |
+
.wco-table td {{
|
| 156 |
+
padding:9px 14px;
|
| 157 |
+
border-bottom:1px solid {WCO_BORDER};
|
| 158 |
+
color:{WCO_TEXT};
|
| 159 |
+
vertical-align:top;
|
| 160 |
+
}}
|
| 161 |
+
.wco-table tr:hover td {{ background:rgba(0,48,135,0.25); }}
|
| 162 |
+
|
| 163 |
+
/* ── Progress bars ── */
|
| 164 |
+
.prog-bar-wrap {{ background:#111D30; border-radius:6px; height:10px; margin:4px 0; overflow:hidden; }}
|
| 165 |
+
.prog-bar-fill {{ height:100%; border-radius:6px; transition:width 0.6s ease; }}
|
| 166 |
+
|
| 167 |
+
/* ── Alerts ── */
|
| 168 |
+
.alert-gold {{
|
| 169 |
+
background:rgba(200,169,81,0.1);
|
| 170 |
+
border-left:4px solid {WCO_GOLD};
|
| 171 |
+
border-radius:0 8px 8px 0;
|
| 172 |
+
padding:12px 16px;
|
| 173 |
+
color:#D4B96A;
|
| 174 |
+
font-size:13px;
|
| 175 |
+
margin:10px 0;
|
| 176 |
+
}}
|
| 177 |
+
.alert-blue {{
|
| 178 |
+
background:rgba(0,102,204,0.1);
|
| 179 |
+
border-left:4px solid {WCO_BLUE};
|
| 180 |
+
border-radius:0 8px 8px 0;
|
| 181 |
+
padding:12px 16px;
|
| 182 |
+
color:#66AAFF;
|
| 183 |
+
font-size:13px;
|
| 184 |
+
margin:10px 0;
|
| 185 |
+
}}
|
| 186 |
+
|
| 187 |
+
/* ── Streamlit widget tweaks ── */
|
| 188 |
+
.stSlider > div > div > div {{ background:{WCO_BORDER} !important; }}
|
| 189 |
+
.stSlider [data-baseweb="slider"] [role="slider"] {{ background:{WCO_GOLD} !important; border-color:{WCO_GOLD} !important; }}
|
| 190 |
+
.stButton > button {{
|
| 191 |
+
background:linear-gradient(135deg,{WCO_NAVY},{WCO_BLUE});
|
| 192 |
+
color:{WCO_GOLD};
|
| 193 |
+
border:1px solid {WCO_GOLD};
|
| 194 |
+
border-radius:8px;
|
| 195 |
+
font-family:'IBM Plex Sans',sans-serif;
|
| 196 |
+
font-weight:600;
|
| 197 |
+
letter-spacing:0.04em;
|
| 198 |
+
padding:8px 24px;
|
| 199 |
+
transition:all 0.2s;
|
| 200 |
+
}}
|
| 201 |
+
.stButton > button:hover {{
|
| 202 |
+
background:linear-gradient(135deg,{WCO_BLUE},{WCO_NAVY});
|
| 203 |
+
border-color:#FFD700;
|
| 204 |
+
color:#FFD700;
|
| 205 |
+
transform:translateY(-1px);
|
| 206 |
+
box-shadow:0 4px 16px rgba(200,169,81,0.25);
|
| 207 |
+
}}
|
| 208 |
+
div[data-testid="stMetricValue"] {{
|
| 209 |
+
font-family:'Playfair Display',serif !important;
|
| 210 |
+
color:{WCO_GOLD} !important;
|
| 211 |
+
}}
|
| 212 |
+
[data-testid="stMetricLabel"] {{ color:{WCO_MUTED} !important; font-size:11px !important; text-transform:uppercase !important; letter-spacing:0.07em !important; }}
|
| 213 |
+
[data-testid="stExpander"] {{
|
| 214 |
+
background:{WCO_CARD_BG} !important;
|
| 215 |
+
border:1px solid {WCO_BORDER} !important;
|
| 216 |
+
border-radius:10px !important;
|
| 217 |
+
}}
|
| 218 |
+
div[data-testid="stDataFrame"] {{ border-radius:10px; overflow:hidden; }}
|
| 219 |
+
.stTabs [data-baseweb="tab-list"] {{ background:{WCO_CARD_BG}; border-radius:10px 10px 0 0; }}
|
| 220 |
+
.stTabs [data-baseweb="tab"] {{ color:{WCO_MUTED}; font-family:'IBM Plex Sans',sans-serif; }}
|
| 221 |
+
.stTabs [aria-selected="true"] {{ color:{WCO_GOLD} !important; border-bottom:2px solid {WCO_GOLD} !important; }}
|
| 222 |
+
hr {{ border-color:{WCO_BORDER} !important; }}
|
| 223 |
+
</style>
|
| 224 |
+
""", unsafe_allow_html=True)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def page_header(icon: str, title: str, subtitle: str):
|
| 228 |
+
st.markdown(f"""
|
| 229 |
+
<div class="wco-header">
|
| 230 |
+
<div style="font-size:40px">{icon}</div>
|
| 231 |
+
<div>
|
| 232 |
+
<h1>{title}</h1>
|
| 233 |
+
<p>{subtitle}</p>
|
| 234 |
+
</div>
|
| 235 |
+
<div style="margin-left:auto;text-align:right;">
|
| 236 |
+
<div style="color:#C8A951;font-family:'IBM Plex Mono',monospace;font-size:11px;">🌐 WCO ACCREDITED</div>
|
| 237 |
+
<div style="color:#6B85AA;font-size:10px;margin-top:2px;">No-CelH Self-Learning RMS v2.0</div>
|
| 238 |
+
</div>
|
| 239 |
+
</div>
|
| 240 |
+
""", unsafe_allow_html=True)
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def metric_row(metrics: list):
|
| 244 |
+
"""metrics = [(value, label, color), ...]"""
|
| 245 |
+
cols_html = ""
|
| 246 |
+
for val, lbl, col in metrics:
|
| 247 |
+
cols_html += f"""
|
| 248 |
+
<div class="kpi-tile">
|
| 249 |
+
<div class="val" style="color:{col}">{val}</div>
|
| 250 |
+
<div class="lbl">{lbl}</div>
|
| 251 |
+
</div>"""
|
| 252 |
+
st.markdown(f'<div class="kpi-row">{cols_html}</div>', unsafe_allow_html=True)
|