File size: 12,408 Bytes
fb9a4be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Convert the Eedi Misconceptions Graph CSV release (construct-map.csv /
misconception-map.csv) into property-graph JSONL (nodes.jsonl /
relationships.jsonl): one file of nodes, one file of relationships.

Source: https://huggingface.co/datasets/Eedi/Eedi-Misconceptions-Graph (CC BY 4.0)

Graph model
-----------
  (:Subject)-[:SUBJECT_CONTAINS_TOPIC]->(:Topic)
  (:Topic)-[:TOPIC_CONTAINS_SUBTOPIC]->(:SubTopic)
  (:SubTopic)-[:SUBTOPIC_CONTAINS_CONSTRUCT]->(:Construct)
  (:Construct)-[:CONSTRUCT_HAS_MISCONCEPTION {percentage}]->(:Misconception)

Node ids are type-prefixed (eedi:construct:27) because Construct ids overlap
with Subject/Topic/SubTopic ids.

Usage
-----
  python csv_to_jsonl.py                    # write nodes.jsonl / relationships.jsonl next to this script
  python csv_to_jsonl.py --csv-dir my/csvs  # use CSVs from somewhere else

CSVs are read from ../data/ when this script sits in a clone of the Hugging Face
repo (scripts/ next to data/); otherwise they're downloaded next to this script.

Standard library only.
"""
# How this works, in one paragraph
# --------------------------------
# The CSVs are "flat": every row repeats the whole Subject -> Topic -> SubTopic ->
# Construct chain. A graph wants each of those things stored ONCE as a node, with
# relationships joining them. So we walk every row, register each node/relationship
# in a dictionary keyed by its id (a repeat of something already seen is simply a
# no-op), and at the end write the de-duplicated contents out as JSONL.
#
# JSONL ("JSON Lines") = one complete JSON object per line. It streams well (no
# need to parse one giant JSON array), and it's database-agnostic - Neo4j is just
# one possible consumer.
#
#   nodes.jsonl         {"id": ..., "labels": [...], "properties": {...}}
#   relationships.jsonl {"type": ..., "startNodeId": ..., "endNodeId": ..., "properties": {...}}

# Lets us write type hints like `dict | None` on older Pythons (3.8/3.9).
from __future__ import annotations

import argparse
import csv
import json
import sys
import urllib.request
from collections import Counter
from pathlib import Path

# `resolve/{tag}` is Hugging Face's "raw file at this revision" URL. Pinning a tag
# (rather than `main`) means the same command always gets the same data.
CSV_URL = "https://huggingface.co/datasets/Eedi/Eedi-Misconceptions-Graph/resolve/{tag}/data/{name}"
DEFAULT_TAG = "v1.0"
CSV_NAMES = ("construct-map.csv", "misconception-map.csv")

# Folder this script lives in - used as the default place to read/write files, so
# the script behaves the same whichever directory you run it from.
SCRIPT_DIR = Path(__file__).resolve().parent
# In a clone of the Hugging Face repo the CSVs already sit in data/, beside scripts/.
REPO_DATA_DIR = SCRIPT_DIR.parent / "data"

# The curriculum tree, top to bottom. Each tuple says how to build one level:
#   (node label, CSV id column, id property name in the graph, CSV name column, parent label)
# Both CSVs contain these same columns, so one table drives the hierarchy for both.
# The graph property names are just the CSV column names in camelCase.
HIERARCHY = [
    ("Subject", "SubjectSubjectId", "subjectSubjectId", "SubjectName", None),
    ("Topic", "TopicSubjectId", "topicSubjectId", "TopicName", "Subject"),
    ("SubTopic", "SubTopicSubjectId", "subTopicSubjectId", "SubTopicName", "Topic"),
    ("Construct", "ConstructId", "constructId", "ConstructName", "SubTopic"),
]
# Relationship type that points INTO each child level from its parent.
CONTAINS = {
    "Topic": "SUBJECT_CONTAINS_TOPIC",
    "SubTopic": "TOPIC_CONTAINS_SUBTOPIC",
    "Construct": "SUBTOPIC_CONTAINS_CONSTRUCT",
}


def node_id(label: str, value: int) -> str:
    """Construct, 27 -> eedi:construct:27

    Why prefix? The raw integer ids aren't unique across types. Subject/Topic/
    SubTopic ids come from one SQL table, so they never clash with each other,
    but Construct ids are a separate sequence (e.g. 49 is both Subject
    'Algebra' and Construct 'Find 10 less than a given number').

    Strictly only Constructs need separating, but every type gets its own prefix
    anyway: one simple rule, ids that say what they are (eedi:topic:144), and no
    reliance on the shared-table guarantee holding in future versions."""
    return f"eedi:{label.lower()}:{value}"


def download(tag: str, dest: Path) -> None:
    """Fetch any CSV not already in `dest`. Existing files are reused, so delete
    them if you want a fresh copy (e.g. after changing --tag)."""
    dest.mkdir(parents=True, exist_ok=True)
    for name in CSV_NAMES:
        p = dest / name
        if not p.exists():
            print(f"Downloading {name} ({tag}) ...")
            urllib.request.urlretrieve(CSV_URL.format(tag=tag, name=name), p)


def default_csv_dir() -> Path:
    """Use the repo's data/ folder if both CSVs are there, else this script's folder
    (where download() will fetch them). Also used by load_eedi_graph.py."""
    if all((REPO_DATA_DIR / name).is_file() for name in CSV_NAMES):
        return REPO_DATA_DIR
    return SCRIPT_DIR


def read_csv(path: Path) -> list[dict]:
    """Read a CSV into a list of {column: value} dicts (all values are strings).

    newline=""          - required by the csv module so quoted fields containing
                          line breaks are handled correctly.
    encoding=utf-8-sig  - plain UTF-8, but silently drops a byte-order mark if the
                          file was saved by Excel (otherwise the first column name
                          would come out as '\\ufeffSubjectName')."""
    with open(path, newline="", encoding="utf-8-sig") as f:
        return list(csv.DictReader(f))


class Graph:
    """Collects nodes/relationships, refusing conflicting duplicates.

    Everything is stored in dicts keyed by identity, so adding the same node or
    relationship twice is harmless - that's what de-duplicates the flat CSV rows.
    But if the "same" thing arrives with DIFFERENT content (e.g. construct 27 with
    two different names), we stop: that means the source data has changed shape
    and silently picking one version would hide the problem."""

    def __init__(self):
        self.nodes: dict[str, dict] = {}    # node id -> node record
        self.rels: dict[tuple, dict] = {}   # (type, start id, end id) -> relationship record
        self.parent: dict[str, str] = {}    # child node id -> parent node id (tree check)

    def add_node(self, label: str, id_prop: str, raw_id: str, name: str) -> str:
        """Register a node (if new) and return its id."""
        value = int(raw_id.strip())  # CSV gives strings; store ids as integers in the graph
        nid = node_id(label, value)
        node = {"id": nid, "labels": [label], "properties": {id_prop: value, "name": name.strip()}}
        # setdefault: "insert `node` if nid is new; either way, give me what's stored".
        # So `existing` is either this node (first sighting) or the earlier one.
        existing = self.nodes.setdefault(nid, node)
        if existing != node:
            sys.exit(f"Conflicting definitions for {nid}:\n  {existing}\n  {node}")
        return nid

    def add_rel(self, rtype: str, start: str, end: str, props: dict | None = None) -> None:
        """Register a relationship (if new). Same setdefault trick as add_node.

        The key is (type, start, end), so there is at most one relationship of a
        given type between two nodes - matching MERGE semantics in the loader."""
        key = (rtype, start, end)
        rel = {"type": rtype, "startNodeId": start, "endNodeId": end, "properties": props or {}}
        existing = self.rels.setdefault(key, rel)
        if existing != rel:
            sys.exit(f"Conflicting definitions for {key}:\n  {existing}\n  {rel}")

    def add_hierarchy(self, row: dict) -> str:
        """Add Subject -> Topic -> SubTopic -> Construct from one row; returns the Construct id."""
        ids = {}  # label -> node id for THIS row, so each level can find its parent
        for label, id_col, id_prop, name_col, parent in HIERARCHY:
            ids[label] = self.add_node(label, id_prop, row[id_col], row[name_col])
            if parent:  # everything except Subject hangs off the level above
                # Each child has exactly one parent - catch a source change that breaks the tree.
                # (add_rel alone wouldn't notice: a second parent is a *different* key,
                # so it would just quietly add a second CONTAINS edge.)
                known = self.parent.setdefault(ids[label], ids[parent])
                if known != ids[parent]:
                    sys.exit(f"{ids[label]} has several parents: {known}, {ids[parent]}")
                self.add_rel(CONTAINS[label], ids[parent], ids[label])
        return ids["Construct"]


def build(csv_dir: Path, out_dir: Path, tag: str = DEFAULT_TAG, fetch: bool = True) -> tuple[Path, Path]:
    """CSVs -> nodes.jsonl / relationships.jsonl. Returns the two output paths.

    This is also what load_eedi_graph.py calls for its --download option."""
    if fetch:
        download(tag, csv_dir)
    for name in CSV_NAMES:
        if not (csv_dir / name).is_file():
            sys.exit(f"{csv_dir / name} not found - drop --no-download, or pass --csv-dir")

    g = Graph()

    # 1) construct-map: one row per Construct -> builds the full curriculum tree.
    for row in read_csv(csv_dir / "construct-map.csv"):
        g.add_hierarchy(row)

    # 2) misconception-map: one row per (Misconception, Construct) pair.
    #    It repeats the hierarchy columns too; re-adding them is a no-op, and it
    #    doubles as a check that both files agree on the tree.
    for row in read_csv(csv_dir / "misconception-map.csv"):
        construct = g.add_hierarchy(row)
        misconception = g.add_node("Misconception", "misconceptionId", row["MisconceptionId"], row["MisconceptionName"])
        # Share of this misconception's tags that fall in this construct (sums to ~100
        # per misconception) - stored as a property on the relationship.
        pct = float(row["PercentageMisconceptionExistsInThisConstruct"])
        g.add_rel("CONSTRUCT_HAS_MISCONCEPTION", construct, misconception, {"percentage": pct})

    # 3) Write one JSON object per line. ensure_ascii=False keeps characters like
    #    '÷' or '²' readable in the file instead of escaping them to \u00f7.
    out_dir.mkdir(parents=True, exist_ok=True)
    nodes_path, rels_path = out_dir / "nodes.jsonl", out_dir / "relationships.jsonl"
    with open(nodes_path, "w", encoding="utf-8") as f:
        for n in g.nodes.values():
            f.write(json.dumps(n, ensure_ascii=False) + "\n")
    with open(rels_path, "w", encoding="utf-8") as f:
        for r in g.rels.values():
            f.write(json.dumps(r, ensure_ascii=False) + "\n")

    # 4) Summary. `:28s` pads to 28 chars, `:>8,` right-aligns with thousands separators.
    for label, c in Counter(n["labels"][0] for n in g.nodes.values()).items():
        print(f"  nodes  {label:28s} {c:>8,}")
    for rtype, c in Counter(r["type"] for r in g.rels.values()).items():
        print(f"  rels   {rtype:32s} {c:>8,}")
    print(f"Wrote {len(g.nodes):,} nodes -> {nodes_path}")
    print(f"Wrote {len(g.rels):,} relationships -> {rels_path}")
    return nodes_path, rels_path


def main():
    # description=__doc__ reuses the module docstring at the top as the --help text.
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--csv-dir", type=Path,
                    help="where the CSVs live / are downloaded to "
                         "(default: ../data if it has them, else this script's folder)")
    ap.add_argument("--out-dir", type=Path, default=SCRIPT_DIR,
                    help="where to write the JSONL (default: this script's folder)")
    ap.add_argument("--tag", default=DEFAULT_TAG, help=f"Hugging Face revision (default {DEFAULT_TAG})")
    ap.add_argument("--no-download", action="store_true", help="never download; CSVs must already be in --csv-dir")
    args = ap.parse_args()
    build(args.csv_dir or default_csv_dir(), args.out_dir, args.tag, fetch=not args.no_download)


# Only run main() when executed as a script - not when load_eedi_graph.py imports
# this file to reuse build().
if __name__ == "__main__":
    main()