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('', '') raw_html = raw_html.replace('', '') # 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()