Spaces:
Sleeping
Sleeping
File size: 4,305 Bytes
d426b80 | 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 | import gradio as gr
import pandas as pd
import pickle
from typing import List, Dict, Any
# CSS styles (unchanged)
css = """
body, html {
height: 100%;
margin: 0;
color: white;
background-color: black;
}
header {
background: url('fraude.png') no-repeat top left;
background-size: 120px; /* Adjust this value to the desired size of your image */
padding-top: 130px; /* Adjust this value to provide space for the image */
}
"""
# Load model and configurations
def load_pickle(filename: str) -> Any:
with open(filename, 'rb') as f:
return pickle.load(f)
model = load_pickle('model/modelo_proyecto_final2.pkl')
ohe_columns = load_pickle('model/categories_ohe_without_fraudulent.pickle')
bins_order = load_pickle('model/saved_bins_order.pickle')
bins_transaction = load_pickle('model/saved_bins_transaction.pickle')
def predict(order_amount: float, order_state: str, payment_method_registration_failure: bool,
payment_method_type: str, payment_method_provider: str, payment_method_issuer: str,
transaction_amount: float, transaction_failed: bool, email_domain: str,
email_provider: str, customer_ip_address_simplified: str, same_city: str) -> str:
# Create input DataFrame
data = {
"orderAmount": [order_amount],
"orderState": [order_state],
"paymentMethodRegistrationFailure": [payment_method_registration_failure],
"paymentMethodType": [payment_method_type],
"paymentMethodProvider": [payment_method_provider],
"paymentMethodIssuer": [payment_method_issuer],
"transactionAmount": [transaction_amount],
"transactionFailed": [transaction_failed],
"emailDomain": [email_domain],
"emailProvider": [email_provider],
"customerIPAddressSimplified": [customer_ip_address_simplified],
"sameCity": [same_city]
}
df = pd.DataFrame(data)
# Fill null values with modes or medians
for column in df.columns:
if pd.api.types.is_numeric_dtype(df[column]):
df[column].fillna(df[column].median(), inplace=True)
else:
df[column].fillna(df[column].mode().iloc[0], inplace=True)
# Apply binning and one-hot encoding
df["orderAmount"] = pd.cut(df["orderAmount"].astype(float), bins=bins_order, include_lowest=True)
df["transactionAmount"] = pd.cut(df["transactionAmount"].astype(int), bins=bins_transaction, include_lowest=True)
df_encoded = pd.get_dummies(df).reindex(columns=ohe_columns, fill_value=0)
# Prediction
prediction = model.predict(df_encoded)
type_of_fraud = int(prediction[0])
responses = ["OK", "FRAUD DETECTED", "Warning"]
return responses[type_of_fraud] if type_of_fraud in [0, 1, 2] else "Error parsing value"
# Configure Gradio interface
interface = gr.Interface(
fn=predict,
inputs=[
gr.Number(label="Order Amount"),
gr.Dropdown(choices=["pending", "fulfilled", "failed"], label="Order State"),
gr.Checkbox(label="Payment Method Registration Failure"),
gr.Dropdown(choices=["card", "bitcoin", "paypal"], label="Payment Method Type"),
gr.Dropdown(choices=['JCB 16 digit', 'VISA 16 digit', 'Diners Club / Carte Blanche', 'Mastercard', 'American Express', 'Maestro', 'Discover', 'Voyager', 'VISA 13 digit', 'JCB 15 digit'], label="Payment Method Provider"),
gr.Dropdown(choices=['Citizens First Banks', 'Solace Banks', 'Vertex Bancorp', 'His Majesty Bank Corp.', 'Bastion Banks', 'Her Majesty Trust', 'Fountain Financial Inc.', 'Grand Credit Corporation', 'weird', 'Bulwark Trust Corp.', 'Rose Bancshares'], label="Payment Method Issuer"),
gr.Number(label="Transaction Amount"),
gr.Checkbox(label="Transaction Failed"),
gr.Dropdown(choices=["info","com","biz","org"], label="Email Domain"),
gr.Dropdown(choices=["yahoo","gmail","hotmail","other"], label="Email Provider"),
gr.Dropdown(choices=["only_letters", "digits_and_letters"], label="Customer IP Address Simplified"),
gr.Dropdown(choices=["yes", "no"], label="Same City")
],
outputs="text",
title="API for Fraud Detection",
description="APP to predict if a transaction is fraudulent.",
css=css
)
if __name__ == "__main__":
interface.launch()
|