codeShare commited on
Commit
e232751
Β·
verified Β·
1 Parent(s): f2329e8

Upload sort_danbooru2026_by_category.ipynb

Browse files
Files changed (1) hide show
  1. sort_danbooru2026_by_category.ipynb +649 -0
sort_danbooru2026_by_category.ipynb ADDED
@@ -0,0 +1,649 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "provenance": [],
7
+ "gpuType": "T4",
8
+ "collapsed_sections": [
9
+ "PvAtznhla3jS"
10
+ ]
11
+ },
12
+ "kernelspec": {
13
+ "name": "python3",
14
+ "display_name": "Python 3"
15
+ },
16
+ "language_info": {
17
+ "name": "python"
18
+ },
19
+ "accelerator": "GPU"
20
+ },
21
+ "cells": [
22
+ {
23
+ "cell_type": "markdown",
24
+ "source": [
25
+ "Using https://huggingface.co/datasets/RicemanT/booru-essence-2026\n",
26
+ "\n",
27
+ "* Dowload the parquet from the huggingface huggingface repo and save to your google drive as /content/drive/MyDrive/booru_essence.parquet and /content/drive/MyDrive/e621_essence.parquet respectively"
28
+ ],
29
+ "metadata": {
30
+ "id": "oSQKdE5VYMoS"
31
+ }
32
+ },
33
+ {
34
+ "cell_type": "markdown",
35
+ "source": [
36
+ "# Parquet Explorer"
37
+ ],
38
+ "metadata": {
39
+ "id": "PvAtznhla3jS"
40
+ }
41
+ },
42
+ {
43
+ "cell_type": "code",
44
+ "source": [
45
+ "from google.colab import drive\n",
46
+ "drive.mount('/content/drive')"
47
+ ],
48
+ "metadata": {
49
+ "id": "HFy5aDxM3G7O",
50
+ "outputId": "6bab9c7a-5b63-4e1b-8698-5468b0715068",
51
+ "colab": {
52
+ "base_uri": "https://localhost:8080/"
53
+ }
54
+ },
55
+ "execution_count": null,
56
+ "outputs": [
57
+ {
58
+ "output_type": "stream",
59
+ "name": "stdout",
60
+ "text": [
61
+ "Mounted at /content/drive\n"
62
+ ]
63
+ }
64
+ ]
65
+ },
66
+ {
67
+ "cell_type": "code",
68
+ "source": [
69
+ "# Step 1: Mount Google Drive\n",
70
+ "#from google.colab import drive\n",
71
+ "#drive.mount('/content/drive')\n",
72
+ "\n",
73
+ "#@markdown paste .parquet file stored on your Google Drive folder to see its characteristics\n",
74
+ "\n",
75
+ "# Step 2: Import required libraries\n",
76
+ "import pandas as pd\n",
77
+ "\n",
78
+ "# Step 3: Define the path to the Parquet file\n",
79
+ "file_path = '/content/drive/MyDrive/Saved from Chrome/danbooru.parquet' #@param {type:'string'}\n",
80
+ "\n",
81
+ "# Step 4: Read the Parquet file\n",
82
+ "df = pd.read_parquet(file_path)\n",
83
+ "\n",
84
+ "# Step 5: Basic exploration of the Parquet file\n",
85
+ "print(\"First 5 rows of the dataset:\")\n",
86
+ "print(df.head())\n",
87
+ "\n",
88
+ "print(\"\\nDataset Info:\")\n",
89
+ "print(df.info())\n",
90
+ "\n",
91
+ "print(\"\\nBasic Statistics:\")\n",
92
+ "print(df.describe())\n",
93
+ "\n",
94
+ "print(\"\\nColumn Names:\")\n",
95
+ "print(df.columns.tolist())\n",
96
+ "\n",
97
+ "print(\"\\nMissing Values:\")\n",
98
+ "print(df.isnull().sum())\n",
99
+ "\n",
100
+ "# Optional: Display number of rows and columns\n",
101
+ "print(f\"\\nShape of the dataset: {df.shape}\")"
102
+ ],
103
+ "metadata": {
104
+ "id": "So-PKtbo5AVA",
105
+ "colab": {
106
+ "base_uri": "https://localhost:8080/"
107
+ },
108
+ "outputId": "4b183874-827d-4822-872b-fea7e5d3ae03"
109
+ },
110
+ "execution_count": null,
111
+ "outputs": [
112
+ {
113
+ "output_type": "stream",
114
+ "name": "stdout",
115
+ "text": [
116
+ "First 5 rows of the dataset:\n",
117
+ " md5 image_path \\\n",
118
+ "0 0004100ffd82a677a13706c7a7049b3c 00/0004100ffd82a677a13706c7a7049b3c.png \n",
119
+ "1 00041bad25f261b96eaa15517dd06cb6 00/00041bad25f261b96eaa15517dd06cb6.jpg \n",
120
+ "2 000665c12cc1638ce15286a7972f5fc2 00/000665c12cc1638ce15286a7972f5fc2.jpg \n",
121
+ "3 001193d9df978b62b0100d12fa6cb270 00/001193d9df978b62b0100d12fa6cb270.jpg \n",
122
+ "4 0011caa6d25cab0016c0dedb523085b1 00/0011caa6d25cab0016c0dedb523085b1.jpg \n",
123
+ "\n",
124
+ " source rating caption_bucket \\\n",
125
+ "0 danbooru sensitive safe \n",
126
+ "1 danbooru sensitive safe \n",
127
+ "2 danbooru sensitive safe \n",
128
+ "3 danbooru sensitive safe \n",
129
+ "4 danbooru sensitive safe \n",
130
+ "\n",
131
+ " tags \\\n",
132
+ "0 zhixie jiaobu, flandre scarlet, touhou, 1girl,... \n",
133
+ "1 kamishima kanon, gogeta, hong meiling, izayoi ... \n",
134
+ "2 ichi (ichikai), kazami yuuka, kazami yuuka (pc... \n",
135
+ "3 hoshikuzu pan, princess peach, princess peach ... \n",
136
+ "4 chiwino, mimi houllier von schwarzlang, totoor... \n",
137
+ "\n",
138
+ " caption caption_model \\\n",
139
+ "0 Drawn by zhixie jiaobu. Flandre Scarlet from T... nl \n",
140
+ "1 Drawn by kamishima kanon. Gogeta from Dragon B... nl \n",
141
+ "2 Drawn by ichi (ichikai). Kazami Yuuka and Koch... nl \n",
142
+ "3 Drawn by hoshikuzu pan. Princess Peach and Ros... nl \n",
143
+ "4 Drawn by chiwino. Totooria Helmold and Mimi Ho... nl \n",
144
+ "\n",
145
+ " trigger_tag url ... \\\n",
146
+ "0 Drawn by zhixie jiaobu 0004100ffd82a677a13706c7a7049b3c ... \n",
147
+ "1 Drawn by kamishima kanon 00041bad25f261b96eaa15517dd06cb6 ... \n",
148
+ "2 Drawn by ichi (ichikai) 000665c12cc1638ce15286a7972f5fc2 ... \n",
149
+ "3 Drawn by hoshikuzu pan 001193d9df978b62b0100d12fa6cb270 ... \n",
150
+ "4 Drawn by chiwino 0011caa6d25cab0016c0dedb523085b1 ... \n",
151
+ "\n",
152
+ " image_height fav_count created_at solo_subject \\\n",
153
+ "0 2480 35 2018-04-10 18:19:04.307000-07:00 True \n",
154
+ "1 1662 83 2012-09-27 07:17:12.405000-07:00 True \n",
155
+ "2 1692 135 2009-05-24 14:37:17.815000-07:00 False \n",
156
+ "3 1275 153 2018-03-23 20:46:43.043000-07:00 False \n",
157
+ "4 850 99 2011-06-22 21:33:11.525000-07:00 False \n",
158
+ "\n",
159
+ " multi_subject artist_weights \\\n",
160
+ "0 False {\"zhixie_jiaobu\": 2.6965785370217326e-05} \n",
161
+ "1 False {\"kamishima_kanon\": 1.632874605151334e-05} \n",
162
+ "2 True {\"ichi_(ichikai)\": 1.9545675811406287e-05} \n",
163
+ "3 True {\"hoshikuzu_pan\": 2.538654628444895e-05} \n",
164
+ "4 True {\"chiwino\": 1.8019746011716172e-05} \n",
165
+ "\n",
166
+ " character_weights species_weights \\\n",
167
+ "0 {\"flandre_scarlet\": 5.549727045990053e-06} {} \n",
168
+ "1 {\"gogeta\": 2.1352518798382155e-05, \"hong_meili... {} \n",
169
+ "2 {\"kazami_yuuka\": 7.954217649439972e-06, \"kochi... {} \n",
170
+ "3 {\"princess_peach\": 9.696893506992817e-06, \"ros... {} \n",
171
+ "4 {\"mimi_houllier_von_schwarzlang\": 3.4177584640... {} \n",
172
+ "\n",
173
+ " post_id_cur post_id_old \n",
174
+ "0 3082788.0 None \n",
175
+ "1 1264640.0 None \n",
176
+ "2 459758.0 None \n",
177
+ "3 3060933.0 None \n",
178
+ "4 940637.0 None \n",
179
+ "\n",
180
+ "[5 rows x 21 columns]\n",
181
+ "\n",
182
+ "Dataset Info:\n",
183
+ "<class 'pandas.core.frame.DataFrame'>\n",
184
+ "RangeIndex: 19987 entries, 0 to 19986\n",
185
+ "Data columns (total 21 columns):\n",
186
+ " # Column Non-Null Count Dtype \n",
187
+ "--- ------ -------------- ----- \n",
188
+ " 0 md5 19987 non-null object \n",
189
+ " 1 image_path 19987 non-null object \n",
190
+ " 2 source 19987 non-null object \n",
191
+ " 3 rating 19987 non-null object \n",
192
+ " 4 caption_bucket 19987 non-null object \n",
193
+ " 5 tags 19987 non-null object \n",
194
+ " 6 caption 19987 non-null object \n",
195
+ " 7 caption_model 19987 non-null object \n",
196
+ " 8 trigger_tag 19987 non-null object \n",
197
+ " 9 url 19987 non-null object \n",
198
+ " 10 image_width 19987 non-null int64 \n",
199
+ " 11 image_height 19987 non-null int64 \n",
200
+ " 12 fav_count 19987 non-null int64 \n",
201
+ " 13 created_at 19987 non-null datetime64[us, America/Los_Angeles]\n",
202
+ " 14 solo_subject 19987 non-null bool \n",
203
+ " 15 multi_subject 19987 non-null bool \n",
204
+ " 16 artist_weights 19987 non-null object \n",
205
+ " 17 character_weights 19987 non-null object \n",
206
+ " 18 species_weights 19987 non-null object \n",
207
+ " 19 post_id_cur 19967 non-null float64 \n",
208
+ " 20 post_id_old 0 non-null object \n",
209
+ "dtypes: bool(2), datetime64[us, America/Los_Angeles](1), float64(1), int64(3), object(14)\n",
210
+ "memory usage: 2.9+ MB\n",
211
+ "None\n",
212
+ "\n",
213
+ "Basic Statistics:\n",
214
+ " image_width image_height fav_count post_id_cur\n",
215
+ "count 19987.000000 19987.000000 19987.000000 1.996700e+04\n",
216
+ "mean 1631.031120 1929.382298 211.866563 4.612090e+06\n",
217
+ "std 1016.239287 1201.701401 208.898400 2.072274e+06\n",
218
+ "min 250.000000 240.000000 0.000000 1.465000e+03\n",
219
+ "25% 952.000000 1097.000000 79.000000 3.272472e+06\n",
220
+ "50% 1311.000000 1540.000000 152.000000 4.727361e+06\n",
221
+ "75% 2048.000000 2400.000000 278.000000 6.222154e+06\n",
222
+ "max 29700.000000 27772.000000 4962.000000 8.359647e+06\n",
223
+ "\n",
224
+ "Column Names:\n",
225
+ "['md5', 'image_path', 'source', 'rating', 'caption_bucket', 'tags', 'caption', 'caption_model', 'trigger_tag', 'url', 'image_width', 'image_height', 'fav_count', 'created_at', 'solo_subject', 'multi_subject', 'artist_weights', 'character_weights', 'species_weights', 'post_id_cur', 'post_id_old']\n",
226
+ "\n",
227
+ "Missing Values:\n",
228
+ "md5 0\n",
229
+ "image_path 0\n",
230
+ "source 0\n",
231
+ "rating 0\n",
232
+ "caption_bucket 0\n",
233
+ "tags 0\n",
234
+ "caption 0\n",
235
+ "caption_model 0\n",
236
+ "trigger_tag 0\n",
237
+ "url 0\n",
238
+ "image_width 0\n",
239
+ "image_height 0\n",
240
+ "fav_count 0\n",
241
+ "created_at 0\n",
242
+ "solo_subject 0\n",
243
+ "multi_subject 0\n",
244
+ "artist_weights 0\n",
245
+ "character_weights 0\n",
246
+ "species_weights 0\n",
247
+ "post_id_cur 20\n",
248
+ "post_id_old 19987\n",
249
+ "dtype: int64\n",
250
+ "\n",
251
+ "Shape of the dataset: (19987, 21)\n"
252
+ ]
253
+ }
254
+ ]
255
+ },
256
+ {
257
+ "cell_type": "markdown",
258
+ "source": [
259
+ "# Create text files from parquet\n",
260
+ "\n",
261
+ "Goals:\n",
262
+ "1) First , sort each parquet item inte separate groups. First by the parquet columns 'solo_subject' vs 'multi_subject rating'. These columns are boolean values with True / False possible values. You will now have four boolean groups.\n",
263
+ "\n",
264
+ "2) Then for each of these four boolean groups , sort the contents by its 'rating' category. The ratings are a string , and can be 'explicit' , 'sensitive' , 'questionable' or 'general'. You should now have 16 groups. Assign a name to each group.\n",
265
+ "\n",
266
+ "3) For each of the 16 groups , append the texts from the parquet columns 'brief_summary' , 'midjourney_style_summary' , and 'tags' into a single text for each item. \n",
267
+ "\n",
268
+ "4) Once each item has the full descriptive text , replace all double quations \" with single quotations ' . \n",
269
+ "\n",
270
+ "5) Make sure all commas , have one space before and one space after them.\n",
271
+ "\n",
272
+ "5) For each text , remove all symbols of the following types: { , } ,] , [ , | , ^ , / , \\\n",
273
+ "\n",
274
+ "6) Replace all captilized letters for lowercase. Except for at the start of a sentence , or at the start of a quatation , for example 'Tree'\n",
275
+ "\n",
276
+ "7) Once the T5 model is loaded , truncate the text for each item to 500 tokens in length\n",
277
+ "\n",
278
+ "8) Encode the full descriptive texts using the T5 for each of the 12 group.\n",
279
+ "\n",
280
+ "9) For each of the 12 groups , put similiar texts into folders using K-means. Each group may contain a maximum of 100 folders of similiar texts.\n",
281
+ "\n",
282
+ "10) For each folder , create a txt file with the contents , using the format shown in the code. The dataset string should be enclosed with the {} symbols and each text should be separated by the | symbol , {text1|text2|....|text1000} . This txt file is javascript for a website. Make sure the indentation is correct. The name of the group and folder id should be included in the javascript as strings. Each txt file may contain a maximum of 1000 texts. Should the amount be exceeded , create more txt files until all texts within that similarity category are listed.\n",
283
+ "\n",
284
+ "11) Package the txt files into a single zip file. The folder structure within the zip file should be sorted by its 12 groups , then by the similiar texts found within each folder.\n",
285
+ "\n"
286
+ ],
287
+ "metadata": {
288
+ "id": "fB-SLVdVQvA4"
289
+ }
290
+ },
291
+ {
292
+ "cell_type": "code",
293
+ "source": [
294
+ "#@title Adapted Pipeline – Danbooru parquet β†’ rating groups β†’ clean β†’ T5 β†’ KMeans β†’ JS TXT (flat, with prev/next) β†’ ZIP\n",
295
+ "\n",
296
+ "!pip install -q transformers scikit-learn tqdm\n",
297
+ "\n",
298
+ "from google.colab import drive\n",
299
+ "drive.mount('/content/drive')\n",
300
+ "\n",
301
+ "import os\n",
302
+ "import re\n",
303
+ "import zipfile\n",
304
+ "import numpy as np\n",
305
+ "import pandas as pd\n",
306
+ "import torch\n",
307
+ "from pathlib import Path\n",
308
+ "from transformers import T5Tokenizer, T5Model\n",
309
+ "from sklearn.cluster import KMeans\n",
310
+ "from tqdm.auto import tqdm\n",
311
+ "import warnings\n",
312
+ "warnings.filterwarnings(\"ignore\")\n",
313
+ "\n",
314
+ "# ============================================================\n",
315
+ "# Configuration\n",
316
+ "# ============================================================\n",
317
+ "parquet_path = \"/content/drive/MyDrive/Saved from Chrome/danbooru.parquet\" #@param {type:\"string\"}\n",
318
+ "t5_model_name = \"t5-base\" #@param [\"t5-small\", \"t5-base\"]\n",
319
+ "max_tokens = 500 #@param {type:\"slider\", min:128, max:512, step:32}\n",
320
+ "batch_size = 1 # keep 1 for safety on Colab\n",
321
+ "max_clusters = 20 # max folders per rating group\n",
322
+ "max_texts_per_file = 500\n",
323
+ "min_texts_per_file = 300 # merge small clusters\n",
324
+ "\n",
325
+ "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
326
+ "print(f\"Device: {device}\")\n",
327
+ "\n",
328
+ "output_base = Path(\"/content/output\")\n",
329
+ "js_root = output_base / \"js_files\"\n",
330
+ "os.makedirs(js_root, exist_ok=True)\n",
331
+ "\n",
332
+ "# ============================================================\n",
333
+ "# 0. Load your parquet\n",
334
+ "# ============================================================\n",
335
+ "print(f\"Loading: {parquet_path}\")\n",
336
+ "df = pd.read_parquet(parquet_path)\n",
337
+ "print(f\"Shape: {df.shape}\")\n",
338
+ "print(f\"Columns: {df.columns.tolist()}\")\n",
339
+ "print(df.head(3))\n",
340
+ "\n",
341
+ "print(\"\\nUnique ratings and counts:\")\n",
342
+ "print(df[\"rating\"].value_counts(dropna=False))\n",
343
+ "\n",
344
+ "# ============================================================\n",
345
+ "# Helper: Text cleaning\n",
346
+ "# ============================================================\n",
347
+ "def clean_text(text: str) -> str:\n",
348
+ " if not isinstance(text, str) or not text.strip():\n",
349
+ " return \"\"\n",
350
+ "\n",
351
+ " text = text.strip()\n",
352
+ "\n",
353
+ " # Replace double quotes with single quotes\n",
354
+ " text = text.replace('\"', \"'\")\n",
355
+ "\n",
356
+ " # Ensure commas have one space before and after\n",
357
+ " text = re.sub(r'\\s*,\\s*', ' , ', text)\n",
358
+ "\n",
359
+ " # Remove forbidden symbols: { } [ ] | ^ / \\\n",
360
+ " text = re.sub(r'[{}\\[\\]\\|\\^/\\\\]', '', text)\n",
361
+ "\n",
362
+ " # Normalize whitespace\n",
363
+ " text = re.sub(r'\\s+', ' ', text).strip()\n",
364
+ "\n",
365
+ " # Lowercase everything except start of sentence / start of quote\n",
366
+ " def smart_case(s):\n",
367
+ " parts = re.split(r'([.!?]\\s+)', s)\n",
368
+ " result = []\n",
369
+ " capitalize_next = True\n",
370
+ "\n",
371
+ " for part in parts:\n",
372
+ " if not part:\n",
373
+ " continue\n",
374
+ "\n",
375
+ " if capitalize_next and part and part[0].isalpha():\n",
376
+ " part = part[0].upper() + part[1:].lower()\n",
377
+ " else:\n",
378
+ " part = part.lower()\n",
379
+ "\n",
380
+ " # Capitalize letter after a single quote (e.g. 'Tree)\n",
381
+ " part = re.sub(\n",
382
+ " r\"(['β€˜β€™])([a-z])\",\n",
383
+ " lambda m: m.group(1) + m.group(2).upper(),\n",
384
+ " part\n",
385
+ " )\n",
386
+ "\n",
387
+ " result.append(part)\n",
388
+ " capitalize_next = part.endswith(('.', '!', '?')) or bool(re.search(r'[.!?]\\s*$', part))\n",
389
+ "\n",
390
+ " return ''.join(result)\n",
391
+ "\n",
392
+ " return smart_case(text)\n",
393
+ "\n",
394
+ "\n",
395
+ "def prepare_text(row) -> str:\n",
396
+ " \"\"\"Combine caption + trigger_tag + tags in the requested format\"\"\"\n",
397
+ " caption = str(row.get(\"caption\", \"\") or \"\")\n",
398
+ " trigger = str(row.get(\"trigger_tag\", \"\") or \"\")\n",
399
+ " tags = str(row.get(\"tags\", \"\") or \"\")\n",
400
+ " combined = f\"{caption} , {trigger} and {tags}\"\n",
401
+ " return clean_text(combined)\n",
402
+ "\n",
403
+ "# ============================================================\n",
404
+ "# Prepare cleaned texts\n",
405
+ "# ============================================================\n",
406
+ "print(\"\\nCleaning texts...\")\n",
407
+ "df = df.copy()\n",
408
+ "df[\"cleaned_text\"] = df.apply(prepare_text, axis=1)\n",
409
+ "df = df[df[\"cleaned_text\"].str.len() > 10].reset_index(drop=True)\n",
410
+ "print(f\"Usable rows after cleaning: {len(df)}\")\n",
411
+ "\n",
412
+ "if len(df) < 2:\n",
413
+ " raise ValueError(\"Not enough usable texts to continue.\")\n",
414
+ "\n",
415
+ "# ============================================================\n",
416
+ "# Load T5 encoder (once)\n",
417
+ "# ============================================================\n",
418
+ "print(f\"\\nLoading {t5_model_name}...\")\n",
419
+ "tokenizer = T5Tokenizer.from_pretrained(t5_model_name)\n",
420
+ "model = T5Model.from_pretrained(t5_model_name).to(device)\n",
421
+ "model.eval()\n",
422
+ "\n",
423
+ "def get_t5_embeddings(texts):\n",
424
+ " all_embs = []\n",
425
+ " for i in tqdm(range(0, len(texts), batch_size), desc=\"Encoding with T5\"):\n",
426
+ " batch = texts[i : i + batch_size]\n",
427
+ " inputs = tokenizer(\n",
428
+ " batch,\n",
429
+ " return_tensors=\"pt\",\n",
430
+ " padding=True,\n",
431
+ " truncation=True,\n",
432
+ " max_length=max_tokens,\n",
433
+ " ).to(device)\n",
434
+ "\n",
435
+ " with torch.no_grad():\n",
436
+ " outputs = model.encoder(**inputs)\n",
437
+ " last_hidden = outputs.last_hidden_state\n",
438
+ " mask = inputs.attention_mask.unsqueeze(-1).float()\n",
439
+ " summed = (last_hidden * mask).sum(dim=1)\n",
440
+ " counts = mask.sum(dim=1).clamp(min=1e-9)\n",
441
+ " mean_pooled = summed / counts\n",
442
+ " all_embs.append(mean_pooled.cpu().numpy())\n",
443
+ " return np.vstack(all_embs)\n",
444
+ "\n",
445
+ "# ============================================================\n",
446
+ "# Process each rating group separately\n",
447
+ "# ============================================================\n",
448
+ "# Preferred order + any extra ratings that appear\n",
449
+ "preferred_order = [\"safe\", \"questionable\", \"sensitive\", \"explicit\"]\n",
450
+ "all_ratings = list(df[\"rating\"].dropna().unique())\n",
451
+ "# Keep preferred first, then any unexpected ratings\n",
452
+ "ordered_ratings = [r for r in preferred_order if r in all_ratings] + \\\n",
453
+ " [r for r in all_ratings if r not in preferred_order]\n",
454
+ "\n",
455
+ "print(f\"\\nWill process these rating groups: {ordered_ratings}\")\n",
456
+ "\n",
457
+ "# We will collect every generated file in writing order so we can set prev/next\n",
458
+ "# Each entry: dict with everything needed to write the file later\n",
459
+ "all_file_specs = []\n",
460
+ "\n",
461
+ "NAME = \"danbooru\"\n",
462
+ "EMOJI = \"🎨\"\n",
463
+ "\n",
464
+ "for rating in ordered_ratings:\n",
465
+ " subset = df[df[\"rating\"] == rating].copy().reset_index(drop=True)\n",
466
+ " print(f\"\\n{'='*60}\")\n",
467
+ " print(f\"Processing rating = '{rating}' β†’ {len(subset)} rows\")\n",
468
+ "\n",
469
+ " if len(subset) < 2:\n",
470
+ " print(\" Skipping – too few rows\")\n",
471
+ " continue\n",
472
+ "\n",
473
+ " texts = subset[\"cleaned_text\"].tolist()\n",
474
+ "\n",
475
+ " # Encode\n",
476
+ " embeddings = get_t5_embeddings(texts)\n",
477
+ " print(f\" Embeddings shape: {embeddings.shape}\")\n",
478
+ "\n",
479
+ " # K-Means\n",
480
+ " k = min(max_clusters, max(2, len(texts) // 8))\n",
481
+ " k = min(k, len(texts))\n",
482
+ " print(f\" Using k = {k} clusters\")\n",
483
+ "\n",
484
+ " kmeans = KMeans(n_clusters=k, random_state=42, n_init=10)\n",
485
+ " labels = kmeans.fit_predict(embeddings)\n",
486
+ " subset[\"cluster\"] = labels\n",
487
+ "\n",
488
+ " # Collect texts per cluster\n",
489
+ " cluster_texts_list = []\n",
490
+ " for c in range(k):\n",
491
+ " cluster_texts = subset.loc[subset[\"cluster\"] == c, \"cleaned_text\"].tolist()\n",
492
+ " if cluster_texts:\n",
493
+ " cluster_texts_list.append(cluster_texts)\n",
494
+ "\n",
495
+ " print(f\" Raw clusters: {len(cluster_texts_list)}\")\n",
496
+ "\n",
497
+ " # Merge small clusters\n",
498
+ " large_clusters = []\n",
499
+ " small_pool = []\n",
500
+ "\n",
501
+ " for texts_list in cluster_texts_list:\n",
502
+ " if len(texts_list) >= min_texts_per_file:\n",
503
+ " large_clusters.append(texts_list)\n",
504
+ " else:\n",
505
+ " small_pool.extend(texts_list)\n",
506
+ "\n",
507
+ " print(f\" Large clusters (β‰₯{min_texts_per_file}): {len(large_clusters)}\")\n",
508
+ " print(f\" Texts in small pool: {len(small_pool)}\")\n",
509
+ "\n",
510
+ " merged_small_clusters = []\n",
511
+ " if small_pool:\n",
512
+ " for start in range(0, len(small_pool), max_texts_per_file):\n",
513
+ " chunk = small_pool[start : start + max_texts_per_file]\n",
514
+ " if (len(chunk) < min_texts_per_file and merged_small_clusters\n",
515
+ " and len(merged_small_clusters[-1]) + len(chunk) <= max_texts_per_file):\n",
516
+ " merged_small_clusters[-1].extend(chunk)\n",
517
+ " else:\n",
518
+ " merged_small_clusters.append(chunk)\n",
519
+ "\n",
520
+ " final_folders = large_clusters + merged_small_clusters\n",
521
+ " print(f\" Final folders after merging: {len(final_folders)}\")\n",
522
+ "\n",
523
+ " # Build file specs for this rating (we write later so we can set prev/next)\n",
524
+ " gname = str(rating).lower().replace(\" \", \"_\")\n",
525
+ "\n",
526
+ " for folder_idx, folder_texts in enumerate(final_folders):\n",
527
+ " folder_id = f\"cluster_{folder_idx:03d}\"\n",
528
+ "\n",
529
+ " for part_idx, start in enumerate(range(0, len(folder_texts), max_texts_per_file)):\n",
530
+ " chunk = folder_texts[start : start + max_texts_per_file]\n",
531
+ " file_index = part_idx + 1\n",
532
+ "\n",
533
+ " # Compute the exact pageTitle string that will appear in the file\n",
534
+ " page_title = f\"{EMOJI} fusion-t2i-{NAME}-{gname}-{folder_id}-{file_index}\"\n",
535
+ "\n",
536
+ " all_file_specs.append({\n",
537
+ " \"gname\": gname,\n",
538
+ " \"folder_id\": folder_id,\n",
539
+ " \"part_idx\": part_idx,\n",
540
+ " \"file_index\": file_index,\n",
541
+ " \"chunk\": chunk,\n",
542
+ " \"page_title\": page_title,\n",
543
+ " })\n",
544
+ "\n",
545
+ "print(f\"\\nTotal TXT files that will be written: {len(all_file_specs)}\")\n",
546
+ "\n",
547
+ "# ============================================================\n",
548
+ "# Write all files FLAT (no subfolders) with correct backward / forward links\n",
549
+ "# ============================================================\n",
550
+ "def write_js_file(spec, backward_title: str, forward_title: str):\n",
551
+ " gname = spec[\"gname\"]\n",
552
+ " folder_id = spec[\"folder_id\"]\n",
553
+ " part_idx = spec[\"part_idx\"]\n",
554
+ " file_index = spec[\"file_index\"]\n",
555
+ " chunk = spec[\"chunk\"]\n",
556
+ " page_title = spec[\"page_title\"]\n",
557
+ "\n",
558
+ " dataset_str = \"{\" + \"|\".join(chunk) + \"}\"\n",
559
+ "\n",
560
+ " # Plain-text previous / next pageTitle\n",
561
+ " backward_str = f'[\"{backward_title}\"]' if backward_title else '[\"\"]'\n",
562
+ " forward_str = f'[\"{forward_title}\"]' if forward_title else '[\"\"]'\n",
563
+ "\n",
564
+ " content = f\"\"\"//start\n",
565
+ "group = \"{gname}\"\n",
566
+ "folder_id = \"{folder_id}\"\n",
567
+ "file_index = {file_index}\n",
568
+ "name = \"{NAME}\"\n",
569
+ "emoji = \"{EMOJI}\"\n",
570
+ "showComments = true\n",
571
+ "showDemo = true\n",
572
+ "\n",
573
+ "pageTitle = {page_title}\n",
574
+ "pageDescription = Captioned works from danbooru parquet – {gname} – {folder_id}\n",
575
+ "\n",
576
+ "tagBlackListRaw = [\"\"]\n",
577
+ "tagBlackList = [tagBlackListRaw.replaceText(' ' , ',')]\n",
578
+ "\n",
579
+ "// Generator browse destinations\n",
580
+ "backward = {backward_str}\n",
581
+ "forward = {forward_str}\n",
582
+ "backward_em = {{emoji}}\n",
583
+ "forward_em = {{emoji}}\n",
584
+ "numItemsStart = 1\n",
585
+ "//----//\n",
586
+ "\n",
587
+ "image_url = [\"https://www.iguides.ru/upload/iblock/ccf/ccf3e83b95a8b350d5089424687fc133.jpg\"]\n",
588
+ "image_description = [\"placeholder\"]\n",
589
+ "optional_image_caption = [\"placeholder\"]\n",
590
+ "\n",
591
+ "$meta\n",
592
+ " title = {EMOJI} {NAME} {gname} {folder_id} {file_index}\n",
593
+ " description = Subset of {gname} – {folder_id} – part {file_index}\n",
594
+ " image = https://i.imgur.com/TPHIzaa.jpeg\n",
595
+ "$output\n",
596
+ " [dataset]\n",
597
+ "\n",
598
+ "data = [(($output.selectMany(document.numItems).join(\" \")+' '))]\n",
599
+ "\n",
600
+ "dataset\n",
601
+ " [\"{dataset_str}\"]\n",
602
+ "//----//\n",
603
+ "\"\"\"\n",
604
+ "\n",
605
+ " # Flat structure: all files directly under js_root\n",
606
+ " filename = f\"fusion-t2i-{NAME}-{gname}-{folder_id}-part{file_index:02d}.txt\"\n",
607
+ " with open(js_root / filename, \"w\", encoding=\"utf-8\") as f:\n",
608
+ " f.write(content)\n",
609
+ "\n",
610
+ "\n",
611
+ "print(\"\\nWriting TXT files (flat) with sequential backward/forward links...\")\n",
612
+ "for i, spec in enumerate(all_file_specs):\n",
613
+ " prev_title = all_file_specs[i-1][\"page_title\"] if i > 0 else \"\"\n",
614
+ " next_title = all_file_specs[i+1][\"page_title\"] if i < len(all_file_specs)-1 else \"\"\n",
615
+ " write_js_file(spec, prev_title, next_title)\n",
616
+ "\n",
617
+ "print(f\"β†’ All files saved flat under {js_root}\")\n",
618
+ "\n",
619
+ "# ============================================================\n",
620
+ "# Create ZIP (all files at top level, no folders)\n",
621
+ "# ============================================================\n",
622
+ "zip_path = \"/content/output/danbooru_js_files.zip\"\n",
623
+ "\n",
624
+ "with zipfile.ZipFile(zip_path, \"w\", zipfile.ZIP_DEFLATED) as zipf:\n",
625
+ " for file in os.listdir(js_root):\n",
626
+ " if file.endswith(\".txt\"):\n",
627
+ " full = js_root / file\n",
628
+ " # arcname = just the filename β†’ top level of the zip\n",
629
+ " zipf.write(full, arcname=file)\n",
630
+ "\n",
631
+ "print(\"\\n\" + \"=\"*70)\n",
632
+ "print(\"βœ… ALL DONE\")\n",
633
+ "print(f\"ZIP file: {zip_path}\")\n",
634
+ "print(\"Structure inside ZIP: completely flat\")\n",
635
+ "print(\" fusion-t2i-danbooru-safe-cluster_000-part01.txt\")\n",
636
+ "print(\" fusion-t2i-danbooru-safe-cluster_000-part02.txt\")\n",
637
+ "print(\" fusion-t2i-danbooru-sensitive-cluster_000-part01.txt\")\n",
638
+ "print(\" ...\")\n",
639
+ "print(\"=\"*70)\n",
640
+ "print(\"Download the ZIP from the Colab file browser (left panel) or copy it to Drive.\")"
641
+ ],
642
+ "metadata": {
643
+ "id": "wsdSxW74jzn2"
644
+ },
645
+ "execution_count": null,
646
+ "outputs": []
647
+ }
648
+ ]
649
+ }