codeShare commited on
Commit
f1269a7
·
verified ·
1 Parent(s): 5a93a2f

Upload sankaku_database_browse_and_caption

Browse files
sankaku_database_browse_and_caption ADDED
@@ -0,0 +1 @@
 
 
1
+ {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[],"gpuType":"T4","authorship_tag":"ABX9TyPqOgaBUPcYPq4DKl26UfD+"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"},"accelerator":"GPU"},"cells":[{"cell_type":"markdown","source":[" **Note: ** when running notebook in the T4 the first time the code will install transformers , and auto restart. This may prompt a message that the instance crashed for an unknown reason. Run the cell again , and it will work fine. The restart is required for transformers package installation."],"metadata":{"id":"eQREjM7BhRn1"}},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"QOdlJl3Hf2YX","outputId":"4b810d69-43d9-47c0-b29d-edb7627e8469"},"outputs":[{"output_type":"stream","name":"stdout","text":["Installed Transformers: 4.48.3\n","Installed Tokenizers: 0.21.0\n","Loaded search seed: 2990522557\n","\n","======================================================================\n","DISCOVERING SANKAKU PARQUET FILES\n","======================================================================\n"]},{"output_type":"stream","name":"stderr","text":["The argument `trust_remote_code` is to be used with Auto classes. It has no effect here and is ignored.\n"]},{"output_type":"stream","name":"stdout","text":["Discovered Parquet files: 11\n","\n","Available files:\n"," tables/images-1.parquet\n"," tables/images-2.parquet\n"," tables/images-3.parquet\n"," tables/images-4.parquet\n"," tables/images-5.parquet\n"," tables/images-6.parquet\n"," tables/images-7.parquet\n"," tables/images-8.parquet\n"," tables/images-9.parquet\n"," tables/images-10.parquet\n"," tables/images-11.parquet\n","\n","Randomized Parquet traversal enabled.\n","\n","Parquet search order:\n","001. tables/images-3.parquet\n","002. tables/images-9.parquet\n","003. tables/images-6.parquet\n","004. tables/images-5.parquet\n","005. tables/images-10.parquet\n","006. tables/images-11.parquet\n","007. tables/images-2.parquet\n","008. tables/images-7.parquet\n","009. tables/images-8.parquet\n","010. tables/images-4.parquet\n","011. tables/images-1.parquet\n","\n","Starting Parquet:\n","tables/images-3.parquet\n","\n","======================================================================\n","SANKAKU IMAGE SEARCH\n","======================================================================\n","Repository: deepghs/sankaku_full\n","Available Parquet files: 11\n","\n","Main search query: 3D -completely_nude -ai-created \n","Required substrings: ['3d']\n","Excluded substrings: ['completely_nude', 'ai-created']\n","\n","Additional words: []\n","Additional matching mode: OR\n","\n","Images requested: 100\n","Minimum favourites: 105\n","Maximum rows: 5000000\n","Batch size: 5000\n","\n","Random search enabled: True\n","Search seed: 2990522557\n","\n","Furrance captioner: True\n","\n","======================================================================\n","LOADING FURRANCE-2-LARGE\n","======================================================================\n","Transformers: 4.48.3\n","Tokenizers: 0.21.0\n","GPU: Tesla T4\n","Device: cuda\n","Dtype: torch.float16\n","Model: lodestone-horizon/furrence2-large\n"]}],"source":["# ============================================================\n","# SANKAKU SEARCH + ORIGINAL IMAGE RETRIEVAL + OPTIONAL FURRANCE\n","# ============================================================\n","# Install CheeseChaser for native Sankaku archive retrieval.\n","\n","\n","# ============================================================\n","# COLAB PARAMETERS\n","# ============================================================\n","\n","SEARCH_QUERY = \"3D -completely_nude -ai-created \" #@param {type:\"string\"}\n","\n","ADDITIONAL_WORDS = \"\" #@param {type:\"string\"}\n","\n","IMAGE_COUNT = 100 #@param {type:\"slider\", min:1, max:500, step:1}\n","\n","MIN_FAVOURITES = 105 #@param {type:\"slider\", min:0, max:1000, step:1}\n","\n","RANDOM_SEARCH_START = True #@param {type:\"boolean\"}\n","\n","ENABLE_FURRANCE_CAPTIONER = True #@param {type:\"boolean\"}\n","\n","\n","# ============================================================\n","# DEPENDENCY CHECK AND AUTOMATIC RUNTIME RESTART\n","# ============================================================\n","\n","import os\n","import sys\n","import subprocess\n","import signal\n","import importlib.metadata\n","\n","REQUIRED_TRANSFORMERS = \"4.48.3\"\n","REQUIRED_TOKENIZERS = \"0.21.0\"\n","\n","\n","def get_installed_version(package):\n","\n"," try:\n"," return importlib.metadata.version(package)\n","\n"," except importlib.metadata.PackageNotFoundError:\n"," return None\n","\n","\n","def install_dependencies():\n","\n"," print(\"=\" * 70)\n"," print(\"INSTALLING DEPENDENCIES\")\n"," print(\"=\" * 70)\n","\n"," packages = [\n"," \"cheesechaser\",\n"," \"pillow\",\n"," \"matplotlib\",\n"," \"accelerate\",\n"," \"timm\",\n"," \"safetensors\",\n"," \"einops\",\n"," \"hf_xet\",\n"," \"pyarrow\",\n"," \"pandas\",\n"," \"huggingface_hub\",\n"," ]\n","\n"," if ENABLE_FURRANCE_CAPTIONER:\n","\n"," packages.extend([\n"," f\"transformers=={REQUIRED_TRANSFORMERS}\",\n"," f\"tokenizers=={REQUIRED_TOKENIZERS}\",\n"," ])\n","\n"," subprocess.run(\n"," [\n"," sys.executable,\n"," \"-m\",\n"," \"pip\",\n"," \"install\",\n"," \"-q\",\n"," \"--upgrade\",\n"," *packages,\n"," ],\n"," check=True,\n"," )\n","\n","\n","if ENABLE_FURRANCE_CAPTIONER:\n","\n"," installed_transformers = get_installed_version(\n"," \"transformers\"\n"," )\n","\n"," installed_tokenizers = get_installed_version(\n"," \"tokenizers\"\n"," )\n","\n"," print(\"Installed Transformers:\", installed_transformers)\n"," print(\"Installed Tokenizers:\", installed_tokenizers)\n","\n"," transformers_ok = (\n"," installed_transformers == REQUIRED_TRANSFORMERS\n"," )\n","\n"," tokenizers_ok = (\n"," installed_tokenizers == REQUIRED_TOKENIZERS\n"," )\n","\n"," if not transformers_ok or not tokenizers_ok:\n","\n"," print(\"\\n\" + \"=\" * 70)\n"," print(\"INCOMPATIBLE FURRANCE DEPENDENCIES DETECTED\")\n"," print(\"=\" * 70)\n","\n"," print(\"Installing required versions:\")\n"," print(\"Transformers:\", REQUIRED_TRANSFORMERS)\n"," print(\"Tokenizers:\", REQUIRED_TOKENIZERS)\n","\n"," install_dependencies()\n","\n"," print(\"\\nDependency installation completed.\")\n"," print(\"Automatically restarting Colab runtime...\")\n"," print(\"\\nRerun this cell after the runtime restarts.\")\n","\n"," # Force a Colab runtime restart.\n"," # This prevents old imported modules from remaining\n"," # in memory after the dependency replacement.\n","\n"," os.kill(\n"," os.getpid(),\n"," signal.SIGKILL,\n"," )\n","\n","else:\n","\n"," print(\"Furrance disabled. Skipping Transformers check.\")\n","\n"," install_dependencies()\n","\n","\n","# ============================================================\n","# IMPORTS\n","# ============================================================\n","\n","import gc\n","import io\n","import re\n","import html\n","import json\n","import base64\n","import random\n","import shutil\n","import zipfile\n","import tempfile\n","import warnings\n","import math\n","\n","import pyarrow.parquet as pq\n","import pandas as pd\n","\n","from PIL import Image, ImageOps\n","\n","from huggingface_hub import (\n"," hf_hub_download,\n"," HfApi,\n",")\n","\n","from google.colab import (\n"," userdata,\n"," output,\n"," files,\n",")\n","\n","from IPython.display import display, HTML\n","\n","from cheesechaser.datapool.sankaku import SankakuDataPool\n","\n","warnings.filterwarnings(\"ignore\")\n","\n","\n","# ============================================================\n","# SEARCH SYNTAX\n","# ============================================================\n","#@markdown ### Using Furrance captioning requires enabling a T4 GPU.\n","#@markdown\n","#@markdown ### Main search syntax\n","#@markdown Space-separated words must ALL match.\n","#@markdown\n","#@markdown - `peach mario` — both substrings must occur.\n","#@markdown - `peach+mario` — equivalent to `peach mario`.\n","#@markdown - `peach,mario` — equivalent to `peach mario`.\n","#@markdown - `peach.mario` — equivalent to `peach mario`.\n","#@markdown\n","#@markdown ### Exclusion syntax\n","#@markdown A minus sign at the beginning of the query or immediately\n","#@markdown after a space excludes the following term.\n","#@markdown\n","#@markdown - `-ai-created` — exclude ai-created.\n","#@markdown - `peach -ai-created` — require peach and exclude ai-created.\n","#@markdown - `peach mario -ai-created` — require peach AND mario.\n","#@markdown\n","#@markdown A hyphen inside a tag name is preserved.\n","#@markdown\n","#@markdown - `ai-created` — search for ai-created.\n","#@markdown - `some-tag-name` — search for some-tag-name.\n","#@markdown\n","#@markdown ### Additional words\n","#@markdown At least ONE additional word must match.\n","#@markdown\n","#@markdown - `rosalina daisy peach` — any one is sufficient.\n","#@markdown\n","#@markdown ### Random search\n","#@markdown Randomizes the order of all available Parquet files.\n","#@markdown The seed is read from `/content/sankaku_search_seed.txt`.\n","#@markdown\n","#@markdown If empty, a new numerical seed is generated.\n","#@markdown The search starts at a randomized Parquet file and\n","#@markdown continues through the remaining files in randomized order.\n","\n","\n","# ============================================================\n","# CONFIGURATION\n","# ============================================================\n","\n","REPO_ID = \"deepghs/sankaku_full\"\n","\n","REPO_TYPE = \"dataset\"\n","\n","TABLE_DIRECTORY = \"tables\"\n","\n","PARQUET_PATTERN = re.compile(\n"," r\"^tables/images-(\\d+)\\.parquet$\"\n",")\n","\n","TEST_IMAGE_COUNT = int(IMAGE_COUNT)\n","\n","TEST_MIN_FAVOURITES = int(MIN_FAVOURITES)\n","\n","MAX_ROWS_TO_EXAMINE = 5_000_000\n","\n","BATCH_SIZE = 5000\n","\n","SEED_FILE = \"/content/sankaku_search_seed.txt\"\n","\n","GRID_MIN_WIDTH = 220\n","\n","IMAGE_HEIGHT = 260\n","\n","THUMBNAIL_MAX_SIZE = (1000, 1000)\n","\n","THUMBNAIL_JPEG_QUALITY = 85\n","\n","EXPORT_IMAGE_MAX_SIZE = (1024, 1024)\n","\n","EXPORT_JPEG_QUALITY = 95\n","\n","OUTPUT_FILE = \"/content/sankaku_search_results.csv\"\n","\n","ZIP_FILE = \"/content/sankaku_image_text_pairs.zip\"\n","\n","DEMO_DIR = \"/content/furrence_demo\"\n","\n","EXPORT_DIR = tempfile.mkdtemp(\n"," prefix=\"sankaku_export_\"\n",")\n","\n","\n","# ============================================================\n","# LOAD OR GENERATE NUMERICAL SEARCH SEED\n","# ============================================================\n","\n","def load_search_seed():\n","\n"," if not os.path.isfile(SEED_FILE):\n","\n"," with open(SEED_FILE, \"w\", encoding=\"utf-8\") as f:\n"," f.write(\"\")\n","\n"," with open(SEED_FILE, \"r\", encoding=\"utf-8\") as f:\n"," seed_text = f.read().strip()\n","\n"," if seed_text:\n","\n"," try:\n"," seed = int(seed_text)\n","\n"," except ValueError:\n"," raise ValueError(\n"," f\"{SEED_FILE} must contain an integer seed, or be empty.\"\n"," )\n","\n"," if seed < 0 or seed > 2**64 - 1:\n"," raise ValueError(\n"," \"The seed must be between 0 and 18446744073709551615.\"\n"," )\n","\n"," print(\"Loaded search seed:\", seed)\n","\n"," else:\n","\n"," seed = random.SystemRandom().randint(\n"," 0,\n"," 2**32 - 1,\n"," )\n","\n"," with open(SEED_FILE, \"w\", encoding=\"utf-8\") as f:\n"," f.write(str(seed))\n","\n"," print(\"Generated new random search seed:\", seed)\n"," print(\"Saved seed to:\", SEED_FILE)\n","\n"," return seed\n","\n","\n","ACTIVE_SEARCH_SEED = load_search_seed()\n","\n","search_rng = random.Random(\n"," ACTIVE_SEARCH_SEED\n",")\n","\n","\n","# ============================================================\n","# AUTHENTICATION\n","# ============================================================\n","\n","HF_TOKEN = userdata.get(\"HF_TOKEN\")\n","\n","if not HF_TOKEN:\n","\n"," raise RuntimeError(\n"," \"HF_TOKEN was not found in Colab Secrets.\"\n"," )\n","\n","os.environ[\"HF_TOKEN\"] = HF_TOKEN\n","\n","os.environ[\"HF_HUB_ENABLE_HF_TRANSFER\"] = \"1\"\n","\n","\n","# ============================================================\n","# DISCOVER ALL AVAILABLE PARQUET FILES\n","# ============================================================\n","\n","print(\"\\n\" + \"=\" * 70)\n","print(\"DISCOVERING SANKAKU PARQUET FILES\")\n","print(\"=\" * 70)\n","\n","api = HfApi(\n"," token=HF_TOKEN\n",")\n","\n","repository_files = api.list_repo_files(\n"," repo_id=REPO_ID,\n"," repo_type=REPO_TYPE,\n",")\n","\n","IMAGE_FILES = []\n","\n","for filename in repository_files:\n","\n"," if PARQUET_PATTERN.match(filename):\n","\n"," IMAGE_FILES.append(filename)\n","\n","\n","def parquet_number(filename):\n","\n"," match = PARQUET_PATTERN.match(filename)\n","\n"," if match:\n"," return int(match.group(1))\n","\n"," return 0\n","\n","\n","IMAGE_FILES.sort(\n"," key=parquet_number\n",")\n","\n","if not IMAGE_FILES:\n","\n"," raise RuntimeError(\n"," \"No images-*.parquet files were discovered \"\n"," f\"in {REPO_ID}.\"\n"," )\n","\n","print(\"Discovered Parquet files:\", len(IMAGE_FILES))\n","\n","print(\"\\nAvailable files:\")\n","\n","for filename in IMAGE_FILES:\n"," print(\" \", filename)\n","\n","\n","# ============================================================\n","# DETERMINE PARQUET SEARCH ORDER\n","# ============================================================\n","\n","PARQUET_SEARCH_ORDER = list(\n"," IMAGE_FILES\n",")\n","\n","if RANDOM_SEARCH_START:\n","\n"," search_rng.shuffle(\n"," PARQUET_SEARCH_ORDER\n"," )\n","\n"," print(\"\\nRandomized Parquet traversal enabled.\")\n","\n","else:\n","\n"," print(\"\\nSequential Parquet traversal enabled.\")\n","\n","print(\"\\nParquet search order:\")\n","\n","for index, filename in enumerate(\n"," PARQUET_SEARCH_ORDER,\n"," start=1,\n","):\n","\n"," print(\n"," f\"{index:03d}. {filename}\"\n"," )\n","\n","print(\"\\nStarting Parquet:\")\n","print(PARQUET_SEARCH_ORDER[0])\n","\n","\n","# ============================================================\n","# QUERY TOKENIZATION\n","# ============================================================\n","\n","def split_search_words(text):\n","\n"," if not text:\n"," return []\n","\n"," return [\n"," word.strip().lower()\n"," for word in re.split(\n"," r\"[\\s+,\\.]+\",\n"," str(text),\n"," )\n"," if word.strip()\n"," ]\n","\n","\n","# ============================================================\n","# PARSE MAIN SEARCH\n","# ============================================================\n","\n","def parse_search_query(query):\n","\n"," required = []\n","\n"," excluded = []\n","\n"," query = str(query).lower()\n","\n"," matches = re.finditer(\n"," r\"[^\\s+,\\.]+\",\n"," query,\n"," )\n","\n"," for match in matches:\n","\n"," term = match.group(0).strip()\n","\n"," if not term:\n"," continue\n","\n"," starts_with_operator = (\n"," term.startswith(\"-\")\n"," and (\n"," match.start() == 0\n"," or query[match.start() - 1].isspace()\n"," )\n"," )\n","\n"," if starts_with_operator:\n","\n"," word = term[1:].strip()\n","\n"," if word:\n"," excluded.append(word)\n","\n"," else:\n","\n"," required.append(term)\n","\n"," return required, excluded\n","\n","\n","REQUIRED_TEST_TAGS, EXCLUDED_TEST_TAGS = (\n"," parse_search_query(SEARCH_QUERY)\n",")\n","\n","ADDITIONAL_TEST_TAGS = split_search_words(\n"," ADDITIONAL_WORDS\n",")\n","\n","\n","if (\n"," not REQUIRED_TEST_TAGS\n"," and not EXCLUDED_TEST_TAGS\n"," and not ADDITIONAL_TEST_TAGS\n","):\n","\n"," raise ValueError(\n"," \"Enter at least one main search term or additional word.\"\n"," )\n","\n","\n","# ============================================================\n","# SEARCH CONFIGURATION SUMMARY\n","# ============================================================\n","\n","print(\"\\n\" + \"=\" * 70)\n","print(\"SANKAKU IMAGE SEARCH\")\n","print(\"=\" * 70)\n","\n","print(\"Repository:\", REPO_ID)\n","\n","print(\"Available Parquet files:\", len(IMAGE_FILES))\n","\n","print(\"\\nMain search query:\", SEARCH_QUERY or \"(None)\")\n","\n","print(\"Required substrings:\", REQUIRED_TEST_TAGS)\n","\n","print(\"Excluded substrings:\", EXCLUDED_TEST_TAGS)\n","\n","print(\"\\nAdditional words:\", ADDITIONAL_TEST_TAGS)\n","\n","print(\"Additional matching mode: OR\")\n","\n","print(\"\\nImages requested:\", TEST_IMAGE_COUNT)\n","\n","print(\"Minimum favourites:\", TEST_MIN_FAVOURITES)\n","\n","print(\"Maximum rows:\", MAX_ROWS_TO_EXAMINE)\n","\n","print(\"Batch size:\", BATCH_SIZE)\n","\n","print(\"\\nRandom search enabled:\", RANDOM_SEARCH_START)\n","\n","print(\"Search seed:\", ACTIVE_SEARCH_SEED)\n","\n","print(\"\\nFurrance captioner:\", ENABLE_FURRANCE_CAPTIONER)\n","\n","\n","# ============================================================\n","# TAG NORMALIZATION\n","# ============================================================\n","\n","def tags_to_search_text(tags):\n","\n"," if tags is None:\n"," return \"\"\n","\n"," if isinstance(tags, (list, tuple, set)):\n","\n"," text = \" \".join(\n"," str(tag)\n"," for tag in tags\n"," if tag is not None\n"," )\n","\n"," else:\n","\n"," text = str(tags)\n","\n"," return text.lower()\n","\n","\n","def tags_to_display_list(tags):\n","\n"," if tags is None:\n"," return []\n","\n"," if isinstance(tags, (list, tuple, set)):\n","\n"," return [\n"," str(tag)\n"," for tag in tags\n"," if tag is not None\n"," ]\n","\n"," return str(tags).split()\n","\n","\n","# ============================================================\n","# MATCHING LOGIC\n","# ============================================================\n","\n","def matches_tag_conditions(tags):\n","\n"," tag_text = tags_to_search_text(tags)\n","\n"," if not tag_text:\n"," return False\n","\n"," if not all(\n"," term in tag_text\n"," for term in REQUIRED_TEST_TAGS\n"," ):\n"," return False\n","\n"," if any(\n"," term in tag_text\n"," for term in EXCLUDED_TEST_TAGS\n"," ):\n"," return False\n","\n"," if ADDITIONAL_TEST_TAGS:\n","\n"," if not any(\n"," term in tag_text\n"," for term in ADDITIONAL_TEST_TAGS\n"," ):\n"," return False\n","\n"," return True\n","\n","\n","# ============================================================\n","# FAVOURITES NORMALIZATION\n","# ============================================================\n","\n","def normalize_fav_count(value):\n","\n"," if value is None:\n"," return 0\n","\n"," try:\n","\n"," if pd.isna(value):\n"," return 0\n","\n"," return max(0, int(value))\n","\n"," except (\n"," TypeError,\n"," ValueError,\n"," OverflowError,\n"," ):\n","\n"," return 0\n","\n","\n","# ============================================================\n","# OPTIONAL: LOAD FURRANCE-2-LARGE\n","# ============================================================\n","\n","furrence_model = None\n","\n","furrence_processor = None\n","\n","furrence_device = None\n","\n","furrence_dtype = None\n","\n","\n","def load_furrence():\n","\n"," global furrence_model\n"," global furrence_processor\n"," global furrence_device\n"," global furrence_dtype\n","\n"," if furrence_model is not None:\n"," return\n","\n"," print(\"\\n\" + \"=\" * 70)\n"," print(\"LOADING FURRANCE-2-LARGE\")\n"," print(\"=\" * 70)\n","\n"," import torch\n"," import transformers\n"," import tokenizers\n","\n"," print(\"Transformers:\", transformers.__version__)\n","\n"," print(\"Tokenizers:\", tokenizers.__version__)\n","\n"," if transformers.__version__ != REQUIRED_TRANSFORMERS:\n","\n"," raise RuntimeError(\n"," \"Incorrect Transformers version. \"\n"," \"Restart the runtime and rerun this cell.\"\n"," )\n","\n"," if tokenizers.__version__ != REQUIRED_TOKENIZERS:\n","\n"," raise RuntimeError(\n"," \"Incorrect Tokenizers version. \"\n"," \"Restart the runtime and rerun this cell.\"\n"," )\n","\n"," if not torch.cuda.is_available():\n","\n"," raise RuntimeError(\n"," \"Furrance requires a CUDA GPU. \"\n"," \"Enable a T4 GPU in Colab.\"\n"," )\n","\n"," gpu_name = torch.cuda.get_device_name(0)\n","\n"," print(\"GPU:\", gpu_name)\n","\n"," furrence_device = \"cuda\"\n","\n"," furrence_dtype = torch.float16\n","\n"," if not os.path.isdir(DEMO_DIR):\n","\n"," subprocess.run(\n"," [\n"," \"git\",\n"," \"clone\",\n"," \"-q\",\n"," \"https://huggingface.co/spaces/Thouph/Furrence-2-Large-Demo\",\n"," DEMO_DIR,\n"," ],\n"," check=True,\n"," )\n","\n"," if DEMO_DIR not in sys.path:\n","\n"," sys.path.insert(\n"," 0,\n"," DEMO_DIR,\n"," )\n","\n"," from florence2_implementation.modeling_florence2 import (\n"," Florence2ForConditionalGeneration\n"," )\n","\n"," from transformers import AutoProcessor\n","\n"," model_id = \"lodestone-horizon/furrence2-large\"\n","\n"," print(\"Device:\", furrence_device)\n","\n"," print(\"Dtype:\", furrence_dtype)\n","\n"," print(\"Model:\", model_id)\n","\n"," furrence_model = (\n"," Florence2ForConditionalGeneration.from_pretrained(\n"," model_id,\n"," torch_dtype=furrence_dtype,\n"," trust_remote_code=True,\n"," )\n"," .to(furrence_device)\n"," .eval()\n"," )\n","\n"," furrence_processor = AutoProcessor.from_pretrained(\n"," os.path.join(\n"," DEMO_DIR,\n"," \"florence2_implementation\",\n"," ),\n"," trust_remote_code=True,\n"," )\n","\n"," print(\"Furrance loaded successfully.\")\n","\n"," print(\n"," \"GPU memory allocated:\",\n"," f\"{torch.cuda.memory_allocated() / 1024**3:.2f} GB\",\n"," )\n","\n","\n","# ============================================================\n","# FURRANCE CAPTION GENERATION\n","# ============================================================\n","\n","def furrence_caption(\n"," image: Image.Image,\n"," tags,\n"," length: int = 120,\n"," max_new_tokens: int = 512,\n",") -> str:\n","\n"," import torch\n","\n"," if isinstance(tags, str):\n","\n"," tags = tags.replace(\",\", \" \").split()\n","\n"," tag_list = [\n"," str(tag).strip()\n"," for tag in tags\n"," if str(tag).strip()\n"," ]\n","\n"," tag_str = \" \".join(tag_list)\n","\n"," prompt = (\n"," f\"{tag_str}\\n\"\n"," f\"species: \\n\"\n"," f\"length: {length}\\n\\n\"\n"," f\"STYLE1 FURRY CAPTION:\"\n"," )\n","\n"," inputs = furrence_processor(\n"," text=prompt,\n"," images=image.convert(\"RGB\"),\n"," return_tensors=\"pt\",\n"," ).to(furrence_device)\n","\n"," if \"pixel_values\" in inputs:\n","\n"," inputs[\"pixel_values\"] = inputs[\n"," \"pixel_values\"\n"," ].to(furrence_dtype)\n","\n"," with torch.inference_mode():\n","\n"," generated_ids = furrence_model.generate(\n"," input_ids=inputs[\"input_ids\"],\n"," attention_mask=inputs[\"attention_mask\"],\n"," pixel_values=inputs[\"pixel_values\"],\n"," max_new_tokens=max_new_tokens,\n"," num_beams=3,\n"," do_sample=False,\n"," early_stopping=False,\n"," )\n","\n"," caption = furrence_processor.batch_decode(\n"," generated_ids,\n"," skip_special_tokens=True,\n"," )[0]\n","\n"," return re.sub(\n"," r\"\\s+\",\n"," \" \",\n"," caption,\n"," ).strip()\n","\n","\n","# ============================================================\n","# INITIALIZE OPTIONAL CAPTIONER\n","# ============================================================\n","\n","if ENABLE_FURRANCE_CAPTIONER:\n","\n"," load_furrence()\n","\n","else:\n","\n"," print(\n"," \"\\nFurrance captioning disabled. \"\n"," \"Skipping model download.\"\n"," )\n","\n","\n","# ============================================================\n","# INITIALIZE NATIVE SANKAKU DATAPOOL\n","# ============================================================\n","\n","print(\"\\n\" + \"=\" * 70)\n","print(\"INITIALIZING SANKAKU DATAPOOL\")\n","print(\"=\" * 70)\n","\n","pool = SankakuDataPool(\n"," hf_token=HF_TOKEN\n",")\n","\n","print(\"DataPool initialized.\")\n","\n","\n","# ============================================================\n","# FIND IMAGE FILE\n","# ============================================================\n","\n","def find_image_file(directory):\n","\n"," candidates = []\n","\n"," for root, dirs, files_in_dir in os.walk(directory):\n","\n"," for filename in files_in_dir:\n","\n"," if filename.endswith(\"_metainfo.json\"):\n"," continue\n","\n"," filepath = os.path.join(\n"," root,\n"," filename,\n"," )\n","\n"," candidates.append(filepath)\n","\n"," if not candidates:\n","\n"," raise RuntimeError(\n"," \"SankakuDataPool returned no files.\"\n"," )\n","\n"," preferred_extensions = {\n"," \".jpg\",\n"," \".jpeg\",\n"," \".png\",\n"," \".webp\",\n"," \".gif\",\n"," \".bmp\",\n"," \".tif\",\n"," \".tiff\",\n"," }\n","\n"," candidates.sort(\n"," key=lambda path: (\n"," os.path.splitext(path)[1].lower()\n"," not in preferred_extensions,\n"," path,\n"," )\n"," )\n","\n"," for filepath in candidates:\n","\n"," try:\n","\n"," with Image.open(filepath) as image:\n"," image.verify()\n","\n"," return filepath\n","\n"," except Exception:\n"," continue\n","\n"," raise RuntimeError(\n"," \"No decodable image was returned.\"\n"," )\n","\n","\n","# ============================================================\n","# MAKE THUMBNAIL DATA URI\n","# ============================================================\n","\n","def make_thumbnail_data_uri(image_path):\n","\n"," with Image.open(image_path) as source:\n","\n"," source.load()\n","\n"," source = ImageOps.exif_transpose(source)\n","\n"," thumbnail = source.convert(\"RGB\")\n","\n"," thumbnail.thumbnail(\n"," THUMBNAIL_MAX_SIZE,\n"," Image.Resampling.LANCZOS,\n"," )\n","\n"," output_buffer = io.BytesIO()\n","\n"," thumbnail.save(\n"," output_buffer,\n"," format=\"JPEG\",\n"," quality=THUMBNAIL_JPEG_QUALITY,\n"," optimize=True,\n"," )\n","\n"," thumbnail_bytes = output_buffer.getvalue()\n","\n"," return (\n"," \"data:image/jpeg;base64,\"\n"," + base64.b64encode(\n"," thumbnail_bytes\n"," ).decode(\"ascii\")\n"," )\n","\n","\n","# ============================================================\n","# PREPARE EXPORT IMAGE\n","# ============================================================\n","\n","def prepare_export_image(image_path):\n","\n"," with Image.open(image_path) as source:\n","\n"," source.load()\n","\n"," source = ImageOps.exif_transpose(source)\n","\n"," export_image = source.convert(\"RGB\")\n","\n"," export_image.thumbnail(\n"," EXPORT_IMAGE_MAX_SIZE,\n"," Image.Resampling.LANCZOS,\n"," )\n","\n"," output_buffer = io.BytesIO()\n","\n"," export_image.save(\n"," output_buffer,\n"," format=\"JPEG\",\n"," quality=EXPORT_JPEG_QUALITY,\n"," optimize=True,\n"," progressive=True,\n"," )\n","\n"," return output_buffer.getvalue()\n","\n","\n","# ============================================================\n","# CREATE SINGLE-LINE TEXT PAIR\n","# ============================================================\n","\n","def make_export_text(item):\n","\n"," tags = item.get(\"tags\", [])\n","\n"," if isinstance(tags, str):\n","\n"," tags = tags.replace(\",\", \" \").split()\n","\n"," tags_text = \" \".join(\n"," str(tag).strip()\n"," for tag in tags\n"," if str(tag).strip()\n"," )\n","\n"," natural_caption = str(\n"," item.get(\"furrence_caption\", \"\") or \"\"\n"," )\n","\n"," natural_caption = re.sub(\n"," r\"\\s+\",\n"," \" \",\n"," natural_caption,\n"," ).strip()\n","\n"," tags_text = re.sub(\n"," r\"\\s+\",\n"," \" \",\n"," tags_text,\n"," ).strip()\n","\n"," if natural_caption and tags_text:\n","\n"," return f\"{natural_caption} {tags_text}\"\n","\n"," if natural_caption:\n"," return natural_caption\n","\n"," return tags_text\n","\n","\n","# ============================================================\n","# GLOBAL SEARCH STATISTICS\n","# ============================================================\n","\n","test_results = []\n","\n","image_data_uris = {}\n","\n","downloaded_bytes = 0\n","\n","failed_images = []\n","\n","caption_failures = []\n","\n","rows_examined = 0\n","\n","batches_examined = 0\n","\n","tag_matches = 0\n","\n","favourites_rejected = 0\n","\n","duplicate_ids_skipped = 0\n","\n","processed_parquet_files = []\n","\n","retrieved_parquet_files = []\n","\n","search_finished = False\n","\n","seen_image_ids = set()\n","\n","\n","# ============================================================\n","# SEARCH ONE PARQUET FILE\n","# ============================================================\n","# Returns candidates from one Parquet file.\n","#\n","# Each file is processed independently.\n","# Row-group order is randomized using the same seeded RNG.\n","#\n","# The main workflow retrieves the candidates before moving\n","# on to another Parquet file.\n","\n","\n","def search_one_parquet(image_filename):\n","\n"," global rows_examined\n"," global batches_examined\n"," global tag_matches\n"," global favourites_rejected\n"," global duplicate_ids_skipped\n","\n"," print(\"\\n\" + \"=\" * 70)\n","\n"," print(\"SEARCHING PARQUET:\", image_filename)\n","\n"," print(\"=\" * 70)\n","\n"," image_file = hf_hub_download(\n"," repo_id=REPO_ID,\n"," repo_type=REPO_TYPE,\n"," filename=image_filename,\n"," token=HF_TOKEN,\n"," )\n","\n"," pf = pq.ParquetFile(\n"," image_file\n"," )\n","\n"," available_columns = set(\n"," pf.schema_arrow.names\n"," )\n","\n"," wanted_columns = [\n"," \"id\",\n"," \"tags\",\n"," \"rating\",\n"," \"width\",\n"," \"height\",\n"," \"created_at\",\n"," \"fav_count\",\n"," \"author_name\",\n"," ]\n","\n"," columns = [\n"," column\n"," for column in wanted_columns\n"," if column in available_columns\n"," ]\n","\n"," if \"id\" not in columns or \"tags\" not in columns:\n","\n"," raise RuntimeError(\n"," f\"{image_filename} must contain id and tags columns.\"\n"," )\n","\n"," if \"fav_count\" not in columns:\n","\n"," raise RuntimeError(\n"," f\"{image_filename} does not contain fav_count.\"\n"," )\n","\n"," print(\n"," \"Total rows:\",\n"," f\"{pf.metadata.num_rows:,}\",\n"," )\n","\n"," print(\n"," \"Row groups:\",\n"," pf.num_row_groups,\n"," )\n","\n"," # --------------------------------------------------------\n"," # RANDOMIZE ROW-GROUP ORDER\n"," # --------------------------------------------------------\n","\n"," row_groups = list(\n"," range(pf.num_row_groups)\n"," )\n","\n"," if RANDOM_SEARCH_START:\n","\n"," search_rng.shuffle(\n"," row_groups\n"," )\n","\n"," print(\"Randomized row-group order.\")\n","\n"," else:\n","\n"," row_groups.sort()\n","\n"," print(\"Sequential row-group order.\")\n","\n"," candidates = []\n","\n"," # --------------------------------------------------------\n"," # PROCESS ROW GROUPS\n"," # --------------------------------------------------------\n","\n"," for row_group_number, row_group in enumerate(\n"," row_groups,\n"," start=1,\n"," ):\n","\n"," if (\n"," MAX_ROWS_TO_EXAMINE is not None\n"," and rows_examined >= MAX_ROWS_TO_EXAMINE\n"," ):\n","\n"," print(\"Maximum row examination limit reached.\")\n","\n"," break\n","\n"," if (\n"," len(test_results) + len(candidates)\n"," >= TEST_IMAGE_COUNT\n"," ):\n","\n"," break\n","\n"," print(\n"," f\"\\nRow group \"\n"," f\"{row_group_number}/{len(row_groups)} \"\n"," f\"(Parquet row group {row_group})\"\n"," )\n","\n"," for batch in pf.iter_batches(\n"," batch_size=BATCH_SIZE,\n"," row_groups=[row_group],\n"," columns=columns,\n"," use_threads=True,\n"," ):\n","\n"," batches_examined += 1\n","\n"," data = batch.to_pydict()\n","\n"," for i, image_tags in enumerate(data[\"tags\"]):\n","\n"," rows_examined += 1\n","\n"," if matches_tag_conditions(image_tags):\n","\n"," tag_matches += 1\n","\n"," fav_count = normalize_fav_count(\n"," data[\"fav_count\"][i]\n"," )\n","\n"," if fav_count < TEST_MIN_FAVOURITES:\n","\n"," favourites_rejected += 1\n","\n"," continue\n","\n"," image_id_value = data[\"id\"][i]\n","\n"," if image_id_value is None:\n"," continue\n","\n"," try:\n","\n"," image_id = str(\n"," int(image_id_value)\n"," )\n","\n"," except (\n"," TypeError,\n"," ValueError,\n"," OverflowError,\n"," ):\n","\n"," continue\n","\n"," if image_id in seen_image_ids:\n","\n"," duplicate_ids_skipped += 1\n","\n"," continue\n","\n"," seen_image_ids.add(\n"," image_id\n"," )\n","\n"," result = {}\n","\n"," for column in columns:\n","\n"," value = data[column][i]\n","\n"," if column == \"tags\":\n","\n"," result[column] = (\n"," tags_to_display_list(image_tags)\n"," )\n","\n"," elif column == \"fav_count\":\n","\n"," result[column] = fav_count\n","\n"," else:\n","\n"," result[column] = value\n","\n"," result[\"source_parquet\"] = image_filename\n","\n"," candidates.append(\n"," result\n"," )\n","\n"," print(\n"," f\" MATCH {len(test_results) + len(candidates)}\"\n"," f\"/{TEST_IMAGE_COUNT}: \"\n"," f\"ID {image_id} \"\n"," f\"({fav_count} favourites)\"\n"," )\n","\n"," if (\n"," len(test_results) + len(candidates)\n"," >= TEST_IMAGE_COUNT\n"," ):\n","\n"," break\n","\n"," if (\n"," MAX_ROWS_TO_EXAMINE is not None\n"," and rows_examined >= MAX_ROWS_TO_EXAMINE\n"," ):\n","\n"," break\n","\n"," del data\n","\n"," gc.collect()\n","\n"," if (\n"," len(test_results) + len(candidates)\n"," >= TEST_IMAGE_COUNT\n"," ):\n","\n"," break\n","\n"," if (\n"," MAX_ROWS_TO_EXAMINE is not None\n"," and rows_examined >= MAX_ROWS_TO_EXAMINE\n"," ):\n","\n"," break\n","\n"," print(\n"," f\"Rows examined: {rows_examined:,} | \"\n"," f\"Tag matches: {tag_matches:,} | \"\n"," f\"Rejected: {favourites_rejected:,} | \"\n"," f\"Candidates: {len(candidates)} | \"\n"," f\"Retrieved: {len(test_results)}\"\n"," )\n","\n"," del pf\n","\n"," gc.collect()\n","\n"," return candidates\n","\n","\n","# ============================================================\n","# RETRIEVE CANDIDATES FROM ONE PARQUET\n","# ============================================================\n","# This function runs after every individual Parquet search.\n","#\n","# Successfully retrieved images are retained.\n","# Failed retrievals do not count toward IMAGE_COUNT.\n","#\n","# If the requested count is not reached, the main workflow\n","# proceeds to the next Parquet file.\n","\n","\n","def retrieve_parquet_candidates(\n"," candidates,\n"," image_filename,\n","):\n","\n"," global downloaded_bytes\n"," global export_image_count\n","\n"," if not candidates:\n"," return\n","\n"," print(\"\\n\" + \"=\" * 70)\n","\n"," print(\"RETRIEVING MATCHES FROM:\", image_filename)\n","\n"," print(\"=\" * 70)\n","\n"," retrieved_from_this_file = 0\n","\n"," for number, item in enumerate(\n"," candidates,\n"," start=1,\n"," ):\n","\n"," if len(test_results) >= TEST_IMAGE_COUNT:\n","\n"," print(\"Requested image count reached.\")\n","\n"," break\n","\n"," image_id = str(\n"," int(item[\"id\"])\n"," )\n","\n"," print(\n"," f\"\\n[{number}/{len(candidates)}] \"\n"," f\"Retrieving ID {image_id}\"\n"," )\n","\n"," try:\n","\n"," with pool.mock_resource(\n"," int(image_id),\n"," None,\n"," silent=True,\n"," ) as (temp_dir, resource_info):\n","\n"," image_path = find_image_file(\n"," temp_dir\n"," )\n","\n"," original_size = os.path.getsize(\n"," image_path\n"," )\n","\n"," downloaded_bytes += original_size\n","\n"," print(\n"," \"Image retrieved:\",\n"," f\"{original_size / 1024:.1f} KB\",\n"," )\n","\n"," # ------------------------------------------------\n"," # THUMBNAIL\n"," # ------------------------------------------------\n","\n"," thumbnail_uri = make_thumbnail_data_uri(\n"," image_path\n"," )\n","\n"," # ------------------------------------------------\n"," # OPTIONAL FURRANCE CAPTION\n"," # ------------------------------------------------\n","\n"," if ENABLE_FURRANCE_CAPTIONER:\n","\n"," try:\n","\n"," print(\n"," \"Generating Furrance caption...\"\n"," )\n","\n"," with Image.open(image_path) as source:\n","\n"," source.load()\n","\n"," caption_image = (\n"," ImageOps.exif_transpose(source)\n"," .convert(\"RGB\")\n"," )\n","\n"," caption = furrence_caption(\n"," image=caption_image,\n"," tags=item.get(\"tags\", []),\n"," length=120,\n"," max_new_tokens=512,\n"," )\n","\n"," item[\"furrence_caption\"] = caption\n","\n"," print(\"Caption:\", caption)\n","\n"," del caption_image\n","\n"," except Exception as caption_error:\n","\n"," item[\"furrence_caption\"] = \"\"\n","\n"," caption_failures.append(\n"," image_id\n"," )\n","\n"," print(\n"," \"CAPTION FAILED:\",\n"," type(caption_error).__name__,\n"," str(caption_error),\n"," )\n","\n"," else:\n","\n"," item[\"furrence_caption\"] = \"\"\n","\n"," # ------------------------------------------------\n"," # PREPARE EXPORT PAIR\n"," # ------------------------------------------------\n","\n"," image_export_path = os.path.join(\n"," EXPORT_DIR,\n"," f\"{image_id}.jpg\",\n"," )\n","\n"," text_export_path = os.path.join(\n"," EXPORT_DIR,\n"," f\"{image_id}.txt\",\n"," )\n","\n"," try:\n","\n"," export_image_bytes = prepare_export_image(\n"," image_path\n"," )\n","\n"," export_text = make_export_text(\n"," item\n"," )\n","\n"," with open(\n"," image_export_path,\n"," \"wb\",\n"," ) as file:\n","\n"," file.write(\n"," export_image_bytes\n"," )\n","\n"," with open(\n"," text_export_path,\n"," \"w\",\n"," encoding=\"utf-8\",\n"," newline=\"\",\n"," ) as file:\n","\n"," file.write(\n"," re.sub(\n"," r\"[\\r\\n]+\",\n"," \" \",\n"," export_text,\n"," ).strip()\n"," )\n","\n"," except Exception:\n","\n"," for partial_path in (\n"," image_export_path,\n"," text_export_path,\n"," ):\n","\n"," if os.path.exists(partial_path):\n","\n"," os.remove(\n"," partial_path\n"," )\n","\n"," raise\n","\n"," # ------------------------------------------------\n"," # COMMIT SUCCESSFUL IMAGE TO RESULTS\n"," # ------------------------------------------------\n","\n"," item[\"retrieved\"] = True\n","\n"," item[\"export_filename\"] = (\n"," f\"{image_id}.jpg\"\n"," )\n","\n"," test_results.append(\n"," item\n"," )\n","\n"," image_data_uris[image_id] = (\n"," thumbnail_uri\n"," )\n","\n"," retrieved_from_this_file += 1\n","\n"," print(\n"," f\"SUCCESS: \"\n"," f\"{len(test_results)}/{TEST_IMAGE_COUNT} \"\n"," f\"images retrieved.\"\n"," )\n","\n"," except Exception as exc:\n","\n"," failed_images.append(\n"," image_id\n"," )\n","\n"," print(\n"," \"IMAGE RETRIEVAL FAILED:\",\n"," f\"{type(exc).__name__}: {exc}\",\n"," )\n","\n"," item[\"retrieved\"] = False\n","\n"," gc.collect()\n","\n"," # Release unused CUDA cache after captioning.\n","\n"," if ENABLE_FURRANCE_CAPTIONER:\n","\n"," try:\n","\n"," import torch\n","\n"," torch.cuda.empty_cache()\n","\n"," except Exception:\n"," pass\n","\n"," if retrieved_from_this_file:\n","\n"," retrieved_parquet_files.append(\n"," image_filename\n"," )\n","\n"," print(\"\\nParquet retrieval completed.\")\n","\n"," print(\n"," \"Retrieved from this Parquet:\",\n"," retrieved_from_this_file,\n"," )\n","\n"," print(\n"," \"Total successfully retrieved:\",\n"," f\"{len(test_results)}/{TEST_IMAGE_COUNT}\",\n"," )\n","\n","\n","# ============================================================\n","# STAGED MULTI-PARQUET SEARCH\n","# ============================================================\n","# Workflow:\n","#\n","# 1. Select the first Parquet using the seeded file order.\n","# 2. Search that Parquet.\n","# 3. Retrieve the matching images immediately.\n","# 4. Check how many images were successfully retrieved.\n","# 5. If the requested count has not been reached, move to\n","# the next Parquet.\n","# 6. Repeat until the requested count or row limit is reached.\n","#\n","# This prevents a large search from accumulating hundreds\n","# of image IDs before attempting image retrieval.\n","\n","\n","print(\"\\n\" + \"=\" * 70)\n","\n","print(\"STARTING STAGED PARQUET SEARCH\")\n","\n","print(\"=\" * 70)\n","\n","print(\n"," \"Target:\",\n"," TEST_IMAGE_COUNT,\n"," \"successfully retrieved images\",\n",")\n","\n","print(\n"," \"Available Parquets:\",\n"," len(PARQUET_SEARCH_ORDER),\n",")\n","\n","\n","for parquet_index, image_filename in enumerate(\n"," PARQUET_SEARCH_ORDER,\n"," start=1,\n","):\n","\n"," if len(test_results) >= TEST_IMAGE_COUNT:\n","\n"," print(\"\\nRequested image count reached.\")\n","\n"," break\n","\n"," if (\n"," MAX_ROWS_TO_EXAMINE is not None\n"," and rows_examined >= MAX_ROWS_TO_EXAMINE\n"," ):\n","\n"," print(\"\\nMaximum row examination limit reached.\")\n","\n"," break\n","\n"," print(\"\\n\\n\" + \"#\" * 70)\n","\n"," print(\n"," f\"PARQUET {parquet_index}/{len(PARQUET_SEARCH_ORDER)}\"\n"," )\n","\n"," print(\"#\" * 70)\n","\n"," print(\"File:\", image_filename)\n","\n"," print(\n"," \"Remaining images:\",\n"," TEST_IMAGE_COUNT - len(test_results),\n"," )\n","\n"," processed_parquet_files.append(\n"," image_filename\n"," )\n","\n"," try:\n","\n"," candidates = search_one_parquet(\n"," image_filename\n"," )\n","\n"," except Exception as parquet_error:\n","\n"," print(\n"," \"\\nPARQUET SEARCH FAILED:\",\n"," type(parquet_error).__name__,\n"," str(parquet_error),\n"," )\n","\n"," candidates = []\n","\n"," # --------------------------------------------------------\n"," # RETRIEVE MATCHES BEFORE MOVING TO NEXT PARQUET\n"," # --------------------------------------------------------\n","\n"," if candidates:\n","\n"," retrieve_parquet_candidates(\n"," candidates,\n"," image_filename,\n"," )\n","\n"," else:\n","\n"," print(\n"," \"No qualifying candidates found in this Parquet.\"\n"," )\n","\n"," del candidates\n","\n"," gc.collect()\n","\n"," print(\"\\n\" + \"=\" * 70)\n","\n"," print(\"STAGED SEARCH PROGRESS\")\n","\n"," print(\"=\" * 70)\n","\n"," print(\n"," \"Successfully retrieved:\",\n"," f\"{len(test_results)}/{TEST_IMAGE_COUNT}\",\n"," )\n","\n"," print(\n"," \"Rows examined:\",\n"," f\"{rows_examined:,}\",\n"," )\n","\n"," print(\n"," \"Parquet files processed:\",\n"," len(processed_parquet_files),\n"," )\n","\n"," print(\n"," \"Parquet files with successful retrievals:\",\n"," len(retrieved_parquet_files),\n"," )\n","\n"," if len(test_results) >= TEST_IMAGE_COUNT:\n","\n"," print(\"\\nTarget reached.\")\n","\n"," search_finished = True\n","\n"," break\n","\n"," if (\n"," MAX_ROWS_TO_EXAMINE is not None\n"," and rows_examined >= MAX_ROWS_TO_EXAMINE\n"," ):\n","\n"," print(\"\\nRow examination limit reached.\")\n","\n"," break\n","\n"," print(\n"," \"\\nTarget not yet reached. \"\n"," \"Continuing to the next Parquet.\"\n"," )\n","\n","\n","# ============================================================\n","# SEARCH SUMMARY\n","# ============================================================\n","\n","print(\"\\n\" + \"=\" * 70)\n","\n","print(\"PARQUET SEARCH SUMMARY\")\n","\n","print(\"=\" * 70)\n","\n","print(\"Available Parquet files:\", len(IMAGE_FILES))\n","\n","print(\"Processed Parquet files:\", len(processed_parquet_files))\n","\n","print(\"Parquets with successful retrievals:\", len(retrieved_parquet_files))\n","\n","print(\"Tag matches:\", tag_matches)\n","\n","print(\"Rejected by favourites:\", favourites_rejected)\n","\n","print(\"Duplicate IDs skipped:\", duplicate_ids_skipped)\n","\n","print(\"Successfully retrieved images:\", len(test_results))\n","\n","print(\"Images requested:\", TEST_IMAGE_COUNT)\n","\n","print(\"Minimum favourites:\", TEST_MIN_FAVOURITES)\n","\n","print(\"Rows examined:\", f\"{rows_examined:,}\")\n","\n","print(\"Batches examined:\", f\"{batches_examined:,}\")\n","\n","print(\"Failed image retrievals:\", len(failed_images))\n","\n","if len(test_results) < TEST_IMAGE_COUNT:\n","\n"," print(\n"," \"\\nWARNING: Only retrieved\",\n"," len(test_results),\n"," \"of\",\n"," TEST_IMAGE_COUNT,\n"," \"requested images.\",\n"," )\n","\n","if not test_results:\n","\n"," raise RuntimeError(\n"," \"No images were successfully retrieved \"\n"," \"from the available Parquet files.\"\n"," )\n","\n","\n","# ============================================================\n","# CREATE SEARCH METADATA\n","# ============================================================\n","\n","def create_search_metadata():\n","\n"," return f\"\"\"\n","SANKAKU SEARCH METADATA\n","=======================\n","\n","REPOSITORY\n","----------\n","\n","Repository:\n","{REPO_ID}\n","\n","Parquet files discovered:\n","{len(IMAGE_FILES)}\n","\n","Parquet search order:\n","{\", \".join(PARQUET_SEARCH_ORDER)}\n","\n","Parquet files processed:\n","{\", \".join(processed_parquet_files)}\n","\n","Parquet files with successful retrievals:\n","{\", \".join(retrieved_parquet_files)}\n","\n","\n","SEARCH CONFIGURATION\n","--------------------\n","\n","Main search query:\n","{SEARCH_QUERY or \"(None)\"}\n","\n","Required substrings:\n","{\", \".join(REQUIRED_TEST_TAGS) or \"(None)\"}\n","\n","Excluded substrings:\n","{\", \".join(EXCLUDED_TEST_TAGS) or \"(None)\"}\n","\n","Additional words:\n","{\", \".join(ADDITIONAL_TEST_TAGS) or \"(None)\"}\n","\n","Additional matching mode:\n","OR\n","\n","Minimum favourites:\n","{TEST_MIN_FAVOURITES}\n","\n","Images requested:\n","{TEST_IMAGE_COUNT}\n","\n","Maximum rows to examine:\n","{MAX_ROWS_TO_EXAMINE}\n","\n","Batch size:\n","{BATCH_SIZE}\n","\n","\n","RANDOM SEARCH\n","-------------\n","\n","Random search enabled:\n","{RANDOM_SEARCH_START}\n","\n","Numerical seed:\n","{ACTIVE_SEARCH_SEED}\n","\n","Seed input filename:\n","{os.path.basename(SEED_FILE)}\n","\n","Starting Parquet:\n","{PARQUET_SEARCH_ORDER[0]}\n","\n","Randomization method:\n","Seeded Python random.Random shuffle of Parquet files\n","and row groups.\n","\n","Traversal:\n","{\n","\"Randomized Parquet and row-group order\" if RANDOM_SEARCH_START else \"Sequential Parquet and row-group order\"}\n","\n","\n","SEARCH RESULTS\n","--------------\n","\n","Rows examined:\n","{rows_examined}\n","\n","Batches examined:\n","{batches_examined}\n","\n","Tag matches:\n","{tag_matches}\n","\n","Rejected by favourites:\n","{favourites_rejected}\n","\n","Duplicate IDs skipped:\n","{duplicate_ids_skipped}\n","\n","Qualifying image candidates:\n","{len(seen_image_ids)}\n","\n","Successfully retrieved images:\n","{len(test_results)}\n","\n","Images requested:\n","{TEST_IMAGE_COUNT}\n","\n","Failed image retrievals:\n","{len(failed_images)}\n","\n","\n","CAPTIONING\n","----------\n","\n","Furrance captioner enabled:\n","{ENABLE_FURRANCE_CAPTIONER}\n","\n","Caption failures:\n","{len(caption_failures)}\n","\n","\n","EXPORT RESULTS\n","--------------\n","\n","Complete image-text pairs:\n","{len(test_results)}\n","\n","Original image data downloaded:\n","{downloaded_bytes / (1024 * 1024):.2f} MB\n","\n","\n","NOTES\n","-----\n","\n","The search begins at the first Parquet in the selected\n","search order.\n","\n","When random search is enabled, the Parquet file order\n","and row-group order are shuffled using the numerical seed.\n","\n","Each Parquet is searched and its matching images are\n","retrieved before the next Parquet is examined.\n","\n","The search continues when image retrieval failures or\n","insufficient matches prevent reaching the requested count.\n","\n","Failed image retrievals do not count toward the requested\n","image total.\n","\n","Duplicate image IDs are skipped.\n","\n","The search stops when the requested number of images\n","has been successfully retrieved, all Parquet files\n","have been processed, or the maximum row examination\n","limit has been reached.\n","\n","Each exported JPG is paired with a TXT file sharing\n","its basename.\n","\n","Exported JPG images have a maximum dimension of 1024 pixels.\n","\n","TXT files contain a single line with the natural-language\n","caption, if available, followed by the original Sankaku tags.\n","\n","A minus sign is an exclusion operator only at the beginning\n","of the query or immediately after whitespace.\n","\"\"\".strip()\n","\n","\n","search_metadata = create_search_metadata()\n","\n","\n","# ============================================================\n","# CREATE ZIP ARCHIVE\n","# ============================================================\n","\n","print(\"\\n\" + \"=\" * 70)\n","\n","print(\"CREATING IMAGE-TEXT ZIP\")\n","\n","print(\"=\" * 70)\n","\n","if os.path.exists(ZIP_FILE):\n","\n"," os.remove(\n"," ZIP_FILE\n"," )\n","\n","complete_pairs = []\n","\n","for item in test_results:\n","\n"," image_id = str(\n"," int(item[\"id\"])\n"," )\n","\n"," image_path = os.path.join(\n"," EXPORT_DIR,\n"," f\"{image_id}.jpg\",\n"," )\n","\n"," text_path = os.path.join(\n"," EXPORT_DIR,\n"," f\"{image_id}.txt\",\n"," )\n","\n"," if (\n"," os.path.isfile(image_path)\n"," and os.path.isfile(text_path)\n"," ):\n","\n"," complete_pairs.append(\n"," image_id\n"," )\n","\n","export_image_count = len(\n"," complete_pairs\n",")\n","\n","with zipfile.ZipFile(\n"," ZIP_FILE,\n"," mode=\"w\",\n"," compression=zipfile.ZIP_DEFLATED,\n"," compresslevel=6,\n",") as archive:\n","\n"," for image_id in complete_pairs:\n","\n"," archive.write(\n"," os.path.join(\n"," EXPORT_DIR,\n"," f\"{image_id}.jpg\",\n"," ),\n"," arcname=f\"{image_id}.jpg\",\n"," )\n","\n"," archive.write(\n"," os.path.join(\n"," EXPORT_DIR,\n"," f\"{image_id}.txt\",\n"," ),\n"," arcname=f\"{image_id}.txt\",\n"," )\n","\n"," archive.writestr(\n"," \"search_metadata.txt\",\n"," search_metadata,\n"," )\n","\n","zip_size_mb = (\n"," os.path.getsize(ZIP_FILE)\n"," / (1024 * 1024)\n",")\n","\n","print(\"Complete export pairs:\", export_image_count)\n","\n","print(\"Metadata included: search_metadata.txt\")\n","\n","print(\"Search seed:\", ACTIVE_SEARCH_SEED)\n","\n","print(\"ZIP file:\", ZIP_FILE)\n","\n","print(f\"ZIP size: {zip_size_mb:.2f} MB\")\n","\n","\n","# ============================================================\n","# SAVE RESULTS INCLUDING CAPTIONS\n","# ============================================================\n","\n","results_df = pd.DataFrame(\n"," test_results\n",")\n","\n","results_df.to_csv(\n"," OUTPUT_FILE,\n"," index=False,\n",")\n","\n","\n","# ============================================================\n","# RETRIEVAL SUMMARY\n","# ============================================================\n","\n","print(\"\\n\" + \"=\" * 70)\n","\n","print(\"RETRIEVAL SUMMARY\")\n","\n","print(\"=\" * 70)\n","\n","print(\"Images requested:\", TEST_IMAGE_COUNT)\n","\n","print(\"Images retrieved:\", len(test_results))\n","\n","print(\"Export pairs:\", export_image_count)\n","\n","print(\"Images failed:\", len(failed_images))\n","\n","print(\"Caption failures:\", len(caption_failures))\n","\n","print(\"Parquets processed:\", len(processed_parquet_files))\n","\n","print(\"Rows examined:\", f\"{rows_examined:,}\")\n","\n","print(\n"," \"Original image data:\",\n"," f\"{downloaded_bytes / (1024 * 1024):.2f} MB\",\n",")\n","\n","print(\"Random search enabled:\", RANDOM_SEARCH_START)\n","\n","print(\"Search seed:\", ACTIVE_SEARCH_SEED)\n","\n","print(\"CSV:\", OUTPUT_FILE)\n","\n","print(\"ZIP:\", ZIP_FILE)\n","\n","if failed_images:\n","\n"," print(\n"," \"Failed image IDs:\",\n"," failed_images,\n"," )\n","\n","if caption_failures:\n","\n"," print(\n"," \"Caption failure IDs:\",\n"," caption_failures,\n"," )\n","\n","\n","# ============================================================\n","# REGISTER COLAB DOWNLOAD CALLBACK\n","# ============================================================\n","\n","def download_sankaku_zip():\n","\n"," if not os.path.isfile(ZIP_FILE):\n","\n"," raise FileNotFoundError(\n"," \"The ZIP archive could not be found.\"\n"," )\n","\n"," files.download(\n"," ZIP_FILE\n"," )\n","\n","\n","output.register_callback(\n"," \"sankaku.download_zip\",\n"," download_sankaku_zip,\n",")\n","\n","\n","# ============================================================\n","# RENDER TAGS\n","# ============================================================\n","\n","def render_caption_tags(tags):\n","\n"," rendered = []\n","\n"," for tag in tags:\n","\n"," tag_string = str(tag)\n","\n"," safe_tag = html.escape(\n"," tag_string\n"," )\n","\n"," is_search_tag = any(\n"," word in tag_string.lower()\n"," for word in (\n"," REQUIRED_TEST_TAGS\n"," + EXCLUDED_TEST_TAGS\n"," + ADDITIONAL_TEST_TAGS\n"," )\n"," )\n","\n"," if is_search_tag:\n","\n"," rendered.append(\n"," f'<span class=\"search-tag\">{safe_tag}</span>'\n"," )\n","\n"," else:\n","\n"," rendered.append(\n"," f'<span class=\"normal-tag\">{safe_tag}</span>'\n"," )\n","\n"," return \" \".join(\n"," rendered\n"," )\n","\n","\n","# ============================================================\n","# BUILD COPY TEXT\n","# ============================================================\n","\n","def make_copy_text(item):\n","\n"," tags = item.get(\n"," \"tags\",\n"," [],\n"," )\n","\n"," if isinstance(tags, str):\n","\n"," tags = tags.replace(\n"," \",\",\n"," \" \",\n"," ).split()\n","\n"," tags_text = \" \".join(\n"," str(tag).strip()\n"," for tag in tags\n"," if str(tag).strip()\n"," )\n","\n"," natural_caption = str(\n"," item.get(\"furrence_caption\", \"\") or \"\"\n"," ).strip()\n","\n"," natural_caption = re.sub(\n"," r\"\\s+\",\n"," \" \",\n"," natural_caption,\n"," )\n","\n"," tags_text = re.sub(\n"," r\"\\s+\",\n"," \" \",\n"," tags_text,\n"," )\n","\n"," if ENABLE_FURRANCE_CAPTIONER and natural_caption:\n","\n"," copy_text = (\n"," f\"{natural_caption} {tags_text}\"\n"," if tags_text\n"," else natural_caption\n"," )\n","\n"," button_label = \"Copy caption + tags\"\n","\n"," else:\n","\n"," copy_text = tags_text\n","\n"," button_label = \"Copy tags\"\n","\n"," return copy_text, button_label\n","\n","\n","def encode_copy_text(text):\n","\n"," return base64.b64encode(\n"," text.encode(\"utf-8\")\n"," ).decode(\"ascii\")\n","\n","\n","# ============================================================\n","# BUILD IMAGE GRID\n","# ============================================================\n","\n","cards = []\n","\n","for item in test_results:\n","\n"," image_id = str(\n"," int(item[\"id\"])\n"," )\n","\n"," image_uri = image_data_uris.get(\n"," image_id\n"," )\n","\n"," if not image_uri:\n"," continue\n","\n"," tags_html = render_caption_tags(\n"," item.get(\"tags\", [])\n"," )\n","\n"," rating = html.escape(\n"," str(item.get(\"rating\", \"\") or \"\")\n"," )\n","\n"," width = item.get(\n"," \"width\",\n"," \"\",\n"," )\n","\n"," height = item.get(\n"," \"height\",\n"," \"\",\n"," )\n","\n"," metadata = []\n","\n"," if (\n"," width is not None\n"," and height is not None\n"," and pd.notna(width)\n"," and pd.notna(height)\n"," ):\n","\n"," metadata.append(\n"," f\"{html.escape(str(width))} × \"\n"," f\"{html.escape(str(height))}\"\n"," )\n","\n"," fav_count = item.get(\n"," \"fav_count\",\n"," \"\",\n"," )\n","\n"," if fav_count is not None and pd.notna(fav_count):\n","\n"," metadata.append(\n"," f\"Favourites: {html.escape(str(fav_count))}\"\n"," )\n","\n"," author = item.get(\n"," \"author_name\",\n"," \"\",\n"," )\n","\n"," if (\n"," author is not None\n"," and pd.notna(author)\n"," and str(author).strip()\n"," ):\n","\n"," metadata.append(\n"," f\"Artist: {html.escape(str(author))}\"\n"," )\n","\n"," natural_caption = str(\n"," item.get(\"furrence_caption\", \"\") or \"\"\n"," ).strip()\n","\n"," if natural_caption:\n","\n"," natural_caption_html = f\"\"\"\n"," <div class=\"furrence-caption\">\n"," <div class=\"caption-heading\">\n"," Furrance natural-language caption\n"," </div>\n"," {html.escape(natural_caption)}\n"," </div>\n"," \"\"\"\n","\n"," else:\n","\n"," natural_caption_html = \"\"\n","\n"," copy_text, button_label = make_copy_text(\n"," item\n"," )\n","\n"," copy_text_b64 = encode_copy_text(\n"," copy_text\n"," )\n","\n"," cards.append(f\"\"\"\n"," <div class=\"image-card\">\n","\n"," <div class=\"image-container\">\n","\n"," <img\n"," src=\"{image_uri}\"\n"," alt=\"Sankaku image {html.escape(image_id)}\"\n"," loading=\"lazy\"\n"," >\n","\n"," </div>\n","\n"," <div class=\"image-info\">\n","\n"," <div class=\"image-meta\">\n","\n"," <span>ID: {html.escape(image_id)}</span>\n","\n"," <span>{rating}</span>\n","\n"," </div>\n","\n"," <div class=\"extra-meta\">\n"," {html.escape(\" | \".join(metadata))}\n"," </div>\n","\n"," {natural_caption_html}\n","\n"," <div class=\"caption-tags\">\n"," {tags_html}\n"," </div>\n","\n"," <button\n"," class=\"copy-prompt-button\"\n"," data-copy-b64=\"{copy_text_b64}\"\n"," onclick=\"copySankakuPrompt(this)\"\n"," type=\"button\"\n"," >\n"," {button_label}\n"," </button>\n","\n"," </div>\n","\n"," </div>\n"," \"\"\")\n","\n","\n","# ============================================================\n","# DISPLAY HTML IMAGE GRID + CLIPBOARD + ZIP DOWNLOAD\n","# ============================================================\n","\n","grid_html = f\"\"\"\n","<style>\n","\n",".sankaku-results {{\n"," background:#181818;\n"," color:white;\n"," padding:18px;\n"," border-radius:8px;\n"," font-family:Arial,sans-serif;\n","}}\n","\n",".sankaku-grid {{ display:grid;\n"," grid-template-columns:repeat(\n"," auto-fill,\n"," minmax({GRID_MIN_WIDTH}px, 1fr)\n"," );\n"," gap:14px;\n","}}\n","\n",".image-card {{\n"," background:#222;\n"," border-radius:6px;\n"," overflow:hidden;\n"," min-width:0;\n","}}\n","\n",".image-container {{\n"," height:{IMAGE_HEIGHT}px;\n"," display:flex;\n"," align-items:center;\n"," justify-content:center;\n"," background:#111;\n","}}\n","\n",".image-container img {{\n"," max-width:100%;\n"," max-height:100%;\n"," object-fit:contain;\n","}}\n","\n",".image-info {{\n"," padding:10px;\n","}}\n","\n",".image-meta {{\n"," display:flex;\n"," justify-content:space-between;\n"," color:#aaa;\n"," font-size:11px;\n"," margin-bottom:5px;\n","}}\n","\n",".extra-meta {{\n"," color:#777;\n"," font-size:10px;\n"," margin-bottom:8px;\n","}}\n","\n",".caption-tags {{ font-size:11px;\n"," line-height:1.9;\n"," overflow-wrap:anywhere;\n","}}\n","\n",".normal-tag {{\n"," color:#ff963d;\n"," margin-right:3px;\n","}}\n","\n",".search-tag {{\n"," color:white;\n"," font-weight:bold;\n"," margin-right:3px;\n","}}\n","\n",".furrence-caption {{\n"," color:#e5e5e5;\n"," font-size:12px;\n"," line-height:1.6;\n"," padding:10px;\n"," margin:8px 0;\n"," background:#303039;\n"," border-left:3px solid #a78bfa;\n"," border-radius:3px;\n"," overflow-wrap:anywhere;\n","}}\n","\n",".caption-heading {{\n"," color:#c4b5fd;\n"," font-size:10px;\n"," font-weight:bold;\n"," text-transform:uppercase;\n"," letter-spacing:0.5px;\n"," margin-bottom:5px;\n","}}\n","\n",".copy-prompt-button {{\n"," display:block;\n"," width:100%;\n"," margin-top:12px;\n"," padding:9px 12px;\n"," border:1px solid #555;\n"," border-radius:5px;\n"," background:#383344;\n"," color:#eee;\n"," font-size:12px;\n"," font-weight:bold;\n"," cursor:pointer;\n"," transition:background 0.15s ease;\n","}}\n","\n",".copy-prompt-button:hover {{\n"," background:#514568;\n","}}\n","\n",".copy-prompt-button:active {{\n"," background:#67578a;\n","}}\n","\n",".download-zip-button {{\n"," display:inline-block;\n"," margin:0 0 16px 0;\n"," padding:12px 18px;\n"," border:1px solid #7662a1;\n"," border-radius:6px;\n"," background:#514078;\n"," color:white;\n"," font-size:13px;\n"," font-weight:bold;\n"," cursor:pointer;\n","}}\n","\n",".download-zip-button:hover {{\n"," background:#67528f;\n","}}\n","\n",".download-zip-button:active {{\n"," background:#7963a5;\n","}}\n","\n",".download-zip-button:disabled {{\n"," opacity:0.5;\n"," cursor:not-allowed;\n","}}\n","\n","</style>\n","\n","<script>\n","\n","window.copySankakuPrompt = async function(button) {{\n","\n"," const encodedText = button.getAttribute(\"data-copy-b64\");\n","\n"," if (!encodedText) {{\n","\n"," button.textContent = \"Nothing to copy\";\n","\n"," return;\n","\n"," }}\n","\n"," const binary = atob(encodedText);\n","\n"," const bytes = Uint8Array.from(\n"," binary,\n"," character => character.charCodeAt(0)\n"," );\n","\n"," const textToCopy = new TextDecoder().decode(bytes);\n","\n"," const originalLabel = button.textContent;\n","\n"," function fallbackCopy(text) {{\n","\n"," const textarea = document.createElement(\"textarea\");\n","\n"," textarea.value = text;\n","\n"," textarea.setAttribute(\"readonly\", \"\");\n","\n"," textarea.style.position = \"fixed\";\n","\n"," textarea.style.left = \"-9999px\";\n","\n"," textarea.style.top = \"0\";\n","\n"," document.body.appendChild(textarea);\n","\n"," textarea.focus();\n","\n"," textarea.select();\n","\n"," textarea.setSelectionRange(\n"," 0,\n"," textarea.value.length\n"," );\n","\n"," let success = false;\n","\n"," try {{\n","\n"," success = document.execCommand(\"copy\");\n","\n"," }} catch (error) {{\n","\n"," success = false;\n","\n"," }}\n","\n"," textarea.remove();\n","\n"," return success;\n","\n"," }}\n","\n"," try {{\n","\n"," if (\n"," navigator.clipboard &&\n"," window.isSecureContext\n"," ) {{\n","\n"," await navigator.clipboard.writeText(textToCopy);\n","\n"," }} else {{\n","\n"," if (!fallbackCopy(textToCopy)) {{\n","\n"," throw new Error(\"Clipboard fallback failed.\");\n","\n"," }}\n","\n"," }}\n","\n"," button.textContent = \"Copied!\";\n","\n"," }} catch (error) {{\n","\n"," if (fallbackCopy(textToCopy)) {{\n","\n"," button.textContent = \"Copied!\";\n","\n"," }} else {{\n","\n"," button.textContent = \"Copy failed\";\n","\n"," console.error(\n"," \"Could not copy prompt:\",\n"," error\n"," );\n","\n"," }}\n","\n"," }}\n","\n"," setTimeout(() => {{\n","\n"," button.textContent = originalLabel;\n","\n"," }}, 1800);\n","\n","}};\n","\n","\n","window.downloadSankakuZip = function(button){{\n","\n"," const originalLabel = button.textContent;\n","\n"," button.textContent = \"Preparing download...\";\n","\n"," button.disabled = true;\n","\n"," google.colab.kernel.invokeFunction(\n"," \"sankaku.download_zip\",\n"," [],\n"," {{}}\n"," ).then(\n"," function() {{\n","\n"," button.textContent = \"Download requested\";\n","\n"," setTimeout(() => {{\n","\n"," button.textContent = originalLabel;\n","\n"," button.disabled = false;\n","\n"," }}, 2000);\n","\n"," }},\n"," function(error) {{\n","\n"," console.error(\"ZIP download failed:\", error);\n","\n"," button.textContent = \"Download failed\";\n","\n"," button.disabled = false;\n","\n"," }}\n"," );\n","\n","}};\n","\n","</script>\n","\n","<div class=\"sankaku-results\">\n","\n"," <h3>\n"," {len(image_data_uris)} retrieved images\n"," </h3>\n","\n"," <div style=\"color:#999;font-size:12px;margin-bottom:16px\">\n","\n"," Main query:\n"," {html.escape(SEARCH_QUERY or \"None\")}\n","\n"," |\n","\n"," Additional words:\n"," {html.escape(ADDITIONAL_WORDS or \"None\")}\n","\n"," |\n","\n"," Minimum favourites:\n"," {TEST_MIN_FAVOURITES}\n","\n"," |\n","\n"," Rows examined:\n"," {rows_examined:,}\n","\n"," |\n","\n"," Images requested:\n"," {TEST_IMAGE_COUNT}\n","\n"," |\n","\n"," Parquets processed:\n"," {len(processed_parquet_files)}\n","\n"," |\n","\n"," Random search:\n"," {\"Enabled\" if RANDOM_SEARCH_START else \"Disabled\"}\n","\n"," |\n","\n"," Seed:\n"," {ACTIVE_SEARCH_SEED}\n","\n"," |\n","\n"," Furrance:\n"," {\"Enabled\" if ENABLE_FURRANCE_CAPTIONER else \"Disabled\"}\n","\n"," </div>\n","\n"," <button\n"," class=\"download-zip-button\"\n"," type=\"button\"\n"," onclick=\"downloadSankakuZip(this)\"\n"," {\"disabled\" if export_image_count == 0 else \"\"}\n"," >\n"," Download image-text pairs (.zip) — {export_image_count} images\n"," </button>\n","\n"," <div style=\"color:#999;font-size:11px;margin-bottom:16px\">\n","\n"," JPG images, maximum dimension 1024 px.\n"," Each JPG has a matching single-line TXT caption file.\n"," The ZIP also includes search_metadata.txt.\n","\n"," </div>\n","\n"," <div class=\"sankaku-grid\">\n","\n"," {''.join(cards)}\n","\n"," </div>\n","\n","</div>\n","\"\"\"\n","\n","display(\n"," HTML(grid_html)\n",")\n","\n","\n","# ============================================================\n","# CLEAN UP TEMPORARY EXPORT DIRECTORY\n","# ============================================================\n","\n","shutil.rmtree(\n"," EXPORT_DIR,\n"," ignore_errors=True,\n",")\n","\n","print(\"\\n\" + \"=\" * 70)\n","\n","print(\"SEARCH AND RETRIEVAL COMPLETE\")\n","\n","print(\"=\" * 70)\n","\n","print(\"CSV saved to:\", OUTPUT_FILE)\n","\n","print(\"ZIP saved to:\", ZIP_FILE)\n","\n","print(\"Export pairs:\", export_image_count)\n","\n","print(\"Search seed:\", ACTIVE_SEARCH_SEED)\n","\n","print(\"Seed input file:\", SEED_FILE)\n","\n","print(\"Parquet files processed:\", len(processed_parquet_files))\n","\n","print(\"Successfully retrieved:\", len(test_results))\n","\n","print(\"Requested:\", TEST_IMAGE_COUNT)"]}]}