File size: 138,970 Bytes
385c678
1
{"cells":[{"cell_type":"markdown","source":["# Sankaku Dataset Search and Captioning"],"metadata":{"id":"EytLQtu1OJ7A"},"id":"EytLQtu1OJ7A"},{"cell_type":"code","source":["# Sankaku Dataset Search and Captioning\n","\n","# ============================================================\n","# SANKAKU DATASET SEARCH AND CAPTIONING\n","# ============================================================\n","# DATASET-PREPARATION VERSION\n","#\n","# Features:\n","# - Randomized Parquet FILE traversal, controlled by search seed\n","# - Randomized Parquet row-group traversal\n","# - Random initial row offset\n","# - Required and excluded tag matching\n","# - Optional additional-word OR matching\n","# - Sankaku rating filters\n","# - Minimum favourites filter\n","# - Image retrieval through the 4-megapixel WebP repository\n","# - Optional Gemma 4 image captioning\n","# - Optional persistent Gemma VRAM residency across cell reruns\n","# - Two ZIP export formats controlled by LORA_TEMPLATE_OUTPUT\n","# - Standalone CSV and JSONL generation in both modes\n","# - Interactive HTML gallery and copy buttons\n","#\n","# ZIP FORMAT A: LORA_TEMPLATE_OUTPUT = False\n","# ------------------------------------------------------------\n","# 123456.jpg\n","# 123456.txt\n","# 123457.jpg\n","# 123457.txt\n","# ...\n","# sankaku_lora_dataset.jsonl\n","# search_metadata.txt\n","#\n","# TXT content:\n","#   Gemma caption + all original Sankaku tags\n","#\n","# If Gemma captioning is disabled or fails:\n","#   TXT contains the original Sankaku tags.\n","#\n","# ZIP FORMAT B: LORA_TEMPLATE_OUTPUT = True\n","# ------------------------------------------------------------\n","# 1.jpg\n","# 1_input.txt\n","# 1_output.txt\n","# 2.jpg\n","# 2_input.txt\n","# 2_output.txt\n","# ...\n","#\n","# Input TXT:\n","#   Exact prompt sent to Gemma during caption generation.\n","#\n","# Output TXT:\n","#   Exact processed Gemma response used by this pipeline.\n","#\n","# If Gemma captioning is disabled or fails:\n","#   The output TXT is still created, but is empty.\n","#\n","# The template ZIP contains ONLY the numbered triplets.\n","#\n","# IMPORTANT:\n","# - The standalone JSONL is generated in both modes.\n","# - The standalone CSV is generated in both modes.\n","# - JSONL records require a successful image export and a\n","#   non-empty Gemma-generated caption.\n","# - Template ZIP entries are independent of JSONL eligibility:\n","#   every successfully retrieved image gets a triplet.\n","#\n","# Image retrieval:\n","#   deepghs/sankaku-webp-4Mpixel\n","#\n","# Parquet metadata:\n","#   deepghs/sankaku_full\n","# ============================================================\n","\n","\n","# ============================================================\n","# INSTALL DEPENDENCIES\n","# ============================================================\n","\n","# Install the same inference stack used by the working Gemma 4 evaluation cell.\n","# torchao is deliberately removed: Colab may ship an old torchao (e.g. 0.10.0),\n","# and recent PEFT versions raise ImportError when they detect that incompatible\n","# installation. This Sankaku inference path uses bitsandbytes, not torchao.\n","!pip -q install -U cheesechaser pyarrow pandas \"pillow<12.0\" transformers accelerate peft bitsandbytes py7zr cryptography huggingface_hub torchvision safetensors sentencepiece packaging\n","!pip -q uninstall -y torchao\n","\n","\n","# ============================================================\n","# COLAB PARAMETERS\n","# ============================================================\n","\n","SEARCH_QUERY = \"mario -ai-created \" #@param {type:\"string\"}\n","ADDITIONAL_WORDS = \"peach daisy\" #@param {type:\"string\"}\n","\n","IMAGE_COUNT = 12 #@param {type:\"slider\", min:1, max:2000, step:1}\n","MIN_FAVOURITES = 11 #@param {type:\"slider\", min:0, max:1000, step:1}\n","\n","RANDOM_SEARCH_START = False #@param {type:\"boolean\"}\n","SEARCH_SEED_INPUT = \"banana123\" #@param {type:\"string\"}\n","\n","SEARCH_SKIP_AHEAD = 3 #@param {type:\"slider\", min:0, max:20, step:1}\n","\n","ENABLE_GEMMA_CAPTIONER = True #@param {type:\"boolean\"}\n","\n","GEMMA_BASE_MODEL_ID = \"coder3101/gemma-4-E2B-it-heretic\"\n","GEMMA_ADAPTER_ID = \"codeShare/gemma-4-E2B-it-heretic-image-caption-adapter\"\n","\n","GEMMA_MAX_NEW_TOKENS = 512 #@param {type:\"slider\", min:64, max:1024, step:64}\n","GEMMA_TEMPERATURE = 0.3 #@param {type:\"slider\", min:0.1, max:1.0, step:0.1}\n","\n","#@markdown ### ZIP export format\n","\n","LORA_TEMPLATE_OUTPUT = True #@param {type:\"boolean\"}\n","\n","#@markdown Disabled: original Sankaku ID image/TXT pairs.\n","#@markdown TXT contains the Gemma caption followed by all original tags.\n","#@markdown\n","#@markdown Enabled: numbered LoRA triplets:\n","#@markdown `1.jpg`, `1_input.txt`, `1_output.txt`, etc.\n","#@markdown Input contains the exact Gemma prompt. Output contains\n","#@markdown only the Gemma response and remains empty if unavailable.\n","#@markdown The template ZIP contains only these triplets.\n","\n","#@markdown ### Gemma VRAM management\n","\n","KEEP_GEMMA_IN_VRAM = True #@param {type:\"boolean\"}\n","\n","#@markdown When enabled, Gemma remains loaded after this cell finishes\n","#@markdown and can be reused if this cell is executed again.\n","#@markdown When disabled, Gemma is unloaded after captioning.\n","\n","#@markdown ### Sankaku rating filters\n","\n","INCLUDE_SAFE = True #@param {type:\"boolean\"}\n","INCLUDE_QUESTIONABLE = False #@param {type:\"boolean\"}\n","INCLUDE_EXPLICIT = False #@param {type:\"boolean\"}\n","\n","\n","# ============================================================\n","# SEARCH CONFIGURATION\n","# ============================================================\n","\n","REPO_ID = \"deepghs/sankaku_full\"\n","WEBP_REPO_ID = \"deepghs/sankaku-webp-4Mpixel\"\n","\n","IMAGE_FILES = []\n","\n","TEST_IMAGE_COUNT = int(IMAGE_COUNT)\n","TEST_MIN_FAVOURITES = int(MIN_FAVOURITES)\n","\n","MAX_ROWS_TO_EXAMINE = 10_000_000\n","BATCH_SIZE = 5000\n","\n","SEED_FILE = \"/content/sankaku_search_seed.txt\"\n","\n","GRID_MIN_WIDTH = 220\n","IMAGE_HEIGHT = 260\n","\n","THUMBNAIL_MAX_SIZE = (1000, 1000)\n","THUMBNAIL_JPEG_QUALITY = 85\n","\n","EXPORT_IMAGE_MAX_SIZE = (1024, 1024)\n","EXPORT_JPEG_QUALITY = 95\n","\n","OUTPUT_FILE = \"/content/sankaku_search_results.csv\"\n","JSONL_FILE = \"/content/sankaku_lora_dataset.jsonl\"\n","\n","if LORA_TEMPLATE_OUTPUT:\n","    ZIP_FILE = \"/content/sankaku_lora_training_template.zip\"\n","else:\n","    ZIP_FILE = \"/content/sankaku_image_text_pairs.zip\"\n","\n","# Export directory is temporary and removed after ZIP creation.\n","EXPORT_DIR = None\n","\n","\n","# ============================================================\n","# DEPENDENCY CHECK FOR GEMMA\n","# ============================================================\n","\n","import os\n","import sys\n","import subprocess\n","import importlib.metadata\n","\n","if ENABLE_GEMMA_CAPTIONER:\n","\n","    from packaging.version import Version\n","\n","    def installed_version(package_name):\n","        try:\n","            return Version(importlib.metadata.version(package_name))\n","        except importlib.metadata.PackageNotFoundError:\n","            return None\n","\n","    transformers_version = installed_version(\"transformers\")\n","    peft_version = installed_version(\"peft\")\n","    torchao_version = installed_version(\"torchao\")\n","\n","    print(\"Installed Transformers:\", transformers_version or \"not installed\")\n","    print(\"Installed PEFT:\", peft_version or \"not installed\")\n","    print(\"Installed torchao:\", torchao_version or \"not installed\")\n","\n","    # Match the package set from the supplied, working Gemma 4 inference cell.\n","    # Do not install torchao: it is not used for this bitsandbytes inference path.\n","    needs_dependency_update = (\n","        transformers_version is None\n","        or transformers_version < Version(\"5.10.1\")\n","        or peft_version is None\n","        or peft_version < Version(\"0.18.1\")\n","        or torchao_version is not None\n","    )\n","\n","    if needs_dependency_update:\n","\n","        print(\"=\" * 70)\n","        print(\"UPDATING GEMMA 4 DEPENDENCIES\")\n","        print(\"=\" * 70)\n","\n","        subprocess.run(\n","            [\n","                sys.executable,\n","                \"-m\",\n","                \"pip\",\n","                \"install\",\n","                \"-q\",\n","                \"--upgrade\",\n","                \"cheesechaser\",\n","                \"pyarrow\",\n","                \"pandas\",\n","                \"pillow<12.0\",\n","                \"transformers\",\n","                \"accelerate\",\n","                \"peft\",\n","                \"bitsandbytes\",\n","                \"py7zr\",\n","                \"cryptography\",\n","                \"huggingface_hub\",\n","                \"torchvision\",\n","                \"safetensors\",\n","                \"sentencepiece\",\n","                \"packaging\",\n","            ],\n","            check=True,\n","        )\n","\n","        # Remove stale/incompatible Colab torchao installations. PEFT's\n","        # optional torchao detection otherwise fails at import time.\n","        subprocess.run(\n","            [sys.executable, \"-m\", \"pip\", \"uninstall\", \"-y\", \"torchao\"],\n","            check=False,\n","        )\n","\n","        print(\"Gemma dependencies updated.\")\n","        print(\"Restart the Colab runtime, then run this cell again.\")\n","\n","        raise RuntimeError(\n","            \"Runtime restart required after updating Gemma dependencies. \"\n","            \"Use Runtime > Restart session, then rerun the Sankaku cell.\"\n","        )\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 secrets\n","import shutil\n","import zipfile\n","import tempfile\n","import warnings\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","    snapshot_download,\n","    HfApi,\n",")\n","\n","from pathlib import Path\n","\n","from google.colab import userdata, output, files\n","from IPython.display import display, HTML\n","\n","from cheesechaser.datapool.sankaku import SankakuWebpDataPool\n","\n","warnings.filterwarnings(\"ignore\")\n","\n","\n","# ============================================================\n","# LOAD OR GENERATE SEARCH SEED\n","# ============================================================\n","\n","def load_search_seed():\n","\n","    if RANDOM_SEARCH_START:\n","\n","        seed_text = secrets.token_hex(32)\n","\n","        with open(SEED_FILE, \"w\", encoding=\"utf-8\") as f:\n","            f.write(seed_text)\n","\n","        print(\"Random search enabled.\")\n","        print(\"Generated a fresh random seed.\")\n","        print(\"Overwrote seed file:\", SEED_FILE)\n","\n","    else:\n","\n","        seed_text = str(SEARCH_SEED_INPUT)\n","\n","        print(\"Random seed generation disabled.\")\n","        print(\"Using manual seed:\", repr(seed_text))\n","        print(\"Seed file was not modified.\")\n","\n","    return seed_text\n","\n","\n","ACTIVE_SEARCH_SEED = load_search_seed()\n","search_rng = random.Random(ACTIVE_SEARCH_SEED)\n","\n","\n","# ============================================================\n","# AUTHENTICATION\n","# ============================================================\n","\n","HF_TOKEN = userdata.get(\"HF_TOKEN\")\n","\n","if not HF_TOKEN:\n","    raise RuntimeError(\n","        \"HF_TOKEN was not found in Colab Secrets.\"\n","    )\n","\n","os.environ[\"HF_TOKEN\"] = HF_TOKEN\n","os.environ[\"HF_HUB_ENABLE_HF_TRANSFER\"] = \"1\"\n","\n","\n","# ============================================================\n","# DISCOVER AND RANDOMIZE PARQUET FILES\n","# ============================================================\n","\n","print(\"\\n\" + \"=\" * 70)\n","print(\"DISCOVERING PARQUET FILES\")\n","print(\"=\" * 70)\n","\n","api = HfApi(token=HF_TOKEN)\n","\n","repository_files = api.list_repo_files(\n","    repo_id=REPO_ID,\n","    repo_type=\"dataset\",\n",")\n","\n","IMAGE_FILES = sorted(\n","    filename\n","    for filename in repository_files\n","    if (\n","        filename.startswith(\"tables/images-\")\n","        and filename.lower().endswith(\".parquet\")\n","    )\n",")\n","\n","if not IMAGE_FILES:\n","    raise RuntimeError(\n","        f\"No tables/images-*.parquet files found in {REPO_ID}.\"\n","    )\n","\n","print(\"Discovered Parquet files:\", len(IMAGE_FILES))\n","\n","search_rng.shuffle(IMAGE_FILES)\n","\n","print(\"\\nSeeded randomized Parquet search order:\")\n","\n","for index, filename in enumerate(IMAGE_FILES, start=1):\n","    print(f\"{index:>3}. {filename}\")\n","\n","print(\"\\nFirst Parquet file to search:\")\n","print(IMAGE_FILES[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(r\"[\\s+,\\.]+\", str(text))\n","        if word.strip()\n","    ]\n","\n","\n","def parse_search_query(query):\n","\n","    required = []\n","    excluded = []\n","\n","    query = str(query).lower()\n","\n","    matches = re.finditer(r\"[^\\s+,\\.]+\", query)\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(ADDITIONAL_WORDS)\n","\n","if (\n","    not REQUIRED_TEST_TAGS\n","    and not EXCLUDED_TEST_TAGS\n","    and not ADDITIONAL_TEST_TAGS\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(\"=\" * 70)\n","print(\"SANKAKU IMAGE SEARCH\")\n","print(\"=\" * 70)\n","\n","print(\"Metadata repository:\", REPO_ID)\n","print(\"Image repository:\", WEBP_REPO_ID)\n","\n","print(\"\\nSeeded Parquet file order:\")\n","\n","for index, filename in enumerate(IMAGE_FILES, start=1):\n","    print(f\"{index:>3}. {filename}\")\n","\n","print(\"\\nMain search query:\", SEARCH_QUERY or \"(None)\")\n","print(\"Required substrings:\", REQUIRED_TEST_TAGS)\n","print(\"Excluded substrings:\", EXCLUDED_TEST_TAGS)\n","\n","print(\"\\nAdditional words:\", ADDITIONAL_TEST_TAGS)\n","print(\"Additional matching mode: OR\")\n","\n","print(\"\\nImages requested:\", TEST_IMAGE_COUNT)\n","print(\"Minimum favourites:\", TEST_MIN_FAVOURITES)\n","print(\"Maximum rows to examine:\", f\"{MAX_ROWS_TO_EXAMINE:,}\")\n","print(\"Batch size:\", BATCH_SIZE)\n","print(\"Skip ahead after each match:\", SEARCH_SKIP_AHEAD)\n","\n","print(\"\\nRandom seed generation:\", RANDOM_SEARCH_START)\n","print(\"Manual seed input:\", repr(SEARCH_SEED_INPUT))\n","print(\"Active search seed:\", repr(ACTIVE_SEARCH_SEED))\n","print(\"Seed file:\", SEED_FILE)\n","\n","print(\"\\nGemma captioner:\", ENABLE_GEMMA_CAPTIONER)\n","\n","if ENABLE_GEMMA_CAPTIONER:\n","    print(\"Gemma base model:\", GEMMA_BASE_MODEL_ID)\n","    print(\"Gemma LoRA adapter:\", GEMMA_ADAPTER_ID)\n","    print(\"Maximum new tokens:\", GEMMA_MAX_NEW_TOKENS)\n","    print(\"Temperature:\", GEMMA_TEMPERATURE)\n","    print(\"Keep Gemma in VRAM:\", KEEP_GEMMA_IN_VRAM)\n","\n","print(\"\\nZIP export format:\")\n","print(\n","    \"Numbered LoRA triplets\"\n","    if LORA_TEMPLATE_OUTPUT\n","    else \"Original Sankaku ID image-text pairs\"\n",")\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 (TypeError, ValueError, OverflowError):\n","        return 0\n","\n","\n","# ============================================================\n","# RATING FILTER\n","# ============================================================\n","\n","ALLOWED_RATINGS = {\n","    rating\n","    for rating, enabled in (\n","        (\"s\", INCLUDE_SAFE),\n","        (\"q\", INCLUDE_QUESTIONABLE),\n","        (\"e\", INCLUDE_EXPLICIT),\n","    )\n","    if enabled\n","}\n","\n","\n","def normalize_rating(value):\n","\n","    if value is None:\n","        return \"\"\n","\n","    try:\n","        if pd.isna(value):\n","            return \"\"\n","    except (TypeError, ValueError):\n","        pass\n","\n","    return str(value).strip().lower()\n","\n","\n","if not ALLOWED_RATINGS:\n","    raise ValueError(\n","        \"Enable at least one Sankaku rating filter.\"\n","    )\n","\n","\n","# ============================================================\n","# SEARCH PARQUET FILES\n","# ============================================================\n","\n","print(\"\\n\" + \"=\" * 70)\n","print(\"SEARCHING PARQUET FILES\")\n","print(\"=\" * 70)\n","\n","test_results = []\n","\n","rows_examined = 0\n","rows_skipped = 0\n","batches_examined = 0\n","\n","tag_matches = 0\n","rating_rejected = 0\n","favourites_rejected = 0\n","\n","search_finished = False\n","search_stop_reason = \"Search not started\"\n","\n","skip_remaining = 0\n","\n","initial_offset_remaining = 0\n","initial_offset_set = False\n","\n","row_group_order_metadata = []\n","\n","\n","for image_filename in IMAGE_FILES:\n","\n","    if search_finished:\n","        break\n","\n","    print(\"\\nOpening:\", image_filename)\n","\n","    image_file = hf_hub_download(\n","        repo_id=REPO_ID,\n","        repo_type=\"dataset\",\n","        filename=image_filename,\n","        token=HF_TOKEN,\n","    )\n","\n","    pf = pq.ParquetFile(image_file)\n","\n","    available_columns = set(pf.schema_arrow.names)\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","    required_columns = {\n","        \"id\",\n","        \"tags\",\n","        \"fav_count\",\n","        \"rating\",\n","    }\n","\n","    missing_columns = required_columns - set(columns)\n","\n","    if missing_columns:\n","        raise RuntimeError(\n","            f\"{image_filename} is missing required columns: \"\n","            f\"{sorted(missing_columns)}\"\n","        )\n","\n","    print(\"Total rows:\", f\"{pf.metadata.num_rows:,}\")\n","    print(\"Row groups:\", pf.num_row_groups)\n","\n","    # --------------------------------------------------------\n","    # RANDOMIZE ROW-GROUP ORDER\n","    # --------------------------------------------------------\n","\n","    row_groups = list(range(pf.num_row_groups))\n","    search_rng.shuffle(row_groups)\n","\n","    row_group_order_metadata.append({\n","        \"file\": image_filename,\n","        \"row_groups\": list(row_groups),\n","    })\n","\n","    print(\"Randomized row-group order enabled.\")\n","\n","    if row_groups:\n","        print(\"Starting row group:\", row_groups[0])\n","\n","    # --------------------------------------------------------\n","    # RANDOMIZE INITIAL ROW OFFSET\n","    # --------------------------------------------------------\n","\n","    if not initial_offset_set and row_groups:\n","\n","        first_group = row_groups[0]\n","\n","        first_group_rows = (\n","            pf.metadata.row_group(first_group).num_rows\n","        )\n","\n","        if first_group_rows > 0:\n","\n","            initial_offset_remaining = search_rng.randrange(\n","                first_group_rows\n","            )\n","\n","        else:\n","\n","            initial_offset_remaining = 0\n","\n","        initial_offset_set = True\n","\n","        print(\n","            \"Random starting row offset:\",\n","            f\"{initial_offset_remaining:,}\",\n","            \"of\",\n","            f\"{first_group_rows:,}\",\n","        )\n","\n","    # --------------------------------------------------------\n","    # PROCESS RANDOMIZED ROW GROUPS\n","    # --------------------------------------------------------\n","\n","    for row_group_number, row_group in enumerate(\n","        row_groups,\n","        start=1,\n","    ):\n","\n","        if search_finished:\n","            break\n","\n","        print(\n","            f\"\\nProcessing row 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","            data = batch.to_pydict()\n","\n","            for i, image_tags in enumerate(data[\"tags\"]):\n","\n","                # ------------------------------------------------\n","                # INITIAL RANDOM OFFSET\n","                # ------------------------------------------------\n","\n","                if initial_offset_remaining > 0:\n","\n","                    initial_offset_remaining -= 1\n","                    rows_skipped += 1\n","                    continue\n","\n","                # ------------------------------------------------\n","                # SKIP AHEAD AFTER A QUALIFYING MATCH\n","                # ------------------------------------------------\n","\n","                if skip_remaining > 0:\n","\n","                    skip_remaining -= 1\n","                    rows_skipped += 1\n","                    continue\n","\n","                # ------------------------------------------------\n","                # CHECK ROW LIMIT\n","                # ------------------------------------------------\n","\n","                if rows_examined >= MAX_ROWS_TO_EXAMINE:\n","\n","                    search_finished = True\n","                    search_stop_reason = (\n","                        \"Maximum examined-row limit reached\"\n","                    )\n","                    break\n","\n","                rows_examined += 1\n","\n","                # ------------------------------------------------\n","                # CHECK TAG CONDITIONS\n","                # ------------------------------------------------\n","\n","                if matches_tag_conditions(image_tags):\n","\n","                    tag_matches += 1\n","\n","                    # --------------------------------------------\n","                    # CHECK RATING\n","                    # --------------------------------------------\n","\n","                    image_rating = normalize_rating(\n","                        data[\"rating\"][i]\n","                    )\n","\n","                    if image_rating not in ALLOWED_RATINGS:\n","\n","                        rating_rejected += 1\n","\n","                    else:\n","\n","                        # ----------------------------------------\n","                        # CHECK FAVOURITES\n","                        # ----------------------------------------\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","                        else:\n","\n","                            # ------------------------------------\n","                            # CHECK IMAGE ID\n","                            # ------------------------------------\n","\n","                            image_id_value = data[\"id\"][i]\n","\n","                            if image_id_value is not None:\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[\"gemma_caption\"] = \"\"\n","                                result[\"input_text\"] = \"\"\n","                                result[\"output_text\"] = \"\"\n","                                result[\"image\"] = \"\"\n","\n","                                test_results.append(result)\n","\n","                                print(\n","                                    f\"  MATCH {len(test_results)}/\"\n","                                    f\"{TEST_IMAGE_COUNT}: \"\n","                                    f\"ID {result['id']} \"\n","                                    f\"({fav_count} favourites)\"\n","                                )\n","\n","                                # --------------------------------\n","                                # SET SKIP-AHEAD COUNTER\n","                                # --------------------------------\n","\n","                                skip_remaining = int(\n","                                    SEARCH_SKIP_AHEAD\n","                                )\n","\n","                                if skip_remaining > 0:\n","\n","                                    print(\n","                                        f\"  Skipping the next \"\n","                                        f\"{skip_remaining} Parquet rows.\"\n","                                    )\n","\n","                                # --------------------------------\n","                                # CHECK IMAGE COUNT\n","                                # --------------------------------\n","\n","                                if len(test_results) >= TEST_IMAGE_COUNT:\n","\n","                                    search_finished = True\n","                                    search_stop_reason = (\n","                                        \"Requested image count reached\"\n","                                    )\n","                                    break\n","\n","                # ------------------------------------------------\n","                # CHECK ROW LIMIT AFTER CURRENT ROW\n","                # ------------------------------------------------\n","\n","                if rows_examined >= MAX_ROWS_TO_EXAMINE:\n","\n","                    search_finished = True\n","                    search_stop_reason = (\n","                        \"Maximum examined-row limit reached\"\n","                    )\n","                    break\n","\n","            del data\n","\n","            if search_finished:\n","                break\n","\n","        print(\n","            f\"Rows examined: {rows_examined:,} | \"\n","            f\"Rows skipped: {rows_skipped:,} | \"\n","            f\"Tag matches: {tag_matches:,} | \"\n","            f\"Rejected by rating: {rating_rejected:,} | \"\n","            f\"Rejected by favourites: {favourites_rejected:,} | \"\n","            f\"Matches: {len(test_results)}/{TEST_IMAGE_COUNT}\"\n","        )\n","\n","        if search_finished:\n","            break\n","\n","    del pf\n","    gc.collect()\n","\n","    if search_finished:\n","        break\n","\n","\n","# ============================================================\n","# SEARCH SUMMARY\n","# ============================================================\n","\n","print(\"\\n\" + \"=\" * 70)\n","print(\"PARQUET SEARCH SUMMARY\")\n","print(\"=\" * 70)\n","\n","print(\"Tag matches:\", tag_matches)\n","print(\"Rejected by rating:\", rating_rejected)\n","print(\"Rejected by favourites:\", favourites_rejected)\n","print(\"Qualifying matches:\", len(test_results))\n","print(\"Images requested:\", TEST_IMAGE_COUNT)\n","print(\"Minimum favourites:\", TEST_MIN_FAVOURITES)\n","print(\"Rows examined:\", f\"{rows_examined:,}\")\n","print(\"Rows skipped:\", f\"{rows_skipped:,}\")\n","print(\"Batches examined:\", f\"{batches_examined:,}\")\n","print(\"Skip ahead setting:\", SEARCH_SKIP_AHEAD)\n","print(\"Stop reason:\", search_stop_reason)\n","print(\"Active search seed:\", repr(ACTIVE_SEARCH_SEED))\n","\n","if not test_results:\n","    raise RuntimeError(\n","        \"No images matched the search conditions and minimum favourites threshold.\"\n","    )\n","\n","if len(test_results) < TEST_IMAGE_COUNT:\n","    print(\n","        f\"Only found {len(test_results)} qualifying matches \"\n","        f\"within the scanned rows.\"\n","    )\n","\n","\n","# ============================================================\n","# GEMMA MODEL STATE\n","# ============================================================\n","\n","if \"gemma_model\" not in globals():\n","    gemma_model = None\n","\n","if \"gemma_processor\" not in globals():\n","    gemma_processor = None\n","\n","if \"gemma_device\" not in globals():\n","    gemma_device = None\n","\n","if \"gemma_dtype\" not in globals():\n","    gemma_dtype = None\n","\n","if \"gemma_input_device\" not in globals():\n","    gemma_input_device = None\n","\n","if \"gemma_loaded_model_id\" not in globals():\n","    gemma_loaded_model_id = None\n","\n","\n","# ============================================================\n","# UNLOAD GEMMA\n","# ============================================================\n","\n","def unload_gemma():\n","\n","    global gemma_model\n","    global gemma_processor\n","    global gemma_device\n","    global gemma_dtype\n","    global gemma_input_device\n","    global gemma_loaded_model_id\n","\n","    print(\"\\n\" + \"=\" * 70)\n","    print(\"UNLOADING GEMMA\")\n","    print(\"=\" * 70)\n","\n","    gemma_model = None\n","    gemma_processor = None\n","\n","    gemma_device = None\n","    gemma_dtype = None\n","    gemma_input_device = None\n","    gemma_loaded_model_id = None\n","\n","    gc.collect()\n","\n","    try:\n","\n","        import torch\n","\n","        if torch.cuda.is_available():\n","\n","            torch.cuda.synchronize()\n","            torch.cuda.empty_cache()\n","\n","            print(\n","                \"GPU memory allocated:\",\n","                f\"{torch.cuda.memory_allocated() / (1024**3):.2f} GB\"\n","            )\n","\n","            print(\n","                \"GPU memory reserved:\",\n","                f\"{torch.cuda.memory_reserved() / (1024**3):.2f} GB\"\n","            )\n","\n","    except Exception as exc:\n","\n","        print(\"GPU cleanup warning:\", str(exc))\n","\n","    print(\"Gemma references released.\")\n","\n","\n","# ============================================================\n","# LOAD GEMMA 4\n","# ============================================================\n","\n","def load_gemma():\n","\n","    global gemma_model\n","    global gemma_processor\n","    global gemma_device\n","    global gemma_dtype\n","    global gemma_input_device\n","    global gemma_loaded_model_id\n","\n","    import torch\n","    import transformers\n","    import json\n","\n","    from packaging.version import Version\n","    from transformers import (\n","        AutoProcessor,\n","        AutoModelForMultimodalLM,\n","        BitsAndBytesConfig,\n","    )\n","    from peft import PeftModel\n","\n","    print(\"\\n\" + \"=\" * 70)\n","    print(\"GEMMA 4 CAPTIONER\")\n","    print(\"=\" * 70)\n","\n","    print(\"Transformers:\", transformers.__version__)\n","\n","    if Version(transformers.__version__) < Version(\"5.10.1\"):\n","        raise RuntimeError(\n","            \"Gemma 4 requires Transformers 5.10.1 or newer. \"\n","            \"Restart the Colab runtime and run the cell again.\"\n","        )\n","\n","    if not torch.cuda.is_available():\n","        raise RuntimeError(\n","            \"Gemma captioning requires a CUDA GPU. \"\n","            \"In Colab, select Runtime -> Change runtime type -> GPU.\"\n","        )\n","\n","    # --------------------------------------------------------\n","    # REUSE EXISTING MODEL\n","    # --------------------------------------------------------\n","\n","    requested_model_id = f\"{GEMMA_BASE_MODEL_ID}+{GEMMA_ADAPTER_ID}\"\n","\n","    if (\n","        gemma_model is not None\n","        and gemma_processor is not None\n","        and gemma_loaded_model_id == requested_model_id\n","    ):\n","\n","        print(\"An existing Gemma model was found.\")\n","        print(\"Reusing the model already loaded in this runtime.\")\n","        print(\"Model:\", gemma_loaded_model_id)\n","\n","        try:\n","            print(\n","                \"GPU memory allocated:\",\n","                f\"{torch.cuda.memory_allocated() / (1024**3):.2f} GB\"\n","            )\n","        except Exception:\n","            pass\n","\n","        return\n","\n","    # --------------------------------------------------------\n","    # REMOVE OLD MODEL IF MODEL ID CHANGED\n","    # --------------------------------------------------------\n","\n","    if gemma_model is not None:\n","        print(\"A different Gemma model is currently loaded.\")\n","        unload_gemma()\n","\n","    print(\"Loading base model:\", GEMMA_BASE_MODEL_ID)\n","    print(\"Downloading LoRA adapter:\", GEMMA_ADAPTER_ID)\n","\n","    gemma_device = \"cuda\"\n","\n","    # Match the supplied, working Gemma 4 evaluation code.\n","    gemma_dtype = (\n","        torch.bfloat16\n","        if torch.cuda.is_bf16_supported()\n","        else torch.float16\n","    )\n","\n","    print(\"Device:\", gemma_device)\n","    print(\"Dtype:\", gemma_dtype)\n","    print(\"Device map: auto\")\n","    print(\"4-bit quantization: enabled\")\n","    print(\"Keep in VRAM:\", KEEP_GEMMA_IN_VRAM)\n","\n","    # --------------------------------------------------------\n","    # DOWNLOAD ADAPTER REPOSITORY LOCALLY\n","    # --------------------------------------------------------\n","    # Do not pass the remote repository ID directly to PEFT.\n","    # Download the complete repository first, then load PEFT\n","    # from the verified local directory, as in the working cell.\n","    # --------------------------------------------------------\n","\n","    adapter_download_dir = Path(\"/content/new_published_adapter\")\n","    adapter_download_dir.mkdir(parents=True, exist_ok=True)\n","\n","    adapter_repo_dir = snapshot_download(\n","        repo_id=GEMMA_ADAPTER_ID,\n","        repo_type=\"model\",\n","        token=HF_TOKEN,\n","        local_dir=str(adapter_download_dir),\n","    )\n","\n","    adapter_dir = Path(adapter_repo_dir)\n","\n","    adapter_config_path = adapter_dir / \"adapter_config.json\"\n","\n","    if not adapter_config_path.is_file():\n","        raise FileNotFoundError(\n","            \"adapter_config.json was not found in the downloaded adapter \"\n","            f\"repository: {adapter_dir}. Check that {GEMMA_ADAPTER_ID} \"\n","            \"contains a PEFT adapter.\"\n","        )\n","\n","    with adapter_config_path.open(\"r\", encoding=\"utf-8\") as f:\n","        adapter_config = json.load(f)\n","\n","    print(\"\\nAdapter configuration:\")\n","    print(\"PEFT type:\", adapter_config.get(\"peft_type\"))\n","    print(\"Base model:\", adapter_config.get(\"base_model_name_or_path\"))\n","    print(\"Rank:\", adapter_config.get(\"r\"))\n","    print(\"Target modules:\", adapter_config.get(\"target_modules\"))\n","\n","    adapter_weight_files = (\n","        list(adapter_dir.glob(\"adapter_model.safetensors\"))\n","        + list(adapter_dir.glob(\"adapter_model.bin\"))\n","    )\n","\n","    if not adapter_weight_files:\n","        raise FileNotFoundError(\n","            \"Neither adapter_model.safetensors nor adapter_model.bin \"\n","            f\"was found in {adapter_dir}.\"\n","        )\n","\n","    print(\"Adapter weights:\", [p.name for p in adapter_weight_files])\n","\n","    # --------------------------------------------------------\n","    # LOAD PROCESSOR FROM THE BASE MODEL\n","    # --------------------------------------------------------\n","    # The LoRA repository supplies adapter weights/configuration.\n","    # The multimodal processor must come from the base model.\n","    # --------------------------------------------------------\n","\n","    print(\"\\nLoading Gemma 4 processor...\")\n","\n","    gemma_processor = AutoProcessor.from_pretrained(\n","        GEMMA_BASE_MODEL_ID,\n","        token=HF_TOKEN,\n","    )\n","\n","    print(\"Processor loaded successfully.\")\n","\n","    # --------------------------------------------------------\n","    # LOAD BASE MODEL IN 4-BIT\n","    # --------------------------------------------------------\n","\n","    print(\"\\nPreparing 4-bit quantization...\")\n","\n","    quantization_config = BitsAndBytesConfig(\n","        load_in_4bit=True,\n","        bnb_4bit_quant_type=\"nf4\",\n","        bnb_4bit_use_double_quant=True,\n","        bnb_4bit_compute_dtype=gemma_dtype,\n","    )\n","\n","    print(\"\\nLoading base Gemma 4 model...\")\n","\n","    gemma_base_model = AutoModelForMultimodalLM.from_pretrained(\n","        GEMMA_BASE_MODEL_ID,\n","        token=HF_TOKEN,\n","        quantization_config=quantization_config,\n","        dtype=gemma_dtype,\n","        device_map=\"auto\",\n","        low_cpu_mem_usage=True,\n","    )\n","\n","    gemma_base_model.config.use_cache = True\n","\n","    # --------------------------------------------------------\n","    # ATTACH THE VERIFIED LOCAL LORA ADAPTER\n","    # --------------------------------------------------------\n","\n","    print(\"\\nAttaching published LoRA adapter from local directory...\")\n","\n","    try:\n","        gemma_model = PeftModel.from_pretrained(\n","            gemma_base_model,\n","            str(adapter_dir),\n","            is_trainable=False,\n","            autocast_adapter_dtype=True,\n","        ).eval()\n","\n","    except Exception:\n","        # Do not leave a partially loaded base model occupying VRAM\n","        # if adapter attachment fails.\n","        del gemma_base_model\n","        gemma_model = None\n","        gemma_processor = None\n","        gc.collect()\n","        torch.cuda.empty_cache()\n","        raise\n","\n","    # The PEFT wrapper retains the base model.\n","    del gemma_base_model\n","\n","    gemma_loaded_model_id = requested_model_id\n","\n","    # Use the device containing the input embeddings.\n","    try:\n","        gemma_input_device = (\n","            gemma_model.get_input_embeddings().weight.device\n","        )\n","    except Exception:\n","        gemma_input_device = gemma_model.device\n","\n","    print(\"\\nGemma loaded successfully.\")\n","    print(\"Adapter directory:\", adapter_dir)\n","    print(\"Input device:\", gemma_input_device)\n","    print(\"Model device map:\", getattr(gemma_model, \"hf_device_map\", \"Not available\"))\n","\n","    try:\n","        print(\n","            \"GPU memory allocated:\",\n","            f\"{torch.cuda.memory_allocated() / (1024**3):.2f} GB\"\n","        )\n","        print(\n","            \"GPU memory reserved:\",\n","            f\"{torch.cuda.memory_reserved() / (1024**3):.2f} GB\"\n","        )\n","    except Exception:\n","        pass\n","\n","\n","# ============================================================\n","# IMAGE TO DATA URI\n","# ============================================================\n","\n","def image_to_data_url(image: Image.Image) -> str:\n","\n","    buffer = io.BytesIO()\n","\n","    image.convert(\"RGB\").save(\n","        buffer,\n","        format=\"PNG\",\n","    )\n","\n","    encoded = base64.b64encode(\n","        buffer.getvalue()\n","    ).decode(\"utf-8\")\n","\n","    return f\"data:image/png;base64,{encoded}\"\n","\n","\n","# ============================================================\n","# BUILD GEMMA INPUT PROMPT\n","# ============================================================\n","# Shared by Gemma generation, CSV, JSONL, and template ZIP.\n","# The exact returned string is stored in item[\"input_text\"].\n","# ============================================================\n","\n","def build_caption_prompt(tags):\n","\n","    if isinstance(tags, str):\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","    # Keep the exact training-style instruction and substitute the\n","    # original Sankaku tags for the <tags> placeholder.\n","    return f\"Please describe this image using these tags <{tag_str}> \"\n","\n","\n","# ============================================================\n","# NORMALIZE GENERATED CAPTION\n","# ============================================================\n","\n","def normalize_caption_text(text):\n","\n","    if text is None:\n","        return \"\"\n","\n","    text = str(text)\n","\n","    text = re.sub(\n","        r\"\\s+\",\n","        \" \",\n","        text,\n","    )\n","\n","    return text.strip()\n","\n","\n","# ============================================================\n","# GEMMA CAPTION GENERATION\n","# ============================================================\n","\n","def gemma_caption(\n","    image: Image.Image,\n","    tags,\n","    max_new_tokens=None,\n",") -> str:\n","\n","    import torch\n","\n","    if gemma_model is None or gemma_processor is None:\n","        raise RuntimeError(\n","            \"Gemma has not been initialized. Call load_gemma() first.\"\n","        )\n","\n","    prompt = build_caption_prompt(tags)\n","\n","    image_url = image_to_data_url(image)\n","\n","    messages = [\n","        {\n","            \"role\": \"user\",\n","            \"content\": [\n","                {\n","                    \"type\": \"image\",\n","                    \"url\": image_url,\n","                },\n","                {\n","                    \"type\": \"text\",\n","                    \"text\": prompt,\n","                },\n","            ],\n","        }\n","    ]\n","\n","    inputs = gemma_processor.apply_chat_template(\n","        messages,\n","        add_generation_prompt=True,\n","        tokenize=True,\n","        return_tensors=\"pt\",\n","        return_dict=True,\n","    )\n","\n","    inputs = inputs.to(gemma_input_device)\n","\n","    token_limit = (\n","        max_new_tokens\n","        if max_new_tokens is not None\n","        else GEMMA_MAX_NEW_TOKENS\n","    )\n","\n","    generation_kwargs = {\n","        \"max_new_tokens\": int(token_limit),\n","        \"repetition_penalty\": 1.05,\n","    }\n","\n","    if GEMMA_TEMPERATURE > 0:\n","\n","        generation_kwargs.update({\n","            \"do_sample\": True,\n","            \"temperature\": float(GEMMA_TEMPERATURE),\n","            \"top_p\": 0.9,\n","        })\n","\n","    else:\n","\n","        generation_kwargs[\"do_sample\"] = False\n","\n","    with torch.inference_mode():\n","\n","        outputs = gemma_model.generate(\n","            **inputs,\n","            **generation_kwargs,\n","        )\n","\n","    input_length = inputs[\"input_ids\"].shape[-1]\n","\n","    generated_tokens = outputs[0][input_length:]\n","\n","    raw_response = gemma_processor.decode(\n","        generated_tokens,\n","        skip_special_tokens=False,\n","    )\n","\n","    if hasattr(gemma_processor, \"parse_response\"):\n","\n","        try:\n","\n","            parsed_response = gemma_processor.parse_response(\n","                raw_response\n","            )\n","\n","        except Exception:\n","\n","            parsed_response = raw_response\n","\n","    else:\n","\n","        parsed_response = raw_response\n","\n","    caption = normalize_caption_text(\n","        parsed_response\n","        if isinstance(parsed_response, str)\n","        else str(parsed_response)\n","    )\n","\n","    del inputs\n","    del outputs\n","    del generated_tokens\n","\n","    return caption\n","\n","\n","# ============================================================\n","# INITIALIZE OPTIONAL CAPTIONER\n","# ============================================================\n","\n","if ENABLE_GEMMA_CAPTIONER:\n","\n","    load_gemma()\n","\n","else:\n","\n","    print(\n","        \"\\nGemma captioning disabled. \"\n","        \"Skipping model download.\"\n","    )\n","\n","\n","# ============================================================\n","# INITIALIZE WEBP SANKAKU DATAPOOL\n","# ============================================================\n","\n","print(\"\\n\" + \"=\" * 70)\n","print(\"INITIALIZING SANKAKU WEBP DATAPOOL\")\n","print(\"=\" * 70)\n","\n","print(\"Image repository:\", WEBP_REPO_ID)\n","\n","pool = SankakuWebpDataPool(\n","    hf_token=HF_TOKEN\n",")\n","\n","print(\"WebP 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(root, filename)\n","            candidates.append(filepath)\n","\n","    if not candidates:\n","        raise RuntimeError(\n","            \"SankakuWebpDataPool returned no files.\"\n","        )\n","\n","    preferred_extensions = [\n","        \".webp\",\n","        \".jpg\",\n","        \".jpeg\",\n","        \".png\",\n","        \".gif\",\n","        \".bmp\",\n","        \".tif\",\n","        \".tiff\",\n","    ]\n","\n","    def extension_priority(path):\n","\n","        extension = os.path.splitext(path)[1].lower()\n","\n","        try:\n","            return preferred_extensions.index(extension)\n","\n","        except ValueError:\n","            return len(preferred_extensions)\n","\n","    candidates.sort(\n","        key=lambda path: (\n","            extension_priority(path),\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 by the WebP DataPool.\"\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","        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(thumbnail_bytes).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","        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 STANDARD IMAGE-TEXT EXPORT\n","# ============================================================\n","# Used only when LORA_TEMPLATE_OUTPUT is False.\n","#\n","# TXT = Gemma caption + original Sankaku tags.\n","#\n","# If no caption is available:\n","# TXT = original Sankaku tags.\n","#\n","# No caption length limit is imposed here.\n","# ============================================================\n","\n","def make_export_text(item):\n","\n","    natural_caption = normalize_caption_text(\n","        item.get(\"gemma_caption\", \"\")\n","    )\n","\n","    tags = item.get(\"tags\", [])\n","\n","    if isinstance(tags, str):\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","    if natural_caption and tags_text:\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","# RETRIEVE WEBP IMAGES + OPTIONAL GEMMA CAPTIONS\n","# ============================================================\n","\n","print(\"\\n\" + \"=\" * 70)\n","print(\"FETCHING MATCHING WEBP IMAGES\")\n","print(\"=\" * 70)\n","\n","image_data_uris = {}\n","\n","downloaded_bytes = 0\n","failed_images = []\n","caption_failures = []\n","\n","EXPORT_DIR = tempfile.mkdtemp(\n","    prefix=\"sankaku_export_\"\n",")\n","\n","export_image_count = 0\n","\n","for number, item in enumerate(test_results, start=1):\n","\n","    image_id = str(int(item[\"id\"]))\n","\n","    print(\n","        f\"\\n[{number}/{len(test_results)}] \"\n","        f\"Retrieving WebP 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(temp_dir)\n","\n","            original_size = os.path.getsize(image_path)\n","            downloaded_bytes += original_size\n","\n","            with Image.open(image_path) as retrieved_image:\n","\n","                retrieved_format = retrieved_image.format\n","                retrieved_dimensions = retrieved_image.size\n","\n","            print(\n","                f\"Image retrieved: {original_size / 1024:.1f} KB\"\n","            )\n","\n","            print(\n","                f\"Format: {retrieved_format} | \"\n","                f\"Dimensions: {retrieved_dimensions[0]} × \"\n","                f\"{retrieved_dimensions[1]}\"\n","            )\n","\n","            # ------------------------------------------------\n","            # THUMBNAIL FOR DISPLAY\n","            # ------------------------------------------------\n","\n","            image_data_uris[image_id] = (\n","                make_thumbnail_data_uri(image_path)\n","            )\n","\n","            # ------------------------------------------------\n","            # BUILD AND STORE EXACT GEMMA INPUT PROMPT\n","            # ------------------------------------------------\n","\n","            input_text = build_caption_prompt(\n","                item.get(\"tags\", [])\n","            )\n","\n","            item[\"input_text\"] = input_text\n","\n","            # ------------------------------------------------\n","            # OPTIONAL GEMMA CAPTION\n","            # ------------------------------------------------\n","\n","            if ENABLE_GEMMA_CAPTIONER:\n","\n","                try:\n","\n","                    print(\n","                        \"Generating Gemma caption \"\n","                        \"from image + Sankaku tags...\"\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 = gemma_caption(\n","                        image=caption_image,\n","                        tags=item.get(\"tags\", []),\n","                    )\n","\n","                    item[\"gemma_caption\"] = caption\n","                    item[\"output_text\"] = caption\n","\n","                    print(\"Gemma caption:\", caption)\n","\n","                    del caption_image\n","\n","                    if not caption.strip():\n","\n","                        caption_failures.append(image_id)\n","\n","                        print(\n","                            \"WARNING: Gemma returned an empty caption.\"\n","                        )\n","\n","                except Exception as caption_error:\n","\n","                    item[\"gemma_caption\"] = \"\"\n","                    item[\"output_text\"] = \"\"\n","\n","                    caption_failures.append(image_id)\n","\n","                    print(\n","                        \"GEMMA CAPTION FAILED:\",\n","                        type(caption_error).__name__,\n","                        str(caption_error),\n","                    )\n","\n","                    try:\n","\n","                        import torch\n","\n","                        if torch.cuda.is_available():\n","                            torch.cuda.empty_cache()\n","\n","                    except Exception:\n","                        pass\n","\n","            else:\n","\n","                item[\"gemma_caption\"] = \"\"\n","                item[\"output_text\"] = \"\"\n","\n","            # ------------------------------------------------\n","            # PREPARE IMAGE EXPORT\n","            # ------------------------------------------------\n","            # Both ZIP modes require the JPG.\n","            # TXT files are created later according to mode.\n","            # ------------------------------------------------\n","\n","            image_export_path = os.path.join(\n","                EXPORT_DIR,\n","                f\"{image_id}.jpg\",\n","            )\n","\n","            try:\n","\n","                export_image_bytes = prepare_export_image(\n","                    image_path\n","                )\n","\n","                with open(image_export_path, \"wb\") as file:\n","                    file.write(export_image_bytes)\n","\n","                item[\"image\"] = f\"{image_id}.jpg\"\n","                export_image_count += 1\n","\n","                print(f\"Image export prepared: {image_id}.jpg\")\n","\n","                if (\n","                    ENABLE_GEMMA_CAPTIONER\n","                    and item[\"output_text\"]\n","                ):\n","\n","                    print(\n","                        \"LoRA JSONL training example: eligible\"\n","                    )\n","\n","                else:\n","\n","                    print(\n","                        \"LoRA JSONL training example: excluded \"\n","                        \"(no generated Gemma caption)\"\n","                    )\n","\n","            except Exception as export_error:\n","\n","                print(\n","                    \"IMAGE EXPORT FAILED:\",\n","                    type(export_error).__name__,\n","                    str(export_error),\n","                )\n","\n","                item[\"image\"] = \"\"\n","\n","                if os.path.exists(image_export_path):\n","                    os.remove(image_export_path)\n","\n","    except Exception as exc:\n","\n","        failed_images.append(image_id)\n","        image_data_uris.pop(image_id, None)\n","\n","        item[\"gemma_caption\"] = \"\"\n","        item[\"input_text\"] = \"\"\n","        item[\"output_text\"] = \"\"\n","        item[\"image\"] = \"\"\n","\n","        print(\n","            f\"IMAGE RETRIEVAL FAILED: \"\n","            f\"{type(exc).__name__}: {exc}\"\n","        )\n","\n","    gc.collect()\n","\n","\n","# ============================================================\n","# GEMMA VRAM CLEANUP / PERSISTENCE\n","# ============================================================\n","\n","print(\"\\n\" + \"=\" * 70)\n","print(\"GEMMA MEMORY MANAGEMENT\")\n","print(\"=\" * 70)\n","\n","if ENABLE_GEMMA_CAPTIONER:\n","\n","    if KEEP_GEMMA_IN_VRAM:\n","\n","        print(\"KEEP_GEMMA_IN_VRAM is enabled.\")\n","        print(\"Gemma remains loaded in this Colab runtime.\")\n","        print(\"A subsequent execution of this cell can reuse it.\")\n","\n","        try:\n","\n","            import torch\n","\n","            if torch.cuda.is_available():\n","\n","                print(\n","                    \"GPU memory allocated:\",\n","                    f\"{torch.cuda.memory_allocated() / (1024**3):.2f} GB\"\n","                )\n","\n","                print(\n","                    \"GPU memory reserved:\",\n","                    f\"{torch.cuda.memory_reserved() / (1024**3):.2f} GB\"\n","                )\n","\n","        except Exception:\n","            pass\n","\n","    else:\n","\n","        print(\"KEEP_GEMMA_IN_VRAM is disabled.\")\n","        print(\"Unloading Gemma after captioning.\")\n","\n","        unload_gemma()\n","\n","else:\n","\n","    print(\"Gemma captioning was disabled.\")\n","\n","\n","# ============================================================\n","# BUILD JSONL TRAINING RECORDS\n","# ============================================================\n","# JSONL remains the same in both ZIP modes.\n","#\n","# Only include records that have:\n","# - A successfully exported JPG\n","# - A non-empty input prompt\n","# - A non-empty Gemma-generated output caption\n","#\n","# JSONL image filenames always use original Sankaku IDs.\n","# ============================================================\n","\n","training_records = []\n","\n","for item in test_results:\n","\n","    image_filename = str(\n","        item.get(\"image\", \"\") or \"\"\n","    ).strip()\n","\n","    input_text = str(\n","        item.get(\"input_text\", \"\") or \"\"\n","    ).strip()\n","\n","    output_text = normalize_caption_text(\n","        item.get(\"output_text\", \"\")\n","    )\n","\n","    if not image_filename:\n","        continue\n","\n","    if not input_text:\n","        continue\n","\n","    if not output_text:\n","        continue\n","\n","    image_path = os.path.join(\n","        EXPORT_DIR,\n","        image_filename,\n","    )\n","\n","    if not os.path.isfile(image_path):\n","        continue\n","\n","    record = {\n","        \"image\": image_filename,\n","        \"input_text\": input_text,\n","        \"output_text\": output_text,\n","    }\n","\n","    training_records.append(record)\n","\n","\n","print(\"\\n\" + \"=\" * 70)\n","print(\"LORA DATASET PREPARATION\")\n","print(\"=\" * 70)\n","\n","print(\"Retrieved image exports:\", export_image_count)\n","print(\"Captioned JSONL training examples:\", len(training_records))\n","print(\n","    \"Images excluded from JSONL:\",\n","    export_image_count - len(training_records),\n",")\n","\n","\n","# ============================================================\n","# SAVE STANDALONE JSONL MANIFEST\n","# ============================================================\n","# This file is generated in BOTH ZIP modes.\n","# It always references original Sankaku ID image filenames.\n","# ============================================================\n","\n","print(\"\\n\" + \"=\" * 70)\n","print(\"SAVING LORA JSONL MANIFEST\")\n","print(\"=\" * 70)\n","\n","with open(\n","    JSONL_FILE,\n","    \"w\",\n","    encoding=\"utf-8\",\n",") as file:\n","\n","    for record in training_records:\n","\n","        file.write(\n","            json.dumps(\n","                record,\n","                ensure_ascii=False,\n","            )\n","            + \"\\n\"\n","        )\n","\n","print(\"JSONL saved:\", JSONL_FILE)\n","print(\"Training records:\", len(training_records))\n","\n","\n","# ============================================================\n","# CREATE SEARCH METADATA\n","# ============================================================\n","\n","row_group_order_text = \"\\n\".join(\n","    (\n","        f\"{entry['file']}: \"\n","        + \", \".join(map(str, entry[\"row_groups\"]))\n","    )\n","    for entry in row_group_order_metadata\n",")\n","\n","if LORA_TEMPLATE_OUTPUT:\n","\n","    zip_format_description = (\n","        \"Numbered LoRA input/output triplets.\"\n","    )\n","\n","    zip_contents_description = (\n","        \"Only numbered JPG/input TXT/output TXT triplets. \"\n","        \"No JSONL or metadata files are included.\"\n","    )\n","\n","    zip_pairing_description = \"\"\"\n","Each successfully exported image is assigned a sequential number.\n","\n","For every image, the ZIP contains:\n","- N.jpg\n","- N_input.txt\n","- N_output.txt\n","\n","The input TXT contains the exact prompt used for Gemma generation.\n","\n","The output TXT contains the processed Gemma response only.\n","Original Sankaku tags are not appended to the output.\n","\n","If Gemma captioning is disabled or fails, the output TXT\n","is still included but is empty.\n","\n","The template ZIP contains only these triplets.\n","\"\"\".strip()\n","\n","else:\n","\n","    zip_format_description = (\n","        \"Original Sankaku ID image-text pairs.\"\n","    )\n","\n","    zip_contents_description = (\n","        \"Original ID JPG/TXT pairs, \"\n","        \"sankaku_lora_dataset.jsonl, and search_metadata.txt.\"\n","    )\n","\n","    zip_pairing_description = \"\"\"\n","Each successfully exported image is named with its original\n","Sankaku ID.\n","\n","For every image, the ZIP contains:\n","- OriginalID.jpg\n","- OriginalID.txt\n","\n","The TXT contains the Gemma caption followed by all original\n","Sankaku tags.\n","\n","If Gemma captioning is disabled or fails, the TXT contains\n","the original Sankaku tags only.\n","\n","The ZIP also contains the standalone JSONL manifest and\n","search metadata.\n","\"\"\".strip()\n","\n","\n","search_metadata = f\"\"\"\n","SANKAKU SEARCH AND LORA DATASET METADATA\n","========================================\n","\n","SEARCH CONFIGURATION\n","--------------------\n","\n","Metadata repository:\n","{REPO_ID}\n","\n","Image repository:\n","{WEBP_REPO_ID}\n","\n","Parquet files (seeded search order):\n","{\", \".join(IMAGE_FILES)}\n","\n","First Parquet file:\n","{IMAGE_FILES[0] if IMAGE_FILES else \"(None)\"}\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","Skip ahead after each qualifying match:\n","{SEARCH_SKIP_AHEAD}\n","\n","Search stop reason:\n","{search_stop_reason}\n","\n","\n","RANDOM SEARCH AND SEED\n","----------------------\n","\n","Random search seed generation enabled:\n","{RANDOM_SEARCH_START}\n","\n","User-entered seed:\n","{SEARCH_SEED_INPUT!r}\n","\n","Active search seed:\n","{ACTIVE_SEARCH_SEED!r}\n","\n","Active search seed (plain text):\n","{ACTIVE_SEARCH_SEED}\n","\n","Active search seed (UTF-8 hexadecimal):\n","{ACTIVE_SEARCH_SEED.encode(\"utf-8\").hex()}\n","\n","Seed file:\n","{SEED_FILE}\n","\n","Seed file behavior:\n","{\n","    \"A fresh random seed was generated and the seed file was overwritten.\"\n","    if RANDOM_SEARCH_START\n","    else \"The manual seed was used. The existing seed file was not modified.\"\n","}\n","\n","Search traversal:\n","Seeded randomized Parquet file order, row-group order, and initial row offset.\n","\n","Randomization method:\n","Python random.Random using the active seed.\n","\n","Parquet file order:\n","{chr(10).join(IMAGE_FILES) or \"(Not available)\"}\n","\n","Row-group order:\n","{row_group_order_text or \"(Not available)\"}\n","\n","\n","SEARCH RESULTS\n","--------------\n","\n","Rows examined:\n","{rows_examined}\n","\n","Rows skipped:\n","{rows_skipped}\n","\n","Batches examined:\n","{batches_examined}\n","\n","Tag matches:\n","{tag_matches}\n","\n","Rejected by rating:\n","{rating_rejected}\n","\n","Rejected by favourites:\n","{favourites_rejected}\n","\n","Qualifying matches:\n","{len(test_results)}\n","\n","\n","RATING FILTERS\n","--------------\n","\n","Include safe:\n","{INCLUDE_SAFE}\n","\n","Include questionable:\n","{INCLUDE_QUESTIONABLE}\n","\n","Include explicit:\n","{INCLUDE_EXPLICIT}\n","\n","Allowed ratings:\n","{\", \".join(sorted(ALLOWED_RATINGS))}\n","\n","\n","GEMMA CONFIGURATION\n","-------------------\n","\n","Gemma captioner enabled:\n","{ENABLE_GEMMA_CAPTIONER}\n","\n","Gemma base model:\n","{GEMMA_BASE_MODEL_ID}\n","\n","Gemma LoRA adapter:\n","{GEMMA_ADAPTER_ID}\n","\n","Gemma maximum new tokens:\n","{GEMMA_MAX_NEW_TOKENS}\n","\n","Gemma caption prompt template:\n","Please describe this image using these tags <tags>\n","\n","Gemma temperature:\n","{GEMMA_TEMPERATURE}\n","\n","Keep Gemma in VRAM:\n","{KEEP_GEMMA_IN_VRAM}\n","\n","Gemma model remains loaded after this run:\n","{\n","    ENABLE_GEMMA_CAPTIONER and KEEP_GEMMA_IN_VRAM\n","}\n","\n","\n","IMAGE RETRIEVAL\n","---------------\n","\n","Image repository:\n","{WEBP_REPO_ID}\n","\n","Image retrieval method:\n","CheeseChaser SankakuWebpDataPool\n","\n","Images successfully retrieved:\n","{len(image_data_uris)}\n","\n","Failed image retrievals:\n","{len(failed_images)}\n","\n","Caption failures:\n","{len(caption_failures)}\n","\n","Successfully exported JPG images:\n","{export_image_count}\n","\n","Total downloaded image data:\n","{downloaded_bytes / (1024 * 1024):.2f} MB\n","\n","\n","LORA DATASET EXPORT\n","-------------------\n","\n","ZIP export mode:\n","{zip_format_description}\n","\n","LORA_TEMPLATE_OUTPUT:\n","{LORA_TEMPLATE_OUTPUT}\n","\n","Standalone CSV:\n","{OUTPUT_FILE}\n","\n","Standalone JSONL:\n","{JSONL_FILE}\n","\n","JSONL records:\n","{len(training_records)}\n","\n","JSONL image field:\n","Relative original-ID JPG filename\n","\n","JSONL input field:\n","input_text\n","\n","JSONL output field:\n","output_text\n","\n","JSONL input format:\n","The exact Gemma captioning instruction used during generation.\n","\n","JSONL output format:\n","Gemma-generated natural-language caption only.\n","\n","Original Sankaku tags:\n","Included in input_text.\n","\n","Original Sankaku tags appended to JSONL output_text:\n","No.\n","\n","Captionless samples:\n","Excluded from the JSONL manifest.\n","\n","ZIP pairing:\n","{zip_pairing_description}\n","\n","ZIP contents:\n","{zip_contents_description}\n","\n","Image format:\n","JPEG\n","\n","Maximum image dimension:\n","{EXPORT_IMAGE_MAX_SIZE[0]} × {EXPORT_IMAGE_MAX_SIZE[1]}\n","\n","JPEG quality:\n","{EXPORT_JPEG_QUALITY}\n","\n","\n","EXPORT FILES\n","------------\n","\n","CSV:\n","{OUTPUT_FILE}\n","\n","JSONL:\n","{JSONL_FILE}\n","\n","ZIP:\n","{ZIP_FILE}\n","\n","\n","NOTES\n","-----\n","\n","The active search seed is included in this metadata file.\n","\n","When random seed generation is enabled, a new random seed is\n","generated for each run. The manual seed input is ignored.\n","The seed file at /content/sankaku_search_seed.txt is overwritten.\n","\n","When random seed generation is disabled, the exact user-entered\n","seed string is used. The seed file is not modified.\n","\n","Using the same manual seed and unchanged Parquet repository file\n","listing produces the same randomized Parquet file order, row-group\n","orders, and initial row offset.\n","\n","The Parquet repository file listing is sorted before it is shuffled.\n","This ensures that the same manual seed starts from the same\n","deterministic initial file list.\n","\n","The initial random row offset is applied only once, at the\n","beginning of the first selected row group in the first selected file.\n","\n","The skip-ahead setting skips the specified number of physical\n","Parquet rows after each qualifying match.\n","\n","Rows skipped are counted separately from rows examined.\n","\n","The maximum row limit applies only to examined rows, not skipped rows.\n","\n","The search stops when the requested image count is reached\n","or the maximum row examination limit is reached.\n","\n","Image IDs are retrieved from the 4-megapixel Sankaku WebP dataset.\n","\n","The standalone CSV and JSONL are generated regardless of ZIP mode.\n","\n","The JSONL manifest always uses original Sankaku ID image filenames\n","and contains only samples with successful image retrieval and\n","non-empty Gemma-generated captions.\n","\n","The JSONL output_text field contains only the generated caption.\n","Original Sankaku tags are not appended to the target caption.\n","\n","The ZIP archive format is controlled by LORA_TEMPLATE_OUTPUT.\n","\n","This cell prepares the dataset only. It does not train a LoRA.\n","\"\"\".strip()\n","\n","\n","# ============================================================\n","# CREATE ZIP ARCHIVE\n","# ============================================================\n","# A ZIP is ALWAYS created.\n","#\n","# Standard mode:\n","#   OriginalID.jpg + OriginalID.txt\n","#   sankaku_lora_dataset.jsonl\n","#   search_metadata.txt\n","#\n","# Template mode:\n","#   1.jpg + 1_input.txt + 1_output.txt\n","#   2.jpg + 2_input.txt + 2_output.txt\n","#   ...\n","#   No additional files.\n","# ============================================================\n","\n","print(\"\\n\" + \"=\" * 70)\n","print(\"CREATING ZIP ARCHIVE\")\n","print(\"=\" * 70)\n","\n","print(\"ZIP mode:\", zip_format_description)\n","print(\"ZIP destination:\", ZIP_FILE)\n","\n","if os.path.exists(ZIP_FILE):\n","    os.remove(ZIP_FILE)\n","\n","\n","# ------------------------------------------------------------\n","# FIND ALL SUCCESSFULLY EXPORTED IMAGE FILES\n","# ------------------------------------------------------------\n","\n","complete_image_ids = []\n","\n","for item in test_results:\n","\n","    image_id = str(int(item[\"id\"]))\n","\n","    image_path = os.path.join(\n","        EXPORT_DIR,\n","        f\"{image_id}.jpg\",\n","    )\n","\n","    if os.path.isfile(image_path):\n","        complete_image_ids.append(image_id)\n","\n","\n","# Remove duplicate IDs while preserving original result order.\n","complete_image_ids = list(dict.fromkeys(complete_image_ids))\n","\n","export_image_count = len(complete_image_ids)\n","\n","\n","# ------------------------------------------------------------\n","# MAP ORIGINAL IMAGE IDS TO THEIR RESULT ITEMS\n","# ------------------------------------------------------------\n","\n","items_by_image_id = {\n","    str(int(item[\"id\"])): item\n","    for item in test_results\n","}\n","\n","\n","# ------------------------------------------------------------\n","# CREATE ZIP\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","    # ========================================================\n","    # TEMPLATE MODE: NUMBERED IMAGE / INPUT / OUTPUT TRIPLETS\n","    # ========================================================\n","\n","    if LORA_TEMPLATE_OUTPUT:\n","\n","        print(\"Creating numbered LoRA training triplets.\")\n","\n","        for number, image_id in enumerate(\n","            complete_image_ids,\n","            start=1,\n","        ):\n","\n","            item = items_by_image_id[image_id]\n","\n","            image_path = os.path.join(\n","                EXPORT_DIR,\n","                f\"{image_id}.jpg\",\n","            )\n","\n","            input_text = str(\n","                item.get(\"input_text\", \"\") or \"\"\n","            )\n","\n","            output_text = str(\n","                item.get(\"output_text\", \"\") or \"\"\n","            )\n","\n","            # ------------------------------------------------\n","            # IMAGE\n","            # ------------------------------------------------\n","\n","            archive.write(\n","                image_path,\n","                arcname=f\"{number}.jpg\",\n","            )\n","\n","            # ------------------------------------------------\n","            # INPUT TXT\n","            # Exact prompt stored during Gemma preparation.\n","            # ------------------------------------------------\n","\n","            archive.writestr(\n","                f\"{number}_input.txt\",\n","                input_text,\n","            )\n","\n","            # ------------------------------------------------\n","            # OUTPUT TXT\n","            # Exact processed Gemma response.\n","            # An empty output file is intentionally created\n","            # when Gemma is disabled or captioning failed.\n","            # ------------------------------------------------\n","\n","            archive.writestr(\n","                f\"{number}_output.txt\",\n","                output_text,\n","            )\n","\n","            print(\n","                f\"  {number}: \"\n","                f\"{number}.jpg + \"\n","                f\"{number}_input.txt + \"\n","                f\"{number}_output.txt\"\n","            )\n","\n","    # ========================================================\n","    # STANDARD MODE: ORIGINAL ID IMAGE / TEXT PAIRS\n","    # ========================================================\n","\n","    else:\n","\n","        print(\"Creating original-ID image-text pairs.\")\n","\n","        for image_id in complete_image_ids:\n","\n","            item = items_by_image_id[image_id]\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","            # ------------------------------------------------\n","            # JPG\n","            # ------------------------------------------------\n","\n","            archive.write(\n","                image_path,\n","                arcname=f\"{image_id}.jpg\",\n","            )\n","\n","            # ------------------------------------------------\n","            # TXT: GEMMA CAPTION + ALL ORIGINAL SANKAKU TAGS\n","            # ------------------------------------------------\n","\n","            export_text = make_export_text(item)\n","\n","            archive.writestr(\n","                f\"{image_id}.txt\",\n","                export_text,\n","            )\n","\n","        # ----------------------------------------------------\n","        # JSONL MANIFEST\n","        # ----------------------------------------------------\n","\n","        archive.write(\n","            JSONL_FILE,\n","            arcname=\"sankaku_lora_dataset.jsonl\",\n","        )\n","\n","        # ----------------------------------------------------\n","        # SEARCH METADATA\n","        # ----------------------------------------------------\n","\n","        archive.writestr(\n","            \"search_metadata.txt\",\n","            search_metadata,\n","        )\n","\n","\n","# ============================================================\n","# ZIP VALIDATION\n","# ============================================================\n","\n","with zipfile.ZipFile(ZIP_FILE, \"r\") as archive:\n","\n","    zip_entries = archive.namelist()\n","\n","    if LORA_TEMPLATE_OUTPUT:\n","\n","        expected_entry_count = export_image_count * 3\n","\n","        if len(zip_entries) != expected_entry_count:\n","            raise RuntimeError(\n","                \"Template ZIP validation failed: \"\n","                f\"expected {expected_entry_count} files, \"\n","                f\"found {len(zip_entries)}.\"\n","            )\n","\n","        for number in range(1, export_image_count + 1):\n","\n","            expected_triplet = {\n","                f\"{number}.jpg\",\n","                f\"{number}_input.txt\",\n","                f\"{number}_output.txt\",\n","            }\n","\n","            if not expected_triplet.issubset(set(zip_entries)):\n","                raise RuntimeError(\n","                    f\"Template ZIP is missing files for item {number}.\"\n","                )\n","\n","        if (\n","            \"sankaku_lora_dataset.jsonl\" in zip_entries\n","            or \"search_metadata.txt\" in zip_entries\n","        ):\n","            raise RuntimeError(\n","                \"Template ZIP unexpectedly contains extra manifest \"\n","                \"or metadata files.\"\n","            )\n","\n","    else:\n","\n","        expected_pair_entries = export_image_count * 2\n","\n","        required_extra_entries = {\n","            \"sankaku_lora_dataset.jsonl\",\n","            \"search_metadata.txt\",\n","        }\n","\n","        if len(zip_entries) != (\n","            expected_pair_entries + len(required_extra_entries)\n","        ):\n","            raise RuntimeError(\n","                \"Standard ZIP validation failed: unexpected file count.\"\n","            )\n","\n","        if not required_extra_entries.issubset(set(zip_entries)):\n","            raise RuntimeError(\n","                \"Standard ZIP is missing its JSONL or metadata file.\"\n","            )\n","\n","\n","zip_size_mb = os.path.getsize(ZIP_FILE) / (1024 * 1024)\n","\n","print(\"\\nZIP validation successful.\")\n","print(\"ZIP entries:\", len(zip_entries))\n","print(\"Exported images:\", export_image_count)\n","\n","if LORA_TEMPLATE_OUTPUT:\n","\n","    print(\"ZIP format: numbered LoRA triplets\")\n","    print(\"Images:\", export_image_count)\n","    print(\"Input TXT files:\", export_image_count)\n","    print(\"Output TXT files:\", export_image_count)\n","    print(\"Extra files: none\")\n","\n","else:\n","\n","    print(\"ZIP format: original-ID image-text pairs\")\n","    print(\"JPG files:\", export_image_count)\n","    print(\"TXT files:\", export_image_count)\n","    print(\"JSONL included: yes\")\n","    print(\"Metadata included: yes\")\n","\n","print(\"Active search seed:\", repr(ACTIVE_SEARCH_SEED))\n","print(\"ZIP file:\", ZIP_FILE)\n","print(f\"ZIP size: {zip_size_mb:.2f} MB\")\n","\n","\n","# ============================================================\n","# SAVE CSV RESULTS INCLUDING TRAINING FIELDS\n","# ============================================================\n","\n","results_df = pd.DataFrame(test_results)\n","\n","# Ensure these fields exist even if captioning was disabled.\n","for column in (\n","    \"image\",\n","    \"input_text\",\n","    \"output_text\",\n","    \"gemma_caption\",\n","):\n","    if column not in results_df.columns:\n","        results_df[column] = \"\"\n","\n","results_df.to_csv(\n","    OUTPUT_FILE,\n","    index=False,\n","    encoding=\"utf-8\",\n",")\n","\n","\n","# ============================================================\n","# RETRIEVAL SUMMARY\n","# ============================================================\n","\n","print(\"\\n\" + \"=\" * 70)\n","print(\"RETRIEVAL AND DATASET SUMMARY\")\n","print(\"=\" * 70)\n","\n","print(\"Matching Parquet rows:\", len(test_results))\n","print(\"Images requested:\", TEST_IMAGE_COUNT)\n","print(\"Minimum favourites:\", TEST_MIN_FAVOURITES)\n","print(\"Images downloaded:\", len(image_data_uris))\n","print(\"Images failed:\", len(failed_images))\n","print(\"Caption failures:\", len(caption_failures))\n","print(\"Exported JPG images:\", export_image_count)\n","\n","print(\"LoRA JSONL records:\", len(training_records))\n","print(\n","    \"Images excluded from LoRA JSONL:\",\n","    export_image_count - len(training_records),\n",")\n","\n","print(\n","    \"Downloaded WebP image data:\",\n","    f\"{downloaded_bytes / (1024 * 1024):.2f} MB\"\n",")\n","\n","print(\"Rows examined:\", f\"{rows_examined:,}\")\n","print(\"Rows skipped:\", f\"{rows_skipped:,}\")\n","print(\"Skip ahead setting:\", SEARCH_SKIP_AHEAD)\n","print(\"Stop reason:\", search_stop_reason)\n","\n","print(\"Random seed generation enabled:\", RANDOM_SEARCH_START)\n","print(\"Manual seed input:\", repr(SEARCH_SEED_INPUT))\n","print(\"Active search seed:\", repr(ACTIVE_SEARCH_SEED))\n","\n","print(\"Parquet files discovered:\", len(IMAGE_FILES))\n","print(\"First Parquet file:\", IMAGE_FILES[0] if IMAGE_FILES else \"(None)\")\n","\n","print(\"Gemma captioner:\", ENABLE_GEMMA_CAPTIONER)\n","print(\"Keep Gemma in VRAM:\", KEEP_GEMMA_IN_VRAM)\n","\n","print(\"\\nZIP export mode:\")\n","print(zip_format_description)\n","\n","print(\"\\nOutput files:\")\n","print(\"CSV:\", OUTPUT_FILE)\n","print(\"JSONL:\", JSONL_FILE)\n","print(\"ZIP:\", ZIP_FILE)\n","\n","\n","if failed_images:\n","    print(\"\\nFailed image IDs:\", failed_images)\n","\n","if caption_failures:\n","    print(\"\\nCaption failure IDs:\", caption_failures)\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","        raise FileNotFoundError(\n","            \"The ZIP archive could not be found.\"\n","        )\n","\n","    files.download(ZIP_FILE)\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","        safe_tag = html.escape(tag_string)\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(rendered)\n","\n","\n","# ============================================================\n","# BUILD COPY TEXT\n","# ============================================================\n","\n","def make_copy_text(item):\n","\n","    tags = item.get(\"tags\", [])\n","\n","    if isinstance(tags, str):\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 = normalize_caption_text(\n","        item.get(\"gemma_caption\", \"\")\n","    )\n","\n","    if ENABLE_GEMMA_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 Gemma caption + tags\"\n","\n","    else:\n","\n","        copy_text = tags_text\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(int(item[\"id\"]))\n","    image_uri = image_data_uris.get(image_id)\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(\"width\", \"\")\n","    height = item.get(\"height\", \"\")\n","\n","    metadata = []\n","\n","    if pd.notna(width) and pd.notna(height):\n","\n","        metadata.append(\n","            f\"{html.escape(str(width))} × \"\n","            f\"{html.escape(str(height))}\"\n","        )\n","\n","    fav_count = item.get(\"fav_count\", \"\")\n","\n","    if pd.notna(fav_count):\n","\n","        metadata.append(\n","            f\"Favourites: {html.escape(str(fav_count))}\"\n","        )\n","\n","    author = item.get(\"author_name\", \"\")\n","\n","    if pd.notna(author) and str(author).strip():\n","\n","        metadata.append(\n","            f\"Artist: {html.escape(str(author))}\"\n","        )\n","\n","    natural_caption = normalize_caption_text(\n","        item.get(\"gemma_caption\", \"\")\n","    )\n","\n","    if natural_caption:\n","\n","        natural_caption_html = f\"\"\"\n","            <div class=\"gemma-caption\">\n","                <div class=\"caption-heading\">\n","                    Gemma-4 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(item)\n","    copy_text_b64 = encode_copy_text(copy_text)\n","\n","    training_status = (\n","        \"LoRA JSONL training example\"\n","        if (\n","            item.get(\"image\")\n","            and item.get(\"input_text\")\n","            and item.get(\"output_text\")\n","        )\n","        else \"Not included in LoRA JSONL\"\n","    )\n","\n","    training_status_html = f\"\"\"\n","        <div class=\"training-status\">\n","            {html.escape(training_status)}\n","        </div>\n","    \"\"\"\n","\n","    cards.append(f\"\"\"\n","        <div class=\"image-card\">\n","\n","            <div class=\"image-container\">\n","                <img\n","                    src=\"{image_uri}\"\n","                    alt=\"Sankaku image {html.escape(image_id)}\"\n","                    loading=\"lazy\"\n","                >\n","            </div>\n","\n","            <div class=\"image-info\">\n","\n","                <div class=\"image-meta\">\n","                    <span>ID: {html.escape(image_id)}</span>\n","                    <span>{rating}</span>\n","                </div>\n","\n","                <div class=\"extra-meta\">\n","                    {html.escape(\" | \".join(metadata))}\n","                </div>\n","\n","                {training_status_html}\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","# HTML ZIP DESCRIPTION\n","# ============================================================\n","\n","if LORA_TEMPLATE_OUTPUT:\n","\n","    zip_button_label = (\n","        \"Download LoRA training template (.zip)\"\n","    )\n","\n","    zip_description_html = f\"\"\"\n","        ZIP contains {export_image_count} numbered triplets:\n","        JPG image, exact Gemma input prompt, and Gemma output text.\n","        Empty output TXT files are retained when captioning fails.\n","        No JSONL or metadata files are included in this ZIP.\n","    \"\"\"\n","\n","else:\n","\n","    zip_button_label = (\n","        \"Download image-text pairs (.zip)\"\n","    )\n","\n","    zip_description_html = f\"\"\"\n","        ZIP contains {export_image_count} original-ID JPG/TXT pairs.\n","        Each TXT contains the Gemma caption followed by all original\n","        Sankaku tags, or tags only if no caption is available.\n","        The ZIP also includes the JSONL manifest and search metadata.\n","        The JSONL contains {len(training_records)} complete\n","        image + input_text + output_text examples.\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 {{\n","    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 {{\n","    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",".gemma-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",".training-status {{\n","    color:#a78bfa;\n","    font-size:10px;\n","    font-weight:bold;\n","    margin:7px 0;\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","        button.textContent = \"Nothing to copy\";\n","        return;\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","        textarea.setAttribute(\"readonly\", \"\");\n","\n","        textarea.style.position = \"fixed\";\n","        textarea.style.left = \"-9999px\";\n","        textarea.style.top = \"0\";\n","\n","        document.body.appendChild(textarea);\n","\n","        textarea.focus();\n","        textarea.select();\n","        textarea.setSelectionRange(0, textarea.value.length);\n","\n","        let success = false;\n","\n","        try {{\n","            success = document.execCommand(\"copy\");\n","        }} catch (error) {{\n","            success = false;\n","        }}\n","\n","        textarea.remove();\n","\n","        return success;\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","                throw new Error(\"Clipboard fallback failed.\");\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","    button.disabled = true;\n","\n","    google.colab.kernel.invokeFunction(\n","        \"sankaku.download_zip\",\n","        [],\n","        {{}}\n","    ).then(\n","        function() {{\n","            button.textContent = \"Download requested\";\n","            setTimeout(() => {{\n","                button.textContent = originalLabel;\n","                button.disabled = false;\n","            }}, 2000);\n","        }},\n","        function(error) {{\n","            console.error(\"ZIP download failed:\", error);\n","            button.textContent = \"Download failed\";\n","            button.disabled = false;\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","        Rows skipped:\n","        {rows_skipped:,}\n","\n","        |\n","\n","        Skip ahead:\n","        {SEARCH_SKIP_AHEAD}\n","\n","        |\n","\n","        Maximum rows:\n","        {MAX_ROWS_TO_EXAMINE:,}\n","\n","        |\n","\n","        Images requested:\n","        {TEST_IMAGE_COUNT}\n","\n","        |\n","\n","        Random seed generation:\n","        {\"Enabled\" if RANDOM_SEARCH_START else \"Disabled\"}\n","\n","        |\n","\n","        Active seed:\n","        {html.escape(repr(ACTIVE_SEARCH_SEED))}\n","\n","        |\n","\n","        First Parquet file:\n","        {html.escape(IMAGE_FILES[0] if IMAGE_FILES else \"None\")}\n","\n","        |\n","\n","        Image source:\n","        {html.escape(WEBP_REPO_ID)}\n","\n","        |\n","\n","        Gemma:\n","        {\"Enabled\" if ENABLE_GEMMA_CAPTIONER else \"Disabled\"}\n","\n","        |\n","\n","        Keep Gemma in VRAM:\n","        {\"Yes\" if KEEP_GEMMA_IN_VRAM else \"No\"}\n","\n","        |\n","\n","        ZIP mode:\n","        {html.escape(zip_format_description)}\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","        {zip_button_label} — {export_image_count} images\n","    </button>\n","\n","    <div style=\"color:#999;font-size:11px;margin-bottom:16px\">\n","        {zip_description_html}\n","    </div>\n","\n","    <div class=\"sankaku-grid\">\n","        {''.join(cards)}\n","    </div>\n","\n","</div>\n","\"\"\"\n","\n","display(HTML(grid_html))\n","\n","\n","# ============================================================\n","# CLEAN UP TEMPORARY EXPORT DIRECTORY\n","# ============================================================\n","# ZIP, CSV, and JSONL have already been saved.\n","# The temporary export directory is no longer needed.\n","# ============================================================\n","\n","shutil.rmtree(\n","    EXPORT_DIR,\n","    ignore_errors=True,\n",")\n","\n","\n","# ============================================================\n","# FINAL SUMMARY\n","# ============================================================\n","\n","print(\"\\n\" + \"=\" * 70)\n","print(\"DATASET PREPARATION COMPLETE\")\n","print(\"=\" * 70)\n","\n","print(\"Metadata repository:\", REPO_ID)\n","print(\"Image repository:\", WEBP_REPO_ID)\n","\n","print(\"\\nZIP export mode:\")\n","print(zip_format_description)\n","\n","print(\"\\nOutput files:\")\n","print(\"CSV:\", OUTPUT_FILE)\n","print(\"JSONL:\", JSONL_FILE)\n","print(\"ZIP:\", ZIP_FILE)\n","\n","print(\"\\nDataset counts:\")\n","print(\"Search matches:\", len(test_results))\n","print(\"Exported JPG images:\", export_image_count)\n","print(\"LoRA JSONL records:\", len(training_records))\n","\n","print(\"\\nSearch statistics:\")\n","print(\"Rows examined:\", f\"{rows_examined:,}\")\n","print(\"Rows skipped:\", f\"{rows_skipped:,}\")\n","print(\"Skip ahead setting:\", SEARCH_SKIP_AHEAD)\n","print(\"Stop reason:\", search_stop_reason)\n","\n","print(\"\\nRandomization:\")\n","print(\"Random seed generation enabled:\", RANDOM_SEARCH_START)\n","print(\"Active search seed:\", repr(ACTIVE_SEARCH_SEED))\n","print(\"Seed input file:\", SEED_FILE)\n","\n","if ENABLE_GEMMA_CAPTIONER and KEEP_GEMMA_IN_VRAM:\n","    print(\n","        \"\\nGemma remains loaded in VRAM \"\n","        \"for subsequent cell executions.\"\n","    )\n","\n","elif ENABLE_GEMMA_CAPTIONER:\n","    print(\"\\nGemma was unloaded after captioning.\")\n","\n","print(\"\\nZIP contents:\")\n","\n","if LORA_TEMPLATE_OUTPUT:\n","\n","    print(\"- N.jpg\")\n","    print(\"- N_input.txt\")\n","    print(\"- N_output.txt\")\n","    print(\"- One triplet for each successfully exported image\")\n","    print(\"- No additional files\")\n","\n","else:\n","\n","    print(\"- Original Sankaku ID JPG files\")\n","    print(\"- Matching TXT files containing caption + tags\")\n","    print(\"- sankaku_lora_dataset.jsonl\")\n","    print(\"- search_metadata.txt\")\n","\n","print(\"\\nStandalone JSONL contains:\")\n","print(\"- image\")\n","print(\"- input_text\")\n","print(\"- output_text\")\n","\n","print(\"\\nNo LoRA training was started.\")\n"],"metadata":{"cellView":"form","id":"2iNwkUP7DTFC"},"id":"2iNwkUP7DTFC","execution_count":null,"outputs":[]},{"cell_type":"markdown","source":[" # Upload zipped results to drive as encryped 7zip using password"],"metadata":{"id":"l3cD3WGpXoiU"},"id":"l3cD3WGpXoiU"},{"cell_type":"code","source":["from google.colab import drive\n","drive.mount('/content/drive')"],"metadata":{"id":"eWymkqmoXqnF"},"id":"eWymkqmoXqnF","execution_count":null,"outputs":[]},{"cell_type":"code","metadata":{"id":"48b0b131"},"source":["#@title ✦ Encrypt and Upload Dataset to Google Drive ✦ { display-mode: \"form\" }\n","\n","import os\n","import subprocess\n","from google.colab import drive\n","\n","#@markdown ### 1. Google Drive Setup\n","#@markdown Press play to run this cell. It will ask for permission to mount your Google Drive if it isn't already mounted.\n","MOUNT_PATH = \"/content/drive\"\n","target_drive_folder = \"/My Drive/SankakuDatasets\" #@param {type:\"string\"}\n","\n","#@markdown ### 2. Output 7z Configuration\n","output_filename = \"/content/drive/MyDrive/sankaku_lora_training_completed.7z\" #@param {type:\"string\"}\n","encryption_password = \"my_password\" #@param {type:\"string\"}\n","\n","# Ensure dependencies\n","print(\"Installing p7zip-full...\")\n","subprocess.run([\"apt-get\", \"install\", \"-y\", \"p7zip-full\"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n","\n","# Mount Google Drive\n","if not os.path.exists(MOUNT_PATH):\n","    print(\"Mounting Google Drive...\")\n","    drive.mount(MOUNT_PATH)\n","else:\n","    print(\"Google Drive is already mounted.\")\n","\n","# Define paths\n","source_zip = \"/content/sankaku_lora_training_completed.zip\"\n","if not os.path.exists(source_zip):\n","    # Fallback to template ZIP if completed ZIP has not been generated by the Gradio editor yet\n","    source_zip = \"/content/sankaku_lora_training_template.zip\"\n","\n","if not os.path.exists(source_zip):\n","    raise FileNotFoundError(\"No dataset ZIP archive found at '/content/sankaku_lora_training_completed.zip' or '/content/sankaku_lora_training_template.zip'. Please run the search/editor cell first.\")\n","\n","# Create Google Drive destination folder if it doesn't exist\n","full_drive_path = MOUNT_PATH + target_drive_folder\n","os.makedirs(full_drive_path, exist_ok=True)\n","\n","# Ensure output filename ends with .7z\n","if not output_filename.endswith(\".7z\"):\n","    output_filename += \".7z\"\n","\n","destination_7z_path = os.path.join(full_drive_path, output_filename)\n","\n","if not encryption_password or encryption_password == \"your_secure_password_here\":\n","    print(\"WARNING: Please set a secure custom password in the form input.\")\n","\n","print(f\"Encrypting '{source_zip}' into '{destination_7z_path}'...\")\n","\n","# Compress with 7z using strong encryption (AES-256) and header encryption (-mhe=on)\n","command = [\n","    \"7z\", \"a\",\n","    f\"-p{encryption_password}\",\n","    \"-mhe=on\",\n","    destination_7z_path,\n","    source_zip\n","]\n","\n","result = subprocess.run(command, capture_output=True, text=True)\n","\n","if result.returncode == 0:\n","    print(\"\\n[SUCCESS] Encrypted 7z dataset created and saved to Google Drive!\")\n","    print(f\"Location: {destination_7z_path}\")\n","    print(f\"Size: {os.path.getsize(destination_7z_path) / (1024*1024):.2f} MB\")\n","else:\n","    print(\"\\n[ERROR] Encryption failed.\")\n","    print(result.stderr)"],"id":"48b0b131","execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["# Dataset Editor window\n","\n"],"metadata":{"id":"RF6CbL6QXEYf"},"id":"RF6CbL6QXEYf"},{"cell_type":"code","source":["# ============================================================\n","# SANKAKU LORA - MOBILE FRIENDLY IMAGE CAPTION EDITOR\n","# Auto-decrypt | Caption Editor | Encrypted Google Drive Backup\n","# Responsive Gradio UI | Dark / Orange / Purple Theme\n","# SAFE NAVIGATION EDITION\n","# ============================================================\n","\n","import os\n","import re\n","import zipfile\n","import shutil\n","import subprocess\n","import threading\n","\n","from pathlib import Path\n","\n","import gradio as gr\n","from google.colab import drive\n","\n","\n","# ============================================================\n","# CONFIGURATION\n","# ============================================================\n","\n","MOUNT_PATH = \"/content/drive\"\n","\n","TARGET_DRIVE_FOLDER = \"/My Drive/SankakuDatasets\"\n","\n","encryption_password = \"my_password\"  #@param {type:\"string\"}\n","\n","save_write_encrypted_filepath_7z = \"/content/drive/MyDrive/sankaku_lora_training_completed.7z\" #@param {type:\"string\"}\n","\n","\n","# ============================================================\n","# MOUNT GOOGLE DRIVE\n","# ============================================================\n","\n","if not os.path.isdir(os.path.join(MOUNT_PATH, \"MyDrive\")):\n","\n","    print(\"Mounting Google Drive...\")\n","\n","    drive.mount(MOUNT_PATH)\n","\n","else:\n","\n","    print(\"Google Drive is already mounted.\")\n","\n","\n","# ============================================================\n","# INSTALL DEPENDENCIES\n","# ============================================================\n","\n","print(\"Installing Gradio...\")\n","\n","!pip -q install -U gradio\n","\n","print(\"Installing p7zip-full...\")\n","\n","subprocess.run(\n","    [\"apt-get\", \"install\", \"-y\", \"p7zip-full\"],\n","    stdout=subprocess.DEVNULL,\n","    stderr=subprocess.DEVNULL,\n","    check=True\n",")\n","\n","\n","# ============================================================\n","# PATH CONFIGURATION\n","# ============================================================\n","\n","if not save_write_encrypted_filepath_7z.endswith(\".7z\"):\n","\n","    save_write_encrypted_filepath_7z += \".7z\"\n","\n","\n","# Accept either an absolute Drive path or a filename.\n","\n","if save_write_encrypted_filepath_7z.startswith(\"/\"):\n","\n","    DRIVE_7Z_PATH = save_write_encrypted_filepath_7z\n","\n","else:\n","\n","    DRIVE_7Z_PATH = os.path.join(\n","        MOUNT_PATH,\n","        TARGET_DRIVE_FOLDER.lstrip(\"/\"),\n","        save_write_encrypted_filepath_7z\n","    )\n","\n","\n","DRIVE_7Z_PATH = os.path.normpath(DRIVE_7Z_PATH)\n","\n","os.makedirs(\n","    os.path.dirname(DRIVE_7Z_PATH),\n","    exist_ok=True\n",")\n","\n","\n","LOCAL_ZIP_PATH = \"/content/sankaku_lora_training_template.zip\"\n","\n","WORK_DIR = \"/content/sankaku_caption_editor\"\n","\n","OUTPUT_ZIP = \"/content/sankaku_lora_training_completed.zip\"\n","\n","\n","# ============================================================\n","# GLOBAL SYNCHRONIZATION\n","# ============================================================\n","\n","# All operations that modify or read the working dataset\n","# use the same lock.\n","\n","dataset_lock = threading.RLock()\n","\n","\n","# ============================================================\n","# EXTRACT & DECRYPT DATASET\n","# ============================================================\n","\n","if os.path.exists(WORK_DIR):\n","\n","    shutil.rmtree(WORK_DIR)\n","\n","\n","os.makedirs(\n","    WORK_DIR,\n","    exist_ok=True\n",")\n","\n","\n","if os.path.exists(DRIVE_7Z_PATH):\n","\n","    print(f\"Found encrypted archive: {DRIVE_7Z_PATH}\")\n","\n","    print(\"Decrypting and extracting dataset...\")\n","\n","    cmd = [\n","        \"7z\",\n","        \"x\",\n","        f\"-p{encryption_password}\",\n","        \"-y\",\n","        f\"-o{WORK_DIR}\",\n","        DRIVE_7Z_PATH\n","    ]\n","\n","    result = subprocess.run(\n","        cmd,\n","        capture_output=True,\n","        text=True\n","    )\n","\n","    if result.returncode != 0:\n","\n","        print(\"Decryption failed. Attempting local ZIP fallback...\")\n","\n","        if os.path.exists(LOCAL_ZIP_PATH):\n","\n","            with zipfile.ZipFile(LOCAL_ZIP_PATH, \"r\") as z:\n","\n","                z.extractall(WORK_DIR)\n","\n","        else:\n","\n","            raise RuntimeError(\n","                \"Drive decryption and local ZIP fallback both failed.\"\n","            )\n","\n","else:\n","\n","    print(\"No encrypted Drive archive found.\")\n","\n","    print(\"Loading local template instead...\")\n","\n","    if os.path.exists(LOCAL_ZIP_PATH):\n","\n","        with zipfile.ZipFile(LOCAL_ZIP_PATH, \"r\") as z:\n","\n","            z.extractall(WORK_DIR)\n","\n","    else:\n","\n","        raise FileNotFoundError(\n","            f\"Dataset not found: {LOCAL_ZIP_PATH}\"\n","        )\n","\n","\n","# ============================================================\n","# FIND NUMBERED IMAGES\n","# ============================================================\n","\n","images = []\n","\n","for root, dirs, filenames in os.walk(WORK_DIR):\n","\n","    dirs.sort()\n","\n","    for filename in filenames:\n","\n","        match = re.fullmatch(\n","            r\"(\\d+)\\.(jpg|jpeg|png|webp)\",\n","            filename,\n","            re.I\n","        )\n","\n","        if match:\n","\n","            number = int(match.group(1))\n","\n","            images.append({\n","\n","                \"number\": number,\n","\n","                \"image\": str(\n","                    Path(root) / filename\n","                ),\n","\n","                \"input\": str(\n","                    Path(root) / f\"{number}_input.txt\"\n","                ),\n","\n","                \"output\": str(\n","                    Path(root) / f\"{number}_output.txt\"\n","                )\n","\n","            })\n","\n","\n","images.sort(\n","    key=lambda x: (x[\"number\"], x[\"image\"].lower())\n",")\n","\n","\n","if not images:\n","\n","    raise RuntimeError(\n","        \"No numbered images found in the working directory.\"\n","    )\n","\n","\n","print(f\"Loaded {len(images)} images successfully.\")\n","\n","\n","# ============================================================\n","# CAPTION MANAGEMENT\n","# ============================================================\n","\n","def read_caption(item):\n","\n","    path = item[\"output\"]\n","\n","    if os.path.exists(path):\n","\n","        return Path(path).read_text(\n","            encoding=\"utf-8\"\n","        )\n","\n","    return \"\"\n","\n","\n","def read_hints(item):\n","\n","    path = item[\"input\"]\n","\n","    if os.path.exists(path):\n","\n","        return Path(path).read_text(\n","            encoding=\"utf-8\"\n","        )\n","\n","    return \"\"\n","\n","\n","def save_caption(item, caption):\n","\n","    Path(item[\"output\"]).write_text(\n","        caption or \"\",\n","        encoding=\"utf-8\"\n","    )\n","\n","\n","# ============================================================\n","# SAFE IMAGE DISPLAY\n","# ============================================================\n","\n","def get_view(index, caption=\"\"):\n","\n","    index = max(\n","        0,\n","        min(int(index), len(images) - 1)\n","    )\n","\n","    item = images[index]\n","\n","    return (\n","\n","        item[\"image\"],\n","\n","        read_caption(item),\n","\n","        read_hints(item),\n","\n","        (\n","            f\"IMAGE {index + 1:04d} / {len(images):04d}\"\n","            f\"    •    FILE {item['number']}\"\n","        ),\n","\n","        index\n","\n","    )\n","\n","\n","# ============================================================\n","# SAFE NAVIGATION\n","# ============================================================\n","\n","def previous_image(index, caption):\n","\n","    with dataset_lock:\n","\n","        index = int(index)\n","\n","        # Save current caption before changing image.\n","        save_caption(\n","            images[index],\n","            caption\n","        )\n","\n","        new_index = max(\n","            0,\n","            index - 1\n","        )\n","\n","        return get_view(\n","            new_index,\n","            caption\n","        )\n","\n","\n","def next_image(index, caption):\n","\n","    with dataset_lock:\n","\n","        index = int(index)\n","\n","        # Save current caption before changing image.\n","        save_caption(\n","            images[index],\n","            caption\n","        )\n","\n","        new_index = min(\n","            len(images) - 1,\n","            index + 1\n","        )\n","\n","        return get_view(\n","            new_index,\n","            caption\n","        )\n","\n","\n","def jump_to_image(index, caption, target):\n","\n","    with dataset_lock:\n","\n","        index = int(index)\n","\n","        # Save current caption before jumping.\n","        save_caption(\n","            images[index],\n","            caption\n","        )\n","\n","        target = int(target)\n","\n","        new_index = max(\n","            0,\n","            min(target - 1, len(images) - 1)\n","        )\n","\n","        return get_view(\n","            new_index,\n","            caption\n","        )\n","\n","\n","# ============================================================\n","# SAVE & EXPORT\n","# ============================================================\n","\n","def save_and_zip(index, caption):\n","\n","    with dataset_lock:\n","\n","        try:\n","\n","            index = int(index)\n","\n","            # ------------------------------------------------\n","            # 1. Save current caption\n","            # ------------------------------------------------\n","\n","            save_caption(\n","                images[index],\n","                caption\n","            )\n","\n","            print(\"All current captions saved.\")\n","\n","            # ------------------------------------------------\n","            # 2. Create local unencrypted ZIP\n","            # ------------------------------------------------\n","\n","            if os.path.exists(OUTPUT_ZIP):\n","\n","                os.remove(OUTPUT_ZIP)\n","\n","            shutil.make_archive(\n","                OUTPUT_ZIP[:-4],\n","                \"zip\",\n","                root_dir=WORK_DIR\n","            )\n","\n","            print(\"Local ZIP created successfully.\")\n","\n","            # ------------------------------------------------\n","            # 3. Create encrypted temporary 7Z archive\n","            # ------------------------------------------------\n","\n","            temp_7z_path = (\n","                DRIVE_7Z_PATH[:-3] + \"tmp.7z\"\n","            )\n","\n","            if os.path.exists(temp_7z_path):\n","\n","                os.remove(temp_7z_path)\n","\n","            print(\n","                f\"Encrypting dataset to Google Drive: {DRIVE_7Z_PATH}\"\n","            )\n","\n","            cmd = [\n","\n","                \"7z\",\n","\n","                \"a\",\n","\n","                \"-t7z\",\n","\n","                f\"-p{encryption_password}\",\n","\n","                \"-mhe=on\",\n","\n","                \"-y\",\n","\n","                temp_7z_path,\n","\n","                \".\"\n","\n","            ]\n","\n","            result = subprocess.run(\n","\n","                cmd,\n","\n","                cwd=WORK_DIR,\n","\n","                capture_output=True,\n","\n","                text=True\n","\n","            )\n","\n","            if result.returncode != 0:\n","\n","                raise RuntimeError(\n","                    result.stderr or result.stdout\n","                )\n","\n","            # ------------------------------------------------\n","            # 4. Replace previous backup only after success\n","            # ------------------------------------------------\n","\n","            if not os.path.exists(temp_7z_path):\n","\n","                raise RuntimeError(\n","                    \"Encrypted temporary archive was not created.\"\n","                )\n","\n","            os.replace(\n","                temp_7z_path,\n","                DRIVE_7Z_PATH\n","            )\n","\n","            status_msg = (\n","\n","                \"### ✅ BACKUP SUCCESSFUL\\n\\n\"\n","\n","                \"All captions saved successfully.\\n\\n\"\n","\n","                \"Local ZIP created.\\n\\n\"\n","\n","                \"Encrypted 7Z dataset backed up to Google Drive.\\n\\n\"\n","\n","                f\"**Drive file:** `{save_write_encrypted_filepath_7z}`\"\n","\n","            )\n","\n","            print(\"Encrypted Google Drive backup completed.\")\n","\n","            return OUTPUT_ZIP, status_msg\n","\n","\n","        except Exception as e:\n","\n","            status_msg = (\n","\n","                \"### ⚠️ BACKUP ERROR\\n\\n\"\n","\n","                \"The backup operation encountered an error.\\n\\n\"\n","\n","                f\"```text\\n{str(e)}\\n```\"\n","\n","            )\n","\n","            print(\"BACKUP ERROR:\", str(e))\n","\n","            return (\n","                OUTPUT_ZIP if os.path.exists(OUTPUT_ZIP) else None,\n","                status_msg\n","            )\n","\n","\n","# ============================================================\n","# THEME\n","# ============================================================\n","\n","theme = gr.themes.Base(\n","\n","    primary_hue=gr.themes.colors.orange,\n","\n","    secondary_hue=gr.themes.colors.purple,\n","\n","    neutral_hue=gr.themes.colors.zinc,\n","\n","    font=[\n","\n","        gr.themes.GoogleFont(\"Inter\"),\n","\n","        \"Arial\",\n","\n","        \"sans-serif\"\n","\n","    ]\n","\n",").set(\n","\n","    body_background_fill=\"#111014\",\n","\n","    body_text_color=\"#F3EDF7\",\n","\n","    block_background_fill=\"#1D1924\",\n","\n","    block_border_color=\"#393044\",\n","\n","    input_background_fill=\"#17131D\",\n","\n","    button_primary_background_fill=\"#F28C28\",\n","\n","    button_primary_background_fill_hover=\"#FFAA50\",\n","\n","    button_primary_text_color=\"#171014\"\n","\n",")\n","\n","\n","# ============================================================\n","# RESPONSIVE CSS\n","# ============================================================\n","\n","css = \"\"\"\n","\n","/* =========================================\n","   GLOBAL APPLICATION\n","========================================= */\n","\n",".gradio-container {\n","    max-width: 1250px !important;\n","    margin: auto !important;\n","    padding: 8px 12px 30px !important;\n","}\n","\n","#app-title {\n","    text-align: center;\n","    padding: 5px 0 10px;\n","}\n","\n","#app-title h1 {\n","    color: #FF983D;\n","    letter-spacing: 2px;\n","    font-size: clamp(19px, 4vw, 28px);\n","}\n","\n","/* =========================================\n","   IMAGE COUNTER\n","========================================= */\n","\n","#counter {\n","    text-align: center;\n","    color: #FF983D;\n","    font-weight: bold;\n","    letter-spacing: 1px;\n","    margin: 4px 0 10px;\n","}\n","\n","/* =========================================\n","   EDITOR LAYOUT\n","========================================= */\n","\n","#editor-layout {\n","    display: grid !important;\n","    grid-template-columns:\n","        minmax(0, 1.15fr)\n","        minmax(0, 0.85fr);\n","    gap: 14px;\n","    align-items: stretch;\n","}\n","\n","#image-panel {\n","    min-width: 0;\n","    display: flex;\n","    flex-direction: column;\n","    justify-content: center;\n","}\n","\n","#caption-panel {\n","    min-width: 0;\n","    display: flex;\n","    flex-direction: column;\n","    gap: 8px;\n","}\n","\n","/* =========================================\n","   IMAGE DISPLAY\n","========================================= */\n","\n","#image-display {\n","    width: 100%;\n","    height: min(70vh, 680px) !important;\n","    min-height: 260px !important;\n","    overflow: hidden;\n","}\n","\n","#image-display img {\n","    width: 100% !important;\n","    height: 100% !important;\n","    max-height: min(70vh, 680px) !important;\n","    object-fit: contain !important;\n","}\n","\n","/* =========================================\n","   CAPTION BOX\n","========================================= */\n","\n","#caption textarea {\n","    font-size: 16px !important;\n","    line-height: 1.6 !important;\n","    background: #17131D !important;\n","    border: 1px solid #704B85 !important;\n","    min-height: 150px !important;\n","}\n","\n","/* =========================================\n","   FLOATING NAVIGATION ARROWS\n","========================================= */\n","\n","#floating-prev,\n","#floating-next {\n","    position: fixed !important;\n","    top: 46% !important;\n","    z-index: 1000 !important;\n","\n","    width: 43px !important;\n","    min-width: 43px !important;\n","\n","    height: 58px !important;\n","    min-height: 58px !important;\n","\n","    padding: 0 !important;\n","\n","    border-radius: 12px !important;\n","\n","    opacity: 0.72;\n","\n","    box-shadow: 0 3px 12px #0008 !important;\n","\n","    transition: opacity 0.2s ease;\n","}\n","\n","#floating-prev {\n","    left: 5px !important;\n","}\n","\n","#floating-next {\n","    right: 5px !important;\n","}\n","\n","#floating-prev:hover,\n","#floating-next:hover {\n","    opacity: 1;\n","}\n","\n","/* =========================================\n","   HIDE NAVIGATION WHILE TYPING\n","========================================= */\n","\n","body.caption-focused #floating-prev,\n","body.caption-focused #floating-next {\n","    opacity: 0 !important;\n","    pointer-events: none !important;\n","}\n","\n","/* =========================================\n","   OTHER BUTTONS\n","========================================= */\n","\n",".nav-button {\n","    min-height: 46px !important;\n","    font-size: 14px !important;\n","}\n","\n","#download-button {\n","    min-height: 52px !important;\n","    font-weight: bold !important;\n","}\n","\n","#export-panel {\n","    margin-top: 18px;\n","}\n","\n","input,\n","textarea {\n","    font-size: 16px !important;\n","}\n","\n","footer {\n","    display: none !important;\n","}\n","\n","/* =========================================\n","   MOBILE LAYOUT\n","========================================= */\n","\n","@media (max-width: 700px) {\n","\n","    .gradio-container {\n","        padding: 5px 8px 20px !important;\n","    }\n","\n","    #app-title {\n","        padding: 3px 0;\n","    }\n","\n","    #app-title h1 {\n","        font-size: 19px;\n","        letter-spacing: 1px;\n","    }\n","\n","    #app-title p {\n","        font-size: 11px !important;\n","        margin: 3px 0;\n","    }\n","\n","    #counter {\n","        font-size: 13px;\n","        margin: 4px 0 8px;\n","    }\n","\n","    /* Stack image and caption */\n","\n","    #editor-layout {\n","        display: flex !important;\n","        flex-direction: column !important;\n","        gap: 8px !important;\n","    }\n","\n","    /* Smaller image to leave room for caption */\n","\n","    #image-display {\n","        height: 39vh !important;\n","        min-height: 180px !important;\n","        max-height: 350px !important;\n","    }\n","\n","    #image-display img {\n","        height: 39vh !important;\n","        max-height: 350px !important;\n","        object-fit: contain !important;\n","    }\n","\n","    /* Caption */\n","\n","    #caption-panel {\n","        width: 100% !important;\n","        gap: 5px !important;\n","    }\n","\n","    #caption textarea {\n","        min-height: 125px !important;\n","        max-height: 220px !important;\n","        font-size: 16px !important;\n","    }\n","\n","    /* Side navigation */\n","\n","    #floating-prev,\n","    #floating-next {\n","        top: 24% !important;\n","\n","        width: 36px !important;\n","        min-width: 36px !important;\n","\n","        height: 48px !important;\n","        min-height: 48px !important;\n","\n","        border-radius: 10px !important;\n","\n","        opacity: 0.48;\n","    }\n","\n","    #floating-prev {\n","        left: 2px !important;\n","    }\n","\n","    #floating-next {\n","        right: 2px !important;\n","    }\n","\n","    #export-panel {\n","        margin-top: 12px;\n","    }\n","}\n","\n","\"\"\"\n","\n","\n","# ============================================================\n","# GRADIO APPLICATION\n","# ============================================================\n","\n","with gr.Blocks(\n","\n","    theme=theme,\n","\n","    css=css,\n","\n","    title=\"Sankaku Caption Studio\"\n","\n",") as demo:\n","\n","\n","    # =========================================\n","    # HEADER\n","    # =========================================\n","\n","    gr.HTML(\"\"\"\n","\n","        <div id=\"app-title\">\n","\n","            <h1>✦ SANKAKU CAPTION STUDIO ✦</h1>\n","\n","            <p style=\"color:#A99BB5\">\n","                LoRA Dataset Caption Editor & Secure Drive Sync\n","            </p>\n","\n","        </div>\n","\n","    \"\"\")\n","\n","\n","    # =========================================\n","    # APPLICATION STATE\n","    # =========================================\n","\n","    # Gradio State is maintained separately per session.\n","\n","    current_index = gr.State(0)\n","\n","\n","    # =========================================\n","    # IMAGE COUNTER\n","    # =========================================\n","\n","    counter = gr.Markdown(\n","\n","        f\"IMAGE 0001 / {len(images):04d}\",\n","\n","        elem_id=\"counter\"\n","\n","    )\n","\n","\n","    # =========================================\n","    # MAIN EDITOR\n","    # =========================================\n","\n","    with gr.Row(elem_id=\"editor-layout\"):\n","\n","\n","        # IMAGE PANEL\n","\n","        with gr.Column(elem_id=\"image-panel\"):\n","\n","            image_display = gr.Image(\n","\n","                value=images[0][\"image\"],\n","\n","                label=\"\",\n","\n","                type=\"filepath\",\n","\n","                interactive=False,\n","\n","                show_label=False,\n","\n","                elem_id=\"image-display\",\n","\n","                height=580\n","\n","            )\n","\n","\n","        # CAPTION PANEL\n","\n","        with gr.Column(elem_id=\"caption-panel\"):\n","\n","            caption_box = gr.Textbox(\n","\n","                value=read_caption(images[0]),\n","\n","                label=\"IMAGE CAPTION\",\n","\n","                placeholder=\"Write your image description here...\",\n","\n","                lines=7,\n","\n","                max_lines=15,\n","\n","                elem_id=\"caption\"\n","\n","            )\n","\n","\n","            with gr.Accordion(\n","\n","                \"▸ INPUT HINTS — click to expand\",\n","\n","                open=False\n","\n","            ):\n","\n","                hints_display = gr.Textbox(\n","\n","                    value=read_hints(images[0]),\n","\n","                    label=\"Original input / tag hints\",\n","\n","                    lines=5,\n","\n","                    interactive=False\n","\n","                )\n","\n","\n","    # =========================================\n","    # FLOATING SIDE NAVIGATION\n","    # =========================================\n","\n","    prev_button = gr.Button(\n","\n","        \"❮\",\n","\n","        variant=\"secondary\",\n","\n","        elem_id=\"floating-prev\"\n","\n","    )\n","\n","\n","    next_button = gr.Button(\n","\n","        \"❯\",\n","\n","        variant=\"primary\",\n","\n","        elem_id=\"floating-next\"\n","\n","    )\n","\n","\n","    # =========================================\n","    # IMAGE JUMP CONTROLS\n","    # =========================================\n","\n","    with gr.Group():\n","\n","        gr.Markdown(\"### IMAGE NAVIGATION\")\n","\n","        with gr.Row():\n","\n","            jump_number = gr.Number(\n","\n","                label=\"Go to image number\",\n","\n","                value=1,\n","\n","                precision=0,\n","\n","                minimum=1,\n","\n","                maximum=len(images)\n","\n","            )\n","\n","\n","            jump_button = gr.Button(\n","\n","                \"GO\",\n","\n","                variant=\"secondary\"\n","\n","            )\n","\n","\n","    gr.Markdown(\"---\")\n","\n","\n","    # =========================================\n","    # EXPORT & BACKUP\n","    # =========================================\n","\n","    with gr.Group(elem_id=\"export-panel\"):\n","\n","        gr.Markdown(\"### ✦ EXPORT & SYNC DATASET\")\n","\n","\n","        download_button = gr.Button(\n","\n","            \"✦ SAVE & BACKUP SECURE 7Z TO DRIVE\",\n","\n","            variant=\"primary\",\n","\n","            elem_id=\"download-button\"\n","\n","        )\n","\n","\n","        download_file = gr.File(\n","\n","            label=\"Completed dataset ZIP (Unencrypted copy)\",\n","\n","            interactive=False\n","\n","        )\n","\n","\n","        status = gr.Markdown(\"\")\n","\n","\n","    # =========================================\n","    # EVENT OUTPUTS\n","    # =========================================\n","\n","    outputs = [\n","\n","        image_display,\n","\n","        caption_box,\n","\n","        hints_display,\n","\n","        counter,\n","\n","        current_index\n","\n","    ]\n","\n","\n","    # =========================================\n","    # SAFE PREVIOUS IMAGE\n","    # =========================================\n","\n","    prev_button.click(\n","\n","        fn=previous_image,\n","\n","        inputs=[\n","\n","            current_index,\n","\n","            caption_box\n","\n","        ],\n","\n","        outputs=outputs,\n","\n","        concurrency_limit=1,\n","\n","        concurrency_id=\"dataset_operations\",\n","\n","        trigger_mode=\"once\"\n","\n","    )\n","\n","\n","    # =========================================\n","    # SAFE NEXT IMAGE\n","    # =========================================\n","\n","    next_button.click(\n","\n","        fn=next_image,\n","\n","        inputs=[\n","\n","            current_index,\n","\n","            caption_box\n","\n","        ],\n","\n","        outputs=outputs,\n","\n","        concurrency_limit=1,\n","\n","        concurrency_id=\"dataset_operations\",\n","\n","        trigger_mode=\"once\"\n","\n","    )\n","\n","\n","    # =========================================\n","    # SAFE IMAGE JUMP\n","    # =========================================\n","\n","    jump_button.click(\n","\n","        fn=jump_to_image,\n","\n","        inputs=[\n","\n","            current_index,\n","\n","            caption_box,\n","\n","            jump_number\n","\n","        ],\n","\n","        outputs=outputs,\n","\n","        concurrency_limit=1,\n","\n","        concurrency_id=\"dataset_operations\",\n","\n","        trigger_mode=\"once\"\n","\n","    )\n","\n","\n","    # =========================================\n","    # SAVE AND BACKUP\n","    # =========================================\n","\n","    download_button.click(\n","\n","        fn=save_and_zip,\n","\n","        inputs=[\n","\n","            current_index,\n","\n","            caption_box\n","\n","        ],\n","\n","        outputs=[\n","\n","            download_file,\n","\n","            status\n","\n","        ],\n","\n","        concurrency_limit=1,\n","\n","        concurrency_id=\"dataset_operations\",\n","\n","        trigger_mode=\"once\"\n","\n","    )\n","\n","\n","    # =========================================\n","    # MOBILE TYPING PROTECTION\n","    # HIDE NAVIGATION WHILE TYPING\n","    # =========================================\n","\n","    gr.HTML(\"\"\"\n","\n","        <script>\n","\n","        (() => {\n","\n","            function setupCaptionNavigation() {\n","\n","                const textbox = document.querySelector(\n","                    '#caption textarea'\n","                );\n","\n","                if (!textbox || textbox.dataset.navSetup) {\n","\n","                    return;\n","\n","                }\n","\n","                textbox.dataset.navSetup = 'true';\n","\n","\n","                function hideArrows() {\n","\n","                    document.body.classList.add(\n","                        'caption-focused'\n","                    );\n","\n","                }\n","\n","\n","                function showArrows() {\n","\n","                    document.body.classList.remove(\n","                        'caption-focused'\n","                    );\n","\n","                }\n","\n","\n","                textbox.addEventListener(\n","                    'focus',\n","                    hideArrows\n","                );\n","\n","\n","                textbox.addEventListener(\n","                    'blur',\n","                    showArrows\n","                );\n","\n","            }\n","\n","\n","            setupCaptionNavigation();\n","\n","\n","            const observer = new MutationObserver(() => {\n","\n","                setupCaptionNavigation();\n","\n","            });\n","\n","\n","            observer.observe(\n","\n","                document.body,\n","\n","                {\n","\n","                    childList: true,\n","\n","                    subtree: true\n","\n","                }\n","\n","            );\n","\n","        })();\n","\n","        </script>\n","\n","    \"\"\")\n","\n","\n","# ============================================================\n","# LAUNCH APPLICATION\n","# ============================================================\n","\n","# Limit concurrent backend operations.\n","# All navigation and backup events share one queue.\n","\n","demo.queue(\n","\n","    default_concurrency_limit=1,\n","\n","    max_size=16\n","\n",")\n","\n","\n","demo.launch(\n","\n","    inline=True,\n","\n","    share=True,\n","\n","    debug=False\n","\n",")"],"metadata":{"cellView":"form","id":"4vpmVKb1VBsc"},"id":"4vpmVKb1VBsc","execution_count":null,"outputs":[]},{"cell_type":"markdown","metadata":{"id":"e9c4035a"},"source":["# Auto disconnect runtime session\n"],"id":"e9c4035a"},{"cell_type":"code","metadata":{"id":"a45ebf2d"},"source":["from google.colab import runtime\n","runtime.unassign()"],"id":"a45ebf2d","execution_count":null,"outputs":[]}],"metadata":{"colab":{"provenance":[{"file_id":"https://huggingface.co/codeShare/gemma-4-E2B-it-heretic-image-caption-adapter/blob/main/sankaku_database_browse_and_caption.ipynb","timestamp":1794143932508},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/sankaku_database_browse_and_caption.ipynb","timestamp":1794090310772},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/sankaku_database_browse_and_caption.ipynb","timestamp":1794087178285},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/sankaku_database_browse_and_caption.ipynb","timestamp":1794067633021}],"collapsed_sections":["EytLQtu1OJ7A","l3cD3WGpXoiU","RF6CbL6QXEYf"]},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"name":"python"}},"nbformat":4,"nbformat_minor":5}