File size: 2,740 Bytes
3c58b5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import joblib
import pandas as pd
from flask import Flask, request, jsonify
from flask_cors import CORS

# Initialize the Flask application
app = Flask(__name__)
CORS(app) # Enable Cross-Origin Resource Sharing

# --- Model Loading ---
# The model is loaded once when the application starts.
try:
    # In Hugging Face Spaces, your files are all in the same root directory.
    model_path = 'realistic_fraud_model.pkl'
    model = joblib.load(model_path)
    print("✅ Model loaded successfully.")
except FileNotFoundError:
    print(f"❌ Error: Model file not found at '{model_path}'")
    model = None
except Exception as e:
    print(f"❌ An error occurred while loading the model: {e}")
    model = None
# --- End of Model Loading ---


# --- API Endpoints ---

# Root endpoint to check if the API is running
@app.route('/', methods=['GET'])
def home():
    return jsonify({"status": "API is running", "model_loaded": model is not None})


# Prediction endpoint
@app.route('/predict', methods=['POST'])
def predict():
    """

    Receives feature data in JSON format and returns a fraud prediction.

    """
    if model is None:
        return jsonify({"error": "Model is not loaded."}), 500

    try:
        # Get data from the POST request
        data = request.get_json(force=True)
        
        # IMPORTANT: You must know the order of features your model expects.
        # The input JSON should be an object with a key like "features"
        # which is a list of values in the correct order.
        # Example: {"features": [0.1, -0.5, 1.2, ...]}
        features = data['features']
        
        # Convert to a Pandas DataFrame for prediction
        # The feature names here are placeholders, they don't affect a
        # scikit-learn model prediction if the order is correct.
        feature_df = pd.DataFrame([features])

        # Make prediction
        prediction = model.predict(feature_df)
        prediction_proba = model.predict_proba(feature_df)

        # Return the result as JSON
        return jsonify({
            'prediction': int(prediction[0]),
            'is_fraud': bool(prediction[0] == 1),
            'prediction_probability': {
                'not_fraud': prediction_proba[0][0],
                'fraud': prediction_proba[0][1]
            }
        })

    except Exception as e:
        return jsonify({"error": f"An error occurred during prediction: {str(e)}"}), 400

# --- End of API Endpoints ---


if __name__ == '__main__':
    # The 'port' is set by Hugging Face Spaces, default to 8080 for local testing
    port = int(os.environ.get("PORT", 8080))
    app.run(host='0.0.0.0', port=port)