File size: 10,069 Bytes
d29bde4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
import os
import time
import shutil
import logging
import pandas as pd
import numpy as np
from contextlib import asynccontextmanager
from fastapi import FastAPI, UploadFile, File, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware

# Import our utility functions
from utils import (
    load_pickle_file,
    preprocess_nids_data,
    preprocess_malware_data,
    get_nids_threat_details,
    get_malware_threat_details,
)

# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("backend_app")

# Ensure uploads directory exists
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
UPLOADS_DIR = os.path.join(BASE_DIR, "uploads")
os.makedirs(UPLOADS_DIR, exist_ok=True)

# Risk levels mapping for prioritization
RISK_PRIORITY = {
    "Critical": 4,
    "High": 3,
    "Medium": 2,
    "Low": 1
}

# Lifespan context manager for loading models once at startup
@asynccontextmanager
async def lifespan(app: FastAPI):
    logger.info("Starting FastAPI server: Loading ML models, scalers, and encoders...")
    try:
        # Load NIDS models
        app.state.nids_model = load_pickle_file("nids_model.pkl")
        app.state.nids_scaler = load_pickle_file("nids_scaler.pkl")
        app.state.nids_label_encoder = load_pickle_file("nids_label_encoder.pkl")
        
        # Load Malware models
        app.state.malware_model = load_pickle_file("malware_model.pkl")
        app.state.malware_scaler = load_pickle_file("malware_scaler.pkl")
        app.state.malware_label_encoder = load_pickle_file("malware_label_encoder.pkl")
        
        logger.info("All pre-trained ML models and scalers loaded successfully.")
    except Exception as e:
        logger.error(f"Critical error loading models during startup: {str(e)}")
        # We do not crash the app startup, but subsequent requests will fail gracefully
        # or we let it raise so the service fails to start if models are missing
        raise RuntimeError(f"Server startup failed due to missing/invalid models: {str(e)}")
        
    yield
    logger.info("Shutting down FastAPI server: Clean up resources if necessary.")


app = FastAPI(
    title="AI-Based Cyber Threat Detection Framework API",
    description="Production-ready FastAPI backend for running NIDS and Malware predictions.",
    version="1.0.0",
    lifespan=lifespan
)

# Configure CORS Middleware
# Allows requests from any origin (e.g. frontend dev servers, Hugging Face Spaces, etc.)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/")
async def root():
    return {
        "status": "online",
        "message": "AI-Based Cyber Threat Detection Backend is running.",
        "docs_url": "/docs"
    }


@app.post("/predict/network")
async def predict_network(request: Request, file: UploadFile = File(...)):
    """
    Accepts a network traffic features CSV file, runs NIDS model prediction, and returns
    predictions, confidence, risk levels, and security recommendations.
    """
    # 1. Validate file extension
    if not file.filename.endswith(".csv"):
        raise HTTPException(status_code=400, detail="Invalid file format. Only CSV files are supported.")
    
    # 2. Save CSV to uploads folder for tracking/logging
    file_path = os.path.join(UPLOADS_DIR, f"nids_{int(time.time())}_{file.filename}")
    try:
        with open(file_path, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)
    except Exception as e:
        logger.error(f"Failed to save file: {str(e)}")
        raise HTTPException(status_code=500, detail=f"Failed to process file upload: {str(e)}")

    # 3. Read CSV into Pandas DataFrame
    try:
        df = pd.read_csv(file_path)
    except Exception as e:
        logger.error(f"Failed to read CSV: {str(e)}")
        raise HTTPException(status_code=400, detail=f"Failed to parse CSV file: {str(e)}")

    # 4. Check if DataFrame is empty
    if df.empty:
        raise HTTPException(status_code=400, detail="The uploaded CSV file contains no data.")

    # 5. Preprocess and Run Inference
    try:
        # Retrieve models from app state
        scaler = request.app.state.nids_scaler
        model = request.app.state.nids_model
        label_encoder = request.app.state.nids_label_encoder

        # Run preprocessing (imputing, feature selection, scaling)
        X_scaled = preprocess_nids_data(df, scaler)

        # Run prediction
        predictions = model.predict(X_scaled)
        
        # Decode target labels
        decoded_labels = label_encoder.inverse_transform(predictions)

        # Get confidence/probabilities
        if hasattr(model, "predict_proba"):
            probs = model.predict_proba(X_scaled)
            confidences = np.max(probs, axis=1).tolist()
        else:
            # Fallback if model does not support predict_proba
            confidences = [1.0] * len(predictions)

        # Generate list of individual predictions
        results = []
        for idx, (label, conf) in enumerate(zip(decoded_labels, confidences)):
            details = get_nids_threat_details(label, conf)
            results.append({
                "row_index": idx,
                "prediction": str(label),
                "confidence": round(float(conf), 4),
                "risk_level": details["risk_level"],
                "recommendation": details["recommendation"]
            })

        # Determine overall threat summary (highest threat in the batch)
        highest_threat_result = max(results, key=lambda x: RISK_PRIORITY.get(x["risk_level"], 0))

        return {
            "prediction": highest_threat_result["prediction"],
            "confidence": highest_threat_result["confidence"],
            "risk_level": highest_threat_result["risk_level"],
            "recommendation": highest_threat_result["recommendation"],
            "is_batch": len(results) > 1,
            "total_samples": len(results),
            "results": results
        }

    except ValueError as val_err:
        logger.warning(f"Validation error in NIDS processing: {str(val_err)}")
        raise HTTPException(status_code=400, detail=str(val_err))
    except Exception as e:
        logger.error(f"Prediction logic error: {str(e)}")
        raise HTTPException(status_code=500, detail=f"An error occurred during prediction processing: {str(e)}")


@app.post("/predict/malware")
async def predict_malware(request: Request, file: UploadFile = File(...)):
    """
    Accepts a malware classification features CSV file, runs malware prediction model, and returns
    predictions, confidence, risk levels, and security recommendations.
    """
    # 1. Validate file extension
    if not file.filename.endswith(".csv"):
        raise HTTPException(status_code=400, detail="Invalid file format. Only CSV files are supported.")
    
    # 2. Save CSV to uploads folder for tracking/logging
    file_path = os.path.join(UPLOADS_DIR, f"malware_{int(time.time())}_{file.filename}")
    try:
        with open(file_path, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)
    except Exception as e:
        logger.error(f"Failed to save file: {str(e)}")
        raise HTTPException(status_code=500, detail=f"Failed to process file upload: {str(e)}")

    # 3. Read CSV into Pandas DataFrame
    try:
        df = pd.read_csv(file_path)
    except Exception as e:
        logger.error(f"Failed to read CSV: {str(e)}")
        raise HTTPException(status_code=400, detail=f"Failed to parse CSV file: {str(e)}")

    # 4. Check if DataFrame is empty
    if df.empty:
        raise HTTPException(status_code=400, detail="The uploaded CSV file contains no data.")

    # 5. Preprocess and Run Inference
    try:
        # Retrieve models from app state
        scaler = request.app.state.malware_scaler
        model = request.app.state.malware_model
        label_encoder = request.app.state.malware_label_encoder

        # Run preprocessing (imputing, feature selection, scaling)
        X_scaled = preprocess_malware_data(df, scaler)

        # Run prediction
        predictions = model.predict(X_scaled)
        
        # Decode target labels
        decoded_labels = label_encoder.inverse_transform(predictions)

        # Get confidence/probabilities
        if hasattr(model, "predict_proba"):
            probs = model.predict_proba(X_scaled)
            confidences = np.max(probs, axis=1).tolist()
        else:
            # Fallback if model does not support predict_proba
            confidences = [1.0] * len(predictions)

        # Generate list of individual predictions
        results = []
        for idx, (label, conf) in enumerate(zip(decoded_labels, confidences)):
            details = get_malware_threat_details(label, conf)
            results.append({
                "row_index": idx,
                "prediction": str(label),
                "confidence": round(float(conf), 4),
                "risk_level": details["risk_level"],
                "recommendation": details["recommendation"]
            })

        # Determine overall threat summary (highest threat in the batch)
        highest_threat_result = max(results, key=lambda x: RISK_PRIORITY.get(x["risk_level"], 0))

        return {
            "prediction": highest_threat_result["prediction"],
            "confidence": highest_threat_result["confidence"],
            "risk_level": highest_threat_result["risk_level"],
            "recommendation": highest_threat_result["recommendation"],
            "is_batch": len(results) > 1,
            "total_samples": len(results),
            "results": results
        }

    except ValueError as val_err:
        logger.warning(f"Validation error in malware processing: {str(val_err)}")
        raise HTTPException(status_code=400, detail=str(val_err))
    except Exception as e:
        logger.error(f"Prediction logic error: {str(e)}")
        raise HTTPException(status_code=500, detail=f"An error occurred during prediction processing: {str(e)}")