|
|
from flask import Flask, render_template, request, jsonify
|
|
|
import joblib
|
|
|
import pandas as pd
|
|
|
import numpy as np
|
|
|
import os
|
|
|
|
|
|
app = Flask(__name__)
|
|
|
|
|
|
|
|
|
MODEL_PATH = 'c:/card/fraud_model.joblib'
|
|
|
SCALER_AMOUNT_PATH = 'c:/card/scaler_amount.joblib'
|
|
|
SCALER_TIME_PATH = 'c:/card/scaler_time.joblib'
|
|
|
DATA_PATH = 'c:/card/creditcard.csv'
|
|
|
|
|
|
model = joblib.load(MODEL_PATH)
|
|
|
scaler_amount = joblib.load(SCALER_AMOUNT_PATH)
|
|
|
scaler_time = joblib.load(SCALER_TIME_PATH)
|
|
|
|
|
|
|
|
|
df_all = pd.read_csv(DATA_PATH)
|
|
|
fraud_samples = df_all[df_all['Class'] == 1].sample(10).to_dict('records')
|
|
|
normal_samples = df_all[df_all['Class'] == 0].sample(10).to_dict('records')
|
|
|
|
|
|
@app.route('/')
|
|
|
def index():
|
|
|
return render_template('index.html')
|
|
|
|
|
|
@app.route('/get_samples', methods=['GET'])
|
|
|
def get_samples():
|
|
|
return jsonify({
|
|
|
"fraud": fraud_samples,
|
|
|
"normal": normal_samples
|
|
|
})
|
|
|
|
|
|
@app.route('/predict', methods=['POST'])
|
|
|
def predict():
|
|
|
try:
|
|
|
data = request.json
|
|
|
|
|
|
|
|
|
v_features = [float(data.get(f'V{i}', 0)) for i in range(1, 29)]
|
|
|
|
|
|
amount = float(data.get('Amount', 0))
|
|
|
time = float(data.get('Time', 0))
|
|
|
|
|
|
scaled_amount = scaler_amount.transform([[amount]])[0][0]
|
|
|
scaled_time = scaler_time.transform([[time]])[0][0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
feature_vector = np.array(v_features + [scaled_amount, scaled_time]).reshape(1, -1)
|
|
|
|
|
|
prediction = int(model.predict(feature_vector)[0])
|
|
|
probability = model.predict_proba(feature_vector)[0].tolist()
|
|
|
|
|
|
return jsonify({
|
|
|
"is_fraud": prediction == 1,
|
|
|
"confidence": max(probability) * 100,
|
|
|
"class": "Fraudulent" if prediction == 1 else "Legitimate"
|
|
|
})
|
|
|
|
|
|
except Exception as e:
|
|
|
return jsonify({"error": str(e)}), 400
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
app.run(debug=True, port=5000)
|
|
|
|