File size: 4,507 Bytes
25b60ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Build the self-contained SciArgEU explorer (one HTML file, no external dependencies).

Reads the full-dataset JSONL, de-duplicates rubrics/questions, embeds everything as JSON
inside an HTML template and writes explorer/sciarg_eu_explorer.html.

    python scripts/build_sciarg_eu_explorer.py
    python scripts/build_sciarg_eu_explorer.py --input data/eu/sciarg_eu_all.jsonl --output explorer/sciarg_eu_explorer.html

The output embeds every student answer, so it carries the dataset's CC-BY-4.0 terms.
Re-run it whenever the JSONL changes; the HTML is a generated file.
"""
import argparse, json, re, sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
TOPIC_ORDER = {"sound": 0, "biodiversity": 1, "txikipedia": 2}
CTX_BINS = {1: "1-2", 2: "1-2", 3: "3-4", 4: "3-4", 5: "5-6", 6: "5-6", 7: "7-8", 8: "7-8", 9: "9-10", 10: "9-10"}


def ctx_bin(v):
    """context_rating is numeric (1-10) or a range string such as '7-8 (Oso ongi)'."""
    if v is None:
        return "unspecified"
    m = re.match(r"\s*(\d+)", str(v))
    if not m or int(m.group(1)) not in CTX_BINS:
        sys.exit(f"Unrecognised context_rating: {v!r}")
    return CTX_BINS[int(m.group(1))]


def build(src: Path, template: Path, dst: Path, img_base: str) -> None:
    rows = [json.loads(l) for l in src.read_text(encoding="utf-8").splitlines() if l.strip()]
    rubrics, rubric_json, groups, items, out, seen = {}, {}, {}, {}, [], set()
    for r in rows:
        rid, g = r["rubric_id"], r["question_group_id"]
        if r["response_id"] in seen:
            sys.exit(f"Duplicate response_id: {r['response_id']}")
        seen.add(r["response_id"])
        lv = sorted(r["rubric"], key=lambda x: x["ordinal_rank"])
        canon = json.dumps(lv, sort_keys=True, ensure_ascii=False)
        if rid not in rubrics:
            rubric_json[rid] = canon
            rubrics[rid] = {"levels": [{"l": x["label"], "d": x["description"], "r": x["ordinal_rank"]} for x in lv],
                            "max": max(x["ordinal_rank"] for x in lv), "guidance": r.get("rubric_guidance")}
        elif rubric_json[rid] != canon:
            sys.exit(f"{r['response_id']}: rubric differs from the first record of {rid}")
        if r["label"] not in {x["l"] for x in rubrics[rid]["levels"]}:
            sys.exit(f"{r['response_id']}: label {r['label']!r} not in rubric {rid}")
        groups.setdefault(g, {"t": r["topic"], "rid": rid, "items": []})
        if r["question_id"] not in groups[g]["items"]:
            groups[g]["items"].append(r["question_id"])
        items.setdefault(r["question_id"], {"g": g, "t": r["topic"], "txt": r["question"],
                                             "fig": r.get("figure_id"), "img": r.get("image_path")})
        out.append([r["response_id"], r["question_id"], r["label"],
                    (r["academic_year"] or "unspecified").replace("/", "-"),
                    r["assessment_phase"] or "unspecified", r["group_type"] or "unspecified",
                    ctx_bin(r["context_rating"]),
                    None if r["context_rating"] is None else str(r["context_rating"]),
                    r["instructor_comment"], r["student_answer"] or ""])
    groups = {g: groups[g] for g in sorted(groups, key=lambda g: (TOPIC_ORDER.get(groups[g]["t"], 9), g))}
    items = {q: items[q] for q in sorted(items, key=lambda q: (TOPIC_ORDER.get(items[q]["t"], 9), items[q]["g"], q))}
    data = {"rubrics": rubrics, "groups": groups, "items": items, "rows": out, "source": src.name, "imgBase": img_base}
    js = json.dumps(data, ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/")
    dst.parent.mkdir(parents=True, exist_ok=True)
    dst.write_text(template.read_text(encoding="utf-8").replace("__DATA__", js), encoding="utf-8")
    print(f"{len(out)} responses, {len(js)//1024} KB data -> {dst}")


if __name__ == "__main__":
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--input", type=Path, default=ROOT / "data/eu/sciarg_eu_all.jsonl")
    ap.add_argument("--template", type=Path, default=ROOT / "scripts/templates/sciarg_eu_explorer.template.html")
    ap.add_argument("--output", type=Path, default=ROOT / "explorer/sciarg_eu_explorer.html")
    ap.add_argument("--image-base", default="../", help="prefix turning image_path into a URL relative to the output file")
    a = ap.parse_args()
    build(a.input, a.template, a.output, a.image_base)