BhavyaSoni21 commited on
Commit
4cce576
·
verified ·
1 Parent(s): a4cb99d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -14
app.py CHANGED
@@ -4,7 +4,7 @@ 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(
@@ -24,38 +24,52 @@ class InputData(BaseModel):
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():
37
  return {"status": "ok"}
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
- }
 
 
 
 
 
 
 
4
  import numpy as np
5
  from fastapi.middleware.cors import CORSMiddleware
6
 
7
+ app = FastAPI(title="Bot Detection API")
8
 
9
  # Allow browser requests
10
  app.add_middleware(
 
24
 
25
  # Load model
26
  try:
27
+ model = joblib.load("bot_detection_model.pkl")
28
  except Exception as e:
29
  raise RuntimeError(f"Model failed to load: {e}")
30
 
31
+ # Root endpoint
32
  @app.get("/")
33
  def home():
34
+ return {
35
+ "message": "Bot detection model running",
36
+ "expected_features": EXPECTED_FEATURES
37
+ }
38
 
39
+ # Health check
40
  @app.get("/health")
41
  def health():
42
  return {"status": "ok"}
43
 
44
+ # Prediction endpoint
45
  @app.post("/predict")
46
  def predict(data: InputData):
47
 
48
+ # Validate feature count
49
  if len(data.features) != EXPECTED_FEATURES:
50
  raise HTTPException(
51
  status_code=400,
52
  detail=f"Expected {EXPECTED_FEATURES} features"
53
  )
54
 
55
+ try:
56
+ input_data = np.array(data.features).reshape(1, -1)
57
 
58
+ prediction = model.predict(input_data)[0]
59
 
60
+ # Convert prediction to readable output
61
+ if prediction == 1:
62
+ result = "bot_detected"
63
+ else:
64
+ result = "normal_traffic"
65
 
66
+ return {
67
+ "prediction": result,
68
+ "raw_prediction": int(prediction)
69
+ }
70
+
71
+ except Exception as e:
72
+ raise HTTPException(
73
+ status_code=500,
74
+ detail=f"Prediction failed: {str(e)}"
75
+ )