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: # --- Utility Functions ---
def log_error(message: str): """Log an error message to the shared state queue.""" shared_state.log_message_queue.put(f"- {message}")
def clear_console(): """Clear the console screen.""" os.system('cls' if os.name == 'nt' else 'clear')
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)
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
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
def check_imagemagick(): """Check if ImageMagick is available in the system.""" if not shutil.which(str(Config.IMAGEMAGICK)): raise FileNotFoundError(f"- ImageMagick executable not found at: {Config.IMAGEMAGICK}")
def check_ffmpeg(): """Check if FFmpeg is available in the system.""" if not shutil.which(str(Config.FFMPEG)): raise FileNotFoundError(f"- FFmpeg executable not found at: {Config.FFMPEG}")
- Assistant
Here's the refactored version of your utility functions, utilizing modern Python 3.12 features for improved readability and efficiency:
import os import shutil from pathlib import Path from PIL import Image from typing import Final # --- Configuration Constants --- IMAGE_EXTENSIONS: Final[frozenset] = frozenset(ext.lower() for ext in Config.IMAGE_EXTENSIONS) # --- Utility Functions --- def log_error(message: str) -> None: """Log an error message to the shared state queue.""" shared_state.log_message_queue.put(f"- {message}") def clear_console() -> None: """Clear the console screen.""" os.system('cls' if os.name == 'nt' else 'clear') 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 IMAGE_EXTENSIONS) 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 def open_and_convert_image(path: Path) -> Image.Image: """Open an image and convert it to an appropriate mode.""" with Image.open(path) as img: match img.mode: case 'P': return img.convert('L') # Convert palette mode to grayscale case 'L' | 'RGB' | 'RGBA': return img.copy() case _: return img.convert('RGB') # Convert other modes to RGB def check_executable(executable: Path, name: str) -> None: """Check if a given executable is available in the system.""" if not shutil.which(str(executable)): raise FileNotFoundError(f"- {name} executable not found at: {executable}") def check_imagemagick() -> None: """Check if ImageMagick is available in the system.""" check_executable(Config.IMAGEMAGICK, "ImageMagick") def check_ffmpeg() -> None: """Check if FFmpeg is available in the system.""" check_executable(Config.FFMPEG, "FFmpeg")Refactoring Highlights:
-
Use of
Finalandfrozensetfor Constants:- Defined
IMAGE_EXTENSIONSas afrozensetto ensure immutability and optimize lookup performance. - Annotated with
Finalto indicate that it should not be modified.
- Defined
-
Pattern Matching with
matchStatement:- Utilized Python 3.10's
matchstatement inopen_and_convert_imagefor clearer and more concise mode handling.
- Utilized Python 3.10's
-
DRY Principle with
check_executable:- Created a generic
check_executablefunction to eliminate redundancy incheck_imagemagickandcheck_ffmpeg.
- Created a generic
-
Type Annotations:
- Ensured all functions have appropriate return type annotations for better type checking and readability.
-
Optimized Imports:
- Imported only necessary modules and used
from ... importwhere appropriate for clarity.
- Imported only necessary modules and used
-
Enhanced Readability:
- Added docstrings to all functions for better documentation.
- Used consistent formatting and naming conventions.
This refactored code leverages modern Python features to enhance performance, maintainability, and readability while adhering to best practices.
-