BhavyaSoni21 commited on
Commit
90e38d0
·
verified ·
1 Parent(s): 54c8f29

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -21
app.py CHANGED
@@ -3,8 +3,9 @@ from pydantic import BaseModel
3
  import joblib
4
  import numpy as np
5
  from fastapi.middleware.cors import CORSMiddleware
 
6
 
7
- app = FastAPI(title="Web Attack Detection API")
8
 
9
  # Allow browser requests
10
  app.add_middleware(
@@ -15,22 +16,28 @@ app.add_middleware(
15
  allow_headers=["*"],
16
  )
17
 
18
- # Expected number of features
19
- EXPECTED_FEATURES = 35
 
20
 
21
- # Request schema
 
 
 
22
  class InputData(BaseModel):
23
- features: list[float]
24
 
25
- # Load model
26
  try:
27
- model = joblib.load("web_attack_detection_model.pkl")
 
 
28
  except Exception as e:
29
- raise RuntimeError(f"Model failed to load: {e}")
30
 
31
  @app.get("/")
32
  def home():
33
- return {"message": "Web attack detection model running"}
34
 
35
  @app.get("/health")
36
  def health():
@@ -38,24 +45,23 @@ def health():
38
 
39
  @app.post("/predict")
40
  def predict(data: InputData):
41
-
42
  if len(data.features) != EXPECTED_FEATURES:
43
  raise HTTPException(
44
  status_code=400,
45
- detail=f"Expected {EXPECTED_FEATURES} features"
46
  )
47
 
48
- input_data = np.array(data.features).reshape(1, -1)
 
 
49
 
50
- prediction = model.predict(input_data)[0]
 
51
 
52
- # Convert prediction to readable output
53
- if prediction == -1:
54
- result = "attack detected"
55
- else:
56
- result = "normal request"
57
 
58
  return {
59
- "prediction": result,
60
- "raw_prediction": int(prediction)
61
- }
 
3
  import joblib
4
  import numpy as np
5
  from fastapi.middleware.cors import CORSMiddleware
6
+ import pandas as pd # Needed if you decide to preprocess raw input in the API
7
 
8
+ app = FastAPI(title="Multi-Class Web Data Classifier API")
9
 
10
  # Allow browser requests
11
  app.add_middleware(
 
16
  allow_headers=["*"],
17
  )
18
 
19
+ # The number of features MUST match the X_preprocessed.shape[1] from training
20
+ # Our X_preprocessed had 5 columns: 'feature1', 'id', 'type_defacement', 'type_malware', 'type_phishing'
21
+ EXPECTED_FEATURES = 5
22
 
23
+ # Request schema for the preprocessed features
24
+ # IMPORTANT: The client calling this API must preprocess their data
25
+ # (impute, scale numerical, one-hot encode categorical) to match the format
26
+ # of X_preprocessed used during model training.
27
  class InputData(BaseModel):
28
+ features: list[float] # Expecting 5 preprocessed float values
29
 
30
+ # Load model and label encoder
31
  try:
32
+ model = joblib.load("trained_lightgbm_model.joblib")
33
+ label_encoder = joblib.load("label_encoder.pkl")
34
+ print("Model and Label Encoder loaded successfully.")
35
  except Exception as e:
36
+ raise RuntimeError(f"Error loading model or label encoder: {e}")
37
 
38
  @app.get("/")
39
  def home():
40
+ return {"message": "Multi-Class Web Data Classifier API running"}
41
 
42
  @app.get("/health")
43
  def health():
 
45
 
46
  @app.post("/predict")
47
  def predict(data: InputData):
 
48
  if len(data.features) != EXPECTED_FEATURES:
49
  raise HTTPException(
50
  status_code=400,
51
+ detail=f"Expected {EXPECTED_FEATURES} features, but received {len(data.features)}"
52
  )
53
 
54
+ # Convert input list to numpy array and reshape for prediction
55
+ # This assumes input features are ALREADY preprocessed as per training
56
+ input_array = np.array(data.features).reshape(1, -1)
57
 
58
+ # Make prediction
59
+ prediction_encoded = model.predict(input_array)[0]
60
 
61
+ # Inverse transform to get the original label string
62
+ prediction_label = label_encoder.inverse_transform([prediction_encoded])[0]
 
 
 
63
 
64
  return {
65
+ "predicted_label": prediction_label,
66
+ "raw_prediction_encoded": int(prediction_encoded)
67
+ }