-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgui_classic_production.py
More file actions
3817 lines (3203 loc) · 162 KB
/
gui_classic_production.py
File metadata and controls
3817 lines (3203 loc) · 162 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
"""
IC Authentication System - Professional Classic GUI
Production-ready interface with comprehensive details display
"""
import sys
import webbrowser
import os
import cv2
import torch
import ctypes
import tempfile
import urllib.request
import urllib.parse
from pathlib import Path
# Safe print function for Windows encoding issues with Unicode characters
def safe_print(msg):
"""Print message without Unicode encoding errors on Windows console"""
try:
print(msg)
except (UnicodeEncodeError, UnicodeDecodeError):
# Fallback: replace problematic characters
try:
ascii_msg = str(msg).encode('ascii', errors='replace').decode('ascii')
print(ascii_msg)
except:
pass # Silent fail - don't crash on print errors
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
QHBoxLayout, QPushButton, QLabel, QFileDialog,
QTextEdit, QTextBrowser, QTabWidget, QGroupBox, QScrollArea,
QMessageBox, QProgressBar, QGridLayout, QSplitter,
QCheckBox, QDialog, QTableWidget, QTableWidgetItem, QHeaderView,
QSpinBox, QToolBar)
from PyQt5.QtCore import Qt, QThread, pyqtSignal, QSize, QEvent, QUrl, QTimer
from PyQt5.QtGui import QImage, QPixmap, QFont, QColor, QPalette, QTextCursor, QIcon
# Import PDF rendering library
try:
import fitz # PyMuPDF
PDF_AVAILABLE = True
except ImportError:
PDF_AVAILABLE = False
safe_print("Warning: PyMuPDF not available - PDF viewer disabled")
# Try to import ultimate authenticator, fallback to fresh YOLO
try:
from smart_ic_authenticator import SmartICAuthenticator as Authenticator
USING_ULTIMATE = True
except ImportError:
from fresh_yolo_authenticator import FreshYOLOAuthenticator as Authenticator
USING_ULTIMATE = False
from datetime import datetime
class ProcessingThread(QThread):
"""Background thread for image processing"""
progress = pyqtSignal(int)
status = pyqtSignal(str)
result = pyqtSignal(dict)
def __init__(self, image_path, authenticator):
super().__init__()
self.image_path = image_path
self.authenticator = authenticator
def run(self):
"""Run the authentication process with aggressive memory management"""
import gc
try:
self.status.emit("🚀 Starting analysis...")
self.progress.emit(10)
QApplication.processEvents()
self.status.emit("📝 Extracting text...")
self.progress.emit(40)
QApplication.processEvents()
self.status.emit("🔍 Detecting part numbers...")
self.progress.emit(60)
QApplication.processEvents()
self.status.emit("📄 Validating datasheets...")
self.progress.emit(80)
QApplication.processEvents()
self.status.emit("✅ Finalizing...")
self.progress.emit(95)
QApplication.processEvents()
# Run authentication using provided authenticator instance
result = self.authenticator.authenticate(self.image_path)
# CRITICAL: Save debug images to disk BEFORE emitting signal
# This prevents passing large numpy arrays through Qt signals
if result.get('debug_ocr_image') is not None:
try:
import tempfile
temp_dir = tempfile.gettempdir()
temp_path = os.path.join(temp_dir, 'ic_auth_debug_ocr.png')
cv2.imwrite(temp_path, result['debug_ocr_image'])
result['debug_ocr_image_path'] = temp_path
del result['debug_ocr_image'] # Remove from memory
except Exception as e:
print(f"Warning: Could not save debug OCR image: {e}")
# Save preprocessing variants to disk
if result.get('debug_variants'):
try:
import tempfile
temp_dir = tempfile.gettempdir()
variant_paths = []
for idx, (name, img) in enumerate(result['debug_variants']):
temp_path = os.path.join(temp_dir, f'ic_auth_variant_{idx}.png')
cv2.imwrite(temp_path, img)
variant_paths.append((name, temp_path))
result['debug_variant_paths'] = variant_paths
del result['debug_variants'] # Remove from memory
except Exception as e:
print(f"Warning: Could not save variants: {e}")
# Remove other large objects
if 'preprocessing_images' in result:
del result['preprocessing_images']
self.progress.emit(100)
self.status.emit("✅ Analysis complete!")
# Force garbage collection before emitting
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
# Emit result (now without large numpy arrays)
self.result.emit(result)
# Final cleanup in thread
gc.collect()
except Exception as e:
import traceback
error_msg = f"Error: {str(e)}\n{traceback.format_exc()}"
self.status.emit(f"❌ {str(e)}")
self.result.emit({'success': False, 'error': error_msg})
class BatchProcessingThread(QThread):
"""Background thread for batch processing multiple images"""
progress = pyqtSignal(int, int, str) # current, total, filename
status = pyqtSignal(str)
batch_result = pyqtSignal(dict) # Single image result
complete = pyqtSignal(dict) # Final summary
def __init__(self, image_paths, authenticator):
super().__init__()
self.image_paths = image_paths
self.authenticator = authenticator
self.results = []
def run(self):
"""Process multiple images"""
try:
self.status.emit(f"🚀 Starting batch processing of {len(self.image_paths)} images...")
# Use provided authenticator instance (models already loaded)
total = len(self.image_paths)
# Create debug_output folder
os.makedirs('debug_output', exist_ok=True)
authentic_count = 0
likely_authentic_count = 0
suspicious_count = 0
counterfeit_count = 0
error_count = 0
for idx, image_path in enumerate(self.image_paths, 1):
filename = os.path.basename(image_path)
self.status.emit(f"📝 Processing {idx}/{total}: {filename}")
self.progress.emit(idx, total, filename)
try:
result = self.authenticator.authenticate(image_path)
result['filename'] = filename
result['filepath'] = image_path
result['success'] = True
# Generate debug image
try:
debug_path = self.authenticator.save_debug_image(result)
result['debug_image_path'] = debug_path
except Exception as e:
result['debug_image_path'] = None
self.results.append(result)
# Emit individual result
self.batch_result.emit(result)
# MEMORY CLEANUP: Remove large image data after emitting
if 'preprocessing_images' in result:
del result['preprocessing_images']
if 'debug_ocr_image' in result:
result['debug_ocr_image'] = None
if 'debug_variants' in result:
result['debug_variants'] = []
# Count results based on verdict
verdict = result.get('verdict', 'ERROR')
if verdict == 'AUTHENTIC':
authentic_count += 1
elif verdict == 'LIKELY AUTHENTIC':
likely_authentic_count += 1
elif verdict == 'SUSPICIOUS':
suspicious_count += 1
elif verdict in ['COUNTERFEIT', 'LIKELY COUNTERFEIT']:
counterfeit_count += 1
else:
error_count += 1
# Force garbage collection every 5 images
if idx % 5 == 0:
import gc
gc.collect()
except Exception as e:
error_count += 1
error_result = {
'filename': filename,
'filepath': image_path,
'success': False,
'error': str(e),
'verdict': 'ERROR',
'is_authentic': False,
'confidence': 0
}
self.results.append(error_result)
self.batch_result.emit(error_result)
# Emit final summary
summary = {
'total': total,
'authentic': authentic_count,
'likely_authentic': likely_authentic_count,
'suspicious': suspicious_count,
'counterfeit': counterfeit_count,
'errors': error_count,
'results': self.results
}
self.status.emit(f"✅ Batch processing complete! {authentic_count} authentic, {likely_authentic_count} likely authentic, {suspicious_count} suspicious, {counterfeit_count} counterfeit, {error_count} errors")
self.complete.emit(summary)
except Exception as e:
import traceback
error_msg = f"Batch processing error: {str(e)}\n{traceback.format_exc()}"
self.status.emit(f"❌ {str(e)}")
self.complete.emit({'success': False, 'error': error_msg})
class ClickableImageLabel(QLabel):
"""QLabel that can be clicked to show full-size image with zoom"""
clicked = pyqtSignal(QPixmap, str)
def __init__(self, pixmap=None, title=""):
super().__init__()
self.full_pixmap = pixmap
self.image_title = title
self.setCursor(Qt.PointingHandCursor)
self.setToolTip("Click to view full size and zoom")
def set_image(self, pixmap, title=""):
"""Set the image and title"""
self.full_pixmap = pixmap
self.image_title = title
def mousePressEvent(self, event):
"""Handle click event"""
if self.full_pixmap and not self.full_pixmap.isNull():
self.clicked.emit(self.full_pixmap, self.image_title)
class ImageViewerDialog(QMessageBox):
"""Dialog for viewing and zooming images"""
def __init__(self, pixmap, title, parent=None):
super().__init__(parent)
self.setWindowTitle(title)
self.setText(f"{title}\n\nUse mouse wheel to zoom. Click and drag to pan.")
self.setIcon(QMessageBox.NoIcon)
# Create scroll area for zooming
scroll = QScrollArea()
scroll.setWidgetResizable(False)
scroll.setMinimumSize(1000, 800)
# Image label
self.img_label = QLabel()
self.img_label.setPixmap(pixmap)
self.img_label.setAlignment(Qt.AlignCenter)
scroll.setWidget(self.img_label)
# Add scroll area to dialog
self.layout().addWidget(scroll, 1, 0, 1, self.layout().columnCount())
# Zoom controls
self.zoom_factor = 1.0
self.original_pixmap = pixmap
# Install event filter for mouse wheel
scroll.viewport().installEventFilter(self)
def eventFilter(self, obj, event):
"""Handle mouse wheel for zooming"""
if event.type() == event.Wheel:
delta = event.angleDelta().y()
if delta > 0:
self.zoom_factor *= 1.1
else:
self.zoom_factor /= 1.1
# Limit zoom
self.zoom_factor = max(0.1, min(10.0, self.zoom_factor))
# Scale image
scaled = self.original_pixmap.scaled(
self.original_pixmap.size() * self.zoom_factor,
Qt.KeepAspectRatio,
Qt.SmoothTransformation
)
self.img_label.setPixmap(scaled)
self.img_label.resize(scaled.size())
return True
return super().eventFilter(obj, event)
class PDFViewerDialog(QDialog):
"""Embedded PDF viewer dialog with continuous scrolling"""
def __init__(self, pdf_path, parent=None):
super().__init__(parent)
self.pdf_path = pdf_path
self.zoom_level = 1.0
self.doc = None
self.page_pixmaps = []
self._is_loading = False
self.setWindowTitle(f"PDF Viewer - {os.path.basename(pdf_path)}")
self.setModal(False)
self.resize(1100, 1200)
# Apply dark theme
self.setStyleSheet("""
QDialog {
background-color: #1e1e1e;
color: #e0e0e0;
}
QPushButton {
background-color: #2d2d2d;
color: #e0e0e0;
border: 1px solid #444;
padding: 8px 15px;
border-radius: 4px;
font-size: 11pt;
}
QPushButton:hover {
background-color: #3d3d3d;
border-color: #555;
}
QPushButton:disabled {
background-color: #1a1a1a;
color: #666;
}
QLabel {
color: #e0e0e0;
}
""")
layout = QVBoxLayout(self)
# Toolbar
toolbar = QWidget()
toolbar_layout = QHBoxLayout(toolbar)
# Page indicator
self.page_label = QLabel("Loading PDF...")
toolbar_layout.addWidget(self.page_label)
toolbar_layout.addStretch()
# Zoom controls
zoom_out_btn = QPushButton("🔍-")
zoom_out_btn.clicked.connect(lambda: self.change_zoom(-0.2))
toolbar_layout.addWidget(zoom_out_btn)
self.zoom_label = QLabel("100%")
toolbar_layout.addWidget(self.zoom_label)
zoom_in_btn = QPushButton("🔍+")
zoom_in_btn.clicked.connect(lambda: self.change_zoom(0.2))
toolbar_layout.addWidget(zoom_in_btn)
layout.addWidget(toolbar)
# PDF display area - continuous scrolling with all pages
self.scroll_area = QScrollArea()
self.scroll_area.setWidgetResizable(False)
self.scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
self.scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
self.scroll_area.setStyleSheet("QScrollArea { border: none; background-color: #2a2a2a; }")
# Container widget for all pages
self.pages_container = QWidget()
self.pages_layout = QVBoxLayout(self.pages_container)
self.pages_layout.setSpacing(10) # Space between pages
self.pages_layout.setContentsMargins(20, 20, 20, 20)
self.pages_layout.setAlignment(Qt.AlignTop)
self.scroll_area.setWidget(self.pages_container)
layout.addWidget(self.scroll_area)
# Load PDF
self.load_pdf()
def load_pdf(self):
"""Load PDF file and display all pages in scrollable view"""
if not PDF_AVAILABLE:
error_label = QLabel("⚠ PyMuPDF not installed\n\nInstall with: pip install PyMuPDF")
error_label.setAlignment(Qt.AlignCenter)
self.pages_layout.addWidget(error_label)
return
try:
print(f"[PDF] Loading: {self.pdf_path}")
# Validate file exists and is readable
if not os.path.exists(self.pdf_path):
raise FileNotFoundError(f"PDF file not found: {self.pdf_path}")
if not os.path.isfile(self.pdf_path):
raise ValueError(f"Path is not a file: {self.pdf_path}")
if os.path.getsize(self.pdf_path) == 0:
raise ValueError("PDF file is empty (0 bytes)")
# Try to open PDF with error handling
try:
self.doc = fitz.open(self.pdf_path)
except Exception as open_error:
raise Exception(f"Failed to open PDF: {str(open_error)}")
if self.doc is None:
raise Exception("PDF document is None after opening")
try:
total_pages = len(self.doc)
except Exception as len_error:
raise Exception(f"Failed to get page count: {str(len_error)}")
if total_pages == 0:
raise Exception("PDF has 0 pages")
self.page_label.setText(f"Total Pages: {total_pages}")
print(f"[PDF] Total pages: {total_pages}")
# Limit pages to prevent memory issues
max_pages_to_render = min(total_pages, 200) # Limit to 200 pages max
if total_pages > max_pages_to_render:
print(f"[PDF] WARNING: PDF has {total_pages} pages, limiting to {max_pages_to_render}")
# Render pages with individual error handling
rendered_count = 0
for page_num in range(max_pages_to_render):
try:
page = self.doc[page_num]
# Render at higher resolution for better quality
mat = fitz.Matrix(2.0 * self.zoom_level, 2.0 * self.zoom_level)
pix = page.get_pixmap(matrix=mat)
print(f"[PDF] Page {page_num+1}: {pix.width}x{pix.height}")
# Validate pixmap dimensions
if pix.width <= 0 or pix.height <= 0:
print(f"[PDF] WARNING: Page {page_num+1} has invalid dimensions, skipping")
continue
# Convert to QImage with error handling
try:
img = QImage(pix.samples, pix.width, pix.height, pix.stride, QImage.Format_RGB888)
if img.isNull():
print(f"[PDF] WARNING: Page {page_num+1} QImage is null, skipping")
continue
pixmap = QPixmap.fromImage(img)
if pixmap.isNull():
print(f"[PDF] WARNING: Page {page_num+1} QPixmap is null, skipping")
continue
except Exception as img_error:
print(f"[PDF] WARNING: Failed to convert page {page_num+1} to image: {img_error}")
continue
print(f"[PDF] Pixmap size: {pixmap.width()}x{pixmap.height()}")
# Create label for this page
page_label = QLabel()
page_label.setPixmap(pixmap)
page_label.setAlignment(Qt.AlignCenter)
page_label.setScaledContents(False)
page_label.setFixedSize(pixmap.size())
# Add page number label
page_num_label = QLabel(f"Page {page_num + 1}")
page_num_label.setAlignment(Qt.AlignCenter)
page_num_label.setStyleSheet("font-weight: bold; padding: 5px; color: #aaa;")
self.pages_layout.addWidget(page_num_label)
self.pages_layout.addWidget(page_label)
self.page_pixmaps.append((page_label, pixmap))
rendered_count += 1
except Exception as page_error:
print(f"[PDF] ERROR on page {page_num+1}: {page_error}")
# Continue with next page instead of failing completely
continue
if rendered_count == 0:
raise Exception("Failed to render any pages from PDF")
# Force layout update and resize container to fit all pages
try:
self.pages_container.adjustSize()
print(f"[PDF] Container size: {self.pages_container.width()}x{self.pages_container.height()}")
except Exception as layout_error:
print(f"[PDF] WARNING: Layout adjustment failed: {layout_error}")
print(f"[PDF] Successfully loaded {rendered_count}/{max_pages_to_render} pages")
if rendered_count < total_pages:
warning_label = QLabel(f"⚠️ Showing {rendered_count} of {total_pages} pages")
warning_label.setAlignment(Qt.AlignCenter)
warning_label.setStyleSheet("color: #ffaa00; padding: 10px;")
self.pages_layout.addWidget(warning_label)
except Exception as e:
print(f"[PDF] CRITICAL ERROR: {e}")
import traceback
traceback.print_exc()
error_msg = f"❌ Error loading PDF:\n\n{str(e)}\n\nFile: {os.path.basename(self.pdf_path)}"
error_label = QLabel(error_msg)
error_label.setAlignment(Qt.AlignCenter)
error_label.setWordWrap(True)
error_label.setStyleSheet("color: #ff4444; padding: 20px;")
self.pages_layout.addWidget(error_label)
# Clean up document if it was opened
try:
if hasattr(self, 'doc') and self.doc is not None:
self.doc.close()
self.doc = None
except:
pass
def change_zoom(self, delta):
"""Change zoom level and re-render all pages"""
if self._is_loading:
print("[PDF] Zoom change ignored - PDF is still loading")
return
self.zoom_level = max(0.5, min(3.0, self.zoom_level + delta))
self.zoom_label.setText(f"{int(self.zoom_level * 100)}%")
# Clear existing pages
try:
for i in reversed(range(self.pages_layout.count())):
item = self.pages_layout.itemAt(i)
if item and item.widget():
item.widget().setParent(None)
except Exception as clear_error:
print(f"[PDF] Warning: Error clearing pages: {clear_error}")
self.page_pixmaps.clear()
# Reload with new zoom
if self.doc:
try:
self._is_loading = True
total_pages = len(self.doc)
self.page_label.setText(f"Total Pages: {total_pages}")
# Limit pages to prevent memory issues
max_pages = min(total_pages, 200)
rendered = 0
for page_num in range(max_pages):
try:
page = self.doc[page_num]
# Render with new zoom level
mat = fitz.Matrix(2.0 * self.zoom_level, 2.0 * self.zoom_level)
pix = page.get_pixmap(matrix=mat)
# Convert to QImage
img = QImage(pix.samples, pix.width, pix.height, pix.stride, QImage.Format_RGB888)
if img.isNull():
continue
pixmap = QPixmap.fromImage(img)
if pixmap.isNull():
continue
# Create label for this page
page_label = QLabel()
page_label.setPixmap(pixmap)
page_label.setAlignment(Qt.AlignCenter)
page_label.setScaledContents(False)
page_label.setFixedSize(pixmap.size())
# Add page number label
page_num_label = QLabel(f"Page {page_num + 1}")
page_num_label.setAlignment(Qt.AlignCenter)
page_num_label.setStyleSheet("font-weight: bold; padding: 5px; color: #aaa;")
self.pages_layout.addWidget(page_num_label)
self.pages_layout.addWidget(page_label)
self.page_pixmaps.append((page_label, pixmap))
rendered += 1
except Exception as page_error:
print(f"[PDF] Warning: Error rendering page {page_num+1}: {page_error}")
continue
# Force layout update
try:
self.pages_container.adjustSize()
except Exception as layout_error:
print(f"[PDF] Warning: Layout adjustment failed: {layout_error}")
print(f"[PDF] Re-rendered {rendered} pages at {int(self.zoom_level * 100)}%")
except Exception as e:
print(f"[PDF] Error re-rendering: {e}")
import traceback
traceback.print_exc()
error_label = QLabel(f"❌ Error re-rendering:\n{str(e)}")
error_label.setAlignment(Qt.AlignCenter)
error_label.setStyleSheet("color: #ff4444; padding: 20px;")
self.pages_layout.addWidget(error_label)
finally:
self._is_loading = False
def closeEvent(self, event):
"""Clean up when closing"""
print("[PDF] Closing PDF viewer, cleaning up resources...")
try:
# Clear pixmaps to free memory
self.page_pixmaps.clear()
# Close PDF document
if self.doc is not None:
try:
self.doc.close()
print("[PDF] Document closed successfully")
except Exception as close_error:
print(f"[PDF] Warning: Error closing document: {close_error}")
finally:
self.doc = None
# Clear layout widgets
try:
while self.pages_layout.count():
item = self.pages_layout.takeAt(0)
if item.widget():
item.widget().deleteLater()
except Exception as layout_error:
print(f"[PDF] Warning: Error clearing layout: {layout_error}")
except Exception as e:
print(f"[PDF] Warning: Error in closeEvent: {e}")
finally:
super().closeEvent(event)
def __del__(self):
"""Destructor - ensure resources are freed"""
try:
if hasattr(self, 'doc') and self.doc is not None:
self.doc.close()
except:
pass
class ICAuthenticatorGUI(QMainWindow):
"""Main GUI Application for IC Authentication System"""
def __init__(self):
super().__init__()
self.current_image_path = None
self.current_results = None
self.current_pdf_path = None # Track current PDF for viewer
self.dark_mode = True
self.processing_thread = None
self.batch_results = [] # Store batch processing results
self.app_icon = None # Store icon reference globally
# Initialize authenticator once and reuse it (prevents reloading YOLO/EasyOCR models)
self.statusBar().showMessage("🚀 Loading models... Please wait...")
QApplication.processEvents() # Update UI immediately
self.authenticator = Authenticator()
# CRITICAL FIX: Add periodic garbage collection to prevent memory buildup
self.cleanup_timer = QTimer()
self.cleanup_timer.timeout.connect(self.periodic_cleanup)
self.cleanup_timer.start(30000) # Run cleanup every 30 seconds
self.init_ui()
self.apply_theme()
def periodic_cleanup(self):
"""Periodic memory cleanup to prevent system from becoming unresponsive"""
try:
import gc
gc.collect()
# Clear GPU cache if using CUDA
if torch.cuda.is_available():
torch.cuda.empty_cache()
# Process pending events to keep UI responsive
QApplication.processEvents()
except Exception as e:
pass # Silent fail - don't interrupt user
def closeEvent(self, event):
"""Clean up resources when closing"""
try:
# Stop cleanup timer
if hasattr(self, 'cleanup_timer'):
self.cleanup_timer.stop()
# Clean up authenticator
if hasattr(self, 'authenticator'):
del self.authenticator
# Final cleanup
import gc
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
except:
pass
event.accept()
def showEvent(self, event):
"""Override showEvent to force icon refresh when window becomes visible"""
super().showEvent(event)
# Force icon update after window is shown (Windows taskbar fix)
if self.app_icon and not self.app_icon.isNull():
self.setWindowIcon(self.app_icon)
QApplication.instance().setWindowIcon(self.app_icon)
def init_ui(self):
"""Initialize the user interface"""
self.setWindowTitle("IC Authentication System - Professional Edition")
self.setGeometry(50, 50, 1800, 1000)
self.setMinimumSize(1400, 800)
# Set window icon with absolute path - store reference to prevent garbage collection
try:
# Try ICO file first (preferred for Windows)
icon_path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'icon.ico'))
if os.path.exists(icon_path):
self.app_icon = QIcon(icon_path)
if not self.app_icon.isNull():
self.setWindowIcon(self.app_icon)
safe_print(f"OK: Window icon set from: {icon_path}")
else:
# Try PNG as fallback
icon_path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'icon.png'))
if os.path.exists(icon_path):
self.app_icon = QIcon(icon_path)
self.setWindowIcon(self.app_icon)
safe_print(f"OK: Window icon set from PNG: {icon_path}")
except Exception as e:
safe_print(f"Could not set window icon: {e}")
# Enable dark title bar on Windows 10/11
if sys.platform == 'win32':
try:
hwnd = int(self.winId())
# DWMWA_USE_IMMERSIVE_DARK_MODE = 20
value = ctypes.c_int(2) # 2 = force dark mode
ctypes.windll.dwmapi.DwmSetWindowAttribute(
hwnd, 20, ctypes.byref(value), ctypes.sizeof(value)
)
except Exception as e:
safe_print(f"Could not set dark title bar: {e}")
# Central widget
central_widget = QWidget()
self.setCentralWidget(central_widget)
main_layout = QVBoxLayout(central_widget)
main_layout.setContentsMargins(0, 0, 0, 0)
main_layout.setSpacing(0)
# Compact header
header = self.create_header()
main_layout.addWidget(header)
# Main content splitter
splitter = QSplitter(Qt.Horizontal)
# Left panel - Control and image
left_panel = self.create_left_panel()
splitter.addWidget(left_panel)
# Right panel - Results
right_panel = self.create_results_panel()
splitter.addWidget(right_panel)
splitter.setSizes([600, 1200])
main_layout.addWidget(splitter)
# Status bar
self.statusBar = self.statusBar()
self.statusBar.showMessage("Ready")
def create_header(self):
"""Create compact header with title"""
header = QWidget()
header.setFixedHeight(50)
layout = QHBoxLayout(header)
layout.setContentsMargins(20, 5, 20, 5)
# Compact title
title = QLabel("🔬 IC Authentication System")
title.setFont(QFont("Arial", 14, QFont.Bold))
layout.addWidget(title)
layout.addStretch()
return header
def create_left_panel(self):
"""Create compact left panel with controls and image"""
panel = QWidget()
layout = QVBoxLayout(panel)
layout.setSpacing(10)
# Full-width button layout
select_layout = QHBoxLayout()
select_layout.setSpacing(5)
select_layout.setContentsMargins(0, 0, 0, 0)
self.select_btn = QPushButton("📁 Select Image")
self.select_btn.setFixedHeight(40)
self.select_btn.setFont(QFont("Arial", 10))
self.select_btn.clicked.connect(self.select_image)
select_layout.addWidget(self.select_btn, stretch=1) # Takes 50% space
# Theme toggle - takes other 50% space
self.theme_btn = QPushButton("🌙 Light Mode")
self.theme_btn.setFixedHeight(40)
self.theme_btn.setFont(QFont("Arial", 10))
self.theme_btn.clicked.connect(self.toggle_theme)
select_layout.addWidget(self.theme_btn, stretch=1) # Takes 50% space
layout.addLayout(select_layout)
# Compact file path display
self.image_path_label = QLabel("No image selected")
self.image_path_label.setWordWrap(True)
self.image_path_label.setMaximumHeight(35)
self.image_path_label.setStyleSheet("padding: 5px; border: 1px solid #444; font-size: 9pt;")
layout.addWidget(self.image_path_label)
# Image display - larger now
display_group = QGroupBox("Image Preview")
display_layout = QVBoxLayout()
display_layout.setContentsMargins(5, 5, 5, 5)
self.image_label = QLabel()
self.image_label.setAlignment(Qt.AlignCenter)
self.image_label.setMinimumSize(450, 450)
self.image_label.setStyleSheet("border: 2px solid #444; background: #2b2b2b;")
self.image_label.setText("No Image Loaded")
display_layout.addWidget(self.image_label)
display_group.setLayout(display_layout)
layout.addWidget(display_group)
# Debug options - better spacing
debug_group = QGroupBox("Debug Options")
debug_layout = QHBoxLayout()
debug_layout.setSpacing(15)
debug_layout.setContentsMargins(10, 10, 10, 10)
self.show_preprocessed_cb = QCheckBox("Show Preprocessing")
self.show_preprocessed_cb.setStyleSheet("font-size: 10pt;")
self.show_preprocessed_cb.setToolTip("Show preprocessed image layers")
self.show_preprocessed_cb.toggled.connect(self.on_debug_option_changed)
debug_layout.addWidget(self.show_preprocessed_cb)
self.show_bboxes_cb = QCheckBox("Show Text Boxes")
self.show_bboxes_cb.setStyleSheet("font-size: 10pt;")
self.show_bboxes_cb.setToolTip("Show OCR bounding boxes")
self.show_bboxes_cb.toggled.connect(self.on_debug_option_changed)
debug_layout.addWidget(self.show_bboxes_cb)
debug_layout.addStretch() # Push checkboxes to left
debug_group.setLayout(debug_layout)
debug_group.setMaximumHeight(65) # Slightly taller for better spacing
layout.addWidget(debug_group)
# Buttons container
buttons_layout = QHBoxLayout()
# Authenticate button
self.auth_btn = QPushButton("🔍 Authenticate IC")
self.auth_btn.setFixedHeight(50)
self.auth_btn.setFont(QFont("Arial", 11, QFont.Bold))
self.auth_btn.setEnabled(False)
self.auth_btn.clicked.connect(self.authenticate)
buttons_layout.addWidget(self.auth_btn, 2)
# Batch process button
self.batch_btn = QPushButton("📁 Batch Process")
self.batch_btn.setFixedHeight(50)
self.batch_btn.setFont(QFont("Arial", 11, QFont.Bold))
self.batch_btn.clicked.connect(self.batch_process)
self.batch_btn.setToolTip("Process multiple images at once")
buttons_layout.addWidget(self.batch_btn, 1)
layout.addLayout(buttons_layout)
# Progress bar
self.progress_bar = QProgressBar()
self.progress_bar.setFixedHeight(25)
self.progress_bar.setVisible(False)
layout.addWidget(self.progress_bar)
# Status and info section
status_group = QGroupBox("Status & Information")
status_layout = QVBoxLayout()
status_layout.setSpacing(5)
self.status_label = QLabel("Ready - Select an image to begin")
self.status_label.setWordWrap(True)
self.status_label.setStyleSheet("padding: 8px; border: 1px solid #444; font-weight: bold;")
status_layout.addWidget(self.status_label)
# Additional info grid
info_grid = QGridLayout()
info_grid.setSpacing(8)
info_grid.setColumnStretch(1, 2) # GPU column gets more space
info_grid.setColumnStretch(3, 1) # Other columns get less space
# GPU status
gpu_label = QLabel("GPU:")
gpu_label.setStyleSheet("font-weight: bold; font-size: 9pt;")
self.gpu_status = QLabel("Detecting...")
self.gpu_status.setStyleSheet("font-size: 9pt;")
self.gpu_status.setWordWrap(True)
self.gpu_status.setMinimumWidth(200)
info_grid.addWidget(gpu_label, 0, 0)
info_grid.addWidget(self.gpu_status, 0, 1)
# Processing time
time_label = QLabel("Time:")
time_label.setStyleSheet("font-weight: bold; font-size: 9pt;")
self.process_time = QLabel("-")
self.process_time.setStyleSheet("font-size: 9pt;")
info_grid.addWidget(time_label, 0, 2)
info_grid.addWidget(self.process_time, 0, 3)
# Image size
size_label = QLabel("Size:")
size_label.setStyleSheet("font-weight: bold; font-size: 9pt;")
self.image_size = QLabel("-")
self.image_size.setStyleSheet("font-size: 9pt;")
info_grid.addWidget(size_label, 1, 0)
info_grid.addWidget(self.image_size, 1, 1)
# Variants used
var_label = QLabel("Variants:")
var_label.setStyleSheet("font-weight: bold; font-size: 9pt;")
self.variants_used = QLabel("-")
self.variants_used.setStyleSheet("font-size: 9pt;")
info_grid.addWidget(var_label, 1, 2)
info_grid.addWidget(self.variants_used, 1, 3)
status_layout.addLayout(info_grid)
status_group.setLayout(status_layout)
layout.addWidget(status_group)