Files changed (1) hide show
  1. app.py +30 -34
app.py CHANGED
@@ -1,19 +1,16 @@
1
  import os
2
- import joblib
3
  import torch
4
  import torch.nn as nn
5
- import numpy as np
6
  from flask import Flask, request, jsonify
7
- from flask_cors import CORS
8
 
9
- # --- 1. Define the same PyTorch Model Architecture ---
10
- # This class must be identical to the one in your training script.
11
  class FraudClassifier(nn.Module):
12
  def __init__(self):
13
  super(FraudClassifier, self).__init__()
14
- self.layer1 = nn.Linear(2, 16) # 2 input features
15
  self.layer2 = nn.Linear(16, 8)
16
- self.layer3 = nn.Linear(8, 1) # 1 output for binary classification
17
  self.relu = nn.ReLU()
18
  self.sigmoid = nn.Sigmoid()
19
 
@@ -23,61 +20,59 @@ class FraudClassifier(nn.Module):
23
  x = self.sigmoid(self.layer3(x))
24
  return x
25
 
26
- # --- 2. Initialize Flask App and Load Assets ---
27
  app = Flask(__name__)
28
- CORS(app) # Enable Cross-Origin Resource Sharing
29
-
30
- # The model and scaler are loaded once when the application starts.
31
  model = None
32
- scaler = None
33
 
34
  try:
35
- # Load the PyTorch model
 
 
 
 
 
 
36
  model = FraudClassifier()
37
- # Use map_location=torch.device('cpu') for compatibility if the server doesn't have a GPU
38
- model.load_state_dict(torch.load("realistic_fraud_model.pth", map_location=torch.device('cpu')))
39
- model.eval() # Set model to evaluation mode
40
  print("βœ… PyTorch model loaded successfully.")
41
 
42
- # Load the scaler
43
- scaler = joblib.load("scaler.pkl")
44
- print("βœ… Scaler loaded successfully.")
45
-
46
  except Exception as e:
47
- print(f"❌ An error occurred during asset loading: {e}")
48
 
49
- # --- 3. API Endpoints ---
50
  @app.route('/', methods=['GET'])
51
  def home():
52
  """Root endpoint to check API status."""
53
  return jsonify({
54
  "status": "API is running",
55
  "model_loaded": model is not None,
56
- "scaler_loaded": scaler is not None
57
  })
58
 
59
  @app.route('/predict', methods=['POST'])
60
  def predict():
61
  """Receives feature data and returns a fraud prediction."""
62
- if not model or not scaler:
63
  return jsonify({"error": "Model or scaler not loaded."}), 500
64
 
65
  try:
66
  data = request.get_json(force=True)
67
  # Expected input: {"features": [value_ether, fee_ether]}
68
- features = np.array(data['features']).reshape(1, -1)
 
 
 
69
 
70
- # Apply the same scaling as in training
71
- scaled_features = scaler.transform(features)
72
 
73
- # Convert to PyTorch tensor
74
- features_tensor = torch.tensor(scaled_features, dtype=torch.float32)
 
75
 
76
- # Make prediction
77
- with torch.no_grad(): # Disable gradient calculation for inference
78
- probability = model(features_tensor)
79
-
80
- prob_fraud = probability.item() # Get the float value from the tensor
81
  prediction = 1 if prob_fraud > 0.5 else 0
82
 
83
  # Return the result
@@ -89,6 +84,7 @@ def predict():
89
  'fraud': prob_fraud
90
  }
91
  })
 
92
  except Exception as e:
93
  return jsonify({"error": f"An error occurred during prediction: {str(e)}"}), 400
94
 
 
1
  import os
 
2
  import torch
3
  import torch.nn as nn
 
4
  from flask import Flask, request, jsonify
 
5
 
6
+ # --- 1. Define the exact same Model Architecture ---
7
+ # This is necessary to load the saved state_dict
8
  class FraudClassifier(nn.Module):
9
  def __init__(self):
10
  super(FraudClassifier, self).__init__()
11
+ self.layer1 = nn.Linear(2, 16)
12
  self.layer2 = nn.Linear(16, 8)
13
+ self.layer3 = nn.Linear(8, 1)
14
  self.relu = nn.ReLU()
15
  self.sigmoid = nn.Sigmoid()
16
 
 
20
  x = self.sigmoid(self.layer3(x))
21
  return x
22
 
23
+ # --- 2. Initialize App and Load Assets ---
24
  app = Flask(__name__)
 
 
 
25
  model = None
26
+ scaler_params = None
27
 
28
  try:
29
+ # Load scaler parameters
30
+ scaler_params = torch.load("scaler_params.pt")
31
+ mean = scaler_params['mean']
32
+ std = scaler_params['std']
33
+ print("βœ… PyTorch scaler parameters loaded.")
34
+
35
+ # Load the trained model
36
  model = FraudClassifier()
37
+ model.load_state_dict(torch.load("realistic_fraud_model.pth"))
38
+ model.eval() # Set to evaluation mode
 
39
  print("βœ… PyTorch model loaded successfully.")
40
 
 
 
 
 
41
  except Exception as e:
42
+ print(f"❌ Error loading assets: {e}")
43
 
44
+ # --- 3. Define API Endpoints ---
45
  @app.route('/', methods=['GET'])
46
  def home():
47
  """Root endpoint to check API status."""
48
  return jsonify({
49
  "status": "API is running",
50
  "model_loaded": model is not None,
51
+ "scaler_loaded": scaler_params is not None
52
  })
53
 
54
  @app.route('/predict', methods=['POST'])
55
  def predict():
56
  """Receives feature data and returns a fraud prediction."""
57
+ if not model or not scaler_params:
58
  return jsonify({"error": "Model or scaler not loaded."}), 500
59
 
60
  try:
61
  data = request.get_json(force=True)
62
  # Expected input: {"features": [value_ether, fee_ether]}
63
+ features = data['features']
64
+
65
+ # Convert to a PyTorch tensor
66
+ features_tensor = torch.tensor(features, dtype=torch.float32)
67
 
68
+ # Apply the scaling transformation
69
+ scaled_tensor = (features_tensor - mean) / std
70
 
71
+ # Get model prediction
72
+ with torch.no_grad():
73
+ probability = model(scaled_tensor)
74
 
75
+ prob_fraud = probability.item()
 
 
 
 
76
  prediction = 1 if prob_fraud > 0.5 else 0
77
 
78
  # Return the result
 
84
  'fraud': prob_fraud
85
  }
86
  })
87
+
88
  except Exception as e:
89
  return jsonify({"error": f"An error occurred during prediction: {str(e)}"}), 400
90