Repository navigation
Expand file tree
/
Copy pathrun.py
More file actions
220 lines (182 loc) · 7.37 KB
/
Copy pathrun.py
File metadata and controls
220 lines (182 loc) · 7.37 KB
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
import subprocess
import sys
import os
import tempfile
def show_menu():
"""Display menu and get user choice"""
print("\nOptions:")
print(" 1. Run all notebooks")
print(" 2. Launch dashboard (Streamlit)")
print(" 3. Compile report (LaTeX to PDF)")
print(" 4. Run notebooks, compile report, then launch dashboard")
print(" 5. Exit")
print()
while True:
choice = input("Enter choice (1-5): ").strip()
if choice in ['1', '2', '3', '4', '5']:
return choice
print("Invalid choice. Please enter 1, 2, 3, 4, or 5.")
def compile_report():
"""Compile the LaTeX report to PDF"""
print("\n--- Compiling LaTeX Report ---")
report_dir = os.path.join(os.path.dirname(__file__), "report")
tex_file = os.path.join(report_dir, "report.tex")
if not os.path.exists(tex_file):
print("Error: report/report.tex not found!")
return False
# Check if pdflatex is available
try:
subprocess.run(["pdflatex", "--version"], capture_output=True, check=True)
except (subprocess.CalledProcessError, FileNotFoundError):
print("Error: pdflatex not found!")
print("\nTo install LaTeX:")
print(" Windows: Install MiKTeX from https://miktex.org/download")
print(" macOS: brew install --cask mactex")
print(" Linux: sudo apt install texlive-full")
return False
print(f"Compiling {tex_file}...")
# Run pdflatex twice for references/TOC
try:
for run in range(2):
result = subprocess.run(
["pdflatex", "-interaction=nonstopmode", "-output-directory", report_dir, tex_file],
capture_output=True,
text=True,
cwd=report_dir
)
if result.returncode != 0 and run == 1:
print(f"Warning: pdflatex returned non-zero exit code")
# Check if PDF was still generated
if not os.path.exists(os.path.join(report_dir, "report.pdf")):
print("Error: PDF was not generated")
print("Check report/report.log for details")
return False
pdf_path = os.path.join(report_dir, "report.pdf")
if os.path.exists(pdf_path):
print(f" -> Success! PDF saved to: {pdf_path}")
return True
else:
print("Error: PDF was not generated")
return False
except Exception as e:
print(f"Error compiling report: {e}")
return False
def launch_dashboard():
"""Launch the Streamlit dashboard"""
print("\n--- Launching Dashboard ---")
app_path = os.path.join(os.path.dirname(__file__), "app.py")
if not os.path.exists(app_path):
print("Error: app.py not found!")
return False
print("Starting Streamlit server...")
print("Dashboard will open in your browser at http://localhost:8501")
print("Press Ctrl+C to stop the server\n")
try:
subprocess.run([sys.executable, "-m", "streamlit", "run", app_path], check=True)
except KeyboardInterrupt:
print("\nDashboard stopped.")
except Exception as e:
print(f"Error launching dashboard: {e}")
print("Try running manually: streamlit run app.py")
return False
return True
def install_packages():
"""Install required packages"""
print("\n--- Installing packages ---")
try:
subprocess.run([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"], check=True)
print("Packages installed successfully!\n")
except:
print("Error installing packages. Please run: pip install -r requirements.txt")
sys.exit(1)
def run_notebooks():
"""Run all notebooks"""
print("--- Running notebooks ---")
print("(Note: Any joblib KeyError warnings are harmless cleanup messages)\n")
# Ensure joblib has a safe temp directory to avoid resource tracker errors
# joblib is a Python library that provides tools for lightweight parallel computing and function caching
joblib_tmp = os.path.join(tempfile.gettempdir(), "joblib_temp")
os.makedirs(joblib_tmp, exist_ok=True)
os.environ["JOBLIB_TEMP_FOLDER"] = joblib_tmp
# Suppress harmless joblib resource tracker warnings
# These KeyError warnings are from cleanup race conditions and don't affect results
# See: https://github.com/joblib/joblib/issues/1076
# https://github.com/joblib/loky/issues/368
# https://github.com/joblib/joblib/issues/1243
# The issue occurs when atexit finalizers delete temp folders before resource_tracker
# processes all cleanup commands, causing harmless KeyErrors during shutdown
os.environ["PYTHONWARNINGS"] = "ignore::ResourceWarning"
os.environ["LOKY_MAX_CPU_COUNT"] = "4"
# Set Python to ignore warnings for the subprocess kernels
import warnings
warnings.filterwarnings('ignore')
notebooks = [
"notebooks/00_data_analysis.ipynb",
"notebooks/01_linear_regression.ipynb",
"notebooks/02_logistic_regression.ipynb",
"notebooks/03_naive_bayes.ipynb",
"notebooks/04_random_forest.ipynb",
"notebooks/05_xgboost.ipynb",
"notebooks/06_testing.ipynb"
]
import nbformat
from nbclient import NotebookClient
for notebook in notebooks:
if not os.path.exists(notebook):
print(f"Skipping {notebook} - not found")
continue
print(f"Running {notebook}...")
try:
with open(notebook, 'r', encoding='utf-8') as f:
nb = nbformat.read(f, as_version=4)
client = NotebookClient(nb, timeout=600, kernel_name='python3',
resources={'metadata': {'path': 'notebooks/'}})
client.execute()
with open(notebook, 'w', encoding='utf-8') as f:
nbformat.write(nb, f)
print(f" -> Done\n")
except Exception as e:
print(f" -> Error: {e}\n")
if __name__ == "__main__":
print("\n" + "="*50)
print(" Malware Classification Project")
print("="*50)
# Check if dataset exists
if os.path.exists("dataset/processed_dataset.csv"):
print("\nDataset found: dataset/processed_dataset.csv")
else:
print("\nWarning: Dataset not found!")
# Check if results exist
if os.path.exists("results/random_forest_results.json"):
print("Results found: results/*.json")
else:
print("Results not found - run notebooks first")
# Show menu and handle choice
choice = show_menu()
if choice == '1':
# Run notebooks only
install_packages()
run_notebooks()
print("\n" + "="*50)
print(" Done! Check the notebooks and results folder")
print("="*50 + "\n")
elif choice == '2':
# Launch dashboard only
launch_dashboard()
elif choice == '3':
# Compile report only
compile_report()
elif choice == '4':
# Run notebooks, compile report, then launch dashboard
install_packages()
run_notebooks()
print("\n" + "="*50)
print(" Notebooks complete! Compiling report...")
print("="*50 + "\n")
compile_report()
print("\n" + "="*50)
print(" Report compiled! Launching dashboard...")
print("="*50 + "\n")
launch_dashboard()
elif choice == '5':
sys.exit(0)