File size: 6,676 Bytes
6342c6d | 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 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | """Validate Chinese_Debate_Documents/README.md as a HuggingFace dataset card.
Checks YAML frontmatter against HF's expected keys and value shapes, and that
declared splits match `data/train-*.parquet` reality.
Exit codes: 0 = clean, 1 = warnings, 2 = errors.
Usage:
python validate_card.py [path/to/README.md]
"""
from __future__ import annotations
import json
import re
import sys
from pathlib import Path
VALID_LICENSES = {
"mit", "apache-2.0", "bsd-3-clause", "bsd-2-clause",
"cc-by-4.0", "cc-by-sa-4.0", "cc-by-nc-4.0", "cc-by-nc-sa-4.0",
"cc0-1.0", "gpl-3.0", "lgpl-3.0", "unlicense", "other",
}
VALID_SIZE = {
"n<1K", "1K<n<10K", "10K<n<100K", "100K<n<1M", "1M<n<10M", "10M<n<100M", "100M<n<1B",
}
# A non-exhaustive whitelist of HF task category strings that fit ASR + NLP.
VALID_TASKS = {
"automatic-speech-recognition", "text-classification", "text-generation",
"token-classification", "summarization", "translation", "question-answering",
"feature-extraction", "sentence-similarity", "zero-shot-classification",
"fill-mask", "conversational",
}
def parse_frontmatter(text: str) -> tuple[dict, str]:
"""Very small YAML parser sufficient for HF dataset-card frontmatter.
Supports: top-level scalars, lists (- item), and nested mappings via indent.
Returns (parsed_dict, body_after_frontmatter)."""
if not text.startswith("---\n") and not text.startswith("---\r\n"):
return {}, text
end = text.find("\n---", 4)
if end == -1:
return {}, text
raw = text[4:end].lstrip("\n")
body = text[end + 4 :]
# Try real YAML first if available
try:
import yaml # type: ignore
return yaml.safe_load(raw) or {}, body
except ImportError:
pass
# Fallback: minimal hand-rolled parser
result: dict = {}
stack: list[tuple[int, object]] = [(0, result)]
pending_key = None
for line in raw.splitlines():
if not line.strip() or line.lstrip().startswith("#"):
continue
indent = len(line) - len(line.lstrip(" "))
while stack and indent < stack[-1][0]:
stack.pop()
stripped = line.strip()
container = stack[-1][1]
if stripped.startswith("- "):
if isinstance(container, list):
container.append(stripped[2:].strip())
elif pending_key and isinstance(container, dict):
container.setdefault(pending_key, []).append(stripped[2:].strip())
continue
if ":" in stripped:
k, _, v = stripped.partition(":")
k = k.strip()
v = v.strip()
if not v:
# nested block follows
new_container: object
# Peek next non-empty line — if it starts with `-`, list; else dict
new_container = {}
container[k] = new_container
stack.append((indent + 2, new_container))
pending_key = k
else:
if v.startswith("[") and v.endswith("]"):
items = [s.strip().strip("'\"") for s in v[1:-1].split(",") if s.strip()]
container[k] = items
else:
container[k] = v.strip().strip("'\"")
pending_key = None
return result, body
def validate(card_path: Path) -> int:
text = card_path.read_text(encoding="utf-8")
meta, body = parse_frontmatter(text)
errors: list[str] = []
warnings: list[str] = []
if not meta:
errors.append("frontmatter not found or unparseable")
_report(errors, warnings)
return 2
# Required scalars
for key in ("license", "pretty_name"):
if not meta.get(key):
errors.append(f"missing required key: {key}")
lic = meta.get("license")
if lic and lic not in VALID_LICENSES:
warnings.append(f"license '{lic}' not in SPDX whitelist (may be flagged by Hub)")
# Language
langs = meta.get("language") or meta.get("languages")
if not langs:
errors.append("missing 'language' (expected list, e.g. [zh])")
elif isinstance(langs, list) and "zh" not in [l.lower() for l in langs]:
warnings.append("language list doesn't include 'zh'")
# Size categories
sizes = meta.get("size_categories")
if sizes:
bad = [s for s in (sizes if isinstance(sizes, list) else [sizes]) if s not in VALID_SIZE]
if bad:
errors.append(f"invalid size_categories values: {bad}")
# Task categories
tasks = meta.get("task_categories")
if tasks:
bad = [t for t in (tasks if isinstance(tasks, list) else [tasks]) if t not in VALID_TASKS]
if bad:
warnings.append(f"task_categories not in known taxonomy: {bad}")
# Configs + dataset_info consistency
configs = meta.get("configs") or []
dataset_info = meta.get("dataset_info")
if not configs:
warnings.append("no 'configs' declared — Hub will default to autodetect")
if dataset_info:
if isinstance(dataset_info, dict):
splits = dataset_info.get("splits") or []
for sp in splits if isinstance(splits, list) else []:
if isinstance(sp, dict) and not sp.get("name"):
errors.append("a dataset_info.splits entry is missing 'name'")
else:
warnings.append("dataset_info is not a mapping")
else:
warnings.append("no 'dataset_info' — Hub will infer features but won't show split sizes")
# Cross-check splits against parquet on disk
repo = card_path.parent
parquets = sorted((repo / "data").glob("*.parquet")) if (repo / "data").is_dir() else []
if not parquets:
warnings.append("no data/*.parquet found — Hub will fall back to scanning raw files")
# Body section presence
required_sections = [
"Dataset Summary", "Languages", "Data Fields",
"Source Data", "Licensing", "Citation",
]
for sect in required_sections:
if sect.lower() not in body.lower():
warnings.append(f"missing prose section: {sect}")
return _report(errors, warnings)
def _report(errors: list[str], warnings: list[str]) -> int:
if errors:
print("ERRORS:")
for e in errors:
print(f" - {e}")
if warnings:
print("WARNINGS:")
for w in warnings:
print(f" - {w}")
if not errors and not warnings:
print("card OK")
return 0
return 2 if errors else 1
if __name__ == "__main__":
path = Path(sys.argv[1] if len(sys.argv) > 1 else "README.md")
sys.exit(validate(path))
|