To effectively refactor the provided code and eliminate redundancies, it's essential to identify recurring patterns and abstract them into reusable components. Here's a comprehensive strategy to achieve a cleaner, more maintainable codebase:
1. Abstract Common Functionality
a. Subprocess Execution with Error Handling
Issue: Multiple functions (resize_image, check_imagemagick, etc.) execute subprocess commands with similar try-except blocks for error handling.
Solution: Create a helper function to execute subprocess commands uniformly, handling errors consistently.
import subprocess
from typing import List
def run_subprocess(command: List[str], description: str) -> subprocess.CompletedProcess:
"""Run a subprocess command with standardized error handling."""
try:
result = subprocess.run(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
check=True
)
if result.stderr:
log_error(f"ImageMagick {description}: {result.stderr.strip()}")
return result
except subprocess.CalledProcessError as e:
log_error(f"ImageMagick {description} failed: {e.stderr.strip()}")
raise
Refactored Usage in resize_image:
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, "identify")
current_width, current_height = map(int, result.stdout.strip().split('x'))
except subprocess.CalledProcessError:
return output_path
# ... rest of the code ...
b. ImageMagick Command Construction
Issue: The construction of ImageMagick commands involves conditional logic that can be streamlined.
Solution: Create helper functions to build specific parts of the command based on parameters.
def build_resize_args(resize_mode: str, maintain_aspect: bool,
current_width: int, current_height: int) -> str:
"""Construct the resize argument based on mode and aspect ratio."""
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)
return f'{target_width}x{target_height}!'
else: # Shortest Side
target_size = int(app.RESIZE_SIDE.get())
return f'{target_size}x{target_size}^'
def determine_resize_command(is_upscaling: bool, resize_arg: str) -> List[str]:
"""Determine the ImageMagick resize command based on upscaling."""
if is_upscaling:
return [
'-filter', 'LanczosSharp',
'-distort', 'Resize', resize_arg,
]
else:
return [
'-colorspace', 'RGB',
'-filter', 'Lanczos2Sharp',
'-resize', resize_arg,
'-colorspace', 'sRGB',
]
Refactored Usage in resize_image:
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, "identify")
current_width, current_height = map(int, result.stdout.strip().split('x'))
except subprocess.CalledProcessError:
return output_path
resize_mode = app.RESIZE_MODE.get()
maintain_aspect = app.maintain_aspect_ratio.get()
resize_arg = build_resize_args(resize_mode, maintain_aspect, current_width, current_height)
is_upscaling = (
(resize_mode == "Fit" and (int(app.RESIZE_WIDTH.get() or 0) > current_width or
int(app.RESIZE_HEIGHT.get() or 0) > current_height)) or
(resize_mode == "Shortest Side" and int(app.RESIZE_SIDE.get()) > min(current_width, current_height))
)
resize_command = determine_resize_command(is_upscaling, resize_arg)
command = [
str(Config.IMAGEMAGICK),
str(input_path),
] + resize_command + [
'-define', 'png:compression-level=5',
str(output_path)
]
try:
run_subprocess(command, "resize")
except subprocess.CalledProcessError:
pass # Output path already set, could handle differently if needed
return output_path
2. Modularize Image Processing Logic
a. Separation of Concerns in process_file
Issue: The process_file function handles multiple responsibilities: validation, reading, processing (color correction, resizing), and saving.
Solution: Break down process_file into smaller, more focused functions.
def validate_image(path: Path) -> bool:
"""Check if the image is valid."""
if not is_valid_image(path):
log_error(f"Invalid image file: {path}")
return False
return True
def read_image(path: Path) -> Optional[np.ndarray]:
"""Read and convert the image to a NumPy array."""
try:
return np.array(open_and_convert_image(path))
except (OSError, ValueError) as e:
log_error(f"Error reading image {path}: {e}")
return None
def determine_output_format() -> str:
"""Determine the output image format based on app settings."""
return 'jpg' if app.RESIZE_FORMAT.get() == 'jpg' else 'png'
def save_final_image(temp_output_path: Path, final_output_path: Path, output_format: str) -> None:
"""Save the processed image in the desired format."""
if output_format == 'jpg':
convert_png_to_jpg(temp_output_path, final_output_path)
else:
shutil.move(str(temp_output_path), str(final_output_path))
Refactored process_file:
def process_file(
path: Path,
start_time,
total_files,
image_processor: 'ImageProcessor',
temp_folder: Path,
resize=False,
auto_correct_and_resize=False
) -> None:
"""Process a single image file."""
if shared_state.stop_event.is_set():
return
if not validate_image(path):
increment_processed_files(start_time, total_files)
return
img = read_image(path)
if img is None:
increment_processed_files(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)
is_color = is_color_image(img)
output_format = determine_output_format()
if auto_correct_and_resize:
intermediate_path = process_auto_correct(img, path, image_processor, temp_folder, is_color)
temp_output_path = resize_image(intermediate_path, temp_output_path)
elif resize:
temp_output_path = resize_image(path, temp_output_path)
else:
process_without_resize(img, path, image_processor, temp_folder, is_color, temp_output_path)
final_output_path = Config.OUTPUT_FOLDER / relative_path.with_suffix(f'.{output_format}')
final_output_path.parent.mkdir(parents=True, exist_ok=True)
save_final_image(temp_output_path, final_output_path, output_format)
increment_processed_files(start_time, total_files)
Additional Helper Functions:
def process_auto_correct(img, path, image_processor, temp_folder, is_color):
if is_color:
intermediate_path, _ = process_color_image(img, path, image_processor, temp_folder)
else:
intermediate_path, _, _ = process_grayscale_image(img, path, image_processor, temp_folder)
return intermediate_path
def process_without_resize(img, path, image_processor, temp_folder, is_color, temp_output_path):
if is_color:
temp_output_path, _ = process_color_image(img, path, image_processor, temp_folder)
else:
temp_output_path, _, _ = process_grayscale_image(img, path, image_processor, temp_folder)
def increment_processed_files(start_time, total_files):
with shared_state.processed_files_lock:
shared_state.processed_files_count += 1
update_status(start_time, shared_state.processed_files_count, total_files)
3. Enhance ImageProcessor Class
a. Simplify Result Writing with Data-Driven Approach
Issue: The write_results_to_files and _write_results methods contain repetitive code structures based on the choice parameter.
Solution: Utilize a mapping strategy to handle different choices, minimizing conditional logic.
class ImageProcessor:
"""Class to handle image processing results."""
def __init__(self):
self.results = {
'white': defaultdict(list),
'black': defaultdict(list),
'color': defaultdict(list)
}
def write_results_to_files(self, output_folder: Path, choice: str):
"""Write processing results to files."""
results_map = {
'2': ("2. Analyze Images", ["black", "white"]),
'3': ("3. Find Color Images", ["color"]),
'5': ("5. Automatic Color Correction", ["black", "white"]),
'6': ("6. Automatic Color Correction + Resize", ["black", "white"])
}
headers_map = {
'2': {"black": "Modal Value Black", "white": "Modal Value White"},
'3': {"color": "Filename"},
'5': {"black": "Modal Value Black", "white": "Modal Value White"},
'6': {"black": "Modal Value Black", "white": "Modal Value White"}
}
header, categories = results_map.get(choice, ("Results", []))
separators = '-' * Config.SEPARATOR_LENGTH
for category in categories:
value_name = headers_map[choice].get(category, "Value")
self._write_results(category, self.results[category], header, value_name)
def _write_results(self, category: str, results: Dict[str, List], header: str, value_name: str):
"""Write results to a specific file."""
content = f"{'-' * Config.SEPARATOR_LENGTH}\n{header}\n{'-' * Config.SEPARATOR_LENGTH}\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.sort()
content += '\n'.join(f" - {filename}" for filename in subfolder_results)
else:
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[category].append(content)
def reset_results(self):
"""Reset all results."""
for key in self.results:
self.results[key].clear()
Benefits:
- Scalability: Easier to add new categories or choices without modifying the core logic.
- Maintainability: Centralized mapping reduces the risk of inconsistencies.
4. Optimize Thread Pool Usage
Issue: Both resize_images and process_folder functions utilize run_with_thread_pool with similar parameters, differing mainly in the resize and auto_correct_and_resize flags.
Solution: Consolidate these functions by parameterizing the differing aspects.
def process_images(input_folder: Path, output_folder: Path, image_processor: 'ImageProcessor',
resize: bool = False, auto_correct_and_resize: bool = False) -> None:
"""Generalized function to process images with optional resizing and auto-correction."""
try:
if auto_correct_and_resize or resize:
check_imagemagick()
except FileNotFoundError as e:
log_error(str(e))
return
tasks = [input_path for input_path in input_folder.rglob('*')
if input_path.is_file() and input_path.suffix.lower() in Config.IMAGE_EXTENSIONS]
if not tasks:
log_error(f"No image files found in '{input_folder}'")
return
with create_temp_folder() as temp_folder:
run_with_thread_pool(
tasks,
process_file,
time.time(),
len(tasks),
image_processor,
temp_folder,
resize,
auto_correct_and_resize
)
Refactored resize_images and process_folder:
def resize_images(input_folder: Path, output_folder: Path, image_processor: 'ImageProcessor'):
"""Resize images in the input folder and save them to the output folder."""
process_images(input_folder, output_folder, image_processor, resize=True)
def process_folder(folder: Path, image_processor: 'ImageProcessor', auto_correct_and_resize=False) -> None:
"""Process all images in a folder."""
image_processor.reset_results()
process_images(folder, Config.OUTPUT_FOLDER, image_processor,
auto_correct_and_resize=auto_correct_and_resize)
5. Streamline Logging Mechanisms
a. Consolidate Error Logging
Issue: Error logging is scattered across various functions with similar patterns.
Solution: Implement a centralized logging mechanism that can be invoked uniformly.
from queue import Queue
from collections import defaultdict
def log_error(message: str) -> None:
"""Log an error message."""
# Assuming there's a logging mechanism in place
logger.error(message)
# Optionally, enqueue the error for asynchronous logging
shared_state.error_queue.put(message)
b. Enhance log_errors Function
Issue: The log_errors function iterates through an error queue and organizes them, which can be optimized.
Solution: Utilize more Pythonic constructs and ensure thread-safety.
def log_errors():
"""Log errors from the error queue."""
error_dict = defaultdict(list)
while not shared_state.error_queue.empty():
error_message = shared_state.error_queue.get()
error_dict[error_message].append(error_message) # Adjust based on how errors are stored
if error_dict:
shared_state.log_message_queue.put("UPDATE_LOG")
for error_message in sorted(error_dict.keys()):
shared_state.log_message_queue.put(f"{error_message}")
shared_state.log_message_queue.put("")
6. Enhance log_and_execute Function
Issue: The log_and_execute function contains nested functions and repetitive logging.
Solution: Simplify threading logic and separate logging from execution.
def log_and_execute(choice: str, label: str, function: callable, *args):
"""Log the execution of a function and run it in a separate thread."""
def run_in_thread():
start_time = time.time()
separator = '-' * Config.SEPARATOR_LENGTH
shared_state.log_message_queue.put(f"{separator}\n{label}\n{separator}\n")
try:
total_files = function(*args)
except (FileNotFoundError, OSError, ValueError) as e:
log_error(f"An error occurred during '{label}': {e}")
total_files = 0
execution_time = time.time() - start_time
shared_state.log_message_queue.put("")
image_processor.write_results_to_files(Config.OUTPUT_FOLDER, choice)
app.after(0, app.update_final_status, execution_time)
app.after(0, app.update_text_area)
threading.Thread(target=run_in_thread).start()
7. General Code Cleanup
-
Consistent Naming: Ensure that variable and function names follow a consistent naming convention for better readability.
-
Type Hinting: Continue to use and expand type hints for better code clarity and tooling support.
-
Documentation: Maintain or enhance docstrings to accurately describe functions, their parameters, and return values.
8. Final Refactored Structure Overview
After applying the above refactoring strategies, the high-level structure of the code would look like this:
- helpers.py
- run_subprocess
- build_resize_args
- determine_resize_command
- validate_image
- read_image
- determine_output_format
- save_final_image
- process_auto_correct
- process_without_resize
- increment_processed_files
- image_processor.py
- ImageProcessor class with streamlined methods
- processing.py
- process_file
- process_images
- resize_images
- process_folder
- logging.py
- log_error
- log_errors
- log_and_execute
- main.py
- Entry point coordinating all modules
Benefits of This Refactoring Strategy
-
Reduced Redundancy: By abstracting common functionalities, the code avoids repetitive patterns, making it shorter and easier to manage.
-
Enhanced Readability: Modular functions with clear responsibilities improve the overall readability and comprehension of the code.
-
Improved Maintainability: Isolated components facilitate easier updates, testing, and debugging.
-
Scalability: The codebase becomes more adaptable to future feature additions or modifications without introducing inconsistencies.
-
Consistent Error Handling: Centralized error handling ensures that all subprocess executions and operations handle errors uniformly, improving reliability.
By implementing this refactoring strategy, the code will become more efficient, easier to maintain, and better structured for future development.