{"cells":[{"cell_type":"markdown","id":"94780df6","metadata":{"id":"94780df6"},"source":["# Anime Keyframes: CLIP clustering, WD tagging, aesthetic scoring & Hugging Face upload\n","\n","This notebook:\n","1. Extracts `/content/drive/MyDrive/keyframes_v0_kf.zip`.\n","2. Extracts OpenCLIP embeddings and groups images with K-means.\n","3. Runs a WD image tagger on CUDA when available.\n","4. Computes LAION CLIP aesthetic predictor scores.\n","5. Writes `captions.parquet` and JSONL shards with image references.\n","6. Uploads the dataset to a new Hugging Face dataset repository named `anime-keyframes`.\n","\n","**Important:** JSONL stores image references and metadata; image bytes are uploaded as ordinary files under `images/`. Parquet `byte_offset` and `byte_length` refer to the exact UTF-8 JSONL line containing each record.\n","\n","Run the cells from top to bottom in Google Colab. The notebook reads your Hugging Face token from Colab Secrets (`HF_TOKEN`)."]},{"cell_type":"markdown","id":"0a4ca906","metadata":{"id":"0a4ca906"},"source":["## 1. Install dependencies"]},{"cell_type":"code","execution_count":1,"id":"712c6f08","metadata":{"id":"712c6f08","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1796134420127,"user_tz":-60,"elapsed":53196,"user":{"displayName":"No Name","userId":"10578412414437288386"}},"outputId":"25843152-7746-4f01-bdd9-c368755c7dd6"},"outputs":[{"output_type":"stream","name":"stdout","text":["\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n","datasets 4.8.5 requires huggingface-hub<2.0,>=0.25.0, but you have huggingface-hub 2.5.0 which is incompatible.\u001b[0m\u001b[31m\n","\u001b[0m\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n","datasets 4.8.5 requires huggingface-hub<2.0,>=0.25.0, but you have huggingface-hub 2.5.0 which is incompatible.\u001b[0m\u001b[31m\n","\u001b[0m\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n","google-colab 1.0.0 requires pandas==2.2.3, but you have pandas 3.1.2 which is incompatible.\n","dask-cudf-cu13 26.6.0 requires pandas<2.4.0,>=2.0, but you have pandas 3.1.2 which is incompatible.\n","gradio 6.31.0 requires pillow<13.0,>=8.0, but you have pillow 13.0.0 which is incompatible.\n","datasets 4.8.5 requires huggingface-hub<2.0,>=0.25.0, but you have huggingface-hub 2.5.0 which is incompatible.\n","cudf-cu13 26.6.0 requires pandas<2.4.0,>=2.0, but you have pandas 3.1.2 which is incompatible.\n","cudf-cu13 26.6.0 requires pyarrow<24,>=19.0.0, but you have pyarrow 26.0.1 which is incompatible.\u001b[0m\u001b[31m\n","\u001b[0m\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n","google-colab 1.0.0 requires pandas==2.2.3, but you have pandas 3.1.2 which is incompatible.\n","dask-cudf-cu13 26.6.0 requires pandas<2.4.0,>=2.0, but you have pandas 3.1.2 which is incompatible.\n","gradio 6.31.0 requires pillow<13.0,>=8.0, but you have pillow 13.0.0 which is incompatible.\n","datasets 4.8.5 requires huggingface-hub<2.0,>=0.25.0, but you have huggingface-hub 2.5.0 which is incompatible.\n","cudf-cu13 26.6.0 requires pandas<2.4.0,>=2.0, but you have pandas 3.1.2 which is incompatible.\n","cudf-cu13 26.6.0 requires pyarrow<24,>=19.0.0, but you have pyarrow 26.0.1 which is incompatible.\u001b[0m\u001b[31m\n","\u001b[0m"]}],"source":["!pip -q install -U open_clip_torch timm huggingface_hub transformers safetensors\n","!pip -q install -U pandas pyarrow scikit-learn pillow tqdm matplotlib\n","!pip -q install -U ftfy regex"]},{"cell_type":"markdown","id":"6b9589d5","metadata":{"id":"6b9589d5"},"source":["## 2. Mount Google Drive and configure paths"]},{"cell_type":"code","execution_count":2,"id":"d9314c68","metadata":{"id":"d9314c68","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1796134445163,"user_tz":-60,"elapsed":25030,"user":{"displayName":"No Name","userId":"10578412414437288386"}},"outputId":"c0634f82-4b71-40da-9714-9fafc91082ea"},"outputs":[{"output_type":"stream","name":"stdout","text":["Mounted at /content/drive\n","Mounted at /content/drive\n","Configuration ready.\n","Configuration ready.\n"]}],"source":["from google.colab import drive, userdata\n","drive.mount('/content/drive')\n","\n","import os, zipfile, shutil, json, math, hashlib, warnings\n","from pathlib import Path\n","from tqdm.auto import tqdm\n","\n","ZIP_PATH = \"/content/drive/MyDrive/keyframes_v0_kf.zip\"\n","INPUT_DIR = Path(\"/content/keyframes_input\")\n","WORK_DIR = Path(\"/content/anime_keyframes_build\")\n","IMAGE_DIR = WORK_DIR / \"images\"\n","JSONL_DIR = WORK_DIR / \"jsonl\"\n","\n","# K-means grouping\n","N_CLUSTERS = 200\n","RANDOM_STATE = 42\n","\n","# WD tagger\n","WD_MODEL_REPO = \"SmilingWolf/wd-swinv2-tagger-v3\"\n","WD_GENERAL_THRESHOLD = 0.35\n","WD_CHARACTER_THRESHOLD = 0.85\n","\n","# JSONL sharding\n","JSONL_SHARD_SIZE = 50\n","\n","# Optional: skip groups after clustering. Leave empty to keep every group.\n","EXCLUDED_GROUPS = []\n","\n","# Export format\n","IMAGE_FORMAT = \"JPEG\" # JPEG or WEBP\n","JPEG_QUALITY = 95\n","WEBP_QUALITY = 95\n","\n","assert os.path.isfile(ZIP_PATH), f\"ZIP file not found: {ZIP_PATH}\"\n","INPUT_DIR.mkdir(parents=True, exist_ok=True)\n","WORK_DIR.mkdir(parents=True, exist_ok=True)\n","IMAGE_DIR.mkdir(parents=True, exist_ok=True)\n","JSONL_DIR.mkdir(parents=True, exist_ok=True)\n","\n","print(\"Configuration ready.\")"]},{"cell_type":"markdown","id":"84171578","metadata":{"id":"84171578"},"source":["## 3. Extract the keyframes archive"]},{"cell_type":"code","execution_count":3,"id":"ea95316c","metadata":{"id":"ea95316c","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1796134477115,"user_tz":-60,"elapsed":31953,"user":{"displayName":"No Name","userId":"10578412414437288386"}},"outputId":"e330f330-1b5f-4b4b-c32d-8738a169dcd5"},"outputs":[{"output_type":"stream","name":"stdout","text":["Extracted to: /content/keyframes_input\n","Extracted to: /content/keyframes_input\n"]}],"source":["# Extract once into a dedicated input directory.\n","# Re-running this cell replaces the extraction directory to avoid stale files.\n","if INPUT_DIR.exists():\n"," shutil.rmtree(INPUT_DIR)\n","INPUT_DIR.mkdir(parents=True, exist_ok=True)\n","\n","with zipfile.ZipFile(ZIP_PATH, \"r\") as zf:\n"," # Basic path traversal protection\n"," root = INPUT_DIR.resolve()\n"," for member in zf.infolist():\n"," target = (INPUT_DIR / member.filename).resolve()\n"," if root not in target.parents and target != root:\n"," raise RuntimeError(f\"Unsafe path in ZIP: {member.filename}\")\n"," zf.extractall(INPUT_DIR)\n","\n","print(\"Extracted to:\", INPUT_DIR)"]},{"cell_type":"markdown","id":"1edf95fd","metadata":{"id":"1edf95fd"},"source":["## 4. Find images"]},{"cell_type":"code","execution_count":4,"id":"cd631dd0","metadata":{"id":"cd631dd0","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1796134477259,"user_tz":-60,"elapsed":145,"user":{"displayName":"No Name","userId":"10578412414437288386"}},"outputId":"7dc1c568-c6d8-4d4b-f24a-eb5e157962f0"},"outputs":[{"output_type":"stream","name":"stdout","text":["Found 7,515 images.\n","Example: /content/keyframes_input/0.jpg\n","Found 7,515 images.\n","Example: /content/keyframes_input/0.jpg\n"]}],"source":["IMAGE_EXTENSIONS = {\".jpg\", \".jpeg\", \".png\", \".webp\", \".bmp\", \".gif\"}\n","image_paths = sorted(\n"," p for p in INPUT_DIR.rglob(\"*\")\n"," if p.is_file() and p.suffix.lower() in IMAGE_EXTENSIONS\n",")\n","if not image_paths:\n"," raise RuntimeError(f\"No supported images found under {INPUT_DIR}\")\n","\n","print(f\"Found {len(image_paths):,} images.\")\n","print(\"Example:\", image_paths[0])"]},{"cell_type":"markdown","id":"609c8a45","metadata":{"id":"609c8a45"},"source":["## 5. Extract OpenCLIP embeddings"]},{"cell_type":"code","execution_count":5,"id":"21f37fdd","metadata":{"id":"21f37fdd","colab":{"base_uri":"https://localhost:8080/","height":373,"referenced_widgets":["799a7c17076040dabeba668f1d70f7ed","e90bf5a45d8847b6a46cbed660f37d54","f5d8c4db545a40ec970c25024d69a93d","61f3ccad820c440887e026ebf883c82e","e30690411e01453389d649c5a65ab47e","e20a9ccf40924bf9b02b06ed6a9a4874","a4e8a26ef7414930b218f4c132271d72","dfb7dad26f274c839548a1c4e4f494a7","822f0a0b6c5f476fbb548ba0bdf02de5","68ebc8d5fd2f4ee18f6e98c6ddd59e48","5d7a321431fa47f68b142c8312895afa","60a7933269e94c3eac4a01a9167160c9","9150e059b8404e8cbe63aa72fa6efa0f","5f1233d9c3d04601bf2db059557debfc","597ead27644e4c0e8a83d2751ecc1d3e","9686a6ed567d4f9884191684f67025ef","c8ab789804344ec89ca044844622721c","73cc78c88d7e4bf5a3795b48acf7f62e","b4ec8f46f1cb482b99b435849864fcc7","9f8ddf9f819744708c9d7518a4c15ea7","dc93eff9c29f48b4ab2de5ca868229a0","48139822dbc04438908c9186dab858bc","c08e551f043b426cabbf2026f9f2db58","fb2dd435573e48b9b40207e6f3541eaf","0d1d651e7994420f95f541f0f24081ef","978420d7dbdb45f781e0a84f71661405","502419a506fb4254b9d6f542beaf412e","e10c61ba03334243b989f0049ef00a82","6894c59dc951494b9f0eb4ad48e52bbf","fc319adda5e94ccfa396f6aa420251ad","2c54c35f9fd94ca18c922a7c9a8be654","fcc022cc024d4d028b1711f0edb9539a","44612f72c230469e93601206e88bbf38"]},"executionInfo":{"status":"ok","timestamp":1796134790623,"user_tz":-60,"elapsed":313293,"user":{"displayName":"No Name","userId":"10578412414437288386"}},"outputId":"6e6480f6-f949-40ec-de5c-2c52ca33ceed"},"outputs":[{"output_type":"stream","name":"stdout","text":["Inference device: cuda\n","Inference device: cuda\n"]},{"output_type":"display_data","data":{"text/plain":["open_clip_model.safetensors: reconstructing file: 0%| | 0.00B / 605MB "],"application/vnd.jupyter.widget-view+json":{"version_major":2,"version_minor":0,"model_id":"799a7c17076040dabeba668f1d70f7ed"}},"metadata":{}},{"output_type":"display_data","data":{"text/plain":["open_clip_model.safetensors: reconstructing file: 0%| | 0.00B / 605MB "],"application/vnd.jupyter.widget-view+json":{"version_major":2,"version_minor":0,"model_id":"799a7c17076040dabeba668f1d70f7ed"}},"metadata":{}},{"output_type":"display_data","data":{"text/plain":["open_clip_model.safetensors: downloading bytes: | 0.00B "],"application/vnd.jupyter.widget-view+json":{"version_major":2,"version_minor":0,"model_id":"60a7933269e94c3eac4a01a9167160c9"}},"metadata":{}},{"output_type":"display_data","data":{"text/plain":["open_clip_model.safetensors: downloading bytes: | 0.00B "],"application/vnd.jupyter.widget-view+json":{"version_major":2,"version_minor":0,"model_id":"60a7933269e94c3eac4a01a9167160c9"}},"metadata":{}},{"output_type":"stream","name":"stderr","text":["/usr/local/lib/python3.13/dist-packages/open_clip/factory.py:555: UserWarning: QuickGELU mismatch between final model config (quick_gelu=False) and pretrained tag 'laion400m_e32' (quick_gelu=True).\n"," warnings.warn(\n","/usr/local/lib/python3.13/dist-packages/open_clip/factory.py:555: UserWarning: QuickGELU mismatch between final model config (quick_gelu=False) and pretrained tag 'laion400m_e32' (quick_gelu=True).\n"," warnings.warn(\n"]},{"output_type":"display_data","data":{"text/plain":["Preprocessing images: 0%| | 0/7515 [00:00, ?it/s]"],"application/vnd.jupyter.widget-view+json":{"version_major":2,"version_minor":0,"model_id":"c08e551f043b426cabbf2026f9f2db58"}},"metadata":{}},{"output_type":"display_data","data":{"text/plain":["Preprocessing images: 0%| | 0/7515 [00:00, ?it/s]"],"application/vnd.jupyter.widget-view+json":{"version_major":2,"version_minor":0,"model_id":"c08e551f043b426cabbf2026f9f2db58"}},"metadata":{}},{"output_type":"stream","name":"stdout","text":["Embeddings: (7515, 512); valid images: 7,515\n","Embeddings: (7515, 512); valid images: 7,515\n"]}],"source":["import numpy as np\n","import torch\n","import open_clip\n","from PIL import Image, ImageFile\n","\n","ImageFile.LOAD_TRUNCATED_IMAGES = True\n","DEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n","print(\"Inference device:\", DEVICE)\n","\n","CLIP_MODEL_NAME = \"ViT-B-32\"\n","CLIP_PRETRAINED = \"laion400m_e32\"\n","clip_model, _, clip_preprocess = open_clip.create_model_and_transforms(\n"," CLIP_MODEL_NAME, pretrained=CLIP_PRETRAINED\n",")\n","clip_model = clip_model.to(DEVICE).eval()\n","\n","def image_batches(paths, preprocess, batch_size=64):\n"," batch_tensors, batch_paths = [], []\n"," for path in tqdm(paths, desc=\"Preprocessing images\"):\n"," try:\n"," with Image.open(path) as im:\n"," tensor = preprocess(im.convert(\"RGB\"))\n"," batch_tensors.append(tensor)\n"," batch_paths.append(path)\n"," except Exception as exc:\n"," print(f\"Skipping unreadable image {path}: {exc}\")\n"," if len(batch_tensors) >= batch_size:\n"," yield batch_paths, torch.stack(batch_tensors)\n"," batch_tensors, batch_paths = [], []\n"," if batch_tensors:\n"," yield batch_paths, torch.stack(batch_tensors)\n","\n","valid_image_paths = []\n","embedding_batches = []\n","with torch.inference_mode():\n"," for batch_paths, batch in image_batches(image_paths, clip_preprocess, batch_size=64):\n"," batch = batch.to(DEVICE)\n"," feats = clip_model.encode_image(batch)\n"," feats = feats / feats.norm(dim=-1, keepdim=True).clamp(min=1e-12)\n"," embedding_batches.append(feats.float().cpu().numpy())\n"," valid_image_paths.extend(batch_paths)\n","\n","embeddings = np.concatenate(embedding_batches, axis=0)\n","print(f\"Embeddings: {embeddings.shape}; valid images: {len(valid_image_paths):,}\")"]},{"cell_type":"markdown","id":"255eeb98","metadata":{"id":"255eeb98"},"source":["## 6. Cluster images into groups"]},{"cell_type":"code","execution_count":6,"id":"4a9d1cd9","metadata":{"id":"4a9d1cd9","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1796134839086,"user_tz":-60,"elapsed":48459,"user":{"displayName":"No Name","userId":"10578412414437288386"}},"outputId":"3342fe2d-8cd6-441c-cd26-83b82079a2f5"},"outputs":[{"output_type":"stream","name":"stderr","text":["/usr/local/lib/python3.13/dist-packages/pandas/core/arrays/masked.py:63: UserWarning: Pandas requires version '1.5.0' or newer of 'bottleneck' (version '1.4.2' currently installed).\n"," from pandas.core import (\n","/usr/local/lib/python3.13/dist-packages/pandas/core/arrays/masked.py:63: UserWarning: Pandas requires version '1.5.0' or newer of 'bottleneck' (version '1.4.2' currently installed).\n"," from pandas.core import (\n"]},{"output_type":"stream","name":"stdout","text":["Silhouette score: 0.0463\n","Groups: 200 | largest group: 107\n","Silhouette score: 0.0463\n","Groups: 200 | largest group: 107\n"]}],"source":["from sklearn.cluster import KMeans\n","from sklearn.metrics import silhouette_score\n","\n","if len(valid_image_paths) < 2:\n"," raise RuntimeError(\"At least two readable images are required for clustering.\")\n","\n","actual_clusters = min(int(N_CLUSTERS), len(valid_image_paths))\n","if actual_clusters < 1:\n"," raise ValueError(\"N_CLUSTERS must be at least 1.\")\n","\n","kmeans = KMeans(\n"," n_clusters=actual_clusters,\n"," random_state=RANDOM_STATE,\n"," n_init=10\n",")\n","group_numbers = kmeans.fit_predict(embeddings).astype(np.int64)\n","\n","if 1 < actual_clusters < len(valid_image_paths):\n"," # Subsample large datasets to keep silhouette evaluation tractable.\n"," sample_n = min(10000, len(valid_image_paths))\n"," sil = silhouette_score(\n"," embeddings, group_numbers,\n"," sample_size=sample_n if sample_n < len(valid_image_paths) else None,\n"," random_state=RANDOM_STATE\n"," )\n"," print(f\"Silhouette score: {sil:.4f}\")\n","else:\n"," print(\"Silhouette score skipped (only one cluster or one sample per cluster).\")\n","\n","unique, counts = np.unique(group_numbers, return_counts=True)\n","print(\"Groups:\", len(unique), \"| largest group:\", int(counts.max()))"]},{"cell_type":"markdown","id":"7a172866","metadata":{"id":"7a172866"},"source":["## 7. Optional UMAP visualization"]},{"cell_type":"code","execution_count":7,"id":"2d3d464e","metadata":{"id":"2d3d464e","executionInfo":{"status":"ok","timestamp":1796134839086,"user_tz":-60,"elapsed":4,"user":{"displayName":"No Name","userId":"10578412414437288386"}}},"outputs":[],"source":["# Set RUN_UMAP = True if you want a 2D plot. This can take time on large datasets.\n","RUN_UMAP = False\n","\n","if RUN_UMAP:\n"," !pip -q install umap-learn\n"," from umap import UMAP\n"," import matplotlib.pyplot as plt\n","\n"," reducer = UMAP(random_state=RANDOM_STATE, n_components=2)\n"," coords = reducer.fit_transform(embeddings)\n","\n"," plt.figure(figsize=(10, 8))\n"," scatter = plt.scatter(coords[:, 0], coords[:, 1], c=group_numbers, cmap=\"tab20\", s=5)\n"," plt.colorbar(scatter, label=\"Group number\")\n"," plt.title(f\"CLIP UMAP projection ({actual_clusters} groups)\")\n"," plt.xlabel(\"UMAP 1\")\n"," plt.ylabel(\"UMAP 2\")\n"," plt.show()"]},{"cell_type":"markdown","id":"b98508ed","metadata":{"id":"b98508ed"},"source":["## 8. Run WD tagger\n","\n","The default model is `SmilingWolf/wd-swinv2-tagger-v3`. It runs on CUDA when available and falls back to CPU otherwise. `tags` contains the selected general/character tags used as the caption prompt; `tag_prediction` stores the complete thresholded prediction list with scores."]},{"cell_type":"code","source":["# ============================================================\n","# WD TAGGER DISABLED — SKIP THIS STEP\n","# ============================================================\n","\n","# Create empty placeholders for downstream compatibility.\n","wd_results = [[] for _ in valid_image_paths]\n","\n","print(\"WD tagging disabled.\")\n","print(f\"Images processed: {len(wd_results)}\")"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"NkqmA-yt_yWd","executionInfo":{"status":"ok","timestamp":1796135141228,"user_tz":-60,"elapsed":47,"user":{"displayName":"No Name","userId":"10578412414437288386"}},"outputId":"1be2419e-119c-4955-b9b2-fbeaf54f5b98"},"id":"NkqmA-yt_yWd","execution_count":12,"outputs":[{"output_type":"stream","name":"stdout","text":["WD tagging disabled.\n","Images processed: 7515\n"]}]},{"cell_type":"markdown","id":"11ad564b","metadata":{"id":"11ad564b"},"source":["## 9. Compute CLIP aesthetic scores\n","\n","This uses LAION's published linear aesthetic predictor trained on normalized OpenCLIP ViT-L/14 image embeddings. The output is a scalar score, not a probability. The notebook stops with an explicit error if the model/checkpoint cannot be loaded, rather than silently writing missing scores."]},{"cell_type":"code","execution_count":13,"id":"aea48c1b","metadata":{"id":"aea48c1b","colab":{"base_uri":"https://localhost:8080/","height":187,"referenced_widgets":["7df827f897f9442ab69a36935b56a665","5f632a57e4c146acbe9bec4baea85647","077406d21dc64fa9b8cd7e1d2dc7e0a8","4e96a620066f46e8b05a4298b931b33a","98d6c5a1a4584f738203f349b951b3fd","88ae59a5c48f4bbf990487ae7ff68e61","31103b797c14442e9eee186bf913cb00","850dd61cb6894ae3878fb47c43ce2574","1ca4bd5abd634401aafb6ef3c98183bc","262cb87825ad44918075250508d9e467","a5c9a75e66bf4728a9b325aaa3911919","943c9d4876e6480f8cc4f9a20c04101d","0bee30a2729e48618a4cbc77e62890ea","b69d41705f194d17860ad7db3120fd73","7dbf28f589e946949212839b69a0a9e6","8113d83cfacc4fd989ec9443a1cb45f4","b5b44f88911441099cccf60574f9d693","eb165fe866de46da90c5357f98e4b6f3","03189fa0d45e41ff839b4d4770a21572","c7fd3239ce574faf92cf455391b72faf","66002d7b3c8c4cd1a3e9359dc58ba2fa","1060ba8a5b39442dad87f7293ca7a174","3dee9eb3a8824145a3f10ab3f3f7b6fb","2ddfaf1572b2465688f41581d1c3bb1b","f4082a4a3bd4493a86ed979c854c86a8","0772934385b442c4ac938e5b089effc8","a66dd0983f99496fa3f1de9f1983cb4b","6f5d9c4db03d40689e46fdc538e52251","d1f6d9c206b34cb9b7d813ab49ec25dc","3a4b377a75714864a809b35119e027d9","aa6bfa09b0f8429494799dc7f64847df","4a3306ee4820446991294837f2a6d1dd","7eab7f2db8534590a9a9d7c7fd59983d"]},"executionInfo":{"status":"ok","timestamp":1796135768337,"user_tz":-60,"elapsed":122564,"user":{"displayName":"No Name","userId":"10578412414437288386"}},"outputId":"6737b9e7-01bf-406a-ca44-1b164dca6f6a"},"outputs":[{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"7df827f897f9442ab69a36935b56a665","version_major":2,"version_minor":0},"text/plain":["open_clip_pytorch_model.bin: reconstructing file: 0%| | 0.00B / 1.71GB "]},"metadata":{},"output_type":"display_data"},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"943c9d4876e6480f8cc4f9a20c04101d","version_major":2,"version_minor":0},"text/plain":["open_clip_pytorch_model.bin: downloading bytes: | 0.00B "]},"metadata":{},"output_type":"display_data"},{"metadata":{"tags":null},"name":"stdout","output_type":"stream","text":["Downloading: \"https://github.com/LAION-AI/aesthetic-predictor/blob/main/sa_0_4_vit_l_14_linear.pth?raw=true\" to /root/.cache/torch/hub/checkpoints/sa_0_4_vit_l_14_linear.pth\n"]},{"metadata":{"tags":null},"name":"stderr","output_type":"stream","text":["100%|██████████| 3.98k/3.98k [00:00<00:00, 2.85MB/s]\n"]},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"3dee9eb3a8824145a3f10ab3f3f7b6fb","version_major":2,"version_minor":0},"text/plain":["Aesthetic scoring: 0%| | 0/235 [00:00, ?it/s]"]},"metadata":{},"output_type":"display_data"},{"output_type":"stream","name":"stdout","text":["Aesthetic scores computed. Range: 1.2699432373046875 to 5.758753776550293\n"]}],"source":["import torch.nn as nn\n","\n","AESTHETIC_CLIP_MODEL = \"ViT-L-14\"\n","AESTHETIC_CLIP_PRETRAINED = \"laion2b_s32b_b82k\"\n","AESTHETIC_CHECKPOINT_URL = (\n"," \"https://github.com/LAION-AI/aesthetic-predictor/\"\n"," \"blob/main/sa_0_4_vit_l_14_linear.pth?raw=true\"\n",")\n","\n","aesthetic_model, _, aesthetic_preprocess = open_clip.create_model_and_transforms(\n"," AESTHETIC_CLIP_MODEL, pretrained=AESTHETIC_CLIP_PRETRAINED\n",")\n","aesthetic_model = aesthetic_model.to(DEVICE).eval()\n","\n","aesthetic_head = nn.Linear(768, 1)\n","checkpoint = torch.hub.load_state_dict_from_url(\n"," AESTHETIC_CHECKPOINT_URL,\n"," map_location=\"cpu\",\n"," progress=True\n",")\n","# Some checkpoint wrappers store the linear state under a \"state_dict\" key.\n","if isinstance(checkpoint, dict) and \"state_dict\" in checkpoint:\n"," checkpoint = checkpoint[\"state_dict\"]\n","aesthetic_head.load_state_dict(checkpoint, strict=True)\n","aesthetic_head = aesthetic_head.to(DEVICE).eval()\n","\n","aesthetic_scores = np.full(len(valid_image_paths), np.nan, dtype=np.float32)\n","aesthetic_batch_size = 32\n","\n","with torch.inference_mode():\n"," for start in tqdm(range(0, len(valid_image_paths), aesthetic_batch_size), desc=\"Aesthetic scoring\"):\n"," end = min(start + aesthetic_batch_size, len(valid_image_paths))\n"," tensors, kept_indices = [], []\n"," for idx in range(start, end):\n"," try:\n"," with Image.open(valid_image_paths[idx]) as im:\n"," tensors.append(aesthetic_preprocess(im.convert(\"RGB\")))\n"," kept_indices.append(idx)\n"," except Exception as exc:\n"," print(f\"Aesthetic scoring skipped {valid_image_paths[idx]}: {exc}\")\n"," if tensors:\n"," batch = torch.stack(tensors).to(DEVICE)\n"," feats = aesthetic_model.encode_image(batch).float()\n"," feats = feats / feats.norm(dim=-1, keepdim=True).clamp(min=1e-12)\n"," scores = aesthetic_head(feats).squeeze(-1).cpu().numpy()\n"," for idx, score in zip(kept_indices, scores):\n"," aesthetic_scores[idx] = float(score)\n","\n","if np.isnan(aesthetic_scores).any():\n"," bad = int(np.isnan(aesthetic_scores).sum())\n"," raise RuntimeError(f\"Aesthetic scoring failed for {bad} images. Fix unreadable images and rerun.\")\n","print(\"Aesthetic scores computed. Range:\",\n"," float(aesthetic_scores.min()), \"to\", float(aesthetic_scores.max()))"]},{"cell_type":"markdown","id":"5dfb4a7c","metadata":{"id":"5dfb4a7c"},"source":["## 10. Prepare image files and build JSONL shards + Parquet index"]},{"cell_type":"code","execution_count":14,"id":"bbcad876","metadata":{"id":"bbcad876","colab":{"base_uri":"https://localhost:8080/","height":87,"referenced_widgets":["033227c7bec04ad496513cba3064d286","b2f681260e744e1db559934aa5a37a63","65943891d07f415c93e6f9a453b04ff3","1eebf9f6869342889bc313fa20d749fb","c27e290cb5ae4f2a8d91c0833a5ef5b2","53f7e4a987cd4320b3f59a500ebc20c0","f4e32026511347449c8d057da0c3b457","515178b54e8f48d19b143f90b8086857","67328eaedf094c0ab46aec3242b0720d","47cba800d47a4c79ae86b9ec420cb098","69a24be0f8244b0ca3145f0f8a0dedc2"]},"executionInfo":{"status":"ok","timestamp":1796135975882,"user_tz":-60,"elapsed":166222,"user":{"displayName":"No Name","userId":"10578412414437288386"}},"outputId":"5fbc63ee-5e45-40f4-c366-2b06bc350b94"},"outputs":[{"output_type":"display_data","data":{"text/plain":["Preparing export images: 0%| | 0/7515 [00:00, ?it/s]"],"application/vnd.jupyter.widget-view+json":{"version_major":2,"version_minor":0,"model_id":"033227c7bec04ad496513cba3064d286"}},"metadata":{}},{"output_type":"stream","name":"stdout","text":["Prepared 7,515 images for export.\n"]}],"source":["# Clear previous export outputs to prevent stale files being uploaded.\n","if IMAGE_DIR.exists():\n"," shutil.rmtree(IMAGE_DIR)\n","if JSONL_DIR.exists():\n"," shutil.rmtree(JSONL_DIR)\n","IMAGE_DIR.mkdir(parents=True, exist_ok=True)\n","JSONL_DIR.mkdir(parents=True, exist_ok=True)\n","\n","from PIL import Image\n","\n","export_rows = []\n","parquet_rows = []\n","kept_count = 0\n","\n","def make_export_filename(idx, source_path, extension):\n"," # Stable, collision-resistant names.\n"," digest = hashlib.sha1(str(source_path).encode(\"utf-8\")).hexdigest()[:10]\n"," return f\"{idx:08d}_{digest}.{extension}\"\n","\n","# Export image files first and retain metadata in memory.\n","for idx, (src, group_no, pred, aesthetic_score) in enumerate(\n"," tqdm(zip(valid_image_paths, group_numbers, wd_results, aesthetic_scores),\n"," total=len(valid_image_paths), desc=\"Preparing export images\")\n","):\n"," if int(group_no) in set(EXCLUDED_GROUPS):\n"," continue\n","\n"," if IMAGE_FORMAT.upper() == \"JPEG\":\n"," ext, pil_format = \"jpg\", \"JPEG\"\n"," elif IMAGE_FORMAT.upper() == \"WEBP\":\n"," ext, pil_format = \"webp\", \"WEBP\"\n"," else:\n"," raise ValueError(\"IMAGE_FORMAT must be JPEG or WEBP.\")\n","\n"," filename = make_export_filename(idx, src, ext)\n"," destination = IMAGE_DIR / filename\n","\n"," try:\n"," with Image.open(src) as im:\n"," rgb = im.convert(\"RGB\")\n"," if pil_format == \"JPEG\":\n"," rgb.save(destination, format=\"JPEG\", quality=JPEG_QUALITY, optimize=True)\n"," else:\n"," rgb.save(destination, format=\"WEBP\", quality=WEBP_QUALITY, method=6)\n"," except Exception as exc:\n"," print(f\"Export skipped {src}: {exc}\")\n"," continue\n","\n"," # Keep WD general + character tags as the human-readable caption/tag string.\n"," #caption_tags = [\n"," # item[\"tag\"] for item in pred\n"," # if item[\"category\"] in (0, 4)\n"," #]\n"," tags_string = \"\" #\", \".join(caption_tags)\n"," prompt = tags_string\n","\n"," full_prediction = json.dumps(pred, ensure_ascii=False, separators=(\",\", \":\"))\n"," export_rows.append({\n"," \"idx\": int(idx),\n"," \"prompt\": prompt,\n"," \"tags\": tags_string,\n"," \"author\": \"Hellsing\",\n"," \"group_number\": int(group_no),\n"," \"clip_aesthetic_score\": float(aesthetic_score),\n"," \"image_filename\": filename,\n"," \"tag_prediction\": full_prediction,\n"," })\n"," kept_count += 1\n","\n","print(f\"Prepared {kept_count:,} images for export.\")\n","if not export_rows:\n"," raise RuntimeError(\"No images remain for export. Check EXCLUDED_GROUPS and source images.\")"]},{"cell_type":"code","execution_count":15,"id":"71d55c98","metadata":{"id":"71d55c98","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1796135981089,"user_tz":-60,"elapsed":89,"user":{"displayName":"No Name","userId":"10578412414437288386"}},"outputId":"c8ccedd9-2431-45b7-f84a-1bb9e615df54"},"outputs":[{"output_type":"stream","name":"stdout","text":["Wrote 151 JSONL shards.\n"]}],"source":["# JSONL shards: each JSONL record has an image path relative to the jsonl/ directory.\n","# Record byte offsets/lengths are measured from the exact UTF-8 bytes written.\n","for shard_start in range(0, len(export_rows), JSONL_SHARD_SIZE):\n"," shard_rows = export_rows[shard_start:shard_start + JSONL_SHARD_SIZE]\n"," shard_number = shard_start // JSONL_SHARD_SIZE\n"," jsonl_name = f\"keyframes-{shard_number:05d}.jsonl\"\n"," jsonl_path = JSONL_DIR / jsonl_name\n","\n"," with open(jsonl_path, \"wb\") as f:\n"," for record in shard_rows:\n"," # JSONL is inside jsonl/, so ../images/ points to the image file.\n"," json_record = {\n"," \"idx\": record[\"idx\"],\n"," \"prompt\": record[\"prompt\"],\n"," \"tags\": record[\"tags\"],\n"," \"author\": record[\"author\"],\n"," \"group_number\": record[\"group_number\"],\n"," \"clip_aesthetic_score\": record[\"clip_aesthetic_score\"],\n"," \"image\": {\"path\": f\"../images/{record['image_filename']}\"},\n"," \"tag_prediction\": record[\"tag_prediction\"],\n"," }\n"," line = (json.dumps(json_record, ensure_ascii=False) + \"\\n\").encode(\"utf-8\")\n"," byte_offset = f.tell()\n"," f.write(line)\n"," byte_length = len(line)\n","\n"," parquet_rows.append({\n"," \"idx\": record[\"idx\"],\n"," \"prompt\": record[\"prompt\"],\n"," \"tags\": record[\"tags\"],\n"," \"author\": record[\"author\"],\n"," \"json_file\": f\"jsonl/{jsonl_name}\",\n"," \"byte_offset\": int(byte_offset),\n"," \"byte_length\": int(byte_length),\n"," \"instruction\": \"\",\n"," \"thinking_response\": \"\",\n"," \"written_response\": \"\",\n"," \"addendum\": \"\",\n"," \"tag_prediction\": record[\"tag_prediction\"],\n"," \"group_number\": record[\"group_number\"],\n"," \"clip_aesthetic_score\": record[\"clip_aesthetic_score\"],\n"," })\n","\n","print(f\"Wrote {len(list(JSONL_DIR.glob('*.jsonl')))} JSONL shards.\")"]},{"cell_type":"markdown","id":"9c5e7e1c","metadata":{"id":"9c5e7e1c"},"source":["## 11. Write `captions.parquet` with explicit column types"]},{"cell_type":"code","execution_count":16,"id":"623ece98","metadata":{"id":"623ece98","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1796135988594,"user_tz":-60,"elapsed":219,"user":{"displayName":"No Name","userId":"10578412414437288386"}},"outputId":"eb974d9b-7727-432e-ec0a-946613a12776"},"outputs":[{"output_type":"stream","name":"stdout","text":["Saved: /content/anime_keyframes_build/captions.parquet\n","Rows: 7515\n","idx: int64\n","prompt: string\n","tags: string\n","author: string\n","json_file: string\n","byte_offset: int64\n","byte_length: int64\n","instruction: string\n","thinking_response: string\n","written_response: string\n","addendum: string\n","tag_prediction: string\n","group_number: int64\n","clip_aesthetic_score: float\n","-- schema metadata --\n","pandas: '{\"index_columns\": [], \"column_indexes\": [], \"columns\": [{\"name\":' + 1751\n"]}],"source":["import pyarrow as pa\n","import pyarrow.parquet as pq\n","\n","columns = [\n"," \"idx\", \"prompt\", \"tags\", \"author\", \"json_file\", \"byte_offset\",\n"," \"byte_length\", \"instruction\", \"thinking_response\", \"written_response\",\n"," \"addendum\", \"tag_prediction\", \"group_number\", \"clip_aesthetic_score\"\n","]\n","df = pd.DataFrame(parquet_rows, columns=columns)\n","\n","# Explicit Arrow schema: int64/string fields as requested, plus group and aesthetic score.\n","schema = pa.schema([\n"," (\"idx\", pa.int64()),\n"," (\"prompt\", pa.string()),\n"," (\"tags\", pa.string()),\n"," (\"author\", pa.string()),\n"," (\"json_file\", pa.string()),\n"," (\"byte_offset\", pa.int64()),\n"," (\"byte_length\", pa.int64()),\n"," (\"instruction\", pa.string()),\n"," (\"thinking_response\", pa.string()),\n"," (\"written_response\", pa.string()),\n"," (\"addendum\", pa.string()),\n"," (\"tag_prediction\", pa.string()),\n"," (\"group_number\", pa.int64()),\n"," (\"clip_aesthetic_score\", pa.float32()),\n","])\n","\n","table = pa.Table.from_pandas(df, schema=schema, preserve_index=False)\n","PARQUET_PATH = WORK_DIR / \"captions.parquet\"\n","pq.write_table(table, PARQUET_PATH, compression=\"zstd\")\n","\n","print(\"Saved:\", PARQUET_PATH)\n","print(\"Rows:\", table.num_rows)\n","print(table.schema)"]},{"cell_type":"markdown","id":"d30dcbc1","metadata":{"id":"d30dcbc1"},"source":["## 12. Validate JSONL byte offsets and Parquet"]},{"cell_type":"code","execution_count":17,"id":"9da11b92","metadata":{"id":"9da11b92","colab":{"base_uri":"https://localhost:8080/","height":359,"referenced_widgets":["5010a472be444855896357b37fbd897e","f7ee3ff640a44426b19a55f81b376fc3","9a9a6cbedf4c4ff7a0ffdafe4934a091","7e99c1537833457e89479d3873771cbf","71b36c005fb845c191080f8069966005","a2f1f990670a45a3bc93726078a2da6e","5d5e687f35ce40e193dd483062dfedeb","108656222c8340c4baaabb10c0778483","41835af4f2ee431f8f3e7ec0434a6c1f","77a57219488d4f908bed05df90a0b1e3","90bd14827c8644ad9370ded5d98b79ed"]},"executionInfo":{"status":"ok","timestamp":1796135995807,"user_tz":-60,"elapsed":593,"user":{"displayName":"No Name","userId":"10578412414437288386"}},"outputId":"378ccf4d-5e89-49a3-9ac9-3ea03b3057ed"},"outputs":[{"output_type":"display_data","data":{"text/plain":["Validating byte offsets: 0%| | 0/7515 [00:00, ?it/s]"],"application/vnd.jupyter.widget-view+json":{"version_major":2,"version_minor":0,"model_id":"5010a472be444855896357b37fbd897e"}},"metadata":{}},{"output_type":"stream","name":"stdout","text":["Validation passed.\n"]},{"output_type":"display_data","data":{"text/plain":[" idx prompt tags author json_file byte_offset \\\n","0 0 Hellsing jsonl/keyframes-00000.jsonl 0 \n","1 1 Hellsing jsonl/keyframes-00000.jsonl 203 \n","2 2 Hellsing jsonl/keyframes-00000.jsonl 405 \n","3 3 Hellsing jsonl/keyframes-00000.jsonl 607 \n","4 4 Hellsing jsonl/keyframes-00000.jsonl 810 \n","\n"," byte_length instruction thinking_response written_response addendum \\\n","0 203 \n","1 202 \n","2 202 \n","3 203 \n","4 202 \n","\n"," tag_prediction group_number clip_aesthetic_score \n","0 [] 162 4.373645 \n","1 [] 22 2.392488 \n","2 [] 22 2.787457 \n","3 [] 54 3.884729 \n","4 [] 15 3.907008 "],"text/html":["
| \n"," | idx | \n","prompt | \n","tags | \n","author | \n","json_file | \n","byte_offset | \n","byte_length | \n","instruction | \n","thinking_response | \n","written_response | \n","addendum | \n","tag_prediction | \n","group_number | \n","clip_aesthetic_score | \n","
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | \n","0 | \n","\n"," | \n"," | Hellsing | \n","jsonl/keyframes-00000.jsonl | \n","0 | \n","203 | \n","\n"," | \n"," | \n"," | \n"," | [] | \n","162 | \n","4.373645 | \n","
| 1 | \n","1 | \n","\n"," | \n"," | Hellsing | \n","jsonl/keyframes-00000.jsonl | \n","203 | \n","202 | \n","\n"," | \n"," | \n"," | \n"," | [] | \n","22 | \n","2.392488 | \n","
| 2 | \n","2 | \n","\n"," | \n"," | Hellsing | \n","jsonl/keyframes-00000.jsonl | \n","405 | \n","202 | \n","\n"," | \n"," | \n"," | \n"," | [] | \n","22 | \n","2.787457 | \n","
| 3 | \n","3 | \n","\n"," | \n"," | Hellsing | \n","jsonl/keyframes-00000.jsonl | \n","607 | \n","203 | \n","\n"," | \n"," | \n"," | \n"," | [] | \n","54 | \n","3.884729 | \n","
| 4 | \n","4 | \n","\n"," | \n"," | Hellsing | \n","jsonl/keyframes-00000.jsonl | \n","810 | \n","202 | \n","\n"," | \n"," | \n"," | \n"," | [] | \n","15 | \n","3.907008 | \n","