"""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 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))