Update app.py
Browse files4 unmodified lines5678910115 unmodified lines1718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384853 unmodified lines89909192939415 unmodified lines11011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330412 unmodified lines3173183193203213223233243253263273283293303313323333343353363373383393403413423433444 unmodified lines# ─── Page config ──────────────────────────────────────────────────────────────st.set_page_config(page_title="Fraud Detection — Bank Monitor",page_icon="🏛️",layout="wide",initial_sidebar_state="expanded",5 unmodified lines/* App Background & Base Typography */.stApp { background-color: #f8fafc; }/* Control Panel Bar */.control-bar {background: #ffffff;padding: 12px 20px;border-radius: 12px;border: 1px solid #e2e8f0;margin-bottom: 16px;box-shadow: 0 1px 3px rgba(0,0,0,0.05);}/* Feed card base (Bank Style) */.tx-card {padding: 12px 16px;border-radius: 8px;border: 1px solid #e2e8f0;margin-bottom: 8px;background: #ffffff;font-size: 13px;transition: all 0.2s;}.tx-card:hover { transform: translateY(-1px); box-shadow: 0 2px 4px rgba(0,0,0,0.05); }.tx-card.fraud { border-left: 4px solid #dc2626; background: #fef2f2; }.tx-card.alert { border-left: 4px solid #d97706; background: #fffbeb; }.tx-card.rule1 { border-left: 4px solid #7c3aed; background: #f5f3ff; }.tx-card.pass { border-left: 4px solid #16a34a; background: #f0fdf4; }/* Badges */.badge {display: inline-block;font-size: 11px;font-weight: 600;padding: 2px 8px;border-radius: 4px;margin-right: 6px;}.badge-block { background:#dc2626; color:#fff; }.badge-alert { background:#d97706; color:#fff; }.badge-rule1 { background:#7c3aed; color:#fff; }.badge-pass { background:#16a34a; color:#fff; }.score-row { font-size: 11px; color: #475569; margin-top: 6px; border-top: 1px dashed #e2e8f0; padding-top: 4px; }.tx-meta { font-size: 11px; color: #64748b; margin-top: 4px; }/* Alert Card */.alert-card {padding: 12px;border-radius: 8px;border: 1px solid;margin-bottom: 8px;font-size: 12px;animation: pulse 2s infinite;}.alert-card.block { border-color:#fca5a5; background:#fff5f5; }.alert-card.otp { border-color:#fde047; background:#fffbeb; }.alert-card.rule { border-color:#c084fc; background:#f5f3ff; }/* GitHub Custom Card */.github-card {background: #0f172a;color: #ffffff;padding: 14px;border-radius: 8px;margin-top: 20px;border: 1px solid #1e293b;}.github-card a {3 unmodified linesdisplay: flex;align-items: center;gap: 8px;}.github-card a:hover { text-decoration: underline; }</style>15 unmodified lines_init()# ─── Sidebar (Settings Only) ──────────────────────────────────────────────────with st.sidebar:st.markdown("### 🏛️ Simulation Settings")st.caption("Configure environment parameters before starting.")st.divider()speed = st.slider("Transmission Speed (sec/tx)", 0.3, 3.0, 1.0, 0.1)fraud_pct = st.slider("High-Risk Target Ratio (%)", 5, 40, 12, 1)n_accs = st.slider("Monitored Accounts", 3, 8, 5, 1)st.divider()st.markdown("**System Thresholds**")st.markdown("🔴 **Critical Block** `≥ 0.80` \n🟡 **Challenge OTP** `≥ 0.50` \n🟢 **Auto Pass** `< 0.50`")# Push GitHub to the absolute bottom of sidebarst.markdown("""<div class="github-card"><p style="margin:0 0 8px 0; font-size:12px; color:#94a3b8;">Want to learn more?</p><a href="https://github.com/PlamGG/Fraud-Detection-Multi-Model-" target="_blank"><svg height="20" width="20" viewBox="0 0 16 16" fill="currentColor" style="color:white;"><path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"></path></svg>Read Technical Docs</a></div>""", unsafe_allow_html=True)# ─── Main Header & Compact Control Panel ──────────────────────────────────────title_col, ctrl_col = st.columns([2, 1], gap="small")with title_col:st.markdown("## 🏛️ Fraud Analytics — Multi-Model Engine")status_color = "green" if st.session_state.running else "orange"status_txt = "Active Monitoring" if st.session_state.running else "System Paused"st.markdown(f"<span style='color:{status_color}; font-weight:600;'>● {status_txt}</span> · Core v2026 · Ensemble Pipeline", unsafe_allow_html=True)with ctrl_col:# Compact horizontal buttons right next to the titlest.markdown("<div style='padding-top: 15px;'></div>", unsafe_allow_html=True)c1, c2, c3 = st.columns(3)start_btn = c1.button("▶ Start", use_container_width=True, type="primary")stop_btn = c2.button("⏹ Stop", use_container_width=True)reset_btn = c3.button("↺ Reset", use_container_width=True)if start_btn:seed = random.randint(0, 99999)st.session_state.accounts = generate_accounts(n=n_accs, seed=seed)st.session_state.running = Truest.session_state.feed = []st.session_state.alerts = []st.session_state.step = 1st.session_state.tx_counter = 1st.session_state.total_tx = 0st.session_state.total_block = 0st.session_state.total_alert = 0st.session_state.total_pass = 0st.session_state.amount_risk = 0.0st.rerun()if stop_btn:st.session_state.running = Falsest.rerun()if reset_btn:for k in ["running","accounts","feed","alerts","step","tx_counter","total_tx","total_block","total_alert","total_pass","amount_risk"]:st.session_state.pop(k, None)_init()st.rerun()st.divider()# ─── Split Row: Financial Metrics (65%) & Target Watchlist (35%) ─────────────metric_col, watchlist_col = st.columns([65, 35], gap="medium")with metric_col:m1, m2, m3, m4 = st.columns(4)m1.metric("Total Processed", f"{st.session_state.total_tx} tx")m2.metric("Critical Blocked", st.session_state.total_block)m3.metric("OTP Challenged", st.session_state.total_alert)m4.metric("Risk Exposure", f"฿{st.session_state.amount_risk:,.0f}")with watchlist_col:st.markdown("<p style='font-size:12px; font-weight:600; color:#64748b; margin:0 0 4px 0;'>🎯 High-Risk Watchlist</p>", unsafe_allow_html=True)if st.session_state.accounts:acc_html = "<div style='display:flex; flex-wrap:wrap; gap:6px;'>"for acc in st.session_state.accounts:icon = {"normal": "🟢", "alert": "🟡", "blocked": "🔴"}.get(acc["status"], "⚪")color = {"low": "#e2e8f0", "medium": "#fef3c7", "high": "#fee2e2"}.get(acc["risk_level"], "#e2e8f0")border = {"low": "#cbd5e1", "medium": "#fcd34d", "high": "#fca5a5"}.get(acc["risk_level"], "#cbd5e1")acc_html += f"<span style='background:{color}; border:1px solid {border}; padding:2px 6px; border-radius:4px; font-size:11px; font-family:monospace;'>{icon} {acc['account_id']}</span>"acc_html += "</div>"st.markdown(acc_html, unsafe_allow_html=True)else:st.caption("No accounts initialized. Press Start.")st.markdown("<br>", unsafe_allow_html=True)# ─── Render Helpers ───────────────────────────────────────────────────────────def _decision_class(tx: dict) -> str:d = tx["decision"]if "Rule" in d: return "rule1"if "Block" in d: return "fraud"if "Alert" in d: return "alert"return "pass"def _badge(tx: dict) -> str:d = tx["decision"]if "Rule" in d: return '<span class="badge badge-rule1">RULE BLOCK</span>'if "Block" in d: return '<span class="badge badge-block">ML BLOCK</span>'if "Alert" in d: return '<span class="badge badge-alert">CHALLENGE OTP</span>'return '<span class="badge badge-pass">PASSED</span>'def render_feed(feed: list):html = ""for tx in feed[:40]:cls = _decision_class(tx)badge = _badge(tx)score_color = "#dc2626" if tx["final_score"] >= 0.8 else "#d97706" if tx["final_score"] >= 0.5 else "#16a34a"flags = [f for f, active in [("Accessibility+Remote", tx["rule1"]), ("Hesitation+NewRecipient", tx["rule2"])] if active]flag_txt = " · ".join(flags) if flags else "No Rules Triggered"html += f"""<div class="tx-card {cls}"><div style="display:flex;justify-content:space-between;align-items:center"><div>{badge} <strong style="font-family:monospace;">{tx['tx_id']}</strong></div><div style="font-weight:700; font-size:14px; color:#1e293b;">฿ {tx['amount']:,.0f}</div></div><div class="tx-meta">Origin: <code style="background:#f1f5f9;padding:2px 4px;border-radius:3px;">{tx['account_id']}</code> → Destination: <code style="background:#f1f5f9;padding:2px 4px;border-radius:3px;">{tx['dest_id']}</code> · Step {tx['step']}</div><div class="score-row">Model A (Behavior): <b>{tx['prob_a']:.2f}</b> |Model B (Receiver): <b>{tx['prob_b']:.2f}</b> |Ensemble Score: <b style="color:{score_color}">{tx['final_score']:.2f}</b><span style="float:right; color:#64748b;">⚠️ {flag_txt}</span></div></div>"""return htmldef render_alerts(alerts: list):html = ""for tx in alerts[:25]:d = tx["decision"]if "Rule" in d:cls, label = "rule", "Rule 1 — Hard Block"detail = "Accessibility Service + Remote Access active. Aborted before ML."elif "Block" in d:cls, label = "block", "Ensemble Block"detail = f"Score {tx['final_score']:.2f} ≥ 0.80 [A:{tx['prob_a']:.2f} · B:{tx['prob_b']:.2f}]."else:cls, label = "otp", "OTP Challenge Triggered"detail = f"Score {tx['final_score']:.2f} ≥ 0.50. Transaction held for verification."html += f"""<div class="alert-card {cls}"><div style="display:flex;align-items:center;gap:6px;margin-bottom:6px"><span class="badge badge-{'rule1' if cls=='rule' else cls}">{label.upper()}</span><strong style="font-family:monospace;">{tx['tx_id']}</strong></div><div style="font-size:11px;color:#334155;font-weight:500;">{detail}</div><div style="font-size:10px;color:#64748b;margin-top:6px;background:rgba(255,255,255,0.5);padding:3px 6px;border-radius:4px;">Account: {tx['account_id']} · Value: ฿{tx['amount']:,.0f} · {tx['layer']}</div></div>"""return html# ─── TWO-COLUMN FIXED HEIGHT CONTAINERS ──────────────────────────────────────feed_col, alert_col = st.columns([3, 2], gap="medium")# Simulation Loop & Renderingif st.session_state.running and st.session_state.accounts:# 1. Create Fixed-Height Containers that auto-scroll internallywith feed_col:st.markdown("#### ⏱️ Real-Time Transaction Feed")st.caption("All processed traffic · Newest on top")feed_placeholder = st.container(height=520) # <-- ล็อคความสูงหน้าจอที่นี่with alert_col:st.markdown(f"#### 🚨 Incident Alerts Queue ({len(st.session_state.alerts)})")st.caption("High-risk anomalies requiring intervention")alert_placeholder = st.container(height=520) # <-- ล็อคความสูงหน้าจอที่นี่# 2. Run simulation loopwhile st.session_state.running:account = random.choice(st.session_state.accounts)raw_tx = generate_transaction(account, step=st.session_state.step, tx_counter=st.session_state.tx_counter)tx = score_transaction(raw_tx)d = tx["decision"]if "Block" in d: account["status"] = "blocked"elif "Alert" in d: account["status"] = "alert"st.session_state.feed = [tx] + st.session_state.feedst.session_state.total_tx += 1st.session_state.tx_counter += 112 unmodified linesif st.session_state.tx_counter % 6 == 0:st.session_state.step += 1# Render dynamically inside the locked height boxesfeed_placeholder.markdown(render_feed(st.session_state.feed), unsafe_allow_html=True)if st.session_state.alerts:alert_placeholder.markdown(render_alerts(st.session_state.alerts), unsafe_allow_html=True)else:alert_placeholder.info("Monitoring active. No anomalies detected yet.")time.sleep(speed)else:# Static render when simulation is not runningwith feed_col:st.markdown("#### ⏱️ Real-Time Transaction Feed")with st.container(height=520):if st.session_state.feed:st.markdown(render_feed(st.session_state.feed), unsafe_allow_html=True)else:st.info("System Ready. Click **▶ Start** to initiate live monitoring feed.")with alert_col:st.markdown(f"#### 🚨 Incident Alerts Queue ({len(st.session_state.alerts)})")with st.container(height=520):if st.session_state.alerts:st.markdown(render_alerts(st.session_state.alerts), unsafe_allow_html=True)else:st.info("No active alerts. Operational status normal.")4 unmodified lines5678910115 unmodified lines17181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465663 unmodified lines7071727374757615 unmodified lines929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122212 unmodified lines2352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083094 unmodified lines# ─── Page config ──────────────────────────────────────────────────────────────st.set_page_config(page_title="Fraud Analytics — Enterprise Monitor",page_icon="🏛️",layout="wide",initial_sidebar_state="expanded",5 unmodified lines/* App Background & Base Typography */.stApp { background-color: #f8fafc; }/* Custom Table Design for Bank Grid */.bank-table {width: 100%;border-collapse: collapse;font-size: 12px;font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;background: white;}.bank-table th {background-color: #f1f5f9;color: #475569;text-align: left;padding: 8px 10px;border-bottom: 2px solid #cbd5e1;font-weight: 600;}.bank-table td {padding: 6px 10px;border-bottom: 1px solid #e2e8f0;color: #334155;vertical-align: middle;}.bank-table tr:hover { background-color: #f8fafc; }/* Decision Styles */.text-pass { color: #16a34a; font-weight: 600; }.text-alert { color: #d97706; font-weight: 600; }.text-block { color: #dc2626; font-weight: 600; }/* Badge for Table inside Streamlit */.status-badge {padding: 2px 6px;border-radius: 4px;font-size: 11px;font-weight: 500;}/* GitHub Card Sticked to Sidebar Bottom */.github-card {background: #0f172a;color: #ffffff;padding: 14px;border-radius: 8px;margin-top: 50px;border: 1px solid #1e293b;}.github-card a {3 unmodified linesdisplay: flex;align-items: center;gap: 8px;font-size: 13px;}.github-card a:hover { text-decoration: underline; }</style>15 unmodified lines_init()# ─── Sidebar (Configuration & Hidden Controls) ────────────────────────────────with st.sidebar:st.markdown("### ⚙️ Engine Settings")st.caption("Adjust variables for the transaction generator.")st.divider()speed = st.slider("Generator Delay (seconds)", 0.3, 3.0, 1.0, 0.1)fraud_pct = st.slider("Mule Account Ratio (%)", 5, 40, 12, 1)n_accs = st.slider("Accounts Network Size", 3, 8, 5, 1)st.divider()st.markdown("**System Actions**")reset_btn = st.button("↺ Reset Simulation Data", use_container_width=True)if reset_btn:for k in ["running","accounts","feed","alerts","step","tx_counter","total_tx","total_block","total_alert","total_pass","amount_risk"]:st.session_state.pop(k, None)_init()st.rerun()# 📌 ส่วนลิงก์ GitHub อยู่ด้านล่างสุดของ Sidebar ตรงนี้เลยครับ เด่นและเป็นระเบียบst.markdown("""<div class="github-card"><p style="margin:0 0 6px 0; font-size:11px; color:#94a3b8;">Want to learn more?</p><a href="https://github.com/PlamGG/Fraud-Detection-Multi-Model-" target="_blank"><svg height="18" width="18" viewBox="0 0 16 16" fill="currentColor" style="color:white;"><path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"></path></svg>Read Technical Docs</a></div>""", unsafe_allow_html=True)# ─── Main Header & Dynamic Bank Controls ──────────────────────────────────────title_col, ctrl_col = st.columns([2, 1])with title_col:st.markdown("## 🏛️ Fraud Operations — Live Matrix Dashboard")status_txt = "🟢 MONITORING ACTIVE" if st.session_state.running else "⏸️ MONITORING PAUSED"st.caption(f"{status_txt} · Model Ensemble Framework A × B · Threshold Rules Enabled")with ctrl_col:st.markdown("<div style='padding-top: 12px;'></div>", unsafe_allow_html=True)c1, c2 = st.columns(2)# ปุ่มควบคุมแบบ Resume และ Pause ไม่ล้างข้อมูลตัวแปรเดิมstart_btn = c1.button("▶ Start / Resume", use_container_width=True, type="primary", disabled=st.session_state.running)pause_btn = c2.button("⏸ Pause", use_container_width=True, disabled=not st.session_state.running)if start_btn:if not st.session_state.accounts: # Initialize accounts only if emptyseed = random.randint(0, 99999)st.session_state.accounts = generate_accounts(n=n_accs, seed=seed)st.session_state.running = Truest.rerun()if pause_btn:st.session_state.running = Falsest.rerun()st.divider()# ─── Top Split Grid: Financial Metrics & Accounts Grid ────────────────────────metric_col, watchlist_col = st.columns([6, 4], gap="medium")with metric_col:m1, m2, m3, m4 = st.columns(4)m1.metric("Processed Transactions", f"{st.session_state.total_tx} tx")m2.metric("Critical Blocked", st.session_state.total_block)m3.metric("OTP Challenges", st.session_state.total_alert)m4.metric("Funds at Risk Exposure", f"฿{st.session_state.amount_risk:,.0f}")with watchlist_col:st.markdown("<p style='font-size:12px; font-weight:600; color:#475569; margin:0 0 6px 0;'>🎯 Account Audit Matrix</p>", unsafe_allow_html=True)if st.session_state.accounts:# แสดงรายชื่อบัญชีเป็นตารางแถวเล็กๆ สไตล์ Excel ไม่อึดอัดacc_table = """<table class="bank-table"><tr><th>Account ID</th><th>Baseline Risk</th><th>Operational Status</th></tr>"""for acc in st.session_state.accounts:icon, status_color = {"normal": ("🟢 Normal", "background:#dcfce7;color:#16a34a"),"alert": ("🟡 Warning", "background:#fef3c7;color:#d97706"),"blocked": ("🔴 Blocked", "background:#fee2e2;color:#dc2626")}.get(acc["status"], ("⚪ Unknown", ""))risk_badge = f"🔥 {acc['risk_level'].upper()}" if acc['risk_level'] == 'high' else acc['risk_level'].upper()acc_table += f"""<tr><td><code style='font-size:11px;'>{acc['account_id']}</code></td><td>{risk_badge}</td><td><span class="status-badge" style="{status_color}">{icon}</span></td></tr>"""acc_table += "</table>"st.markdown(acc_table, unsafe_allow_html=True)else:st.caption("No accounts mapped. Click 'Start / Resume' to link core systems.")st.markdown("<br>", unsafe_allow_html=True)# ─── Bottom Split Grid: Fixed-Height Containers ───────────────────────────────feed_col, alert_col = st.columns([55, 45], gap="medium")# 📊 ตาราง Live Feed ทราฟฟิกทั้งหมด (ซ้าย)with feed_col:st.markdown("#### ⏱️ Real-Time Transaction Ledger")st.caption("Global financial traffic logging (showing last 40 operations)")feed_box = st.container(height=480) # ล็อคความสูงหน้าจอ# 🚨 ตารางสืบสวนเคสอันตราย (ขวา)with alert_col:st.markdown("#### 🚨 Security Incident Alerts Queue")st.caption("Decisions requiring compliance review or automated intercept")alert_box = st.container(height=480) # ล็อคความสูงหน้าจอ# ─── Simulation Core Loop & Rendering Logic ──────────────────────────────────if st.session_state.running and st.session_state.accounts:while st.session_state.running:# Pick account & process transactionaccount = random.choice(st.session_state.accounts)raw_tx = generate_transaction(account, step=st.session_state.step, tx_counter=st.session_state.tx_counter)tx = score_transaction(raw_tx)# Handle status state mutationsd = tx["decision"]if "Block" in d: account["status"] = "blocked"elif "Alert" in d: account["status"] = "alert"# Prepend ledger matrixst.session_state.feed = [tx] + st.session_state.feedst.session_state.total_tx += 1st.session_state.tx_counter += 112 unmodified linesif st.session_state.tx_counter % 6 == 0:st.session_state.step += 1# 1. Render Left Column: Main Excel Tablewith feed_box:html_table = """<table class="bank-table"><tr><th>Tx ID</th><th>Routing Sequence</th><th>Amount</th><th>Ensemble Score</th><th>Action</th></tr>"""for f_tx in st.session_state.feed[:40]:style_cls = "text-block" if "Block" in f_tx["decision"] else "text-alert" if "Alert" in f_tx["decision"] else "text-pass"html_table += f"""<tr><td><strong>{f_tx['tx_id']}</strong></td><td><code>{f_tx['account_id']}</code> ➔ <code>{f_tx['dest_id']}</code> (S{f_tx['step']})</td><td><b>฿{f_tx['amount']:,.0f}</b></td><td><code>{f_tx['final_score']:.2f}</code></td><td class="{style_cls}">{f_tx['decision'].upper()}</td></tr>"""html_table += "</table>"st.markdown(html_table, unsafe_allow_html=True)# 2. Render Right Column: Alerts Queue with Expander Detail Lookupwith alert_box:if st.session_state.alerts:for a_tx in st.session_state.alerts[:20]:title_text = f"🚨 {a_tx['tx_id']} | ฿{a_tx['amount']:,.0f} ➔ {a_tx['decision'].upper()}"# ใช้ st.expander เพื่อให้เจ้าหน้าที่คลิกดูหลักฐานเชิงลึกของ AI ได้ ไม่รกสายตาwith st.expander(title_text):st.markdown(f"""**Incident Deep-Dive Metrics:*** **Source Account:** `{a_tx['account_id']}`* **Destination Target:** `{a_tx['dest_id']}`* **Model A Probability (Behavior Engine):** `{a_tx['prob_a']:.3f}`* **Model B Probability (Counterparty Network):** `{a_tx['prob_b']:.3f}`* **Weighted Ensemble Score:** `{a_tx['final_score']:.3f}`* **Pipeline Detection Layer:** `{a_tx['layer']}`* **Hard Rules Active:** `Rule 1 (Remote Access): {a_tx['rule1']}` | `Rule 2 (Hesitation Pattern): {a_tx['rule2']}`""")else:st.success("🟢 OPERATIONAL STATUS: SECURED — No anomalies flagged by models currently.")time.sleep(speed)else:# Static render loop when user presses PAUSEwith feed_box:if st.session_state.feed:html_table = """<table class="bank-table"><tr><th>Tx ID</th><th>Routing Sequence</th><th>Amount</th><th>Ensemble Score</th><th>Action</th></tr>"""for f_tx in st.session_state.feed[:40]:style_cls = "text-block" if "Block" in f_tx["decision"] else "text-alert" if "Alert" in f_tx["decision"] else "text-pass"html_table += f"""<tr><td><strong>{f_tx['tx_id']}</strong></td><td><code>{f_tx['account_id']}</code> ➔ <code>{f_tx['dest_id']}</code> (S{f_tx['step']})</td><td><b>฿{f_tx['amount']:,.0f}</b></td><td><code>{f_tx['final_score']:.2f}</code></td><td class="{style_cls}">{f_tx['decision'].upper()}</td></tr>"""html_table += "</table>"st.markdown(html_table, unsafe_allow_html=True)else:st.info("System Ready. Click **▶ Start / Resume** to map ledger feeds.")with alert_box:if st.session_state.alerts:for a_tx in st.session_state.alerts[:20]:title_text = f"🚨 {a_tx['tx_id']} | ฿{a_tx['amount']:,.0f} ➔ {a_tx['decision'].upper()}"with st.expander(title_text):st.markdown(f"""**Incident Deep-Dive Metrics:*** **Source Account:** `{a_tx['account_id']}`* **Destination Target:** `{a_tx['dest_id']}`* **Model A Probability:** `{a_tx['prob_a']:.3f}`* **Model B Probability:** `{a_tx['prob_b']:.3f}`* **Weighted Ensemble Score:** `{a_tx['final_score']:.3f}`""")else:st.success("🟢 OPERATIONAL STATUS: SECURED — No anomalies flagged by models currently.")
app.py+179-214