File size: 4,754 Bytes
c1c9129
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Validate local dataset structure and provenance; does not prove mathematics.

Run from any working directory. --load-dataset also exercises Hugging Face's
actual JSON loader against the local file with network access disabled.
"""
from __future__ import annotations

import argparse
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile

ROOT = Path(__file__).resolve().parents[1]


def require(condition, message):
    if not condition:
        raise ValueError(message)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--load-dataset", action="store_true")
    args = parser.parse_args()
    try:
        import yaml
        card = (ROOT / "README.md").read_text(encoding="utf-8")
        require(card.startswith("---\n"), "Dataset card lacks YAML front matter")
        metadata = yaml.safe_load(card.split("---", 2)[1])
        config = metadata["configs"][0]
        require(config["config_name"] == "default", "Unexpected default configuration")
        require(config["data_files"] == [{"split": "train", "path": "data/research_records.jsonl"}],
                "Dataset configuration must select exactly the corpus JSONL")

        spec = importlib.util.spec_from_file_location("release_uploader", ROOT / "upload_dataset.py")
        uploader = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(uploader)
        files = uploader.verify_release(ROOT)
        require(uploader.DATASET_TYPE == "dataset", "Uploader repository type is incorrect")

        data_path = ROOT / "data" / "research_records.jsonl"
        raw = data_path.read_bytes()
        records = [json.loads(line) for line in raw.decode("utf-8").splitlines() if line]
        inventory = json.loads((ROOT / "metadata" / "record_inventory.json").read_text())
        require(len(records) == inventory["record_count"], "Inventory row count mismatch")
        require(hashlib.sha256(raw).hexdigest() == inventory["data_sha256"], "Inventory corpus hash mismatch")
        require(len({r["record_id"] for r in records}) == len(records), "Duplicate record identifier")
        schema = {k: type(v) for k, v in records[0].items()}
        require(all({k: type(v) for k, v in r.items()} == schema for r in records), "Inconsistent JSON row schema")
        for row in records:
            source = ROOT / row["source_file"]
            require(source.is_file(), "Missing source: " + row["source_file"])
            require(hashlib.sha256(source.read_bytes()).hexdigest() == row["source_sha256"],
                    "Source hash mismatch: " + row["source_file"])
        subprocess.run([sys.executable, str(ROOT / "code" / "build_records.py"), "--check-only"],
                       cwd=ROOT, check=True, stdout=subprocess.PIPE, text=True)
        pdf = ROOT / "manuscript" / "Xiorume_Kai_Delta_Manuscript.pdf"
        require(pdf.read_bytes().startswith(b"%PDF-"), "Manuscript is not a PDF")

        report = {
            "status": "passed", "repo_type": uploader.DATASET_TYPE,
            "records": len(records), "schema_columns": len(schema),
            "source_documents": inventory["record_type_counts"]["source_document"],
            "mathematical_result_records": len(records) - inventory["record_type_counts"]["source_document"],
            "checksum_files": len(files), "data_sha256": inventory["data_sha256"],
            "dataset_card_yaml": "parsed", "source_hashes": "passed",
            "deterministic_extraction": "passed", "mathematical_validity_certified": False,
        }
        if args.load_dataset:
            os.environ["HF_HUB_OFFLINE"] = "1"
            os.environ["HF_DATASETS_OFFLINE"] = "1"
            import datasets
            datasets.disable_progress_bars()
            with tempfile.TemporaryDirectory(prefix="xiorume_dataset_check_") as cache:
                corpus = datasets.load_dataset("json", data_files=str(data_path), split="train",
                                               cache_dir=cache, keep_in_memory=True)
                require(len(corpus) == len(records), "Hugging Face loader row count mismatch")
                require(set(corpus.column_names) == set(schema), "Hugging Face loader schema mismatch")
            report["hugging_face_loader"] = "passed_offline"
            report["datasets_version"] = datasets.__version__
        print(json.dumps(report, indent=2, ensure_ascii=False))
        return 0
    except (OSError, ValueError, KeyError, ImportError, subprocess.CalledProcessError) as error:
        print("Release validation failed: " + str(error), file=sys.stderr)
        return 1


if __name__ == "__main__":
    raise SystemExit(main())