File size: 5,223 Bytes
368a487
9c80ddd
 
368a487
 
 
9c80ddd
368a487
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c80ddd
 
368a487
9c80ddd
368a487
 
9c80ddd
368a487
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c80ddd
 
368a487
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c80ddd
 
 
368a487
 
9c80ddd
 
 
 
368a487
9c80ddd
 
04233c7
9c80ddd
 
 
 
 
 
f6de3e3
 
 
 
 
 
 
 
b2de624
 
 
9c80ddd
 
 
b2de624
9c80ddd
 
 
 
 
 
 
b2de624
 
 
 
9c80ddd
 
 
 
 
 
 
04233c7
9c80ddd
 
368a487
9c80ddd
 
984dee8
9c80ddd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
import gradio as gr
import spaces
import json
import os
import pickle
import numpy as np
import time

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
MODEL_PATH = os.path.join(BASE_DIR, "model.pkl")
METADATA_PATH = os.path.join(BASE_DIR, "model_metadata.json")

model = None
metadata = None

if os.path.exists(MODEL_PATH):
    with open(MODEL_PATH, "rb") as f:
        model = pickle.load(f)

if os.path.exists(METADATA_PATH):
    with open(METADATA_PATH, "r") as f:
        metadata = json.load(f)

@spaces.GPU
def predict_fraud(data_str):
    if not model or not metadata:
        return json.dumps({"error": "Model not loaded"})

    try:
        data = json.loads(data_str)
        amount               = float(data.get("amount", 0))
        distance_from_home   = float(data.get("distanceFromHome", 0))
        distance_from_last   = float(data.get("distanceFromLastTxn", 0))
        current_balance      = float(data.get("currentBalance", 0))
        credit_limit         = float(data.get("creditLimit", 1))
        transaction_type     = data.get("transactionType", "purchase")
        merchant_category    = data.get("merchantCategory", "grocery")
        address_match        = data.get("addressMatch", "yes")
        country_match        = data.get("countryMatch", "yes")
        card_type            = data.get("cardType", "credit")

        utilization = current_balance / credit_limit if credit_limit > 0 else 0

        score_base = 0.15
        if amount > 500:              score_base += 0.18
        if amount > 2000:             score_base += 0.22
        if distance_from_home > 100:  score_base += 0.14
        if distance_from_last > 200:  score_base += 0.16
        if utilization > 0.8:         score_base += 0.12
        if address_match == "no":     score_base += 0.15
        if country_match == "no":     score_base += 0.20
        if merchant_category in ["online_retail", "crypto"]: score_base += 0.10
        if transaction_type == "purchase" and amount > 1000: score_base += 0.08

        base_prob = min(0.97, max(0.03, score_base))

        c0_mean = metadata["class_0_mean"]
        c1_mean = metadata["class_1_mean"]
        v_features = [
            (1 - base_prob) * c0_mean[f"V{i}"] + base_prob * c1_mean[f"V{i}"]
            for i in range(1, 29)
        ]

        current_time_secs = int(time.time() % 86400)
        features = np.array([[current_time_secs] + v_features + [amount]])

        ml_prob    = float(model.predict_proba(features)[0][1])
        final_prob = float(np.clip(0.3 * base_prob + 0.7 * ml_prob, 0.03, 0.97))

        if   final_prob >= 0.7: risk_level = "critical"
        elif final_prob >= 0.5: risk_level = "high"
        elif final_prob >= 0.3: risk_level = "medium"
        else:                   risk_level = "low"

        return json.dumps({"fraud_probability": round(final_prob, 4), "risk_level": risk_level})
    except Exception as e:
        return json.dumps({"error": str(e)})


# Load custom HTML, CSS, JS
html_path = os.path.join(BASE_DIR, "templates", "index.html")
css_path = os.path.join(BASE_DIR, "static", "style.css")
js_path = os.path.join(BASE_DIR, "static", "app.js")

with open(html_path, "r", encoding="utf-8") as f:
    raw_html = f.read()

with open(css_path, "r", encoding="utf-8") as f:
    raw_css = f.read()

with open(js_path, "r", encoding="utf-8") as f:
    raw_js = f.read()

# Convert image to Base64 to bypass Gradio file serving issues
import base64
logo_path = os.path.join(BASE_DIR, "static", "images", "app_logo.png")
if os.path.exists(logo_path):
    with open(logo_path, "rb") as img_file:
        b64_logo = base64.b64encode(img_file.read()).decode('utf-8')
        logo_data_uri = f"data:image/png;base64,{b64_logo}"
        raw_html = raw_html.replace('"/static/images/app_logo.png"', f'"{logo_data_uri}"')

# We DO NOT inject raw_js into raw_html via script tags because React's dangerouslySetInnerHTML ignores them.
# Instead, we pass it to gr.Blocks(js=...) below.

# Remove the CSS link from HTML since we will pass it to Gradio's css parameter
raw_html = raw_html.replace('<link rel="stylesheet" href="/static/style.css">', '')
raw_html = raw_html.replace('<script src="/static/app.js"></script>', '')

# Hide all Gradio native elements to make it look 100% like our custom frontend
gradio_hacks = """
footer {display: none !important;}
.gradio-container {max-width: 100% !important; padding: 0 !important; margin: 0 !important; border: none !important; background: transparent !important;}
"""

# Wrap raw_js in an async function to make it valid for Gradio's js parameter
wrapped_js = "async function() {\n" + raw_js + "\n}"

with gr.Blocks(css=raw_css + "\n" + gradio_hacks, js=wrapped_js, title="FraudLens") as demo:
    # Render our exact frontend
    gr.HTML(raw_html)
    
    # Hidden Gradio API bridge
    in_data = gr.Textbox(visible=False)
    out_data = gr.Textbox(visible=False)
    btn = gr.Button("predict", visible=False)
    
    # Expose the GPU function as an API endpoint
    btn.click(predict_fraud, inputs=[in_data], outputs=[out_data], api_name="predict")

# Allow serving files from the static directory
demo.allowed_paths = [os.path.join(BASE_DIR, "static")]

demo.launch()