File size: 6,651 Bytes
dd5f5a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Independent serialized-artifact checks, without importing the builder."""
from collections import Counter, defaultdict
from hashlib import sha256
import json
from pathlib import Path
import re
import sys
import unicodedata

import pyarrow.parquet as pq


def normalized(text):
    return " ".join(re.findall(r"\w+", unicodedata.normalize("NFKC", text).casefold()))


def main(stage):
    papers = pq.read_table(stage / "data/papers/corpus.parquet").to_pylist()
    paragraphs = pq.read_table(stage / "data/paragraphs/corpus.parquet").to_pylist()
    packets = pq.read_table(stage / "data/claim_packets/corpus.parquet").to_pylist()
    docs = {x["id"]: x for x in papers}
    paras = {x["id"]: x for x in paragraphs}
    checks = Counter()
    errors = []
    groups, claims, paragraph_sources = defaultdict(set), defaultdict(set), defaultdict(set)
    def check(ok, kind, identity):
        checks[kind] += 1
        if not ok:
            errors.append({"check": kind, "id": identity})
    def anchor(item, identity):
        doc = docs[item["document_id"]]
        exact = doc["text"][item["source_text_start"]:item["source_text_end"]]
        check(exact == item["quote"], "exact_original_source_anchor", identity)
        check(item["paragraph_id"] in paras, "admitted_paragraph_exists", identity)
        if item["paragraph_id"] in paras:
            paragraph = paras[item["paragraph_id"]]
            check(paragraph["text"][item["paragraph_start"]:item["paragraph_end"]] == item["quote"], "paragraph_relative_anchor", identity)
            check(item["source_xpath"] == paragraph["source_xpath"], "original_XML_locator", identity)
        check(item["xml_sha256"] == doc["source_xml_sha256"], "immutable_XML_hash_link", identity)
        check(item["page"] is None and item["offset_unit"] == "unicode_code_points", "no_invented_page_or_offset_unit", identity)
    for document in papers:
        check(sha256(document["text"].encode()).hexdigest() == document["source_text_sha256"], "paper_text_SHA256", document["id"])
        check(document["rights_receipt"]["license_scope"] == "main_article_prose_only", "main_article_rights_receipt", document["id"])
        check(document["whole_document_training_eligible"] is False, "source_archive_not_whole_document_training_input", document["id"])
        groups[document["document_group"]].add(document["source_role"])
    for paragraph in paragraphs:
        document = docs[paragraph["document_id"]]
        check(document["text"][paragraph["source_text_start"]:paragraph["source_text_end"]] == paragraph["text"], "original_paragraph_span", paragraph["id"])
        paragraph_sources[normalized(paragraph["text"])].add(paragraph["document_id"])
        check(paragraph["unsupervised_training_eligible"] == (paragraph["source_role"] == "train_candidate"), "paragraph_reserved_role_not_fitted", paragraph["id"])
        for ref in paragraph["reference_spans"]:
            check(paragraph["text"][ref["start"]:ref["end"]] == ref["text"], "citation_reference_span", paragraph["id"])
    seen = set()
    for packet in packets:
        pid = packet["id"]
        check(pid not in seen, "unique_packet_id", pid)
        seen.add(pid)
        check(packet["gold_label"] is None and packet["human_review_count"] == 0 and packet["annotation_status"] == "unannotated", "no_label_or_human_review_inflation", pid)
        check(not packet["supervised_training_eligible"] and not packet["gold_evaluation_eligible"], "unannotated_ineligible_for_supervised_or_gold", pid)
        check(packet["retrieval_unsupervised_eligible"] == (packet["source_role"] == "train_candidate"), "no_unsupervised_fit_on_reserved_sources", pid)
        check(packet["claim"] == packet["claim_anchor"]["quote"], "verbatim_claim", pid)
        anchor(packet["claim_anchor"], pid)
        anchor(packet["focal_paragraph"], pid)
        for item in packet["adjacent_context"]:
            anchor(item, pid)
        claims[normalized(packet["claim"])].add((packet["document_id"], packet["source_role"]))
        for field in ("methods_candidates", "results_candidates", "limitations_candidates"):
            for context in packet[field]:
                anchor(context["anchor"], pid)
                check(context["anchor"]["paragraph_id"] != packet["claim_anchor"]["paragraph_id"], "self_paragraph_excluded", pid)
                check(normalized(packet["claim"]) not in normalized(context["anchor"]["quote"]), "normalized_claim_copy_excluded", pid)
                check(context["support_label"] is None, "retrieval_not_entailment", pid)
        for field in ("numeric_mentions", "table_references", "citation_and_cross_reference_spans"):
            for item in packet[field]:
                check(packet["claim"][item["start"]:item["end"]] == item["text"], "exact_" + field, pid)
        for challenge in packet["challenge_prompts"]:
            check(challenge["gold_answer"] is None and challenge["annotation_status"] == "unannotated", "challenge_not_fabricated_reference", pid)
    duplicate_claims = [{"normalized_claim_sha256": sha256(text.encode()).hexdigest(), "sources": sorted(values)}
                        for text, values in claims.items() if len({x[0] for x in values}) > 1]
    for text, sources in paragraph_sources.items():
        check(len(sources) == 1, "no_cross_document_normalized_admitted_paragraph", sha256(text.encode()).hexdigest())
    report = {"papers": len(papers), "paragraphs": len(paragraphs), "packets": len(packets),
              "artifact_sha256": {str(path.relative_to(stage)): sha256(path.read_bytes()).hexdigest() for path in (stage / "data").glob("*/corpus.parquet") if path.parent.name in {"papers", "paragraphs", "claim_packets"}},
              "checks": dict(checks), "assertions": sum(checks.values()), "errors": errors,
              "group_roles_exclusive": all(len(x) == 1 for x in groups.values()),
              "cross_source_normalized_claim_duplicates": duplicate_claims,
              "status": "pass" if not errors and all(len(x) == 1 for x in groups.values()) else "fail",
              "scope": "serialized source/link/provenance integrity; does not establish claim truth, political neutrality or human-label validity"}
    (stage / "integrity_report.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(json.dumps({k: v for k, v in report.items() if k not in {"checks", "cross_source_normalized_claim_duplicates"}}, indent=2))
    if report["status"] != "pass":
        raise SystemExit(1)


if __name__ == "__main__":
    main(Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).resolve().parent / "stage")