File size: 4,141 Bytes
e5277d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Validate every Dataset Card configuration with Hugging Face Datasets.

This script performs a real local load_dataset call. It deliberately does
not contact the Hub and therefore does not validate publication, visibility,
the Dataset Viewer, or the platform-generated Croissant endpoint.
"""

from __future__ import annotations

import argparse
import csv
import json
import sys
from pathlib import Path

import yaml


def read_card(root: Path) -> dict:
    text = (root / "README.md").read_text(encoding="utf-8")
    if not text.startswith("---\n"):
        raise ValueError("README.md must begin with YAML frontmatter")
    return yaml.safe_load(text.split("---", 2)[1]) or {}


def csv_fallback(root: Path, configs: list[dict]) -> list[dict]:
    """Dependency-light structural load; not a substitute for datasets."""
    results = []
    for config in configs:
        name = config["config_name"]
        specs = config.get("data_files") or []
        if len(specs) != 1:
            raise ValueError(f"{name}: expected exactly one data_files entry")
        spec = specs[0]
        path = root / spec["path"]
        with path.open(newline="", encoding="utf-8-sig") as handle:
            reader = csv.DictReader(handle)
            rows = sum(1 for _ in reader)
            columns = list(reader.fieldnames or [])
        results.append(
            {
                "configuration": name,
                "split": spec["split"],
                "path": spec["path"],
                "rows": rows,
                "columns": columns,
                "loader": "python.csv",
                "status": "PASS",
            }
        )
    return results


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("root", nargs="?", default=".")
    parser.add_argument(
        "--require-hf-datasets",
        action="store_true",
        help="fail instead of using the CSV structural fallback",
    )
    parser.add_argument("--json-out")
    args = parser.parse_args()
    root = Path(args.root).resolve()
    configs = read_card(root).get("configs") or []

    try:
        from datasets import get_dataset_config_names, load_dataset
    except ImportError as exc:
        if args.require_hf_datasets:
            print(
                "Hugging Face Datasets is not installed. Install "
                "requirements-validation.txt before using "
                "--require-hf-datasets.",
                file=sys.stderr,
            )
            return 2
        results = csv_fallback(root, configs)
        report = {
            "status": "PASS_STRUCTURAL_CSV_ONLY",
            "hf_datasets_clean_load": "NOT_RUN_DEPENDENCY_UNAVAILABLE",
            "detail": str(exc),
            "configurations": results,
        }
    else:
        expected = [item["config_name"] for item in configs]
        discovered = get_dataset_config_names(str(root))
        if discovered != expected:
            raise RuntimeError(
                f"configuration mismatch: expected {expected}, got {discovered}"
            )
        results = []
        for config in configs:
            name = config["config_name"]
            spec = config["data_files"][0]
            dataset = load_dataset(
                str(root),
                name=name,
                split=spec["split"],
            )
            results.append(
                {
                    "configuration": name,
                    "split": spec["split"],
                    "rows": dataset.num_rows,
                    "columns": dataset.column_names,
                    "loader": "datasets.load_dataset",
                    "status": "PASS",
                }
            )
        report = {
            "status": "PASS_LOCAL_HF_DATASETS_CLEAN_LOAD",
            "hf_datasets_clean_load": "PASS",
            "configurations": results,
        }

    rendered = json.dumps(report, indent=2, sort_keys=True) + "\n"
    if args.json_out:
        Path(args.json_out).write_text(rendered, encoding="utf-8")
    print(rendered, end="")
    return 0


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