Your Python script for image processing is comprehensive and well-structured. Leveraging modern Python 3.12 features can enhance its readability, efficiency, and maintainability. Below are specific instances and suggestions where you can incorporate these modern features:
1. Structural Pattern Matching (match-case)
Where to Apply:
In functions where multiple conditional checks are performed based on the same variable, such as open_and_convert_image and parts of the process_file function.
Current Implementation:
def open_and_convert_image(path: Path) -> Image.Image:
with Image.open(path) as img:
if img.mode == 'P': # Palette mode (indexed)
return img.convert('L') # Convert to true grayscale
elif img.mode in ['L', 'RGB', 'RGBA']:
return img.copy() # Return a copy of the image
else:
return img.convert('RGB') # Convert other modes to RGB
Enhanced with match-case:
def open_and_convert_image(path: Path) -> Image.Image:
with Image.open(path) as img:
match img.mode:
case 'P':
return img.convert('L') # Convert to true grayscale
case 'L' | 'RGB' | 'RGBA':
return img.copy() # Return a copy of the image
case _:
return img.convert('RGB') # Convert other modes to RGB
Benefits:
- Clarity:
match-case provides a cleaner and more readable structure, especially when handling multiple conditions.
- Extensibility: Easier to add new cases without deeply nested
if-elif-else statements.
2. Use of Self Type in Type Hints
Where to Apply:
In class methods that return an instance of the class, such as the initialize method in the Config class.
Current Implementation:
class Config:
# ... existing class attributes ...
@classmethod
def initialize(cls):
"""Initialize the configuration and return a SharedState instance."""
cls.setup()
return SharedState()
Enhanced with Self:
from typing import Self
class Config:
# ... existing class attributes ...
@classmethod
def initialize(cls) -> Self:
"""Initialize the configuration and return a SharedState instance."""
cls.setup()
return SharedState()
Benefits:
- Precision: The
Self type clearly indicates that the method returns an instance of the class.
- Type Safety: Enhances type checking and IDE support.
3. Enhanced Assignment Expressions (Walrus Operator :=)
Where to Apply:
In scenarios where you can assign and use a value within a single expression, such as validating images.
Current Implementation:
def is_valid_image(path: Path) -> bool:
"""Check if the given path is a valid image file."""
try:
with Image.open(path):
return True
except (OSError, ValueError) as e:
log_error(f"Error reading image {path}: {e}")
return False
Enhanced with Walrus Operator:
def is_valid_image(path: Path) -> bool:
"""Check if the given path is a valid image file."""
try:
return (img := Image.open(path)) and True
except (OSError, ValueError) as e:
log_error(f"Error reading image {path}: {e}")
return False
Benefits:
- Conciseness: Reduces the number of lines by combining assignment and evaluation.
- Readability: Makes it clear that the image is being opened and immediately checked.
Note: While the walrus operator can make the code more concise, use it judiciously to avoid compromising readability.
4. Exception Groups and except* Clauses
Python 3.11 introduced Exception Groups and the except* syntax to handle multiple exceptions simultaneously, which is particularly useful in concurrent programming contexts like yours.
Where to Apply:
In the run_with_thread_pool function where multiple threads might raise exceptions.
Current Implementation:
def run_with_thread_pool(tasks, process_func, *args):
# ... setup code ...
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():
for f in futures:
f.cancel()
break
try:
future.result()
except Exception as e:
log_error(f"Error during processing: {e}")
finally:
progress = (i + 1) / total * 100
app.update_progress(progress)
finally:
# ... cleanup code ...
return total
Enhanced with Exception Groups:
from concurrent.futures import ThreadPoolExecutor, as_completed, CancelledError
from exceptions import ExceptionGroup
def run_with_thread_pool(tasks, process_func, *args):
shared_state.processed_files_count = 0
shared_state.total_files_count = len(tasks) # Set total files count
start_time = time.time()
total = len(tasks)
app.update_progress(0)
stop_event = threading.Event()
elapsed_time_thread = start_elapsed_time_thread(start_time, total, stop_event)
exception_group = ExceptionGroup("Processing Exceptions", [])
try:
with ThreadPoolExecutor() as executor:
futures = {executor.submit(process_func, task, *args): task for task in tasks}
for future in as_completed(futures):
if shared_state.stop_event.is_set():
executor.shutdown(cancel_futures=True)
break
try:
future.result()
except Exception as e:
exception_group.exceptions.append(e)
finally:
with shared_state.processed_files_lock:
shared_state.processed_files_count += 1
progress = (shared_state.processed_files_count) / total * 100
app.update_progress(progress)
if exception_group.exceptions:
raise exception_group
except ExceptionGroup as eg:
for e in eg.exceptions:
log_error(f"Error during processing: {e}")
finally:
stop_event.set()
elapsed_time_thread.join()
return total
Benefits:
- Comprehensive Error Handling: Collects all exceptions and handles them collectively, improving the manageability of errors in concurrent environments.
- Cleaner Code: Reduces the need for multiple
try-except blocks scattered throughout the loop.
Caution: Ensure that exception handling logic aligns with your application's requirements to prevent unwanted termination or masking of critical errors.
5. Precise Type Annotations and Enhanced Typing
Modern Python versions continue to enhance the typing module, allowing for more precise and expressive type annotations.
Where to Apply:
Throughout the codebase, especially in function signatures and class definitions.
Current Implementation:
def count_image_files(folder: Path) -> int:
"""Count the number of image files in a folder and its subfolders."""
return sum(1 for path in folder.rglob('*') if path.is_file() and path.suffix.lower() in Config.IMAGE_EXTENSIONS)
Enhanced with More Precise Types:
from collections.abc import Iterable
def count_image_files(folder: Path) -> int:
"""Count the number of image files in a folder and its subfolders."""
return sum(1 for path in folder.rglob('*') if path.is_file() and path.suffix.lower() in Config.IMAGE_EXTENSIONS)
Enhancements:
- Use of
collections.abc: Ensures interoperability and adherence to typing standards.
- Detailed Type Hints: For example, specifying
Queue[str] instead of a generic Queue.
Example in SharedState:
from typing import Final, List, Dict
from queue import Queue
@dataclass
class SharedState:
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)
Benefits:
- Improved Readability: Clear type definitions make the code easier to understand.
- Enhanced Tooling Support: Better type hints enhance the effectiveness of static type checkers and IDE features.
6. Using Final for Constants
The Final qualifier from the typing module can be used to declare constants that should not be overridden, enhancing code safety and clarity.
Where to Apply:
In the Config class for attributes that should remain constant.
Current Implementation:
class Config:
"""Configuration class 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'))
# ... other configurations ...
Enhanced with Final:
from typing import Final
class Config:
"""Configuration class for the image processing application."""
SCRIPT_DIR: Final = Path(__file__).parent.resolve()
INPUT_FOLDER: Final = Path(os.getenv('INPUT_FOLDER', SCRIPT_DIR / '1. Input'))
OUTPUT_FOLDER: Final = Path(os.getenv('OUTPUT_FOLDER', SCRIPT_DIR / '2. Output'))
# ... other configurations ...
Benefits:
- Immutability: Signals to developers that these attributes should not be modified.
- Type Checking: Tools like
mypy will flag any reassignment attempts, preventing accidental modifications.
7. Enumerations (Enum) for Fixed Choices
Using Enum for fixed sets of choices improves code clarity and reduces the risk of typographical errors.
Where to Apply:
In the App class for processing options.
Current Implementation:
def start_processing(self):
# ...
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),
# ... other actions ...
}
label, func, *args = actions.get(choice, ("Unknown Action", lambda: None))
log_and_execute(choice, label, func, *args)
Enhanced with Enum:
from enum import Enum
class ProcessingOption(Enum):
RESIZE_IMAGES = "1"
ANALYZE_IMAGES = "2"
FIND_COLOR_IMAGES = "3"
CHECK_CORRUPTED_FILES = "4"
AUTOMATIC_COLOR_CORRECTION = "5"
AUTOMATIC_COLOR_CORRECTION_RESIZE = "6"
def start_processing(self):
# ...
choice = ProcessingOption(self.option_var.get())
match choice:
case ProcessingOption.RESIZE_IMAGES:
label, func, *args = ("1. Resize Images", resize_images, Config.INPUT_FOLDER, Config.OUTPUT_FOLDER, image_processor)
case ProcessingOption.ANALYZE_IMAGES:
label, func, *args = ("2. Analyze Images", analyze_images, image_processor)
# ... other cases ...
case _:
label, func, *args = ("Unknown Action", lambda: None)
log_and_execute(choice.value, label, func, *args)
Benefits:
- Type Safety: Ensures only predefined options are used.
- Readability: Makes the code more descriptive and easier to understand.
8. Leveraging functools.partial for Cleaner Function Calls
When submitting tasks to the thread pool that require fixed arguments, functools.partial can make the code cleaner.
Where to Apply:
In the analyze_images, find_color_images, and similar functions where multiple arguments are passed to process_func.
Current Implementation:
futures = [executor.submit(process_func, task, *args) for task in tasks]
Enhanced with functools.partial:
from functools import partial
def analyze_images(image_processor: 'ImageProcessor'):
# ...
with create_temp_folder() as temp_folder:
func = partial(analyze_file, start_time=time.time(), total=len(tasks))
run_with_thread_pool(tasks, func)
Benefits:
- Clarity: Simplifies the submission of tasks by pre-filling some arguments.
- Maintainability: Easier to manage and understand how arguments are being passed.
9. Using dataclass Enhancements Like slots
Python's dataclass can be optimized using slots to reduce memory footprint and enhance attribute access speed.
Where to Apply:
In the SharedState and ImageProcessor classes.
Current Implementation:
@dataclass
class SharedState:
processed_files_lock: threading.Lock = field(default_factory=threading.Lock)
# ... other fields ...
Enhanced with slots:
@dataclass(slots=True)
class SharedState:
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)
Benefits:
- Memory Efficiency: Reduces the memory overhead by preventing the creation of
__dict__ for each instance.
- Performance: Faster attribute access due to the use of slots.
Caution:
Using slots restricts adding new attributes dynamically. Ensure all necessary attributes are defined within the class.
10. Improved Logging with logging Module Enhancements
While your current implementation uses a Queue for logging, modern Python logging can be more efficiently handled using logging module features.
Where to Apply:
In the log_error function and overall logging setup.
Current Implementation:
def log_error(message: str):
"""Log an error message to the shared state queue."""
shared_state.log_message_queue.put(f"- {message}")
Enhanced with logging Module:
import logging
# Configure logging at the start
logging.basicConfig(
level=logging.WARNING,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("image_processor.log"),
logging.StreamHandler()
]
)
def log_error(message: str):
"""Log an error message using the logging module."""
logging.error(message)
Benefits:
- Flexibility: Allows for different logging levels and handlers (e.g., file, console).
- Standardization: Utilizes Python's built-in logging capabilities, making it easier to manage and maintain.
- Enhanced Features: Supports features like log rotation, formatting, and filtering out-of-the-box.
Integration with GUI:
To display logs in the Tkinter Text widgets, you can create a custom logging handler that forwards log messages to the GUI.
Example:
class TkinterLoggingHandler(logging.Handler):
def __init__(self, text_widget: tk.Text):
super().__init__()
self.text_widget = text_widget
def emit(self, record):
message = self.format(record)
self.text_widget.config(state='normal')
self.text_widget.insert(tk.END, message + '\n')
self.text_widget.config(state='disabled')
self.text_widget.see(tk.END)
# In App class __init__ or setup_logging()
def setup_logging(self):
self.queue_thread = threading.Thread(target=self.update_text_area_from_queue, daemon=True)
self.queue_thread.start()
log_handler = TkinterLoggingHandler(self.text_areas["Log"])
log_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
logging.getLogger().addHandler(log_handler)
logging.getLogger().setLevel(logging.WARNING)
Benefits:
- Real-Time Logging: Logs are immediately reflected in the GUI without manual queue handling.
- Reduced Complexity: Simplifies the logging mechanism by leveraging the
logging module's capabilities.
11. Utilizing Pathlib Enhancements for Better Path Handling
Ensure that all file and directory operations fully leverage pathlib's capabilities for cleaner and more readable code.
Where to Apply:
Throughout the codebase, especially in file operations like moving, copying, and checking file existence.
Current Implementation:
def move_color_image_file(path, start_time, total_files, image_processor: 'ImageProcessor'):
# ... code ...
out_path = Config.OUTPUT_FOLDER / rel_path
out_path.parent.mkdir(parents=True, exist_ok=True)
shutil.move(str(path), str(out_path))
# ... code ...
Enhanced with Pathlib Methods:
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."""
if is_valid_image(path):
try:
img = np.array(open_and_convert_image(path))
if img.ndim == 3 and img.shape[2] == 3:
if is_color_image(img, Config.COLORDIFF_THRESHOLD, Config.FRACTION_COLORED_PIXELS_THRESHOLD):
rel_path = path.relative_to(Config.INPUT_FOLDER)
out_path = Config.OUTPUT_FOLDER / rel_path
out_path.parent.mkdir(parents=True, exist_ok=True)
path.replace(out_path) # Uses Path.replace for moving
subfolder = str(path.parent.relative_to(Config.INPUT_FOLDER))
filename = path.name
image_processor.color_results[subfolder].append(filename)
except (OSError, ValueError) as e:
log_error(f"Error processing 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)
Benefits:
- Readability: Using
Path.replace or other Pathlib methods makes intentions clearer.
- Safety:
Pathlib methods handle path nuances across different operating systems more gracefully.
12. Refactoring with functools.partial for Cleaner Code
When functions require the same arguments repeatedly, functools.partial can help create specialized versions of these functions, reducing redundancy.
Where to Apply:
In functions like run_with_thread_pool where multiple arguments are passed to the processing functions.
Current Implementation:
def run_with_thread_pool(tasks, process_func, *args):
# ...
futures = [executor.submit(process_func, task, *args) for task in tasks]
# ...
Enhanced with partial:
from functools import partial
def run_with_thread_pool(tasks, process_func, *args):
# ...
partial_func = partial(process_func, *args)
futures = [executor.submit(partial_func, task) for task in tasks]
# ...
Benefits:
- Clarity: Reduces the complexity of passing multiple arguments every time.
- Maintainability: Makes it easier to manage changes in function signatures.
13. Enhanced dataclass Usage with __post_init__
Utilize the __post_init__ method in dataclass for any additional initialization that cannot be handled by default_factory.
Where to Apply:
In the SharedState or ImageProcessor classes if any post-initialization logic is required.
Current Implementation:
@dataclass
class SharedState:
processed_files_lock: threading.Lock = field(default_factory=threading.Lock)
# ... other fields ...
Enhanced Usage:
@dataclass
class SharedState:
processed_files_lock: threading.Lock = field(default_factory=threading.Lock)
# ... other fields ...
def __post_init__(self):
# Any additional initialization
pass
Benefits:
- Flexibility: Allows for complex initializations that depend on multiple fields.
- Organization: Keeps initialization logic encapsulated within the class.
14. Leveraging typing.Protocol for Duck Typing
Define protocols to specify expected behaviors for classes, enhancing type checking without enforcing inheritance.
Where to Apply:
If you have interfaces or expected behaviors for classes like ImageProcessor or App.
Example:
from typing import Protocol
class ImageProcessorProtocol(Protocol):
def reset_results(self) -> None:
...
def write_results_to_files(self, output_folder: Path, choice: str) -> None:
...
Usage in Function Signatures:
def analyze_images(image_processor: ImageProcessorProtocol):
...
Benefits:
- Flexibility: Allows different implementations as long as they adhere to the protocol.
- Type Safety: Enhances static type checking without requiring inheritance.
15. Optimizing File Handling with pathlib and Context Managers
Ensure all file operations are safe and optimized using context managers and pathlib methods.
Where to Apply:
Throughout all functions that handle file I/O, such as convert_png_to_jpg and resize_image.
Current Implementation:
def convert_png_to_jpg(input_path: Path, output_path: Path):
"""Convert a PNG image to JPG format."""
try:
with Image.open(input_path) as img:
# ... processing ...
input_path.unlink()
except Exception as e:
log_error(f"Error converting {input_path} to JPG: {e}")
Enhanced Usage with Context Managers:
def convert_png_to_jpg(input_path: Path, output_path: Path):
"""Convert a PNG image to JPG format."""
try:
with Image.open(input_path) as img:
img = img.convert('RGB') if img.mode not in ('RGB', 'L') else img.copy()
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}")
Benefits:
- Resource Management: Ensures files are properly closed after operations.
- Error Handling: Combined with enhanced exception handling, it prevents resource leaks.
16. Utilizing typing.Literal for Fixed Parameter Values
Use Literal types to restrict function parameters to fixed sets of values, enhancing type safety.
Where to Apply:
In functions like resize_image where certain parameters can only take specific values.
Example:
from typing import Literal
def resize_image(input_path: Path, output_path: Path, resize_mode: Literal["Fit", "Shortest Side"]):
"""Resize an image using ImageMagick."""
# ... implementation ...
Benefits:
- Type Safety: Prevents passing invalid values to functions.
- Documentation: Makes it clear what values are acceptable.
17. Improving GUI Responsiveness with asyncio (Advanced)
While Tkinter isn't natively asynchronous, integrating asyncio can improve GUI responsiveness, especially during long-running tasks.
Where to Apply:
In the App class methods that handle processing, such as start_processing.
Example:
import asyncio
class App(tk.Tk):
# ... existing methods ...
async def start_processing_async(self, choice: ProcessingOption):
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()
if hasattr(self, 'stopped_by_user'):
delattr(self, 'stopped_by_user')
match choice:
case ProcessingOption.RESIZE_IMAGES:
label, func, *args = ("1. Resize Images", resize_images, Config.INPUT_FOLDER, Config.OUTPUT_FOLDER, image_processor)
# ... other cases ...
await asyncio.to_thread(log_and_execute, choice.value, label, func, *args)
def start_processing(self):
choice = ProcessingOption(self.option_var.get())
asyncio.run(self.start_processing_async(choice))
Benefits:
- Responsiveness: Keeps the GUI responsive during background processing.
- Scalability: Efficiently handles multiple asynchronous tasks.
Caution:
Integrating asyncio with Tkinter requires careful management to prevent conflicts between the event loops. Ensure thorough testing if you choose to implement this.
18. Applying @property Decorators for Controlled Access
Use the @property decorator to manage access to class attributes, adding validation or computation as needed.
Where to Apply:
In the Config class for dynamically computed attributes or validation.
Example:
class Config:
# ... existing attributes ...
@property
def INPUT_FOLDER(self) -> Path:
return Path(os.getenv('INPUT_FOLDER', self.SCRIPT_DIR / '1. Input'))
@property
def OUTPUT_FOLDER(self) -> Path:
return Path(os.getenv('OUTPUT_FOLDER', self.SCRIPT_DIR / '2. Output'))
Benefits:
- Encapsulation: Controls how attributes are accessed and modified.
- Flexibility: Allows adding logic when getting or setting attributes without changing the interface.
19. Enhancing the App Class with dataclass (Selective Usage)
Although App inherits from tk.Tk, selective use of dataclass can help manage certain configurations or states more cleanly.
Where to Apply:
For configurations or stateful components within the App class that don't require full Tkinter integration.
Example:
from dataclasses import dataclass, field
@dataclass
class ResizeOptions:
mode: Literal["Fit", "Shortest Side"] = "Shortest Side"
width: int = 0
height: int = 0
side: int = 1600
format: Literal["png", "jpg"] = "png"
maintain_aspect_ratio: bool = False
class App(tk.Tk):
def __init__(self):
super().__init__()
self.resize_options = ResizeOptions()
# ... existing initialization ...
Benefits:
- Organization: Encapsulates related configuration options.
- Maintainability: Makes it easier to manage and pass around configuration data.
20. Optimizing Image Processing with numpy Enhancements
While not strictly a Python language feature, ensuring efficient use of numpy can significantly speed up image processing tasks.
Where to Apply:
In functions like is_color_image, adjust_values, and other image manipulation functions.
Suggestions:
- Vectorization: Ensure operations are fully vectorized to leverage
numpy's performance.
- Memory Efficiency: Use appropriate data types to minimize memory usage.
- Leveraging In-Place Operations: Modify arrays in place where possible to reduce memory overhead.
Example:
def adjust_values(img: np.ndarray) -> Tuple[np.ndarray, int, int]:
"""Adjust the values of a grayscale image."""
try:
hist, bins = np.histogram(img[img >= 250], bins=6, range=(250, 256))
modal_white = int(bins[np.argmax(hist)])
hist, bins = np.histogram(img[img < 61], bins=61, range=(0, 61))
modal_black = int(bins[np.argmax(hist)])
if modal_white != 255:
img *= (255.0 / modal_white)
np.clip(img, 0, 255, out=img)
img = img.astype(np.uint8)
if modal_black:
img -= modal_black
img *= (255.0 / (255 - modal_black))
np.clip(img, 0, 255, out=img)
gamma = 1.0 - (modal_black / 255.0)
img = np.power(img / 255.0, gamma) * 255
img[img == 0] = 0
img[img == 255] = 255
img = img.astype(np.uint8)
else:
adjusted = img
return img, modal_black, modal_white
except ValueError as e:
log_error(f"Error adjusting values for image: {e}")
return img, 0, 255
Benefits:
- Performance: Optimized
numpy operations can lead to significant speedups in image processing.
- Memory Consumption: In-place modifications reduce the application's memory footprint.
Conclusion
Incorporating these modern Python 3.12 features and best practices can lead to more efficient, readable, and maintainable code. Here's a summary of the key enhancements:
- Structural Pattern Matching: For cleaner and more expressive conditional logic.
- Enhanced Type Hints with
Self and Literal: For better type safety and clarity.
- Exception Groups: For comprehensive error handling in concurrent environments.
- Enumerations (
Enum): To manage fixed sets of choices reliably.
- Optimized
dataclass Usage: With features like slots and __post_init__ for better performance and flexibility.
- Advanced Logging Techniques: Utilizing Python's
logging module for more robust and flexible logging.
- Function Optimization with
functools.partial: For cleaner and more maintainable threading code.
- GUI Responsiveness with
asyncio: (Advanced) To enhance the user experience during long-running tasks.
By thoughtfully integrating these features, your application can benefit from Python's evolving capabilities, leading to a more robust and modern codebase.
If you have specific sections you'd like more detailed refactoring on or further explanations of the suggested features, feel free to ask!