codeShare commited on
Commit
8ffd51e
·
verified ·
1 Parent(s): 2cfcd89

Upload Three_Source_Encrypted_Multimodal_Dataset_Builder_Randomized.ipynb

Browse files
qwen35_training/Three_Source_Encrypted_Multimodal_Dataset_Builder_Randomized.ipynb ADDED
@@ -0,0 +1,1373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "metadata": {},
7
+ "outputs": [],
8
+ "source": [
9
+ "# ============================================================\n",
10
+ "# THREE-SOURCE ENCRYPTED MULTIMODAL DATASET BUILDER\n",
11
+ "# Google Colab\n",
12
+ "#\n",
13
+ "# SOURCES\n",
14
+ "# 1) Civitai:\n",
15
+ "# codeShare/civitai-natural-language-prompts-and-images\n",
16
+ "# preproccessed/captions.parquet\n",
17
+ "# All rows; input = \"Describe the image using these tags: {tags}\"\n",
18
+ "# answer = prompt\n",
19
+ "#\n",
20
+ "# 2) Adcom:\n",
21
+ "# codeShare/adcom_captioned_ai_images\n",
22
+ "# captions.parquet\n",
23
+ "# Only author == \"Adcom\" (case-insensitive)\n",
24
+ "# Excludes prompt text containing the whole words \"remove\" or \"improve\"\n",
25
+ "# Same input/answer format as Civitai\n",
26
+ "#\n",
27
+ "# 3) Sankaku:\n",
28
+ "# codeShare/sankaku_captioned_images\n",
29
+ "# preprocessed/captions.parquet\n",
30
+ "# preprocessed/encryption.json\n",
31
+ "# Input = instruction\n",
32
+ "# Answer = prompt + \". \" + thinking_response + \". \" + written_response\n",
33
+ "# Repeated consecutive periods are reduced to one.\n",
34
+ "# Excludes rows where written_response contains the whole word \"user\" or\n",
35
+ "# \"summary\" AND both prompt and thinking_response are empty.\n",
36
+ "# Retains AES-GCM source image decryption.\n",
37
+ "#\n",
38
+ "# OUTPUT\n",
39
+ "# codeShare/kromoss-lora-exports/gemma4_arrow_encrypted_v1/\n",
40
+ "#\n",
41
+ "# Existing encrypted Arrow records are copied unchanged.\n",
42
+ "# New records are encrypted with the existing output encryption key.\n",
43
+ "# ============================================================\n",
44
+ "\n",
45
+ "!pip -q install -U datasets pyarrow cryptography pillow huggingface_hub pandas tqdm\n",
46
+ "\n",
47
+ "import os, io, gc, re, json, time, math, base64, random, secrets\n",
48
+ "import shutil, hashlib, tempfile, mimetypes\n",
49
+ "from pathlib import Path\n",
50
+ "\n",
51
+ "import pandas as pd\n",
52
+ "from PIL import Image, ImageOps\n",
53
+ "from datasets import Dataset, Features, Value, load_from_disk\n",
54
+ "from datasets.arrow_writer import ArrowWriter\n",
55
+ "from huggingface_hub import (\n",
56
+ " HfApi, hf_hub_download, snapshot_download,\n",
57
+ " CommitOperationAdd, CommitOperationDelete\n",
58
+ ")\n",
59
+ "from cryptography.hazmat.primitives.ciphers.aead import AESGCM\n",
60
+ "from cryptography.hazmat.primitives.kdf.scrypt import Scrypt\n",
61
+ "from tqdm.auto import tqdm\n",
62
+ "\n",
63
+ "\n",
64
+ "# ============================================================\n",
65
+ "# 1. CONFIGURATION\n",
66
+ "# ============================================================\n",
67
+ "\n",
68
+ "# Source repositories and exact Parquet paths.\n",
69
+ "CIVITAI_REPO = \"codeShare/civitai-natural-language-prompts-and-images\"\n",
70
+ "CIVITAI_PARQUET = \"preproccessed/captions.parquet\"\n",
71
+ "\n",
72
+ "ADCOM_REPO = \"codeShare/adcom_captioned_ai_images\"\n",
73
+ "ADCOM_PARQUET = \"captions.parquet\"\n",
74
+ "\n",
75
+ "SANKAKU_REPO = \"codeShare/sankaku_captioned_images\"\n",
76
+ "SANKAKU_PARQUET = \"preprocessed/captions.parquet\"\n",
77
+ "SANKAKU_ENCRYPTION_FILE = \"preprocessed/encryption.json\"\n",
78
+ "\n",
79
+ "# Destination (same destination as the uploaded notebook).\n",
80
+ "DEST_REPO = \"codeShare/kromoss-lora-exports\"\n",
81
+ "DEST_REPO_TYPE = \"model\"\n",
82
+ "DESTINATION_SUBFOLDER = \"gemma4_arrow_encrypted_v1\"\n",
83
+ "\n",
84
+ "# Output password:\n",
85
+ "# For an existing destination, this MUST match the password used to\n",
86
+ "# create that destination. The original notebook used \"blueberry\".\n",
87
+ "OUTPUT_PASSWORD = \"blueberry\"\n",
88
+ "\n",
89
+ "# Source Sankaku password is read from Colab Secrets: ENC_PWD.\n",
90
+ "# HF_TOKEN is also read from Colab Secrets.\n",
91
+ "\n",
92
+ "# 0 = process every selected record. Set a small number for a test run.\n",
93
+ "# MAX_RECORDS_PER_SOURCE applies independently to each source.\n",
94
+ "MAX_RECORDS_PER_SOURCE = 0\n",
95
+ "\n",
96
+ "# Image preprocessing.\n",
97
+ "MAX_IMAGE_DIMENSION = 1024\n",
98
+ "JPEG_QUALITY = 95\n",
99
+ "WEBP_QUALITY = 95\n",
100
+ "\n",
101
+ "# Arrow writing.\n",
102
+ "ARROW_MAX_SHARD_SIZE = \"512MB\"\n",
103
+ "ARROW_WRITER_BATCH_SIZE = 16\n",
104
+ "\n",
105
+ "# Verification.\n",
106
+ "VERIFY_SAMPLES = 30\n",
107
+ "RANDOM_SEED = 35667\n",
108
+ "\n",
109
+ "# Final row order is shuffled across ALL three sources (and any retained rows).\n",
110
+ "# Keep this seed to reproduce the same order, or change it for a new shuffle.\n",
111
+ "SHUFFLE_SEED = 20261116\n",
112
+ "\n",
113
+ "# Error handling.\n",
114
+ "STRICT_MODE = False\n",
115
+ "\n",
116
+ "# Set True to prevent any upload unless all three source indexes load.\n",
117
+ "REQUIRE_ALL_THREE_SOURCES = True\n",
118
+ "\n",
119
+ "# Local workspace.\n",
120
+ "WORK_DIR = Path(\"/content/three_source_gemma4_builder\")\n",
121
+ "REMOTE_DIR = WORK_DIR / \"existing\"\n",
122
+ "OUTPUT_DIR = WORK_DIR / \"combined\"\n",
123
+ "TEMP_ARROW = WORK_DIR / \"combined.arrow\"\n",
124
+ "\n",
125
+ "WORK_DIR.mkdir(parents=True, exist_ok=True)\n",
126
+ "REMOTE_DIR.mkdir(parents=True, exist_ok=True)\n",
127
+ "random.seed(RANDOM_SEED)\n",
128
+ "\n",
129
+ "# Source IDs are namespaced to avoid collisions between repositories.\n",
130
+ "SOURCE_PREFIXES = {\n",
131
+ " \"civitai\": \"civitai_nl_v1_\",\n",
132
+ " \"adcom\": \"adcom_captioned_v1_\",\n",
133
+ " \"sankaku\": \"sankaku_captioned_v1_\",\n",
134
+ "}\n",
135
+ "\n",
136
+ "FEATURES = Features({\n",
137
+ " \"sample_id\": Value(\"string\"),\n",
138
+ " \"image_enc\": Value(\"binary\"),\n",
139
+ " \"conversation_enc\": Value(\"binary\"),\n",
140
+ " \"width\": Value(\"int32\"),\n",
141
+ " \"height\": Value(\"int32\"),\n",
142
+ " \"image_format\": Value(\"string\"),\n",
143
+ "})\n",
144
+ "\n",
145
+ "\n",
146
+ "# ============================================================\n",
147
+ "# 2. HUGGING FACE AUTHENTICATION\n",
148
+ "# ============================================================\n",
149
+ "\n",
150
+ "from google.colab import userdata\n",
151
+ "\n",
152
+ "HF_TOKEN = userdata.get(\"HF_TOKEN\")\n",
153
+ "SOURCE_PASSWORD = userdata.get(\"ENC_PWD\")\n",
154
+ "\n",
155
+ "if not HF_TOKEN:\n",
156
+ " raise ValueError(\"HF_TOKEN is missing from Colab Secrets.\")\n",
157
+ "\n",
158
+ "if not SOURCE_PASSWORD:\n",
159
+ " raise ValueError(\"ENC_PWD is missing from Colab Secrets.\")\n",
160
+ "\n",
161
+ "if not OUTPUT_PASSWORD:\n",
162
+ " raise ValueError(\"OUTPUT_PASSWORD is empty.\")\n",
163
+ "\n",
164
+ "api = HfApi(token=HF_TOKEN)\n",
165
+ "print(\"Authenticated as:\", api.whoami()[\"name\"])\n",
166
+ "print(\"Destination:\", DEST_REPO, \"/\", DESTINATION_SUBFOLDER)\n",
167
+ "\n",
168
+ "\n",
169
+ "# ============================================================\n",
170
+ "# 3. GENERAL HELPERS\n",
171
+ "# ============================================================\n",
172
+ "\n",
173
+ "def to_text(value):\n",
174
+ " \"\"\"Convert nullable Parquet values to strings without rewriting text.\"\"\"\n",
175
+ " if value is None:\n",
176
+ " return \"\"\n",
177
+ " try:\n",
178
+ " if pd.isna(value):\n",
179
+ " return \"\"\n",
180
+ " except (TypeError, ValueError):\n",
181
+ " pass\n",
182
+ " return value if isinstance(value, str) else str(value)\n",
183
+ "\n",
184
+ "\n",
185
+ "def make_conversation(instruction, answer):\n",
186
+ " \"\"\"Build a two-message user/image -> assistant conversation.\"\"\"\n",
187
+ " instruction = to_text(instruction)\n",
188
+ " answer = to_text(answer)\n",
189
+ "\n",
190
+ " if not instruction.strip():\n",
191
+ " raise ValueError(\"Empty user instruction.\")\n",
192
+ " if not answer.strip():\n",
193
+ " raise ValueError(\"Empty assistant answer.\")\n",
194
+ "\n",
195
+ " conversation = {\n",
196
+ " \"messages\": [\n",
197
+ " {\n",
198
+ " \"role\": \"user\",\n",
199
+ " \"content\": [\n",
200
+ " {\"type\": \"text\", \"text\": instruction},\n",
201
+ " {\"type\": \"image\"}\n",
202
+ " ]\n",
203
+ " },\n",
204
+ " {\n",
205
+ " \"role\": \"assistant\",\n",
206
+ " \"content\": [{\"type\": \"text\", \"text\": answer}]\n",
207
+ " }\n",
208
+ " ]\n",
209
+ " }\n",
210
+ " return conversation, instruction, answer\n",
211
+ "\n",
212
+ "\n",
213
+ "def make_tags_instruction(tags):\n",
214
+ " # Keep the user's requested wording exact.\n",
215
+ " return \"Describe the image using these tags: \" + to_text(tags)\n",
216
+ "\n",
217
+ "\n",
218
+ "def contains_whole_word(text, words):\n",
219
+ " \"\"\"Case-insensitive whole-word match; avoids matching e.g. 'usernames'.\"\"\"\n",
220
+ " pattern = r\"\\b(?:\" + \"|\".join(re.escape(w) for w in words) + r\")\\b\"\n",
221
+ " return bool(re.search(pattern, to_text(text), flags=re.IGNORECASE))\n",
222
+ "\n",
223
+ "\n",
224
+ "def clean_sankaku_answer(prompt, thinking_response, written_response):\n",
225
+ " \"\"\"Apply requested concatenation and collapse repeated periods.\"\"\"\n",
226
+ " answer = (\n",
227
+ " to_text(prompt) + \". \"\n",
228
+ " + to_text(thinking_response) + \". \"\n",
229
+ " + to_text(written_response)\n",
230
+ " )\n",
231
+ " answer = re.sub(r\"\\.{2,}\", \".\", answer)\n",
232
+ " return answer.strip()\n",
233
+ "\n",
234
+ "\n",
235
+ "def safe_id(value):\n",
236
+ " value = str(value)\n",
237
+ " value = re.sub(r\"[^a-zA-Z0-9_-]\", \"_\", value)\n",
238
+ " return value[:120] or \"unknown\"\n",
239
+ "\n",
240
+ "\n",
241
+ "def derive_scrypt_key(password, salt, n, r, p, length=32):\n",
242
+ " return Scrypt(\n",
243
+ " salt=salt, length=length, n=int(n), r=int(r), p=int(p)\n",
244
+ " ).derive(password.encode(\"utf-8\"))\n",
245
+ "\n",
246
+ "\n",
247
+ "# ============================================================\n",
248
+ "# 4. IMAGE DECRYPTION / DECODING\n",
249
+ "# ============================================================\n",
250
+ "\n",
251
+ "SANKAKU_KEY = None\n",
252
+ "\n",
253
+ "def decrypt_sankaku_image(image_value, source_sample_id):\n",
254
+ " \"\"\"\n",
255
+ " Sankaku source convention from the original notebook:\n",
256
+ " base64(nonce[12] + ciphertext)\n",
257
+ " AAD:\n",
258
+ " gemma4-v1:{source_sample_id}:image\n",
259
+ " \"\"\"\n",
260
+ " if not isinstance(image_value, str):\n",
261
+ " raise TypeError(\"Sankaku encrypted image is not a base64 string.\")\n",
262
+ "\n",
263
+ " encrypted = base64.b64decode(image_value)\n",
264
+ " if len(encrypted) <= 12:\n",
265
+ " raise ValueError(\"Sankaku encrypted image is too short.\")\n",
266
+ "\n",
267
+ " nonce, ciphertext = encrypted[:12], encrypted[12:]\n",
268
+ " aad = f\"gemma4-v1:{source_sample_id}:image\".encode(\"utf-8\")\n",
269
+ " return AESGCM(SANKAKU_KEY).decrypt(nonce, ciphertext, aad)\n",
270
+ "\n",
271
+ "\n",
272
+ "def decode_plain_image(image_value):\n",
273
+ " \"\"\"\n",
274
+ " Civitai/Adcom indexed JSONL records contain base64 image data.\n",
275
+ " Accepts data:image/...;base64,... or raw base64.\n",
276
+ " \"\"\"\n",
277
+ " if not isinstance(image_value, str):\n",
278
+ " raise TypeError(\n",
279
+ " f\"Expected base64 image string, received {type(image_value).__name__}.\"\n",
280
+ " )\n",
281
+ "\n",
282
+ " value = image_value.strip()\n",
283
+ " if value.startswith(\"data:\") and \",\" in value:\n",
284
+ " value = value.split(\",\", 1)[1]\n",
285
+ "\n",
286
+ " value = re.sub(r\"\\s+\", \"\", value)\n",
287
+ " image_bytes = base64.b64decode(value, validate=False)\n",
288
+ "\n",
289
+ " if not image_bytes:\n",
290
+ " raise ValueError(\"Decoded image is empty.\")\n",
291
+ "\n",
292
+ " return image_bytes\n",
293
+ "\n",
294
+ "\n",
295
+ "def preprocess_image(image_bytes):\n",
296
+ " with Image.open(io.BytesIO(image_bytes)) as original:\n",
297
+ " original_format = original.format or \"JPEG\"\n",
298
+ " image = ImageOps.exif_transpose(original)\n",
299
+ "\n",
300
+ " if image.mode in (\"RGBA\", \"LA\") or \"transparency\" in image.info:\n",
301
+ " rgba = image.convert(\"RGBA\")\n",
302
+ " background = Image.new(\"RGBA\", rgba.size, (255, 255, 255, 255))\n",
303
+ " background.alpha_composite(rgba)\n",
304
+ " image = background.convert(\"RGB\")\n",
305
+ " rgba.close()\n",
306
+ " background.close()\n",
307
+ " else:\n",
308
+ " image = image.convert(\"RGB\")\n",
309
+ "\n",
310
+ " width, height = image.size\n",
311
+ " largest = max(width, height)\n",
312
+ "\n",
313
+ " if largest > MAX_IMAGE_DIMENSION:\n",
314
+ " scale = MAX_IMAGE_DIMENSION / largest\n",
315
+ " image = image.resize(\n",
316
+ " (max(1, round(width * scale)), max(1, round(height * scale))),\n",
317
+ " Image.Resampling.LANCZOS\n",
318
+ " )\n",
319
+ "\n",
320
+ " if original_format.upper() == \"PNG\":\n",
321
+ " fmt = \"PNG\"\n",
322
+ " options = {\"format\": \"PNG\", \"optimize\": True}\n",
323
+ " elif original_format.upper() == \"WEBP\":\n",
324
+ " fmt = \"WEBP\"\n",
325
+ " options = {\"format\": \"WEBP\", \"quality\": WEBP_QUALITY, \"method\": 6}\n",
326
+ " else:\n",
327
+ " fmt = \"JPEG\"\n",
328
+ " options = {\n",
329
+ " \"format\": \"JPEG\", \"quality\": JPEG_QUALITY,\n",
330
+ " \"optimize\": True, \"subsampling\": 0\n",
331
+ " }\n",
332
+ "\n",
333
+ " output = io.BytesIO()\n",
334
+ " image.save(output, **options)\n",
335
+ " result = {\n",
336
+ " \"bytes\": output.getvalue(),\n",
337
+ " \"width\": image.width,\n",
338
+ " \"height\": image.height,\n",
339
+ " \"format\": fmt\n",
340
+ " }\n",
341
+ " image.close()\n",
342
+ " return result\n",
343
+ "\n",
344
+ "\n",
345
+ "# ============================================================\n",
346
+ "# 5. OUTPUT ENCRYPTION FUNCTIONS\n",
347
+ "# ============================================================\n",
348
+ "\n",
349
+ "OUTPUT_KEY = None\n",
350
+ "\n",
351
+ "def encrypt_payload(plaintext, sample_id, field_name):\n",
352
+ " nonce = secrets.token_bytes(12)\n",
353
+ " aad = f\"gemma4-v1:{sample_id}:{field_name}\".encode(\"utf-8\")\n",
354
+ " ciphertext = AESGCM(OUTPUT_KEY).encrypt(nonce, plaintext, aad)\n",
355
+ " return nonce + ciphertext\n",
356
+ "\n",
357
+ "\n",
358
+ "def decrypt_payload(encrypted_payload, sample_id, field_name):\n",
359
+ " nonce = encrypted_payload[:12]\n",
360
+ " ciphertext = encrypted_payload[12:]\n",
361
+ " aad = f\"gemma4-v1:{sample_id}:{field_name}\".encode(\"utf-8\")\n",
362
+ " return AESGCM(OUTPUT_KEY).decrypt(nonce, ciphertext, aad)\n",
363
+ "\n",
364
+ "\n",
365
+ "# ============================================================\n",
366
+ "# 6. LOAD / PREPARE DESTINATION\n",
367
+ "# ============================================================\n",
368
+ "\n",
369
+ "destination_prefix = DESTINATION_SUBFOLDER.rstrip(\"/\") + \"/\"\n",
370
+ "remote_files = api.list_repo_files(\n",
371
+ " repo_id=DEST_REPO, repo_type=DEST_REPO_TYPE\n",
372
+ ")\n",
373
+ "existing_remote_files = [\n",
374
+ " f for f in remote_files if f.startswith(destination_prefix)\n",
375
+ "]\n",
376
+ "\n",
377
+ "manifest_path_name = destination_prefix + \"encryption_manifest.json\"\n",
378
+ "dataset_info_name = destination_prefix + \"dataset_info.json\"\n",
379
+ "state_name = destination_prefix + \"state.json\"\n",
380
+ "existing_arrow_files = [f for f in existing_remote_files if f.endswith(\".arrow\")]\n",
381
+ "\n",
382
+ "EXISTING_DATASET_FOUND = (\n",
383
+ " manifest_path_name in remote_files\n",
384
+ " and dataset_info_name in remote_files\n",
385
+ " and state_name in remote_files\n",
386
+ " and bool(existing_arrow_files)\n",
387
+ ")\n",
388
+ "\n",
389
+ "if existing_remote_files and not EXISTING_DATASET_FOUND:\n",
390
+ " raise RuntimeError(\n",
391
+ " \"Destination folder exists but is not a complete encrypted Arrow dataset. \"\n",
392
+ " \"Stopping to protect its contents.\"\n",
393
+ " )\n",
394
+ "\n",
395
+ "existing_dataset = None\n",
396
+ "existing_count = 0\n",
397
+ "manifest = None\n",
398
+ "\n",
399
+ "if EXISTING_DATASET_FOUND:\n",
400
+ " print(\"\\nDownloading existing encrypted dataset...\")\n",
401
+ " snapshot_download(\n",
402
+ " repo_id=DEST_REPO,\n",
403
+ " repo_type=DEST_REPO_TYPE,\n",
404
+ " token=HF_TOKEN,\n",
405
+ " local_dir=str(REMOTE_DIR),\n",
406
+ " allow_patterns=[f\"{DESTINATION_SUBFOLDER}/**\"]\n",
407
+ " )\n",
408
+ "\n",
409
+ " existing_dir = REMOTE_DIR / DESTINATION_SUBFOLDER\n",
410
+ " with open(existing_dir / \"encryption_manifest.json\", \"r\", encoding=\"utf-8\") as f:\n",
411
+ " manifest = json.load(f)\n",
412
+ "\n",
413
+ " existing_dataset = load_from_disk(str(existing_dir))\n",
414
+ " if not isinstance(existing_dataset, Dataset):\n",
415
+ " raise RuntimeError(\"Expected a Hugging Face Dataset, not DatasetDict.\")\n",
416
+ "\n",
417
+ " existing_count = len(existing_dataset)\n",
418
+ " if set(existing_dataset.column_names) != set(FEATURES):\n",
419
+ " raise RuntimeError(\"Existing Arrow schema differs from expected schema.\")\n",
420
+ "\n",
421
+ " encryption_config = manifest[\"encryption\"]\n",
422
+ " if encryption_config.get(\"cipher\") != \"AES-256-GCM\":\n",
423
+ " raise RuntimeError(\"Existing output cipher is not AES-256-GCM.\")\n",
424
+ " if encryption_config.get(\"kdf\") != \"scrypt\":\n",
425
+ " raise RuntimeError(\"Existing output KDF is not scrypt.\")\n",
426
+ " if int(encryption_config.get(\"key_length_bytes\", 32)) != 32:\n",
427
+ " raise RuntimeError(\"Unexpected output key length.\")\n",
428
+ "\n",
429
+ " output_salt = base64.b64decode(encryption_config[\"kdf_salt_base64\"])\n",
430
+ " output_n = int(encryption_config[\"scrypt_n\"])\n",
431
+ " output_r = int(encryption_config[\"scrypt_r\"])\n",
432
+ " output_p = int(encryption_config[\"scrypt_p\"])\n",
433
+ "\n",
434
+ " OUTPUT_KEY = derive_scrypt_key(\n",
435
+ " OUTPUT_PASSWORD, output_salt, output_n, output_r, output_p\n",
436
+ " )\n",
437
+ "\n",
438
+ " # Verify that the supplied output password matches existing records.\n",
439
+ " if existing_count:\n",
440
+ " test_row = existing_dataset[0]\n",
441
+ " test_conv = decrypt_payload(\n",
442
+ " test_row[\"conversation_enc\"], test_row[\"sample_id\"], \"conversation\"\n",
443
+ " )\n",
444
+ " json.loads(test_conv.decode(\"utf-8\"))\n",
445
+ " print(\"Existing output password verification: PASS\")\n",
446
+ "\n",
447
+ "else:\n",
448
+ " print(\"\\nCreating a new encrypted destination...\")\n",
449
+ " output_salt = secrets.token_bytes(16)\n",
450
+ " output_n, output_r, output_p = 2**14, 8, 1\n",
451
+ "\n",
452
+ " encryption_config = {\n",
453
+ " \"cipher\": \"AES-256-GCM\",\n",
454
+ " \"nonce_bytes\": 12,\n",
455
+ " \"kdf\": \"scrypt\",\n",
456
+ " \"kdf_salt_base64\": base64.b64encode(output_salt).decode(\"ascii\"),\n",
457
+ " \"scrypt_n\": output_n,\n",
458
+ " \"scrypt_r\": output_r,\n",
459
+ " \"scrypt_p\": output_p,\n",
460
+ " \"key_length_bytes\": 32,\n",
461
+ " \"aad_format\": \"gemma4-v1:{sample_id}:{field_name}\",\n",
462
+ " \"encrypted_fields\": [\"image_enc\", \"conversation_enc\"]\n",
463
+ " }\n",
464
+ "\n",
465
+ " manifest = {\n",
466
+ " \"dataset_name\": \"three_source_encrypted_multimodal\",\n",
467
+ " \"dataset_version\": 1,\n",
468
+ " \"serialization\": \"Hugging Face Datasets / Apache Arrow\",\n",
469
+ " \"sample_count\": 0,\n",
470
+ " \"image_preprocessing\": {\n",
471
+ " \"max_dimension\": MAX_IMAGE_DIMENSION,\n",
472
+ " \"orientation\": \"EXIF corrected\",\n",
473
+ " \"color_space\": \"RGB\",\n",
474
+ " \"resampling\": \"LANCZOS\"\n",
475
+ " },\n",
476
+ " \"text_preprocessing\": {\n",
477
+ " \"applied\": False,\n",
478
+ " \"description\": \"Source instruction and answer text preserved.\"\n",
479
+ " },\n",
480
+ " \"encryption\": encryption_config,\n",
481
+ " \"arrow_schema\": {\n",
482
+ " \"sample_id\": \"string\",\n",
483
+ " \"image_enc\": \"binary\",\n",
484
+ " \"conversation_enc\": \"binary\",\n",
485
+ " \"width\": \"int32\",\n",
486
+ " \"height\": \"int32\",\n",
487
+ " \"image_format\": \"string\"\n",
488
+ " },\n",
489
+ " \"conversion_statistics\": {\"processed\": 0, \"skipped\": 0},\n",
490
+ " \"source_repositories\": [],\n",
491
+ " \"created_unix\": time.time()\n",
492
+ " }\n",
493
+ "\n",
494
+ " OUTPUT_KEY = derive_scrypt_key(\n",
495
+ " OUTPUT_PASSWORD, output_salt, output_n, output_r, output_p\n",
496
+ " )\n",
497
+ "\n",
498
+ "print(\"Output AES-256-GCM key derived.\")\n",
499
+ "\n",
500
+ "\n",
501
+ "# ============================================================\n",
502
+ "# 7. PREVENT DUPLICATE SOURCE APPENDS\n",
503
+ "# ============================================================\n",
504
+ "\n",
505
+ "existing_sample_ids = set()\n",
506
+ "if existing_dataset is not None:\n",
507
+ " existing_sample_ids = set(existing_dataset[\"sample_id\"])\n",
508
+ "\n",
509
+ "for source_name, prefix in SOURCE_PREFIXES.items():\n",
510
+ " found = [sid for sid in existing_sample_ids if str(sid).startswith(prefix)]\n",
511
+ " if found:\n",
512
+ " raise RuntimeError(\n",
513
+ " f\"Destination already contains {source_name} records \"\n",
514
+ " f\"({len(found):,} IDs; example {found[0]}). \"\n",
515
+ " \"Append cancelled to prevent duplicates. If you intend to rebuild, \"\n",
516
+ " \"use a new DESTINATION_SUBFOLDER or explicitly remove the old source \"\n",
517
+ " \"records with a separate migration.\"\n",
518
+ " )\n",
519
+ "\n",
520
+ "\n",
521
+ "# ============================================================\n",
522
+ "# 8. LOAD INDEXES FOR CIVITAI AND ADCOM\n",
523
+ "# ============================================================\n",
524
+ "\n",
525
+ "def load_index(repo_id, parquet_file, required_columns, source_label):\n",
526
+ " print(f\"\\nLoading {source_label} index: {repo_id}/{parquet_file}\")\n",
527
+ " local_path = hf_hub_download(\n",
528
+ " repo_id=repo_id,\n",
529
+ " filename=parquet_file,\n",
530
+ " repo_type=\"dataset\",\n",
531
+ " token=HF_TOKEN\n",
532
+ " )\n",
533
+ " frame = pd.read_parquet(local_path)\n",
534
+ "\n",
535
+ " missing = set(required_columns) - set(frame.columns)\n",
536
+ " if missing:\n",
537
+ " raise RuntimeError(\n",
538
+ " f\"{source_label} index missing columns: {sorted(missing)}\"\n",
539
+ " )\n",
540
+ "\n",
541
+ " if frame[\"idx\"].isna().any():\n",
542
+ " raise RuntimeError(f\"{source_label}: null idx values found.\")\n",
543
+ " if frame[\"json_file\"].isna().any():\n",
544
+ " raise RuntimeError(f\"{source_label}: null json_file values found.\")\n",
545
+ " if frame[\"byte_offset\"].isna().any() or frame[\"byte_length\"].isna().any():\n",
546
+ " raise RuntimeError(f\"{source_label}: null byte pointers found.\")\n",
547
+ "\n",
548
+ " frame = frame.copy()\n",
549
+ " frame[\"idx\"] = frame[\"idx\"].astype(str)\n",
550
+ " frame[\"json_file\"] = frame[\"json_file\"].astype(str).str.strip()\n",
551
+ "\n",
552
+ " # idx is expected to be unique within each source.\n",
553
+ " if frame[\"idx\"].duplicated().any():\n",
554
+ " count = int(frame[\"idx\"].duplicated().sum())\n",
555
+ " raise RuntimeError(f\"{source_label}: {count} duplicate idx values.\")\n",
556
+ "\n",
557
+ " return frame\n",
558
+ "\n",
559
+ "\n",
560
+ "plain_required = {\"idx\", \"prompt\", \"tags\", \"json_file\", \"byte_offset\", \"byte_length\"}\n",
561
+ "\n",
562
+ "civitai_df = load_index(\n",
563
+ " CIVITAI_REPO, CIVITAI_PARQUET, plain_required, \"Civitai\"\n",
564
+ ")\n",
565
+ "\n",
566
+ "adcom_df = load_index(\n",
567
+ " ADCOM_REPO, ADCOM_PARQUET, plain_required | {\"author\"}, \"Adcom\"\n",
568
+ ")\n",
569
+ "\n",
570
+ "# The Civitai repository may include several author classes; the request\n",
571
+ "# specifies all rows from this source, so no author filter is applied.\n",
572
+ "# Adcom source is explicitly restricted to author == Adcom.\n",
573
+ "adcom_df = adcom_df[\n",
574
+ " adcom_df[\"author\"].fillna(\"\").astype(str).str.casefold() == \"adcom\"\n",
575
+ "].copy()\n",
576
+ "adcom_author_rows = len(adcom_df)\n",
577
+ "\n",
578
+ "# Exclude Adcom records whose prompt contains either whole word,\n",
579
+ "# case-insensitively. Match whole words, not substrings.\n",
580
+ "adcom_blocked_mask = adcom_df[\"prompt\"].fillna(\"\").astype(str).map(\n",
581
+ " lambda value: contains_whole_word(value, [\"remove\", \"improve\"])\n",
582
+ ")\n",
583
+ "adcom_filtered_out = int(adcom_blocked_mask.sum())\n",
584
+ "adcom_df = adcom_df.loc[~adcom_blocked_mask].copy()\n",
585
+ "\n",
586
+ "print(\"\\nCivitai indexed rows:\", f\"{len(civitai_df):,}\")\n",
587
+ "print(\"Adcom rows with author=Adcom before prompt filter:\", f\"{adcom_author_rows:,}\")\n",
588
+ "print(\"Adcom rows excluded (prompt contains 'remove' or 'improve'):\", f\"{adcom_filtered_out:,}\")\n",
589
+ "print(\"Adcom eligible rows:\", f\"{len(adcom_df):,}\")\n",
590
+ "\n",
591
+ "if MAX_RECORDS_PER_SOURCE > 0:\n",
592
+ " civitai_df = civitai_df.head(MAX_RECORDS_PER_SOURCE).copy()\n",
593
+ " adcom_df = adcom_df.head(MAX_RECORDS_PER_SOURCE).copy()\n",
594
+ "\n",
595
+ "\n",
596
+ "# ============================================================\n",
597
+ "# 9. LOAD SANKAKU INDEX AND SOURCE DECRYPTION KEY\n",
598
+ "# ============================================================\n",
599
+ "\n",
600
+ "print(\"\\nLoading Sankaku encryption configuration...\")\n",
601
+ "sankaku_enc_path = hf_hub_download(\n",
602
+ " repo_id=SANKAKU_REPO,\n",
603
+ " filename=SANKAKU_ENCRYPTION_FILE,\n",
604
+ " repo_type=\"dataset\",\n",
605
+ " token=HF_TOKEN\n",
606
+ ")\n",
607
+ "\n",
608
+ "with open(sankaku_enc_path, \"r\", encoding=\"utf-8\") as f:\n",
609
+ " sankaku_encryption = json.load(f)\n",
610
+ "\n",
611
+ "if sankaku_encryption.get(\"cipher\") != \"AES-256-GCM\":\n",
612
+ " raise RuntimeError(\"Unsupported Sankaku source cipher.\")\n",
613
+ "if \"scrypt\" not in str(sankaku_encryption.get(\"kdf\", \"scrypt\")).lower():\n",
614
+ " raise RuntimeError(\"Unsupported Sankaku source KDF.\")\n",
615
+ "\n",
616
+ "SANKAKU_KEY = derive_scrypt_key(\n",
617
+ " SOURCE_PASSWORD,\n",
618
+ " base64.b64decode(sankaku_encryption[\"kdf_salt_base64\"]),\n",
619
+ " int(sankaku_encryption[\"scrypt_n\"]),\n",
620
+ " int(sankaku_encryption[\"scrypt_r\"]),\n",
621
+ " int(sankaku_encryption[\"scrypt_p\"]),\n",
622
+ " int(sankaku_encryption.get(\"key_length_bytes\", 32))\n",
623
+ ")\n",
624
+ "\n",
625
+ "sankaku_required = {\n",
626
+ " \"idx\", \"prompt\", \"instruction\", \"thinking_response\", \"written_response\",\n",
627
+ " \"json_file\", \"byte_offset\", \"byte_length\"\n",
628
+ "}\n",
629
+ "sankaku_df = load_index(\n",
630
+ " SANKAKU_REPO, SANKAKU_PARQUET, sankaku_required, \"Sankaku\"\n",
631
+ ")\n",
632
+ "sankaku_total_indexed = len(sankaku_df)\n",
633
+ "\n",
634
+ "# Ignore only rows that satisfy BOTH conditions:\n",
635
+ "# 1) written_response contains the whole word \"user\" or \"summary\"\n",
636
+ "# 2) prompt AND thinking_response are empty/whitespace-only.\n",
637
+ "sankaku_written_has_blocked_word = sankaku_df[\"written_response\"].fillna(\"\").astype(str).map(\n",
638
+ " lambda value: contains_whole_word(value, [\"user\", \"summary\"])\n",
639
+ ")\n",
640
+ "sankaku_prompt_empty = sankaku_df[\"prompt\"].fillna(\"\").astype(str).str.strip().eq(\"\")\n",
641
+ "sankaku_thinking_empty = sankaku_df[\"thinking_response\"].fillna(\"\").astype(str).str.strip().eq(\"\")\n",
642
+ "sankaku_exclude_mask = (\n",
643
+ " sankaku_written_has_blocked_word\n",
644
+ " & sankaku_prompt_empty\n",
645
+ " & sankaku_thinking_empty\n",
646
+ ")\n",
647
+ "sankaku_filtered_out = int(sankaku_exclude_mask.sum())\n",
648
+ "sankaku_df = sankaku_df.loc[~sankaku_exclude_mask].copy()\n",
649
+ "\n",
650
+ "print(\"Sankaku indexed rows:\", f\"{sankaku_total_indexed:,}\")\n",
651
+ "print(\"Sankaku rows excluded by the two-part rule:\", f\"{sankaku_filtered_out:,}\")\n",
652
+ "print(\"Sankaku eligible rows:\", f\"{len(sankaku_df):,}\")\n",
653
+ "\n",
654
+ "if MAX_RECORDS_PER_SOURCE > 0:\n",
655
+ " sankaku_df = sankaku_df.head(MAX_RECORDS_PER_SOURCE).copy()\n",
656
+ "\n",
657
+ "\n",
658
+ "# ============================================================\n",
659
+ "# 10. INCREMENTAL ARROW WRITER; COPY EXISTING ROWS UNCHANGED\n",
660
+ "# ============================================================\n",
661
+ "\n",
662
+ "if TEMP_ARROW.exists():\n",
663
+ " TEMP_ARROW.unlink()\n",
664
+ "\n",
665
+ "writer = ArrowWriter(\n",
666
+ " path=str(TEMP_ARROW),\n",
667
+ " features=FEATURES,\n",
668
+ " writer_batch_size=ARROW_WRITER_BATCH_SIZE\n",
669
+ ")\n",
670
+ "\n",
671
+ "if existing_dataset is not None:\n",
672
+ " print(\"\\nCopying existing encrypted rows without decrypting/re-encrypting...\")\n",
673
+ " total_batches = math.ceil(existing_count / ARROW_WRITER_BATCH_SIZE)\n",
674
+ " for batch in tqdm(\n",
675
+ " existing_dataset.iter(batch_size=ARROW_WRITER_BATCH_SIZE),\n",
676
+ " total=total_batches,\n",
677
+ " desc=\"Copy existing\"\n",
678
+ " ):\n",
679
+ " writer.write_batch(batch)\n",
680
+ " print(\"Copied:\", f\"{existing_count:,}\")\n",
681
+ "\n",
682
+ "\n",
683
+ "# ============================================================\n",
684
+ "# 11. SHARED RECORD PROCESSOR\n",
685
+ "# ============================================================\n",
686
+ "\n",
687
+ "stats = {\n",
688
+ " \"processed_by_source\": {\"civitai\": 0, \"adcom\": 0, \"sankaku\": 0},\n",
689
+ " \"skipped_by_source\": {\"civitai\": 0, \"adcom\": 0, \"sankaku\": 0},\n",
690
+ " \"filtered_out_before_processing\": {\n",
691
+ " \"adcom_prompt_remove_or_improve\": adcom_filtered_out,\n",
692
+ " \"sankaku_written_user_or_summary_with_empty_prompt_and_thinking\": sankaku_filtered_out\n",
693
+ " },\n",
694
+ " \"errors\": []\n",
695
+ "}\n",
696
+ "\n",
697
+ "verification_samples = []\n",
698
+ "verification_seen = 0\n",
699
+ "\n",
700
+ "\n",
701
+ "def retain_verification(item):\n",
702
+ " global verification_seen\n",
703
+ " verification_seen += 1\n",
704
+ " if len(verification_samples) < VERIFY_SAMPLES:\n",
705
+ " verification_samples.append(item)\n",
706
+ " else:\n",
707
+ " replacement = random.randrange(verification_seen)\n",
708
+ " if replacement < VERIFY_SAMPLES:\n",
709
+ " verification_samples[replacement] = item\n",
710
+ "\n",
711
+ "\n",
712
+ "def write_new_record(source_name, idx, row_number, image_bytes, instruction, answer):\n",
713
+ " \"\"\"Preprocess, encrypt and append one image/conversation record.\"\"\"\n",
714
+ " sample_id = (\n",
715
+ " SOURCE_PREFIXES[source_name]\n",
716
+ " + safe_id(idx)\n",
717
+ " + f\"_r{row_number:010d}\"\n",
718
+ " )\n",
719
+ "\n",
720
+ " conversation, expected_input, expected_output = make_conversation(\n",
721
+ " instruction, answer\n",
722
+ " )\n",
723
+ "\n",
724
+ " conversation_bytes = json.dumps(\n",
725
+ " conversation, ensure_ascii=False, separators=(\",\", \":\")\n",
726
+ " ).encode(\"utf-8\")\n",
727
+ "\n",
728
+ " processed = preprocess_image(image_bytes)\n",
729
+ "\n",
730
+ " encrypted_image = encrypt_payload(processed[\"bytes\"], sample_id, \"image\")\n",
731
+ " encrypted_conversation = encrypt_payload(\n",
732
+ " conversation_bytes, sample_id, \"conversation\"\n",
733
+ " )\n",
734
+ "\n",
735
+ " dataset_index = existing_count + sum(stats[\"processed_by_source\"].values())\n",
736
+ "\n",
737
+ " writer.write({\n",
738
+ " \"sample_id\": sample_id,\n",
739
+ " \"image_enc\": encrypted_image,\n",
740
+ " \"conversation_enc\": encrypted_conversation,\n",
741
+ " \"width\": processed[\"width\"],\n",
742
+ " \"height\": processed[\"height\"],\n",
743
+ " \"image_format\": processed[\"format\"]\n",
744
+ " })\n",
745
+ "\n",
746
+ " retain_verification({\n",
747
+ " \"dataset_index\": dataset_index,\n",
748
+ " \"sample_id\": sample_id,\n",
749
+ " \"expected_input\": expected_input,\n",
750
+ " \"expected_output\": expected_output,\n",
751
+ " \"width\": processed[\"width\"],\n",
752
+ " \"height\": processed[\"height\"],\n",
753
+ " \"image_format\": processed[\"format\"],\n",
754
+ " \"source\": source_name\n",
755
+ " })\n",
756
+ "\n",
757
+ " del conversation_bytes, encrypted_image, encrypted_conversation, processed\n",
758
+ "\n",
759
+ "\n",
760
+ "def process_plain_source(source_name, repo_id, frame):\n",
761
+ " \"\"\"\n",
762
+ " Process Civitai or Adcom indexed JSONL shards.\n",
763
+ " Expected JSONL image field: image (base64 or data URI).\n",
764
+ " \"\"\"\n",
765
+ " grouped = frame.groupby(\"json_file\", sort=False)\n",
766
+ " print(f\"\\n{'='*70}\\nPROCESSING {source_name.upper()}\\n{'='*70}\")\n",
767
+ "\n",
768
+ " for shard_name, shard_rows in tqdm(\n",
769
+ " grouped, total=frame[\"json_file\"].nunique(),\n",
770
+ " desc=f\"{source_name} shards\"\n",
771
+ " ):\n",
772
+ " shard_path = hf_hub_download(\n",
773
+ " repo_id=repo_id,\n",
774
+ " filename=shard_name,\n",
775
+ " repo_type=\"dataset\",\n",
776
+ " token=HF_TOKEN\n",
777
+ " )\n",
778
+ "\n",
779
+ " with open(shard_path, \"rb\") as shard_file:\n",
780
+ " for record in tqdm(\n",
781
+ " shard_rows.itertuples(index=False),\n",
782
+ " total=len(shard_rows),\n",
783
+ " desc=f\"{source_name} records\",\n",
784
+ " leave=False\n",
785
+ " ):\n",
786
+ " idx = str(record.idx)\n",
787
+ " row_number = int(record.row_number)\n",
788
+ "\n",
789
+ " try:\n",
790
+ " offset = int(record.byte_offset)\n",
791
+ " length = int(record.byte_length)\n",
792
+ " if offset < 0 or length <= 0:\n",
793
+ " raise ValueError(\"Invalid JSONL byte pointer.\")\n",
794
+ "\n",
795
+ " shard_file.seek(offset)\n",
796
+ " raw = shard_file.read(length)\n",
797
+ " if len(raw) != length:\n",
798
+ " raise IOError(\n",
799
+ " f\"Short read: expected {length}, got {len(raw)}\"\n",
800
+ " )\n",
801
+ "\n",
802
+ " image_record = json.loads(raw.decode(\"utf-8\"))\n",
803
+ "\n",
804
+ " if \"idx\" in image_record and str(image_record[\"idx\"]) != idx:\n",
805
+ " raise ValueError(\n",
806
+ " f\"idx mismatch: Parquet={idx}, JSONL={image_record['idx']}\"\n",
807
+ " )\n",
808
+ "\n",
809
+ " # The dataset card documents the JSONL payload as `image`.\n",
810
+ " if \"image\" not in image_record:\n",
811
+ " raise KeyError(\n",
812
+ " \"JSONL record has no 'image' field. \"\n",
813
+ " f\"Available keys: {list(image_record.keys())}\"\n",
814
+ " )\n",
815
+ "\n",
816
+ " image_bytes = decode_plain_image(image_record[\"image\"])\n",
817
+ "\n",
818
+ " # User-specified mapping for both sources:\n",
819
+ " # prompt = \"Describe the image using these tags: {tags}\"\n",
820
+ " # expected answer = Parquet prompt.\n",
821
+ " tags = to_text(record.tags)\n",
822
+ " expected = to_text(record.prompt)\n",
823
+ " instruction = make_tags_instruction(tags)\n",
824
+ "\n",
825
+ " write_new_record(\n",
826
+ " source_name, idx, row_number,\n",
827
+ " image_bytes, instruction, expected\n",
828
+ " )\n",
829
+ "\n",
830
+ " stats[\"processed_by_source\"][source_name] += 1\n",
831
+ " del image_bytes, image_record\n",
832
+ "\n",
833
+ " except Exception as error:\n",
834
+ " stats[\"skipped_by_source\"][source_name] += 1\n",
835
+ " error_item = {\n",
836
+ " \"source\": source_name,\n",
837
+ " \"idx\": idx,\n",
838
+ " \"json_file\": shard_name,\n",
839
+ " \"byte_offset\": int(record.byte_offset),\n",
840
+ " \"byte_length\": int(record.byte_length),\n",
841
+ " \"error\": repr(error)\n",
842
+ " }\n",
843
+ " stats[\"errors\"].append(error_item)\n",
844
+ " print(f\"\\nSKIPPED {source_name} idx={idx}: {error}\")\n",
845
+ " if STRICT_MODE:\n",
846
+ " raise\n",
847
+ "\n",
848
+ " processed_total = sum(stats[\"processed_by_source\"].values())\n",
849
+ " if processed_total and processed_total % 250 == 0:\n",
850
+ " gc.collect()\n",
851
+ "\n",
852
+ " del shard_path, shard_rows\n",
853
+ " gc.collect()\n",
854
+ "\n",
855
+ "\n",
856
+ "def process_sankaku_source(frame):\n",
857
+ " \"\"\"Retain original Sankaku image decryption and conversation mapping.\"\"\"\n",
858
+ " grouped = frame.groupby(\"json_file\", sort=False)\n",
859
+ " print(f\"\\n{'='*70}\\nPROCESSING SANKAKU\\n{'='*70}\")\n",
860
+ "\n",
861
+ " for shard_name, shard_rows in tqdm(\n",
862
+ " grouped, total=frame[\"json_file\"].nunique(),\n",
863
+ " desc=\"Sankaku shards\"\n",
864
+ " ):\n",
865
+ " shard_path = hf_hub_download(\n",
866
+ " repo_id=SANKAKU_REPO,\n",
867
+ " filename=shard_name,\n",
868
+ " repo_type=\"dataset\",\n",
869
+ " token=HF_TOKEN\n",
870
+ " )\n",
871
+ "\n",
872
+ " with open(shard_path, \"rb\") as shard_file:\n",
873
+ " for record in tqdm(\n",
874
+ " shard_rows.itertuples(index=False),\n",
875
+ " total=len(shard_rows),\n",
876
+ " desc=\"Sankaku records\",\n",
877
+ " leave=False\n",
878
+ " ):\n",
879
+ " idx = str(record.idx)\n",
880
+ " row_number = int(record.row_number)\n",
881
+ "\n",
882
+ " try:\n",
883
+ " offset = int(record.byte_offset)\n",
884
+ " length = int(record.byte_length)\n",
885
+ " if offset < 0 or length <= 0:\n",
886
+ " raise ValueError(\"Invalid JSONL byte pointer.\")\n",
887
+ "\n",
888
+ " shard_file.seek(offset)\n",
889
+ " raw = shard_file.read(length)\n",
890
+ " if len(raw) != length:\n",
891
+ " raise IOError(\"Incomplete Sankaku JSONL record.\")\n",
892
+ "\n",
893
+ " image_record = json.loads(raw.decode(\"utf-8\"))\n",
894
+ "\n",
895
+ " if \"idx\" in image_record and str(image_record[\"idx\"]) != idx:\n",
896
+ " raise ValueError(\n",
897
+ " f\"idx mismatch: Parquet={idx}, JSONL={image_record['idx']}\"\n",
898
+ " )\n",
899
+ "\n",
900
+ " source_sample_id = str(image_record.get(\"sample_id\", idx))\n",
901
+ " image_bytes = decrypt_sankaku_image(\n",
902
+ " image_record.get(\"image\"), source_sample_id\n",
903
+ " )\n",
904
+ "\n",
905
+ " instruction = to_text(record.instruction)\n",
906
+ " answer = clean_sankaku_answer(\n",
907
+ " record.prompt,\n",
908
+ " record.thinking_response,\n",
909
+ " record.written_response\n",
910
+ " )\n",
911
+ "\n",
912
+ " write_new_record(\n",
913
+ " \"sankaku\", idx, row_number,\n",
914
+ " image_bytes, instruction, answer\n",
915
+ " )\n",
916
+ "\n",
917
+ " stats[\"processed_by_source\"][\"sankaku\"] += 1\n",
918
+ " del image_bytes, image_record\n",
919
+ "\n",
920
+ " except Exception as error:\n",
921
+ " stats[\"skipped_by_source\"][\"sankaku\"] += 1\n",
922
+ " error_item = {\n",
923
+ " \"source\": \"sankaku\",\n",
924
+ " \"idx\": idx,\n",
925
+ " \"json_file\": shard_name,\n",
926
+ " \"byte_offset\": int(record.byte_offset),\n",
927
+ " \"byte_length\": int(record.byte_length),\n",
928
+ " \"error\": repr(error)\n",
929
+ " }\n",
930
+ " stats[\"errors\"].append(error_item)\n",
931
+ " print(f\"\\nSKIPPED Sankaku idx={idx}: {error}\")\n",
932
+ " if STRICT_MODE:\n",
933
+ " raise\n",
934
+ "\n",
935
+ " processed_total = sum(stats[\"processed_by_source\"].values())\n",
936
+ " if processed_total and processed_total % 250 == 0:\n",
937
+ " gc.collect()\n",
938
+ "\n",
939
+ " del shard_path, shard_rows\n",
940
+ " gc.collect()\n",
941
+ "\n",
942
+ "\n",
943
+ "# Add stable row numbers after filtering/truncation.\n",
944
+ "for frame in (civitai_df, adcom_df, sankaku_df):\n",
945
+ " frame.reset_index(drop=True, inplace=True)\n",
946
+ " frame[\"row_number\"] = range(len(frame))\n",
947
+ "\n",
948
+ "\n",
949
+ "# ============================================================\n",
950
+ "# 12. PROCESS ALL THREE SOURCES\n",
951
+ "# ============================================================\n",
952
+ "\n",
953
+ "process_plain_source(\"civitai\", CIVITAI_REPO, civitai_df)\n",
954
+ "del civitai_df\n",
955
+ "gc.collect()\n",
956
+ "\n",
957
+ "process_plain_source(\"adcom\", ADCOM_REPO, adcom_df)\n",
958
+ "del adcom_df\n",
959
+ "gc.collect()\n",
960
+ "\n",
961
+ "process_sankaku_source(sankaku_df)\n",
962
+ "del sankaku_df\n",
963
+ "gc.collect()\n",
964
+ "\n",
965
+ "\n",
966
+ "# ============================================================\n",
967
+ "# 13. FINALIZE ARROW AND CHECK COUNTS\n",
968
+ "# ============================================================\n",
969
+ "\n",
970
+ "print(\"\\nFinalizing Arrow writer...\")\n",
971
+ "writer.finalize()\n",
972
+ "del writer\n",
973
+ "gc.collect()\n",
974
+ "\n",
975
+ "if not TEMP_ARROW.exists() or TEMP_ARROW.stat().st_size == 0:\n",
976
+ " raise RuntimeError(\"Arrow output is missing or empty.\")\n",
977
+ "\n",
978
+ "new_records = sum(stats[\"processed_by_source\"].values())\n",
979
+ "skipped_records = sum(stats[\"skipped_by_source\"].values())\n",
980
+ "expected_total = existing_count + new_records\n",
981
+ "\n",
982
+ "if new_records == 0:\n",
983
+ " raise RuntimeError(\"No new records were processed. Upload cancelled.\")\n",
984
+ "\n",
985
+ "print(\"\\nNew records by source:\")\n",
986
+ "for source_name in (\"civitai\", \"adcom\", \"sankaku\"):\n",
987
+ " print(\n",
988
+ " f\" {source_name}: \"\n",
989
+ " f\"{stats['processed_by_source'][source_name]:,} processed / \"\n",
990
+ " f\"{stats['skipped_by_source'][source_name]:,} skipped\"\n",
991
+ " )\n",
992
+ "print(\"Existing:\", f\"{existing_count:,}\")\n",
993
+ "print(\"New:\", f\"{new_records:,}\")\n",
994
+ "print(\"Expected total:\", f\"{expected_total:,}\")\n",
995
+ "\n",
996
+ "combined_dataset = Dataset.from_file(str(TEMP_ARROW))\n",
997
+ "if len(combined_dataset) != expected_total:\n",
998
+ " raise RuntimeError(\n",
999
+ " f\"Arrow row count mismatch: expected {expected_total}, got {len(combined_dataset)}\"\n",
1000
+ " )\n",
1001
+ "\n",
1002
+ "\n",
1003
+ "# ============================================================\n",
1004
+ "# 14. RANDOM DECRYPTION / CONVERSATION VERIFICATION\n",
1005
+ "# ============================================================\n",
1006
+ "\n",
1007
+ "if not verification_samples:\n",
1008
+ " raise RuntimeError(\"No new records available for verification.\")\n",
1009
+ "\n",
1010
+ "verification = {\"checked\": 0, \"passed\": 0, \"failed\": 0}\n",
1011
+ "\n",
1012
+ "for item in tqdm(verification_samples, desc=\"Verifying encrypted samples\"):\n",
1013
+ " try:\n",
1014
+ " row = combined_dataset[item[\"dataset_index\"]]\n",
1015
+ " assert row[\"sample_id\"] == item[\"sample_id\"]\n",
1016
+ "\n",
1017
+ " image_bytes = decrypt_payload(row[\"image_enc\"], row[\"sample_id\"], \"image\")\n",
1018
+ " conversation_bytes = decrypt_payload(\n",
1019
+ " row[\"conversation_enc\"], row[\"sample_id\"], \"conversation\"\n",
1020
+ " )\n",
1021
+ " conversation = json.loads(conversation_bytes.decode(\"utf-8\"))\n",
1022
+ "\n",
1023
+ " messages = conversation[\"messages\"]\n",
1024
+ " assert len(messages) == 2\n",
1025
+ " assert messages[0][\"role\"] == \"user\"\n",
1026
+ " assert messages[1][\"role\"] == \"assistant\"\n",
1027
+ "\n",
1028
+ " user_content = messages[0][\"content\"]\n",
1029
+ " assistant_content = messages[1][\"content\"]\n",
1030
+ " assert len(user_content) == 2\n",
1031
+ " assert user_content[0][\"type\"] == \"text\"\n",
1032
+ " assert user_content[1][\"type\"] == \"image\"\n",
1033
+ " assert assistant_content[0][\"type\"] == \"text\"\n",
1034
+ "\n",
1035
+ " assert user_content[0][\"text\"] == item[\"expected_input\"]\n",
1036
+ " assert assistant_content[0][\"text\"] == item[\"expected_output\"]\n",
1037
+ "\n",
1038
+ " with Image.open(io.BytesIO(image_bytes)) as im:\n",
1039
+ " im.verify()\n",
1040
+ " with Image.open(io.BytesIO(image_bytes)) as im:\n",
1041
+ " assert im.width == item[\"width\"]\n",
1042
+ " assert im.height == item[\"height\"]\n",
1043
+ " assert im.format == item[\"image_format\"]\n",
1044
+ "\n",
1045
+ " assert row[\"width\"] <= MAX_IMAGE_DIMENSION\n",
1046
+ " assert row[\"height\"] <= MAX_IMAGE_DIMENSION\n",
1047
+ "\n",
1048
+ " verification[\"passed\"] += 1\n",
1049
+ "\n",
1050
+ " except Exception as error:\n",
1051
+ " verification[\"failed\"] += 1\n",
1052
+ " print(\"\\nVerification failed:\", item[\"sample_id\"], repr(error))\n",
1053
+ "\n",
1054
+ " verification[\"checked\"] += 1\n",
1055
+ "\n",
1056
+ "if verification[\"failed\"]:\n",
1057
+ " raise RuntimeError(\"Random verification failed. Upload cancelled.\")\n",
1058
+ "\n",
1059
+ "print(\"Verification PASS:\", verification)\n",
1060
+ "\n",
1061
+ "\n",
1062
+ "# ============================================================\n",
1063
+ "# 15. SHUFFLE THE COMPLETE COMBINED DATASET\n",
1064
+ "# ============================================================\n",
1065
+ "# Shuffle only AFTER all three sources have been appended and verified.\n",
1066
+ "# This includes existing destination records as well as newly fetched rows.\n",
1067
+ "# flatten_indices() physically materializes the shuffled order in Arrow,\n",
1068
+ "# rather than relying on a temporary logical indices mapping.\n",
1069
+ "\n",
1070
+ "print(\"\\nShuffling all combined records across the three sources...\")\n",
1071
+ "pre_shuffle_count = len(combined_dataset)\n",
1072
+ "combined_dataset = combined_dataset.shuffle(\n",
1073
+ " seed=SHUFFLE_SEED,\n",
1074
+ " keep_in_memory=False,\n",
1075
+ " load_from_cache_file=False\n",
1076
+ ")\n",
1077
+ "combined_dataset = combined_dataset.flatten_indices(\n",
1078
+ " keep_in_memory=False\n",
1079
+ ")\n",
1080
+ "\n",
1081
+ "if len(combined_dataset) != pre_shuffle_count:\n",
1082
+ " raise RuntimeError(\n",
1083
+ " f\"Shuffling changed the dataset size: before={pre_shuffle_count}, \"\n",
1084
+ " f\"after={len(combined_dataset)}\"\n",
1085
+ " )\n",
1086
+ "\n",
1087
+ "# Report the source mix in the first 30 rows as a quick diagnostic.\n",
1088
+ "first_rows = combined_dataset[:min(30, len(combined_dataset))][\"sample_id\"]\n",
1089
+ "first_row_source_mix = {\n",
1090
+ " source: sum(str(sample_id).startswith(prefix) for sample_id in first_rows)\n",
1091
+ " for source, prefix in SOURCE_PREFIXES.items()\n",
1092
+ "}\n",
1093
+ "print(\"Shuffle seed:\", SHUFFLE_SEED)\n",
1094
+ "print(\"Rows physically shuffled:\", f\"{len(combined_dataset):,}\")\n",
1095
+ "print(\"Source mix in first\", len(first_rows), \"rows:\", first_row_source_mix)\n",
1096
+ "\n",
1097
+ "\n",
1098
+ "# ============================================================\n",
1099
+ "# 16. UPDATE MANIFEST AND SAVE COMPLETE DATASET\n",
1100
+ "# ============================================================\n",
1101
+ "\n",
1102
+ "manifest[\"sample_count\"] = len(combined_dataset)\n",
1103
+ "manifest[\"encryption\"] = encryption_config\n",
1104
+ "manifest[\"row_order\"] = {\n",
1105
+ " \"method\": \"global_random_shuffle_after_combining_all_sources\",\n",
1106
+ " \"seed\": SHUFFLE_SEED,\n",
1107
+ " \"physically_materialized\": True,\n",
1108
+ " \"includes_existing_destination_records\": True\n",
1109
+ "}\n",
1110
+ "\n",
1111
+ "manifest.setdefault(\"source_repositories\", [])\n",
1112
+ "for repo in (CIVITAI_REPO, ADCOM_REPO, SANKAKU_REPO):\n",
1113
+ " if repo not in manifest[\"source_repositories\"]:\n",
1114
+ " manifest[\"source_repositories\"].append(repo)\n",
1115
+ "\n",
1116
+ "previous_stats = manifest.get(\"conversion_statistics\", {})\n",
1117
+ "manifest[\"conversion_statistics\"] = {\n",
1118
+ " \"processed\": int(previous_stats.get(\"processed\", 0)) + new_records,\n",
1119
+ " \"skipped\": int(previous_stats.get(\"skipped\", 0)) + skipped_records\n",
1120
+ "}\n",
1121
+ "\n",
1122
+ "manifest[\"last_append\"] = {\n",
1123
+ " \"source_repositories\": [CIVITAI_REPO, ADCOM_REPO, SANKAKU_REPO],\n",
1124
+ " \"records_added_by_source\": stats[\"processed_by_source\"],\n",
1125
+ " \"records_skipped_by_source\": stats[\"skipped_by_source\"],\n",
1126
+ " \"records_filtered_out_before_processing\": stats[\"filtered_out_before_processing\"],\n",
1127
+ " \"verification\": verification,\n",
1128
+ " \"shuffle\": {\n",
1129
+ " \"method\": \"global_random_shuffle_after_combining_all_sources\",\n",
1130
+ " \"seed\": SHUFFLE_SEED,\n",
1131
+ " \"physically_materialized\": True,\n",
1132
+ " \"first_30_row_source_mix\": first_row_source_mix\n",
1133
+ " },\n",
1134
+ " \"created_unix\": time.time()\n",
1135
+ "}\n",
1136
+ "\n",
1137
+ "if OUTPUT_DIR.exists():\n",
1138
+ " shutil.rmtree(OUTPUT_DIR)\n",
1139
+ "OUTPUT_DIR.mkdir(parents=True, exist_ok=True)\n",
1140
+ "\n",
1141
+ "combined_dataset.save_to_disk(\n",
1142
+ " str(OUTPUT_DIR),\n",
1143
+ " max_shard_size=ARROW_MAX_SHARD_SIZE\n",
1144
+ ")\n",
1145
+ "\n",
1146
+ "with open(OUTPUT_DIR / \"encryption_manifest.json\", \"w\", encoding=\"utf-8\") as f:\n",
1147
+ " json.dump(manifest, f, ensure_ascii=False, indent=4)\n",
1148
+ "\n",
1149
+ "append_report = {\n",
1150
+ " \"source_repositories\": {\n",
1151
+ " \"civitai\": CIVITAI_REPO,\n",
1152
+ " \"adcom\": ADCOM_REPO,\n",
1153
+ " \"sankaku\": SANKAKU_REPO\n",
1154
+ " },\n",
1155
+ " \"destination_repository\": DEST_REPO,\n",
1156
+ " \"destination_folder\": DESTINATION_SUBFOLDER,\n",
1157
+ " \"existing_records\": existing_count,\n",
1158
+ " \"new_records_by_source\": stats[\"processed_by_source\"],\n",
1159
+ " \"skipped_records_by_source\": stats[\"skipped_by_source\"],\n",
1160
+ " \"filtered_out_before_processing\": stats[\"filtered_out_before_processing\"],\n",
1161
+ " \"new_records_total\": new_records,\n",
1162
+ " \"final_records\": len(combined_dataset),\n",
1163
+ " \"verification\": verification,\n",
1164
+ " \"row_order\": {\n",
1165
+ " \"method\": \"global_random_shuffle_after_combining_all_sources\",\n",
1166
+ " \"seed\": SHUFFLE_SEED,\n",
1167
+ " \"physically_materialized\": True,\n",
1168
+ " \"first_30_row_source_mix\": first_row_source_mix\n",
1169
+ " },\n",
1170
+ " \"created_unix\": time.time()\n",
1171
+ "}\n",
1172
+ "\n",
1173
+ "with open(OUTPUT_DIR / \"append_report.json\", \"w\", encoding=\"utf-8\") as f:\n",
1174
+ " json.dump(append_report, f, ensure_ascii=False, indent=4)\n",
1175
+ "\n",
1176
+ "with open(OUTPUT_DIR / \"processing_errors.json\", \"w\", encoding=\"utf-8\") as f:\n",
1177
+ " json.dump(stats[\"errors\"], f, ensure_ascii=False, indent=2)\n",
1178
+ "\n",
1179
+ "readme = f\"\"\"\n",
1180
+ "# Three-Source Encrypted Multimodal Dataset\n",
1181
+ "\n",
1182
+ "## Sources\n",
1183
+ "\n",
1184
+ "- Civitai: {CIVITAI_REPO}\n",
1185
+ "- Adcom: {ADCOM_REPO}\n",
1186
+ "- Sankaku: {SANKAKU_REPO}\n",
1187
+ "\n",
1188
+ "## Civitai and Adcom conversation format\n",
1189
+ "\n",
1190
+ "User text:\n",
1191
+ "`Describe the image using these tags: {{tags}}`\n",
1192
+ "\n",
1193
+ "Assistant text:\n",
1194
+ "`prompt`\n",
1195
+ "\n",
1196
+ "Adcom is filtered to rows where author equals `Adcom` (case-insensitive).\n",
1197
+ "Adcom rows whose `prompt` contains the whole word `remove` or `improve`\n",
1198
+ "(case-insensitive) are excluded. Civitai rows are not author-filtered.\n",
1199
+ "\n",
1200
+ "## Sankaku conversation format\n",
1201
+ "\n",
1202
+ "User text:\n",
1203
+ "Original `instruction` column, followed by image.\n",
1204
+ "\n",
1205
+ "Assistant text:\n",
1206
+ "`prompt` + `. ` + `thinking_response` + `. ` + `written_response`.\n",
1207
+ "Repeated consecutive periods are reduced to a single period.\n",
1208
+ "Rows are excluded only when `written_response` contains the whole word\n",
1209
+ "`user` or `summary` AND both `prompt` and `thinking_response` are empty.\n",
1210
+ "\n",
1211
+ "## Final row order\n",
1212
+ "\n",
1213
+ "After all source records are appended, the complete dataset is globally shuffled\n",
1214
+ "across Civitai, Adcom, and Sankaku (including retained existing records).\n",
1215
+ "The shuffled order is physically materialized in Arrow. Shuffle seed: {SHUFFLE_SEED}.\n",
1216
+ "\n",
1217
+ "## Storage and encryption\n",
1218
+ "\n",
1219
+ "- Hugging Face Datasets / Apache Arrow\n",
1220
+ "- AES-256-GCM\n",
1221
+ "- Independent encryption for image and conversation\n",
1222
+ "- 12-byte nonce\n",
1223
+ "- Scrypt key derivation\n",
1224
+ "- Authenticated sample IDs and field names\n",
1225
+ "\n",
1226
+ "## Image preprocessing\n",
1227
+ "\n",
1228
+ "- EXIF orientation correction\n",
1229
+ "- RGB conversion\n",
1230
+ "- Maximum dimension: {MAX_IMAGE_DIMENSION}\n",
1231
+ "- LANCZOS resizing\n",
1232
+ "\"\"\"\n",
1233
+ "\n",
1234
+ "(OUTPUT_DIR / \"README.md\").write_text(readme.strip(), encoding=\"utf-8\")\n",
1235
+ "\n",
1236
+ "\n",
1237
+ "# ============================================================\n",
1238
+ "# 16. PRE-UPLOAD VALIDATION\n",
1239
+ "# ============================================================\n",
1240
+ "\n",
1241
+ "required_output_files = {\n",
1242
+ " \"dataset_info.json\", \"state.json\", \"encryption_manifest.json\",\n",
1243
+ " \"README.md\", \"append_report.json\", \"processing_errors.json\"\n",
1244
+ "}\n",
1245
+ "\n",
1246
+ "actual_names = {p.name for p in OUTPUT_DIR.iterdir() if p.is_file()}\n",
1247
+ "missing = required_output_files - actual_names\n",
1248
+ "if missing:\n",
1249
+ " raise RuntimeError(f\"Missing output files: {sorted(missing)}\")\n",
1250
+ "\n",
1251
+ "arrow_files = list(OUTPUT_DIR.glob(\"*.arrow\"))\n",
1252
+ "if not arrow_files:\n",
1253
+ " raise RuntimeError(\"No Arrow shards generated.\")\n",
1254
+ "\n",
1255
+ "print(\"\\nPrepared files:\", len(list(OUTPUT_DIR.rglob(\"*\"))))\n",
1256
+ "print(\"Arrow shards:\", len(arrow_files))\n",
1257
+ "print(\"Total dataset records:\", f\"{len(combined_dataset):,}\")\n",
1258
+ "\n",
1259
+ "\n",
1260
+ "# ============================================================\n",
1261
+ "# 17. ATOMIC HUGGING FACE COMMIT\n",
1262
+ "# ============================================================\n",
1263
+ "\n",
1264
+ "print(\"\\nPreparing atomic destination replacement...\")\n",
1265
+ "\n",
1266
+ "remote_files_now = api.list_repo_files(\n",
1267
+ " repo_id=DEST_REPO, repo_type=DEST_REPO_TYPE\n",
1268
+ ")\n",
1269
+ "old_files = [f for f in remote_files_now if f.startswith(destination_prefix)]\n",
1270
+ "\n",
1271
+ "operations = [\n",
1272
+ " CommitOperationDelete(path_in_repo=f)\n",
1273
+ " for f in old_files\n",
1274
+ "]\n",
1275
+ "\n",
1276
+ "new_local_files = [p for p in OUTPUT_DIR.rglob(\"*\") if p.is_file()]\n",
1277
+ "for local_path in tqdm(new_local_files, desc=\"Preparing commit\"):\n",
1278
+ " relative = local_path.relative_to(OUTPUT_DIR).as_posix()\n",
1279
+ " operations.append(\n",
1280
+ " CommitOperationAdd(\n",
1281
+ " path_in_repo=destination_prefix + relative,\n",
1282
+ " path_or_fileobj=str(local_path)\n",
1283
+ " )\n",
1284
+ " )\n",
1285
+ "\n",
1286
+ "commit = api.create_commit(\n",
1287
+ " repo_id=DEST_REPO,\n",
1288
+ " repo_type=DEST_REPO_TYPE,\n",
1289
+ " operations=operations,\n",
1290
+ " commit_message=(\n",
1291
+ " \"Append Civitai, Adcom and Sankaku encrypted multimodal records\"\n",
1292
+ " )\n",
1293
+ ")\n",
1294
+ "\n",
1295
+ "print(\"\\nCommit completed:\")\n",
1296
+ "print(commit)\n",
1297
+ "\n",
1298
+ "\n",
1299
+ "# ============================================================\n",
1300
+ "# 18. VERIFY REMOTE UPLOAD\n",
1301
+ "# ============================================================\n",
1302
+ "\n",
1303
+ "remote_after = api.list_repo_files(\n",
1304
+ " repo_id=DEST_REPO, repo_type=DEST_REPO_TYPE\n",
1305
+ ")\n",
1306
+ "uploaded = [f for f in remote_after if f.startswith(destination_prefix)]\n",
1307
+ "uploaded_names = {Path(f).name for f in uploaded}\n",
1308
+ "\n",
1309
+ "missing_remote = required_output_files - uploaded_names\n",
1310
+ "if missing_remote:\n",
1311
+ " raise RuntimeError(f\"Remote verification missing files: {sorted(missing_remote)}\")\n",
1312
+ "\n",
1313
+ "remote_arrows = [f for f in uploaded if f.endswith(\".arrow\")]\n",
1314
+ "if not remote_arrows:\n",
1315
+ " raise RuntimeError(\"Remote verification found no Arrow files.\")\n",
1316
+ "\n",
1317
+ "print(\"\\nREMOTE UPLOAD VERIFIED\")\n",
1318
+ "print(\"Remote Arrow shards:\", len(remote_arrows))\n",
1319
+ "print(\"Remote files:\", len(uploaded))\n",
1320
+ "\n",
1321
+ "\n",
1322
+ "# ============================================================\n",
1323
+ "# 19. FINAL REPORT\n",
1324
+ "# ============================================================\n",
1325
+ "\n",
1326
+ "print(\"\\n\" + \"=\" * 80)\n",
1327
+ "print(\"THREE-SOURCE ENCRYPTED DATASET BUILD COMPLETED\")\n",
1328
+ "print(\"=\" * 80)\n",
1329
+ "\n",
1330
+ "print(\"\\nRecords processed:\")\n",
1331
+ "for source_name in (\"civitai\", \"adcom\", \"sankaku\"):\n",
1332
+ " print(\n",
1333
+ " f\"{source_name:10s}: \"\n",
1334
+ " f\"{stats['processed_by_source'][source_name]:,} processed; \"\n",
1335
+ " f\"{stats['skipped_by_source'][source_name]:,} skipped\"\n",
1336
+ " )\n",
1337
+ "\n",
1338
+ "print(\"\\nFiltered before processing:\", stats[\"filtered_out_before_processing\"])\n",
1339
+ "print(\"Existing records:\", f\"{existing_count:,}\")\n",
1340
+ "print(\"New records:\", f\"{new_records:,}\")\n",
1341
+ "print(\"Final records:\", f\"{len(combined_dataset):,}\")\n",
1342
+ "print(\"Verification:\", verification)\n",
1343
+ "print(\"Encryption: AES-256-GCM / Scrypt\")\n",
1344
+ "print(\"Image max dimension:\", MAX_IMAGE_DIMENSION)\n",
1345
+ "print(\"Final global shuffle seed:\", SHUFFLE_SEED)\n",
1346
+ "print(\"Final row order: globally shuffled and physically materialized\")\n",
1347
+ "print(\"\\nDestination:\")\n",
1348
+ "print(\n",
1349
+ " f\"https://huggingface.co/{DEST_REPO}/tree/main/\"\n",
1350
+ " f\"{DESTINATION_SUBFOLDER}\"\n",
1351
+ ")\n",
1352
+ "print(\"\\nLocal output:\", OUTPUT_DIR)\n",
1353
+ "print(\"\\nALL DONE.\")\n"
1354
+ ]
1355
+ }
1356
+ ],
1357
+ "metadata": {
1358
+ "colab": {
1359
+ "name": "Three_Source_Encrypted_Multimodal_Dataset_Builder_Randomized.ipynb",
1360
+ "provenance": []
1361
+ },
1362
+ "kernelspec": {
1363
+ "display_name": "Python 3",
1364
+ "language": "python",
1365
+ "name": "python3"
1366
+ },
1367
+ "language_info": {
1368
+ "name": "python"
1369
+ }
1370
+ },
1371
+ "nbformat": 4,
1372
+ "nbformat_minor": 5
1373
+ }