Analyze the following code. Do not change it just analyze it. Code: import ctypes
import logging
import os
import shutil
import subprocess
import threading
import time
import tkinter as tk
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from pathlib import Path
from queue import Queue
from tkinter import filedialog
from tkinter import ttk
from typing import Any, Callable, Dict, Iterable, List, Set, Tuple
from dataclasses import dataclass, field
import tempfile
import numpy as np
from PIL import Image, ImageOps
--- Configuration ---
@dataclass
class SharedState:
"""Represents the shared state across the application."""
processed_files_lock: threading.Lock = field(default_factory=threading.Lock)
processed_files_count: int = 0
total_files_count: int = 0
log_message_queue: Queue = field(default_factory=Queue)
tab_messages: Dict[str, List[str]] = field(default_factory=lambda: {
"Log": [],
"Black": [],
"White": [],
"Color": []
})
stop_event: threading.Event = field(default_factory=threading.Event)
@contextmanager
def create_temp_folder() -> Path:
"""Yield a temporary folder within the output directory."""
with tempfile.TemporaryDirectory(dir=Config.OUTPUT_FOLDER) as temp_dir:
yield Path(temp_dir)
--- Utility Functions ---
def log_error(message: str) -> None:
"""Log an error message to the shared state queue."""
shared_state.log_message_queue.put(f"- {message}")
Assistant
def clear_console() -> None:
"""Clear the console screen."""
os.system('cls' if os.name == 'nt' else 'clear')
def count_image_files(folder: Path) -> int:
"""Count the number of image files in a folder and its subfolders."""
return sum(1 for path in folder.rglob('*') if path.is_file() and path.suffix.lower() in IMAGE_EXTENSIONS)
def is_valid_image(path: Path) -> bool:
"""Check if the given path is a valid image file."""
try:
with Image.open(path):
return True
except (OSError, ValueError) as e:
log_error(f"Error reading image {path}: {e}")
return False
def open_and_convert_image(path: Path) -> Image.Image:
"""Open an image and convert it to an appropriate mode."""
with Image.open(path) as img:
match img.mode:
case 'P':
return img.convert('L')
case 'L' | 'RGB' | 'RGBA':
return img.copy()
case _:
return img.convert('RGB')
def convert_png_to_jpg(input_path: Path, output_path: Path) -> None:
"""Convert a PNG image to JPG format."""
try:
with Image.open(input_path) as img:
if img.mode not in ('RGB', 'L'):
img = img.convert('RGB')
jpg_path = output_path.with_suffix('.jpg')
img.save(jpg_path, format='JPEG', quality=80, subsampling=0)
input_path.unlink()
except Exception as e:
log_error(f"Error converting {input_path} to JPG: {e}")
def check_executable(executable: Path, name: str) -> None:
"""Check if a given executable is available in the system."""
if not shutil.which(str(executable)):
raise FileNotFoundError(f"- {name} executable not found at: {executable}")
def check_imagemagick() -> None:
"""Check if ImageMagick is available in the system."""
check_executable(Config.IMAGEMAGICK, "ImageMagick")
def check_ffmpeg() -> None:
"""Check if FFmpeg is available in the system."""
check_executable(Config.FFMPEG, "FFmpeg")
--- Color Detection ---
def is_color_image(
img: np.ndarray,
diff_threshold: int = Config.COLORDIFF_THRESHOLD,
fraction_threshold: float = Config.FRACTION_COLORED_PIXELS_THRESHOLD
) -> bool:
"""Determine if an image is color based on RGB channel differences."""
# Check if the image has three channels (RGB)
if img.ndim != 3 or img.shape[2] != 3:
return False
# Calculate the peak-to-peak (max - min) difference across the RGB channels for each pixel
max_diff = np.ptp(img, axis=2)
# Compute the fraction of pixels where the max difference exceeds the threshold
fraction_colored = np.mean(max_diff > diff_threshold)
# Determine if the image meets or exceeds the required fraction of colored pixels
return fraction_colored >= fraction_threshold
--- Process Bar and Multithreading ---
def update_status(start_time: float, processed_count: int, total_files: int) -> None:
"""Update the application's status text with processing details."""
elapsed_time = time.time() - start_time
minutes, seconds = divmod(int(elapsed_time), 60)
elapsed_time_str = f"{minutes:02d}:{seconds:02d}"
def update_elapsed_time(start_time: float, total_files: int, stop_event: threading.Event) -> None:
"""Continuously update the elapsed time until the stop event is set."""
while not stop_event.is_set():
update_status(start_time, shared_state.processed_files_count, total_files)
time.sleep(1)
def start_elapsed_time_thread(start_time: float, total_files: int, stop_event: threading.Event) -> threading.Thread:
"""Start a thread to update the elapsed time."""
thread = threading.Thread(
target=update_elapsed_time,
args=(start_time, total_files, stop_event),
daemon=True
)
thread.start()
return thread
def run_with_thread_pool(tasks: Iterable[Any], process_func: Callable[..., Any], *args) -> int:
"""Execute tasks using a thread pool, updating progress and handling errors."""
shared_state.processed_files_count = 0
shared_state.total_files_count = total = len(tasks)
start_time = time.time()
app.update_progress(0)
stop_event = threading.Event()
elapsed_time_thread = start_elapsed_time_thread(start_time, total, stop_event)
try:
with ThreadPoolExecutor() as executor:
futures: list[Future] = [
executor.submit(process_func, task, *args) for task in tasks
]
for index, future in enumerate(futures, start=1):
if shared_state.stop_event.is_set():
for f in futures:
f.cancel()
break
try:
future.result()
except Exception as e:
log_error(f"Error during processing: {e}")
finally:
progress = (index / total) * 100
app.update_progress(progress)
finally:
stop_event.set()
elapsed_time_thread.join()
return total
def adjust_values(img: np.ndarray) -> Tuple[np.ndarray, int, int]:
"""Adjust the values of a grayscale image."""
try:
# Calculate modal white value in the range [250, 256)
hist_white, bins_white = np.histogram(img[img >= 250], bins=6, range=(250, 256))
modal_white = int(bins_white[np.argmax(hist_white)])
# Calculate modal black value in the range [0, 61)
hist_black, bins_black = np.histogram(img[img < 61], bins=61, range=(0, 61))
modal_black = int(bins_black[np.argmax(hist_black)])
# Convert image to float for processing
adjusted = img.astype(np.float64)
# Scale image if modal white is not at maximum intensity
if modal_white != 255:
adjusted *= 255.0 / modal_white
adjusted = np.clip(adjusted, 0, 255)
# Adjust image based on modal black value
if modal_black:
adjusted = (adjusted - modal_black) * (255.0 / (255 - modal_black))
adjusted = np.clip(adjusted, 0, 255)
gamma = 1.0 - (modal_black / 255.0)
adjusted = np.power(adjusted / 255.0, gamma) * 255
# Preserve original extreme values
adjusted[img == 0] = 0
adjusted[img == 255] = 255
# Convert back to unsigned 8-bit integer
adjusted = adjusted.astype(np.uint8)
return adjusted, modal_black, modal_white
except ValueError as e:
log_error(f"Error adjusting values for image: {e}")
return img, 0, 255
def analyze_images(image_processor: 'ImageProcessor') -> None:
"""Analyze images in the input folder for color properties."""
image_processor.reset_results()
image_files = [
path for path in Config.INPUT_FOLDER.rglob('*')
if path.is_file() and path.suffix.lower() in Config.IMAGE_EXTENSIONS
]
if not image_files:
log_error(f"No image files found in '{Config.INPUT_FOLDER}'")
return
with create_temp_folder() as temp_folder:
start_time = time.time()
run_with_thread_pool(image_files, analyze_file, start_time, len(image_files))
def analyze_file(path: Path, start_time: float, total: int) -> None:
"""Analyze an image to classify it as color or grayscale."""
if not is_valid_image(path):
return
try:
img = np.array(open_and_convert_image(path))
subfolder = path.parent.relative_to(Config.INPUT_FOLDER).as_posix()
filename = path.name
if is_color_image(img):
image_processor.color_results[subfolder].append(filename)
else:
adjusted, modal_black, modal_white = adjust_values(img)
if modal_black:
image_processor.black_results[subfolder].append((filename, modal_black))
if modal_white != 255:
image_processor.white_results[subfolder].append((filename, modal_white))
except (OSError, ValueError) as e:
log_error(f"Error processing image {path}: {e}")
finally:
with shared_state.processed_files_lock:
shared_state.processed_files_count += 1
update_status(start_time, shared_state.processed_files_count, total)
def find_color_images(image_processor: "ImageProcessor") -> None:
"""Find and move color images to the output folder."""
image_processor.reset_results()
image_extensions: set[str] = {ext.lower() for ext in Config.IMAGE_EXTENSIONS}
tasks: list[Path]
if not (tasks := [
path
for path in Config.INPUT_FOLDER.rglob("*")
if path.is_file() and path.suffix.lower() in image_extensions
]):
log_error(f"No image files found in '{Config.INPUT_FOLDER}'")
return
with create_temp_folder():
run_with_thread_pool(
tasks, move_color_image_file, time.time(), len(tasks), image_processor
)
def move_color_image_file(path: Path, start_time: float, total_files: int, image_processor: 'ImageProcessor') -> None:
"""Move a color image file to the output folder and update processing status."""
if not is_valid_image(path):
with shared_state.processed_files_lock:
shared_state.processed_files_count += 1
update_status(start_time, shared_state.processed_files_count, total_files)
return
def check_for_corrupted_files() -> None:
"""Check for corrupted files in the input folder using FFmpeg."""
image_processor.reset_results()
try:
check_ffmpeg()
except FileNotFoundError as error:
log_error(str(error))
return
valid_extensions: set[str] = (
Config.VIDEO_EXTENSIONS
| Config.AUDIO_EXTENSIONS
| Config.IMAGE_EXTENSIONS
)
tasks: List[Path] = [
file
for file in Config.INPUT_FOLDER.rglob("*")
if file.is_file() and file.suffix.lower() in valid_extensions
]
if not tasks:
log_error(f"No valid media files found in '{Config.INPUT_FOLDER}'")
return
error_queue: Queue[Tuple[Path, List[str]]] = Queue()
start_time: float = time.time()
total_files: int = len(tasks)
def check_file(file_path: Path) -> None:
try:
base_command: List[str] = [
str(Config.FFMPEG),
"-v", "error",
"-i", str(file_path)
]
if file_path.suffix.lower() in Config.VIDEO_EXTENSIONS:
base_command += ["-map", "0:a:0"]
base_command += ["-f", "null", "-"]
result: subprocess.CompletedProcess = subprocess.run(
base_command,
capture_output=True,
text=True,
encoding="utf-8",
errors="ignore"
)
combined_output: str = f"{result.stdout}\n{result.stderr}"
error_messages: List[str] = [
line.strip()
for line in combined_output.splitlines()
if "error" in line.lower()
]
if error_messages:
error_queue.put((file_path.resolve(), error_messages))
except Exception as e:
error_queue.put((file_path.resolve(), [f"Error processing file {file_path}: {e}"]))
finally:
with shared_state.processed_files_lock:
shared_state.processed_files_count += 1
update_status(start_time, shared_state.processed_files_count, total_files)
run_with_thread_pool(tasks, check_file)
log_errors(error_queue)
--- Resize Images ---
def resize_image(input_path: Path, output_path: Path) -> Path:
"""Resize an image using ImageMagick."""
output_path = output_path.with_suffix('.png')
identify_command = [
str(Config.IMAGEMAGICK),
str(input_path),
'-format', '%wx%h',
'info:'
]
try:
result = subprocess.run(
identify_command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
check=True
)
current_width, current_height = map(int, result.stdout.strip().split('x'))
except subprocess.CalledProcessError as e:
log_error(f"ImageMagick identify failed for {input_path}: {e.stderr.strip()}")
return output_path
resize_mode = app.RESIZE_MODE.get()
maintain_aspect = app.maintain_aspect_ratio.get()
if resize_mode == "Fit":
target_width = int(app.RESIZE_WIDTH.get() or 0)
target_height = int(app.RESIZE_HEIGHT.get() or 0)
if maintain_aspect:
if target_width == 0 and target_height > 0:
target_width = int(target_height * current_width / current_height)
elif target_height == 0 and target_width > 0:
target_height = int(target_width * current_height / current_width)
resize_arg = f'{target_width}x{target_height}!'
else: # Shortest Side
target_size = int(app.RESIZE_SIDE.get())
resize_arg = f'{target_size}x{target_size}^'
is_upscaling = (
(resize_mode == "Fit" and (target_width > current_width or target_height > current_height)) or
(resize_mode == "Shortest Side" and target_size > min(current_width, current_height))
)
command = [
str(Config.IMAGEMAGICK),
str(input_path),
]
if is_upscaling:
command += [
'-filter', 'LanczosSharp',
'-distort', 'Resize', resize_arg,
]
else:
command += [
'-colorspace', 'RGB',
'-filter', 'Lanczos2Sharp',
'-resize', resize_arg,
'-colorspace', 'sRGB',
]
command += [
'-define', 'png:compression-level=5',
str(output_path)
]
try:
result = subprocess.run(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
check=True
)
if result.stderr:
log_error(f"ImageMagick: {result.stderr.strip()}")
except subprocess.CalledProcessError as e:
log_error(f"ImageMagick resize failed for {input_path}: {e.stderr.strip()}")
return output_path
def resize_images(input_folder: Path, output_folder: Path, image_processor: 'ImageProcessor'):
"""Resize images in the input folder and save them to the output folder."""
try:
check_imagemagick()
except FileNotFoundError as e:
log_error(str(e))
return
tasks = [input_path for input_path in input_folder.rglob('*')
if input_path.is_file() and input_path.suffix.lower() in Config.IMAGE_EXTENSIONS]
if not tasks:
log_error(f"No image files found in '{input_folder}'")
return
with create_temp_folder() as temp_folder:
try:
run_with_thread_pool(tasks, process_file, time.time(), len(tasks), image_processor, temp_folder, True)
finally:
pass
--- Processing ---
def process_file(path: Path, start_time, total_files, image_processor: 'ImageProcessor', temp_folder: Path, resize=False, auto_correct_and_resize=False) -> None:
"""Process a single image file."""
if shared_state.stop_event.is_set():
return
def process_folder(folder: Path, image_processor: 'ImageProcessor', auto_correct_and_resize=False) -> None:
"""Process all images in a folder."""
image_processor.reset_results()
if auto_correct_and_resize:
try:
check_imagemagick()
except FileNotFoundError as e:
log_error(str(e))
return
tasks = [path for path in folder.rglob('*')
if path.is_file() and path.suffix.lower() in Config.IMAGE_EXTENSIONS]
if not tasks:
log_error(f"No image files found in '{folder}'")
return
with create_temp_folder() as temp_folder:
try:
run_with_thread_pool(tasks, process_file, time.time(), len(tasks), image_processor, temp_folder, False, auto_correct_and_resize)
finally:
pass
--- Logging ---
def log_errors(error_queue):
"""Log errors from the error queue."""
error_dict = defaultdict(list)
while not error_queue.empty():
file_path, error_messages = error_queue.get()
error_dict[file_path].extend(error_messages)
if error_dict:
shared_state.log_message_queue.put("UPDATE_LOG")
for file_path in sorted(error_dict.keys()):
shared_state.log_message_queue.put(f"{file_path.resolve()}")
shared_state.log_message_queue.put("")
for error_message in sorted(error_dict[file_path]):
log_error(error_message)
shared_state.log_message_queue.put("")
def log_and_execute(choice: str, label: str, function: callable, *args):
"""Log the execution of a function and run it in a separate thread."""
def run_in_thread():
start_time = time.time()
separator = '-' * Config.SEPARATOR_LENGTH
shared_state.log_message_queue.put(f"{separator}\n{label}\n{separator}\n")
if name == "main":
shared_state = Config.initialize()
image_processor = ImageProcessor()
app = App()
app.mainloop()
Code Analysis: Image Processing Application with Tkinter GUI
The provided Python script implements a comprehensive image processing application with a graphical user interface (GUI) built using Tkinter. The application is designed to perform various operations on image files, including resizing, analyzing for color properties, detecting corrupted files, and automatic color correction. The application leverages multithreading to enhance performance and ensure a responsive user experience. Below is a detailed analysis of the code structure, functionalities, and key components.
1. Imports and Dependencies
Standard Libraries:
ctypes: Used for setting DPI awareness on Windows.
logging, os, shutil, subprocess, threading, time: Fundamental operations for file handling, process management, threading, and logging.
tkinter, ttk, filedialog: Building the GUI.
collections, concurrent.futures, contextlib, pathlib, queue, typing, dataclasses: Data management, threading, and type hinting.
Third-Party Libraries:
tempfile: Managing temporary directories.
numpy: Efficient numerical operations, primarily for image analysis.
PIL (Pillow): Image processing tasks.
2. Configuration Management
SharedState Dataclass:
Manages shared resources across threads, ensuring thread safety with locks and events.
Tracks counts of processed files, total files, and holds messages for various tabs in the GUI.
Config Class:
Centralizes configuration settings such as folder paths, executable paths for ImageMagick and FFmpeg, supported file extensions, display constants, default resize options, and color detection thresholds.
setup Method: Creates the output directory and configures logging settings.
initialize Method: Initializes configurations and returns an instance of SharedState.
3. Utility Functions
Logging and Console Management:
log_error: Queues error messages for the GUI to display.
clear_console: Clears the terminal screen, platform-independent.
File Handling:
count_image_files: Recursively counts image files in a given directory.
is_valid_image: Validates whether a file is a readable image.
open_and_convert_image: Opens an image and converts it to an appropriate mode based on its current mode.
Image Conversion:
convert_png_to_jpg: Converts PNG images to JPG format with specific quality and compression settings.
Executable Checks:
check_executable, check_imagemagick, check_ffmpeg: Ensure that required external tools (ImageMagick and FFmpeg) are available in the system.
4. Color Detection
is_color_image Function:
Determines if an image is color based on the differences across RGB channels.
Uses NumPy to calculate peak-to-peak differences and evaluates the fraction of pixels exceeding a specified threshold.
5. Multithreading and Progress Tracking
Progress and Status Updates:
update_status: Updates the GUI with current processing status, including start time, processed files count, and elapsed time.
update_elapsed_time: Continuously updates elapsed time in a separate thread until processing stops.
Thread Pool Execution:
run_with_thread_pool: Manages the execution of tasks using a thread pool, updates progress bars, and handles errors gracefully.
Ensures that threads can be stopped mid-processing through events.
6. Image Processing Functions
Grayscale Processing:
process_grayscale_image: Adjusts grayscale values and saves the processed image, also categorizing images based on their modal black and white values.
Color Image Processing:
process_color_image: Determines if an image is color or grayscale and processes it accordingly, updating respective results.
Value Adjustment:
adjust_values: Adjusts grayscale values based on modal black and white values, including scaling and gamma correction to enhance image contrast.
Image Analysis:
analyze_images, analyze_file: Scans the input directory, analyzes each image for color properties, and updates processing results.
Color Image Identification and Moving:
find_color_images, move_color_image_file: Identifies color images and moves them to the output directory, updating processing status.
Corrupted File Detection:
check_for_corrupted_files, check_file: Uses FFmpeg to verify the integrity of media files, logging any errors found.
Image Resizing:
resize_image: Utilizes ImageMagick to resize images based on user-selected options, handling upscaling with specific filters.
resize_images, process_file, process_folder: Manage the resizing workflow, including reading images, applying corrections, and saving resized images.
7. Logging Mechanism
log_errors Function:
Aggregates errors from a queue and organizes them per file, preparing them for display in the GUI.
log_and_execute Function:
Logs the initiation of a processing task and executes it in a separate thread to prevent GUI freezing.
Handles task completion, logs results, and updates the GUI with final statuses.
8. ImageProcessor Class
Purpose:
Manages and records results from image processing operations, categorizing them into black, white, and color results.
Methods:
write_results_to_files: Writes categorized results to respective files based on the user's choice.
_write_results: Helper function to format and write specific result categories.
reset_results: Clears all recorded results to prepare for a new processing session.
9. App Class (Tkinter GUI)
Initialization and Setup:
__init__: Sets up the main window, variables, widgets, and logging threads.
setup_window: Configures window properties such as title, size, and DPI awareness.
set_dpi_awareness: Ensures the application displays correctly on high-DPI screens (Windows-specific).
Widget Creation:
Folder Selection:
Allows users to select input and output folders or revert to default paths.
Resize Options:
Provides options for selecting image formats (PNG/JPG), resize modes ("Shortest Side" or "Fit"), dimensions, and aspect ratio maintenance.
Processing Options:
Presents various processing actions via radio buttons (e.g., check corrupted files, analyze images, resize images).
Includes "Start" and "Stop" buttons to control processing.
Text Display Areas:
Utilizes a notebook with tabs ("Log", "Black", "White", "Color") to display processing logs and results.
Progress Bar and Status Label:
Visually represents processing progress and displays current status messages.
Functionality:
Folder Path Management:
set_default_folder, set_default_input, set_default_output: Handle resetting folder paths to defaults.
select_folder, select_input_folder, select_output_folder: Facilitate user selection of folders via dialog boxes.
Processing Control:
start_processing: Initiates the selected processing task, disables the "Start" button, and enables the "Stop" button.
stop_processing: Signals processing threads to stop, disables the "Stop" button, and re-enables the "Start" button.
Resize Options Dynamic Display:
: Dynamically shows or hides resize option widgets based on the selected resize mode.
10. Main Execution Block
if __name__ == "__main__":
Initializes shared state and the image processor.
Instantiates and runs the Tkinter application loop.
11. Overall Workflow
Initialization:
The application initializes configuration settings and shared state.
The GUI is set up with options for folder selection, processing actions, and resize configurations.
User Interaction:
Users select input/output folders and choose desired processing actions and options.
Upon clicking "Start", the application begins processing in a separate thread to maintain GUI responsiveness.
Processing Tasks:
Depending on the user's choice, tasks such as resizing images, analyzing for color properties, or checking for corrupted files are executed.
Multithreading is utilized to handle multiple files concurrently, improving processing speed.
Monitoring and Logging:
Progress bars and status labels provide real-time feedback on processing.
Logs and results are displayed across different tabs in the GUI, organized for easy review.
Completion:
Once processing is complete or stopped by the user, the GUI updates to reflect the final status.
Results are written to output directories and summary files as configured.
12. Potential Considerations and Observations
Error Handling:
The application robustly handles errors by logging them to the GUI without interrupting the processing flow.
External dependencies (ImageMagick and FFmpeg) are checked before performing operations, ensuring necessary tools are available.
Thread Safety:
Shared resources are protected using locks and events to prevent data races and ensure consistent state across threads.
Performance:
Utilizing ThreadPoolExecutor allows for efficient concurrent processing of multiple files.
Temporary directories are managed effectively to handle intermediate processing results.
User Experience:
The GUI is designed to be intuitive, allowing users to easily select options and monitor progress.
Dynamic widget updates based on user selections enhance usability.
Extensibility:
The modular design, with clear separation of configuration, utilities, processing functions, and GUI components, facilitates future extensions or modifications.
Additional processing tasks or functionalities can be integrated with minimal disruption to existing code.
Cross-Platform Considerations:
While the GUI and some functionalities are generally cross-platform, certain aspects like DPI awareness are specific to Windows, which might require conditional handling for full cross-platform compatibility.
Resource Management:
Temporary directories are properly cleaned up after processing to prevent clutter.
External resources like images are safely moved or deleted as per processing outcomes.
Code Maintainability:
The use of dataclasses and structured classes improves readability and maintainability.
Comprehensive inline documentation (docstrings) assists in understanding the purpose of functions and classes.
13. Suggestions for Improvement (Optional)
Note: Since the user requested an analysis without modifications, these suggestions are for informational purposes only.
Asynchronous Logging:
Implementing more advanced logging mechanisms (e.g., using logging.Handler) could provide more flexibility and control over log management.
Configuration File:
Externalizing configuration settings to a file (e.g., YAML or JSON) could enhance flexibility and ease of updates without modifying code.
Progress Reporting:
Incorporating more granular progress indicators, such as per-file progress or estimated time remaining, could provide users with more detailed feedback.
Error Display Enhancements:
Providing categorized error views or the ability to export logs for external review could improve troubleshooting.
Testing:
Implementing unit tests and integration tests would ensure reliability and facilitate future development.
Conclusion
The provided Python script is a well-structured and feature-rich image processing application that leverages multithreading and a graphical user interface to deliver efficient and user-friendly functionality. It effectively manages various image operations, maintains responsiveness through threading, and provides comprehensive logging and feedback mechanisms to users. The modular design and thorough documentation make it both maintainable and extensible for future enhancements.
reset_resize_options: Resets resize options to their default values.
Logging Integration:
setup_logging, update_text_area_from_queue, process_log_message, update_tab_messages: Continuously read log messages from a queue and update the GUI accordingly.
Status Updates:
update_final_status, reset_gui: Handle the final status display after processing completes or is stopped.