Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

app.py 9.1 KB

You have to be logged in to leave a comment. Sign In
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
  1. import os
  2. import sys
  3. import json
  4. import numpy as np
  5. import pandas as pd
  6. from fastapi import FastAPI, HTTPException, Request
  7. from fastapi.responses import JSONResponse
  8. from fastapi.middleware.cors import CORSMiddleware
  9. from pydantic import BaseModel, Field
  10. from typing import Dict, List, Any, Optional
  11. import mlflow
  12. import mlflow.sklearn
  13. import uvicorn
  14. from contextlib import asynccontextmanager
  15. from networksecurity.exception.exception import NetworkSecurityException
  16. from networksecurity.logging.logger import logging
  17. from networksecurity.utils.main_utils import load_object
  18. # Define paths for model and preprocessor
  19. MODEL_PATH = os.path.join("artifact", "model_trainer", "model", "model.pkl")
  20. # Find the latest model artifact directory
  21. def find_latest_model():
  22. artifact_dir = "artifact"
  23. if not os.path.exists(artifact_dir):
  24. return MODEL_PATH
  25. # Get all timestamp directories
  26. timestamp_dirs = [d for d in os.listdir(artifact_dir)
  27. if os.path.isdir(os.path.join(artifact_dir, d)) and
  28. d[0].isdigit()]
  29. if not timestamp_dirs:
  30. return MODEL_PATH
  31. # Sort by timestamp (newest first)
  32. timestamp_dirs.sort(reverse=True)
  33. # Find the first directory that contains a model
  34. for ts_dir in timestamp_dirs:
  35. model_path = os.path.join(artifact_dir, ts_dir, "model_trainer", "trained_model", "model.pkl")
  36. if os.path.exists(model_path):
  37. return model_path
  38. return MODEL_PATH
  39. # Use the latest model
  40. LATEST_MODEL_PATH = find_latest_model()
  41. # Define lifespan to load model on startup
  42. @asynccontextmanager
  43. async def lifespan(app: FastAPI):
  44. # Load model on startup
  45. try:
  46. app.state.model = load_object(LATEST_MODEL_PATH)
  47. logging.info(f"Model loaded from {LATEST_MODEL_PATH}")
  48. logging.info("Model loaded successfully")
  49. except Exception as e:
  50. logging.error(f"Error loading model: {e}")
  51. app.state.model = None
  52. yield
  53. # Cleanup on shutdown
  54. app.state.model = None
  55. # Initialize FastAPI app
  56. app = FastAPI(
  57. title="Network Security Classification API",
  58. description="API for classifying network security threats",
  59. version="1.0.0",
  60. lifespan=lifespan
  61. )
  62. # Add CORS middleware
  63. app.add_middleware(
  64. CORSMiddleware,
  65. allow_origins=["*"],
  66. allow_credentials=True,
  67. allow_methods=["*"],
  68. allow_headers=["*"],
  69. )
  70. # Define input schema for text-based classification
  71. class TextInput(BaseModel):
  72. text: str = Field(..., description="Text to classify for security threats")
  73. # Define input schema for feature-based classification (keeping for backward compatibility)
  74. class NetworkFeatures(BaseModel):
  75. features: List[List[float]] = Field(..., description="List of feature vectors to classify")
  76. feature_names: Optional[List[str]] = Field(None, description="Names of features in the same order as the feature vectors")
  77. # Define output schema
  78. class PredictionResponse(BaseModel):
  79. predictions: List[int] = Field(..., description="Predicted class labels")
  80. prediction_probabilities: Optional[List[Dict[str, float]]] = Field(None, description="Prediction probabilities for each class")
  81. # Error handler
  82. @app.exception_handler(Exception)
  83. async def global_exception_handler(request: Request, exc: Exception):
  84. return JSONResponse(
  85. status_code=500,
  86. content={"message": f"An error occurred: {str(exc)}"}
  87. )
  88. # Health check endpoint
  89. @app.get("/health")
  90. async def health_check():
  91. if app.state.model is None:
  92. raise HTTPException(status_code=503, detail="Model not loaded")
  93. return {"status": "healthy", "model_loaded": True}
  94. # Text-based prediction endpoint
  95. @app.post("/predict/text", response_model=PredictionResponse)
  96. async def predict_text(request: TextInput):
  97. if app.state.model is None:
  98. raise HTTPException(status_code=503, detail="Model not loaded")
  99. try:
  100. # Process the text to extract features
  101. text = request.text.lower()
  102. # Extract the same features we used during training
  103. features = [
  104. # Text length (normalized)
  105. min(len(request.text) / 5000.0, 1.0),
  106. # Word count (normalized)
  107. min(len(request.text.split()) / 500.0, 1.0),
  108. # Keyword-based features
  109. 0.7 if 'malware' in text else 0.0,
  110. 0.6 if 'trojan' in text else 0.0,
  111. 0.6 if 'virus' in text else 0.0,
  112. 0.8 if 'ransomware' in text else 0.0,
  113. 0.4 if 'attack' in text else 0.0,
  114. 0.3 if 'threat' in text else 0.0,
  115. 0.5 if 'vulnerability' in text else 0.0,
  116. 0.5 if 'exploit' in text else 0.0,
  117. 0.2 if 'security' in text else 0.0,
  118. ]
  119. # Convert to numpy array and reshape for prediction
  120. features_array = np.array([features])
  121. # Make predictions
  122. predictions = app.state.model.predict(features_array)
  123. # Get prediction probabilities if available
  124. prediction_probs = None
  125. if hasattr(app.state.model, "predict_proba"):
  126. probs = app.state.model.predict_proba(features_array)
  127. prediction_probs = []
  128. for prob in probs:
  129. prob_dict = {str(i): float(p) for i, p in enumerate(prob)}
  130. prediction_probs.append(prob_dict)
  131. # Return predictions with interpretation
  132. result = {
  133. "predictions": predictions.tolist(),
  134. "prediction_probabilities": prediction_probs,
  135. "interpretation": "Malware detected" if predictions[0] == 1 else "No malware detected"
  136. }
  137. return result
  138. except Exception as e:
  139. logging.error(f"Prediction error: {e}")
  140. raise HTTPException(status_code=500, detail=f"Prediction error: {str(e)}")
  141. # Original feature-based prediction endpoint (keeping for backward compatibility)
  142. @app.post("/predict", response_model=PredictionResponse)
  143. async def predict(request: NetworkFeatures):
  144. if app.state.model is None:
  145. raise HTTPException(status_code=503, detail="Model not loaded")
  146. try:
  147. # Convert input to numpy array
  148. features = np.array(request.features)
  149. # Make predictions
  150. predictions = app.state.model.predict(features)
  151. # Get prediction probabilities if available
  152. prediction_probs = None
  153. if hasattr(app.state.model, "predict_proba"):
  154. probs = app.state.model.predict_proba(features)
  155. prediction_probs = []
  156. for prob in probs:
  157. prob_dict = {str(i): float(p) for i, p in enumerate(prob)}
  158. prediction_probs.append(prob_dict)
  159. # Return predictions
  160. return {
  161. "predictions": predictions.tolist(),
  162. "prediction_probabilities": prediction_probs
  163. }
  164. except Exception as e:
  165. logging.error(f"Prediction error: {e}")
  166. raise HTTPException(status_code=500, detail=f"Prediction error: {str(e)}")
  167. # MLflow integration endpoint
  168. @app.get("/model-info")
  169. async def model_info():
  170. try:
  171. # Try to get model info from MLflow if available
  172. try:
  173. mlflow.set_tracking_uri("https://dagshub.com/austinLorenzMccoy/networkSecurity_project.mlflow")
  174. model_info = mlflow.search_registered_models(filter_string="name='NetworkSecurityModel'")
  175. if model_info and len(model_info) > 0:
  176. latest_version = model_info[0].latest_versions[0]
  177. return {
  178. "model_name": "NetworkSecurityModel",
  179. "version": latest_version.version,
  180. "status": latest_version.status,
  181. "creation_timestamp": latest_version.creation_timestamp,
  182. "last_updated_timestamp": latest_version.last_updated_timestamp,
  183. "metrics": {
  184. "accuracy": latest_version.run.data.metrics.get("test_accuracy", None),
  185. "f1_score": latest_version.run.data.metrics.get("test_f1", None)
  186. }
  187. }
  188. except Exception as mlflow_error:
  189. logging.warning(f"MLflow connection error: {mlflow_error}")
  190. # If MLflow connection fails, try to get metrics from local file
  191. try:
  192. with open("reports/metrics.json", "r") as f:
  193. metrics = json.load(f)
  194. return {
  195. "model_name": "NetworkSecurityModel (Local)",
  196. "version": "1.0.0",
  197. "status": "READY",
  198. "metrics": metrics
  199. }
  200. except Exception as file_error:
  201. logging.warning(f"Local metrics file error: {file_error}")
  202. return {"message": "No model information available from MLflow or local files"}
  203. except Exception as e:
  204. logging.error(f"Error getting model info: {e}")
  205. return {"message": f"Error getting model info: {str(e)}"}
  206. # Run the app
  207. if __name__ == "__main__":
  208. try:
  209. uvicorn.run("app:app", host="0.0.0.0", port=8000, reload=True)
  210. except Exception as e:
  211. raise NetworkSecurityException(e, sys)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...