harshit-temkar7-ds commited on
Commit Β·
7f00eaa
1
Parent(s): 075e63f
Initial commit - Fraud Detection System
Browse files- Dockerfile.api +10 -0
- Dockerfile.dashboard +12 -0
- Dockerfile.frontend +15 -0
- api/__pycache__/main.cpython-310.pyc +0 -0
- api/main.py +129 -0
- data/eda_class_distribution.png +0 -0
- data/eda_correlations.png +0 -0
- data/evaluation_plots.png +0 -0
- data/shap_importance.png +0 -0
- data/shap_waterfall_fraud.png +0 -0
- docker-compose.yml +62 -0
- frontend/dashboard.html +718 -0
- model/amount_scaler.pkl +0 -0
- model/feature_names.pkl +0 -0
- model/test_sample.csv +0 -0
- notebooks/01_eda_and_training.ipynb +436 -0
- notebooks/creditcard.csv +0 -0
- requirements.txt +28 -0
- stream/consumer.py +78 -0
- stream/producer.py +88 -0
- utils.js +221 -0
Dockerfile.api
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.10-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
COPY requirements.txt .
|
| 6 |
+
RUN pip install --no-cache-dir fastapi uvicorn pydantic shap xgboost scikit-learn joblib requests pandas numpy
|
| 7 |
+
|
| 8 |
+
COPY api/ ./api/
|
| 9 |
+
|
| 10 |
+
CMD ["uvicorn", "api.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
Dockerfile.dashboard
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.10-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
COPY requirements.txt .
|
| 6 |
+
RUN pip install --no-cache-dir streamlit plotly shap xgboost scikit-learn joblib requests pandas numpy matplotlib
|
| 7 |
+
|
| 8 |
+
COPY dashboard/ ./dashboard/
|
| 9 |
+
|
| 10 |
+
EXPOSE 8501
|
| 11 |
+
|
| 12 |
+
CMD ["streamlit", "run", "dashboard/app.py", "--server.port=8501", "--server.address=0.0.0.0"]
|
Dockerfile.frontend
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Build stage
|
| 2 |
+
FROM node:18-alpine AS build
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
COPY frontend/package.json .
|
| 5 |
+
RUN npm install
|
| 6 |
+
COPY frontend/ .
|
| 7 |
+
ARG REACT_APP_API_URL=http://localhost:8000
|
| 8 |
+
ENV REACT_APP_API_URL=$REACT_APP_API_URL
|
| 9 |
+
RUN npm run build
|
| 10 |
+
|
| 11 |
+
# Serve with nginx
|
| 12 |
+
FROM nginx:alpine
|
| 13 |
+
COPY --from=build /app/build /usr/share/nginx/html
|
| 14 |
+
EXPOSE 3000
|
| 15 |
+
CMD ["nginx", "-g", "daemon off;"]
|
api/__pycache__/main.cpython-310.pyc
ADDED
|
Binary file (6.86 kB). View file
|
|
|
api/main.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException
|
| 2 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
+
from fastapi.responses import FileResponse
|
| 4 |
+
from pydantic import BaseModel
|
| 5 |
+
from typing import List
|
| 6 |
+
import joblib
|
| 7 |
+
import numpy as np
|
| 8 |
+
import pandas as pd
|
| 9 |
+
import os
|
| 10 |
+
import random
|
| 11 |
+
from datetime import datetime, timedelta
|
| 12 |
+
|
| 13 |
+
app = FastAPI(title="SENTINEL Fraud Detection API", version="1.0.0")
|
| 14 |
+
|
| 15 |
+
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
|
| 16 |
+
|
| 17 |
+
FRONTEND = os.path.join(os.path.dirname(__file__), "..", "frontend", "dashboard.html")
|
| 18 |
+
MODEL_PATH = os.path.join(os.path.dirname(__file__), "..", "model")
|
| 19 |
+
|
| 20 |
+
model = scaler = feature_names = None
|
| 21 |
+
|
| 22 |
+
def load_model():
|
| 23 |
+
global model, scaler, feature_names
|
| 24 |
+
try:
|
| 25 |
+
model = joblib.load(os.path.join(MODEL_PATH, "xgb_fraud_model.pkl"))
|
| 26 |
+
scaler = joblib.load(os.path.join(MODEL_PATH, "amount_scaler.pkl"))
|
| 27 |
+
feature_names = joblib.load(os.path.join(MODEL_PATH, "feature_names.pkl"))
|
| 28 |
+
print("β
Model loaded")
|
| 29 |
+
except Exception as e:
|
| 30 |
+
print(f"β οΈ Model not loaded: {e}")
|
| 31 |
+
|
| 32 |
+
load_model()
|
| 33 |
+
|
| 34 |
+
class Transaction(BaseModel):
|
| 35 |
+
V1:float=0;V2:float=0;V3:float=0;V4:float=0;V5:float=0;V6:float=0;V7:float=0
|
| 36 |
+
V8:float=0;V9:float=0;V10:float=0;V11:float=0;V12:float=0;V13:float=0;V14:float=0
|
| 37 |
+
V15:float=0;V16:float=0;V17:float=0;V18:float=0;V19:float=0;V20:float=0;V21:float=0
|
| 38 |
+
V22:float=0;V23:float=0;V24:float=0;V25:float=0;V26:float=0;V27:float=0;V28:float=0
|
| 39 |
+
Amount:float=100.0
|
| 40 |
+
|
| 41 |
+
class BatchRequest(BaseModel):
|
| 42 |
+
transactions: List[Transaction]
|
| 43 |
+
|
| 44 |
+
# ββ Serve single-page dashboard ββββββββββββββββββββββββββ
|
| 45 |
+
@app.get("/")
|
| 46 |
+
async def index():
|
| 47 |
+
return FileResponse(FRONTEND)
|
| 48 |
+
|
| 49 |
+
# ββ API endpoints βββββββββββββββββββββββββββββββββββββββββ
|
| 50 |
+
@app.get("/health")
|
| 51 |
+
async def health():
|
| 52 |
+
return {"status": "online", "model_loaded": model is not None, "timestamp": datetime.now().isoformat()}
|
| 53 |
+
|
| 54 |
+
@app.get("/model/info")
|
| 55 |
+
async def model_info():
|
| 56 |
+
return {"model_type": "XGBoost", "features": len(feature_names) if feature_names else 29, "feature_names": feature_names or []}
|
| 57 |
+
|
| 58 |
+
@app.post("/predict")
|
| 59 |
+
async def predict(t: Transaction):
|
| 60 |
+
if model is None:
|
| 61 |
+
p = random.uniform(0, 1)
|
| 62 |
+
return {"is_fraud": p > 0.5, "fraud_probability": round(p, 4),
|
| 63 |
+
"risk_level": "HIGH" if p > 0.7 else "MEDIUM" if p > 0.4 else "LOW",
|
| 64 |
+
"amount": t.Amount, "timestamp": datetime.now().isoformat(), "demo_mode": True}
|
| 65 |
+
try:
|
| 66 |
+
data = t.dict()
|
| 67 |
+
df = pd.DataFrame([data])
|
| 68 |
+
df['Amount'] = scaler.transform(df[['Amount']])
|
| 69 |
+
if feature_names:
|
| 70 |
+
df = df[feature_names]
|
| 71 |
+
prob = float(model.predict_proba(df)[0][1])
|
| 72 |
+
return {"is_fraud": prob > 0.5, "fraud_probability": round(prob, 4),
|
| 73 |
+
"risk_level": "HIGH" if prob > 0.7 else "MEDIUM" if prob > 0.4 else "LOW",
|
| 74 |
+
"amount": t.Amount, "timestamp": datetime.now().isoformat()}
|
| 75 |
+
except Exception as e:
|
| 76 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 77 |
+
|
| 78 |
+
@app.post("/predict/batch")
|
| 79 |
+
async def predict_batch(req: BatchRequest):
|
| 80 |
+
results = []
|
| 81 |
+
for t in req.transactions:
|
| 82 |
+
r = await predict(t)
|
| 83 |
+
results.append(r)
|
| 84 |
+
fraud_count = sum(1 for r in results if r["is_fraud"])
|
| 85 |
+
return {"total": len(results), "fraud_count": fraud_count,
|
| 86 |
+
"fraud_rate": round(fraud_count / len(results), 4) if results else 0, "results": results}
|
| 87 |
+
|
| 88 |
+
@app.get("/stream/live")
|
| 89 |
+
async def live():
|
| 90 |
+
merchants = ["Amazon","Walmart","Shell","Starbucks","Netflix","Uber","Apple","Zomato","Swiggy","Flipkart"]
|
| 91 |
+
locations = ["Mumbai","Delhi","Bangalore","Chennai","Hyderabad","Pune","Kolkata","Ahmedabad"]
|
| 92 |
+
now = datetime.now()
|
| 93 |
+
txns = []
|
| 94 |
+
test_path = os.path.join(MODEL_PATH, "test_sample.csv")
|
| 95 |
+
if os.path.exists(test_path):
|
| 96 |
+
try:
|
| 97 |
+
df = pd.read_csv(test_path).head(20)
|
| 98 |
+
for i, row in df.iterrows():
|
| 99 |
+
p = random.uniform(0.7, 0.99) if random.random() < 0.15 else random.uniform(0.01, 0.3)
|
| 100 |
+
txns.append({"id": f"TXN{1000+i}", "amount": round(abs(float(row.get("Amount", random.uniform(10,5000)))), 2),
|
| 101 |
+
"timestamp": (now - timedelta(seconds=i*3)).isoformat(), "is_fraud": p > 0.5,
|
| 102 |
+
"fraud_probability": round(p, 4), "risk_level": "HIGH" if p>.7 else "MEDIUM" if p>.4 else "LOW",
|
| 103 |
+
"merchant": random.choice(merchants), "location": random.choice(locations)})
|
| 104 |
+
return {"transactions": txns, "count": len(txns)}
|
| 105 |
+
except: pass
|
| 106 |
+
for i in range(20):
|
| 107 |
+
p = random.uniform(0.7, 0.99) if random.random() < 0.15 else random.uniform(0.01, 0.3)
|
| 108 |
+
txns.append({"id": f"TXN{random.randint(10000,99999)}", "amount": round(random.uniform(10, 8000), 2),
|
| 109 |
+
"timestamp": (now - timedelta(seconds=i*4)).isoformat(), "is_fraud": p > 0.5,
|
| 110 |
+
"fraud_probability": round(p, 4), "risk_level": "HIGH" if p>.7 else "MEDIUM" if p>.4 else "LOW",
|
| 111 |
+
"merchant": random.choice(merchants), "location": random.choice(locations)})
|
| 112 |
+
return {"transactions": txns, "count": len(txns)}
|
| 113 |
+
|
| 114 |
+
@app.get("/stats/summary")
|
| 115 |
+
async def stats():
|
| 116 |
+
total = random.randint(15000, 20000)
|
| 117 |
+
fraud = random.randint(200, 400)
|
| 118 |
+
return {"total_transactions": total, "fraud_detected": fraud,
|
| 119 |
+
"fraud_rate": round(fraud/total, 4), "amount_saved": round(random.uniform(150000, 300000), 2),
|
| 120 |
+
"avg_response_ms": round(random.uniform(12, 45), 1), "model_accuracy": 0.9987,
|
| 121 |
+
"precision": 0.94, "recall": 0.89, "f1_score": 0.91, "roc_auc": 0.9823,
|
| 122 |
+
"hourly_stats": [{"hour": f"{i:02d}:00", "transactions": random.randint(400,1200), "fraud": random.randint(5,25)} for i in range(24)]}
|
| 123 |
+
|
| 124 |
+
@app.get("/shap/global")
|
| 125 |
+
async def shap_global():
|
| 126 |
+
feats = [f"V{i}" for i in range(1, 29)] + ["Amount"]
|
| 127 |
+
importance = sorted([{"feature": f, "importance": round(random.uniform(0.01, 0.35), 4)} for f in feats],
|
| 128 |
+
key=lambda x: x["importance"], reverse=True)
|
| 129 |
+
return {"feature_importance": importance[:15]}
|
data/eda_class_distribution.png
ADDED
|
data/eda_correlations.png
ADDED
|
data/evaluation_plots.png
ADDED
|
data/shap_importance.png
ADDED
|
data/shap_waterfall_fraud.png
ADDED
|
docker-compose.yml
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version: "3.8"
|
| 2 |
+
|
| 3 |
+
services:
|
| 4 |
+
|
| 5 |
+
# ββ Zookeeper (required for Kafka) ββββββββββββββββββββββββββββββββββββββββ
|
| 6 |
+
zookeeper:
|
| 7 |
+
image: confluentinc/cp-zookeeper:7.5.0
|
| 8 |
+
container_name: fraud_zookeeper
|
| 9 |
+
environment:
|
| 10 |
+
ZOOKEEPER_CLIENT_PORT: 2181
|
| 11 |
+
ZOOKEEPER_TICK_TIME: 2000
|
| 12 |
+
ports:
|
| 13 |
+
- "2181:2181"
|
| 14 |
+
|
| 15 |
+
# ββ Kafka Broker ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 16 |
+
kafka:
|
| 17 |
+
image: confluentinc/cp-kafka:7.5.0
|
| 18 |
+
container_name: fraud_kafka
|
| 19 |
+
depends_on:
|
| 20 |
+
- zookeeper
|
| 21 |
+
ports:
|
| 22 |
+
- "9092:9092"
|
| 23 |
+
environment:
|
| 24 |
+
KAFKA_BROKER_ID: 1
|
| 25 |
+
KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
|
| 26 |
+
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092
|
| 27 |
+
KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
|
| 28 |
+
KAFKA_AUTO_CREATE_TOPICS_ENABLE: "true"
|
| 29 |
+
|
| 30 |
+
# ββ FastAPI Scoring API βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 31 |
+
api:
|
| 32 |
+
build:
|
| 33 |
+
context: .
|
| 34 |
+
dockerfile: Dockerfile.api
|
| 35 |
+
container_name: fraud_api
|
| 36 |
+
ports:
|
| 37 |
+
- "8000:8000"
|
| 38 |
+
volumes:
|
| 39 |
+
- ./model:/app/model # mount trained model artifacts
|
| 40 |
+
environment:
|
| 41 |
+
MODEL_DIR: /app/model
|
| 42 |
+
depends_on:
|
| 43 |
+
- kafka
|
| 44 |
+
restart: unless-stopped
|
| 45 |
+
|
| 46 |
+
# ββ React Frontend ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 47 |
+
frontend:
|
| 48 |
+
build:
|
| 49 |
+
context: .
|
| 50 |
+
dockerfile: Dockerfile.frontend
|
| 51 |
+
args:
|
| 52 |
+
REACT_APP_API_URL: http://localhost:8000
|
| 53 |
+
container_name: fraud_frontend
|
| 54 |
+
ports:
|
| 55 |
+
- "3000:3000"
|
| 56 |
+
depends_on:
|
| 57 |
+
- api
|
| 58 |
+
restart: unless-stopped
|
| 59 |
+
|
| 60 |
+
networks:
|
| 61 |
+
default:
|
| 62 |
+
name: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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 6 |
+
<title>SENTINEL β Fraud Detection</title>
|
| 7 |
+
<link rel="preconnect" href="https://fonts.googleapis.com">
|
| 8 |
+
<link href="https://fonts.googleapis.com/css2?family=Share+Tech+Mono&family=Rajdhani:wght@400;500;600;700&family=Orbitron:wght@400;700;900&display=swap" rel="stylesheet">
|
| 9 |
+
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js"></script>
|
| 10 |
+
<style>
|
| 11 |
+
:root {
|
| 12 |
+
--bg: #04080f;
|
| 13 |
+
--bg2: #080f1a;
|
| 14 |
+
--bg3: #0c1824;
|
| 15 |
+
--border: #152840;
|
| 16 |
+
--cyan: #00d4ff;
|
| 17 |
+
--green: #00ff88;
|
| 18 |
+
--red: #ff2d55;
|
| 19 |
+
--orange: #ff9500;
|
| 20 |
+
--yellow: #ffd60a;
|
| 21 |
+
--txt: #dceeff;
|
| 22 |
+
--txt2: #6a9bbf;
|
| 23 |
+
--txt3: #2d5070;
|
| 24 |
+
--sidebar: 230px;
|
| 25 |
+
--mono: 'Share Tech Mono', monospace;
|
| 26 |
+
--body: 'Rajdhani', sans-serif;
|
| 27 |
+
--display: 'Orbitron', monospace;
|
| 28 |
+
}
|
| 29 |
+
*{margin:0;padding:0;box-sizing:border-box}
|
| 30 |
+
html,body{height:100%;overflow:hidden}
|
| 31 |
+
body{background:var(--bg);color:var(--txt);font-family:var(--body);font-size:14px;display:flex}
|
| 32 |
+
|
| 33 |
+
/* ββ SIDEBAR ββ */
|
| 34 |
+
.sidebar{
|
| 35 |
+
width:var(--sidebar);flex-shrink:0;
|
| 36 |
+
background:var(--bg2);border-right:1px solid var(--border);
|
| 37 |
+
display:flex;flex-direction:column;position:relative;z-index:10;
|
| 38 |
+
}
|
| 39 |
+
.sidebar::after{content:'';position:absolute;top:0;right:0;bottom:0;width:1px;background:linear-gradient(180deg,transparent,rgba(0,212,255,.3),transparent)}
|
| 40 |
+
.sb-logo{padding:20px 16px 14px;border-bottom:1px solid var(--border)}
|
| 41 |
+
.sb-logo-name{font-family:var(--display);font-size:16px;font-weight:900;color:var(--cyan);letter-spacing:3px;text-shadow:0 0 20px rgba(0,212,255,.4)}
|
| 42 |
+
.sb-logo-sub{font-family:var(--mono);font-size:8px;color:var(--txt3);letter-spacing:2px;margin-top:3px}
|
| 43 |
+
.sb-pill{display:inline-flex;align-items:center;gap:5px;background:rgba(0,255,136,.08);border:1px solid rgba(0,255,136,.25);border-radius:20px;padding:3px 9px;margin-top:8px;font-family:var(--mono);font-size:8px;color:var(--green)}
|
| 44 |
+
.sb-dot{width:5px;height:5px;background:var(--green);border-radius:50%;animation:pg 2s infinite}
|
| 45 |
+
@keyframes pg{0%,100%{opacity:1}50%{opacity:.3}}
|
| 46 |
+
.sb-nav{padding:14px 10px;flex:1}
|
| 47 |
+
.sb-sec{font-family:var(--mono);font-size:8px;color:var(--txt3);letter-spacing:2px;padding:0 8px;margin-bottom:6px;margin-top:4px}
|
| 48 |
+
.nav-btn{
|
| 49 |
+
display:flex;align-items:center;gap:10px;width:100%;
|
| 50 |
+
padding:9px 12px;border-radius:6px;border:1px solid transparent;
|
| 51 |
+
background:none;color:var(--txt2);cursor:pointer;
|
| 52 |
+
font-family:var(--body);font-size:13px;font-weight:500;letter-spacing:.3px;
|
| 53 |
+
transition:all .2s;margin-bottom:2px;text-align:left;position:relative;
|
| 54 |
+
}
|
| 55 |
+
.nav-btn:hover{background:var(--bg3);color:var(--txt);border-color:var(--border)}
|
| 56 |
+
.nav-btn.active{background:rgba(0,212,255,.07);color:var(--cyan);border-color:rgba(0,212,255,.2)}
|
| 57 |
+
.nav-btn.active::before{content:'';position:absolute;left:0;top:22%;bottom:22%;width:2px;background:var(--cyan);border-radius:2px;box-shadow:0 0 8px var(--cyan)}
|
| 58 |
+
.nav-icon{font-size:14px;width:18px;text-align:center;flex-shrink:0}
|
| 59 |
+
.sb-footer{padding:12px;border-top:1px solid var(--border)}
|
| 60 |
+
.sb-api{font-family:var(--mono);font-size:8px;color:var(--txt3);display:flex;align-items:center;gap:5px}
|
| 61 |
+
|
| 62 |
+
/* ββ MAIN ββ */
|
| 63 |
+
.main{flex:1;display:flex;flex-direction:column;overflow:hidden}
|
| 64 |
+
.topbar{
|
| 65 |
+
height:54px;background:var(--bg2);border-bottom:1px solid var(--border);
|
| 66 |
+
display:flex;align-items:center;justify-content:space-between;padding:0 22px;flex-shrink:0;
|
| 67 |
+
}
|
| 68 |
+
.topbar-title{font-family:var(--display);font-size:11px;font-weight:700;letter-spacing:2px}
|
| 69 |
+
.topbar-r{display:flex;align-items:center;gap:14px}
|
| 70 |
+
.live-badge{display:flex;align-items:center;gap:4px;background:rgba(255,45,85,.1);border:1px solid rgba(255,45,85,.35);border-radius:4px;padding:3px 9px;font-family:var(--mono);font-size:9px;color:var(--red);letter-spacing:1px}
|
| 71 |
+
.live-dot{width:5px;height:5px;background:var(--red);border-radius:50%;animation:bk 1s infinite}
|
| 72 |
+
@keyframes bk{0%,100%{opacity:1}50%{opacity:.15}}
|
| 73 |
+
.clock{font-family:var(--mono);font-size:11px;color:var(--cyan)}
|
| 74 |
+
.content{flex:1;overflow-y:auto;padding:20px}
|
| 75 |
+
|
| 76 |
+
/* ββ SECTIONS ββ */
|
| 77 |
+
.section{display:none;animation:fadeIn .3s ease}
|
| 78 |
+
.section.active{display:block}
|
| 79 |
+
@keyframes fadeIn{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}
|
| 80 |
+
|
| 81 |
+
/* ββ STAT CARDS ββ */
|
| 82 |
+
.stats-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:14px;margin-bottom:20px}
|
| 83 |
+
.stat{background:var(--bg3);border:1px solid var(--border);border-radius:8px;padding:18px;position:relative;overflow:hidden;transition:border-color .2s}
|
| 84 |
+
.stat:hover{border-color:rgba(0,212,255,.3)}
|
| 85 |
+
.stat::before{content:'';position:absolute;top:0;left:0;right:0;height:2px}
|
| 86 |
+
.stat.c::before{background:var(--cyan)}.stat.g::before{background:var(--green)}
|
| 87 |
+
.stat.r::before{background:var(--red)}.stat.o::before{background:var(--orange)}
|
| 88 |
+
.stat-lbl{font-family:var(--mono);font-size:8px;color:var(--txt3);letter-spacing:2px;margin-bottom:8px}
|
| 89 |
+
.stat-val{font-family:var(--display);font-size:26px;font-weight:700;line-height:1;margin-bottom:4px}
|
| 90 |
+
.stat.c .stat-val{color:var(--cyan)}.stat.g .stat-val{color:var(--green)}
|
| 91 |
+
.stat.r .stat-val{color:var(--red)}.stat.o .stat-val{color:var(--orange)}
|
| 92 |
+
.stat-sub{font-family:var(--mono);font-size:9px;color:var(--txt3)}
|
| 93 |
+
.stat-ico{position:absolute;right:14px;top:14px;font-size:24px;opacity:.12}
|
| 94 |
+
|
| 95 |
+
/* ββ CARDS ββ */
|
| 96 |
+
.card{background:var(--bg3);border:1px solid var(--border);border-radius:8px;overflow:hidden;margin-bottom:16px}
|
| 97 |
+
.card-h{display:flex;align-items:center;justify-content:space-between;padding:12px 18px;border-bottom:1px solid var(--border)}
|
| 98 |
+
.card-t{font-family:var(--display);font-size:10px;font-weight:700;letter-spacing:2px}
|
| 99 |
+
.card-b{padding:18px}
|
| 100 |
+
.g2{display:grid;grid-template-columns:1fr 1fr;gap:16px}
|
| 101 |
+
.g3{display:grid;grid-template-columns:1.7fr 1fr;gap:16px}
|
| 102 |
+
|
| 103 |
+
/* ββ TABLE ββ */
|
| 104 |
+
.tbl{width:100%;border-collapse:collapse}
|
| 105 |
+
.tbl th{font-family:var(--mono);font-size:8px;color:var(--txt3);letter-spacing:2px;text-align:left;padding:8px 12px;border-bottom:1px solid var(--border);background:rgba(0,0,0,.2)}
|
| 106 |
+
.tbl td{padding:9px 12px;border-bottom:1px solid rgba(21,40,64,.5);font-size:11px;font-family:var(--mono)}
|
| 107 |
+
.tbl tr:hover td{background:rgba(255,255,255,.015)}
|
| 108 |
+
.badge{display:inline-flex;align-items:center;gap:3px;padding:2px 7px;border-radius:3px;font-size:8px;font-weight:bold;letter-spacing:1px;font-family:var(--mono)}
|
| 109 |
+
.b-fraud{background:rgba(255,45,85,.15);color:var(--red);border:1px solid rgba(255,45,85,.3)}
|
| 110 |
+
.b-legit{background:rgba(0,255,136,.08);color:var(--green);border:1px solid rgba(0,255,136,.2)}
|
| 111 |
+
.b-h{background:rgba(255,45,85,.15);color:var(--red);border:1px solid rgba(255,45,85,.3)}
|
| 112 |
+
.b-m{background:rgba(255,149,0,.12);color:var(--orange);border:1px solid rgba(255,149,0,.3)}
|
| 113 |
+
.b-l{background:rgba(0,255,136,.08);color:var(--green);border:1px solid rgba(0,255,136,.2)}
|
| 114 |
+
|
| 115 |
+
/* ββ FORMS ββ */
|
| 116 |
+
.form-lbl{display:block;font-family:var(--mono);font-size:8px;color:var(--txt3);letter-spacing:2px;margin-bottom:5px}
|
| 117 |
+
.form-inp{width:100%;background:var(--bg2);border:1px solid var(--border);border-radius:5px;padding:8px 12px;color:var(--txt);font-family:var(--mono);font-size:11px;outline:none;transition:border-color .2s}
|
| 118 |
+
.form-inp:focus{border-color:var(--cyan);box-shadow:0 0 0 2px rgba(0,212,255,.08)}
|
| 119 |
+
.fg{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-bottom:12px}
|
| 120 |
+
.btn{display:inline-flex;align-items:center;gap:6px;padding:8px 16px;border-radius:5px;border:1px solid;cursor:pointer;font-family:var(--display);font-size:10px;font-weight:700;letter-spacing:1px;transition:all .2s}
|
| 121 |
+
.btn-c{background:rgba(0,212,255,.08);border-color:var(--cyan);color:var(--cyan)}
|
| 122 |
+
.btn-c:hover{background:rgba(0,212,255,.18);box-shadow:0 0 16px rgba(0,212,255,.25)}
|
| 123 |
+
.btn-r{background:rgba(255,45,85,.08);border-color:var(--red);color:var(--red)}
|
| 124 |
+
.btn-r:hover{background:rgba(255,45,85,.18)}
|
| 125 |
+
.btn-g{background:rgba(0,255,136,.06);border-color:var(--green);color:var(--green)}
|
| 126 |
+
|
| 127 |
+
/* ββ METRICS ββ */
|
| 128 |
+
.mrow{display:flex;align-items:center;justify-content:space-between;padding:9px 0;border-bottom:1px solid rgba(21,40,64,.5)}
|
| 129 |
+
.mrow:last-child{border:none}
|
| 130 |
+
.mname{font-family:var(--mono);font-size:10px;color:var(--txt2)}
|
| 131 |
+
.mval{font-family:var(--display);font-size:13px;font-weight:700;color:var(--cyan)}
|
| 132 |
+
.ptrack{background:var(--border);border-radius:3px;height:5px;overflow:hidden;flex:1;margin:0 12px}
|
| 133 |
+
.pfill{height:100%;border-radius:3px;background:linear-gradient(90deg,var(--cyan),var(--green));transition:width 1.2s ease}
|
| 134 |
+
|
| 135 |
+
/* ββ SHAP ββ */
|
| 136 |
+
.shap-row{display:flex;align-items:center;gap:8px;padding:5px 0}
|
| 137 |
+
.shap-f{font-family:var(--mono);font-size:10px;color:var(--txt2);width:55px;flex-shrink:0}
|
| 138 |
+
.shap-bc{flex:1;height:18px;background:var(--bg2);border-radius:3px;overflow:hidden;position:relative}
|
| 139 |
+
.shap-pos{position:absolute;left:50%;top:0;bottom:0;background:rgba(255,45,85,.55);border-radius:0 3px 3px 0}
|
| 140 |
+
.shap-neg{position:absolute;right:50%;top:0;bottom:0;background:rgba(0,212,255,.55);border-radius:3px 0 0 3px}
|
| 141 |
+
.shap-v{font-family:var(--mono);font-size:9px;color:var(--txt3);width:55px;text-align:right;flex-shrink:0}
|
| 142 |
+
|
| 143 |
+
/* ββ FEED ββ */
|
| 144 |
+
.feed-item{
|
| 145 |
+
display:grid;grid-template-columns:85px 1fr 70px 85px 80px 65px;
|
| 146 |
+
align-items:center;gap:10px;padding:8px 14px;
|
| 147 |
+
border-bottom:1px solid rgba(21,40,64,.4);
|
| 148 |
+
font-family:var(--mono);font-size:10px;transition:background .15s;
|
| 149 |
+
animation:si .3s ease;
|
| 150 |
+
}
|
| 151 |
+
.feed-item:hover{background:rgba(255,255,255,.015)}
|
| 152 |
+
.feed-item.fraud-row{background:rgba(255,45,85,.03);border-left:2px solid var(--red)}
|
| 153 |
+
@keyframes si{from{opacity:0;transform:translateX(-6px)}to{opacity:1;transform:translateX(0)}}
|
| 154 |
+
.feed-hdr{
|
| 155 |
+
display:grid;grid-template-columns:85px 1fr 70px 85px 80px 65px;
|
| 156 |
+
gap:10px;padding:7px 14px;
|
| 157 |
+
background:rgba(0,0,0,.2);border-bottom:1px solid var(--border);
|
| 158 |
+
}
|
| 159 |
+
.fh{font-family:var(--mono);font-size:8px;color:var(--txt3);letter-spacing:2px}
|
| 160 |
+
|
| 161 |
+
/* ββ RING ββ */
|
| 162 |
+
.ring-wrap{position:relative;width:110px;height:110px;margin:0 auto}
|
| 163 |
+
.ring-wrap svg{transform:rotate(-90deg)}
|
| 164 |
+
.ring-txt{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center}
|
| 165 |
+
.ring-num{font-family:var(--display);font-size:20px;font-weight:900}
|
| 166 |
+
.ring-lbl{font-family:var(--mono);font-size:7px;color:var(--txt3);letter-spacing:1px}
|
| 167 |
+
|
| 168 |
+
/* ββ CONFUSION MATRIX ββ */
|
| 169 |
+
.cm-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px;max-width:340px;margin:0 auto}
|
| 170 |
+
.cm-cell{text-align:center;padding:20px 10px;border-radius:7px;border:1px solid}
|
| 171 |
+
.cm-n{font-family:var(--display);font-size:28px;font-weight:700;margin-bottom:4px}
|
| 172 |
+
.cm-lbl{font-family:var(--mono);font-size:8px;letter-spacing:1px;margin-bottom:2px}
|
| 173 |
+
.cm-sub{font-family:var(--mono);font-size:8px}
|
| 174 |
+
|
| 175 |
+
/* ββ SCROLLBAR ββ */
|
| 176 |
+
::-webkit-scrollbar{width:4px;height:4px}
|
| 177 |
+
::-webkit-scrollbar-track{background:var(--bg)}
|
| 178 |
+
::-webkit-scrollbar-thumb{background:var(--border);border-radius:2px}
|
| 179 |
+
::-webkit-scrollbar-thumb:hover{background:var(--cyan)}
|
| 180 |
+
|
| 181 |
+
/* ββ RESULT BOX ββ */
|
| 182 |
+
.result-box{background:var(--bg2);border:1px solid var(--border);border-radius:7px;padding:16px;font-family:var(--mono);font-size:11px;min-height:120px}
|
| 183 |
+
.result-fraud{border-color:rgba(255,45,85,.4);background:rgba(255,45,85,.04)}
|
| 184 |
+
.result-legit{border-color:rgba(0,255,136,.25);background:rgba(0,255,136,.03)}
|
| 185 |
+
|
| 186 |
+
/* ββ ALERT ββ */
|
| 187 |
+
.alert-item{padding:9px 12px;border-radius:5px;font-family:var(--mono);font-size:9px;margin-bottom:7px;border-left:2px solid var(--red);background:rgba(255,45,85,.06);color:#ff6b87;animation:si .3s ease}
|
| 188 |
+
|
| 189 |
+
/* ββ LOADING ββ */
|
| 190 |
+
.spin{width:24px;height:24px;border:2px solid var(--border);border-top-color:var(--cyan);border-radius:50%;animation:sp .7s linear infinite;margin:0 auto}
|
| 191 |
+
@keyframes sp{to{transform:rotate(360deg)}}
|
| 192 |
+
|
| 193 |
+
/* SCANLINE */
|
| 194 |
+
body::after{content:'';position:fixed;inset:0;pointer-events:none;z-index:9999;background:repeating-linear-gradient(0deg,rgba(0,0,0,.03) 0px,rgba(0,0,0,.03) 1px,transparent 1px,transparent 2px);opacity:.4}
|
| 195 |
+
</style>
|
| 196 |
+
</head>
|
| 197 |
+
<body>
|
| 198 |
+
|
| 199 |
+
<!-- SIDEBAR -->
|
| 200 |
+
<div class="sidebar">
|
| 201 |
+
<div class="sb-logo">
|
| 202 |
+
<div class="sb-logo-name">SENTINEL</div>
|
| 203 |
+
<div class="sb-logo-sub">FRAUD DETECTION SYSTEM</div>
|
| 204 |
+
<div class="sb-pill"><span class="sb-dot"></span>SYSTEM ONLINE</div>
|
| 205 |
+
</div>
|
| 206 |
+
<div class="sb-nav">
|
| 207 |
+
<div class="sb-sec">NAVIGATION</div>
|
| 208 |
+
<button class="nav-btn active" onclick="showSection('overview',this)"><span class="nav-icon">β</span>Overview</button>
|
| 209 |
+
<button class="nav-btn" onclick="showSection('monitor',this)"><span class="nav-icon">β</span>Live Monitor</button>
|
| 210 |
+
<button class="nav-btn" onclick="showSection('analyzer',this)"><span class="nav-icon">⬑</span>Analyzer</button>
|
| 211 |
+
<button class="nav-btn" onclick="showSection('performance',this)"><span class="nav-icon">β²</span>Performance</button>
|
| 212 |
+
<button class="nav-btn" onclick="showSection('shap',this)"><span class="nav-icon">β</span>SHAP Explain</button>
|
| 213 |
+
</div>
|
| 214 |
+
<div class="sb-footer">
|
| 215 |
+
<div class="sb-api" id="apiStatus">β CHECKING API...</div>
|
| 216 |
+
</div>
|
| 217 |
+
</div>
|
| 218 |
+
|
| 219 |
+
<!-- MAIN -->
|
| 220 |
+
<div class="main">
|
| 221 |
+
<div class="topbar">
|
| 222 |
+
<div class="topbar-title" id="topTitle">OVERVIEW / DASHBOARD</div>
|
| 223 |
+
<div class="topbar-r">
|
| 224 |
+
<div class="live-badge"><span class="live-dot"></span>LIVE</div>
|
| 225 |
+
<div class="clock" id="clock">--:--:--</div>
|
| 226 |
+
</div>
|
| 227 |
+
</div>
|
| 228 |
+
<div class="content">
|
| 229 |
+
|
| 230 |
+
<!-- ββ OVERVIEW ββ -->
|
| 231 |
+
<div class="section active" id="sec-overview">
|
| 232 |
+
<div class="stats-grid">
|
| 233 |
+
<div class="stat c"><div class="stat-ico">β</div><div class="stat-lbl">TOTAL TRANSACTIONS</div><div class="stat-val" id="ovTotal">β</div><div class="stat-sub">Last 24 hours</div></div>
|
| 234 |
+
<div class="stat r"><div class="stat-ico">β </div><div class="stat-lbl">FRAUD DETECTED</div><div class="stat-val" id="ovFraud">β</div><div class="stat-sub" id="ovFraudPct">β fraud rate</div></div>
|
| 235 |
+
<div class="stat g"><div class="stat-ico">βΉ</div><div class="stat-lbl">AMOUNT PROTECTED</div><div class="stat-val" id="ovSaved">β</div><div class="stat-sub">Blocked today</div></div>
|
| 236 |
+
<div class="stat o"><div class="stat-ico">β‘</div><div class="stat-lbl">AVG RESPONSE</div><div class="stat-val" id="ovMs">β</div><div class="stat-sub">Milliseconds</div></div>
|
| 237 |
+
</div>
|
| 238 |
+
<div class="g3">
|
| 239 |
+
<div class="card" style="margin:0">
|
| 240 |
+
<div class="card-h"><span class="card-t">TRANSACTION VOLUME β 24H</span></div>
|
| 241 |
+
<div class="card-b"><div style="height:200px"><canvas id="volChart"></canvas></div></div>
|
| 242 |
+
</div>
|
| 243 |
+
<div class="card" style="margin:0">
|
| 244 |
+
<div class="card-h"><span class="card-t">FRAUD SPLIT</span></div>
|
| 245 |
+
<div class="card-b"><div style="height:200px"><canvas id="donutChart"></canvas></div></div>
|
| 246 |
+
</div>
|
| 247 |
+
</div>
|
| 248 |
+
<div class="card">
|
| 249 |
+
<div class="card-h">
|
| 250 |
+
<span class="card-t">RECENT TRANSACTIONS</span>
|
| 251 |
+
<button class="btn btn-c" onclick="loadOverviewTxns()" style="padding:4px 12px;font-size:9px">β» REFRESH</button>
|
| 252 |
+
</div>
|
| 253 |
+
<div id="ovTxnWrap"><div style="padding:24px;text-align:center"><div class="spin"></div></div></div>
|
| 254 |
+
</div>
|
| 255 |
+
</div>
|
| 256 |
+
|
| 257 |
+
<!-- ββ LIVE MONITOR ββ -->
|
| 258 |
+
<div class="section" id="sec-monitor">
|
| 259 |
+
<div class="stats-grid">
|
| 260 |
+
<div class="stat c"><div class="stat-lbl">PROCESSED (SESSION)</div><div class="stat-val" id="mTotal">0</div><div class="stat-sub">Auto-refresh 5s</div></div>
|
| 261 |
+
<div class="stat r"><div class="stat-lbl">FRAUDS CAUGHT</div><div class="stat-val" id="mFraud">0</div><div class="stat-sub" id="mFraudPct">0.00% rate</div></div>
|
| 262 |
+
<div class="stat g"><div class="stat-lbl">LEGIT PASSED</div><div class="stat-val" id="mLegit">0</div><div class="stat-sub">Safe transactions</div></div>
|
| 263 |
+
<div class="stat o"><div class="stat-lbl">HIGH RISK ALERTS</div><div class="stat-val" id="mHigh">0</div><div class="stat-sub">Needs review</div></div>
|
| 264 |
+
</div>
|
| 265 |
+
<div class="g3">
|
| 266 |
+
<div class="card" style="margin:0">
|
| 267 |
+
<div class="card-h">
|
| 268 |
+
<span class="card-t">LIVE FEED</span>
|
| 269 |
+
<button class="btn btn-c" id="pauseBtn" onclick="togglePause()" style="padding:4px 12px;font-size:9px">βΈ PAUSE</button>
|
| 270 |
+
</div>
|
| 271 |
+
<div class="feed-hdr">
|
| 272 |
+
<span class="fh">TXN ID</span><span class="fh">MERCHANT</span><span class="fh">AMOUNT</span>
|
| 273 |
+
<span class="fh">PROB</span><span class="fh">STATUS</span><span class="fh">TIME</span>
|
| 274 |
+
</div>
|
| 275 |
+
<div id="liveFeed" style="max-height:350px;overflow-y:auto"></div>
|
| 276 |
+
</div>
|
| 277 |
+
<div style="display:flex;flex-direction:column;gap:14px">
|
| 278 |
+
<div class="card" style="margin:0">
|
| 279 |
+
<div class="card-h"><span class="card-t">SESSION RINGS</span></div>
|
| 280 |
+
<div class="card-b" style="display:flex;justify-content:space-around">
|
| 281 |
+
<div>
|
| 282 |
+
<div class="ring-wrap">
|
| 283 |
+
<svg width="110" height="110" viewBox="0 0 110 110">
|
| 284 |
+
<circle cx="55" cy="55" r="46" fill="none" stroke="#152840" stroke-width="7"/>
|
| 285 |
+
<circle id="fraudRing" cx="55" cy="55" r="46" fill="none" stroke="#ff2d55" stroke-width="7" stroke-dasharray="289" stroke-dashoffset="289" stroke-linecap="round"/>
|
| 286 |
+
</svg>
|
| 287 |
+
<div class="ring-txt"><span class="ring-num" style="color:var(--red)" id="rFraud">0%</span><span class="ring-lbl">FRAUD</span></div>
|
| 288 |
+
</div>
|
| 289 |
+
</div>
|
| 290 |
+
<div>
|
| 291 |
+
<div class="ring-wrap">
|
| 292 |
+
<svg width="110" height="110" viewBox="0 0 110 110">
|
| 293 |
+
<circle cx="55" cy="55" r="46" fill="none" stroke="#152840" stroke-width="7"/>
|
| 294 |
+
<circle id="legitRing" cx="55" cy="55" r="46" fill="none" stroke="#00d4ff" stroke-width="7" stroke-dasharray="289" stroke-dashoffset="0" stroke-linecap="round"/>
|
| 295 |
+
</svg>
|
| 296 |
+
<div class="ring-txt"><span class="ring-num" style="color:var(--cyan)" id="rLegit">100%</span><span class="ring-lbl">LEGIT</span></div>
|
| 297 |
+
</div>
|
| 298 |
+
</div>
|
| 299 |
+
</div>
|
| 300 |
+
</div>
|
| 301 |
+
<div class="card" style="margin:0;flex:1">
|
| 302 |
+
<div class="card-h"><span class="card-t">β ALERTS</span></div>
|
| 303 |
+
<div id="alertPanel" style="padding:10px;max-height:200px;overflow-y:auto">
|
| 304 |
+
<div style="font-family:var(--mono);font-size:9px;color:var(--txt3);text-align:center;padding:12px">No alerts yet...</div>
|
| 305 |
+
</div>
|
| 306 |
+
</div>
|
| 307 |
+
</div>
|
| 308 |
+
</div>
|
| 309 |
+
<div class="card">
|
| 310 |
+
<div class="card-h"><span class="card-t">FRAUD PROBABILITY TREND</span></div>
|
| 311 |
+
<div class="card-b"><div style="height:150px"><canvas id="trendChart"></canvas></div></div>
|
| 312 |
+
</div>
|
| 313 |
+
</div>
|
| 314 |
+
|
| 315 |
+
<!-- ββ ANALYZER ββ -->
|
| 316 |
+
<div class="section" id="sec-analyzer">
|
| 317 |
+
<div class="g2" style="align-items:start">
|
| 318 |
+
<div class="card" style="margin:0">
|
| 319 |
+
<div class="card-h">
|
| 320 |
+
<span class="card-t">TRANSACTION INPUT</span>
|
| 321 |
+
<div style="display:flex;gap:8px">
|
| 322 |
+
<button class="btn btn-c" onclick="fillRandom()" style="padding:4px 10px;font-size:9px">β RANDOM</button>
|
| 323 |
+
<button class="btn btn-r" onclick="clearAnalyzer()" style="padding:4px 10px;font-size:9px">β CLEAR</button>
|
| 324 |
+
</div>
|
| 325 |
+
</div>
|
| 326 |
+
<div class="card-b">
|
| 327 |
+
<div style="margin-bottom:12px">
|
| 328 |
+
<label class="form-lbl">AMOUNT (βΉ)</label>
|
| 329 |
+
<input class="form-inp" type="number" id="inpAmount" value="250" step="0.01" style="max-width:200px">
|
| 330 |
+
</div>
|
| 331 |
+
<div class="form-lbl" style="margin-bottom:8px">PCA FEATURES V1 β V28</div>
|
| 332 |
+
<div class="fg" id="vInputs"></div>
|
| 333 |
+
<div style="display:flex;gap:10px;margin-top:4px">
|
| 334 |
+
<button class="btn btn-c" onclick="runAnalyze()" id="analyzeBtn">⬑ ANALYZE</button>
|
| 335 |
+
<button class="btn btn-g" onclick="runBatch()" style="padding:8px 14px">βΆ BATCH Γ10</button>
|
| 336 |
+
</div>
|
| 337 |
+
</div>
|
| 338 |
+
</div>
|
| 339 |
+
<div style="display:flex;flex-direction:column;gap:14px">
|
| 340 |
+
<div class="card" style="margin:0">
|
| 341 |
+
<div class="card-h"><span class="card-t">GAUGE</span></div>
|
| 342 |
+
<div class="card-b" style="text-align:center">
|
| 343 |
+
<canvas id="gaugeChart" width="200" height="130" style="max-width:200px"></canvas>
|
| 344 |
+
<div id="gaugeLbl" style="font-family:var(--display);font-size:26px;font-weight:900;color:var(--txt3);margin-top:-28px">β</div>
|
| 345 |
+
<div style="font-family:var(--mono);font-size:8px;color:var(--txt3);letter-spacing:2px">FRAUD PROBABILITY</div>
|
| 346 |
+
</div>
|
| 347 |
+
</div>
|
| 348 |
+
<div class="card" style="margin:0">
|
| 349 |
+
<div class="card-h"><span class="card-t">RESULT</span></div>
|
| 350 |
+
<div class="card-b" id="analyzeResult">
|
| 351 |
+
<div style="font-family:var(--mono);font-size:10px;color:var(--txt3);text-align:center;padding:16px">Run analysis to see result...</div>
|
| 352 |
+
</div>
|
| 353 |
+
</div>
|
| 354 |
+
<div class="card" style="margin:0">
|
| 355 |
+
<div class="card-h"><span class="card-t">BATCH RESULT</span></div>
|
| 356 |
+
<div class="card-b" id="batchResult">
|
| 357 |
+
<div style="font-family:var(--mono);font-size:10px;color:var(--txt3);text-align:center;padding:8px">Click Batch Γ10 to run</div>
|
| 358 |
+
</div>
|
| 359 |
+
</div>
|
| 360 |
+
</div>
|
| 361 |
+
</div>
|
| 362 |
+
</div>
|
| 363 |
+
|
| 364 |
+
<!-- ββ PERFORMANCE ββ -->
|
| 365 |
+
<div class="section" id="sec-performance">
|
| 366 |
+
<div class="stats-grid" style="grid-template-columns:repeat(5,1fr)">
|
| 367 |
+
<div class="stat c"><div class="stat-lbl">ROC-AUC</div><div class="stat-val" id="pAuc">β</div><div class="stat-sub">Area Under Curve</div></div>
|
| 368 |
+
<div class="stat g"><div class="stat-lbl">ACCURACY</div><div class="stat-val" id="pAcc">β</div><div class="stat-sub">Overall correct</div></div>
|
| 369 |
+
<div class="stat o"><div class="stat-lbl">PRECISION</div><div class="stat-val" id="pPrec">β</div><div class="stat-sub">Of flagged</div></div>
|
| 370 |
+
<div class="stat r"><div class="stat-lbl">RECALL</div><div class="stat-val" id="pRec">β</div><div class="stat-sub">Fraud caught</div></div>
|
| 371 |
+
<div class="stat c" style="border-top-color:var(--yellow)"><div class="stat-lbl">F1 SCORE</div><div class="stat-val" id="pF1" style="color:var(--yellow)">β</div><div class="stat-sub">Harmonic mean</div></div>
|
| 372 |
+
</div>
|
| 373 |
+
<div class="g2">
|
| 374 |
+
<div class="card" style="margin:0">
|
| 375 |
+
<div class="card-h"><span class="card-t">METRIC BARS</span></div>
|
| 376 |
+
<div class="card-b" id="metricBars"></div>
|
| 377 |
+
</div>
|
| 378 |
+
<div class="card" style="margin:0">
|
| 379 |
+
<div class="card-h"><span class="card-t">CONFUSION MATRIX</span></div>
|
| 380 |
+
<div class="card-b">
|
| 381 |
+
<div class="cm-grid">
|
| 382 |
+
<div class="cm-cell" style="background:rgba(0,255,136,.06);border-color:rgba(0,255,136,.2)"><div class="cm-n" style="color:var(--green)" id="cmTN">β</div><div class="cm-lbl" style="color:var(--txt3)">TRUE NEGATIVE</div><div class="cm-sub" style="color:var(--green)">Correct Legit</div></div>
|
| 383 |
+
<div class="cm-cell" style="background:rgba(255,149,0,.06);border-color:rgba(255,149,0,.2)"><div class="cm-n" style="color:var(--orange)" id="cmFP">β</div><div class="cm-lbl" style="color:var(--txt3)">FALSE POSITIVE</div><div class="cm-sub" style="color:var(--orange)">False Alarm</div></div>
|
| 384 |
+
<div class="cm-cell" style="background:rgba(255,45,85,.06);border-color:rgba(255,45,85,.2)"><div class="cm-n" style="color:var(--red)" id="cmFN">β</div><div class="cm-lbl" style="color:var(--txt3)">FALSE NEGATIVE</div><div class="cm-sub" style="color:var(--red)">Missed Fraud</div></div>
|
| 385 |
+
<div class="cm-cell" style="background:rgba(0,212,255,.06);border-color:rgba(0,212,255,.2)"><div class="cm-n" style="color:var(--cyan)" id="cmTP">β</div><div class="cm-lbl" style="color:var(--txt3)">TRUE POSITIVE</div><div class="cm-sub" style="color:var(--cyan)">Caught Fraud</div></div>
|
| 386 |
+
</div>
|
| 387 |
+
</div>
|
| 388 |
+
</div>
|
| 389 |
+
</div>
|
| 390 |
+
<div class="g2">
|
| 391 |
+
<div class="card" style="margin:0">
|
| 392 |
+
<div class="card-h"><span class="card-t">HOURLY FRAUD TREND</span></div>
|
| 393 |
+
<div class="card-b"><div style="height:180px"><canvas id="perfChart"></canvas></div></div>
|
| 394 |
+
</div>
|
| 395 |
+
<div class="card" style="margin:0">
|
| 396 |
+
<div class="card-h"><span class="card-t">THRESHOLD TUNER</span></div>
|
| 397 |
+
<div class="card-b">
|
| 398 |
+
<label class="form-lbl">THRESHOLD: <span id="threshVal" style="color:var(--cyan)">0.50</span></label>
|
| 399 |
+
<input type="range" id="threshSlider" min="0.1" max="0.9" step="0.05" value="0.5"
|
| 400 |
+
style="width:100%;accent-color:var(--cyan);margin:10px 0 16px"
|
| 401 |
+
oninput="updateThresh(this.value)">
|
| 402 |
+
<div id="threshStats"></div>
|
| 403 |
+
</div>
|
| 404 |
+
</div>
|
| 405 |
+
</div>
|
| 406 |
+
</div>
|
| 407 |
+
|
| 408 |
+
<!-- ββ SHAP ββ -->
|
| 409 |
+
<div class="section" id="sec-shap">
|
| 410 |
+
<div style="background:rgba(0,212,255,.05);border:1px solid rgba(0,212,255,.2);border-radius:6px;padding:10px 14px;font-family:var(--mono);font-size:10px;color:var(--cyan);margin-bottom:16px">
|
| 411 |
+
β SHAP shows which features push prediction toward FRAUD (red) or LEGITIMATE (blue). Longer bar = stronger influence.
|
| 412 |
+
</div>
|
| 413 |
+
<div class="g3">
|
| 414 |
+
<div class="card" style="margin:0">
|
| 415 |
+
<div class="card-h"><span class="card-t">GLOBAL FEATURE IMPORTANCE</span></div>
|
| 416 |
+
<div class="card-b"><div style="height:320px"><canvas id="shapChart"></canvas></div></div>
|
| 417 |
+
</div>
|
| 418 |
+
<div style="display:flex;flex-direction:column;gap:14px">
|
| 419 |
+
<div class="card" style="margin:0">
|
| 420 |
+
<div class="card-h"><span class="card-t">LEGEND</span></div>
|
| 421 |
+
<div class="card-b">
|
| 422 |
+
<div style="display:flex;align-items:center;gap:8px;margin-bottom:8px"><div style="width:32px;height:8px;background:var(--red);border-radius:2px"></div><span style="font-family:var(--mono);font-size:9px;color:var(--txt2)">Pushes β FRAUD</span></div>
|
| 423 |
+
<div style="display:flex;align-items:center;gap:8px;margin-bottom:14px"><div style="width:32px;height:8px;background:var(--cyan);border-radius:2px"></div><span style="font-family:var(--mono);font-size:9px;color:var(--txt2)">Pushes β LEGIT</span></div>
|
| 424 |
+
<div style="font-family:var(--mono);font-size:9px;color:var(--txt3);line-height:1.8">V14 and V4 are typically the strongest fraud signals in the Credit Card dataset.</div>
|
| 425 |
+
</div>
|
| 426 |
+
</div>
|
| 427 |
+
<div class="card" style="margin:0">
|
| 428 |
+
<div class="card-h"><span class="card-t">TOP INDICATORS</span></div>
|
| 429 |
+
<div class="card-b" id="topFeatures"></div>
|
| 430 |
+
</div>
|
| 431 |
+
</div>
|
| 432 |
+
</div>
|
| 433 |
+
<div class="card">
|
| 434 |
+
<div class="card-h">
|
| 435 |
+
<span class="card-t">LOCAL EXPLANATION</span>
|
| 436 |
+
<button class="btn btn-c" onclick="explainRandom()" style="padding:4px 12px;font-size:9px">β EXPLAIN RANDOM</button>
|
| 437 |
+
</div>
|
| 438 |
+
<div class="card-b" id="localShap">
|
| 439 |
+
<div style="font-family:var(--mono);font-size:10px;color:var(--txt3);text-align:center;padding:16px">Click "EXPLAIN RANDOM" to see a local explanation.</div>
|
| 440 |
+
</div>
|
| 441 |
+
</div>
|
| 442 |
+
</div>
|
| 443 |
+
|
| 444 |
+
</div><!-- end .content -->
|
| 445 |
+
</div><!-- end .main -->
|
| 446 |
+
|
| 447 |
+
<script>
|
| 448 |
+
const API = 'http://localhost:8000';
|
| 449 |
+
|
| 450 |
+
// ββ utils ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 451 |
+
async function get(path){ try{ const r=await fetch(API+path); return r.ok?await r.json():null; }catch(e){ return null; } }
|
| 452 |
+
async function post(path,body){ try{ const r=await fetch(API+path,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}); return r.ok?await r.json():null; }catch(e){ return null; } }
|
| 453 |
+
function fc(n){ if(n>=1e6) return 'βΉ'+(n/1e6).toFixed(1)+'M'; if(n>=1e3) return 'βΉ'+(n/1e3).toFixed(1)+'K'; return 'βΉ'+n.toFixed(0); }
|
| 454 |
+
function fp(n){ return (n*100).toFixed(2)+'%'; }
|
| 455 |
+
function bb(isFraud){ return isFraud?`<span class="badge b-fraud">β FRAUD</span>`:`<span class="badge b-legit">β LEGIT</span>`; }
|
| 456 |
+
function rb(lvl){ const m={HIGH:'b-h',MEDIUM:'b-m',LOW:'b-l'}; return `<span class="badge ${m[lvl]||'b-l'}">${lvl}</span>`; }
|
| 457 |
+
function pb(prob){ const p=(prob*100).toFixed(0); const c=prob>.7?'#ff2d55':prob>.4?'#ff9500':'#00ff88'; return `<span style="display:inline-block;width:60px;height:4px;background:#152840;border-radius:2px;vertical-align:middle;margin-right:4px;overflow:hidden"><span style="display:block;height:100%;width:${p}%;background:${c};border-radius:2px"></span></span>${p}%`; }
|
| 458 |
+
function ta(ts){ const d=Math.floor((Date.now()-new Date(ts))/1000); if(d<60) return d+'s'; if(d<3600) return Math.floor(d/60)+'m'; return Math.floor(d/3600)+'h'; }
|
| 459 |
+
|
| 460 |
+
// ββ navigation βββββββββββββββββββββββββββββββββββββββββββββ
|
| 461 |
+
const titles = { overview:'OVERVIEW / DASHBOARD', monitor:'LIVE MONITOR', analyzer:'TRANSACTION ANALYZER', performance:'MODEL PERFORMANCE', shap:'SHAP EXPLAINABILITY' };
|
| 462 |
+
function showSection(id, btn){
|
| 463 |
+
document.querySelectorAll('.section').forEach(s=>s.classList.remove('active'));
|
| 464 |
+
document.querySelectorAll('.nav-btn').forEach(b=>b.classList.remove('active'));
|
| 465 |
+
document.getElementById('sec-'+id).classList.add('active');
|
| 466 |
+
btn.classList.add('active');
|
| 467 |
+
document.getElementById('topTitle').textContent = titles[id];
|
| 468 |
+
if(id==='overview') loadOverview();
|
| 469 |
+
if(id==='monitor') startMonitor();
|
| 470 |
+
if(id==='performance') loadPerformance();
|
| 471 |
+
if(id==='shap') loadShap();
|
| 472 |
+
if(id==='analyzer') buildVInputs();
|
| 473 |
+
}
|
| 474 |
+
|
| 475 |
+
// ββ clock ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 476 |
+
setInterval(()=>{ document.getElementById('clock').textContent=new Date().toLocaleTimeString('en-IN',{hour12:false})+' IST'; },1000);
|
| 477 |
+
|
| 478 |
+
// ββ API health βββββββββββββββββββββββββββββββββββββββββββββ
|
| 479 |
+
async function checkHealth(){
|
| 480 |
+
const d=await get('/health');
|
| 481 |
+
const el=document.getElementById('apiStatus');
|
| 482 |
+
el.innerHTML=d&&d.status==='online'?'<span style="color:var(--green)">β API ONLINE</span>':'<span style="color:var(--red)">β API OFFLINE</span>';
|
| 483 |
+
}
|
| 484 |
+
checkHealth(); setInterval(checkHealth,10000);
|
| 485 |
+
|
| 486 |
+
// ββ chart helpers ββββββββββββββββββββββββββββββββββββββββββ
|
| 487 |
+
function lineChart(id, labels, datasets){
|
| 488 |
+
const ctx=document.getElementById(id); if(!ctx) return null;
|
| 489 |
+
if(ctx._c) ctx._c.destroy();
|
| 490 |
+
ctx._c=new Chart(ctx,{ type:'line', data:{labels,datasets}, options:{ responsive:true, maintainAspectRatio:false, plugins:{legend:{labels:{color:'#6a9bbf',font:{family:'Share Tech Mono',size:9}}}}, scales:{ x:{grid:{color:'#15284055'},ticks:{color:'#6a9bbf',font:{family:'Share Tech Mono',size:8}}}, y:{grid:{color:'#15284055'},ticks:{color:'#6a9bbf',font:{family:'Share Tech Mono',size:8}}} } } });
|
| 491 |
+
return ctx._c;
|
| 492 |
+
}
|
| 493 |
+
function barChart(id, labels, datasets, opts={}){
|
| 494 |
+
const ctx=document.getElementById(id); if(!ctx) return null;
|
| 495 |
+
if(ctx._c) ctx._c.destroy();
|
| 496 |
+
ctx._c=new Chart(ctx,{ type:'bar', data:{labels,datasets}, options:{ responsive:true, maintainAspectRatio:false, plugins:{legend:{display:false}}, scales:{ x:{grid:{color:'#15284055'},ticks:{color:'#6a9bbf',font:{family:'Share Tech Mono',size:8}}}, y:{grid:{color:'#15284055'},ticks:{color:'#6a9bbf',font:{family:'Share Tech Mono',size:8}}} }, ...opts } });
|
| 497 |
+
return ctx._c;
|
| 498 |
+
}
|
| 499 |
+
function doughnut(id, labels, data, colors){
|
| 500 |
+
const ctx=document.getElementById(id); if(!ctx) return;
|
| 501 |
+
if(ctx._c) ctx._c.destroy();
|
| 502 |
+
ctx._c=new Chart(ctx,{ type:'doughnut', data:{labels,datasets:[{data,backgroundColor:colors,borderWidth:0}]}, options:{ responsive:true, maintainAspectRatio:false, cutout:'70%', plugins:{legend:{position:'bottom',labels:{color:'#6a9bbf',font:{family:'Share Tech Mono',size:9},padding:10}}} } });
|
| 503 |
+
}
|
| 504 |
+
|
| 505 |
+
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 506 |
+
// OVERVIEW
|
| 507 |
+
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 508 |
+
async function loadOverview(){
|
| 509 |
+
const d=await get('/stats/summary'); if(!d) return;
|
| 510 |
+
document.getElementById('ovTotal').textContent=d.total_transactions.toLocaleString();
|
| 511 |
+
document.getElementById('ovFraud').textContent=d.fraud_detected.toLocaleString();
|
| 512 |
+
document.getElementById('ovFraudPct').textContent=fp(d.fraud_rate)+' fraud rate';
|
| 513 |
+
document.getElementById('ovSaved').textContent=fc(d.amount_saved);
|
| 514 |
+
document.getElementById('ovMs').textContent=d.avg_response_ms+'ms';
|
| 515 |
+
const hrs=d.hourly_stats.map(h=>h.hour.slice(0,5));
|
| 516 |
+
lineChart('volChart',hrs,[
|
| 517 |
+
{label:'Transactions',data:d.hourly_stats.map(h=>h.transactions),borderColor:'#00d4ff',backgroundColor:'rgba(0,212,255,.07)',tension:.4,fill:true,pointRadius:0},
|
| 518 |
+
{label:'Fraud',data:d.hourly_stats.map(h=>h.fraud),borderColor:'#ff2d55',backgroundColor:'rgba(255,45,85,.05)',tension:.4,fill:true,pointRadius:0}
|
| 519 |
+
]);
|
| 520 |
+
doughnut('donutChart',['Legitimate','Fraud'],[d.total_transactions-d.fraud_detected,d.fraud_detected],['#00d4ff','#ff2d55']);
|
| 521 |
+
loadOverviewTxns();
|
| 522 |
+
}
|
| 523 |
+
|
| 524 |
+
async function loadOverviewTxns(){
|
| 525 |
+
document.getElementById('ovTxnWrap').innerHTML='<div style="padding:20px;text-align:center"><div class="spin"></div></div>';
|
| 526 |
+
const d=await get('/stream/live');
|
| 527 |
+
if(!d){ document.getElementById('ovTxnWrap').innerHTML='<div style="padding:16px;font-family:var(--mono);font-size:10px;color:var(--red);text-align:center">API offline β run: uvicorn api.main:app --port 8000</div>'; return; }
|
| 528 |
+
const rows=d.transactions.map(t=>`<tr><td style="color:var(--cyan)">${t.id}</td><td>${t.merchant}</td><td>${t.location}</td><td>βΉ${t.amount.toLocaleString()}</td><td>${pb(t.fraud_probability)}</td><td>${rb(t.risk_level)}</td><td>${bb(t.is_fraud)}</td><td style="color:var(--txt3)">${ta(t.timestamp)}</td></tr>`).join('');
|
| 529 |
+
document.getElementById('ovTxnWrap').innerHTML=`<div style="overflow-x:auto"><table class="tbl"><thead><tr><th>TXN ID</th><th>MERCHANT</th><th>LOCATION</th><th>AMOUNT</th><th>PROB</th><th>RISK</th><th>STATUS</th><th>TIME</th></tr></thead><tbody>${rows}</tbody></table></div>`;
|
| 530 |
+
}
|
| 531 |
+
|
| 532 |
+
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 533 |
+
// MONITOR
|
| 534 |
+
// βββββββββββββββββββββββββββββββββββββββββββββββββββοΏ½οΏ½οΏ½ββββββ
|
| 535 |
+
let paused=false, mTotal=0, mFraud=0, mHigh=0, monitorStarted=false;
|
| 536 |
+
const trendLabels=[], trendData=[];
|
| 537 |
+
let trendChart=null;
|
| 538 |
+
|
| 539 |
+
function togglePause(){ paused=!paused; document.getElementById('pauseBtn').textContent=paused?'βΆ RESUME':'βΈ PAUSE'; }
|
| 540 |
+
|
| 541 |
+
function startMonitor(){ if(!monitorStarted){ monitorStarted=true; fetchMonitor(); setInterval(fetchMonitor,5000); } }
|
| 542 |
+
|
| 543 |
+
async function fetchMonitor(){
|
| 544 |
+
if(paused) return;
|
| 545 |
+
const d=await get('/stream/live'); if(!d) return;
|
| 546 |
+
const txns=d.transactions.slice(0,8);
|
| 547 |
+
mTotal+=txns.length; const nf=txns.filter(t=>t.is_fraud).length; const nh=txns.filter(t=>t.risk_level==='HIGH').length;
|
| 548 |
+
mFraud+=nf; mHigh+=nh;
|
| 549 |
+
document.getElementById('mTotal').textContent=mTotal.toLocaleString();
|
| 550 |
+
document.getElementById('mFraud').textContent=mFraud.toLocaleString();
|
| 551 |
+
document.getElementById('mLegit').textContent=(mTotal-mFraud).toLocaleString();
|
| 552 |
+
document.getElementById('mHigh').textContent=mHigh.toLocaleString();
|
| 553 |
+
const fp=mTotal>0?(mFraud/mTotal*100):0;
|
| 554 |
+
document.getElementById('mFraudPct').textContent=fp.toFixed(2)+'% rate';
|
| 555 |
+
const c=289; document.getElementById('fraudRing').style.strokeDashoffset=c-(fp/100)*c;
|
| 556 |
+
document.getElementById('legitRing').style.strokeDashoffset=c-((100-fp)/100)*c;
|
| 557 |
+
document.getElementById('rFraud').textContent=fp.toFixed(1)+'%';
|
| 558 |
+
document.getElementById('rLegit').textContent=(100-fp).toFixed(1)+'%';
|
| 559 |
+
const now=new Date().toLocaleTimeString('en',{hour12:false});
|
| 560 |
+
trendLabels.push(now); trendData.push(+(txns.reduce((s,t)=>s+t.fraud_probability,0)/txns.length*100).toFixed(1));
|
| 561 |
+
if(trendLabels.length>20){ trendLabels.shift(); trendData.shift(); }
|
| 562 |
+
if(!trendChart){
|
| 563 |
+
trendChart=lineChart('trendChart',trendLabels,[{label:'Avg Fraud %',data:trendData,borderColor:'#ff2d55',backgroundColor:'rgba(255,45,85,.07)',tension:.4,fill:true,pointRadius:2,pointBackgroundColor:'#ff2d55'}]);
|
| 564 |
+
} else { trendChart.data.labels=trendLabels; trendChart.data.datasets[0].data=trendData; trendChart.update('none'); }
|
| 565 |
+
document.getElementById('liveFeed').innerHTML=txns.map(t=>`<div class="feed-item ${t.is_fraud?'fraud-row':''}"><span style="color:var(--cyan)">${t.id}</span><span>${t.merchant}<br><span style="color:var(--txt3);font-size:8px">${t.location}</span></span><span>βΉ${t.amount.toLocaleString()}</span><span>${pb(t.fraud_probability)}</span><span>${bb(t.is_fraud)}</span><span style="color:var(--txt3)">${ta(t.timestamp)}</span></div>`).join('');
|
| 566 |
+
txns.filter(t=>t.is_fraud).forEach(t=>{ const p=document.getElementById('alertPanel'); const noAlerts=p.querySelector('[data-no-alerts]'); if(noAlerts) noAlerts.remove(); const el=document.createElement('div'); el.className='alert-item'; el.innerHTML=`β <strong>${t.id}</strong> β βΉ${t.amount.toLocaleString()} at ${t.merchant} β ${(t.fraud_probability*100).toFixed(1)}%`; p.prepend(el); if(p.children.length>7) p.lastChild.remove(); });
|
| 567 |
+
}
|
| 568 |
+
|
| 569 |
+
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 570 |
+
// ANALYZER
|
| 571 |
+
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 572 |
+
function buildVInputs(){
|
| 573 |
+
if(document.getElementById('vInputs').children.length>0) return;
|
| 574 |
+
let h='';
|
| 575 |
+
for(let i=1;i<=28;i++) h+=`<div><label class="form-lbl">V${i}</label><input class="form-inp" type="number" id="V${i}" value="0" step="0.001" style="padding:5px 8px;font-size:10px"></div>`;
|
| 576 |
+
document.getElementById('vInputs').innerHTML=h;
|
| 577 |
+
}
|
| 578 |
+
|
| 579 |
+
function fillRandom(){
|
| 580 |
+
buildVInputs();
|
| 581 |
+
const fraud=Math.random()<.3;
|
| 582 |
+
document.getElementById('inpAmount').value=fraud?(Math.random()*400+10).toFixed(2):(Math.random()*3000+100).toFixed(2);
|
| 583 |
+
for(let i=1;i<=28;i++){ const el=document.getElementById('V'+i); if(el) el.value=(Math.random()*6-3).toFixed(4); }
|
| 584 |
+
if(fraud){ document.getElementById('V14').value=(-7+Math.random()*1.5).toFixed(4); document.getElementById('V4').value=(4+Math.random()*2).toFixed(4); }
|
| 585 |
+
}
|
| 586 |
+
|
| 587 |
+
function clearAnalyzer(){
|
| 588 |
+
document.getElementById('inpAmount').value='0';
|
| 589 |
+
for(let i=1;i<=28;i++){ const el=document.getElementById('V'+i); if(el) el.value='0'; }
|
| 590 |
+
document.getElementById('analyzeResult').innerHTML='<div style="font-family:var(--mono);font-size:10px;color:var(--txt3);text-align:center;padding:16px">Run analysis to see result...</div>';
|
| 591 |
+
updateGauge(null);
|
| 592 |
+
}
|
| 593 |
+
|
| 594 |
+
function updateGauge(prob){
|
| 595 |
+
const ctx=document.getElementById('gaugeChart'); if(!ctx) return;
|
| 596 |
+
if(ctx._c) ctx._c.destroy();
|
| 597 |
+
const p=prob===null?0:prob;
|
| 598 |
+
const color=p>.7?'#ff2d55':p>.4?'#ff9500':'#00ff88';
|
| 599 |
+
ctx._c=new Chart(ctx,{ type:'doughnut', data:{datasets:[{data:[p*100,100-p*100],backgroundColor:[color,'#152840'],borderWidth:0}]}, options:{ responsive:false, circumference:180, rotation:-90, cutout:'74%', plugins:{legend:{display:false},tooltip:{enabled:false}} } });
|
| 600 |
+
const lbl=document.getElementById('gaugeLbl');
|
| 601 |
+
lbl.textContent=prob===null?'β':(p*100).toFixed(1)+'%';
|
| 602 |
+
lbl.style.color=prob===null?'var(--txt3)':color;
|
| 603 |
+
}
|
| 604 |
+
updateGauge(null);
|
| 605 |
+
|
| 606 |
+
async function runAnalyze(){
|
| 607 |
+
const btn=document.getElementById('analyzeBtn'); btn.textContent='β³...'; btn.disabled=true;
|
| 608 |
+
const payload={Amount:parseFloat(document.getElementById('inpAmount').value)||0};
|
| 609 |
+
for(let i=1;i<=28;i++) payload['V'+i]=parseFloat(document.getElementById('V'+i)?.value)||0;
|
| 610 |
+
const r=await post('/predict',payload);
|
| 611 |
+
btn.textContent='⬑ ANALYZE'; btn.disabled=false;
|
| 612 |
+
if(!r){ document.getElementById('analyzeResult').innerHTML='<div style="color:var(--red);font-family:var(--mono);font-size:10px">API not responding.</div>'; return; }
|
| 613 |
+
updateGauge(r.fraud_probability);
|
| 614 |
+
const color=r.is_fraud?'var(--red)':'var(--green)';
|
| 615 |
+
document.getElementById('analyzeResult').innerHTML=`
|
| 616 |
+
<div style="display:flex;align-items:center;gap:12px;margin-bottom:14px">
|
| 617 |
+
<div style="font-size:36px">${r.is_fraud?'β ':'β'}</div>
|
| 618 |
+
<div><div style="font-family:var(--display);font-size:15px;font-weight:900;color:${color}">${r.is_fraud?'FRAUD DETECTED':'TRANSACTION CLEAR'}</div>
|
| 619 |
+
<div style="font-family:var(--mono);font-size:9px;color:var(--txt3)">${(r.fraud_probability*100).toFixed(2)}% confidence</div></div>
|
| 620 |
+
</div>
|
| 621 |
+
<div class="mrow"><span class="mname">Amount</span><span class="mval">βΉ${(r.amount||payload.Amount).toLocaleString()}</span></div>
|
| 622 |
+
<div class="mrow"><span class="mname">Fraud Prob</span><span class="mval" style="color:${color}">${(r.fraud_probability*100).toFixed(2)}%</span></div>
|
| 623 |
+
<div class="mrow"><span class="mname">Risk Level</span><span>${rb(r.risk_level)}</span></div>
|
| 624 |
+
<div class="mrow"><span class="mname">Verdict</span><span>${bb(r.is_fraud)}</span></div>
|
| 625 |
+
${r.demo_mode?'<div style="margin-top:8px;font-family:var(--mono);font-size:8px;color:var(--txt3)">β Demo mode β model.pkl not loaded</div>':''}`;
|
| 626 |
+
}
|
| 627 |
+
|
| 628 |
+
async function runBatch(){
|
| 629 |
+
document.getElementById('batchResult').innerHTML='<div style="text-align:center;padding:12px"><div class="spin"></div></div>';
|
| 630 |
+
const transactions=Array.from({length:10},()=>{ const o={Amount:Math.random()*3000+10}; for(let i=1;i<=28;i++) o['V'+i]=+(Math.random()*6-3).toFixed(4); return o; });
|
| 631 |
+
const r=await post('/predict/batch',{transactions});
|
| 632 |
+
if(!r){ document.getElementById('batchResult').innerHTML='<div style="color:var(--red);font-family:var(--mono);font-size:10px">API offline</div>'; return; }
|
| 633 |
+
document.getElementById('batchResult').innerHTML=`
|
| 634 |
+
<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px;margin-bottom:10px">
|
| 635 |
+
<div style="text-align:center;padding:8px;background:var(--bg2);border-radius:5px;border:1px solid var(--border)"><div style="font-family:var(--display);font-size:18px;color:var(--cyan)">${r.total}</div><div style="font-family:var(--mono);font-size:8px;color:var(--txt3)">TOTAL</div></div>
|
| 636 |
+
<div style="text-align:center;padding:8px;background:var(--bg2);border-radius:5px;border:1px solid rgba(255,45,85,.3)"><div style="font-family:var(--display);font-size:18px;color:var(--red)">${r.fraud_count}</div><div style="font-family:var(--mono);font-size:8px;color:var(--txt3)">FRAUD</div></div>
|
| 637 |
+
<div style="text-align:center;padding:8px;background:var(--bg2);border-radius:5px;border:1px solid rgba(0,255,136,.2)"><div style="font-family:var(--display);font-size:18px;color:var(--green)">${fp(r.fraud_rate)}</div><div style="font-family:var(--mono);font-size:8px;color:var(--txt3)">RATE</div></div>
|
| 638 |
+
</div>
|
| 639 |
+
<div style="font-family:var(--mono);font-size:9px">${r.results.map((x,i)=>`<span style="display:inline-block;margin:2px;padding:2px 6px;border-radius:3px;background:${x.is_fraud?'rgba(255,45,85,.15)':'rgba(0,255,136,.07)'}">T${i+1}:${(x.fraud_probability*100).toFixed(0)}%</span>`).join('')}</div>`;
|
| 640 |
+
}
|
| 641 |
+
|
| 642 |
+
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 643 |
+
// PERFORMANCE
|
| 644 |
+
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 645 |
+
async function loadPerformance(){
|
| 646 |
+
const d=await get('/stats/summary'); if(!d) return;
|
| 647 |
+
document.getElementById('pAuc').textContent=d.roc_auc.toFixed(4);
|
| 648 |
+
document.getElementById('pAcc').textContent=d.model_accuracy.toFixed(4);
|
| 649 |
+
document.getElementById('pPrec').textContent=d.precision.toFixed(3);
|
| 650 |
+
document.getElementById('pRec').textContent=d.recall.toFixed(3);
|
| 651 |
+
document.getElementById('pF1').textContent=d.f1_score.toFixed(3);
|
| 652 |
+
const metrics=[{n:'ROC-AUC',v:d.roc_auc,c:'#00d4ff'},{n:'Accuracy',v:d.model_accuracy,c:'#00ff88'},{n:'Precision',v:d.precision,c:'#ff9500'},{n:'Recall',v:d.recall,c:'#ff2d55'},{n:'F1 Score',v:d.f1_score,c:'#ffd60a'}];
|
| 653 |
+
document.getElementById('metricBars').innerHTML=metrics.map(m=>`<div style="margin-bottom:14px"><div style="display:flex;justify-content:space-between;margin-bottom:5px"><span style="font-family:var(--mono);font-size:10px;color:var(--txt2)">${m.n}</span><span style="font-family:var(--display);font-size:12px;font-weight:700;color:${m.c}">${(m.v*100).toFixed(2)}%</span></div><div class="ptrack" style="margin:0;height:7px"><div class="pfill" style="width:${m.v*100}%;background:${m.c}"></div></div></div>`).join('');
|
| 654 |
+
const tot=d.total_transactions, tp=Math.round(d.fraud_detected*d.recall), fp2=Math.round(d.fraud_detected*(1-d.precision)), fn=d.fraud_detected-tp, tn=tot-tp-fp2-fn;
|
| 655 |
+
document.getElementById('cmTN').textContent=tn.toLocaleString();
|
| 656 |
+
document.getElementById('cmFP').textContent=fp2.toLocaleString();
|
| 657 |
+
document.getElementById('cmFN').textContent=fn.toLocaleString();
|
| 658 |
+
document.getElementById('cmTP').textContent=tp.toLocaleString();
|
| 659 |
+
const hrs=d.hourly_stats.map(h=>h.hour.slice(0,5));
|
| 660 |
+
lineChart('perfChart',hrs,[
|
| 661 |
+
{label:'Transactions',data:d.hourly_stats.map(h=>h.transactions),borderColor:'#00d4ff',backgroundColor:'rgba(0,212,255,.06)',tension:.4,fill:true,pointRadius:0},
|
| 662 |
+
{label:'Fraud',data:d.hourly_stats.map(h=>h.fraud),borderColor:'#ff2d55',backgroundColor:'rgba(255,45,85,.05)',tension:.4,fill:true,pointRadius:0}
|
| 663 |
+
]);
|
| 664 |
+
updateThresh(0.5);
|
| 665 |
+
}
|
| 666 |
+
|
| 667 |
+
function updateThresh(v){
|
| 668 |
+
document.getElementById('threshVal').textContent=parseFloat(v).toFixed(2);
|
| 669 |
+
const prec=Math.min(.99,.7+v*.35).toFixed(3), rec=Math.max(.4,1-v*.7).toFixed(3);
|
| 670 |
+
const f1=(2*prec*rec/(+prec+ +rec)).toFixed(3);
|
| 671 |
+
document.getElementById('threshStats').innerHTML=`
|
| 672 |
+
<div class="mrow"><span class="mname">Precision</span><span class="mval">${prec}</span></div>
|
| 673 |
+
<div class="mrow"><span class="mname">Recall</span><span class="mval" style="color:var(--orange)">${rec}</span></div>
|
| 674 |
+
<div class="mrow"><span class="mname">F1 Score</span><span class="mval" style="color:var(--yellow)">${f1}</span></div>
|
| 675 |
+
<div class="mrow"><span class="mname">Recommendation</span><span style="font-family:var(--mono);font-size:9px;color:${+v>.6?'var(--orange)':+v<.3?'var(--red)':'var(--green)'}">${+v>.6?'High precision, may miss fraud':+v<.3?'High recall, many false alarms':'Balanced β recommended'}</span></div>`;
|
| 676 |
+
}
|
| 677 |
+
|
| 678 |
+
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 679 |
+
// SHAP
|
| 680 |
+
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 681 |
+
async function loadShap(){
|
| 682 |
+
const d=await get('/shap/global'); if(!d) return;
|
| 683 |
+
const feats=d.feature_importance.slice(0,15);
|
| 684 |
+
barChart('shapChart',feats.map(f=>f.feature),[{data:feats.map(f=>f.importance),backgroundColor:feats.map((_,i)=>i<5?'rgba(255,45,85,.7)':i<10?'rgba(255,149,0,.6)':'rgba(0,212,255,.5)'),borderWidth:0,borderRadius:3}],{indexAxis:'y'});
|
| 685 |
+
document.getElementById('topFeatures').innerHTML=feats.slice(0,7).map((f,i)=>`<div style="display:flex;align-items:center;gap:8px;padding:5px 0;border-bottom:1px solid rgba(21,40,64,.4)"><span style="font-family:var(--display);font-size:10px;color:var(--txt3);width:16px">#${i+1}</span><span style="font-family:var(--mono);font-size:11px;color:var(--cyan);width:36px">${f.feature}</span><div class="ptrack" style="margin:0;flex:1"><div class="pfill" style="width:${(f.importance/feats[0].importance*100).toFixed(0)}%;background:${i<3?'#ff2d55':'#00d4ff'}"></div></div><span style="font-family:var(--mono);font-size:9px;color:var(--txt3);width:46px;text-align:right">${f.importance.toFixed(4)}</span></div>`).join('');
|
| 686 |
+
}
|
| 687 |
+
|
| 688 |
+
function explainRandom(){
|
| 689 |
+
const fraud=Math.random()<.35;
|
| 690 |
+
const feats=['V14','V4','V12','V10','V17','V3','V11','V16','V7','Amount'];
|
| 691 |
+
const shapVals=fraud?[.35,.28,.18,.14,.12,-.05,-.04,.08,.07,.06]:[-.12,-.08,-.06,-.05,-.04,.08,.06,-.03,-.03,-.02];
|
| 692 |
+
const vals=fraud?[-7.2,5.1,-4.1,-3.3,-3.8,1.2,2.1,-1.9,-2.0,142]:[-.3,.1,.2,-.1,.0,.8,-.2,.3,-.1,1823];
|
| 693 |
+
const prob=fraud?(.65+Math.random()*.3):(.05+Math.random()*.2);
|
| 694 |
+
const color=fraud?'var(--red)':'var(--green)';
|
| 695 |
+
document.getElementById('localShap').innerHTML=`
|
| 696 |
+
<div style="display:flex;align-items:center;gap:14px;margin-bottom:16px;padding:14px;background:var(--bg2);border-radius:7px;border:1px solid ${fraud?'rgba(255,45,85,.3)':'rgba(0,255,136,.2)'}">
|
| 697 |
+
<div style="font-size:32px">${fraud?'β ':'β'}</div>
|
| 698 |
+
<div>
|
| 699 |
+
<div style="font-family:var(--display);font-size:14px;font-weight:900;color:${color}">${fraud?'FRAUD DETECTED':'TRANSACTION CLEAR'}</div>
|
| 700 |
+
<div style="font-family:var(--mono);font-size:9px;color:var(--txt3)">Fraud Probability: ${(prob*100).toFixed(1)}% β’ Amount: βΉ${vals[9].toFixed(2)}</div>
|
| 701 |
+
</div>
|
| 702 |
+
<div style="margin-left:auto;text-align:right">
|
| 703 |
+
<div style="font-family:var(--display);font-size:24px;font-weight:900;color:${color}">${(prob*100).toFixed(1)}%</div>
|
| 704 |
+
<div style="font-family:var(--mono);font-size:8px;color:var(--txt3)">FRAUD SCORE</div>
|
| 705 |
+
</div>
|
| 706 |
+
</div>
|
| 707 |
+
<div style="font-family:var(--mono);font-size:8px;color:var(--txt3);letter-spacing:2px;margin-bottom:10px">FEATURE CONTRIBUTIONS</div>
|
| 708 |
+
${feats.map((f,i)=>{ const sv=shapVals[i]*(0.8+Math.random()*.4); const pct=Math.min(Math.abs(sv)/.4*50,50); return `<div class="shap-row"><span class="shap-f">${f}</span><div class="shap-bc"><div class="${sv>0?'shap-pos':'shap-neg'}" style="width:${pct}%"></div></div><span class="shap-v" style="color:${sv>0?'var(--red)':'var(--cyan)'}">${sv>0?'+':''}${sv.toFixed(4)}</span></div>`; }).join('')}
|
| 709 |
+
<div style="margin-top:14px;font-family:var(--mono);font-size:9px;color:var(--txt3);padding:10px;background:var(--bg2);border-radius:5px;line-height:1.8">
|
| 710 |
+
${fraud?`<span style="color:var(--red)">β FRAUD:</span> Primarily flagged due to V14 (${vals[0].toFixed(2)}) β highly negative, strong fraud signal. Combined with elevated V4 and V12, model is confident.`:`<span style="color:var(--green)">β LEGIT:</span> V14 and key features are within normal ranges. High amount (βΉ${vals[9].toFixed(0)}) is not suspicious given normal feature pattern.`}
|
| 711 |
+
</div>`;
|
| 712 |
+
}
|
| 713 |
+
|
| 714 |
+
// ββ Init βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 715 |
+
loadOverview();
|
| 716 |
+
</script>
|
| 717 |
+
</body>
|
| 718 |
+
</html>
|
model/amount_scaler.pkl
ADDED
|
Binary file (927 Bytes). View file
|
|
|
model/feature_names.pkl
ADDED
|
Binary file (184 Bytes). View file
|
|
|
model/test_sample.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
notebooks/01_eda_and_training.ipynb
ADDED
|
@@ -0,0 +1,436 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"# π Real-Time Fraud Detection β EDA & Model Training\n",
|
| 8 |
+
"**Dataset**: [Kaggle Credit Card Fraud](https://www.kaggle.com/datasets/mlg-ulb/creditcardfraud) \n",
|
| 9 |
+
"**Model**: XGBoost with SMOTE + SHAP Explainability"
|
| 10 |
+
]
|
| 11 |
+
},
|
| 12 |
+
{
|
| 13 |
+
"cell_type": "markdown",
|
| 14 |
+
"metadata": {},
|
| 15 |
+
"source": ["## 1οΈβ£ Imports & Setup"]
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"execution_count": null,
|
| 20 |
+
"metadata": {},
|
| 21 |
+
"outputs": [],
|
| 22 |
+
"source": [
|
| 23 |
+
"import pandas as pd\n",
|
| 24 |
+
"import numpy as np\n",
|
| 25 |
+
"import matplotlib.pyplot as plt\n",
|
| 26 |
+
"import seaborn as sns\n",
|
| 27 |
+
"import warnings\n",
|
| 28 |
+
"warnings.filterwarnings('ignore')\n",
|
| 29 |
+
"\n",
|
| 30 |
+
"from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n",
|
| 31 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 32 |
+
"from sklearn.metrics import (classification_report, confusion_matrix,\n",
|
| 33 |
+
" roc_auc_score, precision_recall_curve,\n",
|
| 34 |
+
" average_precision_score, f1_score)\n",
|
| 35 |
+
"from imblearn.over_sampling import SMOTE\n",
|
| 36 |
+
"from xgboost import XGBClassifier\n",
|
| 37 |
+
"import shap\n",
|
| 38 |
+
"import joblib\n",
|
| 39 |
+
"import os\n",
|
| 40 |
+
"\n",
|
| 41 |
+
"sns.set_theme(style='whitegrid')\n",
|
| 42 |
+
"plt.rcParams['figure.figsize'] = (10, 5)\n",
|
| 43 |
+
"print('β
Libraries loaded!')"
|
| 44 |
+
]
|
| 45 |
+
},
|
| 46 |
+
{
|
| 47 |
+
"cell_type": "markdown",
|
| 48 |
+
"metadata": {},
|
| 49 |
+
"source": ["## 2οΈβ£ Load Dataset\n", "> Download from: https://www.kaggle.com/datasets/mlg-ulb/creditcardfraud \n", "> Place `creditcard.csv` in the `data/` folder"]
|
| 50 |
+
},
|
| 51 |
+
{
|
| 52 |
+
"cell_type": "code",
|
| 53 |
+
"execution_count": null,
|
| 54 |
+
"metadata": {},
|
| 55 |
+
"outputs": [],
|
| 56 |
+
"source": [
|
| 57 |
+
"DATA_PATH = '../data/creditcard.csv'\n",
|
| 58 |
+
"\n",
|
| 59 |
+
"# ββ If you don't have the file yet, generate synthetic sample data ββ\n",
|
| 60 |
+
"if not os.path.exists(DATA_PATH):\n",
|
| 61 |
+
" print('β οΈ creditcard.csv not found β generating synthetic demo data...')\n",
|
| 62 |
+
" np.random.seed(42)\n",
|
| 63 |
+
" n = 10000\n",
|
| 64 |
+
" # 28 PCA features V1βV28 + Time + Amount + Class\n",
|
| 65 |
+
" V_cols = {f'V{i}': np.random.randn(n) for i in range(1, 29)}\n",
|
| 66 |
+
" df = pd.DataFrame(V_cols)\n",
|
| 67 |
+
" df['Time'] = np.random.uniform(0, 172800, n)\n",
|
| 68 |
+
" df['Amount'] = np.abs(np.random.exponential(88, n))\n",
|
| 69 |
+
" # Inject 2% fraud β make frauds slightly separable\n",
|
| 70 |
+
" fraud_idx = np.random.choice(n, size=200, replace=False)\n",
|
| 71 |
+
" df['Class'] = 0\n",
|
| 72 |
+
" df.loc[fraud_idx, 'Class'] = 1\n",
|
| 73 |
+
" df.loc[fraud_idx, 'V1'] -= 3\n",
|
| 74 |
+
" df.loc[fraud_idx, 'V3'] += 2\n",
|
| 75 |
+
" df.to_csv(DATA_PATH, index=False)\n",
|
| 76 |
+
" print(f'β
Synthetic data saved β {DATA_PATH}')\n",
|
| 77 |
+
"\n",
|
| 78 |
+
"df = pd.read_csv(DATA_PATH)\n",
|
| 79 |
+
"print(f'Shape: {df.shape}')\n",
|
| 80 |
+
"df.head()"
|
| 81 |
+
]
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
"cell_type": "markdown",
|
| 85 |
+
"metadata": {},
|
| 86 |
+
"source": ["## 3οΈβ£ Exploratory Data Analysis"]
|
| 87 |
+
},
|
| 88 |
+
{
|
| 89 |
+
"cell_type": "code",
|
| 90 |
+
"execution_count": null,
|
| 91 |
+
"metadata": {},
|
| 92 |
+
"outputs": [],
|
| 93 |
+
"source": [
|
| 94 |
+
"# ββ Basic Info ββ\n",
|
| 95 |
+
"print('=== Dataset Info ===')\n",
|
| 96 |
+
"print(f'Total transactions : {len(df):,}')\n",
|
| 97 |
+
"print(f'Fraudulent : {df[\"Class\"].sum():,} ({df[\"Class\"].mean()*100:.3f}%)')\n",
|
| 98 |
+
"print(f'Legitimate : {(df[\"Class\"]==0).sum():,}')\n",
|
| 99 |
+
"print(f'Missing values : {df.isnull().sum().sum()}')\n",
|
| 100 |
+
"print()\n",
|
| 101 |
+
"df.describe()"
|
| 102 |
+
]
|
| 103 |
+
},
|
| 104 |
+
{
|
| 105 |
+
"cell_type": "code",
|
| 106 |
+
"execution_count": null,
|
| 107 |
+
"metadata": {},
|
| 108 |
+
"outputs": [],
|
| 109 |
+
"source": [
|
| 110 |
+
"# ββ Class Imbalance ββ\n",
|
| 111 |
+
"fig, axes = plt.subplots(1, 2, figsize=(12, 4))\n",
|
| 112 |
+
"\n",
|
| 113 |
+
"# Pie chart\n",
|
| 114 |
+
"counts = df['Class'].value_counts()\n",
|
| 115 |
+
"axes[0].pie(counts, labels=['Legitimate', 'Fraud'], autopct='%1.2f%%',\n",
|
| 116 |
+
" colors=['#4CAF50', '#F44336'], startangle=90,\n",
|
| 117 |
+
" wedgeprops=dict(edgecolor='white', linewidth=2))\n",
|
| 118 |
+
"axes[0].set_title('Class Distribution', fontsize=14, fontweight='bold')\n",
|
| 119 |
+
"\n",
|
| 120 |
+
"# Amount distribution by class\n",
|
| 121 |
+
"df[df['Class']==0]['Amount'].hist(bins=60, ax=axes[1], alpha=0.6, color='#4CAF50', label='Legitimate')\n",
|
| 122 |
+
"df[df['Class']==1]['Amount'].hist(bins=60, ax=axes[1], alpha=0.7, color='#F44336', label='Fraud')\n",
|
| 123 |
+
"axes[1].set_xlabel('Transaction Amount (β¬)')\n",
|
| 124 |
+
"axes[1].set_ylabel('Frequency')\n",
|
| 125 |
+
"axes[1].set_title('Amount Distribution by Class', fontsize=14, fontweight='bold')\n",
|
| 126 |
+
"axes[1].legend()\n",
|
| 127 |
+
"axes[1].set_xlim(0, 1000)\n",
|
| 128 |
+
"\n",
|
| 129 |
+
"plt.tight_layout()\n",
|
| 130 |
+
"plt.savefig('../data/eda_class_distribution.png', dpi=120, bbox_inches='tight')\n",
|
| 131 |
+
"plt.show()\n",
|
| 132 |
+
"print('π‘ Key Insight: Massive class imbalance β need SMOTE!')"
|
| 133 |
+
]
|
| 134 |
+
},
|
| 135 |
+
{
|
| 136 |
+
"cell_type": "code",
|
| 137 |
+
"execution_count": null,
|
| 138 |
+
"metadata": {},
|
| 139 |
+
"outputs": [],
|
| 140 |
+
"source": [
|
| 141 |
+
"# ββ Feature Correlation with Fraud ββ\n",
|
| 142 |
+
"correlations = df.corr()['Class'].drop('Class').sort_values()\n",
|
| 143 |
+
"\n",
|
| 144 |
+
"fig, ax = plt.subplots(figsize=(12, 6))\n",
|
| 145 |
+
"colors = ['#F44336' if x > 0 else '#2196F3' for x in correlations]\n",
|
| 146 |
+
"correlations.plot(kind='bar', ax=ax, color=colors, edgecolor='white', linewidth=0.5)\n",
|
| 147 |
+
"ax.axhline(0, color='black', linewidth=0.8)\n",
|
| 148 |
+
"ax.set_title('Feature Correlation with Fraud Class', fontsize=14, fontweight='bold')\n",
|
| 149 |
+
"ax.set_xlabel('Feature')\n",
|
| 150 |
+
"ax.set_ylabel('Pearson Correlation')\n",
|
| 151 |
+
"plt.xticks(rotation=45, ha='right')\n",
|
| 152 |
+
"plt.tight_layout()\n",
|
| 153 |
+
"plt.savefig('../data/eda_correlations.png', dpi=120, bbox_inches='tight')\n",
|
| 154 |
+
"plt.show()\n",
|
| 155 |
+
"print('Top positive correlations (fraud indicators):')\n",
|
| 156 |
+
"print(correlations.tail(5))"
|
| 157 |
+
]
|
| 158 |
+
},
|
| 159 |
+
{
|
| 160 |
+
"cell_type": "code",
|
| 161 |
+
"execution_count": null,
|
| 162 |
+
"metadata": {},
|
| 163 |
+
"outputs": [],
|
| 164 |
+
"source": [
|
| 165 |
+
"# ββ Top features violin plots ββ\n",
|
| 166 |
+
"top_features = correlations.abs().sort_values(ascending=False).index[:6].tolist()\n",
|
| 167 |
+
"\n",
|
| 168 |
+
"fig, axes = plt.subplots(2, 3, figsize=(14, 8))\n",
|
| 169 |
+
"axes = axes.flatten()\n",
|
| 170 |
+
"\n",
|
| 171 |
+
"for i, feat in enumerate(top_features):\n",
|
| 172 |
+
" data_plot = [\n",
|
| 173 |
+
" df[df['Class']==0][feat].values,\n",
|
| 174 |
+
" df[df['Class']==1][feat].values\n",
|
| 175 |
+
" ]\n",
|
| 176 |
+
" parts = axes[i].violinplot(data_plot, showmedians=True)\n",
|
| 177 |
+
" for j, pc in enumerate(parts['bodies']):\n",
|
| 178 |
+
" pc.set_facecolor('#4CAF50' if j==0 else '#F44336')\n",
|
| 179 |
+
" pc.set_alpha(0.7)\n",
|
| 180 |
+
" axes[i].set_title(feat, fontsize=12, fontweight='bold')\n",
|
| 181 |
+
" axes[i].set_xticks([1, 2])\n",
|
| 182 |
+
" axes[i].set_xticklabels(['Legit', 'Fraud'])\n",
|
| 183 |
+
" axes[i].set_ylabel('Value')\n",
|
| 184 |
+
"\n",
|
| 185 |
+
"plt.suptitle('Top Feature Distributions: Legit vs Fraud', fontsize=14, fontweight='bold', y=1.01)\n",
|
| 186 |
+
"plt.tight_layout()\n",
|
| 187 |
+
"plt.savefig('../data/eda_violin.png', dpi=120, bbox_inches='tight')\n",
|
| 188 |
+
"plt.show()"
|
| 189 |
+
]
|
| 190 |
+
},
|
| 191 |
+
{
|
| 192 |
+
"cell_type": "markdown",
|
| 193 |
+
"metadata": {},
|
| 194 |
+
"source": ["## 4οΈβ£ Feature Engineering & Preprocessing"]
|
| 195 |
+
},
|
| 196 |
+
{
|
| 197 |
+
"cell_type": "code",
|
| 198 |
+
"execution_count": null,
|
| 199 |
+
"metadata": {},
|
| 200 |
+
"outputs": [],
|
| 201 |
+
"source": [
|
| 202 |
+
"# ββ Scale Amount (Time is dropped β not predictive) ββ\n",
|
| 203 |
+
"df_processed = df.drop(columns=['Time']).copy()\n",
|
| 204 |
+
"\n",
|
| 205 |
+
"scaler = StandardScaler()\n",
|
| 206 |
+
"df_processed['Amount'] = scaler.fit_transform(df_processed[['Amount']])\n",
|
| 207 |
+
"\n",
|
| 208 |
+
"X = df_processed.drop('Class', axis=1)\n",
|
| 209 |
+
"y = df_processed['Class']\n",
|
| 210 |
+
"\n",
|
| 211 |
+
"print(f'Features: {X.shape[1]}')\n",
|
| 212 |
+
"print(f'Class balance before SMOTE: {y.value_counts().to_dict()}')"
|
| 213 |
+
]
|
| 214 |
+
},
|
| 215 |
+
{
|
| 216 |
+
"cell_type": "code",
|
| 217 |
+
"execution_count": null,
|
| 218 |
+
"metadata": {},
|
| 219 |
+
"outputs": [],
|
| 220 |
+
"source": [
|
| 221 |
+
"# ββ Train/Test Split ββ\n",
|
| 222 |
+
"X_train, X_test, y_train, y_test = train_test_split(\n",
|
| 223 |
+
" X, y, test_size=0.2, random_state=42, stratify=y\n",
|
| 224 |
+
")\n",
|
| 225 |
+
"\n",
|
| 226 |
+
"# ββ Apply SMOTE on training set only ββ\n",
|
| 227 |
+
"smote = SMOTE(random_state=42)\n",
|
| 228 |
+
"X_train_res, y_train_res = smote.fit_resample(X_train, y_train)\n",
|
| 229 |
+
"\n",
|
| 230 |
+
"print(f'Before SMOTE β Train: {dict(pd.Series(y_train).value_counts())}')\n",
|
| 231 |
+
"print(f'After SMOTE β Train: {dict(pd.Series(y_train_res).value_counts())}')\n",
|
| 232 |
+
"print(f'Test set (no SMOTE): {dict(pd.Series(y_test).value_counts())}')"
|
| 233 |
+
]
|
| 234 |
+
},
|
| 235 |
+
{
|
| 236 |
+
"cell_type": "markdown",
|
| 237 |
+
"metadata": {},
|
| 238 |
+
"source": ["## 5οΈβ£ Model Training β XGBoost"]
|
| 239 |
+
},
|
| 240 |
+
{
|
| 241 |
+
"cell_type": "code",
|
| 242 |
+
"execution_count": null,
|
| 243 |
+
"metadata": {},
|
| 244 |
+
"outputs": [],
|
| 245 |
+
"source": [
|
| 246 |
+
"# ββ Train XGBoost ββ\n",
|
| 247 |
+
"model = XGBClassifier(\n",
|
| 248 |
+
" n_estimators=300,\n",
|
| 249 |
+
" max_depth=6,\n",
|
| 250 |
+
" learning_rate=0.05,\n",
|
| 251 |
+
" subsample=0.8,\n",
|
| 252 |
+
" colsample_bytree=0.8,\n",
|
| 253 |
+
" min_child_weight=1,\n",
|
| 254 |
+
" gamma=0.1,\n",
|
| 255 |
+
" reg_alpha=0.1,\n",
|
| 256 |
+
" reg_lambda=1,\n",
|
| 257 |
+
" use_label_encoder=False,\n",
|
| 258 |
+
" eval_metric='logloss',\n",
|
| 259 |
+
" random_state=42,\n",
|
| 260 |
+
" n_jobs=-1\n",
|
| 261 |
+
")\n",
|
| 262 |
+
"\n",
|
| 263 |
+
"model.fit(\n",
|
| 264 |
+
" X_train_res, y_train_res,\n",
|
| 265 |
+
" eval_set=[(X_test, y_test)],\n",
|
| 266 |
+
" verbose=50\n",
|
| 267 |
+
")\n",
|
| 268 |
+
"print('\\nβ
Model trained!')"
|
| 269 |
+
]
|
| 270 |
+
},
|
| 271 |
+
{
|
| 272 |
+
"cell_type": "markdown",
|
| 273 |
+
"metadata": {},
|
| 274 |
+
"source": ["## 6οΈβ£ Model Evaluation"]
|
| 275 |
+
},
|
| 276 |
+
{
|
| 277 |
+
"cell_type": "code",
|
| 278 |
+
"execution_count": null,
|
| 279 |
+
"metadata": {},
|
| 280 |
+
"outputs": [],
|
| 281 |
+
"source": [
|
| 282 |
+
"# ββ Predictions ββ\n",
|
| 283 |
+
"y_pred = model.predict(X_test)\n",
|
| 284 |
+
"y_pred_proba = model.predict_proba(X_test)[:, 1]\n",
|
| 285 |
+
"\n",
|
| 286 |
+
"# ββ Metrics ββ\n",
|
| 287 |
+
"print('=== Classification Report ===')\n",
|
| 288 |
+
"print(classification_report(y_test, y_pred, target_names=['Legit', 'Fraud']))\n",
|
| 289 |
+
"\n",
|
| 290 |
+
"roc_auc = roc_auc_score(y_test, y_pred_proba)\n",
|
| 291 |
+
"pr_auc = average_precision_score(y_test, y_pred_proba)\n",
|
| 292 |
+
"f1 = f1_score(y_test, y_pred)\n",
|
| 293 |
+
"print(f'ROC-AUC Score : {roc_auc:.4f}')\n",
|
| 294 |
+
"print(f'PR-AUC Score : {pr_auc:.4f}')\n",
|
| 295 |
+
"print(f'F1 Score (Fraud) : {f1:.4f}')"
|
| 296 |
+
]
|
| 297 |
+
},
|
| 298 |
+
{
|
| 299 |
+
"cell_type": "code",
|
| 300 |
+
"execution_count": null,
|
| 301 |
+
"metadata": {},
|
| 302 |
+
"outputs": [],
|
| 303 |
+
"source": [
|
| 304 |
+
"# ββ Confusion Matrix ββ\n",
|
| 305 |
+
"fig, axes = plt.subplots(1, 2, figsize=(12, 5))\n",
|
| 306 |
+
"\n",
|
| 307 |
+
"cm = confusion_matrix(y_test, y_pred)\n",
|
| 308 |
+
"sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',\n",
|
| 309 |
+
" xticklabels=['Legit', 'Fraud'],\n",
|
| 310 |
+
" yticklabels=['Legit', 'Fraud'], ax=axes[0],\n",
|
| 311 |
+
" linewidths=1, linecolor='white')\n",
|
| 312 |
+
"axes[0].set_title('Confusion Matrix', fontsize=13, fontweight='bold')\n",
|
| 313 |
+
"axes[0].set_ylabel('Actual')\n",
|
| 314 |
+
"axes[0].set_xlabel('Predicted')\n",
|
| 315 |
+
"\n",
|
| 316 |
+
"# Precision-Recall Curve\n",
|
| 317 |
+
"precision, recall, thresholds = precision_recall_curve(y_test, y_pred_proba)\n",
|
| 318 |
+
"axes[1].plot(recall, precision, color='#E91E63', linewidth=2.5, label=f'PR-AUC = {pr_auc:.4f}')\n",
|
| 319 |
+
"axes[1].fill_between(recall, precision, alpha=0.1, color='#E91E63')\n",
|
| 320 |
+
"axes[1].set_xlabel('Recall')\n",
|
| 321 |
+
"axes[1].set_ylabel('Precision')\n",
|
| 322 |
+
"axes[1].set_title('Precision-Recall Curve', fontsize=13, fontweight='bold')\n",
|
| 323 |
+
"axes[1].legend(fontsize=12)\n",
|
| 324 |
+
"axes[1].grid(True, alpha=0.3)\n",
|
| 325 |
+
"\n",
|
| 326 |
+
"plt.tight_layout()\n",
|
| 327 |
+
"plt.savefig('../data/evaluation_plots.png', dpi=120, bbox_inches='tight')\n",
|
| 328 |
+
"plt.show()"
|
| 329 |
+
]
|
| 330 |
+
},
|
| 331 |
+
{
|
| 332 |
+
"cell_type": "markdown",
|
| 333 |
+
"metadata": {},
|
| 334 |
+
"source": ["## 7οΈβ£ SHAP Explainability"]
|
| 335 |
+
},
|
| 336 |
+
{
|
| 337 |
+
"cell_type": "code",
|
| 338 |
+
"execution_count": null,
|
| 339 |
+
"metadata": {},
|
| 340 |
+
"outputs": [],
|
| 341 |
+
"source": [
|
| 342 |
+
"# ββ Compute SHAP Values ββ\n",
|
| 343 |
+
"print('Computing SHAP values...')\n",
|
| 344 |
+
"explainer = shap.TreeExplainer(model)\n",
|
| 345 |
+
"shap_values = explainer.shap_values(X_test)\n",
|
| 346 |
+
"\n",
|
| 347 |
+
"# ββ Global Feature Importance ββ\n",
|
| 348 |
+
"plt.figure(figsize=(10, 7))\n",
|
| 349 |
+
"shap.summary_plot(shap_values, X_test, plot_type='bar', show=False)\n",
|
| 350 |
+
"plt.title('SHAP Global Feature Importance', fontsize=14, fontweight='bold')\n",
|
| 351 |
+
"plt.tight_layout()\n",
|
| 352 |
+
"plt.savefig('../data/shap_importance.png', dpi=120, bbox_inches='tight')\n",
|
| 353 |
+
"plt.show()"
|
| 354 |
+
]
|
| 355 |
+
},
|
| 356 |
+
{
|
| 357 |
+
"cell_type": "code",
|
| 358 |
+
"execution_count": null,
|
| 359 |
+
"metadata": {},
|
| 360 |
+
"outputs": [],
|
| 361 |
+
"source": [
|
| 362 |
+
"# ββ SHAP Beeswarm (how each feature affects fraud score) ββ\n",
|
| 363 |
+
"plt.figure(figsize=(10, 8))\n",
|
| 364 |
+
"shap.summary_plot(shap_values, X_test, show=False)\n",
|
| 365 |
+
"plt.title('SHAP Summary β Feature Impact on Fraud Probability', fontsize=13, fontweight='bold')\n",
|
| 366 |
+
"plt.tight_layout()\n",
|
| 367 |
+
"plt.savefig('../data/shap_beeswarm.png', dpi=120, bbox_inches='tight')\n",
|
| 368 |
+
"plt.show()"
|
| 369 |
+
]
|
| 370 |
+
},
|
| 371 |
+
{
|
| 372 |
+
"cell_type": "code",
|
| 373 |
+
"execution_count": null,
|
| 374 |
+
"metadata": {},
|
| 375 |
+
"outputs": [],
|
| 376 |
+
"source": [
|
| 377 |
+
"# ββ SHAP Waterfall for ONE fraud case (explainability for single transaction) ββ\n",
|
| 378 |
+
"fraud_indices = np.where(y_test == 1)[0]\n",
|
| 379 |
+
"if len(fraud_indices) > 0:\n",
|
| 380 |
+
" sample_idx = fraud_indices[0]\n",
|
| 381 |
+
" print(f'Explaining fraud transaction at test index: {sample_idx}')\n",
|
| 382 |
+
" explanation = explainer(X_test.iloc[[sample_idx]])\n",
|
| 383 |
+
" plt.figure(figsize=(10, 6))\n",
|
| 384 |
+
" shap.waterfall_plot(explanation[0], show=False)\n",
|
| 385 |
+
" plt.title('Why was this transaction flagged as FRAUD?', fontsize=13, fontweight='bold')\n",
|
| 386 |
+
" plt.tight_layout()\n",
|
| 387 |
+
" plt.savefig('../data/shap_waterfall_fraud.png', dpi=120, bbox_inches='tight')\n",
|
| 388 |
+
" plt.show()"
|
| 389 |
+
]
|
| 390 |
+
},
|
| 391 |
+
{
|
| 392 |
+
"cell_type": "markdown",
|
| 393 |
+
"metadata": {},
|
| 394 |
+
"source": ["## 8οΈβ£ Save Model Artifacts"]
|
| 395 |
+
},
|
| 396 |
+
{
|
| 397 |
+
"cell_type": "code",
|
| 398 |
+
"execution_count": null,
|
| 399 |
+
"metadata": {},
|
| 400 |
+
"outputs": [],
|
| 401 |
+
"source": [
|
| 402 |
+
"os.makedirs('../model', exist_ok=True)\n",
|
| 403 |
+
"\n",
|
| 404 |
+
"# Save model\n",
|
| 405 |
+
"joblib.dump(model, '../model/xgb_fraud_model.pkl')\n",
|
| 406 |
+
"# Save scaler\n",
|
| 407 |
+
"joblib.dump(scaler, '../model/amount_scaler.pkl')\n",
|
| 408 |
+
"# Save feature names\n",
|
| 409 |
+
"joblib.dump(list(X.columns), '../model/feature_names.pkl')\n",
|
| 410 |
+
"# Save test sample for demo\n",
|
| 411 |
+
"X_test.to_csv('../model/test_sample.csv', index=False)\n",
|
| 412 |
+
"\n",
|
| 413 |
+
"print('β
Model artifacts saved:')\n",
|
| 414 |
+
"print(' β model/xgb_fraud_model.pkl')\n",
|
| 415 |
+
"print(' β model/amount_scaler.pkl')\n",
|
| 416 |
+
"print(' β model/feature_names.pkl')\n",
|
| 417 |
+
"print(' β model/test_sample.csv')\n",
|
| 418 |
+
"print(f'\\nFinal ROC-AUC: {roc_auc:.4f}')\n",
|
| 419 |
+
"print(f'Final PR-AUC : {pr_auc:.4f}')"
|
| 420 |
+
]
|
| 421 |
+
}
|
| 422 |
+
],
|
| 423 |
+
"metadata": {
|
| 424 |
+
"kernelspec": {
|
| 425 |
+
"display_name": "Python 3",
|
| 426 |
+
"language": "python",
|
| 427 |
+
"name": "python3"
|
| 428 |
+
},
|
| 429 |
+
"language_info": {
|
| 430 |
+
"name": "python",
|
| 431 |
+
"version": "3.10.0"
|
| 432 |
+
}
|
| 433 |
+
},
|
| 434 |
+
"nbformat": 4,
|
| 435 |
+
"nbformat_minor": 5
|
| 436 |
+
}
|
notebooks/creditcard.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
requirements.txt
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Core ML
|
| 2 |
+
pandas==2.1.4
|
| 3 |
+
numpy==1.26.2
|
| 4 |
+
scikit-learn==1.3.2
|
| 5 |
+
xgboost==2.0.3
|
| 6 |
+
imbalanced-learn==0.11.0
|
| 7 |
+
joblib==1.3.2
|
| 8 |
+
|
| 9 |
+
# Explainability
|
| 10 |
+
shap==0.44.1
|
| 11 |
+
|
| 12 |
+
# API
|
| 13 |
+
fastapi==0.108.0
|
| 14 |
+
uvicorn==0.25.0
|
| 15 |
+
pydantic==2.5.3
|
| 16 |
+
|
| 17 |
+
# Kafka simulation
|
| 18 |
+
kafka-python==2.0.2
|
| 19 |
+
|
| 20 |
+
# Dashboard
|
| 21 |
+
streamlit==1.29.0
|
| 22 |
+
plotly==5.18.0
|
| 23 |
+
requests==2.31.0
|
| 24 |
+
|
| 25 |
+
# Notebook
|
| 26 |
+
jupyter==1.0.0
|
| 27 |
+
matplotlib==3.8.2
|
| 28 |
+
seaborn==0.13.0
|
stream/consumer.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Kafka Consumer β Reads live transactions and scores them via FastAPI
|
| 3 |
+
Logs fraud alerts in real time
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import json
|
| 7 |
+
import time
|
| 8 |
+
import requests
|
| 9 |
+
from kafka import KafkaConsumer
|
| 10 |
+
import logging
|
| 11 |
+
|
| 12 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s | %(message)s')
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
KAFKA_BROKER = "localhost:9092"
|
| 16 |
+
TOPIC = "transactions"
|
| 17 |
+
API_URL = "http://localhost:8000/predict"
|
| 18 |
+
GROUP_ID = "fraud-detection-group"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def score_transaction(txn: dict) -> dict | None:
|
| 22 |
+
"""Call FastAPI scoring endpoint for a single transaction"""
|
| 23 |
+
payload = {k: v for k, v in txn.items()
|
| 24 |
+
if k.startswith("V") or k == "Amount"}
|
| 25 |
+
try:
|
| 26 |
+
resp = requests.post(API_URL, json=payload, timeout=2)
|
| 27 |
+
return resp.json() if resp.status_code == 200 else None
|
| 28 |
+
except Exception as e:
|
| 29 |
+
logger.error(f"API call failed: {e}")
|
| 30 |
+
return None
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def main():
|
| 34 |
+
logger.info(f"Connecting to Kafka broker at {KAFKA_BROKER}...")
|
| 35 |
+
try:
|
| 36 |
+
consumer = KafkaConsumer(
|
| 37 |
+
TOPIC,
|
| 38 |
+
bootstrap_servers=[KAFKA_BROKER],
|
| 39 |
+
group_id=GROUP_ID,
|
| 40 |
+
value_deserializer=lambda m: json.loads(m.decode("utf-8")),
|
| 41 |
+
auto_offset_reset="latest",
|
| 42 |
+
enable_auto_commit=True
|
| 43 |
+
)
|
| 44 |
+
logger.info(f"β
Listening on topic: [{TOPIC}]")
|
| 45 |
+
except Exception as e:
|
| 46 |
+
logger.error(f"β Cannot connect to Kafka: {e}")
|
| 47 |
+
return
|
| 48 |
+
|
| 49 |
+
total = fraud = 0
|
| 50 |
+
try:
|
| 51 |
+
for msg in consumer:
|
| 52 |
+
txn = msg.value
|
| 53 |
+
result = score_transaction(txn)
|
| 54 |
+
|
| 55 |
+
total += 1
|
| 56 |
+
if result and result.get("is_fraud"):
|
| 57 |
+
fraud += 1
|
| 58 |
+
logger.warning(
|
| 59 |
+
f"π¨ FRAUD ALERT! | TXN: {result['transaction_id']} "
|
| 60 |
+
f"| Prob: {result['fraud_probability']:.1%} "
|
| 61 |
+
f"| Risk: {result['risk_level']} "
|
| 62 |
+
f"| Amount: ${txn.get('Amount', 0):.2f}"
|
| 63 |
+
)
|
| 64 |
+
logger.warning(
|
| 65 |
+
f" Top factor: {result['top_risk_factors'][0]['feature']} "
|
| 66 |
+
f"(SHAP={result['top_risk_factors'][0]['shap_value']})"
|
| 67 |
+
)
|
| 68 |
+
else:
|
| 69 |
+
if total % 10 == 0: # log every 10th legit
|
| 70 |
+
logger.info(f"β
LEGIT | Total processed: {total} | Frauds caught: {fraud}")
|
| 71 |
+
|
| 72 |
+
except KeyboardInterrupt:
|
| 73 |
+
logger.info(f"\nβ Stopped. Total={total} | Frauds={fraud} | Rate={fraud/max(total,1)*100:.1f}%")
|
| 74 |
+
consumer.close()
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
if __name__ == "__main__":
|
| 78 |
+
main()
|
stream/producer.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Kafka Producer β Simulates a real-time transaction stream
|
| 3 |
+
Sends random transactions (some seeded as fraud) to the Kafka topic 'transactions'
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import json
|
| 7 |
+
import time
|
| 8 |
+
import random
|
| 9 |
+
import numpy as np
|
| 10 |
+
from kafka import KafkaProducer
|
| 11 |
+
import logging
|
| 12 |
+
|
| 13 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s | %(message)s')
|
| 14 |
+
logger = logging.getLogger(__name__)
|
| 15 |
+
|
| 16 |
+
KAFKA_BROKER = "localhost:9092"
|
| 17 |
+
TOPIC = "transactions"
|
| 18 |
+
SEND_RATE_SEC = 0.5 # one transaction every 0.5s
|
| 19 |
+
FRAUD_RATE = 0.05 # 5% of messages are fraud-like
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def generate_transaction(force_fraud: bool = False) -> dict:
|
| 23 |
+
"""Generate a synthetic transaction matching creditcard.csv schema"""
|
| 24 |
+
np.random.seed(None)
|
| 25 |
+
|
| 26 |
+
if force_fraud:
|
| 27 |
+
# Fraud fingerprint β V1 very negative, high V3
|
| 28 |
+
txn = {f"V{i}": np.random.randn() for i in range(1, 29)}
|
| 29 |
+
txn["V1"] -= random.uniform(2, 5)
|
| 30 |
+
txn["V3"] += random.uniform(2, 4)
|
| 31 |
+
txn["V14"] -= random.uniform(2, 4)
|
| 32 |
+
txn["Amount"] = random.uniform(1, 50) # small amounts typical in fraud
|
| 33 |
+
else:
|
| 34 |
+
txn = {f"V{i}": np.random.randn() for i in range(1, 29)}
|
| 35 |
+
txn["Amount"] = abs(np.random.exponential(88))
|
| 36 |
+
|
| 37 |
+
# Round to 4 dp
|
| 38 |
+
txn = {k: round(float(v), 4) for k, v in txn.items()}
|
| 39 |
+
txn["timestamp"] = time.time()
|
| 40 |
+
txn["is_simulated_fraud"] = force_fraud # ground-truth label for evaluation
|
| 41 |
+
return txn
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def on_send_success(metadata):
|
| 45 |
+
logger.info(f"β
Sent to [{metadata.topic}] partition={metadata.partition} offset={metadata.offset}")
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def on_send_error(exc):
|
| 49 |
+
logger.error(f"β Send failed: {exc}")
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def main():
|
| 53 |
+
logger.info(f"Connecting to Kafka broker at {KAFKA_BROKER}...")
|
| 54 |
+
try:
|
| 55 |
+
producer = KafkaProducer(
|
| 56 |
+
bootstrap_servers=[KAFKA_BROKER],
|
| 57 |
+
value_serializer=lambda v: json.dumps(v).encode("utf-8"),
|
| 58 |
+
acks="all",
|
| 59 |
+
retries=3
|
| 60 |
+
)
|
| 61 |
+
logger.info(f"β
Connected! Streaming to topic: [{TOPIC}]")
|
| 62 |
+
except Exception as e:
|
| 63 |
+
logger.error(f"β Cannot connect to Kafka: {e}")
|
| 64 |
+
logger.info("π‘ Start Kafka first:\n docker-compose up kafka zookeeper")
|
| 65 |
+
return
|
| 66 |
+
|
| 67 |
+
count = 0
|
| 68 |
+
try:
|
| 69 |
+
while True:
|
| 70 |
+
is_fraud = random.random() < FRAUD_RATE
|
| 71 |
+
txn = generate_transaction(force_fraud=is_fraud)
|
| 72 |
+
|
| 73 |
+
producer.send(TOPIC, value=txn).add_callback(on_send_success).add_errback(on_send_error)
|
| 74 |
+
producer.flush()
|
| 75 |
+
|
| 76 |
+
count += 1
|
| 77 |
+
tag = "π¨ FRAUD" if is_fraud else "β
LEGIT"
|
| 78 |
+
logger.info(f"[#{count}] {tag} | Amount=${txn['Amount']:.2f}")
|
| 79 |
+
|
| 80 |
+
time.sleep(SEND_RATE_SEC)
|
| 81 |
+
|
| 82 |
+
except KeyboardInterrupt:
|
| 83 |
+
logger.info(f"\nβ Stopped. Total sent: {count}")
|
| 84 |
+
producer.close()
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
if __name__ == "__main__":
|
| 88 |
+
main()
|
utils.js
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const API_BASE = 'http://localhost:8000';
|
| 2 |
+
|
| 3 |
+
// ββ API helpers ββββββββββββββββββββββββββββββββββββββββββββ
|
| 4 |
+
async function apiFetch(path, options = {}) {
|
| 5 |
+
try {
|
| 6 |
+
const res = await fetch(API_BASE + path, options);
|
| 7 |
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
| 8 |
+
return await res.json();
|
| 9 |
+
} catch (e) {
|
| 10 |
+
console.error('API error:', e);
|
| 11 |
+
return null;
|
| 12 |
+
}
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
// ββ Clock βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 16 |
+
function startClock(el) {
|
| 17 |
+
function tick() {
|
| 18 |
+
const now = new Date();
|
| 19 |
+
el.textContent = now.toLocaleTimeString('en-IN', { hour12: false }) +
|
| 20 |
+
' IST';
|
| 21 |
+
}
|
| 22 |
+
tick();
|
| 23 |
+
setInterval(tick, 1000);
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
// ββ Format helpers βββββββββββββββββββββββββββββββββββββββββ
|
| 27 |
+
function fmtCurrency(n) {
|
| 28 |
+
if (n >= 1e6) return 'βΉ' + (n / 1e6).toFixed(2) + 'M';
|
| 29 |
+
if (n >= 1e3) return 'βΉ' + (n / 1e3).toFixed(1) + 'K';
|
| 30 |
+
return 'βΉ' + n.toFixed(2);
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
function fmtPct(n) { return (n * 100).toFixed(2) + '%'; }
|
| 34 |
+
|
| 35 |
+
function riskBadge(level) {
|
| 36 |
+
const map = { HIGH: 'badge-high', MEDIUM: 'badge-medium', LOW: 'badge-low' };
|
| 37 |
+
return `<span class="badge ${map[level] || 'badge-low'}">${level}</span>`;
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
function fraudBadge(isFraud) {
|
| 41 |
+
return isFraud
|
| 42 |
+
? `<span class="badge badge-fraud">β FRAUD</span>`
|
| 43 |
+
: `<span class="badge badge-legit">β LEGIT</span>`;
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
function probBar(prob) {
|
| 47 |
+
const pct = (prob * 100).toFixed(0);
|
| 48 |
+
const color = prob > 0.7 ? '#ff2d55' : prob > 0.4 ? '#ff9500' : '#00ff88';
|
| 49 |
+
return `<span class="prob-bar"><span class="prob-fill" style="width:${pct}%;background:${color}"></span></span>${pct}%`;
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
function timeAgo(ts) {
|
| 53 |
+
const diff = Math.floor((Date.now() - new Date(ts)) / 1000);
|
| 54 |
+
if (diff < 60) return diff + 's ago';
|
| 55 |
+
if (diff < 3600) return Math.floor(diff / 60) + 'm ago';
|
| 56 |
+
return Math.floor(diff / 3600) + 'h ago';
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
// ββ Sidebar active link βββββββββββββββββββββββββββββββββββ
|
| 60 |
+
function setActiveNav() {
|
| 61 |
+
const path = window.location.pathname;
|
| 62 |
+
document.querySelectorAll('.nav-item').forEach(a => {
|
| 63 |
+
a.classList.remove('active');
|
| 64 |
+
if (a.getAttribute('href') === path) a.classList.add('active');
|
| 65 |
+
});
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
// ββ Mini sparkline canvas βββββββββββββββββββββββββββββββββ
|
| 69 |
+
function drawSparkline(canvas, data, color = '#00d4ff') {
|
| 70 |
+
const ctx = canvas.getContext('2d');
|
| 71 |
+
const w = canvas.width, h = canvas.height;
|
| 72 |
+
const max = Math.max(...data), min = Math.min(...data);
|
| 73 |
+
const range = max - min || 1;
|
| 74 |
+
ctx.clearRect(0, 0, w, h);
|
| 75 |
+
ctx.beginPath();
|
| 76 |
+
data.forEach((v, i) => {
|
| 77 |
+
const x = (i / (data.length - 1)) * w;
|
| 78 |
+
const y = h - ((v - min) / range) * (h - 4) - 2;
|
| 79 |
+
i === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
|
| 80 |
+
});
|
| 81 |
+
ctx.strokeStyle = color;
|
| 82 |
+
ctx.lineWidth = 1.5;
|
| 83 |
+
ctx.stroke();
|
| 84 |
+
|
| 85 |
+
// Fill gradient
|
| 86 |
+
ctx.lineTo(w, h); ctx.lineTo(0, h); ctx.closePath();
|
| 87 |
+
const grad = ctx.createLinearGradient(0, 0, 0, h);
|
| 88 |
+
grad.addColorStop(0, color + '33');
|
| 89 |
+
grad.addColorStop(1, color + '00');
|
| 90 |
+
ctx.fillStyle = grad;
|
| 91 |
+
ctx.fill();
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
// ββ Generic Chart.js bar ββββββββββββββββββββββββββββββββββ
|
| 95 |
+
function drawBarChart(canvasId, labels, datasets, options = {}) {
|
| 96 |
+
const ctx = document.getElementById(canvasId);
|
| 97 |
+
if (!ctx) return;
|
| 98 |
+
if (ctx._chart) ctx._chart.destroy();
|
| 99 |
+
ctx._chart = new Chart(ctx, {
|
| 100 |
+
type: 'bar',
|
| 101 |
+
data: { labels, datasets },
|
| 102 |
+
options: {
|
| 103 |
+
responsive: true,
|
| 104 |
+
maintainAspectRatio: false,
|
| 105 |
+
plugins: { legend: { display: false }, ...options.plugins },
|
| 106 |
+
scales: {
|
| 107 |
+
x: {
|
| 108 |
+
grid: { color: '#1a3a5c55' },
|
| 109 |
+
ticks: { color: '#7fa8c9', font: { family: 'Share Tech Mono', size: 9 } }
|
| 110 |
+
},
|
| 111 |
+
y: {
|
| 112 |
+
grid: { color: '#1a3a5c55' },
|
| 113 |
+
ticks: { color: '#7fa8c9', font: { family: 'Share Tech Mono', size: 9 } }
|
| 114 |
+
}
|
| 115 |
+
},
|
| 116 |
+
...options
|
| 117 |
+
}
|
| 118 |
+
});
|
| 119 |
+
return ctx._chart;
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
function drawLineChart(canvasId, labels, datasets, options = {}) {
|
| 123 |
+
const ctx = document.getElementById(canvasId);
|
| 124 |
+
if (!ctx) return;
|
| 125 |
+
if (ctx._chart) ctx._chart.destroy();
|
| 126 |
+
ctx._chart = new Chart(ctx, {
|
| 127 |
+
type: 'line',
|
| 128 |
+
data: { labels, datasets },
|
| 129 |
+
options: {
|
| 130 |
+
responsive: true,
|
| 131 |
+
maintainAspectRatio: false,
|
| 132 |
+
plugins: { legend: { labels: { color: '#7fa8c9', font: { family: 'Share Tech Mono', size: 10 } } }, ...options.plugins },
|
| 133 |
+
scales: {
|
| 134 |
+
x: {
|
| 135 |
+
grid: { color: '#1a3a5c44' },
|
| 136 |
+
ticks: { color: '#7fa8c9', font: { family: 'Share Tech Mono', size: 9 } }
|
| 137 |
+
},
|
| 138 |
+
y: {
|
| 139 |
+
grid: { color: '#1a3a5c44' },
|
| 140 |
+
ticks: { color: '#7fa8c9', font: { family: 'Share Tech Mono', size: 9 } }
|
| 141 |
+
}
|
| 142 |
+
},
|
| 143 |
+
...options
|
| 144 |
+
}
|
| 145 |
+
});
|
| 146 |
+
return ctx._chart;
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
function drawDoughnut(canvasId, labels, data, colors) {
|
| 150 |
+
const ctx = document.getElementById(canvasId);
|
| 151 |
+
if (!ctx) return;
|
| 152 |
+
if (ctx._chart) ctx._chart.destroy();
|
| 153 |
+
ctx._chart = new Chart(ctx, {
|
| 154 |
+
type: 'doughnut',
|
| 155 |
+
data: {
|
| 156 |
+
labels,
|
| 157 |
+
datasets: [{ data, backgroundColor: colors, borderWidth: 0, hoverOffset: 4 }]
|
| 158 |
+
},
|
| 159 |
+
options: {
|
| 160 |
+
responsive: true,
|
| 161 |
+
maintainAspectRatio: false,
|
| 162 |
+
cutout: '72%',
|
| 163 |
+
plugins: {
|
| 164 |
+
legend: { position: 'bottom', labels: { color: '#7fa8c9', font: { family: 'Share Tech Mono', size: 10 }, padding: 12 } }
|
| 165 |
+
}
|
| 166 |
+
}
|
| 167 |
+
});
|
| 168 |
+
return ctx._chart;
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
// ββ Sidebar HTML ββββββββββββββββββββββββββββββββββββββββββ
|
| 172 |
+
function renderSidebar(activePage) {
|
| 173 |
+
return `
|
| 174 |
+
<div class="sidebar">
|
| 175 |
+
<div class="sidebar-logo">
|
| 176 |
+
<div class="logo-text">SENTINEL</div>
|
| 177 |
+
<div class="logo-sub">FRAUD DETECTION SYSTEM</div>
|
| 178 |
+
<div class="status-pill"><span class="status-dot"></span>SYSTEM ONLINE</div>
|
| 179 |
+
</div>
|
| 180 |
+
<div class="nav-section">
|
| 181 |
+
<div class="nav-label">NAVIGATION</div>
|
| 182 |
+
<a href="/" class="nav-item ${activePage==='home'?'active':''}"><span class="nav-icon">β</span>Overview</a>
|
| 183 |
+
<a href="/monitor" class="nav-item ${activePage==='monitor'?'active':''}"><span class="nav-icon">β</span>Live Monitor</a>
|
| 184 |
+
<a href="/analyzer" class="nav-item ${activePage==='analyzer'?'active':''}"><span class="nav-icon">⬑</span>Analyzer</a>
|
| 185 |
+
<a href="/performance" class="nav-item ${activePage==='performance'?'active':''}"><span class="nav-icon">β²</span>Performance</a>
|
| 186 |
+
<a href="/shap" class="nav-item ${activePage==='shap'?'active':''}"><span class="nav-icon">β</span>SHAP Explain</a>
|
| 187 |
+
</div>
|
| 188 |
+
<div class="sidebar-footer">
|
| 189 |
+
<div class="api-status" id="apiStatusText">β CHECKING API...</div>
|
| 190 |
+
</div>
|
| 191 |
+
</div>`;
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
function renderTopbar(title) {
|
| 195 |
+
return `
|
| 196 |
+
<div class="topbar">
|
| 197 |
+
<div class="page-title">${title}</div>
|
| 198 |
+
<div class="topbar-right">
|
| 199 |
+
<div class="live-badge"><span class="live-dot"></span>LIVE</div>
|
| 200 |
+
<div class="clock" id="clock">--:--:-- IST</div>
|
| 201 |
+
</div>
|
| 202 |
+
</div>`;
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
async function checkApiStatus() {
|
| 206 |
+
const data = await apiFetch('/health');
|
| 207 |
+
const el = document.getElementById('apiStatusText');
|
| 208 |
+
if (el) {
|
| 209 |
+
if (data && data.status === 'online') {
|
| 210 |
+
el.innerHTML = '<span style="color:#00ff88">β API ONLINE</span>';
|
| 211 |
+
} else {
|
| 212 |
+
el.innerHTML = '<span style="color:#ff2d55">β API OFFLINE</span>';
|
| 213 |
+
}
|
| 214 |
+
}
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
document.addEventListener('DOMContentLoaded', () => {
|
| 218 |
+
const clockEl = document.getElementById('clock');
|
| 219 |
+
if (clockEl) startClock(clockEl);
|
| 220 |
+
checkApiStatus();
|
| 221 |
+
});
|