File size: 29,510 Bytes
3bee27f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
#!/usr/bin/env python3
"""Build the general science QA release before upload.

The script reads local parquet snapshots only. It creates train/test JSONL
files, exports ScienceQA images, computes release statistics, and writes a
dataset card.
"""

from __future__ import annotations

import hashlib
import json
import random
import re
import sys
from collections import Counter, defaultdict
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Callable

try:
    import pyarrow.parquet as pq
except ImportError as exc:
    raise SystemExit("pyarrow is required. Run with: conda run -n memory python ...") from exc


RELEASE_DIR = Path(__file__).resolve().parents[1]
DATA_ROOT = RELEASE_DIR.parent
IMAGE_DIR = RELEASE_DIR / "images" / "scienceqa"
TRAIN_PATH = RELEASE_DIR / "train.jsonl"
TEST_PATH = RELEASE_DIR / "test.jsonl"
STATS_PATH = RELEASE_DIR / "stats.json"
CARD_PATH = RELEASE_DIR / "general_science_card.md"
README_PATH = RELEASE_DIR / "README.md"

SEED = 42
TASK_TYPE = "multiple_choice_science_qa"

SOURCE_LICENSES = {
    "allenai/sciq": {
        "license": "CC BY-NC 3.0",
        "license_id": "cc-by-nc-3.0",
        "license_source": "local Hugging Face dataset card: sciq/README.md",
        "url": "https://huggingface.co/datasets/allenai/sciq",
    },
    "allenai/ai2_arc": {
        "license": "CC BY-SA 4.0",
        "license_id": "cc-by-sa-4.0",
        "license_source": "local Hugging Face dataset card: ai2_arc/README.md",
        "url": "https://huggingface.co/datasets/allenai/ai2_arc",
    },
    "derek-thomas/ScienceQA": {
        "license": "TBD: not available in local snapshot",
        "license_id": "unknown-local-snapshot",
        "license_source": "local parquet snapshot does not include README/license metadata; verify upstream before public upload",
        "url": "https://huggingface.co/datasets/derek-thomas/ScienceQA",
    },
}


@dataclass(frozen=True)
class SourceFile:
    display_name: str
    dataset: str
    subset: str | None
    source_split: str
    final_split: str
    path: Path
    converter: Callable[[dict[str, Any], int, "SourceFile"], dict[str, Any] | None]


def read_rows(path: Path) -> list[dict[str, Any]]:
    if not path.exists():
        raise FileNotFoundError(f"Required parquet file not found: {path}")
    return pq.read_table(path).to_pylist()


def find_single_parquet(pattern: str) -> Path:
    matches = sorted(DATA_ROOT.glob(pattern))
    if len(matches) != 1:
        found = ", ".join(str(path.relative_to(DATA_ROOT)) for path in matches) or "none"
        raise FileNotFoundError(f"Expected exactly one parquet for {pattern}; found {found}")
    return matches[0]


def clean_text(value: Any) -> str | None:
    if value is None:
        return None
    text = str(value).strip()
    return text or None


def normalize_for_key(value: Any) -> str:
    text = clean_text(value) or ""
    text = text.lower()
    text = re.sub(r"\s+", " ", text)
    text = re.sub(r"[^\w\s]+", "", text)
    return text.strip()


def generated_label(index: int) -> str:
    label = ""
    index += 1
    while index:
        index, remainder = divmod(index - 1, 26)
        label = chr(ord("A") + remainder) + label
    return label


def stable_rng(key: str) -> random.Random:
    digest = hashlib.sha256(f"{SEED}:{key}".encode("utf-8")).hexdigest()
    return random.Random(int(digest[:16], 16))


def sanitize_id(value: str) -> str:
    return re.sub(r"[^A-Za-z0-9_.:-]+", "-", value).strip("-")


def detect_image_format(image_bytes: bytes) -> tuple[str, str]:
    if image_bytes.startswith(b"\x89PNG\r\n\x1a\n"):
        return "png", "image/png"
    if image_bytes.startswith(b"\xff\xd8\xff"):
        return "jpg", "image/jpeg"
    if image_bytes.startswith(b"GIF87a") or image_bytes.startswith(b"GIF89a"):
        return "gif", "image/gif"
    if image_bytes.startswith(b"RIFF") and image_bytes[8:12] == b"WEBP":
        return "webp", "image/webp"
    return "bin", "application/octet-stream"


def extract_image_payload(row: dict[str, Any]) -> dict[str, Any] | None:
    image = row.get("image")
    if not isinstance(image, dict):
        return None

    image_bytes = image.get("bytes")
    original_path = clean_text(image.get("path"))
    if isinstance(image_bytes, bytes) and image_bytes:
        extension, mime_type = detect_image_format(image_bytes)
        return {
            "bytes": image_bytes,
            "extension": extension,
            "mime_type": mime_type,
            "original_path": original_path,
        }
    if original_path:
        return {
            "bytes": None,
            "extension": None,
            "mime_type": None,
            "original_path": original_path,
        }
    return None


def materialize_image(example_id: str, payload: dict[str, Any] | None) -> dict[str, Any] | None:
    if payload is None:
        return None

    image_bytes = payload.get("bytes")
    if isinstance(image_bytes, bytes) and image_bytes:
        IMAGE_DIR.mkdir(parents=True, exist_ok=True)
        extension = payload["extension"]
        image_path = IMAGE_DIR / f"{example_id}.{extension}"
        image_path.write_bytes(image_bytes)
        return {
            "path": str(image_path.relative_to(RELEASE_DIR)),
            "mime_type": payload["mime_type"],
        }

    original_path = payload.get("original_path")
    if original_path:
        return {"path": original_path, "mime_type": payload.get("mime_type")}
    return None


def combine_support(*parts: Any) -> str | None:
    cleaned = [text for text in (clean_text(part) for part in parts) if text]
    return "\n\n".join(cleaned) if cleaned else None


def make_dedup_key(question: str, choices: list[dict[str, Any]], answer_text: str) -> str:
    choice_texts = sorted(normalize_for_key(choice["text"]) for choice in choices)
    return " || ".join([normalize_for_key(question), *choice_texts, normalize_for_key(answer_text)])


def shuffle_and_relabel(raw_choices: list[dict[str, Any]], example_id: str) -> tuple[list[dict[str, str]], str | None]:
    choices = list(raw_choices)
    stable_rng(example_id).shuffle(choices)

    output_choices: list[dict[str, str]] = []
    answer_label = None
    for index, choice in enumerate(choices):
        label = generated_label(index)
        output_choices.append({"label": label, "text": choice["text"]})
        if choice.get("is_correct"):
            answer_label = label
    return output_choices, answer_label


def build_example(item: dict[str, Any]) -> dict[str, Any]:
    choices, answer_label = shuffle_and_relabel(item["raw_choices"], item["id"])
    image = materialize_image(item["id"], item.get("image_payload"))
    modality = "image_text" if image else "text"

    example = {
        "id": item["id"],
        "dataset": item["dataset"],
        "subset": item["subset"],
        "split": item["split"],
        "task_type": TASK_TYPE,
        "modality": modality,
        "question": item["question"],
        "image": image,
        "choices": choices,
        "answer_label": answer_label,
        "answer_text": item["answer_text"],
        "support": item["support"],
        "source_meta": item["source_meta"],
    }
    validate_example(example)
    return example


def validate_example(example: dict[str, Any]) -> None:
    required = [
        "id",
        "dataset",
        "split",
        "task_type",
        "modality",
        "question",
        "image",
        "choices",
        "answer_label",
        "answer_text",
        "source_meta",
    ]
    missing = [field for field in required if field not in example]
    if missing:
        raise ValueError(f"{example.get('id')} missing fields: {missing}")
    if not example["question"] or not example["answer_label"] or not example["answer_text"]:
        raise ValueError(f"{example['id']} has empty question or answer")
    if not isinstance(example["choices"], list) or len(example["choices"]) < 4:
        raise ValueError(f"{example['id']} has fewer than 4 choices")
    if example["answer_label"] not in {choice["label"] for choice in example["choices"]}:
        raise ValueError(f"{example['id']} answer_label is absent from choices")
    if example["modality"] == "image_text" and not example["image"]:
        raise ValueError(f"{example['id']} image_text example has no image")


def convert_sciq(row: dict[str, Any], index: int, source: SourceFile) -> dict[str, Any] | None:
    question = clean_text(row.get("question"))
    answer_text = clean_text(row.get("correct_answer"))
    support = clean_text(row.get("support"))
    choice_texts = [
        clean_text(row.get("distractor1")),
        clean_text(row.get("distractor2")),
        clean_text(row.get("distractor3")),
        answer_text,
    ]
    if question is None or answer_text is None or any(choice is None for choice in choice_texts):
        return None

    raw_choices = [
        {"text": choice, "is_correct": idx == 3}
        for idx, choice in enumerate(choice_texts)
        if choice is not None
    ]
    if len(raw_choices) < 4:
        return None

    example_id = f"sciq-{source.source_split}-{index:05d}"
    return {
        "id": example_id,
        "dataset": source.dataset,
        "subset": source.subset,
        "split": source.final_split,
        "question": question,
        "raw_choices": raw_choices,
        "answer_text": answer_text,
        "support": support,
        "image_payload": None,
        "source_meta": {
            "source_file": str(source.path.relative_to(DATA_ROOT)),
            "source_split": source.source_split,
            "source_index": index,
            "original_answer_text": answer_text,
            **SOURCE_LICENSES[source.dataset],
        },
    }


def extract_struct_choices(raw_choices: Any) -> list[dict[str, str]] | None:
    if not isinstance(raw_choices, dict):
        return None
    texts = raw_choices.get("text")
    labels = raw_choices.get("label")
    if not isinstance(texts, list) or not isinstance(labels, list) or len(texts) != len(labels):
        return None
    choices: list[dict[str, str]] = []
    for label, text in zip(labels, texts):
        clean_label = clean_text(label)
        clean_choice_text = clean_text(text)
        if clean_label is None or clean_choice_text is None:
            return None
        choices.append({"label": clean_label, "text": clean_choice_text})
    return choices


def convert_ai2_arc(row: dict[str, Any], index: int, source: SourceFile) -> dict[str, Any] | None:
    question = clean_text(row.get("question"))
    answer_key = clean_text(row.get("answerKey"))
    choices = extract_struct_choices(row.get("choices"))
    if question is None or answer_key is None or choices is None or len(choices) < 4:
        return None

    answer_text = None
    for choice in choices:
        if choice["label"] == answer_key or choice["label"].lower() == answer_key.lower():
            answer_text = choice["text"]
            break
    if answer_text is None:
        return None

    raw_choices = [
        {"text": choice["text"], "is_correct": choice["text"] == answer_text}
        for choice in choices
    ]
    original_id = clean_text(row.get("id")) or f"{source.source_split}-{index:05d}"
    subset_id = sanitize_id(source.subset or "default")
    example_id = f"ai2_arc-{subset_id}-{source.source_split}-{sanitize_id(original_id)}"
    return {
        "id": example_id,
        "dataset": source.dataset,
        "subset": source.subset,
        "split": source.final_split,
        "question": question,
        "raw_choices": raw_choices,
        "answer_text": answer_text,
        "support": None,
        "image_payload": None,
        "source_meta": {
            "source_file": str(source.path.relative_to(DATA_ROOT)),
            "source_split": source.source_split,
            "source_index": index,
            "original_id": original_id,
            "original_answer_label": answer_key,
            "original_choice_labels": [choice["label"] for choice in choices],
            **SOURCE_LICENSES[source.dataset],
        },
    }


def convert_scienceqa(row: dict[str, Any], index: int, source: SourceFile) -> dict[str, Any] | None:
    question = clean_text(row.get("question"))
    raw_choice_values = row.get("choices")
    answer_index = row.get("answer")
    subject = clean_text(row.get("subject"))
    if subject != "natural science":
        return None
    if question is None or not isinstance(raw_choice_values, list):
        return None
    choice_texts = [clean_text(choice) for choice in raw_choice_values]
    if any(choice is None for choice in choice_texts) or len(choice_texts) < 4:
        return None
    if not isinstance(answer_index, int) or isinstance(answer_index, bool):
        return None
    if answer_index < 0 or answer_index >= len(choice_texts):
        return None

    answer_text = choice_texts[answer_index]
    raw_choices = [
        {"text": choice, "is_correct": choice_index == answer_index}
        for choice_index, choice in enumerate(choice_texts)
        if choice is not None
    ]
    example_id = f"scienceqa-{source.source_split}-{index:05d}"
    image_payload = extract_image_payload(row)
    return {
        "id": example_id,
        "dataset": source.dataset,
        "subset": source.subset,
        "split": source.final_split,
        "question": question,
        "raw_choices": raw_choices,
        "answer_text": answer_text,
        "support": combine_support(row.get("hint"), row.get("lecture"), row.get("solution")),
        "image_payload": image_payload,
        "source_meta": {
            "source_file": str(source.path.relative_to(DATA_ROOT)),
            "source_split": source.source_split,
            "source_index": index,
            "original_answer_index": answer_index,
            "task": clean_text(row.get("task")),
            "grade": clean_text(row.get("grade")),
            "subject": subject,
            "topic": clean_text(row.get("topic")),
            "category": clean_text(row.get("category")),
            "skill": clean_text(row.get("skill")),
            "image_present": image_payload is not None,
            "original_image_path": image_payload.get("original_path") if image_payload else None,
            **SOURCE_LICENSES[source.dataset],
        },
    }


def load_source_files() -> list[SourceFile]:
    scienceqa_train = find_single_parquet("scienceqa_hf/data/train-*.parquet")
    scienceqa_validation = find_single_parquet("scienceqa_hf/data/validation-*.parquet")
    scienceqa_test = find_single_parquet("scienceqa_hf/data/test-*.parquet")

    files: list[SourceFile] = [
        SourceFile("SciQ", "allenai/sciq", None, "train", "train", DATA_ROOT / "sciq/data/train-00000-of-00001.parquet", convert_sciq),
        SourceFile("SciQ", "allenai/sciq", None, "validation", "train", DATA_ROOT / "sciq/data/validation-00000-of-00001.parquet", convert_sciq),
        SourceFile("SciQ", "allenai/sciq", None, "test", "test", DATA_ROOT / "sciq/data/test-00000-of-00001.parquet", convert_sciq),
        SourceFile("AI2 ARC-Challenge", "allenai/ai2_arc", "ARC-Challenge", "train", "train", DATA_ROOT / "ai2_arc/ARC-Challenge/train-00000-of-00001.parquet", convert_ai2_arc),
        SourceFile("AI2 ARC-Challenge", "allenai/ai2_arc", "ARC-Challenge", "validation", "train", DATA_ROOT / "ai2_arc/ARC-Challenge/validation-00000-of-00001.parquet", convert_ai2_arc),
        SourceFile("AI2 ARC-Challenge", "allenai/ai2_arc", "ARC-Challenge", "test", "test", DATA_ROOT / "ai2_arc/ARC-Challenge/test-00000-of-00001.parquet", convert_ai2_arc),
        SourceFile("AI2 ARC-Easy", "allenai/ai2_arc", "ARC-Easy", "train", "train", DATA_ROOT / "ai2_arc/ARC-Easy/train-00000-of-00001.parquet", convert_ai2_arc),
        SourceFile("AI2 ARC-Easy", "allenai/ai2_arc", "ARC-Easy", "validation", "train", DATA_ROOT / "ai2_arc/ARC-Easy/validation-00000-of-00001.parquet", convert_ai2_arc),
        SourceFile("AI2 ARC-Easy", "allenai/ai2_arc", "ARC-Easy", "test", "test", DATA_ROOT / "ai2_arc/ARC-Easy/test-00000-of-00001.parquet", convert_ai2_arc),
        SourceFile("ScienceQA", "derek-thomas/ScienceQA", None, "train", "train", scienceqa_train, convert_scienceqa),
        SourceFile("ScienceQA", "derek-thomas/ScienceQA", None, "validation", "train", scienceqa_validation, convert_scienceqa),
        SourceFile("ScienceQA", "derek-thomas/ScienceQA", None, "test", "test", scienceqa_test, convert_scienceqa),
    ]
    return files


def collect_items() -> tuple[list[dict[str, Any]], dict[str, Any]]:
    raw_items: list[dict[str, Any]] = []
    source_stats: dict[str, Any] = {}

    for source in load_source_files():
        rows = read_rows(source.path)
        converted = 0
        skipped = 0
        for index, row in enumerate(rows):
            item = source.converter(row, index, source)
            if item is None:
                skipped += 1
                continue
            item["dedup_key"] = make_dedup_key(item["question"], item["raw_choices"], item["answer_text"])
            raw_items.append(item)
            converted += 1
        key = f"{source.dataset}|{source.subset}|{source.source_split}"
        source_stats[key] = {
            "display_name": source.display_name,
            "dataset": source.dataset,
            "subset": source.subset,
            "source_split": source.source_split,
            "final_split": source.final_split,
            "source_file": str(source.path.relative_to(DATA_ROOT)),
            "raw_rows": len(rows),
            "converted": converted,
            "skipped": skipped,
        }
        print(f"{source.display_name} {source.source_split}: converted {converted}, skipped {skipped}")
    return raw_items, source_stats


def deduplicate(items: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], dict[str, Any]]:
    train = [item for item in items if item["split"] == "train"]
    test = [item for item in items if item["split"] == "test"]

    def dedup_split(split_items: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], int]:
        seen: set[str] = set()
        output: list[dict[str, Any]] = []
        duplicates = 0
        for item in split_items:
            key = item["dedup_key"]
            if key in seen:
                duplicates += 1
                continue
            seen.add(key)
            output.append(item)
        return output, duplicates

    test, test_dups = dedup_split(test)
    test_keys = {item["dedup_key"] for item in test}
    train, train_dups = dedup_split(train)
    train_before_leak_filter = len(train)
    train = [item for item in train if item["dedup_key"] not in test_keys]
    train_removed_for_test_overlap = train_before_leak_filter - len(train)

    stats = {
        "train_duplicates_removed": train_dups,
        "test_duplicates_removed": test_dups,
        "train_removed_for_test_overlap": train_removed_for_test_overlap,
        "train_test_overlap_after_filter": len({item["dedup_key"] for item in train} & test_keys),
    }
    return train + test, stats


TOKEN_PATTERN = re.compile(r"\w+|[^\w\s]", re.UNICODE)


def get_token_counter() -> tuple[str, Callable[[str], int]]:
    try:
        import tiktoken  # type: ignore

        encoding = tiktoken.get_encoding("cl100k_base")
        return "cl100k_base via tiktoken", lambda text: len(encoding.encode(text or ""))
    except Exception:
        return "regex_approx_v1", lambda text: len(TOKEN_PATTERN.findall(text or ""))


def input_text(example: dict[str, Any]) -> str:
    choices = "\n".join(f"{choice['label']}. {choice['text']}" for choice in example["choices"])
    image_hint = f"\n[image: {example['image']['path']}]" if example.get("image") else ""
    return f"{example['question']}{image_hint}\n{choices}"


def compute_stats(examples: list[dict[str, Any]], source_stats: dict[str, Any], dedup_stats: dict[str, Any]) -> dict[str, Any]:
    tokenizer_name, count_tokens = get_token_counter()

    def empty_bucket() -> dict[str, Any]:
        return {
            "num_examples": 0,
            "input_tokens": 0,
            "support_tokens": 0,
            "full_record_tokens": 0,
            "image_examples": 0,
            "text_examples": 0,
        }

    buckets: dict[str, dict[str, Any]] = defaultdict(empty_bucket)
    by_dataset: dict[str, dict[str, Any]] = defaultdict(empty_bucket)
    by_modality = Counter()

    for example in examples:
        serialized = json.dumps(example, ensure_ascii=False, sort_keys=True)
        support = example.get("support") or ""
        values = {
            "num_examples": 1,
            "input_tokens": count_tokens(input_text(example)),
            "support_tokens": count_tokens(support),
            "full_record_tokens": count_tokens(serialized),
            "image_examples": 1 if example.get("image") else 0,
            "text_examples": 0 if example.get("image") else 1,
        }
        keys = [
            "overall",
            f"split::{example['split']}",
        ]
        dataset_key = f"{example['dataset']}|{example.get('subset')}"
        by_modality[example["modality"]] += 1
        for key in keys:
            for stat_key, value in values.items():
                buckets[key][stat_key] += value
        for stat_key, value in values.items():
            by_dataset[dataset_key][stat_key] += value

    def finalize(bucket: dict[str, Any]) -> dict[str, Any]:
        count = bucket["num_examples"]
        output = dict(bucket)
        if count:
            output["avg_input_tokens"] = round(bucket["input_tokens"] / count, 2)
            output["avg_support_tokens"] = round(bucket["support_tokens"] / count, 2)
            output["avg_full_record_tokens"] = round(bucket["full_record_tokens"] / count, 2)
        else:
            output["avg_input_tokens"] = 0
            output["avg_support_tokens"] = 0
            output["avg_full_record_tokens"] = 0
        return output

    stats = {
        "name": "general_science_release",
        "version": "v0.1-local",
        "generated_at_utc": datetime.now(timezone.utc).isoformat(),
        "seed": SEED,
        "tokenizer": {
            "name": tokenizer_name,
            "note": "Token counts are computed over question+choices(+image placeholder), support, and serialized full JSON record.",
        },
        "splits": {
            "train": finalize(buckets["split::train"]),
            "test": finalize(buckets["split::test"]),
            "overall": finalize(buckets["overall"]),
        },
        "by_dataset": {key: finalize(value) for key, value in sorted(by_dataset.items())},
        "by_modality": dict(by_modality),
        "source_files": source_stats,
        "deduplication": dedup_stats,
        "sources": SOURCE_LICENSES,
        "outputs": {
            "train": str(TRAIN_PATH.relative_to(RELEASE_DIR)),
            "test": str(TEST_PATH.relative_to(RELEASE_DIR)),
            "stats": str(STATS_PATH.relative_to(RELEASE_DIR)),
            "card": str(CARD_PATH.relative_to(RELEASE_DIR)),
            "readme": str(README_PATH.relative_to(RELEASE_DIR)),
            "scienceqa_images": str(IMAGE_DIR.relative_to(RELEASE_DIR)),
        },
    }
    return stats


def write_jsonl(path: Path, examples: list[dict[str, Any]]) -> None:
    with path.open("w", encoding="utf-8") as handle:
        for example in examples:
            handle.write(json.dumps(example, ensure_ascii=False) + "\n")


def markdown_table(rows: list[list[Any]], headers: list[str]) -> str:
    lines = [
        "| " + " | ".join(headers) + " |",
        "| " + " | ".join("---" for _ in headers) + " |",
    ]
    for row in rows:
        lines.append("| " + " | ".join(str(cell) for cell in row) + " |")
    return "\n".join(lines)


def write_card(stats: dict[str, Any]) -> None:
    source_rows = []
    for dataset, info in SOURCE_LICENSES.items():
        source_rows.append([
            dataset,
            "ARC-Challenge, ARC-Easy" if dataset == "allenai/ai2_arc" else "`null`",
            info["license"],
            info["license_source"],
            info["url"],
        ])

    split_rows = []
    for split_name in ["train", "test", "overall"]:
        split = stats["splits"][split_name]
        split_rows.append([
            split_name,
            split["num_examples"],
            split["image_examples"],
            split["text_examples"],
            split["avg_input_tokens"],
            split["avg_support_tokens"],
            split["avg_full_record_tokens"],
        ])

    dataset_rows = []
    for key, value in stats["by_dataset"].items():
        dataset, subset = key.split("|", 1)
        dataset_rows.append([
            dataset,
            subset,
            value["num_examples"],
            value["image_examples"],
            value["avg_input_tokens"],
            value["avg_support_tokens"],
        ])

    card = f"""# General Science QA Release

## Summary

This release consolidates local science QA snapshots into a unified JSONL format for text and image-text multiple-choice science QA.
It is built from local parquet files only and stops before any public upload.

## Output Files

- `train.jsonl`
- `test.jsonl`
- `stats.json`
- `images/scienceqa/`
- `general_science_card.md`
- `README.md`

## Sources

{markdown_table(source_rows, ["Dataset", "Subset", "License", "License source", "URL"])}

OpenBookQA is present locally but is not included in this main release because its license is not confirmed in the local snapshot. It can be added later as an internal/optional extension after license confirmation.

## Split Construction

- Upstream `train` and `validation` splits are merged into `train.jsonl`.
- Upstream `test` splits are kept as the held-out `test.jsonl`.
- Train/test leakage is checked using normalized question, choices, and answer text.
- If a normalized duplicate appears in held-out test, the matching train example is removed.

## Schema

```json
{{
  "id": "string",
  "dataset": "string",
  "subset": "string or null",
  "split": "train or test",
  "task_type": "multiple_choice_science_qa",
  "modality": "text or image_text",
  "question": "string",
  "image": null,
  "choices": [
    {{"label": "A", "text": "string"}}
  ],
  "answer_label": "string",
  "answer_text": "string",
  "support": "string or null",
  "source_meta": {{}}
}}
```

For ScienceQA image examples, `image` is:

```json
{{"path": "images/scienceqa/<id>.png", "mime_type": "image/png"}}
```

## Counts and Token Statistics

Tokenizer: `{stats["tokenizer"]["name"]}`.

{markdown_table(split_rows, ["Split", "Examples", "Image examples", "Text examples", "Avg input tokens", "Avg support tokens", "Avg full record tokens"])}

## Counts by Dataset

{markdown_table(dataset_rows, ["Dataset", "Subset", "Examples", "Image examples", "Avg input tokens", "Avg support tokens"])}

## Modality Distribution

{markdown_table([[key, value] for key, value in sorted(stats["by_modality"].items())], ["Modality", "Count"])}

## Deduplication

```json
{json.dumps(stats["deduplication"], ensure_ascii=False, indent=2)}
```

## Construction Notes

- SciQ: combines `distractor1`, `distractor2`, `distractor3`, and `correct_answer`, then deterministically shuffles choices.
- AI2 ARC: uses both `ARC-Challenge` and `ARC-Easy`; finds the answer text from `answerKey`, then deterministically shuffles choices.
- ScienceQA: keeps `subject == "natural science"` examples with at least four choices and a valid answer index. Images embedded as parquet bytes are exported to `images/scienceqa/`.
- Choices with more than four options are retained; labels are regenerated from `A`.

## License Notes

This release combines multiple upstream datasets. Downstream redistribution must satisfy all upstream licenses.
ScienceQA license metadata was not present in the local snapshot available to this build; verify the upstream license before public HF/ModelScope upload.

## Recommended Evaluation Input

For model evaluation, use `question`, `image`, and `choices`.
Do not feed `support` unless the task explicitly allows explanations or retrieval context, because `support` may contain answer-revealing information.
"""
    CARD_PATH.write_text(card, encoding="utf-8")
    README_PATH.write_text(card, encoding="utf-8")


def main() -> int:
    RELEASE_DIR.mkdir(parents=True, exist_ok=True)
    IMAGE_DIR.mkdir(parents=True, exist_ok=True)

    raw_items, source_stats = collect_items()
    deduped_items, dedup_stats = deduplicate(raw_items)
    examples = [build_example(item) for item in deduped_items]

    train = [example for example in examples if example["split"] == "train"]
    test = [example for example in examples if example["split"] == "test"]
    write_jsonl(TRAIN_PATH, train)
    write_jsonl(TEST_PATH, test)

    stats = compute_stats(examples, source_stats, dedup_stats)
    STATS_PATH.write_text(json.dumps(stats, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    write_card(stats)

    print(f"Train: wrote {len(train)} examples to {TRAIN_PATH.name}")
    print(f"Test: wrote {len(test)} examples to {TEST_PATH.name}")
    print(f"Total: wrote {len(examples)} examples")
    print(f"Image examples: {stats['splits']['overall']['image_examples']}")
    print(f"Dataset card: {CARD_PATH.name}")
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except Exception as exc:
        print(f"Error: {exc}", file=sys.stderr)
        raise SystemExit(1) from exc