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)