CodebaseAi commited on
Commit
87f8e11
Β·
1 Parent(s): bf30d02

deploy: updated backend structure and ignored frontend

Browse files
Files changed (45) hide show
  1. .gitignore +55 -12
  2. backend/Dockerfile β†’ Dockerfile +0 -0
  3. backend/app.py β†’ app.py +2 -1
  4. backend/utils/model_selector.py +0 -116
  5. {backend/capture β†’ capture}/__init__.py +0 -0
  6. {backend/capture β†’ capture}/live_capture.py +0 -0
  7. {backend/capture β†’ capture}/live_manager.py +0 -0
  8. backend/extensions.py β†’ extensions.py +0 -0
  9. backend/flow_builder.py β†’ flow_builder.py +0 -0
  10. {backend/generated_reports β†’ generated_reports}/traffic_logs.csv +0 -0
  11. backend/list_groq_models.py β†’ list_groq_models.py +0 -0
  12. {backend/logs β†’ logs}/bcc_logs.csv +0 -0
  13. {backend/logs β†’ logs}/cicids_logs.csv +0 -0
  14. {backend/reporting β†’ reporting}/pdf_report.py +0 -0
  15. backend/requirements.txt β†’ requirements.txt +0 -0
  16. backend/retrain_requests.jsonl β†’ retrain_requests.jsonl +0 -0
  17. {backend/routes β†’ routes}/__init__.py +0 -0
  18. {backend/routes β†’ routes}/ai_route.py +0 -0
  19. {backend/routes β†’ routes}/alerts_route.py +0 -0
  20. {backend/routes β†’ routes}/chat_route.py +0 -0
  21. {backend/routes β†’ routes}/geo_route.py +0 -0
  22. {backend/routes β†’ routes}/ip_lookup_route.py +0 -0
  23. {backend/routes β†’ routes}/live_route.py +0 -0
  24. {backend/routes β†’ routes}/logs_route.py +0 -0
  25. {backend/routes β†’ routes}/manual_predict_route.py +0 -0
  26. {backend/routes β†’ routes}/ml_route.py +0 -0
  27. {backend/routes β†’ routes}/ml_switch_route.py +0 -0
  28. {backend/routes β†’ routes}/offline_detection.py +0 -0
  29. {backend/routes β†’ routes}/predict_route.py +0 -0
  30. {backend/routes β†’ routes}/reports_route.py +0 -0
  31. {backend/routes β†’ routes}/system_info.py +0 -0
  32. {backend/routes β†’ routes}/traffic_routes.py +0 -0
  33. {backend/sample β†’ sample}/bcc_sample.csv +0 -0
  34. {backend/sample β†’ sample}/cicids_sample.csv +0 -0
  35. backend/socket_manager.py β†’ socket_manager.py +0 -0
  36. {backend/uploads β†’ uploads}/bcc_sample.csv +0 -0
  37. {backend/uploads β†’ uploads}/cicids_sample.csv +0 -0
  38. {backend/uploads β†’ uploads}/cicids_sample_1.csv +0 -0
  39. {backend/uploads β†’ uploads}/iris.csv +0 -0
  40. {backend/utils β†’ utils}/ai_engine.py +0 -0
  41. {backend/utils β†’ utils}/geo_lookup.py +0 -0
  42. {backend/utils β†’ utils}/logger.py +0 -0
  43. utils/model_selector.py +95 -0
  44. {backend/utils β†’ utils}/pcap_to_csv.py +0 -0
  45. {backend/utils β†’ utils}/risk_engine.py +0 -0
.gitignore CHANGED
@@ -1,18 +1,61 @@
1
- # --- SENSITIVE KEYS (Never Push) ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  .env
3
- backend/.env
4
- frontend/.env
5
- *.env
 
 
 
 
 
 
6
 
7
- # --- HEAVY FOLDERS (Never Push) ---
 
 
8
  node_modules/
9
- frontend/node_modules/
10
- backend/env/
11
- env/
12
- __pycache__/
13
- backend/__pycache__/
14
  dist/
15
  build/
16
 
17
- # --- ML MODELS (Ignore entire folder over 100MB) ---
18
- backend/ml_models/
 
 
 
 
 
 
 
 
 
 
 
1
+ # --- Python Specific ---
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ env/
8
+ venv/
9
+ .venv/
10
+ pip-log.txt
11
+ pip-delete-this-directory.txt
12
+ .tox/
13
+ .coverage
14
+ .coverage.*
15
+ .cache
16
+ nosetests.xml
17
+ coverage.xml
18
+ *.cover
19
+ .hypothesis/
20
+ .pytest_cache/
21
+
22
+ # --- ML Models (Ignored because they are on the HF Hub) ---
23
+ # We ignore the local folder to prevent 1.5GB pushes
24
+ ml_models/
25
+ *.joblib
26
+ *.pkl
27
+ *.pth
28
+ *.onnx
29
+
30
+ # --- Environment & Secrets ---
31
+ # Never push your API keys or email passwords
32
  .env
33
+ .flaskenv
34
+ secrets.json
35
+
36
+ # --- OS Specific ---
37
+ .DS_Store
38
+ .DS_Store?
39
+ ._*
40
+ Thumbs.db
41
+ desktop.ini
42
 
43
+ # --- Frontend (Excluding local frontend code if in same repo) ---
44
+ # Since you'll deploy the frontend separately to Vercel
45
+ frontend/
46
  node_modules/
 
 
 
 
 
47
  dist/
48
  build/
49
 
50
+ # --- Logs & Reports ---
51
+ *.log
52
+ backend/reporting/*.pdf
53
+ backend/reporting/*.csv
54
+
55
+ # --- Docker ---
56
+ .dockerignore
57
+
58
+ # Fonts and Media
59
+ backend/reporting/*.ttf
60
+ frontend/public/*.mp3
61
+ frontend/src/assests/*.png
backend/Dockerfile β†’ Dockerfile RENAMED
File without changes
backend/app.py β†’ app.py RENAMED
@@ -97,5 +97,6 @@ def home():
97
 
98
  if __name__ == "__main__":
99
  print("πŸš€ Starting Adaptive AI NIDS Backend...")
100
- socketio.run(app, host="0.0.0.0", port=5000, debug=False)
 
101
 
 
97
 
98
  if __name__ == "__main__":
99
  print("πŸš€ Starting Adaptive AI NIDS Backend...")
100
+ # 7860 is the magic number for Hugging Face
101
+ socketio.run(app, host="0.0.0.0", port=7860, debug=False)
102
 
backend/utils/model_selector.py DELETED
@@ -1,116 +0,0 @@
1
- import os
2
- import joblib
3
- import threading
4
- import traceback
5
-
6
- # Global active model (default = bcc so your current flow remains unchanged)
7
- ACTIVE_MODEL = "bcc"
8
- _ACTIVE_LOCK = threading.Lock()
9
-
10
- # Cache loaded models to avoid repeated disk loads
11
- _MODEL_CACHE = {}
12
- ML_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "ml_models"))
13
- print("[model_selector] ML_DIR =", ML_DIR)
14
- try:
15
- print("[model_selector] ML_DIR files:", os.listdir(ML_DIR))
16
- except Exception as e:
17
- print("[model_selector] Could not list ML_DIR:", e)
18
-
19
-
20
- def _try_load(path):
21
- """Try to joblib.load(path). On failure return None but print full traceback."""
22
- if not os.path.exists(path):
23
- print(f"[model_selector] SKIP (not found): {path}")
24
- return None
25
- try:
26
- print(f"[model_selector] Attempting to load: {path}")
27
- obj = joblib.load(path)
28
- print(f"[model_selector] Successfully loaded: {os.path.basename(path)}")
29
- return obj
30
- except Exception as e:
31
- print(f"[model_selector] FAILED to load {path}: {e}")
32
- traceback.print_exc()
33
- return None
34
-
35
- def load_model(model_key):
36
- """Return a dict with keys depending on model. Caches result."""
37
- if model_key in _MODEL_CACHE:
38
- return _MODEL_CACHE[model_key]
39
-
40
- if model_key == "bcc":
41
- # original BCC artifact names (your working files)
42
- model_path = os.path.join(ML_DIR, "realtime_model.pkl")
43
- scaler_path = os.path.join(ML_DIR, "realtime_scaler.pkl")
44
- encoder_path = os.path.join(ML_DIR, "realtime_encoder.pkl")
45
-
46
- model = _try_load(model_path)
47
- scaler = _try_load(scaler_path)
48
- encoder = _try_load(encoder_path)
49
-
50
- if model is None:
51
- print(f"[model_selector] WARNING: bcc model not found at {model_path}")
52
- _MODEL_CACHE["bcc"] = {"model": model, "scaler": scaler, "encoder": encoder}
53
- return _MODEL_CACHE["bcc"]
54
-
55
- if model_key == "cicids":
56
- # Prefer the RF pipeline you requested; try common names in preferred order
57
- candidate_models = [
58
- "rf_pipeline.joblib", # preferred - your RF pipeline
59
- "cicids_rf.joblib",
60
- "rf_pipeline.pkl",
61
- "cicids_model.joblib",
62
- "lgb_pipeline.joblib",
63
- "cicids_rf.pkl",
64
- ]
65
- # prefer 'training_artifacts' or 'cicids_artifacts'
66
- candidate_artifacts = [
67
- "training_artifacts.joblib",
68
- "training_artifacts.pkl",
69
- "cicids_artifacts.joblib",
70
- "cicids_artifacts.pkl",
71
- "artifacts.joblib",
72
- "artifacts.pkl"
73
- ]
74
-
75
- model = None
76
- artifacts = None
77
- for fn in candidate_models:
78
- p = os.path.join(ML_DIR, fn)
79
- model = _try_load(p)
80
- if model is not None:
81
- print(f"[model_selector] Loaded cicids model from {p}")
82
- break
83
-
84
- for fn in candidate_artifacts:
85
- p = os.path.join(ML_DIR, fn)
86
- artifacts = _try_load(p)
87
- if artifacts is not None:
88
- print(f"[model_selector] Loaded cicids artifacts from {p}")
89
- break
90
-
91
- if model is None:
92
- print("[model_selector] WARNING: No cicids model found in ml_models.")
93
- if artifacts is None:
94
- print("[model_selector] WARNING: No cicids artifacts found in ml_models.")
95
-
96
- # artifacts expected to include: 'scaler' and 'features' at minimum
97
- _MODEL_CACHE["cicids"] = {
98
- "model": model,
99
- "artifacts": artifacts
100
- }
101
- return _MODEL_CACHE["cicids"]
102
-
103
- raise ValueError("Unknown model_key")
104
-
105
- def set_active_model(key: str):
106
- global ACTIVE_MODEL
107
- if key not in ("bcc", "cicids"):
108
- raise ValueError("Active model must be 'bcc' or 'cicids'")
109
- with _ACTIVE_LOCK:
110
- ACTIVE_MODEL = key
111
- print(f"[model_selector] ACTIVE_MODEL set to: {ACTIVE_MODEL}")
112
-
113
- def get_active_model():
114
- return ACTIVE_MODEL
115
-
116
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
{backend/capture β†’ capture}/__init__.py RENAMED
File without changes
{backend/capture β†’ capture}/live_capture.py RENAMED
File without changes
{backend/capture β†’ capture}/live_manager.py RENAMED
File without changes
backend/extensions.py β†’ extensions.py RENAMED
File without changes
backend/flow_builder.py β†’ flow_builder.py RENAMED
File without changes
{backend/generated_reports β†’ generated_reports}/traffic_logs.csv RENAMED
File without changes
backend/list_groq_models.py β†’ list_groq_models.py RENAMED
File without changes
{backend/logs β†’ logs}/bcc_logs.csv RENAMED
File without changes
{backend/logs β†’ logs}/cicids_logs.csv RENAMED
File without changes
{backend/reporting β†’ reporting}/pdf_report.py RENAMED
File without changes
backend/requirements.txt β†’ requirements.txt RENAMED
File without changes
backend/retrain_requests.jsonl β†’ retrain_requests.jsonl RENAMED
File without changes
{backend/routes β†’ routes}/__init__.py RENAMED
File without changes
{backend/routes β†’ routes}/ai_route.py RENAMED
File without changes
{backend/routes β†’ routes}/alerts_route.py RENAMED
File without changes
{backend/routes β†’ routes}/chat_route.py RENAMED
File without changes
{backend/routes β†’ routes}/geo_route.py RENAMED
File without changes
{backend/routes β†’ routes}/ip_lookup_route.py RENAMED
File without changes
{backend/routes β†’ routes}/live_route.py RENAMED
File without changes
{backend/routes β†’ routes}/logs_route.py RENAMED
File without changes
{backend/routes β†’ routes}/manual_predict_route.py RENAMED
File without changes
{backend/routes β†’ routes}/ml_route.py RENAMED
File without changes
{backend/routes β†’ routes}/ml_switch_route.py RENAMED
File without changes
{backend/routes β†’ routes}/offline_detection.py RENAMED
File without changes
{backend/routes β†’ routes}/predict_route.py RENAMED
File without changes
{backend/routes β†’ routes}/reports_route.py RENAMED
File without changes
{backend/routes β†’ routes}/system_info.py RENAMED
File without changes
{backend/routes β†’ routes}/traffic_routes.py RENAMED
File without changes
{backend/sample β†’ sample}/bcc_sample.csv RENAMED
File without changes
{backend/sample β†’ sample}/cicids_sample.csv RENAMED
File without changes
backend/socket_manager.py β†’ socket_manager.py RENAMED
File without changes
{backend/uploads β†’ uploads}/bcc_sample.csv RENAMED
File without changes
{backend/uploads β†’ uploads}/cicids_sample.csv RENAMED
File without changes
{backend/uploads β†’ uploads}/cicids_sample_1.csv RENAMED
File without changes
{backend/uploads β†’ uploads}/iris.csv RENAMED
File without changes
{backend/utils β†’ utils}/ai_engine.py RENAMED
File without changes
{backend/utils β†’ utils}/geo_lookup.py RENAMED
File without changes
{backend/utils β†’ utils}/logger.py RENAMED
File without changes
utils/model_selector.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import joblib
3
+ import threading
4
+ import traceback
5
+ from huggingface_hub import hf_hub_download
6
+
7
+ # --- CONFIGURATION ---
8
+ HF_REPO_ID = "CodebaseAi/netraids-ml-models" # Replace with your actual public repo ID
9
+ # ---------------------
10
+
11
+ ACTIVE_MODEL = "bcc"
12
+ _ACTIVE_LOCK = threading.Lock()
13
+ _MODEL_CACHE = {}
14
+
15
+ # 1. FIXED PATH LOGIC:
16
+ # __file__ is /app/utils/model_selector.py
17
+ # dirname(__file__) is /app/utils
18
+ # dirname(dirname(...)) is /app (the ROOT)
19
+ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
20
+ ML_DIR = os.path.join(BASE_DIR, "ml_models")
21
+
22
+ # Ensure the local ml_models directory exists for caching
23
+ if not os.path.exists(ML_DIR):
24
+ os.makedirs(ML_DIR, exist_ok=True)
25
+
26
+ print(f"[model_selector] ROOT BASE_DIR: {BASE_DIR}")
27
+ print(f"[model_selector] ML_DIR: {ML_DIR}")
28
+
29
+ def _get_model_path(filename):
30
+ """
31
+ First looks in the local 'ml_models' folder.
32
+ If not found, downloads from the public Hugging Face Hub.
33
+ """
34
+ local_path = os.path.join(ML_DIR, filename)
35
+
36
+ # 1. Check if the file is already there
37
+ if os.path.exists(local_path):
38
+ return local_path
39
+
40
+ # 2. Download from Hub if missing
41
+ try:
42
+ print(f"[model_selector] {filename} not found locally. Downloading from Hub...")
43
+ # We specify local_dir to force it into our ml_models folder
44
+ downloaded_path = hf_hub_download(
45
+ repo_id=HF_REPO_ID,
46
+ filename=filename,
47
+ local_dir=ML_DIR
48
+ )
49
+ return downloaded_path
50
+ except Exception as e:
51
+ print(f"[model_selector] ERROR: Could not find/download {filename}: {e}")
52
+ return None
53
+
54
+ def _try_load(filename):
55
+ path = _get_model_path(filename)
56
+ if not path or not os.path.exists(path):
57
+ print(f"[model_selector] SKIP: {filename} path invalid.")
58
+ return None
59
+ try:
60
+ return joblib.load(path)
61
+ except Exception as e:
62
+ print(f"[model_selector] FAILED to load {filename}: {e}")
63
+ return None
64
+
65
+ def load_model(model_key):
66
+ if model_key in _MODEL_CACHE:
67
+ return _MODEL_CACHE[model_key]
68
+
69
+ if model_key == "bcc":
70
+ _MODEL_CACHE["bcc"] = {
71
+ "model": _try_load("realtime_model.pkl"),
72
+ "scaler": _try_load("realtime_scaler.pkl"),
73
+ "encoder": _try_load("realtime_encoder.pkl")
74
+ }
75
+ return _MODEL_CACHE["bcc"]
76
+
77
+ if model_key == "cicids":
78
+ # It will look for your RF files in the Hub
79
+ _MODEL_CACHE["cicids"] = {
80
+ "model": _try_load("rf_pipeline.joblib"),
81
+ "artifacts": _try_load("training_artifacts.joblib")
82
+ }
83
+ return _MODEL_CACHE["cicids"]
84
+
85
+ raise ValueError(f"Unknown model_key: {model_key}")
86
+
87
+ def set_active_model(key: str):
88
+ global ACTIVE_MODEL
89
+ with _ACTIVE_LOCK:
90
+ ACTIVE_MODEL = key
91
+ print(f"[model_selector] ACTIVE_MODEL set to: {ACTIVE_MODEL}")
92
+
93
+ def get_active_model():
94
+ return ACTIVE_MODEL
95
+
{backend/utils β†’ utils}/pcap_to_csv.py RENAMED
File without changes
{backend/utils β†’ utils}/risk_engine.py RENAMED
File without changes