File size: 3,425 Bytes
545c42e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Build schema-stable JSONL files for the Hugging Face Dataset Viewer."""

from __future__ import annotations

import json
import re
from pathlib import Path
from typing import Any


ROOT = Path(__file__).resolve().parents[1]
OUTPUT_DIR = ROOT / "viewer"
IMAGE_TOKEN = re.compile(r"<image:([^>]+)>")

CONFIGS = {
    "implicit_pattern": (
        "Implicit Pattern Induction",
        "Implicit Pattern Generation",
        86,
    ),
    "symbolic_constraint": (
        "Ad-hoc Constraint Execution",
        "Symbolic Constraint Generation",
        153,
    ),
    "visual_constraint": (
        "Ad-hoc Constraint Execution",
        "Visual Constraint Generation",
        60,
    ),
    "prior_conflicting": (
        "Contextual Knowledge Adaptation",
        "Prior-Conflicting Generation",
        101,
    ),
    "multi_semantic": (
        "Contextual Knowledge Adaptation",
        "Multi-Semantic Generation",
        110,
    ),
}


def normalize_hint(value: Any) -> str | None:
    """Represent every optional hint as one nullable string column."""
    if value is None:
        return None
    if isinstance(value, str):
        return value
    if isinstance(value, list) and all(isinstance(item, str) for item in value):
        return "\n".join(value)
    raise TypeError(f"Unsupported hint value: {value!r}")


def image_paths(config_name: str, row: dict[str, Any]) -> list[str]:
    """Resolve ordered, unique image tokens to repository-relative paths."""
    text_parts = [
        row.get("context", ""),
        row.get("instruction", ""),
        row.get("rc_hint", ""),
        normalize_hint(row.get("vc_hint")) or "",
    ]
    names = IMAGE_TOKEN.findall("\n".join(text_parts))
    return list(dict.fromkeys(f"{config_name}/images/{name}.png" for name in names))


def build_config(config_name: str, dimension: str, task: str, expected: int) -> int:
    source_path = ROOT / config_name / "test_data.json"
    rows = json.loads(source_path.read_text(encoding="utf-8"))
    if not isinstance(rows, list) or len(rows) != expected:
        raise ValueError(f"{source_path}: expected {expected} rows, found {len(rows)}")

    output_path = OUTPUT_DIR / f"{config_name}.jsonl"
    with output_path.open("w", encoding="utf-8") as output:
        for source in rows:
            record = {
                "id": source["id"],
                "dimension": dimension,
                "task": task,
                "sub_dimension": source["sub_dimension"],
                "sub_sub_dimension": source.get("sub_sub_dimension"),
                "context": source["context"],
                "instruction": source["instruction"],
                "rc_hint": source["rc_hint"],
                "vc_hint": normalize_hint(source.get("vc_hint")),
                "image_paths": image_paths(config_name, source),
            }
            output.write(json.dumps(record, ensure_ascii=False, separators=(",", ":")))
            output.write("\n")
    return len(rows)


def main() -> None:
    OUTPUT_DIR.mkdir(exist_ok=True)
    total = sum(
        build_config(config_name, dimension, task, expected)
        for config_name, (dimension, task, expected) in CONFIGS.items()
    )
    if total != 510:
        raise ValueError(f"Expected 510 total rows, found {total}")
    print(f"Wrote {total} records across {len(CONFIGS)} files to {OUTPUT_DIR}")


if __name__ == "__main__":
    main()