Analyze the code for instances where it uses old python features that have better alternatives in python 3.12. Only list concrete cases in the code where a new python feature can be implemented and show how to implement it. Python code: import ctypes
import logging
import os
import signal
import shutil
import subprocess
import tempfile
import threading
import time
import tkinter as tk
from collections import defaultdict
from concurrent.futures import Future, ThreadPoolExecutor
from contextlib import contextmanager
from dataclasses import dataclass, field
from pathlib import Path
from queue import Queue
from tkinter import filedialog, ttk
from typing import Any, Callable, Sequence, Generator, cast
import numpy as np
from PIL import Image
--- Configuration ---
@dataclass
class SharedState:
"""Represents the shared state across the application."""
@contextmanager
def create_temp_directory() -> Generator[Path, None, None]:
"""Yield a temporary directory within the output directory."""
with tempfile.TemporaryDirectory(dir=Config.OUTPUT_FOLDER) as temp_dir:
yield Path(temp_dir)
--- Logging ---
def log_error_messages(error_queue: Queue[tuple[Path, list[str]]]) -> None:
"""Log error messages from the error queue."""
error_dict: defaultdict[Path, list[str]] = 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_message(error_message)
shared_state.log_message_queue.put("")
def log_and_execute_in_thread(
choice: str, label: str, function: Callable[..., Any], *args: Any
) -> None:
"""Log the execution of a function and run it in a separate thread."""
def log_error_message(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) -> Image.Image | None:
"""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_message(f"Error reading image {path}: {e}")
return None
def load_image_to_numpy_array(path: Path, mode: str | None = None) -> np.ndarray | None:
"""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
img = img.convert(mode) if mode else img
try:
return np.array(img)
except (OSError, ValueError) as e:
log_error_message(f"Error converting image to array {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")
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_message(f"Error converting {input_path} to JPG: {e}")
def verify_executable_exists(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_file_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_processing_status(start_time, shared_state.processed_files_count, total_files)
def generate_new_filename(pattern: str, original_filename: str) -> str:
"""Rename the file based on the provided pattern."""
original_path = Path(original_filename)
new_base = pattern.replace("{Filename}", original_path.stem).strip()
# Ensure the new base name is not empty
if not new_base:
new_base = original_path.stem
# Replace or remove any illegal characters if necessary
illegal_chars = r'\/:*?"<>|'
new_base = ''.join('_' if char in illegal_chars else char for char in new_base)
return f"{new_base}{original_path.suffix}"
def run_subprocess(command: list[str], check: bool = False, **kwargs) -> subprocess.CompletedProcess:
"""Run a subprocess while tracking it in active_subprocesses."""
with shared_state.active_subprocesses_lock:
proc = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
**kwargs
)
shared_state.active_subprocesses.append(proc)
try:
stdout, stderr = proc.communicate()
if check and proc.returncode != 0:
raise subprocess.CalledProcessError(proc.returncode, proc.args, output=stdout, stderr=stderr)
return subprocess.CompletedProcess(proc.args, proc.returncode, stdout, stderr)
finally:
with shared_state.active_subprocesses_lock:
if proc in shared_state.active_subprocesses:
shared_state.active_subprocesses.remove(proc)
--- Process Bar and Multithreading ---
def update_processing_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_processing_status(start_time, shared_state.processed_files_count, total_files)
time.sleep(1)
def execute_tasks_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()
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_message(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
# 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_grayscale_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)
# Create a mask for extreme original values (0 and 255)
mask = (img == 0) | (img == 255)
# Exclude extreme values from the white adjustment
white_adjust_mask = ~mask
# Scale image if modal white is not at maximum intensity
if modal_white != 255:
adjusted[white_adjust_mask] *= 255.0 / modal_white
adjusted = np.clip(adjusted, 0, 255)
# After white value adjustment, identify new extreme values
new_extremes = (adjusted == 0) | (adjusted == 255)
# Combine masks to exclude all extreme values from black adjustment
total_extremes = mask | new_extremes
black_adjust_mask = ~total_extremes
# Adjust image based on modal black value
if modal_black:
adjusted[black_adjust_mask] = (
adjusted[black_adjust_mask] - modal_black
) * (255.0 / (255 - modal_black))
adjusted = np.clip(adjusted, 0, 255)
gamma = 1.0 - (modal_black / 255.0)
adjusted[black_adjust_mask] = (
np.power(adjusted[black_adjust_mask] / 255.0, gamma) * 255
)
# Round to nearest integer and then convert to uint8
adjusted = np.rint(adjusted).astype(np.uint8)
return adjusted, modal_black, modal_white
except ValueError as e:
log_error_message(f"Error adjusting values for image: {e}")
return img, 0, 255
--- Image Analysis ---
def analyze_image_color_properties(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
]
if not image_files:
log_error_message(f"No image files found in '{Config.INPUT_FOLDER}'")
return
with create_temp_directory() as temp_folder:
start_time = time.time()
execute_tasks_with_thread_pool(image_files, analyze_image_file, start_time, len(image_files))
def analyze_image_file(path: Path, start_time: float, total: int) -> None:
"""Analyze an image to classify it as color or grayscale."""
if shared_state.stop_event.is_set():
return
img_array = load_image_to_numpy_array(path)
if img_array is None:
increment_processed_file_count(start_time, total)
return
subfolder = path.parent.relative_to(Config.INPUT_FOLDER).as_posix()
filename = path.name
if is_color_image(img_array):
image_processor.color_results[subfolder].append(filename)
else:
# Load the image as grayscale before adjusting values
img_gray = load_image_to_numpy_array(path, mode='L')
if img_gray is None:
increment_processed_file_count(start_time, total)
return
adjusted, modal_black, modal_white = adjust_grayscale_values(img_gray)
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))
increment_processed_file_count(start_time, total)
def identify_and_move_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_message(f"No image files found in '{Config.INPUT_FOLDER}'")
return
with create_temp_directory():
execute_tasks_with_thread_pool(
tasks, move_color_image, time.time(), len(tasks), image_processor
)
def move_color_image(
path: Path, start_time: float, total_files: int, image_processor: "ImageProcessor"
) -> None:
"""Move a color image file to the output folder with renaming and update processing status."""
if shared_state.stop_event.is_set():
return
img_array = load_image_to_numpy_array(path)
if img_array is None:
increment_processed_file_count(start_time, total_files)
return
if is_color_image(img_array):
rel_path = path.relative_to(Config.INPUT_FOLDER)
# Extract the original filename
original_filename = rel_path.name
# Apply renaming pattern to the original filename
new_filename = generate_new_filename(app.RENAME_PATTERN.get(), original_filename)
# Determine the new relative path with the renamed file
new_rel_path = rel_path.with_name(new_filename)
# Construct the full output path
out_path = Config.OUTPUT_FOLDER / new_rel_path
# Ensure that the parent directories exist
out_path.parent.mkdir(parents=True, exist_ok=True)
try:
shutil.move(str(path), str(out_path))
except Exception as e:
log_error_message(f"Failed to move {path} to {out_path}: {e}")
increment_processed_file_count(start_time, total_files)
return
subfolder = str(rel_path.parent)
# **Store the original filename instead of the new filename**
image_processor.color_results[subfolder].append(original_filename)
increment_processed_file_count(start_time, total_files)
--- Corrupted Files ---
def check_for_corrupted_files() -> None:
"""Check for corrupted files in the input folder using FFmpeg."""
image_processor.reset_results()
try:
verify_executable_exists(Config.FFMPEG, "FFmpeg")
except FileNotFoundError as error:
log_error_message(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_message(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:
"""Function to check a single file for corruption using FFmpeg."""
if shared_state.stop_event.is_set():
return
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 = run_subprocess(
base_command,
check=False,
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_file_count(start_time, total_files)
execute_tasks_with_thread_pool(tasks, check_file)
log_error_messages(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:
verify_executable_exists(Config.IMAGEMAGICK, "ImageMagick")
except FileNotFoundError as e:
log_error_message(str(e))
return
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_message(f"No image files found in '{input_folder}'")
return
with create_temp_directory() as temp_folder:
execute_tasks_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")
identify_command = [
str(Config.IMAGEMAGICK),
str(input_path),
"-format",
"%wx%h",
"info:",
]
try:
result = run_subprocess(
identify_command,
check=True
)
current_width, current_height = map(int, result.stdout.strip().split("x"))
except subprocess.CalledProcessError as e:
log_error_message(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 = run_subprocess(
command,
check=True
)
if result.stderr:
log_error_message(f"ImageMagick: {result.stderr.strip()}")
except subprocess.CalledProcessError as e:
log_error_message(f"ImageMagick resize failed for {input_path}: {e.stderr.strip()}")
return output_path
img_array = load_image_to_numpy_array(path)
if img_array is None:
increment_processed_file_count(start_time, 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
)
resized_path = resize_image(intermediate_path, temp_output_path)
elif resize:
# Only resize the original image
resized_path = resize_image(path, temp_output_path)
else:
# Adjust and save image without resizing
resized_path, _, _ = adjust_and_save_image(
img_array, path, image_processor, temp_folder
)
# Determine the final output format
output_format = app.RESIZE_FORMAT.get().lower()
if output_format not in ["jpg", "png"]:
output_format = "png" # Fallback to PNG if an unsupported format is selected
# Apply renaming pattern
new_filename = generate_new_filename(app.RENAME_PATTERN.get(), relative_path.name)
new_filename = os.path.splitext(new_filename)[0] + f".{output_format}"
final_output_path = Config.OUTPUT_FOLDER / relative_path.parent / new_filename
final_output_path.parent.mkdir(parents=True, exist_ok=True)
# Save the final processed file
if output_format == "jpg":
convert_png_to_jpg(resized_path, final_output_path)
else:
shutil.move(str(resized_path), str(final_output_path))
increment_processed_file_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()
if auto_correct_and_resize:
try:
verify_executable_exists(Config.IMAGEMAGICK, "ImageMagick")
except FileNotFoundError as e:
log_error_message(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_message(f"No image files found in '{folder}'")
return
with create_temp_directory() as temp_folder:
execute_tasks_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, int | None, int | None]:
"""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
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
# Load the image as grayscale before adjusting values
img_gray = load_image_to_numpy_array(path, mode='L')
if img_gray is None:
log_error_message(f"Error loading image {path} as grayscale.")
return out_path, None, None
adjusted_img, modal_black, modal_white = adjust_grayscale_values(img_gray)
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_message(f"Error processing image {path}: {e}")
return path, None, None
--- ImageProcessor Class ---
class ImageProcessor:
"""Class to handle image processing results."""
def __init__(self) -> None:
self.white_results: dict[str, list[tuple[str, int]]] = defaultdict(list)
self.black_results: dict[str, list[tuple[str, int]]] = defaultdict(list)
self.color_results: dict[str, list[str]] = defaultdict(list)
def collect_processing_results(self, output_folder: Path, choice: str) -> None:
"""Collect processing results and prepare them for display or logging."""
results_map: dict[str, tuple[str, str, str] | tuple[str, str]] = {
"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",
),
}
headers = results_map.get(choice)
if headers:
if choice == "3":
self._write_results("Color", self.color_results, headers[0], headers[1])
else:
self._write_results("Black", self.black_results, headers[0], headers[1])
self._write_results("White", self.white_results, headers[0], headers[2])
self._write_results("Color", self.color_results, headers[0], "Filename")
def _write_results(
self,
file_path: str,
results: dict[str, list[tuple[str, int]] | list[str]],
header: str,
value_name: str,
) -> None:
"""Write results to a specific file."""
separator = "-" * Config.SEPARATOR_LENGTH
content = f"{separator}\n{header}\n{separator}\n"
if results:
for subfolder, subfolder_results in sorted(results.items()):
full_subfolder_path = Config.INPUT_FOLDER / subfolder
content += f"\n{full_subfolder_path}\n\n"
if value_name == "Filename":
subfolder_results = cast(list[str], subfolder_results)
subfolder_results.sort()
content += "\n".join(
f" - {filename}" for filename in subfolder_results
)
else:
subfolder_results = cast(list[tuple[str, int]], subfolder_results)
subfolder_results.sort(key=lambda x: x[1], reverse=True)
content += "\n".join(
f" - {filename}, {value_name}: {value}"
for filename, value in subfolder_results
)
content += "\n"
shared_state.tab_messages[file_path].append(content)
def reset_results(self) -> None:
"""Reset all results."""
self.white_results = defaultdict(list)
self.black_results = defaultdict(list)
self.color_results = defaultdict(list)
if name == "main":
shared_state = Config.initialize()
image_processor = ImageProcessor()
app = App()
app.mainloop()
Upon analyzing your Python code, it’s clear that it already leverages many modern Python features, such as type hints, data classes, and pattern matching introduced in earlier versions of Python. However, Python 3.12 introduces several enhancements and new features that can further optimize and modernize your code. Below are concrete instances within your code where Python 3.12 features can be implemented, along with examples of how to apply them.
1. Utilizing the Self Type for Improved Type Hinting
Context:
Python 3.12 introduces the Self type in the typing module, which can be used to annotate methods that return an instance of their containing class. This enhances readability and type safety, especially in class methods that are designed for method chaining.
Where to Implement:
In your ImageProcessor and App classes, certain methods could be designed to return self to allow method chaining or for other design patterns. Although your current methods do not return self, modifying them to do so can take advantage of the Self type.
Example Implementation:
from typing import Self
from collections import defaultdict
@dataclass
class SharedState:
"""Represents the shared state across the application."""
# ... existing fields ...
class ImageProcessor:
"""Class to handle image processing results."""
def __init__(self) -> None:
self.white_results: dict[str, list[tuple[str, int]]] = defaultdict(list)
self.black_results: dict[str, list[tuple[str, int]]] = defaultdict(list)
self.color_results: dict[str, list[str]] = defaultdict(list)
def reset_results(self) -> Self:
"""Reset all processing results and return self for method chaining."""
self.white_results = defaultdict(list)
self.black_results = defaultdict(list)
self.color_results = defaultdict(list)
return self
def collect_processing_results(self, output_folder: Path, choice: str) -> Self:
"""Collect processing results and return self."""
# ... existing logic ...
return self
# Usage example:
image_processor = ImageProcessor().reset_results().collect_processing_results(Path("/output"), "2")
Benefits:
Readability: Makes it clear that the method returns an instance of the class.
Type Safety: Enhances type checking by explicitly indicating the return type as Self.
2. Implementing Exception Groups with except* for Concurrent Error Handling
Context:
Python 3.11 introduced Exception Groups to handle multiple exceptions that may occur concurrently, especially useful in asynchronous or multi-threaded applications. Python 3.12 continues this support, allowing for more granular and organized exception handling using the except* syntax.
Where to Implement:
In your execute_tasks_with_thread_pool function, exceptions from multiple threads are currently caught individually within each thread. Utilizing Exception Groups allows you to handle all exceptions collectively after all threads have completed, simplifying error management.
Original Code Snippet:
def execute_tasks_with_thread_pool(
tasks: Sequence[Path], process_func: Callable[..., Any], *args: Any
) -> int:
# ... setup code ...
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_message(f"Error during processing: {e}")
finally:
progress = (index / total) * 100
app.update_progress(progress)
finally:
stop_event.set()
elapsed_time_thread.join()
return total
Improved Code with Exception Groups:
from concurrent.futures import ThreadPoolExecutor, Future
from typing import Sequence, Callable, Any, List
from exceptions import ExceptionGroup # Available in Python 3.11+
def execute_tasks_with_thread_pool(
tasks: Sequence[Path], process_func: Callable[..., Any], *args: Any
) -> int:
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)
exceptions: List[BaseException] = []
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:
exceptions.append(e)
finally:
progress = (index / total) * 100
app.update_progress(progress)
if exceptions:
raise ExceptionGroup("Multiple exceptions occurred during task execution.", exceptions)
except* Exception as eg:
for e in eg.exceptions:
log_error_message(f"Processing error: {e}")
finally:
stop_event.set()
elapsed_time_thread.join()
return total
Explanation:
Collect Exceptions: Instead of logging each exception immediately, collect them in a list.
Raise Exception Group: After all tasks are processed, if any exceptions occurred, raise an ExceptionGroup.
Handle Exception Group with except*: Use the except* syntax to catch and handle all exceptions within the group collectively.
Benefits:
Coherent Error Handling: Simplifies the management of multiple exceptions arising from concurrent tasks.
Improved Logging: Allows for aggregated logging of errors, making debugging easier.
3. Enhancing Debugging with Improved f-String Syntax
Context:
Python 3.12 improves f-strings by allowing more expressive debugging outputs. By using the = specifier in f-strings, you can automatically include both the expression text and its value, which is invaluable for debugging.
Where to Implement:
In the App class’s configure_dpi_awareness method, you currently have a print statement that logs an error message if setting DPI awareness fails.
Original Code Snippet:
def configure_dpi_awareness(self) -> None:
try:
ctypes.windll.shcore.SetProcessDpiAwareness(1)
except Exception as e:
print(f"Could not set DPI awareness: {e}")
Improved Code with Enhanced f-Strings:
def configure_dpi_awareness(self) -> None:
try:
ctypes.windll.shcore.SetProcessDpiAwareness(1)
except Exception as e:
print(f"Could not set DPI awareness: e={e}")
Explanation:
e={e} Syntax: The = in the f-string automatically includes both the variable name (e) and its value. This provides clearer and more informative debug messages.
Benefits:
Enhanced Clarity: Makes it immediately clear which variable the value corresponds to.
Improved Debugging: Facilitates quicker identification of issues by providing more context in log messages.
4. Refining Type Hints with Literal for Specific Options
Context:
Using Literal from the typing module allows you to specify that a variable can only take on a specific set of values. This enhances type safety and can prevent bugs related to unexpected values.
Where to Implement:
In the App class’s start_processing method, the choice variable is derived from user input and corresponds to a predefined set of options.
Defining OptionChoice: Specifies that choice can only be one of the predefined string literals.
Type-Annotated actions Dictionary: Uses OptionChoice as the key type, ensuring that only valid keys are used.
Enhanced Type Safety: The type checker can now enforce that only valid choices are processed, reducing the risk of unexpected behavior.
Benefits:
Error Prevention: Prevents invalid option selections from being processed.
Improved Readability: Makes it clear what the valid options are.
Better Type Checking: Assists static type checkers in identifying potential mismatches or errors.
5. Leveraging Enhanced Type Narrowing in Control Flow
Context:
Python 3.12 continues to improve type narrowing, allowing the type checker to more accurately determine variable types within different branches of control flow statements.
Where to Implement:
In the validate_and_load_image function, the img variable undergoes different transformations based on its mode. Enhancing type hints and leveraging type narrowing can improve clarity and safety.
Original Code Snippet:
def validate_and_load_image(path: Path) -> Image.Image | None:
"""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_message(f"Error reading image {path}: {e}")
return None
Improved Code with Enhanced Type Narrowing:
from typing import Optional
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:
if img.mode == "P":
return img.convert("L")
elif img.mode in {"L", "RGB", "RGBA"}:
return img.copy()
else:
return img.convert("RGB")
except (OSError, ValueError) as e:
log_error_message(f"Error reading image {path}: {e}")
return None
Explanation:
Using Optional Instead of Union: Replaces Image.Image | None with Optional[Image.Image] for improved readability.
Explicit Control Flow with if-elif-else: While match is powerful, using if-elif-else can sometimes offer clearer type narrowing for the type checker, especially when dealing with more complex conditions.
Benefits:
Improved Readability:Optional is a commonly used type hint that clearly indicates a value may be None.
Enhanced Type Safety: Explicit control flow can sometimes aid the type checker in understanding variable states, reducing the likelihood of type-related bugs.
6. Optimizing Use of Path Methods with New Features
Context:
While not a direct Python 3.12 feature, Python 3.12 may introduce optimizations or enhancements to pathlib.Path methods. Ensuring that your code leverages the most efficient and up-to-date methods can improve performance and maintainability.
Where to Implement:
In functions like generate_new_filename and process_file, you manipulate file paths extensively. Ensuring that you use the latest Path methods optimizes these operations.
Original Code Snippet:
def generate_new_filename(pattern: str, original_filename: str) -> str:
"""Rename the file based on the provided pattern."""
original_path = Path(original_filename)
new_base = pattern.replace("{Filename}", original_path.stem).strip()
# Ensure the new base name is not empty
if not new_base:
new_base = original_path.stem
# Replace or remove any illegal characters if necessary
illegal_chars = r'\/:*?"<>|'
new_base = ''.join('_' if char in illegal_chars else char for char in new_base)
return f"{new_base}{original_path.suffix}"
Improved Code with Enhanced Path Methods:
def generate_new_filename(pattern: str, original_filename: str) -> str:
"""Rename the file based on the provided pattern."""
original_path = Path(original_filename)
new_base = pattern.replace("{Filename}", original_path.stem).strip()
# Ensure the new base name is not empty
if not new_base:
new_base = original_path.stem
# Use Path's `with_name` or `with_suffix` methods for safer path manipulations
# Replace or remove any illegal characters if necessary
illegal_chars = set(r'\/:*?"<>|')
new_base = ''.join('_' if char in illegal_chars else char for char in new_base)
return f"{new_base}{original_path.suffix}"
Explanation:
Utilizing Path Methods: While the original code is already efficient, ensuring consistent use of Path methods like with_name or with_suffix can enhance readability and safety.
Using a Set for illegal_chars: Converting illegal_chars to a set optimizes the lookup time from O(n) to O(1).
Benefits:
Performance Improvement: Using a set for illegal_chars enhances performance, especially with larger strings.
Enhanced Readability and Safety: Consistently using Path methods ensures safer path manipulations and makes the code more readable.
7. Leveraging Enhanced Context Manager Features
Context:
Python 3.12 may introduce subtle improvements to context managers, making resource management more efficient and readable. Ensuring that your use of context managers like tempfile.TemporaryDirectory and ThreadPoolExecutor aligns with the latest best practices can optimize resource handling.
Where to Implement:
In your create_temp_directory and other resource-handling functions.
Original Code Snippet:
@contextmanager
def create_temp_directory() -> Generator[Path, None, None]:
"""Yield a temporary directory within the output directory."""
with tempfile.TemporaryDirectory(dir=Config.OUTPUT_FOLDER) as temp_dir:
yield Path(temp_dir)
Improved Code with Enhanced Context Manager Practices:
from contextlib import contextmanager
from pathlib import Path
import tempfile
@contextmanager
def create_temp_directory() -> Generator[Path, None, None]:
"""Yield a temporary directory within the output directory."""
temp_dir = tempfile.TemporaryDirectory(dir=Config.OUTPUT_FOLDER)
try:
yield Path(temp_dir.name)
finally:
temp_dir.cleanup()
Explanation:
Explicit Cleanup: Ensures that the temporary directory is cleaned up even if an exception occurs during its use.
Enhanced Readability: Makes the resource management flow clearer.
Benefits:
Resource Safety: Guarantees that resources are properly released.
Improved Readability: Clearer structure enhances understanding and maintenance.
Summary
While your code is already well-structured and employs many modern Python features, integrating Python 3.12 enhancements can further improve type safety, error handling, debugging, and resource management. Here's a quick recap of the suggested improvements:
Use the Self type for method return annotations to enhance type clarity and enable method chaining.
Implement Exception Groups with the except* syntax to handle multiple concurrent exceptions more effectively.
Enhance f-strings with the = specifier for clearer and more informative debug messages.
Refine type hints with Literal to enforce specific allowed values, improving type safety.
Leverage improved type narrowing in control flow statements to aid static type checking and prevent bugs.
Optimize Path method usage for safer and more readable file path manipulations.
Enhance context manager usage to ensure robust resource management and improve code clarity.
By incorporating these Python 3.12 features, you can make your codebase even more robust, readable, and maintainable.