Analyze the code for redundancies that can be solved. 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, Future
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, Iterable, Optional, Sequence, Union, Generator, cast
from dataclasses import dataclass, field
import tempfile
import numpy as np
from PIL import Image
--- 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[str] = 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() -> Generator[Path, None, None]:
"""Yield a temporary folder within the output directory."""
with tempfile.TemporaryDirectory(dir=Config.OUTPUT_FOLDER) as temp_dir:
yield Path(temp_dir)
--- Logging ---
def log_errors(error_queue: Queue[tuple[Path, list[str]]]) -> None:
"""Log errors from the error queue."""
error_dict: dict[Path, list[str]] = defaultdict(list)
while not error_queue.empty():
file_path, error_messages = error_queue.get()
error_dict[file_path].extend(error_messages)
code
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[..., Any], *args: Any) -> None:
"""Log the execution of a function and run it in a separate thread."""
def run_in_thread() -> None:
start_time = time.time()
separator = '-' * Config.SEPARATOR_LENGTH
shared_state.log_message_queue.put(f"{separator}\n{label}\n{separator}\n")
def log_error(message: str) -> None:
"""Log an error message to the shared state queue."""
shared_state.log_message_queue.put(f"- {message}")
def validate_and_load_image(path: Path) -> Optional[Image.Image]:
"""Validate and load image, return None if invalid."""
try:
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')
except (OSError, ValueError) as e:
log_error(f"Error reading image {path}: {e}")
return None
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')
code
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 increment_processed_count(start_time: float, total_files: int) -> None:
"""Safely increment the processed files count and update the status."""
with shared_state.processed_files_lock:
shared_state.processed_files_count += 1
update_status(start_time, shared_state.processed_files_count, total_files)
--- 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: Sequence[Path], process_func: Callable[..., Any], *args: Any) -> 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()
code
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
--- Color Detection And Adjustment ---
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
code
# 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
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)])
code
# 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
--- Image Analysis ---
def analyze_images(image_processor: 'ImageProcessor') -> None:
"""Analyze images in the input folder for color properties."""
image_processor.reset_results()
image_files: list[Path] = [
path for path in Config.INPUT_FOLDER.rglob('*')
if path.is_file() and path.suffix.lower() in Config.IMAGE_EXTENSIONS
]
code
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."""
img = validate_and_load_image(path)
if img is None:
return
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}
code
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."""
img = validate_and_load_image(path)
if img is None:
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()
code
try:
check_executable(Config.FFMPEG, "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:
increment_processed_count(start_time, total_files)
run_with_thread_pool(tasks, check_file)
log_errors(error_queue)
--- Resize Images ---
def resize_images(input_folder: Path, output_folder: Path, image_processor: 'ImageProcessor') -> None:
"""Resize images in the input folder and save them to the output folder."""
try:
check_executable(Config.IMAGEMAGICK, "ImageMagick")
except FileNotFoundError as e:
log_error(str(e))
return
code
tasks: list[Path] = [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:
run_with_thread_pool(tasks, process_file, time.time(), len(tasks), image_processor, temp_folder, True)
def resize_image(input_path: Path, output_path: Path) -> Path:
"""Resize an image using ImageMagick."""
output_path = output_path.with_suffix('.png')
code
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
img = validate_and_load_image(path)
if img is None:
log_error(f"Invalid image file: {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
try:
img_array = np.array(img)
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(start_time, shared_state.processed_files_count, total_files)
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:
# Adjust and save image, then resize
intermediate_path, _, _ = adjust_and_save_image(img_array, path, image_processor, temp_folder)
temp_output_path = resize_image(intermediate_path, temp_output_path)
elif resize:
# Only resize the original image
temp_output_path = resize_image(path, temp_output_path)
else:
# Adjust and save image without resizing
temp_output_path, _, _ = adjust_and_save_image(img_array, path, image_processor, temp_folder)
final_output_path = Config.OUTPUT_FOLDER / relative_path.with_suffix(
'.jpg' if app.RESIZE_FORMAT.get() == 'jpg' else '.png'
)
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:
shutil.move(str(temp_output_path), str(final_output_path))
increment_processed_count(start_time, total_files)
def process_folder(folder: Path, image_processor: 'ImageProcessor', auto_correct_and_resize: bool = False) -> None:
"""Process all images in a folder."""
image_processor.reset_results()
code
if auto_correct_and_resize:
try:
check_executable(Config.IMAGEMAGICK, "ImageMagick")
except FileNotFoundError as e:
log_error(str(e))
return
tasks: list[Path] = [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:
run_with_thread_pool(tasks, process_file, time.time(), len(tasks), image_processor, temp_folder, False, auto_correct_and_resize)
def adjust_and_save_image(
img: np.ndarray,
path: Path,
image_processor: 'ImageProcessor',
temp_folder: Path,
diff_threshold: int = Config.COLORDIFF_THRESHOLD,
fraction_threshold: float = Config.FRACTION_COLORED_PIXELS_THRESHOLD
) -> tuple[Path, Optional[int], Optional[int]]:
"""Process an image, adjusting and saving depending on whether it is color or grayscale."""
try:
is_color = is_color_image(img, diff_threshold, fraction_threshold)
relative_parent = path.parent.relative_to(Config.INPUT_FOLDER)
out_path = temp_folder / relative_parent / f"{path.stem}.png"
out_path.parent.mkdir(parents=True, exist_ok=True)
subfolder = relative_parent.as_posix()
filename = path.name
code
if is_color:
# Save color image as PNG
Image.fromarray(img).save(out_path, format='PNG', compress_level=5)
image_processor.color_results[subfolder].append(filename)
return out_path, None, None
else:
# Adjust grayscale values
adjusted_img, modal_black, modal_white = adjust_values(img)
Image.fromarray(adjusted_img).convert('L').save(out_path, format='PNG', compress_level=5)
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 (OSError, ValueError) as e:
log_error(f"Error processing image {path}: {e}")
return path, None, None
if name == "main":
shared_state = Config.initialize()
image_processor = ImageProcessor()
app = App()
app.mainloop()
Certainly! After analyzing your code, I've identified several redundancies, particularly in functions dealing with image loading, error handling, and updating shared state. Below, I'll highlight these redundancies and provide suggestions on how to refactor the code to eliminate them.
Repeated Code for Loading Images and Handling Errors
Redundant sections:
In multiple places, you have code that loads an image and converts it to a NumPy array, with error handling. For example:
python
# In analyze_file
img = validate_and_load_image(path)
if img is None:
return
try:
img_array = np.array(img)
# ... rest of the code
except (OSError, ValueError) as e:
log_error(f"Error processing image {path}: {e}")
python
# In move_color_image_file
img = validate_and_load_image(path)
if img is None:
with shared_state.processed_files_lock:
shared_state.processed_files_count += 1
update_status(start_time, shared_state.processed_files_count, total_files)
return
try:
img_array = np.array(img)
# ... rest of the code
except (OSError, ValueError) as e:
log_error(f"Error processing image {path}: {e}")
Solution:
Create a utility function that encapsulates this pattern.
python
def load_image_as_array(path: Path) -> Optional[np.ndarray]:
"""Load an image and convert it to a NumPy array with error handling."""
img = validate_and_load_image(path)
if img is None:
return None
try:
return np.array(img)
except (OSError, ValueError) as e:
log_error(f"Error converting image to array {path}: {e}")
return None
Now, you can replace the redundant code with a call to load_image_as_array.
python
# In analyze_file
img_array = load_image_as_array(path)
if img_array is None:
return
# ... rest of the code
This not only reduces redundancy but also centralizes error handling related to image loading and conversion.
Repeated Code for Incrementing Processed Files Count and Updating Status
Redundant sections:
In several places, you increment the processed_files_count and update the status:
python
with shared_state.processed_files_lock:
shared_state.processed_files_count += 1
update_status(start_time, shared_state.processed_files_count, total_files)
Solution:
Create a function that does both:
python
def increment_and_update_status(start_time: float, total_files: int) -> None:
"""Increment the processed files count and update the status."""
with shared_state.processed_files_lock:
shared_state.processed_files_count += 1
update_status(start_time, shared_state.processed_files_count, total_files)
Repeated Code for Getting Image Files from a Folder
Redundant sections:
You have similar code for listing image files in different functions:
python
image_files = [
path for path in Config.INPUT_FOLDER.rglob('*')
if path.is_file() and path.suffix.lower() in Config.IMAGE_EXTENSIONS
]
Solution:
Create a utility function:
python
def get_image_files(folder: Path, extensions: Set[str]) -> List[Path]:
"""Get a list of image files in a folder with the specified extensions."""
return [
path for path in folder.rglob('*')
if path.is_file() and path.suffix.lower() in extensions
]
Now, you can use this function wherever you need to get image files:
Functions like process_file, analyze_file, and move_color_image_file have similar structures:
They load an image.
Convert it to a NumPy array.
Perform some processing.
Handle exceptions.
Update the processed count.
Solution:
Consider creating a higher-order function or a decorator that can wrap these common steps. You can create a decorator that handles loading the image, converting it to an array, and error handling.
python
def image_processing_wrapper(func):
"""Decorator to handle image loading and error handling."""
def wrapper(path: Path, *args, **kwargs):
if shared_state.stop_event.is_set():
return
img_array = load_image_as_array(path)
if img_array is None:
increment_and_update_status(*args)
return
try:
func(img_array, path, *args, **kwargs)
except Exception as e:
log_error(f"Error processing image {path}: {e}")
finally:
increment_and_update_status(*args)
return wrapper
You can further consolidate the processing logic by parameterizing the actions within the process_file function. For example, use flags or an enumeration to specify what processing steps to perform (e.g., resize, adjust values, move).
Simplify GUI Update Mechanisms
In the App class, the method update_text_area_from_queue has code that processes different messages to update various tabs. You can simplify this by using a mapping or by standardizing the messages in the queue.
update_tabs = {"UPDATE_LOG": "Log", "UPDATE_BLACK": "Black", "UPDATE_WHITE": "White", "UPDATE_COLOR": "Color"}
if item in update_tabs:
self.after(0, self.update_text_area, update_tabs[item])
else:
# Handle other messages
By implementing these changes, you reduce code repetition, enhance readability, and improve maintainability. Each function now has a clear, single responsibility, and shared logic is centralized, making future updates or bug fixes easier to manage.
Here is how the refactored sections of your code might look:
python
# --- Utility Functions ---
def increment_and_update_status(start_time: float, total_files: int) -> None:
"""Increment the processed files count and update the status."""
with shared_state.processed_files_lock:
shared_state.processed_files_count += 1
update_status(start_time, shared_state.processed_files_count, total_files)
def load_image_as_array(path: Path) -> Optional[np.ndarray]:
"""Load an image and convert it to a NumPy array with error handling."""
img = validate_and_load_image(path)
if img is None:
return None
try:
return np.array(img)
except (OSError, ValueError) as e:
log_error(f"Error converting image to array {path}: {e}")
return None
def get_image_files(folder: Path, extensions: Set[str]) -> List[Path]:
"""Get a list of image files in a folder with the specified extensions."""
return [
path for path in folder.rglob('*')
if path.is_file() and path.suffix.lower() in extensions
]
# --- Processing Functions ---
def image_processing_wrapper(func):
"""Decorator to handle image loading and error handling."""
def wrapper(path: Path, start_time: float, total_files: int, *args, **kwargs):
if shared_state.stop_event.is_set():
return
img_array = load_image_as_array(path)
if img_array is None:
increment_and_update_status(start_time, total_files)
return
try:
func(img_array, path, *args, **kwargs)
except Exception as e:
log_error(f"Error processing image {path}: {e}")
finally:
increment_and_update_status(start_time, total_files)
return wrapper
@image_processing_wrapper
def process_file(img_array: np.ndarray, path: Path, start_time: float, total_files: int, image_processor: 'ImageProcessor', temp_folder: Path, resize: bool = False, auto_correct_and_resize: bool = False):
# ... rest of the code
Implementing these changes should solve the redundancies in your code.