Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,28 +1,61 @@
|
|
| 1 |
-
from fastapi import FastAPI
|
| 2 |
from pydantic import BaseModel
|
| 3 |
import joblib
|
| 4 |
import numpy as np
|
|
|
|
| 5 |
|
| 6 |
-
app = FastAPI()
|
| 7 |
|
| 8 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
class InputData(BaseModel):
|
| 10 |
features: list[float]
|
| 11 |
|
| 12 |
-
# Load
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
@app.get("/")
|
| 16 |
def home():
|
| 17 |
-
return {"message": "
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
@app.post("/predict")
|
| 20 |
def predict(data: InputData):
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
input_data = np.array(data.features).reshape(1, -1)
|
| 23 |
|
| 24 |
-
prediction = model.predict(input_data)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
return {
|
| 27 |
-
"prediction":
|
|
|
|
| 28 |
}
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException
|
| 2 |
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(
|
| 11 |
+
CORSMiddleware,
|
| 12 |
+
allow_origins=["*"],
|
| 13 |
+
allow_credentials=True,
|
| 14 |
+
allow_methods=["*"],
|
| 15 |
+
allow_headers=["*"],
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
# Expected number of features
|
| 19 |
+
EXPECTED_FEATURES = 7
|
| 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():
|
| 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 |
}
|