Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
import numpy as np
|
| 4 |
+
import json
|
| 5 |
+
from huggingface_hub import hf_hub_download
|
| 6 |
+
|
| 7 |
+
REPO = "gabrielnkl/model-fraud-detect"
|
| 8 |
+
MODEL = "model.pt"
|
| 9 |
+
|
| 10 |
+
model_path = hf_hub_download(repo_id=REPO, filename=MODEL)
|
| 11 |
+
model = torch.jit.load(model_path)
|
| 12 |
+
model.eval()
|
| 13 |
+
|
| 14 |
+
TYPE_MAP = {
|
| 15 |
+
"PAYMENT": 0,
|
| 16 |
+
"TRANSFER": 1,
|
| 17 |
+
"CASH_OUT": 2,
|
| 18 |
+
"DEBIT": 3,
|
| 19 |
+
"CASH_IN": 4
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
def predict(json_input):
|
| 23 |
+
|
| 24 |
+
try:
|
| 25 |
+
d = json.loads(json_input)
|
| 26 |
+
|
| 27 |
+
amount = float(d["amount"])
|
| 28 |
+
old = float(d["oldbalanceOrg"])
|
| 29 |
+
new = float(d["newbalanceOrig"])
|
| 30 |
+
t = TYPE_MAP[d["type"]]
|
| 31 |
+
|
| 32 |
+
x = np.array([[amount, old, new, t]], dtype=np.float32)
|
| 33 |
+
tensor = torch.from_numpy(x)
|
| 34 |
+
|
| 35 |
+
prob = float(model(tensor).item())
|
| 36 |
+
pred = int(prob > 0.5)
|
| 37 |
+
|
| 38 |
+
return {
|
| 39 |
+
"prediction": pred,
|
| 40 |
+
"fraud_probability": round(prob, 4)
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
except Exception as e:
|
| 44 |
+
return {"error": str(e)}
|
| 45 |
+
|
| 46 |
+
iface = gr.Interface(
|
| 47 |
+
fn=predict,
|
| 48 |
+
inputs=gr.Textbox(lines=8, label="JSON Input"),
|
| 49 |
+
outputs="json",
|
| 50 |
+
title="Fraud Detection API"
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
if __name__ == "__main__":
|
| 54 |
+
iface.launch(server_name="0.0.0.0", server_port=7860)
|
| 55 |
+
|