codeShare commited on
Commit
fcac10b
·
verified ·
1 Parent(s): 0995f61

Upload civitai_create_enriched_captions.ipynb

Browse files
qwen35_training/civitai_create_enriched_captions.ipynb ADDED
@@ -0,0 +1,911 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "c2bde1ed",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Civitai Natural Language Prompts — create enriched captions Parquet\n",
9
+ "\n",
10
+ "This notebook creates a **new folder** in `codeShare/civitai-natural-language-prompts-and-images` containing a Parquet file with the requested expanded schema:\n",
11
+ "\n",
12
+ "`idx, prompt, tags, author, json_file, byte_offset, byte_length, instruction, thinking_response, written_response, addendum`\n",
13
+ "\n",
14
+ "For each source row it:\n",
15
+ "- Checks whether `tags` already contains `general`, `sensitive`, `questionable`, or `explicit`.\n",
16
+ "- If no rating exists, retrieves the corresponding image from its JSONL shard, runs WD14 on the **Colab T4 GPU**, adds the predicted rating and adds predicted tags not already present.\n",
17
+ "- Creates `instruction` as `Describe this image using these tags: {tags}`.\n",
18
+ "- Creates `thinking_response` from a Danbooru wiki tag definition, using the unique-first selection approach in the uploaded `tag_definition` notebook.\n",
19
+ "- Creates `written_response` as `<response> {prompt} </response>`.\n",
20
+ "- Creates an empty `addendum` string.\n",
21
+ "- Writes `enriched/captions.parquet` (configurable), validates it, then uploads it.\n",
22
+ "\n",
23
+ "**Important source-format assumption:** The supplied repository structure has byte-offset-indexed JSONL records. This notebook expects each JSONL record's `image` field to contain base64 image data (optionally a `data:` URI), as in the Civitai image-retrieval example. It does not assume AES encryption or ask for an encryption password.\n",
24
+ "\n",
25
+ "**T4 requirement:** Select **Runtime → Change runtime type → T4 GPU** before running. The notebook installs `onnxruntime-gpu` and stops if CUDA is not available; it will not silently fall back to CPU.\n",
26
+ "\n",
27
+ "Add `HF_TOKEN` to Colab Secrets. The token needs read and write access to the repository."
28
+ ]
29
+ },
30
+ {
31
+ "cell_type": "markdown",
32
+ "id": "1e14de8e",
33
+ "metadata": {},
34
+ "source": [
35
+ "## 1. Install dependencies"
36
+ ]
37
+ },
38
+ {
39
+ "cell_type": "code",
40
+ "execution_count": null,
41
+ "id": "99eca89d",
42
+ "metadata": {},
43
+ "outputs": [],
44
+ "source": [
45
+ "!pip -q install -U \"huggingface_hub>=0.25.0\" \"pyarrow>=15\" \"pandas>=2\" \"pillow>=10\" datasets tqdm onnxruntime-gpu"
46
+ ]
47
+ },
48
+ {
49
+ "cell_type": "markdown",
50
+ "id": "f56dde65",
51
+ "metadata": {},
52
+ "source": [
53
+ "## 2. Authenticate and configure repository paths"
54
+ ]
55
+ },
56
+ {
57
+ "cell_type": "code",
58
+ "execution_count": null,
59
+ "id": "332692d2",
60
+ "metadata": {},
61
+ "outputs": [],
62
+ "source": [
63
+ "from google.colab import userdata\n",
64
+ "from huggingface_hub import login, hf_hub_download, HfApi\n",
65
+ "from datasets import load_dataset\n",
66
+ "\n",
67
+ "from pathlib import Path\n",
68
+ "from collections import defaultdict, Counter\n",
69
+ "from datetime import datetime, timezone\n",
70
+ "\n",
71
+ "import base64\n",
72
+ "import csv\n",
73
+ "import gc\n",
74
+ "import io\n",
75
+ "import json\n",
76
+ "import random\n",
77
+ "import re\n",
78
+ "import shutil\n",
79
+ "import numpy as np\n",
80
+ "import pandas as pd\n",
81
+ "import pyarrow as pa\n",
82
+ "import pyarrow.parquet as pq\n",
83
+ "import onnxruntime as ort\n",
84
+ "\n",
85
+ "from PIL import Image, ImageFile\n",
86
+ "from tqdm.auto import tqdm\n",
87
+ "\n",
88
+ "ImageFile.LOAD_TRUNCATED_IMAGES = True\n",
89
+ "\n",
90
+ "HF_TOKEN = userdata.get(\"HF_TOKEN\")\n",
91
+ "if not HF_TOKEN:\n",
92
+ " raise RuntimeError(\"HF_TOKEN is missing from Colab Secrets.\")\n",
93
+ "\n",
94
+ "login(token=HF_TOKEN)\n",
95
+ "api = HfApi(token=HF_TOKEN)\n",
96
+ "\n",
97
+ "REPO_ID = \"codeShare/civitai-natural-language-prompts-and-images\"\n",
98
+ "REPO_TYPE = \"dataset\"\n",
99
+ "SOURCE_PARQUET = \"captions.parquet\"\n",
100
+ "\n",
101
+ "# New folder and output file in the SAME repository.\n",
102
+ "OUTPUT_FOLDER = \"enriched\"\n",
103
+ "OUTPUT_PARQUET_REPO_PATH = f\"{OUTPUT_FOLDER}/captions.parquet\"\n",
104
+ "\n",
105
+ "# WD14 ONNX model.\n",
106
+ "WD_MODEL_REPO = \"SmilingWolf/wd-swinv2-tagger-v3\"\n",
107
+ "\n",
108
+ "# WD14 inference settings.\n",
109
+ "TAG_THRESHOLD = 0.35\n",
110
+ "BATCH_SIZE = 500\n",
111
+ "RANDOM_SEED = 20261124\n",
112
+ "random.seed(RANDOM_SEED)\n",
113
+ "\n",
114
+ "# Full dataset by default. Keep None for a complete output.\n",
115
+ "MAX_ROWS = None\n",
116
+ "\n",
117
+ "# Safety: upload only if every row has a recognized rating.\n",
118
+ "ABORT_UPLOAD_IF_MISSING_RATINGS = True\n",
119
+ "\n",
120
+ "# Keep a local copy of the source and generated output.\n",
121
+ "WORK_DIR = Path(\"/content/civitai_enriched_captions\")\n",
122
+ "WORK_DIR.mkdir(parents=True, exist_ok=True)\n",
123
+ "LOCAL_SOURCE = WORK_DIR / \"captions_source.parquet\"\n",
124
+ "LOCAL_OUTPUT = WORK_DIR / \"captions.parquet\"\n",
125
+ "\n",
126
+ "VALID_RATINGS = {\"general\", \"sensitive\", \"questionable\", \"explicit\"}\n",
127
+ "\n",
128
+ "print(\"Repository:\", REPO_ID)\n",
129
+ "print(\"Source:\", SOURCE_PARQUET)\n",
130
+ "print(\"Destination:\", OUTPUT_PARQUET_REPO_PATH)"
131
+ ]
132
+ },
133
+ {
134
+ "cell_type": "markdown",
135
+ "id": "4703958d",
136
+ "metadata": {},
137
+ "source": [
138
+ "## 3. Download and inspect source Parquet"
139
+ ]
140
+ },
141
+ {
142
+ "cell_type": "code",
143
+ "execution_count": null,
144
+ "id": "e8979905",
145
+ "metadata": {},
146
+ "outputs": [],
147
+ "source": [
148
+ "source_path = hf_hub_download(\n",
149
+ " repo_id=REPO_ID,\n",
150
+ " repo_type=REPO_TYPE,\n",
151
+ " filename=SOURCE_PARQUET,\n",
152
+ " token=HF_TOKEN,\n",
153
+ " force_download=True,\n",
154
+ ")\n",
155
+ "shutil.copy2(source_path, LOCAL_SOURCE)\n",
156
+ "\n",
157
+ "source_pf = pq.ParquetFile(LOCAL_SOURCE)\n",
158
+ "source_schema = source_pf.schema_arrow\n",
159
+ "source_columns = set(source_schema.names)\n",
160
+ "\n",
161
+ "required = {\n",
162
+ " \"idx\", \"prompt\", \"tags\", \"author\",\n",
163
+ " \"json_file\", \"byte_offset\", \"byte_length\",\n",
164
+ "}\n",
165
+ "missing = required - source_columns\n",
166
+ "if missing:\n",
167
+ " raise RuntimeError(\"Source Parquet missing columns: \" + \", \".join(sorted(missing)))\n",
168
+ "\n",
169
+ "TOTAL_ROWS = source_pf.metadata.num_rows\n",
170
+ "if MAX_ROWS is not None:\n",
171
+ " TOTAL_ROWS = min(TOTAL_ROWS, int(MAX_ROWS))\n",
172
+ "\n",
173
+ "print(\"Source rows:\", f\"{source_pf.metadata.num_rows:,}\")\n",
174
+ "print(\"Rows to process:\", f\"{TOTAL_ROWS:,}\")\n",
175
+ "print(\"Source schema:\")\n",
176
+ "print(source_schema)"
177
+ ]
178
+ },
179
+ {
180
+ "cell_type": "markdown",
181
+ "id": "0bd4ed36",
182
+ "metadata": {},
183
+ "source": [
184
+ "## 4. Load WD14 ONNX model and require T4/CUDA"
185
+ ]
186
+ },
187
+ {
188
+ "cell_type": "code",
189
+ "execution_count": null,
190
+ "id": "2b560249",
191
+ "metadata": {},
192
+ "outputs": [],
193
+ "source": [
194
+ "# Colab must be configured with a T4 GPU before this cell.\n",
195
+ "try:\n",
196
+ " import torch\n",
197
+ " print(\"PyTorch CUDA available:\", torch.cuda.is_available())\n",
198
+ " if torch.cuda.is_available():\n",
199
+ " print(\"GPU:\", torch.cuda.get_device_name(0))\n",
200
+ "except Exception as exc:\n",
201
+ " print(\"PyTorch GPU check unavailable:\", exc)\n",
202
+ "\n",
203
+ "if \"CUDAExecutionProvider\" not in ort.get_available_providers():\n",
204
+ " raise RuntimeError(\n",
205
+ " \"ONNX Runtime CUDAExecutionProvider is unavailable. \"\n",
206
+ " \"Select a T4 GPU runtime, restart the runtime, and rerun the install cell.\"\n",
207
+ " )\n",
208
+ "\n",
209
+ "MODEL_PATH = hf_hub_download(\n",
210
+ " repo_id=WD_MODEL_REPO,\n",
211
+ " filename=\"model.onnx\",\n",
212
+ " token=HF_TOKEN,\n",
213
+ ")\n",
214
+ "TAGS_CSV_PATH = hf_hub_download(\n",
215
+ " repo_id=WD_MODEL_REPO,\n",
216
+ " filename=\"selected_tags.csv\",\n",
217
+ " token=HF_TOKEN,\n",
218
+ ")\n",
219
+ "\n",
220
+ "session = ort.InferenceSession(\n",
221
+ " MODEL_PATH,\n",
222
+ " providers=[\"CUDAExecutionProvider\", \"CPUExecutionProvider\"],\n",
223
+ ")\n",
224
+ "input_info = session.get_inputs()[0]\n",
225
+ "output_info = session.get_outputs()[0]\n",
226
+ "\n",
227
+ "tag_df = pd.read_csv(TAGS_CSV_PATH)\n",
228
+ "if not {\"name\", \"category\"}.issubset(tag_df.columns):\n",
229
+ " raise RuntimeError(\"selected_tags.csv must have name and category columns.\")\n",
230
+ "\n",
231
+ "tag_names = tag_df[\"name\"].astype(str).tolist()\n",
232
+ "tag_categories = tag_df[\"category\"].astype(int).to_numpy()\n",
233
+ "\n",
234
+ "# WD14 category 9 contains rating labels.\n",
235
+ "rating_indices = {}\n",
236
+ "for i, (name, category) in enumerate(zip(tag_names, tag_categories)):\n",
237
+ " if category != 9:\n",
238
+ " continue\n",
239
+ " normalized = name.strip().lower()\n",
240
+ " if normalized.startswith(\"rating:\"):\n",
241
+ " normalized = normalized.split(\":\", 1)[1].strip()\n",
242
+ " if normalized == \"safe\":\n",
243
+ " normalized = \"general\"\n",
244
+ " if normalized in VALID_RATINGS:\n",
245
+ " rating_indices[normalized] = i\n",
246
+ "\n",
247
+ "if not rating_indices:\n",
248
+ " raise RuntimeError(\n",
249
+ " \"No supported category-9 rating labels found in this WD14 model.\"\n",
250
+ " )\n",
251
+ "\n",
252
+ "# Determine model tensor layout and dimensions.\n",
253
+ "shape = input_info.shape\n",
254
+ "if len(shape) != 4:\n",
255
+ " raise RuntimeError(f\"Unexpected model input shape: {shape}\")\n",
256
+ "\n",
257
+ "if shape[1] == 3 and isinstance(shape[2], int) and isinstance(shape[3], int):\n",
258
+ " INPUT_LAYOUT = \"NCHW\"\n",
259
+ " IMAGE_HEIGHT, IMAGE_WIDTH = shape[2], shape[3]\n",
260
+ "elif isinstance(shape[1], int) and isinstance(shape[2], int) and shape[3] == 3:\n",
261
+ " INPUT_LAYOUT = \"NHWC\"\n",
262
+ " IMAGE_HEIGHT, IMAGE_WIDTH = shape[1], shape[2]\n",
263
+ "else:\n",
264
+ " raise RuntimeError(f\"Unsupported WD14 input shape: {shape}\")\n",
265
+ "\n",
266
+ "print(\"ONNX providers:\", session.get_providers())\n",
267
+ "print(\"Input:\", input_info.name, shape)\n",
268
+ "print(\"Image dimensions:\", IMAGE_WIDTH, \"x\", IMAGE_HEIGHT, INPUT_LAYOUT)\n",
269
+ "print(\"Number of labels:\", len(tag_names))\n",
270
+ "print(\"Rating labels:\", rating_indices)\n",
271
+ "\n",
272
+ "if \"CUDAExecutionProvider\" not in session.get_providers():\n",
273
+ " raise RuntimeError(\"The WD14 session did not initialize the CUDA provider.\")"
274
+ ]
275
+ },
276
+ {
277
+ "cell_type": "markdown",
278
+ "id": "28980d86",
279
+ "metadata": {},
280
+ "source": [
281
+ "## 5. WD14 image preprocessing and prediction"
282
+ ]
283
+ },
284
+ {
285
+ "cell_type": "code",
286
+ "execution_count": null,
287
+ "id": "9a150b37",
288
+ "metadata": {},
289
+ "outputs": [],
290
+ "source": [
291
+ "def preprocess_wd_image(image):\n",
292
+ " image = image.convert(\"RGB\")\n",
293
+ " arr = np.asarray(image)[:, :, ::-1] # RGB -> BGR, expected by WD14\n",
294
+ "\n",
295
+ " h, w = arr.shape[:2]\n",
296
+ " side = max(h, w)\n",
297
+ " padded = np.full((side, side, 3), 255, dtype=np.uint8)\n",
298
+ " top = (side - h) // 2\n",
299
+ " left = (side - w) // 2\n",
300
+ " padded[top:top+h, left:left+w] = arr\n",
301
+ "\n",
302
+ " resized = Image.fromarray(padded).resize(\n",
303
+ " (IMAGE_WIDTH, IMAGE_HEIGHT),\n",
304
+ " Image.Resampling.LANCZOS,\n",
305
+ " )\n",
306
+ " tensor = np.asarray(resized, dtype=np.float32)\n",
307
+ "\n",
308
+ " if INPUT_LAYOUT == \"NHWC\":\n",
309
+ " return tensor[None, ...]\n",
310
+ " return np.transpose(tensor, (2, 0, 1))[None, ...]\n",
311
+ "\n",
312
+ "\n",
313
+ "def run_wd_tagger(image_bytes):\n",
314
+ " with Image.open(io.BytesIO(image_bytes)) as im:\n",
315
+ " tensor = preprocess_wd_image(im)\n",
316
+ "\n",
317
+ " scores = session.run(\n",
318
+ " [output_info.name],\n",
319
+ " {input_info.name: tensor},\n",
320
+ " )[0].reshape(-1)\n",
321
+ "\n",
322
+ " if len(scores) != len(tag_names):\n",
323
+ " raise RuntimeError(\n",
324
+ " f\"Model returned {len(scores)} scores for {len(tag_names)} labels.\"\n",
325
+ " )\n",
326
+ "\n",
327
+ " # Pick the highest-scoring available rating class.\n",
328
+ " rating = max(\n",
329
+ " rating_indices,\n",
330
+ " key=lambda label: float(scores[rating_indices[label]])\n",
331
+ " )\n",
332
+ "\n",
333
+ " # Return non-rating labels over threshold.\n",
334
+ " predicted_tags = []\n",
335
+ " for i, (name, category) in enumerate(zip(tag_names, tag_categories)):\n",
336
+ " if category == 9:\n",
337
+ " continue\n",
338
+ " if float(scores[i]) >= TAG_THRESHOLD:\n",
339
+ " label = str(name).strip()\n",
340
+ " if label:\n",
341
+ " predicted_tags.append(label)\n",
342
+ "\n",
343
+ " return rating, predicted_tags\n",
344
+ "\n",
345
+ "print(\"WD14 inference function ready.\")"
346
+ ]
347
+ },
348
+ {
349
+ "cell_type": "markdown",
350
+ "id": "d416f6cc",
351
+ "metadata": {},
352
+ "source": [
353
+ "## 6. Load Danbooru wiki definitions (using the uploaded notebook's method)"
354
+ ]
355
+ },
356
+ {
357
+ "cell_type": "code",
358
+ "execution_count": null,
359
+ "id": "b0743f28",
360
+ "metadata": {},
361
+ "outputs": [],
362
+ "source": [
363
+ "print(\"Loading lylogummy/danbooru_wikis_2026 ...\")\n",
364
+ "wiki_ds = load_dataset(\"lylogummy/danbooru_wikis_2026\", split=\"train\")\n",
365
+ "\n",
366
+ "def clean_definition(text):\n",
367
+ " \"\"\"\n",
368
+ " Same cleaning approach as the uploaded tag_definition notebook:\n",
369
+ " retain letters, digits, comma, period, quotes, apostrophe, !, ?, and spaces;\n",
370
+ " collapse whitespace and lowercase the first character.\n",
371
+ " \"\"\"\n",
372
+ " if not text:\n",
373
+ " return \"\"\n",
374
+ " cleaned = re.sub(r\"[^A-Za-z0-9,.\\\"'!? ]+\", \" \", str(text))\n",
375
+ " cleaned = \" \".join(cleaned.split())\n",
376
+ " if cleaned:\n",
377
+ " cleaned = cleaned[0].lower() + cleaned[1:]\n",
378
+ " return cleaned\n",
379
+ "\n",
380
+ "\n",
381
+ "wiki_lookup = {}\n",
382
+ "for item in tqdm(wiki_ds, desc=\"Building wiki lookup\"):\n",
383
+ " if item.get(\"is_deleted\", False):\n",
384
+ " continue\n",
385
+ " title = (item.get(\"title\") or \"\").strip().lower()\n",
386
+ " body = item.get(\"body\")\n",
387
+ " if not title or not body:\n",
388
+ " continue\n",
389
+ " definition = clean_definition(body)\n",
390
+ " if definition:\n",
391
+ " wiki_lookup[title] = definition\n",
392
+ "\n",
393
+ "print(\"Usable wiki definitions:\", f\"{len(wiki_lookup):,}\")"
394
+ ]
395
+ },
396
+ {
397
+ "cell_type": "markdown",
398
+ "id": "3fa6e1d0",
399
+ "metadata": {},
400
+ "source": [
401
+ "## 7. Helpers: ratings, tags, image decoding, and response text"
402
+ ]
403
+ },
404
+ {
405
+ "cell_type": "code",
406
+ "execution_count": null,
407
+ "id": "8143f6c7",
408
+ "metadata": {},
409
+ "outputs": [],
410
+ "source": [
411
+ "def split_tags(value):\n",
412
+ " if not isinstance(value, str) or not value.strip():\n",
413
+ " return []\n",
414
+ " return [part.strip() for part in value.split(\",\") if part.strip()]\n",
415
+ "\n",
416
+ "\n",
417
+ "def norm_tag(value):\n",
418
+ " return re.sub(r\"\\s+\", \" \", str(value).strip()).casefold()\n",
419
+ "\n",
420
+ "\n",
421
+ "def find_rating(tags):\n",
422
+ " for tag in tags:\n",
423
+ " normalized = norm_tag(tag)\n",
424
+ " if normalized.startswith(\"rating:\"):\n",
425
+ " normalized = normalized.split(\":\", 1)[1].strip()\n",
426
+ " if normalized == \"safe\":\n",
427
+ " normalized = \"general\"\n",
428
+ " if normalized in VALID_RATINGS:\n",
429
+ " return normalized\n",
430
+ " return None\n",
431
+ "\n",
432
+ "\n",
433
+ "def merge_missing_tags(existing, additions):\n",
434
+ " result = list(existing)\n",
435
+ " seen = {norm_tag(x) for x in result}\n",
436
+ " added = 0\n",
437
+ " for item in additions:\n",
438
+ " item = str(item).strip()\n",
439
+ " if not item:\n",
440
+ " continue\n",
441
+ " key = norm_tag(item)\n",
442
+ " if key not in seen:\n",
443
+ " result.append(item)\n",
444
+ " seen.add(key)\n",
445
+ " added += 1\n",
446
+ " return result, added\n",
447
+ "\n",
448
+ "\n",
449
+ "def decode_jsonl_image(image_value):\n",
450
+ " \"\"\"\n",
451
+ " The Civitai repository's image field is expected to be base64,\n",
452
+ " optionally wrapped in a data URI. This is not the encrypted Sankaku format.\n",
453
+ " \"\"\"\n",
454
+ " if not isinstance(image_value, str) or not image_value.strip():\n",
455
+ " raise ValueError(\"JSONL record has no usable image field.\")\n",
456
+ "\n",
457
+ " value = image_value.strip()\n",
458
+ " if value.startswith(\"data:\") and \",\" in value:\n",
459
+ " value = value.split(\",\", 1)[1]\n",
460
+ "\n",
461
+ " value = re.sub(r\"\\s+\", \"\", value)\n",
462
+ " return base64.b64decode(value, validate=True)\n",
463
+ "\n",
464
+ "\n",
465
+ "def load_image_bytes_for_row(shard_file, row):\n",
466
+ " offset = int(row[\"byte_offset\"])\n",
467
+ " length = int(row[\"byte_length\"])\n",
468
+ " if offset < 0 or length <= 0:\n",
469
+ " raise ValueError(\"Invalid byte_offset or byte_length.\")\n",
470
+ "\n",
471
+ " shard_file.seek(offset)\n",
472
+ " raw = shard_file.read(length)\n",
473
+ " if len(raw) != length:\n",
474
+ " raise IOError(f\"Short JSONL read: expected {length}, got {len(raw)}.\")\n",
475
+ "\n",
476
+ " record = json.loads(raw.decode(\"utf-8\"))\n",
477
+ " if str(record.get(\"idx\")) != str(row[\"idx\"]):\n",
478
+ " raise ValueError(\n",
479
+ " f\"idx mismatch: Parquet={row['idx']}, JSONL={record.get('idx')}\"\n",
480
+ " )\n",
481
+ "\n",
482
+ " return decode_jsonl_image(record.get(\"image\"))\n",
483
+ "\n",
484
+ "\n",
485
+ "def choose_tag_definition(tags, used_tags):\n",
486
+ " \"\"\"\n",
487
+ " Select a matching Danbooru wiki tag, preferring one not used for an earlier row.\n",
488
+ " Falls back to a matching tag if all matches have already been used.\n",
489
+ " \"\"\"\n",
490
+ " matches = []\n",
491
+ " seen = set()\n",
492
+ " for tag in tags:\n",
493
+ " key = str(tag).strip().lower()\n",
494
+ " if key in wiki_lookup and key not in seen:\n",
495
+ " matches.append(key)\n",
496
+ " seen.add(key)\n",
497
+ "\n",
498
+ " if not matches:\n",
499
+ " return \"\"\n",
500
+ "\n",
501
+ " unused = [tag for tag in matches if tag not in used_tags]\n",
502
+ " chosen = random.choice(unused if unused else matches)\n",
503
+ " used_tags.add(chosen)\n",
504
+ "\n",
505
+ " definition = wiki_lookup[chosen]\n",
506
+ " return f\"The {chosen} tag means this image has {definition}\"\n",
507
+ "\n",
508
+ "\n",
509
+ "def make_thinking_response(definition):\n",
510
+ " return f\"<thinking> {definition} </thinking>\"\n",
511
+ "\n",
512
+ "\n",
513
+ "def make_written_response(prompt):\n",
514
+ " prompt = \"\" if prompt is None else str(prompt)\n",
515
+ " return f\"<response> {prompt} </response>\"\n",
516
+ "\n",
517
+ "print(\"Helpers ready.\")"
518
+ ]
519
+ },
520
+ {
521
+ "cell_type": "markdown",
522
+ "id": "90eb8459",
523
+ "metadata": {},
524
+ "source": [
525
+ "## 8. Define the exact output schema"
526
+ ]
527
+ },
528
+ {
529
+ "cell_type": "code",
530
+ "execution_count": null,
531
+ "id": "dcc849fa",
532
+ "metadata": {},
533
+ "outputs": [],
534
+ "source": [
535
+ "output_schema = pa.schema([\n",
536
+ " pa.field(\"idx\", pa.int64()),\n",
537
+ " pa.field(\"prompt\", pa.string()),\n",
538
+ " pa.field(\"tags\", pa.string()),\n",
539
+ " pa.field(\"author\", pa.string()),\n",
540
+ " pa.field(\"json_file\", pa.string()),\n",
541
+ " pa.field(\"byte_offset\", pa.int64()),\n",
542
+ " pa.field(\"byte_length\", pa.int64()),\n",
543
+ " pa.field(\"instruction\", pa.string()),\n",
544
+ " pa.field(\"thinking_response\", pa.string()),\n",
545
+ " pa.field(\"written_response\", pa.string()),\n",
546
+ " pa.field(\"addendum\", pa.string()),\n",
547
+ "])\n",
548
+ "\n",
549
+ "print(output_schema)"
550
+ ]
551
+ },
552
+ {
553
+ "cell_type": "markdown",
554
+ "id": "58759228",
555
+ "metadata": {},
556
+ "source": [
557
+ "## 9. Process the full dataset and write the new Parquet"
558
+ ]
559
+ },
560
+ {
561
+ "cell_type": "code",
562
+ "execution_count": null,
563
+ "id": "6f09fc0a",
564
+ "metadata": {},
565
+ "outputs": [],
566
+ "source": [
567
+ "stats = Counter()\n",
568
+ "failures = []\n",
569
+ "shard_cache = {}\n",
570
+ "used_definition_tags = set()\n",
571
+ "processed_rows = 0\n",
572
+ "\n",
573
+ "writer = pq.ParquetWriter(\n",
574
+ " LOCAL_OUTPUT,\n",
575
+ " output_schema,\n",
576
+ " compression=\"zstd\",\n",
577
+ ")\n",
578
+ "\n",
579
+ "progress = tqdm(total=TOTAL_ROWS, desc=\"Building enriched captions\", unit=\"rows\")\n",
580
+ "\n",
581
+ "try:\n",
582
+ " for batch in source_pf.iter_batches(\n",
583
+ " batch_size=BATCH_SIZE,\n",
584
+ " columns=[\n",
585
+ " \"idx\", \"prompt\", \"tags\", \"author\",\n",
586
+ " \"json_file\", \"byte_offset\", \"byte_length\",\n",
587
+ " ],\n",
588
+ " ):\n",
589
+ " source_rows = batch.to_pylist()\n",
590
+ " if MAX_ROWS is not None:\n",
591
+ " remaining = TOTAL_ROWS - processed_rows\n",
592
+ " source_rows = source_rows[:remaining]\n",
593
+ " if not source_rows:\n",
594
+ " break\n",
595
+ "\n",
596
+ " # Identify rows requiring WD14 because their tag string has no rating.\n",
597
+ " missing_rating_by_shard = defaultdict(list)\n",
598
+ " output_rows = []\n",
599
+ "\n",
600
+ " for pos, source_row in enumerate(source_rows):\n",
601
+ " tags = split_tags(source_row.get(\"tags\"))\n",
602
+ " existing_rating = find_rating(tags)\n",
603
+ "\n",
604
+ " if existing_rating:\n",
605
+ " stats[\"existing_rating\"] += 1\n",
606
+ " else:\n",
607
+ " shard = source_row.get(\"json_file\")\n",
608
+ " if not shard:\n",
609
+ " failures.append({\n",
610
+ " \"idx\": source_row.get(\"idx\"),\n",
611
+ " \"reason\": \"Missing json_file\",\n",
612
+ " })\n",
613
+ " stats[\"missing_shard\"] += 1\n",
614
+ " else:\n",
615
+ " missing_rating_by_shard[str(shard)].append(pos)\n",
616
+ "\n",
617
+ " output_rows.append({\n",
618
+ " \"idx\": int(source_row[\"idx\"]),\n",
619
+ " \"prompt\": None if source_row.get(\"prompt\") is None else str(source_row[\"prompt\"]),\n",
620
+ " \"tags\": \", \".join(tags),\n",
621
+ " \"author\": None if source_row.get(\"author\") is None else str(source_row[\"author\"]),\n",
622
+ " \"json_file\": None if source_row.get(\"json_file\") is None else str(source_row[\"json_file\"]),\n",
623
+ " \"byte_offset\": int(source_row[\"byte_offset\"]),\n",
624
+ " \"byte_length\": int(source_row[\"byte_length\"]),\n",
625
+ " \"instruction\": \"\",\n",
626
+ " \"thinking_response\": \"\",\n",
627
+ " \"written_response\": make_written_response(source_row.get(\"prompt\")),\n",
628
+ " \"addendum\": \"\",\n",
629
+ " })\n",
630
+ "\n",
631
+ " # For each shard, fetch images only for rows lacking a rating.\n",
632
+ " for shard_name, positions in missing_rating_by_shard.items():\n",
633
+ " try:\n",
634
+ " if shard_name not in shard_cache:\n",
635
+ " shard_cache[shard_name] = hf_hub_download(\n",
636
+ " repo_id=REPO_ID,\n",
637
+ " filename=shard_name,\n",
638
+ " repo_type=REPO_TYPE,\n",
639
+ " token=HF_TOKEN,\n",
640
+ " )\n",
641
+ "\n",
642
+ " with open(shard_cache[shard_name], \"rb\") as shard_file:\n",
643
+ " for pos in positions:\n",
644
+ " source_row = source_rows[pos]\n",
645
+ " try:\n",
646
+ " image_bytes = load_image_bytes_for_row(\n",
647
+ " shard_file, source_row\n",
648
+ " )\n",
649
+ " predicted_rating, predicted_tags = run_wd_tagger(\n",
650
+ " image_bytes\n",
651
+ " )\n",
652
+ "\n",
653
+ " tags = split_tags(source_row.get(\"tags\"))\n",
654
+ " tags, added_count = merge_missing_tags(\n",
655
+ " tags, predicted_tags\n",
656
+ " )\n",
657
+ " tags, _ = merge_missing_tags(\n",
658
+ " tags, [predicted_rating]\n",
659
+ " )\n",
660
+ "\n",
661
+ " # Put the rating first for convenient downstream filtering.\n",
662
+ " rating_key = norm_tag(predicted_rating)\n",
663
+ " tags = [predicted_rating] + [\n",
664
+ " tag for tag in tags\n",
665
+ " if norm_tag(tag) != rating_key\n",
666
+ " and norm_tag(tag) != \"rating:\" + rating_key\n",
667
+ " ]\n",
668
+ "\n",
669
+ " output_rows[pos][\"tags\"] = \", \".join(tags)\n",
670
+ " stats[\"classified_missing_rating\"] += 1\n",
671
+ " stats[\"predicted_tags_added\"] += added_count\n",
672
+ " stats[f\"predicted_rating_{predicted_rating}\"] += 1\n",
673
+ "\n",
674
+ " del image_bytes\n",
675
+ "\n",
676
+ " except Exception as exc:\n",
677
+ " failures.append({\n",
678
+ " \"idx\": source_row.get(\"idx\"),\n",
679
+ " \"shard\": shard_name,\n",
680
+ " \"reason\": str(exc),\n",
681
+ " })\n",
682
+ " stats[\"image_or_inference_failures\"] += 1\n",
683
+ "\n",
684
+ " except Exception as exc:\n",
685
+ " for pos in positions:\n",
686
+ " failures.append({\n",
687
+ " \"idx\": source_rows[pos].get(\"idx\"),\n",
688
+ " \"shard\": shard_name,\n",
689
+ " \"reason\": str(exc),\n",
690
+ " })\n",
691
+ " stats[\"shard_failures\"] += len(positions)\n",
692
+ "\n",
693
+ " # Now create instruction and wiki-definition thinking response\n",
694
+ " # from the final tags (including WD14 additions where available).\n",
695
+ " for out_row in output_rows:\n",
696
+ " final_tags = split_tags(out_row[\"tags\"])\n",
697
+ " out_row[\"instruction\"] = (\n",
698
+ " \"Describe this image using these tags: \" + out_row[\"tags\"]\n",
699
+ " )\n",
700
+ " definition = choose_tag_definition(\n",
701
+ " final_tags,\n",
702
+ " used_definition_tags,\n",
703
+ " )\n",
704
+ " out_row[\"thinking_response\"] = make_thinking_response(definition)\n",
705
+ "\n",
706
+ " rating = find_rating(final_tags)\n",
707
+ " if rating:\n",
708
+ " stats[f\"output_rating_{rating}\"] += 1\n",
709
+ " else:\n",
710
+ " stats[\"output_missing_rating\"] += 1\n",
711
+ "\n",
712
+ " if not definition:\n",
713
+ " stats[\"no_matching_wiki_definition\"] += 1\n",
714
+ "\n",
715
+ " table = pa.Table.from_pylist(output_rows, schema=output_schema)\n",
716
+ " writer.write_table(table)\n",
717
+ "\n",
718
+ " processed_rows += len(output_rows)\n",
719
+ " progress.update(len(output_rows))\n",
720
+ "\n",
721
+ " del batch, source_rows, output_rows, table\n",
722
+ " gc.collect()\n",
723
+ "\n",
724
+ "finally:\n",
725
+ " writer.close()\n",
726
+ " progress.close()\n",
727
+ "\n",
728
+ "FAILURE_REPORT = WORK_DIR / \"processing_failures.json\"\n",
729
+ "with open(FAILURE_REPORT, \"w\", encoding=\"utf-8\") as f:\n",
730
+ " json.dump(failures, f, ensure_ascii=False, indent=2)\n",
731
+ "\n",
732
+ "print(\"\\\\nProcessing complete.\")\n",
733
+ "print(\"Rows written:\", f\"{processed_rows:,}\")\n",
734
+ "for key, value in sorted(stats.items()):\n",
735
+ " print(f\"{key}: {value:,}\")\n",
736
+ "print(\"Failures:\", len(failures))\n",
737
+ "print(\"Unique wiki tags used:\", f\"{len(used_definition_tags):,}\")\n",
738
+ "print(\"Failure report:\", FAILURE_REPORT)\n",
739
+ "print(\"Local output:\", LOCAL_OUTPUT)"
740
+ ]
741
+ },
742
+ {
743
+ "cell_type": "markdown",
744
+ "id": "91f2cede",
745
+ "metadata": {},
746
+ "source": [
747
+ "## 10. Validate output schema, content, and ratings"
748
+ ]
749
+ },
750
+ {
751
+ "cell_type": "code",
752
+ "execution_count": null,
753
+ "id": "0cb2c2fd",
754
+ "metadata": {},
755
+ "outputs": [],
756
+ "source": [
757
+ "out_pf = pq.ParquetFile(LOCAL_OUTPUT)\n",
758
+ "\n",
759
+ "if out_pf.metadata.num_rows != processed_rows:\n",
760
+ " raise RuntimeError(\"Output row count mismatch.\")\n",
761
+ "\n",
762
+ "if not out_pf.schema_arrow.equals(output_schema, check_metadata=False):\n",
763
+ " raise RuntimeError(\n",
764
+ " \"Output schema mismatch.\\\\nExpected:\\\\n\"\n",
765
+ " + str(output_schema)\n",
766
+ " + \"\\\\nActual:\\\\n\"\n",
767
+ " + str(out_pf.schema_arrow)\n",
768
+ " )\n",
769
+ "\n",
770
+ "validation = Counter()\n",
771
+ "validation_errors = []\n",
772
+ "\n",
773
+ "for batch in tqdm(\n",
774
+ " out_pf.iter_batches(\n",
775
+ " batch_size=25_000,\n",
776
+ " columns=[\n",
777
+ " \"idx\", \"tags\", \"instruction\",\n",
778
+ " \"thinking_response\", \"written_response\", \"addendum\",\n",
779
+ " ],\n",
780
+ " ),\n",
781
+ " desc=\"Validating generated Parquet\",\n",
782
+ "):\n",
783
+ " for row in batch.to_pylist():\n",
784
+ " tags = split_tags(row[\"tags\"])\n",
785
+ " rating = find_rating(tags)\n",
786
+ " if rating:\n",
787
+ " validation[f\"rating_{rating}\"] += 1\n",
788
+ " else:\n",
789
+ " validation[\"missing_rating\"] += 1\n",
790
+ "\n",
791
+ " if row[\"instruction\"] != \"Describe this image using these tags: \" + (row[\"tags\"] or \"\"):\n",
792
+ " validation_errors.append((row[\"idx\"], \"instruction\"))\n",
793
+ "\n",
794
+ " if not (str(row[\"written_response\"]).startswith(\"<response> \")\n",
795
+ " and str(row[\"written_response\"]).endswith(\" </response>\")):\n",
796
+ " validation_errors.append((row[\"idx\"], \"written_response\"))\n",
797
+ "\n",
798
+ " if not (str(row[\"thinking_response\"]).startswith(\"<thinking> \")\n",
799
+ " and str(row[\"thinking_response\"]).endswith(\" </thinking>\")):\n",
800
+ " validation_errors.append((row[\"idx\"], \"thinking_response\"))\n",
801
+ "\n",
802
+ " if row[\"addendum\"] != \"\":\n",
803
+ " validation_errors.append((row[\"idx\"], \"addendum\"))\n",
804
+ "\n",
805
+ "print(\"Rows:\", f\"{out_pf.metadata.num_rows:,}\")\n",
806
+ "for key, value in sorted(validation.items()):\n",
807
+ " print(f\"{key}: {value:,}\")\n",
808
+ "print(\"Validation errors:\", len(validation_errors))\n",
809
+ "if validation_errors:\n",
810
+ " print(\"First validation errors:\", validation_errors[:20])\n",
811
+ "\n",
812
+ "if validation_errors:\n",
813
+ " raise RuntimeError(\"Output validation failed.\")\n",
814
+ "\n",
815
+ "if ABORT_UPLOAD_IF_MISSING_RATINGS and validation[\"missing_rating\"]:\n",
816
+ " raise RuntimeError(\n",
817
+ " f\"{validation['missing_rating']} rows have no rating. \"\n",
818
+ " \"Upload blocked; inspect processing_failures.json.\"\n",
819
+ " )\n",
820
+ "\n",
821
+ "if MAX_ROWS is not None:\n",
822
+ " raise RuntimeError(\n",
823
+ " \"MAX_ROWS is limited. Refusing to upload a partial output as a full dataset.\"\n",
824
+ " )\n",
825
+ "\n",
826
+ "print(\"Validation passed.\")"
827
+ ]
828
+ },
829
+ {
830
+ "cell_type": "markdown",
831
+ "id": "98bc9657",
832
+ "metadata": {},
833
+ "source": [
834
+ "## 11. Upload the new Parquet into the new repository folder"
835
+ ]
836
+ },
837
+ {
838
+ "cell_type": "code",
839
+ "execution_count": null,
840
+ "id": "9b477941",
841
+ "metadata": {},
842
+ "outputs": [],
843
+ "source": [
844
+ "if not LOCAL_OUTPUT.exists() or LOCAL_OUTPUT.stat().st_size == 0:\n",
845
+ " raise RuntimeError(\"Output Parquet is missing or empty.\")\n",
846
+ "\n",
847
+ "if MAX_ROWS is not None:\n",
848
+ " raise RuntimeError(\"Partial run configured; upload cancelled.\")\n",
849
+ "\n",
850
+ "if ABORT_UPLOAD_IF_MISSING_RATINGS and validation[\"missing_rating\"]:\n",
851
+ " raise RuntimeError(\"Missing ratings detected; upload cancelled.\")\n",
852
+ "\n",
853
+ "# Ensure the new file is in a distinct folder; source captions.parquet is untouched.\n",
854
+ "print(\"Uploading:\", OUTPUT_PARQUET_REPO_PATH)\n",
855
+ "\n",
856
+ "api.upload_file(\n",
857
+ " path_or_fileobj=str(LOCAL_OUTPUT),\n",
858
+ " path_in_repo=OUTPUT_PARQUET_REPO_PATH,\n",
859
+ " repo_id=REPO_ID,\n",
860
+ " repo_type=REPO_TYPE,\n",
861
+ " commit_message=(\n",
862
+ " \"Add enriched Civitai captions Parquet with WD14 ratings \"\n",
863
+ " \"and Danbooru wiki definitions\"\n",
864
+ " ),\n",
865
+ ")\n",
866
+ "\n",
867
+ "print(\"\\\\nUPLOAD COMPLETE\")\n",
868
+ "print(\"New file:\")\n",
869
+ "print(\n",
870
+ " f\"https://huggingface.co/datasets/{REPO_ID}/blob/main/{OUTPUT_PARQUET_REPO_PATH}\"\n",
871
+ ")\n",
872
+ "print(\"Original source remains unchanged:\", SOURCE_PARQUET)\n",
873
+ "print(\"Rows:\", f\"{processed_rows:,}\")\n",
874
+ "print(\"Unique wiki definitions selected:\", f\"{len(used_definition_tags):,}\")"
875
+ ]
876
+ },
877
+ {
878
+ "cell_type": "markdown",
879
+ "id": "74843273",
880
+ "metadata": {},
881
+ "source": [
882
+ "## Notes\n",
883
+ "\n",
884
+ "- The source `captions.parquet` is not overwritten. The new file is uploaded to `enriched/captions.parquet`.\n",
885
+ "- The notebook uses the original row's `prompt` as the written response text, wrapped in `<response> ... </response>`.\n",
886
+ "- `thinking_response` uses the uploaded notebook's Danbooru wiki source (`lylogummy/danbooru_wikis_2026`) and its definition-cleaning logic. It prefers tags whose definitions have not yet been used, then reuses a matching tag only when necessary.\n",
887
+ "- If no tag in a row matches a wiki title, `thinking_response` will contain an empty `<thinking> </thinking>` wrapper.\n",
888
+ "- Existing ratings are preserved. WD14 inference is run only for rows without one of the four recognized rating tokens. Rows successfully classified also receive missing WD14 tags above the configured threshold.\n",
889
+ "- A model can only predict rating classes actually present in its `selected_tags.csv`. The notebook prints the available rating labels and maps WD14's `safe` label to `general` if present.\n",
890
+ "- The notebook explicitly requires ONNX Runtime's CUDA provider. Confirm the session reports `CUDAExecutionProvider` and Colab reports a T4 GPU before processing.\n",
891
+ "- Any image/shard failure is recorded in `processing_failures.json`. With the default upload gate, a missing rating blocks upload rather than silently creating a partial result."
892
+ ]
893
+ }
894
+ ],
895
+ "metadata": {
896
+ "colab": {
897
+ "name": "civitai_create_enriched_captions.ipynb",
898
+ "provenance": []
899
+ },
900
+ "kernelspec": {
901
+ "display_name": "Python 3",
902
+ "language": "python",
903
+ "name": "python3"
904
+ },
905
+ "language_info": {
906
+ "name": "python"
907
+ }
908
+ },
909
+ "nbformat": 4,
910
+ "nbformat_minor": 5
911
+ }