Spaces:
Sleeping
Sleeping
| 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() | |