codeShare commited on
Commit
c407533
·
verified ·
1 Parent(s): 11e1089

Upload append_author_to_repaired_dataset.ipynb

Browse files
append_author_to_repaired_dataset.ipynb ADDED
@@ -0,0 +1,686 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Append an author dataset to the repaired multi-author dataset\n",
8
+ "\n",
9
+ "This notebook assigns globally sequential image IDs, writes the author into each JSONL record, appends the Parquet index, validates all new byte references, and submits exactly one Hugging Face commit.\n",
10
+ "\n",
11
+ "Set `SOURCE_PREFIX` and `AUTHOR_VALUE` in the configuration section before running. **The final code cell performs the upload when run.**"
12
+ ]
13
+ },
14
+ {
15
+ "cell_type": "code",
16
+ "execution_count": null,
17
+ "metadata": {},
18
+ "outputs": [],
19
+ "source": [
20
+ "# Install/update required packages in Colab\n",
21
+ "!pip -q install -U \"huggingface_hub>=0.25,<2.0\" pyarrow tqdm\n"
22
+ ]
23
+ },
24
+ {
25
+ "cell_type": "code",
26
+ "execution_count": null,
27
+ "metadata": {},
28
+ "outputs": [],
29
+ "source": [
30
+ "# ============================================================\n",
31
+ "# APPEND A NEW AUTHOR DATASET TO THE REPAIRED ROOT DATASET\n",
32
+ "#\n",
33
+ "# Repaired structure:\n",
34
+ "# captions.parquet\n",
35
+ "# images/part_00000.jsonl ... images/part_XXXXX.jsonl\n",
36
+ "#\n",
37
+ "# Every JSONL image record has:\n",
38
+ "# idx = GLOBAL image-record ID (not author-local)\n",
39
+ "# author = author name\n",
40
+ "# image, caption, tags, plus any other source fields\n",
41
+ "#\n",
42
+ "# Every Parquet caption row has exactly:\n",
43
+ "# idx, prompt, tags, author, json_file, byte_offset, byte_length\n",
44
+ "#\n",
45
+ "# One commit:\n",
46
+ "# - replaces captions.parquet\n",
47
+ "# - adds only new images/part_XXXXX.jsonl shards\n",
48
+ "# - does not modify existing image shards\n",
49
+ "# ============================================================\n",
50
+ "\n",
51
+ "# Run in Google Colab after installing: huggingface_hub, pyarrow, tqdm.\n",
52
+ "\n",
53
+ "# Must be set before importing huggingface_hub.\n",
54
+ "import os\n",
55
+ "os.environ[\"HF_HUB_DISABLE_XET\"] = \"1\"\n",
56
+ "\n",
57
+ "# ============================================================\n",
58
+ "# 1. IMPORTS\n",
59
+ "# ============================================================\n",
60
+ "\n",
61
+ "import json\n",
62
+ "import re\n",
63
+ "import tempfile\n",
64
+ "from pathlib import Path\n",
65
+ "\n",
66
+ "import pyarrow as pa\n",
67
+ "import pyarrow.parquet as pq\n",
68
+ "from tqdm.auto import tqdm\n",
69
+ "from google.colab import userdata\n",
70
+ "\n",
71
+ "from huggingface_hub import (\n",
72
+ " HfApi,\n",
73
+ " hf_hub_download,\n",
74
+ " CommitOperationAdd,\n",
75
+ ")\n",
76
+ "\n",
77
+ "# ============================================================\n",
78
+ "# 2. CONFIGURATION\n",
79
+ "# ============================================================\n",
80
+ "\n",
81
+ "REPO_ID = \"codeShare/adcom_captioned_ai_images\"\n",
82
+ "REPO_TYPE = \"dataset\"\n",
83
+ "BASE_REVISION = \"main\"\n",
84
+ "\n",
85
+ "#@markdown Folder in the repository containing the incoming author JSONL files\n",
86
+ "SOURCE_PREFIX = \"authors/new_name/\" #@param {type:\"string\"}\n",
87
+ "\n",
88
+ "#@markdown Exact author value to write into BOTH JSONL and Parquet\n",
89
+ "AUTHOR_VALUE = \"new_name\" #@param {type:\"string\"}\n",
90
+ "\n",
91
+ "#@markdown Target maximum shard size in MiB\n",
92
+ "CHUNK_SIZE_MB = 300 #@param {type:\"integer\"}\n",
93
+ "\n",
94
+ "#@markdown Number of upload threads (keep at 1)\n",
95
+ "UPLOAD_THREADS = 1 #@param {type:\"integer\"}\n",
96
+ "\n",
97
+ "#@markdown Stop on the first malformed source record (recommended)\n",
98
+ "STRICT_SOURCE_VALIDATION = True #@param {type:\"boolean\"}\n",
99
+ "\n",
100
+ "DEST_PARQUET = \"captions.parquet\"\n",
101
+ "DEST_IMAGE_DIR = \"images\"\n",
102
+ "EXPECTED_COLUMNS = [\n",
103
+ " \"idx\",\n",
104
+ " \"prompt\",\n",
105
+ " \"tags\",\n",
106
+ " \"author\",\n",
107
+ " \"json_file\",\n",
108
+ " \"byte_offset\",\n",
109
+ " \"byte_length\",\n",
110
+ "]\n",
111
+ "\n",
112
+ "SOURCE_PREFIX = SOURCE_PREFIX.strip().strip(\"/\") + \"/\"\n",
113
+ "AUTHOR_VALUE = AUTHOR_VALUE.strip()\n",
114
+ "CHUNK_SIZE_BYTES = int(CHUNK_SIZE_MB) * 1024 * 1024\n",
115
+ "COMMIT_MESSAGE = f\"Append {AUTHOR_VALUE} captions and image shards\"\n",
116
+ "\n",
117
+ "if not SOURCE_PREFIX.startswith(\"authors/\"):\n",
118
+ " raise ValueError(\"SOURCE_PREFIX must point to a folder under authors/.\")\n",
119
+ "if not AUTHOR_VALUE:\n",
120
+ " raise ValueError(\"AUTHOR_VALUE cannot be empty.\")\n",
121
+ "if CHUNK_SIZE_MB < 1:\n",
122
+ " raise ValueError(\"CHUNK_SIZE_MB must be at least 1.\")\n",
123
+ "if UPLOAD_THREADS != 1:\n",
124
+ " raise ValueError(\"UPLOAD_THREADS must be exactly 1.\")\n",
125
+ "\n",
126
+ "print(\"Repository:\", REPO_ID)\n",
127
+ "print(\"Source folder:\", SOURCE_PREFIX)\n",
128
+ "print(\"Author:\", AUTHOR_VALUE)\n",
129
+ "print(\"Chunk target:\", CHUNK_SIZE_MB, \"MiB\")\n",
130
+ "print(\"Xet disabled:\", os.environ[\"HF_HUB_DISABLE_XET\"])\n",
131
+ "\n",
132
+ "# ============================================================\n",
133
+ "# 3. AUTHENTICATION AND REPOSITORY SNAPSHOT\n",
134
+ "# ============================================================\n",
135
+ "\n",
136
+ "HF_TOKEN = userdata.get(\"HF_TOKEN\")\n",
137
+ "if not HF_TOKEN:\n",
138
+ " raise RuntimeError(\n",
139
+ " \"HF_TOKEN was not found in Colab Secrets. Add a secret named HF_TOKEN.\"\n",
140
+ " )\n",
141
+ "\n",
142
+ "api = HfApi(token=HF_TOKEN)\n",
143
+ "whoami = api.whoami()\n",
144
+ "print(\"Authenticated as:\", whoami.get(\"name\", \"Hugging Face user\"))\n",
145
+ "\n",
146
+ "repo_info = api.repo_info(\n",
147
+ " repo_id=REPO_ID,\n",
148
+ " repo_type=REPO_TYPE,\n",
149
+ " revision=BASE_REVISION,\n",
150
+ ")\n",
151
+ "BASE_COMMIT = repo_info.sha\n",
152
+ "if not BASE_COMMIT:\n",
153
+ " raise RuntimeError(\"Could not capture the starting repository commit.\")\n",
154
+ "\n",
155
+ "repo_files = api.list_repo_files(\n",
156
+ " repo_id=REPO_ID,\n",
157
+ " repo_type=REPO_TYPE,\n",
158
+ " revision=BASE_REVISION,\n",
159
+ ")\n",
160
+ "repo_file_set = set(repo_files)\n",
161
+ "\n",
162
+ "if DEST_PARQUET not in repo_file_set:\n",
163
+ " raise RuntimeError(f\"Missing root file: {DEST_PARQUET}\")\n",
164
+ "\n",
165
+ "source_shards = sorted(\n",
166
+ " p for p in repo_files\n",
167
+ " if p.startswith(SOURCE_PREFIX) and p.lower().endswith(\".jsonl\")\n",
168
+ ")\n",
169
+ "if not source_shards:\n",
170
+ " raise RuntimeError(f\"No .jsonl source files found under {SOURCE_PREFIX}\")\n",
171
+ "\n",
172
+ "# The repaired dataset now uses root images/. Do not silently write to a\n",
173
+ "# different path or accidentally build on the retired images_repaired/ layout.\n",
174
+ "existing_image_files = sorted(\n",
175
+ " p for p in repo_files\n",
176
+ " if p.startswith(DEST_IMAGE_DIR + \"/\") and p.lower().endswith(\".jsonl\")\n",
177
+ ")\n",
178
+ "if not existing_image_files:\n",
179
+ " raise RuntimeError(\n",
180
+ " \"No existing images/*.jsonl shards found. \"\n",
181
+ " \"Expected the repaired root layout under images/.\"\n",
182
+ " )\n",
183
+ "\n",
184
+ "if any(p.startswith(\"images_repaired/\") for p in repo_files):\n",
185
+ " print(\n",
186
+ " \"WARNING: images_repaired/ still exists in the repository. \"\n",
187
+ " \"This append script will use images/ only and will not modify it.\"\n",
188
+ " )\n",
189
+ "\n",
190
+ "part_pattern = re.compile(r\"^images/part_(\\d+)\\.jsonl$\")\n",
191
+ "existing_chunk_numbers = [\n",
192
+ " int(m.group(1))\n",
193
+ " for p in existing_image_files\n",
194
+ " for m in [part_pattern.match(p)]\n",
195
+ " if m\n",
196
+ "]\n",
197
+ "if not existing_chunk_numbers:\n",
198
+ " raise RuntimeError(\n",
199
+ " \"Found images/*.jsonl files, but none match part_XXXXX.jsonl.\"\n",
200
+ " )\n",
201
+ "\n",
202
+ "next_chunk_index = max(existing_chunk_numbers) + 1\n",
203
+ "\n",
204
+ "print(\"\\nRepository snapshot\")\n",
205
+ "print(\"Starting commit:\", BASE_COMMIT)\n",
206
+ "print(\"Existing root image shards:\", len(existing_image_files))\n",
207
+ "print(\"Next new shard index:\", next_chunk_index)\n",
208
+ "print(\"Incoming source shards:\", len(source_shards))\n",
209
+ "for p in source_shards:\n",
210
+ " print(\" \", p)\n",
211
+ "\n",
212
+ "# ============================================================\n",
213
+ "# 4. DOWNLOAD AND CHECK EXISTING PARQUET\n",
214
+ "# ============================================================\n",
215
+ "\n",
216
+ "existing_parquet_path = hf_hub_download(\n",
217
+ " repo_id=REPO_ID,\n",
218
+ " repo_type=REPO_TYPE,\n",
219
+ " filename=DEST_PARQUET,\n",
220
+ " revision=BASE_REVISION,\n",
221
+ " token=HF_TOKEN,\n",
222
+ ")\n",
223
+ "existing_table = pq.read_table(existing_parquet_path)\n",
224
+ "existing_schema = existing_table.schema\n",
225
+ "\n",
226
+ "if existing_schema.names != EXPECTED_COLUMNS:\n",
227
+ " raise RuntimeError(\n",
228
+ " \"Unexpected captions.parquet columns.\\n\"\n",
229
+ " f\"Expected: {EXPECTED_COLUMNS}\\n\"\n",
230
+ " f\"Found: {existing_schema.names}\"\n",
231
+ " )\n",
232
+ "\n",
233
+ "# Validate the logical Arrow types needed by the repaired index.\n",
234
+ "expected_types = {\n",
235
+ " \"idx\": pa.types.is_integer,\n",
236
+ " \"prompt\": pa.types.is_string,\n",
237
+ " \"tags\": lambda t: pa.types.is_string(t) or pa.types.is_large_string(t),\n",
238
+ " \"author\": lambda t: pa.types.is_string(t) or pa.types.is_large_string(t),\n",
239
+ " \"json_file\": lambda t: pa.types.is_string(t) or pa.types.is_large_string(t),\n",
240
+ " \"byte_offset\": pa.types.is_integer,\n",
241
+ " \"byte_length\": pa.types.is_integer,\n",
242
+ "}\n",
243
+ "for name, checker in expected_types.items():\n",
244
+ " if not checker(existing_schema.field(name).type):\n",
245
+ " raise RuntimeError(\n",
246
+ " f\"Unexpected type for {name!r}: {existing_schema.field(name).type}\"\n",
247
+ " )\n",
248
+ "\n",
249
+ "if existing_table.num_rows == 0:\n",
250
+ " raise RuntimeError(\"Existing captions.parquet is unexpectedly empty.\")\n",
251
+ "\n",
252
+ "existing_idx = existing_table.column(\"idx\").to_pylist()\n",
253
+ "if any(v is None or int(v) < 0 for v in existing_idx):\n",
254
+ " raise RuntimeError(\"Existing Parquet contains null or negative idx values.\")\n",
255
+ "\n",
256
+ "# Multiple caption rows may intentionally point to the same image idx.\n",
257
+ "# Therefore do NOT require idx uniqueness in captions.parquet.\n",
258
+ "next_global_idx = max(int(v) for v in existing_idx) + 1\n",
259
+ "\n",
260
+ "existing_prompts = set(\n",
261
+ " p for p in existing_table.column(\"prompt\").to_pylist()\n",
262
+ " if isinstance(p, str)\n",
263
+ ")\n",
264
+ "\n",
265
+ "print(\"\\nExisting Parquet rows:\", existing_table.num_rows)\n",
266
+ "print(\"Existing unique prompts:\", len(existing_prompts))\n",
267
+ "print(\"Next GLOBAL image idx:\", next_global_idx)\n",
268
+ "print(\"Existing schema:\")\n",
269
+ "print(existing_schema)\n",
270
+ "\n",
271
+ "# ============================================================\n",
272
+ "# 5. PREPARE OUTPUT SHARDS\n",
273
+ "# ============================================================\n",
274
+ "\n",
275
+ "temp_dir = Path(tempfile.mkdtemp(prefix=\"repaired_author_append_\"))\n",
276
+ "new_rows = []\n",
277
+ "new_chunk_paths = []\n",
278
+ "seen_prompts = set(existing_prompts)\n",
279
+ "\n",
280
+ "stats = {\n",
281
+ " \"source_records\": 0,\n",
282
+ " \"added_records\": 0,\n",
283
+ " \"duplicate_prompts\": 0,\n",
284
+ " \"invalid_records\": 0,\n",
285
+ "}\n",
286
+ "\n",
287
+ "current_file = None\n",
288
+ "current_path = None\n",
289
+ "current_size = 0\n",
290
+ "current_chunk_index = next_chunk_index\n",
291
+ "next_idx = next_global_idx\n",
292
+ "\n",
293
+ "def close_chunk():\n",
294
+ " global current_file\n",
295
+ " if current_file is not None:\n",
296
+ " current_file.flush()\n",
297
+ " os.fsync(current_file.fileno())\n",
298
+ " current_file.close()\n",
299
+ " current_file = None\n",
300
+ "\n",
301
+ "def open_chunk():\n",
302
+ " global current_file, current_path, current_size, current_chunk_index\n",
303
+ "\n",
304
+ " close_chunk()\n",
305
+ " filename = f\"part_{current_chunk_index:05d}.jsonl\"\n",
306
+ " current_path = temp_dir / filename\n",
307
+ " current_file = open(current_path, \"wb\")\n",
308
+ " current_size = 0\n",
309
+ "\n",
310
+ " repo_path = f\"{DEST_IMAGE_DIR}/{filename}\"\n",
311
+ " if repo_path in repo_file_set:\n",
312
+ " raise RuntimeError(f\"Refusing to overwrite existing shard: {repo_path}\")\n",
313
+ "\n",
314
+ " new_chunk_paths.append({\n",
315
+ " \"repo_path\": repo_path,\n",
316
+ " \"local_path\": current_path,\n",
317
+ " })\n",
318
+ " current_chunk_index += 1\n",
319
+ "\n",
320
+ "# ============================================================\n",
321
+ "# 6. READ SOURCE RECORDS, REPAIR IDS/AUTHOR, WRITE NEW JSONL\n",
322
+ "# ============================================================\n",
323
+ "\n",
324
+ "try:\n",
325
+ " for source_path in tqdm(source_shards, desc=\"Source shards\"):\n",
326
+ " local_source = hf_hub_download(\n",
327
+ " repo_id=REPO_ID,\n",
328
+ " repo_type=REPO_TYPE,\n",
329
+ " filename=source_path,\n",
330
+ " revision=BASE_REVISION,\n",
331
+ " token=HF_TOKEN,\n",
332
+ " )\n",
333
+ "\n",
334
+ " with open(local_source, \"rb\") as source_file:\n",
335
+ " for line_number, raw_line in enumerate(source_file, start=1):\n",
336
+ " if not raw_line.strip():\n",
337
+ " continue\n",
338
+ "\n",
339
+ " stats[\"source_records\"] += 1\n",
340
+ " raw_payload = raw_line.rstrip(b\"\\r\\n\")\n",
341
+ "\n",
342
+ " try:\n",
343
+ " record = json.loads(raw_payload.decode(\"utf-8\"))\n",
344
+ " if not isinstance(record, dict):\n",
345
+ " raise ValueError(\"JSONL value is not an object.\")\n",
346
+ "\n",
347
+ " required = (\"idx\", \"image\", \"caption\", \"tags\")\n",
348
+ " missing = [k for k in required if k not in record]\n",
349
+ " if missing:\n",
350
+ " raise ValueError(f\"Missing required fields: {missing}\")\n",
351
+ "\n",
352
+ " # The incoming idx is author-local/legacy metadata.\n",
353
+ " # Validate it, but NEVER reuse it in the repaired dataset.\n",
354
+ " source_idx = record[\"idx\"]\n",
355
+ " if isinstance(source_idx, bool):\n",
356
+ " raise ValueError(\"Source idx cannot be boolean.\")\n",
357
+ " int(source_idx)\n",
358
+ "\n",
359
+ " if not isinstance(record[\"caption\"], str):\n",
360
+ " raise ValueError(\"caption must be a string.\")\n",
361
+ " prompt = record[\"caption\"]\n",
362
+ " if not prompt.strip():\n",
363
+ " raise ValueError(\"caption is empty or whitespace-only.\")\n",
364
+ "\n",
365
+ " if not isinstance(record[\"image\"], str) or not record[\"image\"].strip():\n",
366
+ " raise ValueError(\"image must be a non-empty string.\")\n",
367
+ "\n",
368
+ " if prompt in seen_prompts:\n",
369
+ " stats[\"duplicate_prompts\"] += 1\n",
370
+ " continue\n",
371
+ "\n",
372
+ " # Apply repaired structure: globally sequential idx and\n",
373
+ " # explicit author field inside every JSONL record.\n",
374
+ " output_record = dict(record)\n",
375
+ " output_record[\"idx\"] = next_idx\n",
376
+ " output_record[\"author\"] = AUTHOR_VALUE\n",
377
+ "\n",
378
+ " # Compact UTF-8 JSON. The byte offsets below refer to\n",
379
+ " # these exact serialized bytes, not the source line.\n",
380
+ " output_bytes = json.dumps(\n",
381
+ " output_record,\n",
382
+ " ensure_ascii=False,\n",
383
+ " separators=(\",\", \":\"),\n",
384
+ " allow_nan=False,\n",
385
+ " ).encode(\"utf-8\")\n",
386
+ " line_bytes = output_bytes + b\"\\n\"\n",
387
+ "\n",
388
+ " if current_file is None:\n",
389
+ " open_chunk()\n",
390
+ " elif current_size > 0 and current_size + len(line_bytes) > CHUNK_SIZE_BYTES:\n",
391
+ " open_chunk()\n",
392
+ "\n",
393
+ " byte_offset = current_size\n",
394
+ " current_file.write(line_bytes)\n",
395
+ " current_size += len(line_bytes)\n",
396
+ " byte_length = len(output_bytes)\n",
397
+ "\n",
398
+ " tags_value = record[\"tags\"]\n",
399
+ " parquet_tags = None if tags_value is None else str(tags_value)\n",
400
+ "\n",
401
+ " new_rows.append({\n",
402
+ " \"idx\": next_idx,\n",
403
+ " \"prompt\": prompt,\n",
404
+ " \"tags\": parquet_tags,\n",
405
+ " \"author\": AUTHOR_VALUE,\n",
406
+ " \"json_file\": f\"{DEST_IMAGE_DIR}/{current_path.name}\",\n",
407
+ " \"byte_offset\": int(byte_offset),\n",
408
+ " \"byte_length\": int(byte_length),\n",
409
+ " })\n",
410
+ "\n",
411
+ " seen_prompts.add(prompt)\n",
412
+ " next_idx += 1\n",
413
+ " stats[\"added_records\"] += 1\n",
414
+ "\n",
415
+ " except Exception as exc:\n",
416
+ " stats[\"invalid_records\"] += 1\n",
417
+ " message = (\n",
418
+ " f\"Invalid source record at {source_path}, \"\n",
419
+ " f\"line {line_number}: {exc}\"\n",
420
+ " )\n",
421
+ " if STRICT_SOURCE_VALIDATION:\n",
422
+ " raise RuntimeError(message) from exc\n",
423
+ " print(\"SKIPPED:\", message)\n",
424
+ "\n",
425
+ "finally:\n",
426
+ " close_chunk()\n",
427
+ "\n",
428
+ "print(\"\\nPreprocessing summary\")\n",
429
+ "for key, value in stats.items():\n",
430
+ " print(f\"{key}: {value}\")\n",
431
+ "print(\"New JSONL shards:\", len(new_chunk_paths))\n",
432
+ "\n",
433
+ "if stats[\"added_records\"] == 0:\n",
434
+ " raise RuntimeError(\n",
435
+ " \"No new records were appended. No commit was created.\"\n",
436
+ " )\n",
437
+ "\n",
438
+ "if stats[\"invalid_records\"] and STRICT_SOURCE_VALIDATION:\n",
439
+ " raise RuntimeError(\"Invalid source records found; refusing to commit.\")\n",
440
+ "\n",
441
+ "# ============================================================\n",
442
+ "# 7. BUILD UPDATED PARQUET USING THE EXISTING SCHEMA\n",
443
+ "# ============================================================\n",
444
+ "\n",
445
+ "new_table = pa.Table.from_pylist(new_rows, schema=existing_schema)\n",
446
+ "updated_table = pa.concat_tables([existing_table, new_table])\n",
447
+ "\n",
448
+ "updated_parquet_path = temp_dir / DEST_PARQUET\n",
449
+ "pq.write_table(\n",
450
+ " updated_table,\n",
451
+ " updated_parquet_path,\n",
452
+ " compression=\"zstd\",\n",
453
+ ")\n",
454
+ "\n",
455
+ "# Re-open the actual file that will be uploaded.\n",
456
+ "check_table = pq.read_table(updated_parquet_path)\n",
457
+ "\n",
458
+ "if check_table.schema.names != EXPECTED_COLUMNS:\n",
459
+ " raise RuntimeError(\"Written Parquet has incorrect columns.\")\n",
460
+ "if not check_table.schema.equals(existing_schema, check_metadata=False):\n",
461
+ " raise RuntimeError(\n",
462
+ " \"Written Parquet schema/types differ from the existing schema.\"\n",
463
+ " )\n",
464
+ "if check_table.num_rows != existing_table.num_rows + len(new_rows):\n",
465
+ " raise RuntimeError(\"Written Parquet row count is incorrect.\")\n",
466
+ "\n",
467
+ "# Ensure the old rows are byte-for-byte/logically preserved in order.\n",
468
+ "if not check_table.slice(0, existing_table.num_rows).equals(existing_table):\n",
469
+ " raise RuntimeError(\"Existing Parquet rows were changed.\")\n",
470
+ "\n",
471
+ "# Ensure all newly added prompts are unique and absent from old data.\n",
472
+ "new_prompts = [r[\"prompt\"] for r in new_rows]\n",
473
+ "if len(new_prompts) != len(set(new_prompts)):\n",
474
+ " raise RuntimeError(\"Duplicate prompts exist among the new rows.\")\n",
475
+ "if not set(new_prompts).isdisjoint(existing_prompts):\n",
476
+ " raise RuntimeError(\"A new prompt duplicates an existing prompt.\")\n",
477
+ "\n",
478
+ "# Global IDs must be sequential for the newly appended image records.\n",
479
+ "new_ids = [int(r[\"idx\"]) for r in new_rows]\n",
480
+ "expected_new_ids = list(range(next_global_idx, next_global_idx + len(new_rows)))\n",
481
+ "if new_ids != expected_new_ids:\n",
482
+ " raise RuntimeError(\"New global idx values are not sequential.\")\n",
483
+ "\n",
484
+ "# ============================================================\n",
485
+ "# 8. VALIDATE EVERY NEW JSONL FILE AND PARQUET BYTE REFERENCE\n",
486
+ "# ============================================================\n",
487
+ "\n",
488
+ "chunk_local = {}\n",
489
+ "chunk_sizes = {}\n",
490
+ "\n",
491
+ "for item in new_chunk_paths:\n",
492
+ " path = Path(item[\"local_path\"])\n",
493
+ " if not path.is_file() or path.stat().st_size == 0:\n",
494
+ " raise RuntimeError(f\"Missing or empty output shard: {path}\")\n",
495
+ " chunk_local[item[\"repo_path\"]] = path\n",
496
+ " chunk_sizes[item[\"repo_path\"]] = path.stat().st_size\n",
497
+ "\n",
498
+ "# Parse every output JSONL line, not merely the records referenced below.\n",
499
+ "for repo_path, local_path in chunk_local.items():\n",
500
+ " with open(local_path, \"rb\") as f:\n",
501
+ " for line_no, line in enumerate(f, start=1):\n",
502
+ " if not line.endswith(b\"\\n\"):\n",
503
+ " raise RuntimeError(f\"Missing final newline: {repo_path}:{line_no}\")\n",
504
+ " payload = line[:-1]\n",
505
+ " if not payload:\n",
506
+ " raise RuntimeError(f\"Blank JSONL line: {repo_path}:{line_no}\")\n",
507
+ " try:\n",
508
+ " parsed = json.loads(payload.decode(\"utf-8\"))\n",
509
+ " except Exception as exc:\n",
510
+ " raise RuntimeError(\n",
511
+ " f\"Invalid output JSON: {repo_path}:{line_no}: {exc}\"\n",
512
+ " ) from exc\n",
513
+ " if not isinstance(parsed, dict):\n",
514
+ " raise RuntimeError(f\"Output record is not an object: {repo_path}:{line_no}\")\n",
515
+ " if parsed.get(\"author\") != AUTHOR_VALUE:\n",
516
+ " raise RuntimeError(f\"JSONL author mismatch: {repo_path}:{line_no}\")\n",
517
+ "\n",
518
+ "print(\"\\nValidating Parquet -> JSONL byte references...\")\n",
519
+ "validated = 0\n",
520
+ "\n",
521
+ "for row in tqdm(new_rows, desc=\"Byte-reference validation\"):\n",
522
+ " repo_path = row[\"json_file\"]\n",
523
+ " if repo_path not in chunk_local:\n",
524
+ " raise RuntimeError(f\"Parquet points to an unknown new shard: {repo_path}\")\n",
525
+ "\n",
526
+ " offset = int(row[\"byte_offset\"])\n",
527
+ " length = int(row[\"byte_length\"])\n",
528
+ " size = chunk_sizes[repo_path]\n",
529
+ "\n",
530
+ " if offset < 0 or length <= 0 or offset + length >= size + 1:\n",
531
+ " raise RuntimeError(\n",
532
+ " f\"Out-of-range byte reference: {repo_path}, \"\n",
533
+ " f\"offset={offset}, length={length}, size={size}\"\n",
534
+ " )\n",
535
+ "\n",
536
+ " with open(chunk_local[repo_path], \"rb\") as f:\n",
537
+ " f.seek(offset)\n",
538
+ " payload = f.read(length)\n",
539
+ " newline = f.read(1)\n",
540
+ "\n",
541
+ " if len(payload) != length:\n",
542
+ " raise RuntimeError(f\"Short read at {repo_path}, offset {offset}.\")\n",
543
+ " if newline != b\"\\n\":\n",
544
+ " raise RuntimeError(f\"Missing newline at {repo_path}, offset {offset}.\")\n",
545
+ "\n",
546
+ " parsed = json.loads(payload.decode(\"utf-8\"))\n",
547
+ "\n",
548
+ " if int(parsed.get(\"idx\", -1)) != int(row[\"idx\"]):\n",
549
+ " raise RuntimeError(f\"idx mismatch at {repo_path}, offset {offset}.\")\n",
550
+ " if parsed.get(\"author\") != row[\"author\"]:\n",
551
+ " raise RuntimeError(f\"author mismatch at {repo_path}, offset {offset}.\")\n",
552
+ " if parsed.get(\"caption\") != row[\"prompt\"]:\n",
553
+ " raise RuntimeError(f\"prompt/caption mismatch at {repo_path}, offset {offset}.\")\n",
554
+ "\n",
555
+ " expected_tags = None if parsed.get(\"tags\") is None else str(parsed.get(\"tags\"))\n",
556
+ " if expected_tags != row[\"tags\"]:\n",
557
+ " raise RuntimeError(f\"tags mismatch at {repo_path}, offset {offset}.\")\n",
558
+ "\n",
559
+ " validated += 1\n",
560
+ "\n",
561
+ "if validated != len(new_rows):\n",
562
+ " raise RuntimeError(\"Not all newly appended Parquet references were validated.\")\n",
563
+ "\n",
564
+ "# Check that all upload targets are unique and no image target already exists.\n",
565
+ "upload_paths = [DEST_PARQUET] + [x[\"repo_path\"] for x in new_chunk_paths]\n",
566
+ "if len(upload_paths) != len(set(upload_paths)):\n",
567
+ " raise RuntimeError(\"Duplicate paths in commit manifest.\")\n",
568
+ "\n",
569
+ "collisions = set(x[\"repo_path\"] for x in new_chunk_paths) & repo_file_set\n",
570
+ "if collisions:\n",
571
+ " raise RuntimeError(f\"Refusing to overwrite existing image shards: {sorted(collisions)}\")\n",
572
+ "\n",
573
+ "# Verify the prepared upload files.\n",
574
+ "upload_local_paths = [updated_parquet_path] + [\n",
575
+ " Path(x[\"local_path\"]) for x in new_chunk_paths\n",
576
+ "]\n",
577
+ "for path in upload_local_paths:\n",
578
+ " if not path.is_file() or path.stat().st_size <= 0:\n",
579
+ " raise RuntimeError(f\"Missing or empty upload file: {path}\")\n",
580
+ "\n",
581
+ "print(\"\\nPRE-UPLOAD VALIDATION PASSED\")\n",
582
+ "print(\"Existing Parquet rows preserved:\", existing_table.num_rows)\n",
583
+ "print(\"New Parquet rows:\", len(new_rows))\n",
584
+ "print(\"Updated Parquet rows:\", check_table.num_rows)\n",
585
+ "print(\"New global idx range:\", new_ids[0], \"to\", new_ids[-1])\n",
586
+ "print(\"New JSONL shards:\", len(new_chunk_paths))\n",
587
+ "print(\"JSONL byte references validated:\", validated)\n",
588
+ "print(\"Parquet columns/types preserved:\", True)\n",
589
+ "\n",
590
+ "# ============================================================\n",
591
+ "# 9. BUILD EXACTLY ONE COMMIT\n",
592
+ "# ============================================================\n",
593
+ "\n",
594
+ "operations = [\n",
595
+ " CommitOperationAdd(\n",
596
+ " path_in_repo=DEST_PARQUET,\n",
597
+ " path_or_fileobj=str(updated_parquet_path),\n",
598
+ " )\n",
599
+ "]\n",
600
+ "\n",
601
+ "for item in new_chunk_paths:\n",
602
+ " operations.append(\n",
603
+ " CommitOperationAdd(\n",
604
+ " path_in_repo=item[\"repo_path\"],\n",
605
+ " path_or_fileobj=str(item[\"local_path\"]),\n",
606
+ " )\n",
607
+ " )\n",
608
+ "\n",
609
+ "print(\"\\nCommit manifest\")\n",
610
+ "for op in operations:\n",
611
+ " print(\"ADD/REPLACE:\", op.path_in_repo)\n",
612
+ "print(\"Total operations:\", len(operations))\n",
613
+ "print(\"Parent commit:\", BASE_COMMIT)\n",
614
+ "print(\"Commit message:\", COMMIT_MESSAGE)\n",
615
+ "\n",
616
+ "# Last-moment optimistic concurrency check.\n",
617
+ "latest_info = api.repo_info(\n",
618
+ " repo_id=REPO_ID,\n",
619
+ " repo_type=REPO_TYPE,\n",
620
+ " revision=BASE_REVISION,\n",
621
+ ")\n",
622
+ "if latest_info.sha != BASE_COMMIT:\n",
623
+ " raise RuntimeError(\n",
624
+ " \"Repository changed while the append was being prepared. \"\n",
625
+ " \"Nothing was committed. Re-run from the new repository revision.\"\n",
626
+ " )\n",
627
+ "\n",
628
+ "# One create_commit call. No automatic retry.\n",
629
+ "print(\"\\nUploading one commit...\")\n",
630
+ "try:\n",
631
+ " result = api.create_commit(\n",
632
+ " repo_id=REPO_ID,\n",
633
+ " repo_type=REPO_TYPE,\n",
634
+ " revision=BASE_REVISION,\n",
635
+ " parent_commit=BASE_COMMIT,\n",
636
+ " operations=operations,\n",
637
+ " commit_message=COMMIT_MESSAGE,\n",
638
+ " num_threads=UPLOAD_THREADS,\n",
639
+ " )\n",
640
+ " print(\"\\nSUCCESS: one commit created.\")\n",
641
+ " print(\"Commit URL:\", getattr(result, \"commit_url\", result))\n",
642
+ " print(\"Author:\", AUTHOR_VALUE)\n",
643
+ " print(\"Added caption rows:\", len(new_rows))\n",
644
+ " print(\"New JSONL shards:\", len(new_chunk_paths))\n",
645
+ " print(\"Final Parquet rows:\", check_table.num_rows)\n",
646
+ "\n",
647
+ "except Exception as upload_error:\n",
648
+ " print(\"\\nUPLOAD ERROR:\", type(upload_error).__name__, str(upload_error))\n",
649
+ " print(\"Checking repository state; do not blindly retry...\")\n",
650
+ " try:\n",
651
+ " current_info = api.repo_info(\n",
652
+ " repo_id=REPO_ID,\n",
653
+ " repo_type=REPO_TYPE,\n",
654
+ " revision=BASE_REVISION,\n",
655
+ " )\n",
656
+ " if current_info.sha == BASE_COMMIT:\n",
657
+ " print(\"Repository revision is unchanged; commit was not finalized on this branch.\")\n",
658
+ " else:\n",
659
+ " print(\"Repository revision changed.\")\n",
660
+ " print(\"Original:\", BASE_COMMIT)\n",
661
+ " print(\"Current:\", current_info.sha)\n",
662
+ " print(\"Inspect commit history and files before doing anything else.\")\n",
663
+ " except Exception as check_error:\n",
664
+ " print(\"Could not verify repository state:\", repr(check_error))\n",
665
+ " print(\"Inspect the Hugging Face commit history before retrying.\")\n",
666
+ " raise\n"
667
+ ]
668
+ }
669
+ ],
670
+ "metadata": {
671
+ "colab": {
672
+ "name": "append_author_to_repaired_dataset.ipynb",
673
+ "provenance": []
674
+ },
675
+ "kernelspec": {
676
+ "display_name": "Python 3",
677
+ "language": "python",
678
+ "name": "python3"
679
+ },
680
+ "language_info": {
681
+ "name": "python"
682
+ }
683
+ },
684
+ "nbformat": 4,
685
+ "nbformat_minor": 5
686
+ }