-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1109 lines (928 loc) · 37.9 KB
/
app.py
File metadata and controls
1109 lines (928 loc) · 37.9 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
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import logging
import threading
import subprocess
import tempfile
from pathlib import Path
from typing import Optional, Tuple, Union
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
class LazyLoader:
"""
Lazy module loader that imports modules only when they're first accessed.
This helps reduce startup time by deferring heavy imports until they're needed.
Args:
module_name (str): Name of the module to lazy load
"""
def __init__(self, module_name):
"""Initialize the lazy loader with the module name."""
self.module_name = module_name
self.module = None
def __getattr__(self, name):
"""
Load the module on first access and return the requested attribute.
Args:
name (str): Name of the attribute to access
Returns:
Any: The requested attribute from the loaded module
"""
if self.module is None:
self.module = __import__(self.module_name, fromlist=['*'])
return getattr(self.module, name)
lazy_imports = {
'PIL': LazyLoader('PIL'),
'numpy': LazyLoader('numpy'),
'ttkbootstrap': LazyLoader('ttkbootstrap'),
'matplotlib': LazyLoader('matplotlib'),
'pandas': LazyLoader('pandas'),
'tensorflow': LazyLoader('tensorflow')
}
def lazy_import(module_name: str, attrs: Optional[list] = None):
"""
Lazy import utility function that loads modules only when needed.
Args:
module_name (str): Name of the module to import
attrs (Optional[list]): List of attributes to import from the module
If None, returns the entire module
If single attribute, returns that attribute
If multiple attributes, returns a tuple of attributes
Returns:
Any: The imported module or requested attributes
"""
if module_name not in lazy_imports:
lazy_imports[module_name] = LazyLoader(module_name)
module = lazy_imports[module_name]
if attrs:
if len(attrs) == 1:
return getattr(module, attrs[0])
return tuple(getattr(module, attr) for attr in attrs)
return module
# constants that don't require heavy imports
IMAGE_SIZE = (200, 200)
IMAGE_MODE = "RGB"
THRESHOLD = 0.5
UNCERTAIN_THRESHOLD = 0.45
MAX_FILE_SIZE = 80_000_000 # 80 MB
IMG_SIZE = (224, 224)
# colors and theme
THEME = "darkly"
PRIMARY_COLOR = "#2563eb"
SUCCESS_COLOR = "#10b981"
ERROR_COLOR = "#ef4444"
WARNING_COLOR = "#fbbf24"
TEXT_COLOR = "#f3f4f6"
SUBTEXT_COLOR = "#9ca3af"
log_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
# file handler
file_handler = logging.FileHandler("logs/app.log", mode='a')
file_handler.setFormatter(log_formatter)
file_handler.setLevel(logging.INFO)
# stream handler (console)
console_handler = logging.StreamHandler()
console_handler.setFormatter(log_formatter)
console_handler.setLevel(logging.INFO)
# root logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.addHandler(file_handler)
logger.addHandler(console_handler)
# constants
IMAGE_SIZE = (200, 200)
IMAGE_MODE = "RGB"
THRESHOLD = 0.5
UNCERTAIN_THRESHOLD = 0.45
# colors
THEME = "darkly"
PRIMARY_COLOR = "#2563eb"
SUCCESS_COLOR = "#10b981"
ERROR_COLOR = "#ef4444"
WARNING_COLOR = "#fbbf24"
TEXT_COLOR = "#f3f4f6"
SUBTEXT_COLOR = "#9ca3af"
IMAGE_SIZE = (250, 250)
MAX_FILE_SIZE = 80_000_000 # 80 MB
THRESHOLD = 0.6
UNCERTAIN_THRESHOLD = 0.4
def load_model(model_path: str):
try:
logger.info("Loading model...")
start_time = time.time()
tf = lazy_imports['tensorflow']
model = tf.keras.models.load_model(model_path)
load_time = time.time() - start_time
logger.info(f"Model loaded successfully in {load_time:.2f} seconds")
return model
except Exception as e:
logger.error(f"Failed to load model: {e}")
raise
# model path - will be loaded when needed
MODEL_PATH = Path(__file__).parent / "src" / "models" / "best_model.h5"
model = None
def get_model():
"""
Get the pre-trained CNN model for malware classification.
Returns:
tensorflow.keras.Model: The loaded CNN model
"""
global model
if model is None:
model = load_model(str(MODEL_PATH))
return model
# --- automation pipeline ---
PIPELINE_STEPS = [
("src/preprocessing/convert_to_image.py", " Convert to Image"),
("src/utils/data_loader.py", " Load Data"),
("train.py", " Train Model"),
("evaluate.py", " Evaluate Model")
]
def run_script(script_path: str) -> bool:
"""
Run a Python script using the subprocess module.
Args:
script_path (str): Path to the script to run
Returns:
bool: True if the script runs successfully, False otherwise
"""
try:
logger.info(f"Running script: {script_path}")
subprocess.run([sys.executable, script_path], check=True)
logger.info(f"Script completed: {script_path}")
return True
except subprocess.CalledProcessError as e:
logger.error(f"Script failed: {script_path} - {e}")
return False
except Exception as e:
logger.error(f"Unexpected error running script: {script_path} - {e}")
return False
def run_pipeline():
"""
Run the automation pipeline by executing each script in sequence.
"""
for step in PIPELINE_STEPS:
run_script(step[0])
# --- GUI Elements ---
def create_round_button(root, text, command):
"""
Create a rounded button widget.
Args:
root (tkinter.Tk): The parent window
text (str): The button text
command (callable): The button command
Returns:
tkinter.Canvas: The button widget
"""
btn_frame = tk.Frame(root, bg="#2c3e50")
btn_frame.pack(pady=8, padx=20, fill="x")
btn_canvas = tk.Canvas(btn_frame, width=200, height=50, bg="#2c3e50", highlightthickness=0)
btn_canvas.pack()
btn_canvas.create_oval(0, 0, 200, 50, fill="#3498db", outline="")
btn_canvas.create_oval(0, 0, 200, 50, fill="#2980b9", outline="", state=tk.HIDDEN,
tags="hover")
btn_canvas.create_text(100, 25, text=text, fill="white", font=("Segoe UI", 12, "bold"))
def on_enter(event):
btn_canvas.itemconfig("hover", state=tk.NORMAL)
btn_canvas.itemconfig(0, fill="#2980b9")
btn_canvas.itemconfig(1, fill="#3498db")
def on_leave(event):
btn_canvas.itemconfig("hover", state=tk.HIDDEN)
btn_canvas.itemconfig(0, fill="#3498db")
btn_canvas.itemconfig(1, fill="#2980b9")
def on_click(event):
command()
btn_canvas.bind("<Enter>", on_enter)
btn_canvas.bind("<Leave>", on_leave)
btn_canvas.bind("<Button-1>", lambda e: on_click(e))
return btn_canvas
def create_progress_bar(parent):
"""
Create a progress bar widget.
Args:
parent (tkinter.Tk): The parent window
Returns:
tuple: (ttk.Progressbar, ttk.Label) The progress bar and label widgets
"""
pb_frame = ttk.Frame(parent, padding="10")
pb_frame.pack(fill=tk.X, padx=10, pady=5)
progress_bar = ttk.Progressbar(pb_frame, orient=tk.HORIZONTAL, length=400, mode='determinate')
progress_bar.pack(fill=tk.X, expand=True)
progress_label = ttk.Label(pb_frame, text="")
progress_label.pack(pady=5)
return progress_bar, progress_label
def create_log_area(parent):
"""
Create a log area widget.
Args:
parent (tkinter.Tk): The parent window
Returns:
tkinter.Text: The log area widget
"""
log_frame = ttk.Frame(parent, padding="10")
log_frame.grid(row=0, column=0, sticky=(tk.W, tk.E))
log_text = tk.Text(log_frame, height=10, width=50, bg="#2c3e50", fg="#ecf0f1",
font=("Consolas", 12, "normal"),
insertbackground="#ecf0f1",
padx=10, pady=10)
log_text.grid(row=0, column=0, pady=5)
return log_text
# --- image classification ---
def preprocess_image(img_path: str):
"""
Preprocess an image for malware classification.
Args:
img_path (str): Path to the image file
Returns:
numpy.ndarray: The preprocessed image array
"""
try:
logger.info(f"Preprocessing image: {img_path}")
Image = lazy_imports['PIL'].Image
np = lazy_imports['numpy']
img = Image.open(img_path).convert("L")
img = img.resize((64, 64))
img_array = np.array(img) / 255.0
img_array = np.expand_dims(img_array, axis=-1)
img_array = np.expand_dims(img_array, axis=0)
return img_array
except Exception as e:
logger.error(f"Image preprocessing failed: {e}")
raise
def convert_exe_to_image(exe_path: str) -> Optional[str]:
"""
Convert an executable file to a grayscale image for classification.
Args:
exe_path (str): Path to the executable file
Returns:
str: Path to the generated image file
Raises:
ValueError: If file size exceeds maximum allowed size
RuntimeError: If image conversion fails
"""
temp_file = None
try:
file_size = os.path.getsize(exe_path)
if file_size > MAX_FILE_SIZE:
logger.warning(f"File too large: {file_size} bytes (max {MAX_FILE_SIZE} allowed)")
return None
logger.info(f"Converting {os.path.basename(exe_path)} to image ({file_size} bytes)")
# get required modules
np = lazy_imports['numpy']
Image = lazy_imports['PIL'].Image
with open(exe_path, "rb") as f:
byte_data = f.read(MAX_FILE_SIZE)
# calculate dimensions for a square image
width = IMAGE_SIZE[0]
rem = len(byte_data) % width
if rem != 0:
byte_data += b'\x00' * (width - rem)
# create grayscale image from bytes
img_array = np.frombuffer(byte_data, dtype=np.uint8).reshape(-1, width)
img = Image.fromarray(img_array, mode='L')
# resize to standard dimensions while maintaining aspect ratio
img = img.resize(IMAGE_SIZE, Image.Resampling.LANCZOS)
# create temp file
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
temp_filename = temp_file.name
temp_file.close()
# save with optimization
img.save(temp_filename, optimize=True, quality=95)
logger.info(f"Created temporary image: {os.path.basename(temp_filename)}")
return temp_filename
except Exception as e:
logger.error(f"Failed to convert {os.path.basename(exe_path)} to image: {e}")
if temp_file and os.path.exists(temp_file.name):
try:
os.unlink(temp_file.name)
except Exception as cleanup_error:
logger.warning(f"Failed to clean up temp file: {cleanup_error}")
return None
def handle_dropped_file(file_path: str) -> None:
"""
Handle a dropped file by classifying it as malicious or benign.
Args:
file_path (str): Path to the dropped file
"""
try:
file_path = file_path.strip().replace("{", "").replace("}", "")
if os.path.isfile(file_path):
logger.info(f"Dropped file received: {file_path}")
classify_dropped_file(file_path)
else:
logger.warning(f"Dropped file not found: {file_path}")
result_label.config(text=" File not found", foreground=ERROR_COLOR)
result_details.config(text="Please try again.", foreground=SUBTEXT_COLOR)
except Exception as e:
logger.error(f"Error handling dropped file: {e}")
result_label.config(text=" Error", foreground=ERROR_COLOR)
result_details.config(text=str(e), foreground=SUBTEXT_COLOR)
def classify_dropped_file(file_path: str):
"""
Classify a dropped file as malicious or benign using the CNN model.
Args:
file_path (str): Path to the file to classify
Returns:
tuple: (classification_result, confidence_score)
classification_result (str): 'Malicious' or 'Benign'
confidence_score (float): Confidence score between 0 and 1
Raises:
ValueError: If file type is not supported
RuntimeError: If classification fails
"""
global model, root
try:
# get required modules
Image = lazy_imports['PIL'].Image
ImageTk = lazy_imports['PIL'].ImageTk
ImageOps = lazy_imports['PIL'].ImageOps
# check if the file is an executable type that needs conversion
is_executable = file_path.lower().endswith((".exe", ".msi"))
if is_executable:
converted_path = convert_exe_to_image(file_path)
if not converted_path:
file_type = "MSI" if file_path.lower().endswith(".msi") else "EXE"
result_label.config(text=f"❌ Could not convert {file_type}", foreground=ERROR_COLOR)
result_details.config(text="Conversion failed.", foreground=SUBTEXT_COLOR)
return
file_path = converted_path
img = Image.open(file_path).convert(IMAGE_MODE)
img_rounded = add_rounded_corners(img, 20)
img_resized = ImageOps.fit(img_rounded, IMAGE_SIZE, method=Image.Resampling.LANCZOS)
img_tk = ImageTk.PhotoImage(img_resized)
image_label.config(image=img_tk)
image_label.image = img_tk
# ensure model is loaded
if model is None:
# show loading message
result_label.config(
text="⏳ Loading model...",
foreground=PRIMARY_COLOR,
font=("Segoe UI", 16, "bold")
)
result_details.config(
text="Please wait while the model loads (this may take a moment on first run)...",
foreground=SUBTEXT_COLOR,
font=("Segoe UI", 12)
)
# update the UI to show the loading message
root.update_idletasks()
# load the model
model = get_model()
if model is None:
raise Exception("Failed to load the model")
# clear loading message
result_label.config(text="")
result_details.config(text="")
preprocessed = preprocess_image(file_path)
prediction = model.predict(preprocessed)
prediction_value = prediction[0][0]
confidence = prediction_value if prediction_value > 0.5 else 1 - prediction_value
if UNCERTAIN_THRESHOLD <= prediction_value <= THRESHOLD:
result_label.config(text="⚠️ Uncertain Prediction!", foreground=WARNING_COLOR)
elif prediction_value > THRESHOLD:
result_label.config(text="🚨 Malware Detected!", foreground=ERROR_COLOR)
else:
result_label.config(text="✅ Benign File", foreground=SUCCESS_COLOR)
result_details.config(
text=f"Confidence: {confidence:.2%} | Prediction: {prediction_value:.4f}",
foreground=SUBTEXT_COLOR
)
except Exception as e:
logger.error(f"Drag-drop classification failed: {e}")
result_label.config(text="❌ Error", foreground=ERROR_COLOR)
result_details.config(text=str(e), foreground=SUBTEXT_COLOR)
def classify_image(root_window=None):
global root
if root_window is not None:
root = root_window
try:
# get required modules
Image = lazy_imports['PIL'].Image
ImageTk = lazy_imports['PIL'].ImageTk
ImageOps = lazy_imports['PIL'].ImageOps
file_path = filedialog.askopenfilename(
filetypes=[("Executable or Image", "*.exe *.png *.jpg *.jpeg")]
)
if not file_path:
return
is_exe = file_path.lower().endswith(".exe")
if is_exe:
converted_path = convert_exe_to_image(file_path)
if not converted_path:
result_label.config(
text="❌ Could not convert EXE",
foreground=ERROR_COLOR,
font=("Segoe UI", 16, "bold")
)
result_details.config(
text="Failed to convert executable file to image format",
foreground=SUBTEXT_COLOR,
font=("Segoe UI", 12)
)
return
file_path = converted_path
img = Image.open(file_path).convert(IMAGE_MODE)
img_rounded = add_rounded_corners(img, 20)
img_resized = ImageOps.fit(
img_rounded, IMAGE_SIZE,
method=Image.Resampling.LANCZOS
)
img_tk = ImageTk.PhotoImage(img_resized)
# update image display
image_label.config(image=img_tk)
image_label.image = img_tk
# ensure model is loaded
global model
if model is None:
# show loading message
result_label.config(
text="⏳ Loading model...",
foreground=PRIMARY_COLOR,
font=("Segoe UI", 16, "bold")
)
result_details.config(
text="Please wait while the model loads (this may take a moment on first run)...",
foreground=SUBTEXT_COLOR,
font=("Segoe UI", 12)
)
# update the UI to show the loading message
root.update_idletasks()
# load the model
model = get_model()
if model is None:
raise Exception("Failed to load the model")
# clear loading message
result_label.config(text="")
result_details.config(text="")
# process image for model
preprocessed = preprocess_image(file_path)
prediction = model.predict(preprocessed)
prediction_value = prediction[0][0]
confidence = prediction_value if prediction_value > 0.5 else 1 - prediction_value
logger.info(f"Prediction: {prediction_value:.4f}, Confidence: {confidence:.4f}")
# update result display
if UNCERTAIN_THRESHOLD <= prediction_value <= THRESHOLD:
result_label.config(
text="⚠️ Uncertain Prediction",
foreground=WARNING_COLOR,
font=("Segoe UI", 16, "bold")
)
result_details.config(
text=f"Confidence: {confidence:.2%}\nPrediction Value: {prediction_value:.4f}\nThreshold: {THRESHOLD}",
foreground=SUBTEXT_COLOR,
font=("Segoe UI", 12)
)
elif prediction_value > THRESHOLD:
result_label.config(
text="🚨 Malware Detected!",
foreground=ERROR_COLOR,
font=("Segoe UI", 16, "bold")
)
result_details.config(
text=f"Confidence: {confidence:.2%}\nPrediction Value: {prediction_value:.4f}\nThreshold: {THRESHOLD}",
foreground=SUBTEXT_COLOR,
font=("Segoe UI", 12)
)
else:
result_label.config(
text="✅ Benign File",
foreground=SUCCESS_COLOR,
font=("Segoe UI", 16, "bold")
)
result_details.config(
text=f"Confidence: {confidence:.2%}\nPrediction Value: {prediction_value:.4f}\nThreshold: {THRESHOLD}",
foreground=SUBTEXT_COLOR,
font=("Segoe UI", 12)
)
except Exception as e:
logger.error(f"Classification failed: {e}")
result_label.config(
text="❌ Error",
foreground=ERROR_COLOR,
font=("Segoe UI", 16, "bold")
)
result_details.config(
text=str(e),
foreground=SUBTEXT_COLOR,
font=("Segoe UI", 12)
)
finally:
# clean up temporary file if it was an EXE or MSI
if is_exe and 'converted_path' in locals() and converted_path:
try:
os.unlink(converted_path)
file_type = "MSI" if file_path.lower().endswith(".msi") else "EXE"
logger.info(f"Cleaned up temporary {file_type} file: {converted_path}")
except Exception as cleanup_error:
logger.error(f"Failed to clean up temporary file: {cleanup_error}")
def add_rounded_corners(image: 'Image.Image', radius: int) -> 'Image.Image':
try:
# get required modules
Image = lazy_imports['PIL'].Image
ImageDraw = lazy_imports['PIL'].ImageDraw
circle = Image.new('L', (radius * 2, radius * 2), 0)
draw = ImageDraw.Draw(circle)
draw.ellipse((0, 0, radius * 2, radius * 2), fill=255)
alpha = Image.new('L', image.size, 255)
w, h = image.size
alpha.paste(circle.crop((0, 0, radius, radius)), (0, 0))
alpha.paste(circle.crop((0, radius, radius, radius * 2)), (0, h - radius))
alpha.paste(circle.crop((radius, 0, radius * 2, radius)), (w - radius, 0))
alpha.paste(circle.crop((radius, radius, radius * 2, radius * 2)), (w - radius, h - radius))
image.putalpha(alpha)
return ImageOps.fit(image, image.size, centering=(0.5, 0.5))
except Exception as e:
logger.error(f"Failed to add rounded corners: {e}")
return image
# --- automation pipeline GUI ---
def start_automation(progress_bar, progress_label, pipeline_label, log_text):
def target():
progress_bar["maximum"] = len(PIPELINE_STEPS)
progress_bar["value"] = 0
for i, step in enumerate(PIPELINE_STEPS):
pipeline_label.config(text=f"🔧 Running: {step[1]}")
progress_label.config(text=f"[{step[0]}]")
log_text.insert(tk.END, f"\n🔧 Running: {step[1]} [{step[0]}]...\n")
log_text.see(tk.END)
log_text.update()
try:
subprocess.run([sys.executable, step[0]], check=True)
pipeline_label.config(text=f"✅ {step[1]} completed successfully!")
log_text.insert(tk.END, f"✅ {step[1]} completed successfully!\n", "green")
log_text.tag_config("green", foreground="#27ae60")
except subprocess.CalledProcessError as e:
pipeline_label.config(text=f"❌ Error in {step[1]}: {str(e)}")
log_text.insert(tk.END, f"❌ Error in {step[1]}: {str(e)}\n", "red")
log_text.tag_config("red", foreground="#e74c3c")
break
progress_bar["value"] = i+1
progress_bar.update()
pipeline_label.config(text="✅ Automation pipeline finished!")
log_text.insert(tk.END, "\n✅ Automation pipeline finished!\n")
thread = threading.Thread(target=target)
thread.daemon = True
thread.start()
def create_main_gui():
# import TkinterDnD only when needed
from tkinterdnd2 import TkinterDnD, DND_FILES
root = TkinterDnD.Tk()
# set initial window state
root.state('iconic') # start minimized to show loading is faster
root.withdraw() # hide window while setting up
# now load heavy UI components
import ttkbootstrap as ttk
from ttkbootstrap.constants import (
TOP, BOTTOM, LEFT, RIGHT, BOTH, X, Y, N, S, E, W,
HORIZONTAL, VERTICAL, NORMAL, DISABLED, CENTER,
SOLID, ROUND, FLAT, RAISED, SUNKEN, GROOVE, RIDGE
)
from PIL import Image, ImageTk, ImageDraw, ImageOps
import numpy as np
# initialize TkinterDnD window with dark theme
style = ttk.Style(theme="darkly")
root.title("Malware Detection System")
# set window icon if logo exists
try:
icon_path = os.path.join("assets", "logo.ico")
if os.path.exists(icon_path):
root.iconbitmap(icon_path)
else:
# fallback to png if ico is not found
logo_path = os.path.join("assets", "logo.png")
if os.path.exists(logo_path):
img = Image.open(logo_path)
# convert to icon format
img = img.resize((32, 32), Image.Resampling.LANCZOS)
photo = ImageTk.PhotoImage(img)
root.iconphoto(True, photo)
except Exception as e:
logger.warning(f"Could not load window icon: {e}")
# set window size and position
window_width = 1200
window_height = 900
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
center_x = int(screen_width/2 - window_width/2)
center_y = int(screen_height/2 - window_height/2)
root.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}')
root.minsize(1000, 800)
# configure styles with increased font sizes
style = ttk.Style()
# base styles
style.configure(".", font=("Segoe UI", 12))
# title and headers
style.configure("Title.TLabel", font=("Segoe UI", 28, "bold"), foreground="#3498db")
style.configure("Subtitle.TLabel", font=("Segoe UI", 14), foreground="#95a5a6")
# buttons
style.configure("TButton", font=("Segoe UI", 12), padding=10)
style.configure("Primary.TButton", font=("Segoe UI", 14, "bold"), padding=12)
# results and text
style.configure("Result.TLabel", font=("Segoe UI", 16, "bold"))
style.configure("Result.TFrame", font=("Segoe UI", 12))
style.configure("TLabel", font=("Segoe UI", 12))
# other elements
style.configure("TNotebook.Tab", font=("Segoe UI", 12))
style.configure("Card.TFrame", background="#2c3e50")
# main container with padding
main_frame = ttk.Frame(root, padding="15")
main_frame.pack(fill=tk.BOTH, expand=True)
# header Section
header_frame = ttk.Frame(main_frame)
header_frame.pack(fill=tk.X, pady=(0, 20))
title_label = ttk.Label(
header_frame,
text="Malware Detection System",
style="Title.TLabel"
)
title_label.pack(pady=(0, 5))
subtitle_label = ttk.Label(
header_frame,
text="Analyze and detect malware using image-based classification",
style="Subtitle.TLabel"
)
subtitle_label.pack()
# main content area (2 columns)
content_frame = ttk.Frame(main_frame)
content_frame.pack(fill=tk.BOTH, expand=True, pady=10)
# left column (Image and Controls)
left_frame = ttk.Frame(content_frame, padding="10")
left_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(0, 10))
left_frame.configure(style="Card.TFrame")
# drag and drop area
drop_frame = ttk.Frame(left_frame)
drop_frame.pack(fill=tk.X, pady=10, padx=10)
drop_label = ttk.Label(
drop_frame,
text="📂 Drag and Drop File Here",
font=("Segoe UI", 14, "bold"),
background="#34495e",
foreground="#ecf0f1",
anchor="center",
padding=20,
relief="ridge",
borderwidth=2
)
drop_label.pack(fill=tk.BOTH, expand=True, pady=(0, 10))
# register as drop target
drop_label.drop_target_register(DND_FILES)
drop_label.dnd_bind('<<Drop>>', lambda e: handle_dropped_file(e.data))
# image display
image_frame = ttk.Frame(left_frame)
image_frame.pack(fill=tk.BOTH, expand=True, pady=10)
image_label = ttk.Label(image_frame)
image_label.pack(expand=True)
# default background image
img_bg = Image.new("RGBA", IMAGE_SIZE, (0, 0, 0, 0))
img_bg_draw = ImageDraw.Draw(img_bg)
img_bg_draw.ellipse((0, 0, *IMAGE_SIZE), fill="#34495e")
img_bg_tk = ImageTk.PhotoImage(img_bg)
image_label.config(image=img_bg_tk)
image_label.image = img_bg_tk
# control buttons
button_frame = ttk.Frame(left_frame)
button_frame.pack(fill=tk.X, pady=(10, 0))
analyze_btn = ttk.Button(
button_frame,
text="🔍 Analyze File",
command=classify_image,
style="Primary.TButton"
)
analyze_btn.pack(side=tk.LEFT, padx=(0, 10))
pipeline_btn = ttk.Button(
button_frame,
text="🚀 Run Pipeline",
command=lambda: start_automation(progress_bar, progress_label, pipeline_label, log_text),
style="Primary.TButton"
)
pipeline_btn.pack(side=tk.LEFT)
# right column (results and logs)
right_frame = ttk.Frame(content_frame, padding="10")
right_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
right_frame.configure(style="Card.TFrame")
# results section
result_frame = ttk.LabelFrame(right_frame, text=" Analysis Results ", padding="15")
result_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 10))
result_label = ttk.Label(
result_frame,
text="",
font=("Segoe UI", 18, "bold"),
foreground=TEXT_COLOR,
wraplength=400,
anchor=tk.CENTER
)
result_label.pack(fill=tk.X, pady=5)
result_details = ttk.Label(
result_frame,
text="",
font=("Segoe UI", 14),
foreground=SUBTEXT_COLOR,
wraplength=400,
anchor=tk.CENTER,
padding=(0, 10, 0, 0)
)
result_details.pack(fill=tk.X, pady=5)
# status and progress
status_frame = ttk.Frame(right_frame)
status_frame.pack(fill=tk.X, pady=(0, 10))
status_label = ttk.Label(
status_frame,
text="Ready",
font=("Segoe UI", 11),
foreground=SUBTEXT_COLOR,
anchor=tk.W
)
status_label.pack(side=tk.LEFT, fill=tk.X, expand=True)
pipeline_label = ttk.Label(
status_frame,
text="",
font=("Segoe UI", 11),
foreground=SUBTEXT_COLOR,
anchor=tk.E
)
pipeline_label.pack(side=tk.RIGHT)
# progress bar
progress_frame = ttk.Frame(right_frame)
progress_frame.pack(fill=tk.X, pady=(0, 10))
progress_bar = ttk.Progressbar(
progress_frame,
orient=tk.HORIZONTAL,
length=100,
mode='determinate'
)
progress_bar.pack(fill=tk.X, expand=True)
progress_label = ttk.Label(
progress_frame,
text="",
font=("Segoe UI", 8),
foreground=SUBTEXT_COLOR,
anchor=tk.CENTER
)
progress_label.pack(fill=tk.X)
# log area
log_frame = ttk.LabelFrame(right_frame, text=" Logs ", padding="10")
log_frame.pack(fill=tk.BOTH, expand=True)
log_text = tk.Text(
log_frame,
height=8,
bg="#2c3e50",
fg="#ecf0f1",
insertbackground="#ecf0f1",
font=("Consolas", 9),
wrap=tk.WORD,
padx=5,
pady=5
)
log_text.pack(fill=tk.BOTH, expand=True)
# add scrollbar to log area
scrollbar = ttk.Scrollbar(log_frame, orient=tk.VERTICAL, command=log_text.yview)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
log_text.configure(yscrollcommand=scrollbar.set)
# --- model performance Chart ---
chart_frame = ttk.LabelFrame(right_frame, text=" Model Performance ", padding="10")
chart_frame.pack(fill=tk.BOTH, expand=True, pady=(10, 0))
# create a frame for the chart and controls
chart_container = ttk.Frame(chart_frame)
chart_container.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
# add controls frame at the top of the chart frame
chart_controls = ttk.Frame(chart_frame, padding="0 5 0 0")
chart_controls.pack(fill=tk.X, pady=0)
# add a separator line below controls
ttk.Separator(chart_frame, orient='horizontal').pack(fill=tk.X, pady=2)
# initialize chart_canvas variable
chart_canvas = None
def refresh_chart():
nonlocal chart_canvas
# clear existing chart
for widget in chart_container.winfo_children():
widget.destroy()
if hasattr(refresh_chart, 'canvas_widget'):
refresh_chart.canvas_widget.destroy()
try:
# lazy load required modules
pd = lazy_imports['pandas']
import matplotlib.pyplot as plt
history_path = Path("results/history.csv")
if not history_path.exists():
logger.warning("History file not found.")
no_data_label = ttk.Label(
chart_container,
text="No training data found.\nRun the training pipeline first.",
foreground="#95a5a6",
justify=tk.CENTER
)
no_data_label.pack(expand=True, pady=20)
return
# read the CSV file
df = pd.read_csv(history_path)
# create a new figure with better layout and more space
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(6, 8), dpi=80, gridspec_kw={'height_ratios': [2, 1]})
# plot accuracy
ax1.plot(df['accuracy'], label='Train Accuracy', color='#3498db', linewidth=2)
if 'val_accuracy' in df.columns:
ax1.plot(df['val_accuracy'], label='Val Accuracy', color='#2ecc71', linestyle='--', linewidth=2)
ax1.set_title('Model Training Progress', pad=15, fontsize=12, fontweight='bold')
ax1.set_ylabel('Accuracy', labelpad=10, fontsize=10)
ax1.tick_params(axis='both', which='major', labelsize=8)
ax1.legend(loc='lower right', fontsize=8, framealpha=0.3)
ax1.grid(True, linestyle='--', alpha=0.3)
# plot loss
ax2.plot(df['loss'], label='Train Loss', color='#e74c3c', linewidth=2)
if 'val_loss' in df.columns:
ax2.plot(df['val_loss'], label='Val Loss', color='#f39c12', linestyle='--', linewidth=2)
ax2.set_xlabel('Epoch', labelpad=10, fontsize=10)
ax2.set_ylabel('Loss', labelpad=10, fontsize=10)
ax2.tick_params(axis='both', which='major', labelsize=8)
ax2.legend(loc='upper right', fontsize=8, framealpha=0.3)
ax2.grid(True, linestyle='--', alpha=0.3)
# set dark theme colors for both subplots
for ax in [ax1, ax2]:
ax.set_facecolor('#2c3e50')
ax.title.set_color('#ecf0f1')
ax.xaxis.label.set_color('#ecf0f1')