Skip to content

Commit b18c7b8

Browse files
authored
fix #3: add setup_model.py to auto-generate data and train model on first run
1 parent 5cdc449 commit b18c7b8

1 file changed

Lines changed: 62 additions & 0 deletions

File tree

setup_model.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Fix #3: Model Setup Script
4+
5+
This script auto-generates training data and trains the Isolation Forest model
6+
if the .pkl files are missing. Run this ONCE after cloning the repo before
7+
starting the backend server.
8+
9+
Usage:
10+
python setup_model.py
11+
"""
12+
import os
13+
import sys
14+
15+
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
16+
MODEL_FILE = os.path.join(BASE_DIR, "ai-model", "isolation_forest_model.pkl")
17+
ENCODERS_FILE = os.path.join(BASE_DIR, "ai-model", "encoders.pkl")
18+
DATA_FILE = os.path.join(BASE_DIR, "data", "generated_logs.csv")
19+
20+
def main():
21+
print("=" * 50)
22+
print("AI Security Monitor - Model Setup")
23+
print("=" * 50)
24+
25+
# Step 1: Generate training data if missing
26+
if not os.path.exists(DATA_FILE):
27+
print("[1/2] Generating training data...")
28+
sys.path.insert(0, os.path.join(BASE_DIR, "backend"))
29+
try:
30+
from log_generator import generate_logs
31+
generate_logs()
32+
print(f" Data saved to: {DATA_FILE}")
33+
except ImportError:
34+
print(" Running log_generator.py directly...")
35+
os.system(f"{sys.executable} backend/log_generator.py")
36+
else:
37+
print(f"[1/2] Training data already exists: {DATA_FILE}")
38+
39+
# Step 2: Train model if .pkl files are missing
40+
if not os.path.exists(MODEL_FILE) or not os.path.exists(ENCODERS_FILE):
41+
print("[2/2] Training Isolation Forest model...")
42+
os.system(f"{sys.executable} ai-model/train_model.py")
43+
if os.path.exists(MODEL_FILE):
44+
print(f" Model saved to: {MODEL_FILE}")
45+
print(f" Encoders saved to: {ENCODERS_FILE}")
46+
else:
47+
print(" ERROR: Model training failed. Check the output above.")
48+
sys.exit(1)
49+
else:
50+
print(f"[2/2] Model files already exist:")
51+
print(f" {MODEL_FILE}")
52+
print(f" {ENCODERS_FILE}")
53+
54+
print("")
55+
print("Setup complete! You can now run:")
56+
print(" docker-compose up --build # Full Docker setup")
57+
print(" OR")
58+
print(" cd backend && uvicorn main:app --reload # Local backend")
59+
print(" cd frontend && npm run dev # Local frontend")
60+
61+
if __name__ == "__main__":
62+
main()

0 commit comments

Comments
 (0)