Initial commit
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
from flask import Flask, render_template, request, jsonify
|
||||
import joblib
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
from datetime import datetime
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# Load the model
|
||||
try:
|
||||
model = joblib.load('models/fraud_model.pkl')
|
||||
except Exception as e:
|
||||
print(f"Error loading model: {e}")
|
||||
raise
|
||||
|
||||
|
||||
def preprocess_input(data):
|
||||
# Convert to DataFrame
|
||||
df = pd.DataFrame([data])
|
||||
|
||||
# Convert numeric fields explicitly
|
||||
numeric_fields = ['amt', 'city_pop', 'lat', 'long', 'merch_lat', 'merch_long']
|
||||
for field in numeric_fields:
|
||||
df[field] = pd.to_numeric(df[field], errors='coerce')
|
||||
|
||||
# Convert transaction time to datetime
|
||||
df['trans_date_trans_time'] = pd.to_datetime(df['trans_date_trans_time'])
|
||||
|
||||
# Extract time features
|
||||
df['hour'] = df['trans_date_trans_time'].dt.hour
|
||||
df['day_of_week'] = df['trans_date_trans_time'].dt.dayofweek
|
||||
df['month'] = df['trans_date_trans_time'].dt.month
|
||||
|
||||
# Calculate age from dob
|
||||
df['dob'] = pd.to_datetime(df['dob'])
|
||||
df['age'] = (pd.to_datetime('today') - df['dob']).dt.days // 365
|
||||
|
||||
# Calculate distance between user and merchant
|
||||
df['distance'] = np.sqrt(
|
||||
(df['lat'].astype(float) - df['merch_lat'].astype(float))**2 +
|
||||
(df['long'].astype(float) - df['merch_long'].astype(float))**2
|
||||
)
|
||||
|
||||
# Drop unnecessary columns
|
||||
return df.drop(['trans_date_trans_time', 'dob'], axis=1, errors='ignore')
|
||||
|
||||
|
||||
@app.route('/')
|
||||
def home():
|
||||
return render_template('index.html')
|
||||
|
||||
|
||||
@app.route('/predict', methods=['POST'])
|
||||
def predict():
|
||||
try:
|
||||
# Get data from form
|
||||
data = request.form.to_dict()
|
||||
|
||||
# Preprocess the input
|
||||
processed_data = preprocess_input(data)
|
||||
|
||||
# Make prediction
|
||||
prediction = model.predict(processed_data)
|
||||
probability = model.predict_proba(processed_data)[0][1]
|
||||
|
||||
result = {
|
||||
'prediction': int(prediction[0]),
|
||||
'probability': float(probability),
|
||||
'is_fraud': bool(prediction[0])
|
||||
}
|
||||
|
||||
return render_template('index.html', prediction=result)
|
||||
|
||||
except Exception as e:
|
||||
return jsonify({'error': str(e)}), 400
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(debug=True)
|
||||
Reference in New Issue
Block a user