File size: 5,116 Bytes
1e02da8
 
 
 
 
 
 
 
 
 
 
4b5c805
1e02da8
 
 
 
 
 
 
 
4b5c805
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e02da8
cd53a71
 
 
 
 
1e02da8
 
 
cd53a71
 
1e02da8
 
 
 
 
 
 
 
 
 
 
 
 
4b5c805
 
 
 
 
1e02da8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd53a71
 
 
1e02da8
 
 
 
 
 
 
 
 
 
 
 
 
 
4b5c805
 
 
 
 
1e02da8
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Phase 3: apply LLM-classifier decisions to queued xref edges.

The classifier's decisions live in data/xref_review_decisions.json and were
made ONLY from supplied verse text + corpus evidence (see that file's note).
This script is deterministic: it matches decisions to queued edges, fills
relation + records the rationale, and keeps review_status='queue' with
human_reviewed=false. Human review flips edges to accepted.
"""
import json
import math
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
DATA_DIR = ROOT / "data"

def main():
    dec = json.loads((DATA_DIR / "xref_review_decisions.json").read_text(encoding="utf-8"))
    edges = [json.loads(l) for l in (DATA_DIR / "xref_edges.jsonl").open(encoding="utf-8")]
    # corpus IDF for lexical edges the classifier CREATES (same formula as
    # build_xrefs shared_lemma edges): rarest shared lemma of the verse pair
    df_lemma = {}
    verse_lemmas = {}
    for wf in sorted(DATA_DIR.glob("words_[0-9]*.jsonl")):
        for line in wf.open(encoding="utf-8"):
            w = json.loads(line)
            s, a, _ = w["ref"].split(":")
            v = f"{s}:{a}"
            lem = w.get("lemma")
            if lem:
                df_lemma.setdefault(lem, set()).add(v)
                verse_lemmas.setdefault(v, set()).add(lem)

    def lexical_idf(v_from, v_to):
        shared = verse_lemmas.get(v_from, set()) & verse_lemmas.get(v_to, set())
        if not shared:
            return None, None, None
        lem = min(shared, key=lambda l: len(df_lemma[l]))
        w = round(math.log(6236 / max(len(df_lemma[lem]), 1)) + 2.0, 3)
        return w, "shared_lemma", lem

    applied = 0
    def _already_created(m, d) -> bool:
        return any(e["from"] == m["from"] and e["to"] == m["to"] and e["source"] == m["source"]
                   and e.get("relation") == d["relation"] and e.get("classifier_rationale") == d["rationale"]
                   for e in edges)

    for d in dec["decisions"]:
        m = d["match"]
        if d.get("create"):
            if _already_created(m, d):
                continue
            edges.append({
                "from": m["from"],
                "to": m["to"],
                "source": m["source"],
                "relation": d["relation"],
                "evidence": d.get("evidence", {"kind": "llm_review"}),
                "citing_mufassir": m.get("citing_mufassir"),
                "confidence": 0.85,
                "human_reviewed": False,
                "review_status": "queue",
                "classifier_rationale": d["rationale"],
                "classified_by": dec["classifier"],
            })
            if m["source"] == "lexical":
                w, kind_name, shared = lexical_idf(m["from"], m["to"])
                if w is not None:
                    edges[-1]["evidence"]["idf_weight"] = w
                    edges[-1]["evidence"][kind_name] = shared
            applied += 1
            continue
        matched = False
        for e in edges:
            if e["from"] == m["from"] and e["to"] == m["to"] and e["source"] == m["source"] and e["relation"] is None:
                ev_kind = m.get("evidence_kind")
                if ev_kind and e["evidence"].get("kind") != ev_kind:
                    continue
                e["relation"] = d["relation"]
                e["classifier_rationale"] = d["rationale"]
                e["classified_by"] = dec["classifier"]
                e["review_status"] = "queue"
                e["human_reviewed"] = False
                applied += 1
                matched = True
                break
        if not matched:
            if _already_created(m, d):
                matched = True
                continue
            # classifier-created edge (e.g. narrative link not present in citation graph)
            edges.append({
                "from": m["from"],
                "to": m["to"],
                "source": m["source"],
                "relation": d["relation"],
                "evidence": {"kind": "llm_review", "basis": "classifier decision from supplied verse texts + corpus evidence"},
                "citing_mufassir": m.get("citing_mufassir"),
                "confidence": 0.8,
                "human_reviewed": False,
                "review_status": "queue",
                "classifier_rationale": d["rationale"],
                "classified_by": dec["classifier"],
            })
            if m["source"] == "lexical":
                w, kind_name, shared = lexical_idf(m["from"], m["to"])
                if w is not None:
                    edges[-1]["evidence"]["idf_weight"] = w
                    edges[-1]["evidence"][kind_name] = shared
            applied += 1
    with (DATA_DIR / "xref_edges.jsonl").open("w", encoding="utf-8") as f:
        for e in edges:
            f.write(json.dumps(e, ensure_ascii=False) + "\n")
    rel = sum(1 for e in edges if e.get("relation"))
    print(f"classifier decisions applied: {applied}; edges with relation: {rel}/{len(edges)} (rest queued unclassified)")

if __name__ == "__main__":
    main()