#!/usr/bin/env python3 """ Advanced Duplicate Detector GUI with Side-by-Side Comparison and Settings Panel """ import tkinter as tk from tkinter import ttk, filedialog, messagebox import threading import queue import os import sys import time from pathlib import Path from PIL import Image, ImageTk import json from typing import Dict, List, Any, Optional, Tuple import logging # Windows console encoding fix for Unicode characters if sys.platform == 'win32': try: import codecs if hasattr(sys.stdout, 'detach'): sys.stdout = codecs.getwriter('utf-8')(sys.stdout.detach()) if hasattr(sys.stderr, 'detach'): sys.stderr = codecs.getwriter('utf-8')(sys.stderr.detach()) except Exception: pass # Fallback to default if encoding fix fails # Add current directory to path current_dir = Path(__file__).parent sys.path.insert(0, str(current_dir)) try: from auto_optimize_detector import SystemDetector, OptimizationEngine from duplicate_detector import DuplicateDetector except ImportError as e: print(f"Error importing modules: {e}") sys.exit(1) class AdvancedDuplicateDetectorGUI: """Advanced GUI with side-by-side comparison and customizable settings.""" def __init__(self): self.root = tk.Tk() self.root.title("Advanced Duplicate Detector") self.root.geometry("1400x900") self.root.configure(bg='#f0f0f0') # Initialize variables self.system_info = {} self.optimization_profile = {} self.detector = None self.duplicates = [] self.current_duplicate_index = 0 self.processing_thread = None self.progress_queue = queue.Queue() self.settings = self.load_settings() # Setup logging self.setup_logging() # Create GUI self.create_gui() # Auto-detect system on startup self.auto_detect_system() # Start progress queue processor self.process_progress_queue() def setup_logging(self): """Setup logging for the GUI with Windows Unicode support.""" import sys if sys.platform == 'win32': # Windows console encoding fix for Unicode characters try: import codecs if hasattr(sys.stdout, 'detach'): sys.stdout = codecs.getwriter('utf-8')(sys.stdout.detach()) if hasattr(sys.stderr, 'detach'): sys.stderr = codecs.getwriter('utf-8')(sys.stderr.detach()) except Exception: pass # Fallback to default if encoding fix fails logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', handlers=[ logging.FileHandler('duplicate_detection_gui.log', encoding='utf-8'), logging.StreamHandler() ] ) self.logger = logging.getLogger(__name__) def create_gui(self): """Create the main GUI interface.""" # Create notebook for tabs self.notebook = ttk.Notebook(self.root) self.notebook.pack(fill='both', expand=True, padx=10, pady=10) # Create tabs self.create_system_info_tab() self.create_settings_tab() self.create_folder_selection_tab() self.create_processing_tab() self.create_results_tab() self.create_comparison_tab() def create_system_info_tab(self): """Create system information tab.""" self.system_frame = ttk.Frame(self.notebook) self.notebook.add(self.system_frame, text="System Info") # System info display info_frame = ttk.LabelFrame(self.system_frame, text="Hardware Detection", padding=10) info_frame.pack(fill='both', expand=True, padx=10, pady=10) self.system_info_text = tk.Text(info_frame, height=20, width=80, wrap='word') scrollbar = ttk.Scrollbar(info_frame, orient='vertical', command=self.system_info_text.yview) self.system_info_text.configure(yscrollcommand=scrollbar.set) self.system_info_text.pack(side='left', fill='both', expand=True) scrollbar.pack(side='right', fill='y') # Refresh button refresh_btn = ttk.Button(info_frame, text="Refresh Detection", command=self.auto_detect_system) refresh_btn.pack(pady=5) def create_settings_tab(self): """Create settings configuration tab.""" self.settings_frame = ttk.Frame(self.notebook) self.notebook.add(self.settings_frame, text="Settings") # Create scrollable frame canvas = tk.Canvas(self.settings_frame) scrollbar = ttk.Scrollbar(self.settings_frame, orient="vertical", command=canvas.yview) scrollable_frame = ttk.Frame(canvas) scrollable_frame.bind( "", lambda e: canvas.configure(scrollregion=canvas.bbox("all")) ) canvas.create_window((0, 0), window=scrollable_frame, anchor="nw") canvas.configure(yscrollcommand=scrollbar.set) # Performance Settings perf_frame = ttk.LabelFrame(scrollable_frame, text="Performance Settings", padding=10) perf_frame.pack(fill='x', padx=10, pady=5) # CPU Workers ttk.Label(perf_frame, text="CPU Workers:").grid(row=0, column=0, sticky='w', padx=5, pady=2) self.cpu_workers_var = tk.IntVar(value=self.settings.get('max_workers', 4)) cpu_workers_scale = ttk.Scale(perf_frame, from_=1, to=16, variable=self.cpu_workers_var, orient='horizontal') cpu_workers_scale.grid(row=0, column=1, sticky='ew', padx=5, pady=2) self.cpu_workers_label = ttk.Label(perf_frame, text=f"Workers: {self.cpu_workers_var.get()}") self.cpu_workers_label.grid(row=0, column=2, padx=5, pady=2) # GPU Workers ttk.Label(perf_frame, text="GPU Workers:").grid(row=1, column=0, sticky='w', padx=5, pady=2) self.gpu_workers_var = tk.IntVar(value=self.settings.get('gpu_workers', 2)) gpu_workers_scale = ttk.Scale(perf_frame, from_=0, to=8, variable=self.gpu_workers_var, orient='horizontal') gpu_workers_scale.grid(row=1, column=1, sticky='ew', padx=5, pady=2) self.gpu_workers_label = ttk.Label(perf_frame, text=f"Workers: {self.gpu_workers_var.get()}") self.gpu_workers_label.grid(row=1, column=2, padx=5, pady=2) # Chunk Size ttk.Label(perf_frame, text="Chunk Size:").grid(row=2, column=0, sticky='w', padx=5, pady=2) self.chunk_size_var = tk.IntVar(value=self.settings.get('chunk_size', 1000)) chunk_size_scale = ttk.Scale(perf_frame, from_=100, to=2000, variable=self.chunk_size_var, orient='horizontal') chunk_size_scale.grid(row=2, column=1, sticky='ew', padx=5, pady=2) self.chunk_size_label = ttk.Label(perf_frame, text=f"Files: {self.chunk_size_var.get()}") self.chunk_size_label.grid(row=2, column=2, padx=5, pady=2) # GPU Settings gpu_frame = ttk.LabelFrame(scrollable_frame, text="GPU Acceleration", padding=10) gpu_frame.pack(fill='x', padx=10, pady=5) self.use_gpu_var = tk.BooleanVar(value=self.settings.get('use_gpu', True)) ttk.Checkbutton(gpu_frame, text="Enable GPU Acceleration", variable=self.use_gpu_var).grid(row=0, column=0, sticky='w', padx=5, pady=2) self.use_npu_var = tk.BooleanVar(value=self.settings.get('use_npu', True)) ttk.Checkbutton(gpu_frame, text="Enable NPU/AI Acceleration", variable=self.use_npu_var).grid(row=1, column=0, sticky='w', padx=5, pady=2) self.force_gpu_var = tk.BooleanVar(value=self.settings.get('force_gpu', False)) ttk.Checkbutton(gpu_frame, text="Force GPU Usage (Override Detection)", variable=self.force_gpu_var).grid(row=2, column=0, sticky='w', padx=5, pady=2) self.use_cache_var = tk.BooleanVar(value=self.settings.get('use_cache', True)) ttk.Checkbutton(gpu_frame, text="Enable Hash Caching", variable=self.use_cache_var).grid(row=3, column=0, sticky='w', padx=5, pady=2) # Detection Settings detection_frame = ttk.LabelFrame(scrollable_frame, text="Detection Settings", padding=10) detection_frame.pack(fill='x', padx=10, pady=5) # Hash Threshold ttk.Label(detection_frame, text="Hash Threshold:").grid(row=0, column=0, sticky='w', padx=5, pady=2) self.hash_threshold_var = tk.DoubleVar(value=self.settings.get('hash_threshold', 0.85)) hash_threshold_scale = ttk.Scale(detection_frame, from_=0.5, to=1.0, variable=self.hash_threshold_var, orient='horizontal') hash_threshold_scale.grid(row=0, column=1, sticky='ew', padx=5, pady=2) self.hash_threshold_label = ttk.Label(detection_frame, text=f"Threshold: {self.hash_threshold_var.get():.2f}") self.hash_threshold_label.grid(row=0, column=2, padx=5, pady=2) # SSIM Threshold ttk.Label(detection_frame, text="SSIM Threshold:").grid(row=1, column=0, sticky='w', padx=5, pady=2) self.ssim_threshold_var = tk.DoubleVar(value=self.settings.get('ssim_threshold', 0.8)) ssim_threshold_scale = ttk.Scale(detection_frame, from_=0.5, to=1.0, variable=self.ssim_threshold_var, orient='horizontal') ssim_threshold_scale.grid(row=1, column=1, sticky='ew', padx=5, pady=2) self.ssim_threshold_label = ttk.Label(detection_frame, text=f"Threshold: {self.ssim_threshold_var.get():.2f}") self.ssim_threshold_label.grid(row=1, column=2, padx=5, pady=2) # Video Settings video_frame = ttk.LabelFrame(scrollable_frame, text="Video Processing", padding=10) video_frame.pack(fill='x', padx=10, pady=5) ttk.Label(video_frame, text="Max Video Frames:").grid(row=0, column=0, sticky='w', padx=5, pady=2) self.max_video_frames_var = tk.IntVar(value=self.settings.get('max_video_frames', 10)) max_video_frames_scale = ttk.Scale(video_frame, from_=5, to=50, variable=self.max_video_frames_var, orient='horizontal') max_video_frames_scale.grid(row=0, column=1, sticky='ew', padx=5, pady=2) self.max_video_frames_label = ttk.Label(video_frame, text=f"Frames: {self.max_video_frames_var.get()}") self.max_video_frames_label.grid(row=0, column=2, padx=5, pady=2) # Bind scale events cpu_workers_scale.configure(command=self.update_cpu_workers_label) gpu_workers_scale.configure(command=self.update_gpu_workers_label) chunk_size_scale.configure(command=self.update_chunk_size_label) hash_threshold_scale.configure(command=self.update_hash_threshold_label) ssim_threshold_scale.configure(command=self.update_ssim_threshold_label) max_video_frames_scale.configure(command=self.update_max_video_frames_label) # Save/Load buttons button_frame = ttk.Frame(scrollable_frame) button_frame.pack(fill='x', padx=10, pady=10) ttk.Button(button_frame, text="Save Settings", command=self.save_settings).pack(side='left', padx=5) ttk.Button(button_frame, text="Load Settings", command=self.load_settings).pack(side='left', padx=5) ttk.Button(button_frame, text="Reset to Defaults", command=self.reset_settings).pack(side='left', padx=5) ttk.Button(button_frame, text="Auto-Optimize", command=self.auto_optimize_settings).pack(side='left', padx=5) canvas.pack(side="left", fill="both", expand=True) scrollbar.pack(side="right", fill="y") def create_folder_selection_tab(self): """Create folder selection tab.""" self.folder_frame = ttk.Frame(self.notebook) self.notebook.add(self.folder_frame, text="Select Folder") # Folder selection folder_selection_frame = ttk.LabelFrame(self.folder_frame, text="Select Media Folder", padding=10) folder_selection_frame.pack(fill='x', padx=10, pady=10) self.folder_path_var = tk.StringVar() folder_entry = ttk.Entry(folder_selection_frame, textvariable=self.folder_path_var, width=60) folder_entry.pack(side='left', padx=5, pady=5) ttk.Button(folder_selection_frame, text="Browse", command=self.browse_folder).pack(side='left', padx=5, pady=5) # Start processing button self.start_btn = ttk.Button(folder_selection_frame, text="Start Detection", command=self.start_processing) self.start_btn.pack(side='right', padx=5, pady=5) def create_processing_tab(self): """Create processing progress tab.""" self.processing_frame = ttk.Frame(self.notebook) self.notebook.add(self.processing_frame, text="Processing") # Progress bar progress_frame = ttk.LabelFrame(self.processing_frame, text="Progress", padding=10) progress_frame.pack(fill='x', padx=10, pady=10) self.progress_var = tk.DoubleVar() self.progress_bar = ttk.Progressbar(progress_frame, variable=self.progress_var, maximum=100) self.progress_bar.pack(fill='x', padx=5, pady=5) self.progress_label = ttk.Label(progress_frame, text="Ready to start...") self.progress_label.pack(pady=5) # Status indicator self.status_label = ttk.Label(progress_frame, text="Status: Ready", foreground="green") self.status_label.pack(pady=2) # Log display log_frame = ttk.LabelFrame(self.processing_frame, text="Processing Log", padding=10) log_frame.pack(fill='both', expand=True, padx=10, pady=10) self.log_text = tk.Text(log_frame, height=15, wrap='word') log_scrollbar = ttk.Scrollbar(log_frame, orient='vertical', command=self.log_text.yview) self.log_text.configure(yscrollcommand=log_scrollbar.set) self.log_text.pack(side='left', fill='both', expand=True) log_scrollbar.pack(side='right', fill='y') def create_results_tab(self): """Create results display tab.""" self.results_frame = ttk.Frame(self.notebook) self.notebook.add(self.results_frame, text="Results") # Results summary summary_frame = ttk.LabelFrame(self.results_frame, text="Detection Summary", padding=10) summary_frame.pack(fill='x', padx=10, pady=10) self.results_text = tk.Text(summary_frame, height=8, wrap='word') self.results_text.pack(fill='x', padx=5, pady=5) # Duplicates list duplicates_frame = ttk.LabelFrame(self.results_frame, text="Found Duplicates", padding=10) duplicates_frame.pack(fill='both', expand=True, padx=10, pady=10) # Listbox with scrollbar listbox_frame = ttk.Frame(duplicates_frame) listbox_frame.pack(fill='both', expand=True) self.duplicates_listbox = tk.Listbox(listbox_frame, height=15) duplicates_scrollbar = ttk.Scrollbar(listbox_frame, orient='vertical', command=self.duplicates_listbox.yview) self.duplicates_listbox.configure(yscrollcommand=duplicates_scrollbar.set) self.duplicates_listbox.pack(side='left', fill='both', expand=True) duplicates_scrollbar.pack(side='right', fill='y') # Bind selection event self.duplicates_listbox.bind('<>', self.on_duplicate_select) # Action buttons action_frame = ttk.Frame(duplicates_frame) action_frame.pack(fill='x', pady=5) ttk.Button(action_frame, text="View Comparison", command=self.view_comparison).pack(side='left', padx=5) ttk.Button(action_frame, text="Delete Selected", command=self.delete_selected).pack(side='left', padx=5) ttk.Button(action_frame, text="Delete All Duplicates", command=self.delete_all_duplicates).pack(side='left', padx=5) ttk.Button(action_frame, text="Export Results", command=self.export_results).pack(side='left', padx=5) def create_comparison_tab(self): """Create side-by-side comparison tab.""" self.comparison_frame = ttk.Frame(self.notebook) self.notebook.add(self.comparison_frame, text="Comparison") # Comparison controls controls_frame = ttk.Frame(self.comparison_frame) controls_frame.pack(fill='x', padx=10, pady=10) ttk.Button(controls_frame, text="Previous", command=self.previous_duplicate).pack(side='left', padx=5) ttk.Button(controls_frame, text="Next", command=self.next_duplicate).pack(side='left', padx=5) self.comparison_label = ttk.Label(controls_frame, text="No duplicates selected") self.comparison_label.pack(side='left', padx=20) # Delete buttons ttk.Button(controls_frame, text="Delete Current", command=self.delete_current_duplicate).pack(side='right', padx=5) ttk.Button(controls_frame, text="Delete All", command=self.delete_all_duplicates).pack(side='right', padx=5) # Image comparison frame self.image_frame = ttk.Frame(self.comparison_frame) self.image_frame.pack(fill='both', expand=True, padx=10, pady=10) # Left image left_frame = ttk.LabelFrame(self.image_frame, text="Original", padding=5) left_frame.pack(side='left', fill='both', expand=True, padx=5) self.left_image_label = ttk.Label(left_frame, text="No image loaded") self.left_image_label.pack(expand=True) # Right image right_frame = ttk.LabelFrame(self.image_frame, text="Duplicate", padding=5) right_frame.pack(side='right', fill='both', expand=True, padx=5) self.right_image_label = ttk.Label(right_frame, text="No image loaded") self.right_image_label.pack(expand=True) # Comparison info info_frame = ttk.LabelFrame(self.comparison_frame, text="Comparison Details", padding=10) info_frame.pack(fill='x', padx=10, pady=10) self.comparison_info_text = tk.Text(info_frame, height=6, wrap='word') self.comparison_info_text.pack(fill='x') def update_cpu_workers_label(self, value): """Update CPU workers label.""" self.cpu_workers_label.config(text=f"Workers: {int(float(value))}") def update_gpu_workers_label(self, value): """Update GPU workers label.""" self.gpu_workers_label.config(text=f"Workers: {int(float(value))}") def update_chunk_size_label(self, value): """Update chunk size label.""" self.chunk_size_label.config(text=f"Files: {int(float(value))}") def update_hash_threshold_label(self, value): """Update hash threshold label.""" self.hash_threshold_label.config(text=f"Threshold: {float(value):.2f}") def update_ssim_threshold_label(self, value): """Update SSIM threshold label.""" self.ssim_threshold_label.config(text=f"Threshold: {float(value):.2f}") def update_max_video_frames_label(self, value): """Update max video frames label.""" self.max_video_frames_label.config(text=f"Frames: {int(float(value))}") def load_settings(self) -> Dict[str, Any]: """Load settings from file.""" settings_file = Path("gui_settings.json") if settings_file.exists(): try: with open(settings_file, 'r') as f: return json.load(f) except Exception as e: self.logger.warning(f"Error loading settings: {e}") # Default settings return { 'max_workers': 4, 'gpu_workers': 2, 'chunk_size': 1000, 'use_gpu': True, 'use_npu': True, 'force_gpu': False, 'use_cache': True, 'hash_threshold': 0.85, 'ssim_threshold': 0.8, 'max_video_frames': 10 } def save_settings(self): """Save current settings to file.""" settings = { 'max_workers': self.cpu_workers_var.get(), 'gpu_workers': self.gpu_workers_var.get(), 'chunk_size': self.chunk_size_var.get(), 'use_gpu': self.use_gpu_var.get(), 'use_npu': self.use_npu_var.get(), 'force_gpu': self.force_gpu_var.get(), 'use_cache': self.use_cache_var.get(), 'hash_threshold': self.hash_threshold_var.get(), 'ssim_threshold': self.ssim_threshold_var.get(), 'max_video_frames': self.max_video_frames_var.get() } try: with open("gui_settings.json", 'w') as f: json.dump(settings, f, indent=2) messagebox.showinfo("Settings", "Settings saved successfully!") except Exception as e: messagebox.showerror("Error", f"Failed to save settings: {e}") def reset_settings(self): """Reset settings to defaults.""" self.cpu_workers_var.set(4) self.gpu_workers_var.set(2) self.chunk_size_var.set(1000) self.use_gpu_var.set(True) self.use_npu_var.set(True) self.force_gpu_var.set(False) self.use_cache_var.set(True) self.hash_threshold_var.set(0.85) self.ssim_threshold_var.set(0.8) self.max_video_frames_var.set(10) # Update labels self.update_cpu_workers_label(4) self.update_gpu_workers_label(2) self.update_chunk_size_label(1000) self.update_hash_threshold_label(0.85) self.update_ssim_threshold_label(0.8) self.update_max_video_frames_label(10) def auto_optimize_settings(self): """Auto-optimize settings based on detected hardware.""" try: # Use the optimization engine to get optimal settings if self.optimization_profile: # Update GUI variables self.cpu_workers_var.set(self.optimization_profile.get('max_workers', 4)) self.gpu_workers_var.set(self.optimization_profile.get('gpu_workers', 2)) self.chunk_size_var.set(self.optimization_profile.get('chunk_size', 1000)) self.use_gpu_var.set(self.optimization_profile.get('use_gpu', True)) self.use_npu_var.set(self.optimization_profile.get('use_npu', True)) self.use_cache_var.set(self.optimization_profile.get('use_cache', True)) self.hash_threshold_var.set(self.optimization_profile.get('hash_threshold', 0.85)) self.ssim_threshold_var.set(self.optimization_profile.get('ssim_threshold', 0.8)) self.max_video_frames_var.set(self.optimization_profile.get('max_video_frames', 10)) # Update labels self.update_cpu_workers_label(self.optimization_profile.get('max_workers', 4)) self.update_gpu_workers_label(self.optimization_profile.get('gpu_workers', 2)) self.update_chunk_size_label(self.optimization_profile.get('chunk_size', 1000)) self.update_hash_threshold_label(self.optimization_profile.get('hash_threshold', 0.85)) self.update_ssim_threshold_label(self.optimization_profile.get('ssim_threshold', 0.8)) self.update_max_video_frames_label(self.optimization_profile.get('max_video_frames', 10)) messagebox.showinfo("Auto-Optimization", "Settings optimized based on your hardware!") else: messagebox.showwarning("Auto-Optimization", "No optimization profile available. Please run system detection first.") except Exception as e: messagebox.showerror("Error", f"Auto-optimization failed: {e}") def auto_detect_system(self): """Auto-detect system hardware and capabilities.""" try: self.logger.info("Starting system detection...") # Detect system detector = SystemDetector() self.system_info = detector.detect_all() # Generate optimization profile optimizer = OptimizationEngine(self.system_info) self.optimization_profile = optimizer.generate_optimization_profile() # Display system info self.display_system_info() self.logger.info("System detection completed") except Exception as e: self.logger.error(f"System detection failed: {e}") messagebox.showerror("Error", f"System detection failed: {e}") def display_system_info(self): """Display system information in the GUI.""" info_text = "=== SYSTEM DETECTION RESULTS ===\n\n" # CPU Info cpu_info = self.system_info.get('cpu', {}) info_text += f"CPU: {cpu_info.get('model', 'Unknown')}\n" info_text += f"Vendor: {cpu_info.get('vendor', 'Unknown')}\n" info_text += f"Cores: {cpu_info.get('cores_physical', 'Unknown')}\n" info_text += f"Threads: {cpu_info.get('cores_logical', 'Unknown')}\n" info_text += f"Architecture: {cpu_info.get('architecture', 'Unknown')}\n" info_text += f"Features: {', '.join(cpu_info.get('features', []))}\n\n" # Memory Info memory_info = self.system_info.get('memory', {}) info_text += f"Memory: {memory_info.get('total_gb', 0):.1f} GB total, {memory_info.get('available_gb', 0):.1f} GB available\n\n" # GPU Info gpu_info = self.system_info.get('gpu', {}) gpus = gpu_info.get('gpus', []) info_text += f"GPUs Detected: {len(gpus)}\n" for i, gpu in enumerate(gpus): info_text += f"\nGPU {i+1}:\n" info_text += f" Name: {gpu.get('name', 'Unknown')}\n" info_text += f" Vendor: {gpu.get('vendor', 'Unknown')}\n" info_text += f" Type: {gpu.get('type', 'Unknown')}\n" info_text += f" Memory: {gpu.get('memory_gb', 0):.1f} GB\n" info_text += f" Performance Tier: {gpu.get('performance_tier', 'Unknown')}\n" info_text += f" AI Support: {gpu.get('supports_ai', False)}\n" info_text += f" NPU Available: {gpu.get('has_npu', False)}\n" # AI Acceleration ai_capabilities = gpu_info.get('ai_acceleration_available', {}) info_text += f"\nAI Acceleration:\n" info_text += f" CUDA AI: {ai_capabilities.get('cuda_ai', False)}\n" info_text += f" OpenCL AI: {ai_capabilities.get('opencl_ai', False)}\n" info_text += f" Metal AI: {ai_capabilities.get('metal_ai', False)}\n" info_text += f" Vulkan AI: {ai_capabilities.get('vulkan_ai', False)}\n" info_text += f" NPU Available: {ai_capabilities.get('npu_available', False)}\n\n" # Optimization Profile if self.optimization_profile: info_text += "=== OPTIMAL SETTINGS ===\n" info_text += f"CPU Workers: {self.optimization_profile.get('max_workers', 'Unknown')}\n" info_text += f"GPU Workers: {self.optimization_profile.get('gpu_workers', 2)}\n" info_text += f"Chunk Size: {self.optimization_profile.get('chunk_size', 'Unknown')}\n" info_text += f"Use GPU: {self.optimization_profile.get('use_gpu', 'Unknown')}\n" info_text += f"Use NPU: {self.optimization_profile.get('use_npu', 'Unknown')}\n" info_text += f"Use Cache: {self.optimization_profile.get('use_cache', 'Unknown')}\n" info_text += f"Hash Threshold: {self.optimization_profile.get('hash_threshold', 'Unknown')}\n" info_text += f"SSIM Threshold: {self.optimization_profile.get('ssim_threshold', 'Unknown')}\n" info_text += f"Max Video Frames: {self.optimization_profile.get('max_video_frames', 'Unknown')}\n" self.system_info_text.delete(1.0, tk.END) self.system_info_text.insert(1.0, info_text) def browse_folder(self): """Browse for folder to scan.""" folder = filedialog.askdirectory(title="Select Media Folder") if folder: self.folder_path_var.set(folder) def start_processing(self): """Start duplicate detection processing.""" folder_path = self.folder_path_var.get() if not folder_path or not os.path.exists(folder_path): messagebox.showerror("Error", "Please select a valid folder") return # Get current settings settings = { 'max_workers': self.cpu_workers_var.get(), 'gpu_workers': self.gpu_workers_var.get(), 'chunk_size': self.chunk_size_var.get(), 'use_gpu': self.use_gpu_var.get(), 'use_npu': self.use_npu_var.get(), 'force_gpu': self.force_gpu_var.get(), 'use_cache': self.use_cache_var.get(), 'hash_threshold': self.hash_threshold_var.get(), 'ssim_threshold': self.ssim_threshold_var.get(), 'max_video_frames': self.max_video_frames_var.get() } # Switch to processing tab immediately self.notebook.select(3) # Processing tab # Update progress immediately self.update_progress(0, "Initializing duplicate detection...") # Start processing in background thread self.processing_thread = threading.Thread(target=self.process_duplicates, args=(folder_path, settings)) self.processing_thread.daemon = True self.processing_thread.start() def process_duplicates(self, folder_path: str, settings: Dict[str, Any]): """Process duplicates in background thread.""" try: self.logger.info(f"Starting duplicate detection for: {folder_path}") # Initialize detector with settings self.detector = DuplicateDetector( input_dir=folder_path, max_workers=settings['max_workers'], use_cache=settings['use_cache'], chunk_size=settings['chunk_size'], # Use user's preferred chunk size hash_threshold=settings['hash_threshold'], ssim_threshold=settings['ssim_threshold'], max_video_frames=settings['max_video_frames'], use_gpu=settings['use_gpu'], use_npu=settings['use_npu'], force_gpu=settings.get('force_gpu', False), gpu_workers=settings.get('gpu_workers', 2), hardware_profile=self.optimization_profile, processing_timeout=300 # 5 minutes timeout for large files ) # Update progress using queue self.progress_queue.put(('progress', 10, "Starting duplicate detection...")) # Create progress callback function def progress_callback(percent, message): self.logger.info(f"GUI Progress callback: {percent}% - {message}") self.progress_queue.put(('progress', percent, message)) # Process folder with progress callback self.detector.scan_directory(progress_callback=progress_callback) # Update progress self.progress_queue.put(('progress', 95, "Processing completed, analyzing results...")) # Get duplicates from the detector's statistics and duplicates folder self.duplicates = self.get_duplicates_from_detector() # Update GUI in main thread self.logger.info("Calling processing_completed in main thread") self.progress_queue.put(('completed', None, None)) except Exception as e: self.logger.error(f"Processing failed: {e}") # Check if it's a timeout error and provide better message if "futures unfinished" in str(e): self.logger.warning("Some chunks timed out, but processing will continue with available results") self.progress_queue.put(('warning', None, "Some files timed out, but processing will continue with available results")) else: self.progress_queue.put(('error', None, f"Processing failed: {e}")) def get_duplicates_from_detector(self) -> List[List[str]]: """Get duplicate information from the detector's statistics.""" duplicates = [] try: # Get actual duplicate groups from the detector if hasattr(self.detector, 'duplicate_groups') and self.detector.duplicate_groups: duplicates = self.detector.duplicate_groups self.duplicates = duplicates # Clean up the groups to remove non-existent files self.cleanup_duplicate_groups() duplicates = self.duplicates self.logger.info(f"Retrieved {len(duplicates)} duplicate groups from detector") else: # Fallback to statistics if no groups available stats = self.detector.stats duplicates_found = stats.get('duplicates_found', 0) files_moved = stats.get('files_moved', 0) if duplicates_found > 0: # Create a summary representation summary_info = [ f"Total duplicates found: {duplicates_found}", f"Files moved to duplicates folder: {files_moved}", f"Duplicates folder: {self.detector.duplicates_dir}" ] duplicates.append(summary_info) self.logger.info(f"Found {duplicates_found} duplicates, moved {files_moved} files") except Exception as e: self.logger.error(f"Error getting duplicates from detector: {e}") return duplicates def update_progress(self, value: int, message: str): """Update progress bar and label.""" self.logger.info(f"Updating progress: {value}% - {message}") self.progress_var.set(value) self.progress_label.config(text=message) # Update status indicator if value == 0: self.status_label.config(text="Status: Initializing...", foreground="orange") elif value < 100: self.status_label.config(text="Status: Processing...", foreground="blue") else: self.status_label.config(text="Status: Completed", foreground="green") self.log_text.insert(tk.END, f"{message}\n") self.log_text.see(tk.END) self.root.update_idletasks() # Force GUI update def processing_completed(self): """Handle processing completion.""" self.logger.info("Processing completed - updating GUI") self.progress_var.set(100) self.progress_label.config(text="Processing completed!") # Update results self.update_results_display() # Switch to results tab self.logger.info("Switching to results tab") self.notebook.select(4) # Results tab duplicates_found = self.detector.stats.get('duplicates_found', 0) if self.detector else 0 self.logger.info(f"Showing completion dialog: {duplicates_found} duplicates found") messagebox.showinfo("Complete", f"Processing completed! Found {duplicates_found} duplicates.") def update_results_display(self): """Update results display.""" # Clean up duplicate groups to remove non-existent files self.cleanup_duplicate_groups() # Get statistics from detector stats = self.detector.stats if self.detector else {} # Update summary summary_text = f"Detection Summary:\n" summary_text += f"Images processed: {stats.get('images_processed', 0)}\n" summary_text += f"Videos processed: {stats.get('videos_processed', 0)}\n" summary_text += f"Duplicates found: {stats.get('duplicates_found', 0)}\n" summary_text += f"Files moved: {stats.get('files_moved', 0)}\n" summary_text += f"Processing time: {stats.get('processing_time', 0):.2f} seconds\n" summary_text += f"Cache hits: {stats.get('cache_hits', 0)}\n" summary_text += f"Errors: {stats.get('errors', 0)}\n\n" if stats.get('gpu_acceleration_used', False): summary_text += f"GPU acceleration: ENABLED\n" if hasattr(self.detector, 'gpu_memory_info') and self.detector.gpu_memory_info: gpu_info = self.detector.gpu_memory_info summary_text += f"GPU memory: {gpu_info['used']:.1f}GB / {gpu_info['total']:.1f}GB used\n" else: summary_text += f"GPU acceleration: DISABLED\n" summary_text += f"\nDuplicates folder: {self.detector.duplicates_dir if self.detector else 'N/A'}\n" self.results_text.delete(1.0, tk.END) self.results_text.insert(1.0, summary_text) # Update duplicates list self.duplicates_listbox.delete(0, tk.END) if self.duplicates: for i, group in enumerate(self.duplicates): if isinstance(group[0], str) and group[0].startswith("Total duplicates found"): # This is a summary group group_text = f"Summary: {group[0]}" else: group_text = f"Group {i+1}: {len(group)} files" self.duplicates_listbox.insert(tk.END, group_text) def calculate_space_savings(self) -> float: """Calculate potential space savings in MB.""" total_size = 0 for group in self.duplicates: if len(group) > 1: # Calculate size of duplicate files (excluding the first one) for file_path in group[1:]: try: total_size += os.path.getsize(file_path) except: pass return total_size / (1024 * 1024) # Convert to MB def on_duplicate_select(self, event): """Handle duplicate selection.""" selection = self.duplicates_listbox.curselection() if selection: self.current_duplicate_index = selection[0] self.update_comparison_display() def view_comparison(self): """View side-by-side comparison.""" if not self.duplicates: messagebox.showwarning("Warning", "No duplicates to compare") return # Switch to comparison tab self.notebook.select(5) # Comparison tab self.update_comparison_display() def update_comparison_display(self): """Update side-by-side comparison display.""" if not self.duplicates or self.current_duplicate_index >= len(self.duplicates): return group = self.duplicates[self.current_duplicate_index] if len(group) < 2: return # Update comparison label self.comparison_label.config(text=f"Group {self.current_duplicate_index + 1} of {len(self.duplicates)} - {len(group)} files") # Load and display images self.load_comparison_images(group[0], group[1]) # Update comparison info self.update_comparison_info(group) def clear_comparison_display(self): """Clear the comparison display when no more duplicates exist.""" # Clear images self.left_image_label.config(image="", text="No more duplicates to display") self.right_image_label.config(image="", text="All duplicates have been processed") # Clear image references self.left_image_label.image = None self.right_image_label.image = None # Update comparison label self.comparison_label.config(text="All duplicates processed") # Clear comparison info self.comparison_info_text.delete(1.0, tk.END) self.comparison_info_text.insert(tk.END, "All duplicate files have been processed.\n\nYou can:\n• Run a new scan\n• Check the Results tab for summary\n• Close the application") # Disable navigation buttons (if they exist) try: # Find and disable navigation buttons for widget in self.root.winfo_children(): if isinstance(widget, ttk.Frame): for child in widget.winfo_children(): if isinstance(child, ttk.Button) and child['text'] in ['Previous', 'Next']: child.config(state=tk.DISABLED) except: pass # Ignore if buttons can't be found # Disable delete buttons (if they exist) try: # Find and disable delete buttons dynamically for widget in self.root.winfo_children(): if isinstance(widget, ttk.Frame): for child in widget.winfo_children(): if isinstance(child, ttk.Button) and child['text'] in ['Delete Current', 'Delete All', 'Delete Selected', 'Delete All Duplicates']: child.config(state=tk.DISABLED) except: pass # Ignore if buttons can't be found def resolve_image_path(self, image_path: str) -> str: """Resolve image path, checking both original location and duplicates folder.""" # First check if the original path exists if os.path.exists(image_path): return image_path # If not, check if it's in the duplicates folder if self.detector and hasattr(self.detector, 'duplicates_dir') and os.path.exists(self.detector.duplicates_dir): # Get the filename from the original path filename = os.path.basename(image_path) duplicate_path = os.path.join(self.detector.duplicates_dir, filename) if os.path.exists(duplicate_path): return duplicate_path # Also check subdirectories in duplicates folder (only if duplicates_dir exists) try: for root, dirs, files in os.walk(self.detector.duplicates_dir): if filename in files: return os.path.join(root, filename) except (OSError, PermissionError): # If we can't walk the directory, just return None pass return None def load_image_with_fallback(self, image_path: str) -> Optional[Image.Image]: """Load image with fallback support for RAW and HEIC/HEIF formats.""" from pathlib import Path file_ext = Path(image_path).suffix.lower() try: # Try standard PIL first return Image.open(image_path) except Exception: pass # Handle RAW formats if file_ext in {'.dng', '.cr2', '.cr3', '.nef', '.nrw', '.arw', '.srf', '.sr2', '.orf', '.rw2', '.pef', '.ptx', '.x3f', '.r3d', '.fff', '.raf', '.rwl', '.dcr', '.k25', '.kdc', '.erf', '.mef', '.mos', '.mrw', '.srw', '.3fr', '.ari', '.bay', '.cap', '.data', '.dcs', '.drf', '.eip', '.iiq', '.mdc', '.mfw', '.obm', '.pxn', '.rwz', '.raw'}: try: # Try with rawpy for RAW files import rawpy with rawpy.imread(image_path) as raw: rgb = raw.postprocess() return Image.fromarray(rgb) except ImportError: pass except Exception: pass # Handle HEIC/HEIF formats if file_ext in {'.heic', '.heif'}: try: # Try with pillow-heif from pillow_heif import register_heif_opener register_heif_opener() return Image.open(image_path) except ImportError: pass except Exception: pass # Handle AVIF format (optional support) if file_ext in {'.avif'}: try: # Try with pillow-avif-plugin from pillow_avif import register_avif_opener register_avif_opener() return Image.open(image_path) except ImportError: # AVIF support not available - this is optional pass except Exception: # AVIF processing failed pass # If all else fails, return None return None def cleanup_duplicate_groups(self): """Clean up duplicate groups by removing references to files that no longer exist.""" if not self.duplicates: return original_count = len(self.duplicates) cleaned_groups = [] for group in self.duplicates: # Keep only files that actually exist existing_files = [] for file_path in group: resolved_path = self.resolve_image_path(file_path) if resolved_path and os.path.exists(resolved_path): existing_files.append(file_path) # Only keep groups that have at least 2 files (original + duplicates) if len(existing_files) >= 2: cleaned_groups.append(existing_files) self.duplicates = cleaned_groups # Debug logging self.logger.info(f"Cleanup: {original_count} groups -> {len(self.duplicates)} groups") # Adjust current index if needed if self.current_duplicate_index >= len(self.duplicates): self.current_duplicate_index = max(0, len(self.duplicates) - 1) def load_comparison_images(self, image1_path: str, image2_path: str): """Load and display comparison images.""" try: # Resolve image paths (check both original and duplicates folder) resolved_path1 = self.resolve_image_path(image1_path) resolved_path2 = self.resolve_image_path(image2_path) # Load first image if resolved_path1 and os.path.exists(resolved_path1): img1 = self.load_image_with_fallback(resolved_path1) if img1: img1.thumbnail((400, 400), Image.Resampling.LANCZOS) photo1 = ImageTk.PhotoImage(img1) self.left_image_label.config(image=photo1, text="") self.left_image_label.image = photo1 # Keep reference else: self.left_image_label.config(image="", text="Unsupported format") else: self.left_image_label.config(image="", text="Image not found") # Load second image if resolved_path2 and os.path.exists(resolved_path2): img2 = self.load_image_with_fallback(resolved_path2) if img2: img2.thumbnail((400, 400), Image.Resampling.LANCZOS) photo2 = ImageTk.PhotoImage(img2) self.right_image_label.config(image=photo2, text="") self.right_image_label.image = photo2 # Keep reference else: self.right_image_label.config(image="", text="Unsupported format") else: self.right_image_label.config(image="", text="Image not found") except Exception as e: self.logger.error(f"Error loading images: {e}") self.left_image_label.config(image="", text="Error loading image") self.right_image_label.config(image="", text="Error loading image") def update_comparison_info(self, group: List[str]): """Update comparison information.""" info_text = f"Duplicate Group Information:\n\n" info_text += f"Files in group: {len(group)}\n" info_text += f"Original file: {os.path.basename(group[0])}\n" info_text += f"Duplicate files: {len(group) - 1}\n\n" info_text += "File details:\n" for i, file_path in enumerate(group): try: file_size = os.path.getsize(file_path) info_text += f"{i+1}. {os.path.basename(file_path)} ({file_size / 1024:.1f} KB)\n" except: info_text += f"{i+1}. {os.path.basename(file_path)} (size unknown)\n" self.comparison_info_text.delete(1.0, tk.END) self.comparison_info_text.insert(1.0, info_text) def previous_duplicate(self): """Go to previous duplicate group.""" if self.duplicates and self.current_duplicate_index > 0: self.current_duplicate_index -= 1 self.update_comparison_display() def next_duplicate(self): """Go to next duplicate group.""" if self.duplicates and self.current_duplicate_index < len(self.duplicates) - 1: self.current_duplicate_index += 1 self.update_comparison_display() def delete_selected(self): """Delete selected duplicate files.""" if not self.duplicates or self.current_duplicate_index >= len(self.duplicates): return # Clean up duplicate groups first to remove non-existent files self.cleanup_duplicate_groups() if self.current_duplicate_index >= len(self.duplicates): return group = self.duplicates[self.current_duplicate_index] if len(group) < 2: return # Count existing files in this group existing_files = 0 for file_path in group[1:]: # Skip first file (keep original) resolved_path = self.resolve_image_path(file_path) if resolved_path and os.path.exists(resolved_path): existing_files += 1 if existing_files == 0: messagebox.showinfo("No Duplicates", "No duplicate files found in this group to delete.") return # Ask for confirmation result = messagebox.askyesno( "Confirm Delete", f"Deleting {existing_files} duplicates for 1 photo" ) if result: try: deleted_count = 0 for file_path in group[1:]: # Skip first file (keep original) try: # Resolve the actual file path (check duplicates folder) resolved_path = self.resolve_image_path(file_path) if resolved_path and os.path.exists(resolved_path): os.remove(resolved_path) deleted_count += 1 self.logger.info(f"Deleted duplicate: {resolved_path}") # Don't log warnings for files that don't exist - they were likely already moved except Exception as e: self.logger.error(f"Error deleting {file_path}: {e}") messagebox.showinfo("Delete Complete", f"Deleted {deleted_count} duplicate files") # Check if current group still has duplicates current_group = self.duplicates[self.current_duplicate_index] remaining_duplicates = 0 for file_path in current_group[1:]: # Skip first file (keep original) resolved_path = self.resolve_image_path(file_path) if resolved_path and os.path.exists(resolved_path): remaining_duplicates += 1 # Refresh results self.update_results_display() # Update comparison display based on remaining duplicates if remaining_duplicates == 0: # Current group has no more duplicates, move to next or clear display if self.current_duplicate_index < len(self.duplicates) - 1: self.next_duplicate() else: # No more groups, clear the comparison display self.clear_comparison_display() else: # Still has duplicates, refresh current display self.update_comparison_display() except Exception as e: messagebox.showerror("Error", f"Delete failed: {e}") def delete_current_duplicate(self): """Delete the currently displayed duplicate group.""" if not self.duplicates or self.current_duplicate_index >= len(self.duplicates): messagebox.showwarning("Warning", "No duplicate group selected") return # Clean up duplicate groups first to remove non-existent files self.cleanup_duplicate_groups() if self.current_duplicate_index >= len(self.duplicates): messagebox.showwarning("Warning", "No duplicate group selected") return group = self.duplicates[self.current_duplicate_index] if len(group) < 2: messagebox.showwarning("Warning", "No duplicates in this group") return # Count existing files in this group existing_files = 0 for file_path in group[1:]: # Skip first file (keep original) resolved_path = self.resolve_image_path(file_path) if resolved_path and os.path.exists(resolved_path): existing_files += 1 if existing_files == 0: messagebox.showinfo("No Duplicates", "No duplicate files found in this group to delete.") return # Ask for confirmation result = messagebox.askyesno( "Confirm Delete", f"Deleting {existing_files} duplicates for 1 photo" ) if result: try: deleted_count = 0 for file_path in group[1:]: # Skip first file (keep original) try: # Resolve the actual file path (check duplicates folder) resolved_path = self.resolve_image_path(file_path) if resolved_path and os.path.exists(resolved_path): os.remove(resolved_path) deleted_count += 1 self.logger.info(f"Deleted duplicate: {resolved_path}") # Don't log warnings for files that don't exist - they were likely already moved except Exception as e: self.logger.error(f"Error deleting {file_path}: {e}") messagebox.showinfo("Delete Complete", f"Deleted {deleted_count} duplicate files") # Check if current group still has duplicates current_group = self.duplicates[self.current_duplicate_index] remaining_duplicates = 0 for file_path in current_group[1:]: # Skip first file (keep original) resolved_path = self.resolve_image_path(file_path) if resolved_path and os.path.exists(resolved_path): remaining_duplicates += 1 if remaining_duplicates == 0: # Current group has no more duplicates, move to next or clear display if self.current_duplicate_index < len(self.duplicates) - 1: self.next_duplicate() else: # No more groups, clear the comparison display self.clear_comparison_display() else: # Still has duplicates, refresh current display self.update_comparison_display() except Exception as e: messagebox.showerror("Error", f"Delete failed: {e}") def delete_all_duplicates(self): """Delete all duplicate files.""" if not self.duplicates: return # Clean up duplicate groups first to remove non-existent files self.cleanup_duplicate_groups() # Force a fresh count by re-checking all files existing_duplicates = 0 total_files_checked = 0 # Log the current state self.logger.info(f"Delete All: Starting count with {len(self.duplicates)} groups") # Calculate group size distribution group_sizes = [len(group) for group in self.duplicates] self.logger.info(f"Delete All: Group sizes: {group_sizes[:10]}{'...' if len(group_sizes) > 10 else ''}") self.logger.info(f"Delete All: Average group size: {sum(group_sizes) / len(group_sizes):.1f}") for group_idx, group in enumerate(self.duplicates): if group_idx < 5: # Only log first 5 groups to avoid spam self.logger.info(f"Delete All: Processing group {group_idx + 1} with {len(group)} files") for file_idx, file_path in enumerate(group[1:]): # Skip first file (keep original) total_files_checked += 1 resolved_path = self.resolve_image_path(file_path) exists = resolved_path and os.path.exists(resolved_path) if exists: existing_duplicates += 1 if group_idx < 5: # Only log first 5 groups to avoid spam self.logger.info(f"Delete All: File {file_idx + 1}: '{file_path}' -> '{resolved_path}' (exists: {exists})") # Debug logging self.logger.info(f"Delete All: Checked {total_files_checked} files, found {existing_duplicates} existing files") self.logger.info(f"Delete All: Duplicates folder: {getattr(self.detector, 'duplicates_dir', 'None') if self.detector else 'No detector'}") # Additional debug: show some example file paths if self.duplicates and len(self.duplicates) > 0: example_group = self.duplicates[0] if len(example_group) > 1: example_file = example_group[1] resolved = self.resolve_image_path(example_file) self.logger.info(f"Delete All: Example file '{example_file}' -> resolved to '{resolved}'") # Log the discrepancy if any if existing_duplicates != total_files_checked: missing_files = total_files_checked - existing_duplicates self.logger.info(f"Delete All: {missing_files} files are missing (already moved/deleted)") if existing_duplicates == 0: messagebox.showinfo("No Duplicates", "No duplicate files found to delete.") return # Calculate the number of photos (groups) total_photos = len(self.duplicates) # Simple, clear message - only show what we can actually delete message = f"Deleting {existing_duplicates} duplicates for {total_photos} photos" # Log the exact message being shown self.logger.info(f"Delete All: Showing dialog with message: {message}") result = messagebox.askyesno("Confirm Delete All", message) if result: try: deleted_count = 0 failed_count = 0 for group in self.duplicates: for file_path in group[1:]: # Skip first file (keep original) try: # Resolve the actual file path (check duplicates folder) resolved_path = self.resolve_image_path(file_path) if resolved_path and os.path.exists(resolved_path): os.remove(resolved_path) deleted_count += 1 self.logger.info(f"Deleted duplicate: {resolved_path}") else: # File doesn't exist - this is expected for some files self.logger.debug(f"File not found (already moved): {file_path}") except Exception as e: failed_count += 1 self.logger.error(f"Error deleting {file_path}: {e}") # Show completion message with actual results if failed_count == 0: messagebox.showinfo("Delete Complete", f"Deleted {deleted_count} duplicate files") else: messagebox.showinfo("Delete Complete", f"Deleted {deleted_count} duplicate files\n{failed_count} files failed to delete") # Clear results self.duplicates = [] self.update_results_display() # Clear comparison display since all duplicates are gone self.clear_comparison_display() except Exception as e: messagebox.showerror("Error", f"Delete failed: {e}") def export_results(self): """Export results to file.""" if not self.duplicates: messagebox.showwarning("Warning", "No results to export") return file_path = filedialog.asksaveasfilename( defaultextension=".txt", filetypes=[("Text files", "*.txt"), ("All files", "*.*")] ) if file_path: try: with open(file_path, 'w') as f: f.write("Duplicate Detection Results\n") f.write("=" * 50 + "\n\n") f.write(f"Total duplicate groups: {len(self.duplicates)}\n") f.write(f"Total duplicate files: {sum(len(group) for group in self.duplicates)}\n\n") for i, group in enumerate(self.duplicates): f.write(f"Group {i+1} ({len(group)} files):\n") for file_path in group: f.write(f" - {file_path}\n") f.write("\n") messagebox.showinfo("Export Complete", f"Results exported to {file_path}") except Exception as e: messagebox.showerror("Error", f"Export failed: {e}") def process_progress_queue(self): """Process progress queue for real-time updates.""" try: while True: item = self.progress_queue.get_nowait() if item: message_type, value, message = item if message_type == 'progress': self.logger.info(f"Processing progress queue: {value}% - {message}") self.update_progress(value, message) elif message_type == 'completed': self.processing_completed() elif message_type == 'error': messagebox.showerror("Error", message) elif message_type == 'warning': messagebox.showwarning("Warning", message) else: # Legacy string message self.log_text.insert(tk.END, str(item) + "\n") self.log_text.see(tk.END) except queue.Empty: pass # Schedule next check (more frequent for better responsiveness) self.root.after(50, self.process_progress_queue) def run(self): """Run the GUI application.""" self.root.mainloop() def main(): """Main function.""" print("🚀 Starting Advanced Duplicate Detector GUI...") try: app = AdvancedDuplicateDetectorGUI() app.run() except Exception as e: print(f"❌ Error starting GUI: {e}") sys.exit(1) if __name__ == "__main__": main()