import os import asyncio import aiohttp from PIL import Image 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_image_id_image_tags_path_tuple_dict(image_dir): if not os.path.isdir(image_dir): raise FileNotFoundError(f"\"{image_dir}\" is not a directory!") image_id_image_tags_path_tuple_dict = {} for path in os.listdir(image_dir): image_id, ext = os.path.splitext(path) if ext == ".txt": continue path = os.path.join(image_dir, path) if not os.path.isfile(path): continue tags_path = os.path.splitext(path)[0] + ".txt" if not os.path.isfile(tags_path): continue image_id_image_tags_path_tuple_dict[image_id] = (path, tags_path) return image_id_image_tags_path_tuple_dict def get_existing_image_id_set(image_dir): return set(get_image_id_image_tags_path_tuple_dict(image_dir)) def get_session(timeout=None, cookies=None): kwargs = {"connector": aiohttp.TCPConnector(limit=0, ttl_dns_cache=600), "cookies": cookies} if timeout is not None: kwargs["timeout"] = aiohttp.ClientTimeout(total=timeout) return aiohttp.ClientSession(**kwargs) def get_model_tags(model_tags_path): if not os.path.isfile(model_tags_path): raise FileNotFoundError(f"\"{model_tags_path}\" is not a file, please place one there!") index_tag_dict = {} with open(model_tags_path, "r", encoding="utf8") as model_tags_file: for line in model_tags_file: line = line.split() if len(line) != 2: continue index_tag_dict[int(line[0])] = line[1] if len(index_tag_dict) <= 0: return [] sorted_index_tag_tuple_list = sorted(index_tag_dict.items(), key=lambda x: x[0]) if len(sorted_index_tag_tuple_list) != sorted_index_tag_tuple_list[-1][0] + 1: raise ValueError(f"The index specified in \"{model_tags_path}\" is not continuous!") return [tag for _, tag in sorted_index_tag_tuple_list] def get_tags_set(tags_path): if not os.path.isfile(tags_path): raise FileNotFoundError(f"\"{tags_path}\" is not a file!") with open(tags_path, "r", encoding="utf8") as tags_file: tags_text = tags_file.read() tags_set = set() for tag in tags_text.split(","): tag = tag.strip() if tag: tag = tag.replace(" ", "_") if tag == "nsfw": tag = "rating:explicit" elif tag == "qfw": tag = "rating:questionable" elif tag == "sfw": tag = "rating:safe" tags_set.add(tag) return tags_set