You are a Python programmer tasked with refactoring code. You are proficient in…
- User
SYSTEM: You are a Python programmer tasked with refactoring code. You are proficient in Python 3.12 and use modern features where appropriate. Your code is clear, easy to read, and free of unnecessary verbosity. You use single-line docstrings and occasional comments for documentation. Often, the code you receive is just one part of a larger program. USER: # --- Resize Images ---
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 = 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_pathdef resize_images(input_folder: Path, output_folder: Path, image_processor: 'ImageProcessor'): """Resize images in the input folder and save them to the output folder.""" try: 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: try: run_with_thread_pool(tasks, process_file, time.time(), len(tasks), image_processor, temp_folder, True) finally: pass--- Processing ---
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 is_valid_image(path): log_error(f"Invalid image file: {path}") with shared_state.processed_files_lock: shared_state.processed_files_count += 1 update_status(start_time, shared_state.processed_files_count, total_files) return try: img = np.array(open_and_convert_image(path)) except (OSError, ValueError) as e: log_error(f"Error reading image {path}: {e}") with shared_state.processed_files_lock: shared_state.processed_files_count += 1 update_status(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 temp_output_path = temp_output_path.with_suffix('.png') temp_output_path.parent.mkdir(parents=True, exist_ok=True) if auto_correct_and_resize: if img.ndim == 2 or (img.ndim == 3 and img.shape[2] == 1): intermediate_path, _, _ = process_grayscale_image(img, path, image_processor, temp_folder) else: intermediate_path, _ = process_color_image(img, path, image_processor, temp_folder) temp_output_path = resize_image(intermediate_path, temp_output_path) elif resize: temp_output_path = resize_image(path, temp_output_path) else: if img.ndim == 2 or (img.ndim == 3 and img.shape[2] == 1): temp_output_path, _, _ = process_grayscale_image(img, path, image_processor, temp_folder) else: temp_output_path, _ = process_color_image(img, path, image_processor, temp_folder) final_output_path = Config.OUTPUT_FOLDER / relative_path final_output_path.parent.mkdir(parents=True, exist_ok=True) if app.RESIZE_FORMAT.get() == 'jpg': final_output_path = final_output_path.with_suffix('.jpg') convert_png_to_jpg(temp_output_path, final_output_path) else: final_output_path = final_output_path.with_suffix('.png') shutil.move(str(temp_output_path), str(final_output_path)) with shared_state.processed_files_lock: shared_state.processed_files_count += 1 update_status(start_time, shared_state.processed_files_count, total_files)def process_folder(folder: Path, image_processor: 'ImageProcessor', auto_correct_and_resize=False) -> None: """Process all images in a folder.""" image_processor.reset_results()
if auto_correct_and_resize: try: check_imagemagick() except FileNotFoundError as e: log_error(str(e)) return tasks = [path for path in folder.rglob('*') if path.is_file() and path.suffix.lower() in Config.IMAGE_EXTENSIONS] if not tasks: log_error(f"No image files found in '{folder}'") return with create_temp_folder() as temp_folder: try: run_with_thread_pool(tasks, process_file, time.time(), len(tasks), image_processor, temp_folder, False, auto_correct_and_resize) finally: pass - Assistant
import subprocess import shutil import time from pathlib import Path from typing import Optional import numpy as np # --- Configuration and Logging --- # Assuming Config, app, log_error, check_imagemagick, # create_temp_folder, run_with_thread_pool, shared_state, # is_valid_image, open_and_convert_image, process_grayscale_image, # process_color_image, convert_png_to_jpg, update_status are defined elsewhere. # --- Image Resizing --- def resize_image(input_path: Path, output_path: Path) -> Path: """Resize an image using ImageMagick.""" output_path = output_path.with_suffix('.png') try: current_width, current_height = get_image_dimensions(input_path) resize_arg, is_upscaling = determine_resize_parameters(current_width, current_height) command = build_resize_command(input_path, output_path, resize_arg, is_upscaling) execute_command(command, input_path) except subprocess.CalledProcessError as e: log_error(f"ImageMagick resize failed for {input_path}: {e.stderr.strip()}") return output_path def get_image_dimensions(path: Path) -> tuple[int, int]: """Retrieve image dimensions using ImageMagick's identify.""" identify_cmd = [ str(Config.IMAGEMAGICK), str(path), '-format', '%wx%h', 'info:' ] result = subprocess.run( identify_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True ) return map(int, result.stdout.strip().split('x')) def determine_resize_parameters(width: int, height: int) -> tuple[str, bool]: """Determine resize arguments and upscaling status.""" mode = app.RESIZE_MODE.get() maintain_aspect = app.maintain_aspect_ratio.get() if 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 * width / height) elif target_height == 0 and target_width > 0: target_height = int(target_width * height / width) resize_arg = f'{target_width}x{target_height}!' is_upscaling = target_width > width or target_height > height else: # Shortest Side target_size = int(app.RESIZE_SIDE.get()) resize_arg = f'{target_size}x{target_size}^' is_upscaling = target_size > min(width, height) return resize_arg, is_upscaling def build_resize_command(input_path: Path, output_path: Path, resize_arg: str, is_upscaling: bool) -> list[str]: """Construct the ImageMagick resize command.""" base_cmd = [ str(Config.IMAGEMAGICK), str(input_path), ] if is_upscaling: base_cmd += [ '-filter', 'LanczosSharp', '-distort', 'Resize', resize_arg, ] else: base_cmd += [ '-colorspace', 'RGB', '-filter', 'Lanczos2Sharp', '-resize', resize_arg, '-colorspace', 'sRGB', ] base_cmd += [ '-define', 'png:compression-level=5', str(output_path) ] return base_cmd def execute_command(command: list[str], input_path: Path) -> None: """Execute a subprocess command and handle errors.""" result = subprocess.run( command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True ) if result.stderr: log_error(f"ImageMagick: {result.stderr.strip()}") def resize_images(input_folder: Path, output_folder: Path, image_processor: 'ImageProcessor') -> None: """Resize all images in the input folder and save to the output folder.""" try: check_imagemagick() except FileNotFoundError as e: log_error(str(e)) return tasks = [ path for path in input_folder.rglob('*') if path.is_file() and path.suffix.lower() in Config.IMAGE_EXTENSIONS ] if not tasks: log_error(f"No image files found in '{input_folder}'") return with create_temp_folder() as temp_folder: run_with_thread_pool( tasks, process_file, time.time(), len(tasks), image_processor, temp_folder, resize=True ) # --- Image Processing --- def process_file( path: Path, start_time: float, total_files: int, image_processor: 'ImageProcessor', temp_folder: Path, resize: bool = False, auto_correct_and_resize: bool = False ) -> None: """Process a single image file.""" if shared_state.stop_event.is_set(): return if not is_valid_image(path): log_error(f"Invalid image file: {path}") increment_processed_count(start_time, total_files) return try: img = np.array(open_and_convert_image(path)) except (OSError, ValueError) as e: log_error(f"Error reading image {path}: {e}") increment_processed_count(start_time, total_files) return relative_path = path.relative_to(Config.INPUT_FOLDER) temp_output_path = prepare_temp_output_path(temp_folder, relative_path) if auto_correct_and_resize: temp_output_path = handle_auto_correct_and_resize(img, path, image_processor, temp_folder, temp_output_path) elif resize: temp_output_path = resize_image(path, temp_output_path) else: temp_output_path = handle_standard_processing(img, path, image_processor, temp_folder, temp_output_path) final_output_path = move_to_final_output(relative_path, temp_output_path) increment_processed_count(start_time, total_files) def prepare_temp_output_path(temp_folder: Path, relative_path: Path) -> Path: """Prepare the temporary output path.""" temp_output = temp_folder / relative_path temp_output = temp_output.with_suffix('.png') temp_output.parent.mkdir(parents=True, exist_ok=True) return temp_output def handle_auto_correct_and_resize( img: np.ndarray, path: Path, image_processor: 'ImageProcessor', temp_folder: Path, temp_output_path: Path ) -> Path: """Process image with auto-correct and resize.""" if img.ndim == 2 or (img.ndim == 3 and img.shape[2] == 1): intermediate_path, _, _ = process_grayscale_image(img, path, image_processor, temp_folder) else: intermediate_path, _ = process_color_image(img, path, image_processor, temp_folder) return resize_image(intermediate_path, temp_output_path) def handle_standard_processing( img: np.ndarray, path: Path, image_processor: 'ImageProcessor', temp_folder: Path, temp_output_path: Path ) -> Path: """Process image without resizing.""" if img.ndim == 2 or (img.ndim == 3 and img.shape[2] == 1): return process_grayscale_image(img, path, image_processor, temp_folder)[0] return process_color_image(img, path, image_processor, temp_folder)[0] def move_to_final_output(relative_path: Path, temp_output_path: Path) -> Path: """Move the processed image to the final output directory.""" final_output = Config.OUTPUT_FOLDER / relative_path final_output.parent.mkdir(parents=True, exist_ok=True) if app.RESIZE_FORMAT.get() == 'jpg': final_output = final_output.with_suffix('.jpg') convert_png_to_jpg(temp_output_path, final_output) else: final_output = final_output.with_suffix('.png') shutil.move(str(temp_output_path), str(final_output)) return final_output def increment_processed_count(start_time: float, total_files: int) -> None: """Increment the processed files count and update 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 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: check_imagemagick() except FileNotFoundError as e: log_error(str(e)) return tasks = [ path for path in folder.rglob('*') if path.is_file() and path.suffix.lower() in Config.IMAGE_EXTENSIONS ] if not tasks: log_error(f"No image files found in '{folder}'") return with create_temp_folder() as temp_folder: run_with_thread_pool( tasks, process_file, time.time(), len(tasks), image_processor, temp_folder, resize=False, auto_correct_and_resize=auto_correct_and_resize )
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.