import random from datetime import datetime import joblib import pandas as pd import requests # Load the trained model and feature names model, feature_names = joblib.load("model.pkl") # Function to fetch data from final_data.csv based on user input def fetch_data(user_id, txn_amount): final_data = pd.read_csv("final_data.csv") fetched_data = final_data[(final_data["user_id"] == user_id) & (final_data["TxnAmount($)"] == txn_amount)] return fetched_data # Define the prediction function def predict_fraud(input_data): # Reorder and align input_data to match the feature names used during training input_data = input_data.reindex(columns=feature_names, fill_value=0) # Make the prediction prediction = model.predict(input_data) return prediction[0] # Function to handle real-time data and make predictions def handle_real_time_data(real_time_data): predictions = [] for index, row in real_time_data.iterrows(): input_data = pd.DataFrame([row]) prediction = predict_fraud(input_data) predictions.append(prediction) real_time_data["Prediction"] = predictions return real_time_data def fetch_test_data(): # Simulate real-time data fetching from an API or a streaming service return pd.read_csv("test.csv") # Example CSV file for real-time transactions # Function to determine time of day def time_of_day(hour, minute, second): if 5 <= hour < 11: return 0 elif hour == 11 and minute < 1: return 0.166666667 elif 11 <= hour < 13: return 0.166666667 elif hour == 13 and minute < 1: return 0.333333333 elif 13 <= hour < 15: return 0.333333333 elif hour == 15 and minute < 1: return 0.5 elif 15 <= hour < 17: return 0.5 elif hour == 17 and minute < 1: return 0.666666667 elif 17 <= hour < 19: return 0.666666667 elif hour == 19 and minute < 1: return 0.833333333 elif 19 <= hour < 24: return 0.833333333 elif hour == 0 and minute < 1: return 1 elif 0 <= hour < 5: return 1 else: return "Invalid time" def payee_type(payee): payee_types = ["Individual", "Business or corporations", "Financial agency", "Charity", "Educational Institute"] payee_values = [0, 0.369070247, 0.630929753, 0.834043767, 1] if payee in payee_types: return payee_values[payee_types.index(payee)] else: return "Invalid Payee Type" # Get current location details including latitude and longitude def get_location(): try: res = requests.get("https://ipinfo.io/") data = res.json() loc = data["loc"].split(",") latitude = loc[0] longitude = loc[1] return data["city"], data["region"], data["country"], data["ip"], latitude, longitude except Exception as e: print("Unable to retrieve location:", e) return None, None, None, None, None, None # Function to generate synthetic data def generate_synthetic_data(user_id, txn_amount): # Define the feature values based on model requirements lag_amount1 = random.randint(50, 200) # Random lag_amount1 average_amount_3txns = random.randint(50, 200) # Random average amount of last 3 transactions time_since_last_txn = random.randint(1, 60) # Random time since last transaction (in minutes) velocity_txns = random.randint(1, 10) # Random velocity of transactions weekday = random.choice([0, 1, 2, 3, 4, 5, 6]) # Random weekday encoded as numerical value ip_used_known = random.choice([0, 1]) # Random IP used known time_slots = time_of_day( datetime.now().hour, datetime.now().minute, datetime.now().second ) # Time of day based on current time known_device_browser = random.choice([0, 1]) # Random known device and browser payee_type_value = payee_type( random.choice( ["Individual", "Business or corporations", "Financial agency", "Charity", "Educational Institute"] ) ) # Random payee type value time_since_payee_regn = random.randint(1, 365) # Random time since payee registration (in days) known_location = random.choice([0, 1]) # Random known location otp = random.choice([0, 1]) # Random OTP authentication_level = random.choice([0, 1, 2]) # Random authentication level time_limit = random.choice([0, 1]) # Random time limit browser_known = random.choice([0, 1]) # Random browser known location_change = random.choice([0, 1]) # Random location change # Create a DataFrame with the generated synthetic data synthetic_data = pd.DataFrame( { "user_id": [user_id], "TxnAmount($)": [txn_amount], "LagAmount1": [lag_amount1], "AverageAmount(Last3txns)": [average_amount_3txns], "TimeSinceLastTxn": [time_since_last_txn], "VelocityTxns": [velocity_txns], "WeekDay": [weekday], "IPUsedKnown": [ip_used_known], "TimeSlots": [time_slots], "KnownDeviceBrowser": [known_device_browser], "PayeeType": [payee_type_value], "Timesincepayeeregn": [time_since_payee_regn], "KnownLocation": [known_location], "OTP": [otp], "AuthenticationLevel": [authentication_level], "Timelimit": [time_limit], "BrowserKnown": [browser_known], "location_change": [location_change], } ) return synthetic_data # Function to simulate fetching real-time data def fetch_real_time_data(user_id, txn_amount): # Simulate real-time data fetching from an API or a streaming service return generate_synthetic_data(user_id, txn_amount) # Generating synthetic data instead of reading from CSV