gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
Simplify next Python code and make it more professional: def setwallpaper(directory,…
- User
Simplify next Python code and make it more professional: def set_wallpaper(directory, monitor): if not os.path.isdir(directory): print(f"Error: Directory '{directory}' does not exist.") sys.exit(1)
try: allowed_extensions = ('.png', '.jpg', '.jpeg', '.jxl', '.webp') valid_files = [file for file in os.listdir(directory) if file.lower().endswith(allowed_extensions)] random_background = random.choice(valid_files) wallpaper_path = os.path.join(directory, random_background) original_image = Image.open(wallpaper_path) monitor_width, monitor_height = map(int, get_monitor_resolution().split('x')) background = Image.new('RGB', (monitor_width, monitor_height), (0, 0, 0)) aspect_ratio = original_image.width / original_image.height new_height = monitor_height new_width = int(aspect_ratio * new_height) if new_width > monitor_width: new_width = monitor_width new_height = int(monitor_width / aspect_ratio) resized_image = original_image.resize((new_width, new_height), Image.Resampling.LANCZOS) position = ((monitor_width - new_width) // 2, (monitor_height - new_height) // 2) background.paste(resized_image, position) background.save("/tmp/hypermalevichtmp.jpg") subprocess.run(["hyprctl", "hyprpaper", "unload", "/tmp/hypermalevichtmp.jpg"], check=True) subprocess.run(["hyprctl", "hyprpaper", "preload", "/tmp/hypermalevichtmp.jpg"], check=True) subprocess.run(["hyprctl", "hyprpaper", "wallpaper", f"{monitor}, /tmp/hypermalevichtmp.jpg"], check=True) subprocess.run(["hyprctl", "hyprpaper", "unload", "unused"], check=True) os.system("rm /tmp/hypermalevichtmp.jpg") print(f"Successfully set wallpaper to: {wallpaper_path}") except Exception as e: print(f"Error while setting wallpaper: {e}") - Assistant
Here's a simplified and more professional version of your Python code. I've added some enhancements like better exception handling, separated logic into smaller functions for better readability, and ensured that resources are properly managed.
import os import sys import random import subprocess from PIL import Image def validate_directory(directory): if not os.path.isdir(directory): print(f"Error: Directory '{directory}' does not exist.") sys.exit(1) def get_valid_files(directory, allowed_extensions): return [ file for file in os.listdir(directory) if file.lower().endswith(allowed_extensions) ] def resize_image(image, monitor_resolution): aspect_ratio = image.width / image.height monitor_width, monitor_height = monitor_resolution new_height = monitor_height new_width = int(aspect_ratio * new_height) if new_width > monitor_width: new_width = monitor_width new_height = int(monitor_width / aspect_ratio) return image.resize((new_width, new_height), Image.LANCZOS) def create_background_image(image, monitor_resolution): background = Image.new('RGB', monitor_resolution, (0, 0, 0)) new_image = resize_image(image, monitor_resolution) position = ((monitor_resolution[0] - new_image.width) // 2, (monitor_resolution[1] - new_image.height) // 2) background.paste(new_image, position) return background def set_wallpaper(directory, monitor): validate_directory(directory) allowed_extensions = ('.png', '.jpg', '.jpeg', '.jxl', '.webp') try: valid_files = get_valid_files(directory, allowed_extensions) if not valid_files: print(f"No valid wallpaper files found in '{directory}'.") return random_background = random.choice(valid_files) wallpaper_path = os.path.join(directory, random_background) with Image.open(wallpaper_path) as original_image: monitor_resolution = tuple(map(int, get_monitor_resolution().split('x'))) background_image = create_background_image(original_image, monitor_resolution) temp_filepath = "/tmp/hypermalevichtmp.jpg" background_image.save(temp_filepath) commands = [ ["hyprctl", "hyprpaper", "unload", temp_filepath], ["hyprctl", "hyprpaper", "preload", temp_filepath], ["hyprctl", "hyprpaper", "wallpaper", f"{monitor}, {temp_filepath}"], ["hyprctl", "hyprpaper", "unload", "unused"] ] for command in commands: subprocess.run(command, check=True) print(f"Successfully set wallpaper to: {wallpaper_path}") except Exception as e: print(f"Error while setting wallpaper: {e}") finally: if os.path.exists(temp_filepath): os.remove(temp_filepath) def get_monitor_resolution(): # Implement this function to return the current monitor resolution in 'widthxheight' format passKey Changes:
- Modular Functions: The code is broken down into smaller functions (
validate_directory,get_valid_files,resize_image, andcreate_background_image). This modular design enhances readability and maintainability. - Resource Management: Used a
withstatement to ensure that the image file is properly closed after use. - Improved Error Handling: Graceful handling of scenarios where no valid wallpaper files are found, along with improved exception messaging.
- Constants: Moved the allowed extensions into a variable for easier management.
- Clean-Up Logic: The temporary file is deleted in a
finallyblock to ensure it gets cleaned up, even if an exception occurs during processing.
Make sure to implement the
get_monitor_resolutionfunction to return the screen resolution in the expected format (width x height). - Modular Functions: The code is broken down into smaller functions (