import os import sys import signal import asyncio from PIL import Image SIGINT_COUNTER = 0 def sigint_handler(signum, frame): global SIGINT_COUNTER SIGINT_COUNTER += 1 print() if SIGINT_COUNTER >= 3: print("Script force quit by user, exiting...") sys.exit(1) def register_sigint_callback(): signal.signal(signal.SIGINT, sigint_handler) def validate_image(image_path, tags_path, width=None, height=None, convert_to_avif=False): new_path = None try: with Image.open(image_path) as img: save_kwargs = {} if isinstance(width, int) and width > 0 and isinstance(height, int) and height > 0: img = img.resize((width, height)) new_path = image_path if convert_to_avif: import pillow_avif save_kwargs["quality"] = 50 new_path = os.path.splitext(image_path)[0] + ".avif" if new_path is not None: img.load() img.save(new_path, **save_kwargs) else: img.verify() if new_path is not None and os.path.isfile(new_path) and os.path.realpath(new_path) != os.path.realpath(image_path): os.remove(image_path) return True except Exception as e: print(f"Error validating image {image_path}: {e}") try: os.remove(image_path) except Exception as e: print("Error deleting image file:", e) try: os.remove(tags_path) print(f"Deleted invalid image and tags files: {image_path}, {tags_path}") except Exception as e: print("Error deleting tags file:", e) try: if new_path is not None and os.path.isfile(new_path): os.remove(new_path) print("Deleted invalid new image file:", new_path) except Exception as e: print("Error deleting new image file:", e) return False async def submit_validation(thread_pool, image_path, tags_path, width=None, height=None, convert_to_avif=False): return await asyncio.wrap_future(thread_pool.submit(validate_image, image_path, tags_path, width, height, convert_to_avif)) def get_existing_image_tags_set(image_dir): if not os.path.isdir(image_dir): return set() existing_image_tags = set() for path in os.listdir(image_dir): image_id, ext = os.path.splitext(path) if ext != ".txt": continue existing_image_tags.add(image_id) return existing_image_tags