import gradio as gr import joblib import numpy as np import json from huggingface_hub import hf_hub_download REPO = "gabrielnkl/model-fraud-detect" MODEL = "modelo_fraude.pkl" model_path = hf_hub_download(repo_id=REPO, filename=MODEL) model = joblib.load(model_path) TYPES = ["TRANSFER","CASH_OUT","PAYMENT","DEBIT","CASH_IN"] THRESHOLD = 0.8 # <<<<<< FRAUD probability cutoff def predict(json_input): try: d = json.loads(json_input) amount = float(d["amount"]) old = float(d["oldbalanceOrg"]) new = float(d["newbalanceOrig"]) t = d["type"] # engineered features errorBalanceOrig = old - new - amount balanceDifference = old - new features = [ amount, old, new, errorBalanceOrig, balanceDifference ] # one-hot encode transaction type for typ in TYPES: features.append(1.0 if t == typ else 0.0) X = np.array([features], dtype=float) prob = float(model.predict_proba(X)[0][1]) # NEW RULE: # classify as fraud ONLY IF prob > 0.80 pred = int(prob > THRESHOLD) return { "prediction": pred, "fraud_probability": round(prob, 4), "threshold": THRESHOLD } except Exception as e: return {"error": str(e)} iface = gr.Interface( fn=predict, inputs=gr.Textbox(lines=8, label="JSON Input"), outputs="json", title="Fraud Detection API (Threshold-Calibrated)", description="Flags transactions as fraud only when probability exceeds 0.80" ) if __name__ == "__main__": iface.launch(ssr_mode=True)