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 pathlib import Path
from queue import Queue
from tkinter import filedialog, ttk
from typing import Dict, List, Tuple, Set
from dataclasses import dataclass, field
import numpy as np
from PIL import Image, ImageOps
# --- Configuration ---
class Config:
"""Configuration for the image processing application."""
SCRIPT_DIR = Path(__file__).parent.resolve()
INPUT_FOLDER = Path(os.getenv('INPUT_FOLDER', SCRIPT_DIR / '1. Input'))
OUTPUT_FOLDER = Path(os.getenv('OUTPUT_FOLDER', SCRIPT_DIR / '2. Output'))
IMAGEMAGICK = Path(os.getenv('IMAGEMAGICK', 'D:/Bilder/Python/0. Code/Requirements/ImageMagick.exe'))
FFMPEG = Path(os.getenv('FFMPEG', 'D:/Bilder/Python/0. Code/Requirements/ffmpeg.exe'))
AUDIO_EXTENSIONS: Set[str] = {'.mka', '.mpga', '.mp3', '.aac', '.flac', '.opus'}
IMAGE_EXTENSIONS: Set[str] = {'.png', '.jpg', '.jpeg', '.webp'}
VIDEO_EXTENSIONS: Set[str] = {'.mkv', '.mp4'}
SEPARATOR_LENGTH = 310
PADDING_LENGTH = 82
PROGRESS_BAR_LENGTH = 100
DEFAULT_RESIZE_MODE = "Shortest Side"
DEFAULT_RESIZE_WIDTH = 0
DEFAULT_RESIZE_HEIGHT = 0
DEFAULT_RESIZE_SIDE = 1600
DEFAULT_RESIZE_FORMAT = "png"
COLORDIFF_THRESHOLD = 5
FRACTION_COLORED_PIXELS_THRESHOLD = 0.03
@classmethod
def setup(cls):
"""Set up output folder and configure logging."""
cls.OUTPUT_FOLDER.mkdir(parents=True, exist_ok=True)
logging.getLogger("PIL").setLevel(logging.WARNING)
@classmethod
def initialize(cls):
"""Initialize configuration and return shared state."""
cls.setup()
return SharedState()
@dataclass
class SharedState:
"""Shared state across threads."""
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)
# --- Utility Functions ---
def log_error(message: str):
"""Log an error message to the shared state queue."""
shared_state.log_message_queue.put(f"- {message}")
def clear_console():
"""Clear the console screen."""
os.system('cls' if os.name == 'nt' else 'clear')
def count_image_files(folder: Path) -> int:
"""Count image files in a folder and subfolders."""
return sum(1 for path in folder.rglob('*') if path.is_file() and path.suffix.lower() in Config.IMAGE_EXTENSIONS)
def is_valid_image(path: Path) -> bool:
"""Check if the path is a valid image."""
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 and convert image to appropriate mode."""
with Image.open(path) as img:
return (img.convert('L') if img.mode == 'P' else img.copy()) if img.mode in ['P', 'L', 'RGB', 'RGBA'] else img.convert('RGB')
def create_temp_folder() -> Path:
"""Create a temporary processing folder."""
temp_dir = Config.OUTPUT_FOLDER / f"temp_{int(time.time())}"
temp_dir.mkdir(parents=True, exist_ok=True)
return temp_dir
def cleanup_temp_folder(temp_folder: Path):
"""Remove the temporary processing folder."""
shutil.rmtree(temp_folder, ignore_errors=True)
def check_executable(executable: Path, name: str):
"""Check if an executable exists."""
if not shutil.which(str(executable)):
raise FileNotFoundError(f"- {name} executable not found at: {executable}")
def check_imagemagick():
"""Ensure ImageMagick is available."""
check_executable(Config.IMAGEMAGICK, "ImageMagick")
def check_ffmpeg():
"""Ensure FFmpeg is available."""
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 image is color based on RGB differences."""
if img.ndim != 3 or img.shape[2] != 3:
return False
diff = np.max(np.abs(img.astype(np.int16)[:, :, :3] - img.astype(np.int16)[:, :, 1:]), axis=2)
return np.mean(diff > diff_threshold) >= fraction_threshold
# --- Process Bar and Multithreading ---
def update_status(start_time: float, processed_count: int, total_files: int):
"""Update processing status."""
elapsed = time.time() - start_time
elapsed_str = f"{int(elapsed // 60):02d}:{int(elapsed % 60):02d}"
start_str = time.strftime('%H:%M:%S', time.localtime(start_time))
status = f"Start Time: {start_str} - Processed Files: {processed_count}/{total_files} - Elapsed Time: {elapsed_str} Minutes"
app.update_status_text(status.ljust(Config.PADDING_LENGTH))
def update_elapsed_time(start_time: float, total_files: int, stop_event: threading.Event):
"""Continuously update elapsed time."""
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 thread to update elapsed time."""
thread = threading.Thread(target=update_elapsed_time, args=(start_time, total_files, stop_event))
thread.start()
return thread
def run_with_thread_pool(tasks: List[Path], process_func, *args):
"""Run tasks using ThreadPoolExecutor."""
shared_state.processed_files_count = 0
shared_state.total_files_count = len(tasks)
start_time = time.time()
app.update_progress(0)
stop_event = threading.Event()
elapsed_thread = start_elapsed_time_thread(start_time, len(tasks), stop_event)
try:
with ThreadPoolExecutor() as executor:
futures = [executor.submit(process_func, task, *args) for task in tasks]
for i, future in enumerate(futures):
if shared_state.stop_event.is_set():
break
try:
future.result()
except Exception as e:
log_error(f"Error during processing: {e}")
finally:
progress = ((i + 1) / len(tasks)) * 100
app.update_progress(progress)
finally:
stop_event.set()
elapsed_thread.join()
return len(tasks)
# --- Image Processing Functions ---
def adjust_values(img: np.ndarray) -> Tuple[np.ndarray, int, int]:
"""Adjust grayscale image values."""
try:
modal_white = int(np.histogram(img[img >= 250], bins=6, range=(250, 256))[1][np.argmax(np.histogram(img[img >= 250], bins=6, range=(250, 256))[0])])
modal_black = int(np.histogram(img[img < 61], bins=61, range=(0, 61))[1][np.argmax(np.histogram(img[img < 61], bins=61, range=(0, 61))[0])])
if modal_white != 255:
img = np.clip(img.astype(np.float64) * (255.0 / modal_white), 0, 255).astype(np.uint8)
if modal_black:
adjusted = np.clip((img - modal_black) * (255.0 / (255 - modal_black)), 0, 255)
gamma = 1.0 - (modal_black / 255.0)
adjusted = np.power(adjusted / 255.0, gamma) * 255
adjusted[img == 0] = 0
adjusted[img == 255] = 255
adjusted = adjusted.astype(np.uint8)
else:
adjusted = img
return adjusted, modal_black, modal_white
except ValueError as e:
log_error(f"Error adjusting values for image: {e}")
return img, 0, 255
def process_grayscale_image(img: np.ndarray, path: Path, image_processor: 'ImageProcessor', temp_folder: Path) -> Tuple[Path, int, int]:
"""Process and save a grayscale image."""
try:
adjusted, modal_black, modal_white = adjust_values(img)
out_path = temp_folder / path.parent.relative_to(Config.INPUT_FOLDER) / f"{path.stem}.png"
out_path.parent.mkdir(parents=True, exist_ok=True)
Image.fromarray(adjusted).convert('L').save(out_path, format='PNG', compress_level=5)
subfolder = str(path.parent.relative_to(Config.INPUT_FOLDER))
filename = path.name
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))
return out_path, modal_black, modal_white
except (ValueError, OSError) as e:
log_error(f"Error processing grayscale image {path}: {e}")
return path, 0, 255
def process_color_image(img: np.ndarray, path: Path, image_processor: 'ImageProcessor', temp_folder: Path) -> Tuple[Path, bool]:
"""Process and save a color image."""
try:
if is_color_image(img):
out_path = temp_folder / path.relative_to(Config.INPUT_FOLDER).with_suffix('.png')
out_path.parent.mkdir(parents=True, exist_ok=True)
Image.fromarray(img).save(out_path, format='PNG', compress_level=5)
subfolder = str(path.parent.relative_to(Config.INPUT_FOLDER))
image_processor.color_results[subfolder].append(path.name)
return out_path, False
else:
gray = ImageOps.grayscale(Image.fromarray(img))
out_path, modal_black, modal_white = process_grayscale_image(np.array(gray), path, image_processor, temp_folder)
return out_path, modal_black != 0
except (OSError, ValueError) as e:
log_error(f"Error processing color image {path}: {e}")
return path, False
def analyze_images(image_processor: 'ImageProcessor'):
"""Analyze images for color properties."""
image_processor.reset_results()
tasks = [path for path in Config.INPUT_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 '{Config.INPUT_FOLDER}'")
return
def process_task(path: Path):
analyze_file(path, image_processor)
with shared_state.processed_files_lock:
shared_state.processed_files_count += 1
run_with_thread_pool(tasks, process_task)
def analyze_file(path: Path, image_processor: 'ImageProcessor'):
"""Analyze a single image file."""
if not is_valid_image(path):
return
try:
img = np.array(open_and_convert_image(path))
if img.ndim <= 2 or (img.ndim == 3 and img.shape[2] == 1):
adjusted, modal_black, modal_white = adjust_values(img)
subfolder = str(path.parent.relative_to(Config.INPUT_FOLDER))
filename = path.name
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))
else:
if is_color_image(img):
subfolder = str(path.parent.relative_to(Config.INPUT_FOLDER))
image_processor.color_results[subfolder].append(path.name)
else:
adjusted, modal_black, modal_white = adjust_values(img)
subfolder = str(path.parent.relative_to(Config.INPUT_FOLDER))
filename = path.name
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}")
def find_color_images(image_processor: 'ImageProcessor'):
"""Find and move color images to the output folder."""
image_processor.reset_results()
tasks = [path for path in Config.INPUT_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 '{Config.INPUT_FOLDER}'")
return
def move_task(path: Path):
if not is_valid_image(path):
return
try:
img = np.array(open_and_convert_image(path))
if is_color_image(img):
rel_path = path.relative_to(Config.INPUT_FOLDER)
out_path = Config.OUTPUT_FOLDER / rel_path
out_path.parent.mkdir(parents=True, exist_ok=True)
shutil.move(str(path), str(out_path))
image_processor.color_results[str(rel_path.parent)].append(rel_path.name)
except (OSError, ValueError) as e:
log_error(f"Error moving image {path}: {e}")
with shared_state.processed_files_lock:
shared_state.processed_files_count += 1
run_with_thread_pool(tasks, move_task)
# --- Corrupted Files ---
def check_file_for_corruption(file_path: Path, error_queue: Queue):
"""Check if a file is corrupted using FFmpeg."""
try:
ext = file_path.suffix.lower()
if ext not in Config.VIDEO_EXTENSIONS | Config.AUDIO_EXTENSIONS | Config.IMAGE_EXTENSIONS:
return
base_command = [str(Config.FFMPEG), '-v', 'error', '-i', str(file_path)]
command = base_command + (['-map', '0:a:0', '-f', 'null', '-'] if ext in Config.VIDEO_EXTENSIONS else ['-f', 'null', '-'])
process = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
errors = [line for line in process.stderr.split('\n') if 'error' in line.lower()]
if errors:
error_queue.put((file_path.resolve(), errors))
except Exception as e:
error_queue.put((file_path.resolve(), [f"Error processing file {file_path}: {e}"]))
def check_for_corrupted_files():
"""Check for corrupted media files."""
image_processor.reset_results()
try:
check_ffmpeg()
except FileNotFoundError as e:
log_error(str(e))
return
tasks = [file for file in Config.INPUT_FOLDER.rglob('*') if file.is_file() and file.suffix.lower() in
Config.VIDEO_EXTENSIONS | Config.AUDIO_EXTENSIONS | Config.IMAGE_EXTENSIONS]
if not tasks:
log_error(f"No valid media files found in '{Config.INPUT_FOLDER}'")
return
error_queue = Queue()
def process_task(file_path: Path):
check_file_for_corruption(file_path, error_queue)
with shared_state.processed_files_lock:
shared_state.processed_files_count += 1
run_with_thread_pool(tasks, process_task)
log_errors(error_queue)
def log_errors(error_queue: Queue):
"""Log errors from the error queue."""
errors = defaultdict(list)
while not error_queue.empty():
path, msgs = error_queue.get()
errors[path].extend(msgs)
if errors:
shared_state.log_message_queue.put("UPDATE_LOG")
for path, msgs in sorted(errors.items()):
shared_state.log_message_queue.put(f"{path}\n" + "\n".join(f" - {msg.strip()}" for msg in sorted(msgs)) + "\n")
# --- Image Conversion and Resizing ---
def convert_png_to_jpg(input_path: Path, output_path: Path):
"""Convert PNG image to JPG."""
try:
with Image.open(input_path) as img:
img = img.convert('RGB') if img.mode not in ('RGB', 'L') else img
jpg_path = output_path.with_suffix('.jpg')
img.save(jpg_path, 'JPEG', quality=80, subsampling=0)
input_path.unlink()
except Exception as e:
log_error(f"Error converting {input_path} to JPG: {e}")
def resize_image(input_path: Path, output_path: Path) -> Path:
"""Resize image using ImageMagick."""
output_path = output_path.with_suffix('.png')
try:
result = subprocess.run([
str(Config.IMAGEMAGICK), str(input_path), '-format', '%wx%h', 'info:'
], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True)
current_width, current_height = map(int, result.stdout.strip().split('x'))
mode = app.RESIZE_MODE.get()
if mode == "Fit":
width = int(app.RESIZE_WIDTH.get()) if app.RESIZE_WIDTH.get() else 0
height = int(app.RESIZE_HEIGHT.get()) if app.RESIZE_HEIGHT.get() else 0
if app.maintain_aspect_ratio.get():
if width == 0:
width = int(height * (current_width / current_height))
elif height == 0:
height = int(width * (current_height / current_width))
resize_arg = f'{width}x{height}!' if mode == "Fit" else f'{int(app.RESIZE_SIDE.get())}x{int(app.RESIZE_SIDE.get())}^'
else:
target_size = int(app.RESIZE_SIDE.get())
resize_arg = f'{target_size}x{target_size}^'
is_upscaling = (
(mode == "Fit" and (width > current_width or height > current_height)) or
(mode == "Shortest Side" and target_size > min(current_width, current_height))
)
command = [
str(Config.IMAGEMAGICK), str(input_path),
'-filter', 'LanczosSharp' if is_upscaling else 'Lanczos2Sharp',
'-distort' if is_upscaling else '-resize', resize_arg,
'-colorspace', 'sRGB' if not is_upscaling else '',
'-define', 'png:compression-level=5',
str(output_path)
]
subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True)
except subprocess.CalledProcessError as e:
log_error(f"ImageMagick error: {e.stderr.strip()}")
return output_path
# --- Processing ---
def resize_images(input_folder: Path, output_folder: Path, image_processor: 'ImageProcessor'):
"""Resize images in the input folder."""
try:
check_imagemagick()
except FileNotFoundError as e:
log_error(str(e))
return
tasks = [path for path in input_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 '{input_folder}'")
return
temp_folder = create_temp_folder()
try:
run_with_thread_pool(tasks, process_file, image_processor, temp_folder, True)
finally:
cleanup_temp_folder(temp_folder)
def process_file(path: Path, image_processor: 'ImageProcessor', temp_folder: Path, resize: bool = False, auto_correct_and_resize: bool = False):
"""Process a single image file."""
if shared_state.stop_event.is_set():
return
if not is_valid_image(path):
log_error(f"Invalid image file: {path}")
with shared_state.processed_files_lock:
shared_state.processed_files_count += 1
update_status(app.process_start_time, shared_state.processed_files_count, shared_state.total_files_count)
return
try:
img = np.array(open_and_convert_image(path))
except (OSError, ValueError) as e:
log_error(f"Error reading image {path}: {e}")
with shared_state.processed_files_lock:
shared_state.processed_files_count += 1
update_status(app.process_start_time, shared_state.processed_files_count, shared_state.total_files_count)
return
relative_path = path.relative_to(Config.INPUT_FOLDER)
temp_output_path = temp_folder / relative_path.with_suffix('.png')
temp_output_path.parent.mkdir(parents=True, exist_ok=True)
if auto_correct_and_resize:
if img.ndim <= 2 or (img.ndim == 3 and img.shape[2] == 1):
intermediate_path, _, _ = process_grayscale_image(img, path, image_processor, temp_folder)
else:
intermediate_path, _ = process_color_image(img, path, image_processor, temp_folder)
temp_output_path = resize_image(intermediate_path, temp_output_path)
elif resize:
temp_output_path = resize_image(path, temp_output_path)
else:
if img.ndim <= 2 or (img.ndim == 3 and img.shape[2] == 1):
temp_output_path, _, _ = process_grayscale_image(img, path, image_processor, temp_folder)
else:
temp_output_path, _ = process_color_image(img, path, image_processor, temp_folder)
final_output_path = Config.OUTPUT_FOLDER / relative_path
final_output_path.parent.mkdir(parents=True, exist_ok=True)
if app.RESIZE_FORMAT.get() == 'jpg':
convert_png_to_jpg(temp_output_path, final_output_path)
else:
final_output_path = final_output_path.with_suffix('.png')
shutil.move(str(temp_output_path), str(final_output_path))
with shared_state.processed_files_lock:
shared_state.processed_files_count += 1
update_status(app.process_start_time, shared_state.processed_files_count, shared_state.total_files_count)
def process_folder(folder: Path, image_processor: 'ImageProcessor', auto_correct_and_resize: bool = False):
"""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
temp_folder = create_temp_folder()
try:
run_with_thread_pool(tasks, process_file, image_processor, temp_folder, False, auto_correct_and_resize)
finally:
cleanup_temp_folder(temp_folder)
# --- Logging ---
def log_and_execute(choice: str, label: str, function: callable, *args):
"""Log and execute a function in a separate thread."""
def run():
start_time = time.time()
shared_state.log_message_queue.put(f"{'-' * Config.SEPARATOR_LENGTH}\n{label}\n{'-' * Config.SEPARATOR_LENGTH}\n")
try:
function(*args)
except FileNotFoundError as e:
log_error(str(e))
except (OSError, ValueError) as e:
log_error(f"An error occurred during '{label}': {e}")
image_processor.write_results_to_files(Config.OUTPUT_FOLDER, choice)
execution_time = time.time() - start_time
app.after(0, app.update_final_status, execution_time)
threading.Thread(target=run).start()
# --- ImageProcessor Class ---
class ImageProcessor:
"""Handles image processing results."""
def __init__(self):
self.white_results = defaultdict(list)
self.black_results = defaultdict(list)
self.color_results = defaultdict(list)
def write_results_to_files(self, output_folder: Path, choice: str):
"""Write processing results based on choice."""
headers = {
'2': ("2. Analyze Images", "Modal Value Black", "Modal Value White"),
'3': ("3. Find Color Images", "Filename"),
'5': ("5. Automatic Color Correction", "Modal Value Black", "Modal Value White"),
'6': ("6. Automatic Color Correction + Resize", "Modal Value Black", "Modal Value White")
}
header = headers.get(choice)
if not header:
return
if choice == '3':
self._write_results("Color", self.color_results, header[0], header[1])
else:
self._write_results("Black", self.black_results, header[0], header[1])
self._write_results("White", self.white_results, header[0], header[2])
self._write_results("Color", self.color_results, header[0], "Filename")
def _write_results(self, key: str, results: Dict[str, List], header: str, value_name: str):
"""Write specific results to the tab messages."""
separator = '-' * Config.SEPARATOR_LENGTH
content = f"{separator}\n{header}\n{separator}\n"
for subfolder, items in sorted(results.items()):
content += f"\n{Config.INPUT_FOLDER / subfolder}\n\n"
if value_name == "Filename":
items.sort()
content += '\n'.join(f" - {item}" for item in items) + "\n"
else:
items.sort(key=lambda x: x[1], reverse=True)
content += '\n'.join(f" - {filename}, {value_name}: {value}" for filename, value in items) + "\n"
shared_state.tab_messages[key].append(content)
def reset_results(self):
"""Reset all processing results."""
self.white_results.clear()
self.black_results.clear()
self.color_results.clear()
# --- Tkinter App ---
class App(tk.Tk):
"""Tkinter application for image processing."""
def __init__(self):
super().__init__()
self.setup_window()
self.create_variables()
self.create_widgets()
self.setup_logging()
def setup_window(self):
"""Configure the main window."""
self.set_dpi_awareness()
self.title("Image Processor")
self.geometry("2100x1180")
self.default_font = ("Roboto Flex", 16)
self.apply_default_font()
def set_dpi_awareness(self):
"""Set DPI awareness for better scaling."""
try:
ctypes.windll.shcore.SetProcessDpiAwareness(1)
except Exception as e:
print(f"Could not set DPI awareness: {e}")
def apply_default_font(self):
"""Apply default font to all widgets."""
self.option_add("*Font", self.default_font)
style = ttk.Style()
for widget in ["TButton", "TLabel", "TEntry", "TRadiobutton", "TNotebook.Tab"]:
style.configure(widget, font=self.default_font)
style.configure("TFrame", background="#fdfdfd")
style.configure("TLabel", background="#fdfdfd")
style.configure("TNotebook", background="#f8f8f8")
style.configure("TRadiobutton", background="#fdfdfd")
def create_variables(self):
"""Initialize Tkinter variables."""
self.RESIZE_MODE = tk.StringVar(value=Config.DEFAULT_RESIZE_MODE)
self.RESIZE_WIDTH = tk.StringVar(value=str(Config.DEFAULT_RESIZE_WIDTH))
self.RESIZE_HEIGHT = tk.StringVar(value=str(Config.DEFAULT_RESIZE_HEIGHT))
self.RESIZE_SIDE = tk.StringVar(value=str(Config.DEFAULT_RESIZE_SIDE))
self.RESIZE_FORMAT = tk.StringVar(value=Config.DEFAULT_RESIZE_FORMAT)
self.option_var = tk.StringVar(value="4")
self.status_text = tk.StringVar(value="")
def create_widgets(self):
"""Create all widgets."""
main_frame = ttk.Frame(self, padding="20")
main_frame.pack(fill=tk.BOTH, expand=True)
self.create_folder_selection(main_frame)
self.create_resize_options(main_frame)
self.create_processing_options(main_frame)
self.create_text_areas(main_frame)
self.create_progress_bar(main_frame)
self.create_status_label(main_frame)
def create_folder_selection(self, parent):
"""Create input and output folder selection."""
for label, default_path, command in [
("Input", Config.INPUT_FOLDER, self.select_input_folder),
("Output", Config.OUTPUT_FOLDER, self.select_output_folder)
]:
frame = ttk.Frame(parent)
frame.pack(fill=tk.X, pady=(0, 10))
ttk.Button(frame, text="Default", command=lambda l=label: self.set_default_folder(l)).pack(side=tk.LEFT, padx=(0, 10))
entry = ttk.Entry(frame)
entry.insert(0, str(default_path))
entry.pack(side=tk.LEFT, expand=True, fill=tk.X)
ttk.Button(frame, text=f"Select {label} Folder", command=lambda l=label, e=entry: self.select_folder(e, l)).pack(side=tk.LEFT, padx=(10, 0))
setattr(self, f"{label.lower()}_entry", entry)
def set_default_folder(self, label: str):
"""Set default folder path."""
folder_attr = 'INPUT_FOLDER' if label == "Input" else 'OUTPUT_FOLDER'
folder = Config.DEFAULT_INPUT_FOLDER if label == "Input" else Config.DEFAULT_OUTPUT_FOLDER
entry = getattr(self, f"{label.lower()}_entry")
entry.delete(0, tk.END)
entry.insert(0, str(folder))
setattr(Config, folder_attr, folder)
def select_folder(self, entry: ttk.Entry, label: str):
"""Open folder selection dialog."""
selected = filedialog.askdirectory()
if selected:
path = Path(selected).resolve()
entry.delete(0, tk.END)
entry.insert(0, str(path))
setattr(Config, f"{label.upper()}_FOLDER", path)
def create_resize_options(self, parent):
"""Create resize options frame."""
frame = ttk.Frame(parent)
frame.pack(fill=tk.X, pady=(0, 10))
ttk.Button(frame, text="Default", command=self.reset_resize_options, width=10).pack(side=tk.LEFT, padx=(0, 10))
ttk.Label(frame, text="Format:").pack(side=tk.LEFT, padx=(0, 5))
ttk.Combobox(frame, textvariable=self.RESIZE_FORMAT, values=["png", "jpg"], state="readonly", width=4).pack(side=tk.LEFT, padx=(0, 10))
ttk.Label(frame, text="Resize:").pack(side=tk.LEFT, padx=(0, 5))
mode_combo = ttk.Combobox(frame, textvariable=self.RESIZE_MODE, values=["Shortest Side", "Fit"], state="readonly", width=12)
mode_combo.pack(side=tk.LEFT, padx=(0, 10))
mode_combo.bind("<<ComboboxSelected>>", self.update_resize_options)
self.create_resize_entries(frame)
ttk.Button(frame, text="Start", command=self.start_processing, width=20).pack(side=tk.RIGHT, padx=(10, 0))
def create_resize_entries(self, frame):
"""Create resize input fields."""
self.width_label = ttk.Label(frame, text="Width:")
self.width_entry = ttk.Entry(frame, textvariable=self.RESIZE_WIDTH, width=5)
self.height_label = ttk.Label(frame, text="Height:")
self.height_entry = ttk.Entry(frame, textvariable=self.RESIZE_HEIGHT, width=5)
self.maintain_aspect_ratio = tk.BooleanVar(value=False)
self.aspect_ratio_cb = ttk.Checkbutton(frame, text="Maintain Aspect Ratio", variable=self.maintain_aspect_ratio)
self.side_label = ttk.Label(frame, text="Side:")
self.side_entry = ttk.Entry(frame, textvariable=self.RESIZE_SIDE, width=5)
self.update_resize_options()
def update_resize_options(self, event=None):
"""Toggle resize options based on mode."""
mode = self.RESIZE_MODE.get()
widgets = [
self.width_label, self.width_entry,
self.height_label, self.height_entry,
self.aspect_ratio_cb,
self.side_label, self.side_entry
]
for widget in widgets:
widget.pack_forget()
if mode == "Fit":
self.width_label.pack(side=tk.LEFT, padx=(10, 5))
self.width_entry.pack(side=tk.LEFT, padx=(0, 10))
self.height_label.pack(side=tk.LEFT, padx=(0, 5))
self.height_entry.pack(side=tk.LEFT, padx=(0, 10))
self.aspect_ratio_cb.pack(side=tk.LEFT, padx=(10, 0))
else:
self.side_label.pack(side=tk.LEFT, padx=(10, 5))
self.side_entry.pack(side=tk.LEFT, padx=(0, 10))
def reset_resize_options(self):
"""Reset resize options to default."""
self.RESIZE_MODE.set(Config.DEFAULT_RESIZE_MODE)
self.RESIZE_WIDTH.set(str(Config.DEFAULT_RESIZE_WIDTH))
self.RESIZE_HEIGHT.set(str(Config.DEFAULT_RESIZE_HEIGHT))
self.RESIZE_SIDE.set(str(Config.DEFAULT_RESIZE_SIDE))
self.RESIZE_FORMAT.set(Config.DEFAULT_RESIZE_FORMAT)
self.maintain_aspect_ratio.set(False)
self.update_resize_options()
def create_processing_options(self, parent):
"""Create processing options and start/stop buttons."""
frame = ttk.Frame(parent)
frame.pack(fill=tk.X, pady=(0, 10))
options = [
("Check For Corrupted Files", "4"),
("Analyze Images", "2"),
("Find Color Images", "3"),
("Resize Images", "1"),
("Automatic Color Correction", "5"),
("Automatic Color Correction + Resize", "6")
]
options_frame = ttk.Frame(frame)
options_frame.pack(side=tk.LEFT, fill=tk.X, expand=True)
for col, (text, value) in enumerate(options):
ttk.Radiobutton(options_frame, text=text, variable=self.option_var, value=value).grid(row=0, column=col, sticky="ew")
options_frame.columnconfigure(col, weight=1)
self.stop_button = ttk.Button(frame, text="Stop", command=self.stop_processing, width=20, state=tk.DISABLED)
self.stop_button.pack(side=tk.RIGHT, padx=(10, 0))
def create_text_areas(self, parent):
"""Create tabbed text areas for logs and results."""
frame = ttk.Frame(parent)
frame.pack(fill=tk.BOTH, expand=True)
self.notebook = ttk.Notebook(frame)
self.notebook.pack(fill=tk.BOTH, expand=True)
self.text_areas = {}
for tab in ["Log", "Black", "White", "Color"]:
tab_frame = ttk.Frame(self.notebook)
self.notebook.add(tab_frame, text=tab)
text_area = tk.Text(tab_frame, wrap=tk.NONE, bg="#ffffff", state='disabled',
padx=7, pady=7, fg="#000000", font=self.default_font)
scrollbar_y = ttk.Scrollbar(tab_frame, command=text_area.yview)
scrollbar_x = ttk.Scrollbar(tab_frame, command=text_area.xview, orient='horizontal')
scrollbar_y.pack(side=tk.RIGHT, fill=tk.Y)
text_area.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
scrollbar_x.pack(side=tk.BOTTOM, fill=tk.X)
text_area.config(yscrollcommand=scrollbar_y.set, xscrollcommand=scrollbar_x.set)
self.text_areas[tab] = text_area
def create_progress_bar(self, parent):
"""Create a progress bar."""
self.progress = ttk.Progressbar(parent, mode="determinate", maximum=Config.PROGRESS_BAR_LENGTH)
self.progress.pack(pady=(30, 0), padx=20, fill="x")
self.progress.config(value=0)
def create_status_label(self, parent):
"""Create a status label."""
ttk.Label(parent, textvariable=self.status_text).pack(pady=(10, 15))
def setup_logging(self):
"""Set up logging thread."""
threading.Thread(target=self.update_text_area_from_queue, daemon=True).start()
def update_status_text(self, text: str):
"""Update the status text."""
self.status_text.set(text)
self.update_idletasks()
def update_progress(self, value: float):
"""Update the progress bar."""
self.progress['value'] = min(value, Config.PROGRESS_BAR_LENGTH)
self.update_idletasks()
def update_text_area(self, tab: str = None, message: str = None):
"""Update text areas with messages."""
for tab_key, text_area in self.text_areas.items():
text_area.configure(state='normal')
text_area.delete("1.0", tk.END)
content = "\n".join(shared_state.tab_messages[tab_key])
text_area.insert(tk.END, content)
text_area.configure(state='disabled')
def start_processing(self):
"""Start the selected processing task."""
shared_state.stop_event.clear()
self.start_button.config(state=tk.DISABLED)
self.stop_button.config(state=tk.NORMAL)
self.process_start_time = time.time()
choice = self.option_var.get()
actions = {
"1": ("1. Resize Images", resize_images, Config.INPUT_FOLDER, Config.OUTPUT_FOLDER, image_processor),
"2": ("2. Analyze Images", analyze_images, image_processor),
"3": ("3. Find Color Images", find_color_images, image_processor),
"4": ("4. Check For Corrupted Files", check_for_corrupted_files),
"5": ("5. Automatic Color Correction", process_folder, Config.INPUT_FOLDER, image_processor),
"6": ("6. Automatic Color Correction + Resize", process_folder, Config.INPUT_FOLDER, image_processor, True),
}
label, func, *args = actions.get(choice, ("Unknown Action", lambda: None))
log_and_execute(choice, label, func, *args)
def stop_processing(self):
"""Stop the ongoing processing."""
shared_state.stop_event.set()
self.stop_button.config(state=tk.DISABLED)
self.start_button.config(state=tk.NORMAL)
def update_text_area_from_queue(self):
"""Update text areas from the log message queue."""
while True:
try:
item = shared_state.log_message_queue.get(timeout=0.1)
if item in {"UPDATE_LOG", "UPDATE_BLACK", "UPDATE_WHITE", "UPDATE_COLOR"}:
self.update_text_area()
else:
self.update_tab_messages(item)
except:
pass
def update_tab_messages(self, message: str):
"""Append messages to respective tabs."""
for key in ["Black", "White", "Color"]:
if key in message:
shared_state.tab_messages[key].append(message)
shared_state.tab_messages["Log"].append(message)
self.update_text_area()
def update_final_status(self, execution_time: float):
"""Update final status after processing."""
self.update_progress(100)
elapsed_minutes = int(execution_time // 60)
elapsed_seconds = int(execution_time % 60)
status = (
f"Start Time: {time.strftime('%H:%M:%S', time.localtime(self.process_start_time))} - "
f"Processed Files: {shared_state.processed_files_count}/{shared_state.total_files_count} - "
f"Elapsed Time: {elapsed_minutes:02d}:{elapsed_seconds:02d} Minutes"
)
if shared_state.stop_event.is_set():
status += " - Processing stopped by user"
self.update_status_text(status.ljust(Config.PADDING_LENGTH))
self.reset_gui()
def reset_gui(self):
"""Reset GUI elements after processing."""
self.start_button.config(state=tk.NORMAL)
self.stop_button.config(state=tk.DISABLED)
# --- Main Execution ---
if __name__ == "__main__":
shared_state = Config.initialize()
image_processor = ImageProcessor()
app = App()
app.mainloop()