Download scripts/validate_dataset.py from continuum-oss/ccrb: direct link, hf CLI and curl.
- Browser
- Download file 11.1 kB
-
https://huggingface.co/datasets/continuum-oss/ccrb/resolve/main/scripts/validate_dataset.py
- Command line
-
hf download hf://datasets/continuum-oss/ccrb/scripts/validate_dataset.py
-
curl -L -o validate_dataset.py https://huggingface.co/datasets/continuum-oss/ccrb/resolve/main/scripts/validate_dataset.py
11.1 kB
| """Validate CCRB queries, document corpora, qrels, and anti-leakage invariants.""" | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import re | |
| import sys | |
| from collections import Counter | |
| from dataclasses import dataclass, field | |
| from pathlib import Path | |
| _REPO_ROOT = Path(__file__).resolve().parent.parent | |
| if str(_REPO_ROOT) not in sys.path: | |
| sys.path.insert(0, str(_REPO_ROOT)) | |
| from scripts.pipeline_utils import ( | |
| TRACKS, | |
| VALID_QUERY_TYPES, | |
| VALID_RELEVANCE_GRADES, | |
| VALID_SPLITS, | |
| load_jsonl, | |
| load_qrels, | |
| ) | |
| # Identifiers that act as trivial lexical shortcuts when leaked verbatim into queries. | |
| LEAKAGE_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = ( | |
| ("CVE_ID", re.compile(r"\bCVE-\d{4}-\d{4,7}\b", re.IGNORECASE)), | |
| ("CWE_ID", re.compile(r"\bCWE-\d{1,4}\b", re.IGNORECASE)), | |
| ("CAPEC_ID", re.compile(r"\bCAPEC-\d{1,4}\b", re.IGNORECASE)), | |
| ("GHSA_ID", re.compile(r"\bGHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}\b", re.IGNORECASE)), | |
| ("ATTACK_TECHNIQUE_ID", re.compile(r"\bT\d{4}(?:\.\d{3})?\b")), | |
| ("ATTACK_TACTIC_ID", re.compile(r"\bTA\d{4}\b")), | |
| ("ATTACK_MITIGATION_ID", re.compile(r"\bM\d{4}\b")), | |
| ) | |
| class ValidationReport: | |
| """Structured validation outcome across all CCRB tracks.""" | |
| errors: list[str] = field(default_factory=list) | |
| warnings: list[str] = field(default_factory=list) | |
| track_stats: dict[str, dict[str, object]] = field(default_factory=dict) | |
| def ok(self) -> bool: | |
| return len(self.errors) == 0 | |
| def _normalize_text(text: str) -> str: | |
| return re.sub(r"\s+", " ", text.strip().lower()) | |
| def _require_non_empty_str( | |
| record: dict[str, object], | |
| key: str, | |
| location: str, | |
| errors: list[str], | |
| ) -> str | None: | |
| value = record.get(key) | |
| if not isinstance(value, str) or not value.strip(): | |
| errors.append(f"{location}: field {key!r} must be a non-empty string") | |
| return None | |
| return value | |
| def validate_track( | |
| data_dir: Path, | |
| track: str, | |
| *, | |
| allow_empty: bool = False, | |
| strict_leakage: bool = False, | |
| seen_query_ids: set[str] | None = None, | |
| seen_doc_ids: set[str] | None = None, | |
| ) -> tuple[list[str], list[str], dict[str, object]]: | |
| """Validate queries, documents, and qrels for a single CCRB track.""" | |
| errors: list[str] = [] | |
| warnings: list[str] = [] | |
| queries_path = data_dir / "queries" / f"{track}.jsonl" | |
| docs_path = data_dir / "documents" / f"{track}.jsonl" | |
| qrels_path = data_dir / "qrels" / f"{track}.tsv" | |
| for required_path in (queries_path, docs_path, qrels_path): | |
| if not required_path.exists(): | |
| errors.append(f"[{track}] missing required file: {required_path}") | |
| if errors: | |
| return errors, warnings, {} | |
| global_qids = seen_query_ids if seen_query_ids is not None else set() | |
| global_dids = seen_doc_ids if seen_doc_ids is not None else set() | |
| queries_by_id: dict[str, dict[str, object]] = {} | |
| docs_by_id: dict[str, dict[str, object]] = {} | |
| normalized_queries: dict[str, str] = {} | |
| split_counts: Counter[str] = Counter() | |
| grade_counts: Counter[int] = Counter() | |
| try: | |
| raw_queries = load_jsonl(queries_path) | |
| except (json.JSONDecodeError, ValueError) as exc: | |
| errors.append(f"[{track}] invalid queries JSONL: {exc}") | |
| raw_queries = [] | |
| try: | |
| raw_docs = load_jsonl(docs_path) | |
| except (json.JSONDecodeError, ValueError) as exc: | |
| errors.append(f"[{track}] invalid documents JSONL: {exc}") | |
| raw_docs = [] | |
| try: | |
| qrels = load_qrels(qrels_path) | |
| except ValueError as exc: | |
| errors.append(f"[{track}] invalid qrels TSV: {exc}") | |
| qrels = {} | |
| if not allow_empty and (not raw_queries or not raw_docs or not qrels): | |
| errors.append( | |
| f"[{track}] track files must be non-empty (queries={len(raw_queries)}, " | |
| f"docs={len(raw_docs)}, qrel_queries={len(qrels)})" | |
| ) | |
| for line_no, obj in raw_queries: | |
| loc = f"{queries_path}:{line_no}" | |
| qid = _require_non_empty_str(obj, "query_id", loc, errors) | |
| qtext = _require_non_empty_str(obj, "query", loc, errors) | |
| qtrack = _require_non_empty_str(obj, "track", loc, errors) | |
| if qtrack is not None and qtrack != track: | |
| errors.append(f"{loc}: track={qtrack!r} does not match expected {track!r}") | |
| split = obj.get("split") | |
| if split is not None: | |
| if not isinstance(split, str) or split not in VALID_SPLITS: | |
| errors.append(f"{loc}: optional field 'split' must be one of {sorted(VALID_SPLITS)}") | |
| else: | |
| split_counts[split] += 1 | |
| qtype = obj.get("query_type") | |
| if qtype is not None and (not isinstance(qtype, str) or qtype not in VALID_QUERY_TYPES): | |
| errors.append( | |
| f"{loc}: optional field 'query_type' must be one of {sorted(VALID_QUERY_TYPES)}" | |
| ) | |
| if qid is not None: | |
| if qid in queries_by_id or qid in global_qids: | |
| errors.append(f"{loc}: duplicate query_id {qid!r}") | |
| else: | |
| queries_by_id[qid] = obj | |
| global_qids.add(qid) | |
| if qtext is not None: | |
| norm = _normalize_text(qtext) | |
| if norm in normalized_queries: | |
| warnings.append( | |
| f"{loc}: duplicate normalized query text matches {normalized_queries[norm]!r}" | |
| ) | |
| elif qid is not None: | |
| normalized_queries[norm] = qid | |
| for label, pattern in LEAKAGE_PATTERNS: | |
| match = pattern.search(qtext) | |
| if match: | |
| msg = ( | |
| f"{loc}: potential identifier shortcut ({label}={match.group(0)!r}) " | |
| f"in query_id={qid!r}" | |
| ) | |
| if strict_leakage: | |
| errors.append(msg) | |
| else: | |
| warnings.append(msg) | |
| for line_no, obj in raw_docs: | |
| loc = f"{docs_path}:{line_no}" | |
| did = _require_non_empty_str(obj, "document_id", loc, errors) | |
| _require_non_empty_str(obj, "title", loc, errors) | |
| _require_non_empty_str(obj, "text", loc, errors) | |
| _require_non_empty_str(obj, "source", loc, errors) | |
| dtrack = _require_non_empty_str(obj, "track", loc, errors) | |
| if dtrack is not None and dtrack != track: | |
| errors.append(f"{loc}: track={dtrack!r} does not match expected {track!r}") | |
| if did is not None: | |
| if did in docs_by_id or did in global_dids: | |
| errors.append(f"{loc}: duplicate document_id {did!r}") | |
| else: | |
| docs_by_id[did] = obj | |
| global_dids.add(did) | |
| for qid, doc_map in qrels.items(): | |
| if qid not in queries_by_id: | |
| errors.append(f"[{track}] qrels references unknown query_id {qid!r}") | |
| positive_count = 0 | |
| for did, rel in doc_map.items(): | |
| if rel not in VALID_RELEVANCE_GRADES: | |
| errors.append(f"[{track}] invalid relevance grade {rel!r} for ({qid!r}, {did!r})") | |
| else: | |
| grade_counts[rel] += 1 | |
| if did not in docs_by_id: | |
| errors.append(f"[{track}] qrels references unknown document_id {did!r}") | |
| elif rel >= 2 and qid in queries_by_id: | |
| q_norm = _normalize_text(str(queries_by_id[qid].get("query", ""))) | |
| title_norm = _normalize_text(str(docs_by_id[did].get("title", ""))) | |
| if len(title_norm) >= 20 and title_norm in q_norm: | |
| msg = ( | |
| f"[{track}] query {qid!r} contains verbatim target title of {did!r}" | |
| ) | |
| if strict_leakage: | |
| errors.append(msg) | |
| else: | |
| warnings.append(msg) | |
| if rel >= 1: | |
| positive_count += 1 | |
| if positive_count == 0: | |
| errors.append(f"[{track}] query {qid!r} has qrel entries but zero positives (rel >= 1)") | |
| for qid in queries_by_id: | |
| if qid not in qrels: | |
| errors.append(f"[{track}] query {qid!r} has no qrels entries") | |
| stats: dict[str, object] = { | |
| "queries": len(queries_by_id), | |
| "documents": len(docs_by_id), | |
| "qrel_pairs": sum(len(v) for v in qrels.values()), | |
| "grades": {str(g): grade_counts[g] for g in sorted(VALID_RELEVANCE_GRADES)}, | |
| "splits": dict(split_counts), | |
| } | |
| return errors, warnings, stats | |
| def validate_dataset( | |
| data_dir: Path, | |
| *, | |
| tracks: tuple[str, ...] = TRACKS, | |
| allow_empty: bool = False, | |
| strict_leakage: bool = False, | |
| ) -> ValidationReport: | |
| """Validate all tracks in a CCRB data directory.""" | |
| report = ValidationReport() | |
| seen_query_ids: set[str] = set() | |
| seen_doc_ids: set[str] = set() | |
| for track in tracks: | |
| errs, warns, stats = validate_track( | |
| data_dir, | |
| track, | |
| allow_empty=allow_empty, | |
| strict_leakage=strict_leakage, | |
| seen_query_ids=seen_query_ids, | |
| seen_doc_ids=seen_doc_ids, | |
| ) | |
| report.errors.extend(errs) | |
| report.warnings.extend(warns) | |
| report.track_stats[track] = stats | |
| return report | |
| def main(argv: list[str] | None = None) -> int: | |
| parser = argparse.ArgumentParser(description="Validate CCRB dataset files.") | |
| parser.add_argument( | |
| "--data-dir", | |
| type=Path, | |
| default=Path("data"), | |
| help="Path to the CCRB data directory (default: data).", | |
| ) | |
| parser.add_argument( | |
| "--tracks", | |
| nargs="+", | |
| choices=TRACKS, | |
| default=list(TRACKS), | |
| help="Subset of tracks to validate (default: all 6 tracks).", | |
| ) | |
| parser.add_argument( | |
| "--allow-empty", | |
| action="store_true", | |
| help="Allow empty placeholder files during early development.", | |
| ) | |
| parser.add_argument( | |
| "--strict-leakage", | |
| action="store_true", | |
| help="Treat identifier/title leakage warnings as validation errors.", | |
| ) | |
| args = parser.parse_args(argv) | |
| report = validate_dataset( | |
| args.data_dir, | |
| tracks=tuple(args.tracks), | |
| allow_empty=args.allow_empty, | |
| strict_leakage=args.strict_leakage, | |
| ) | |
| print("CCRB Dataset Validation Summary") | |
| print("=" * 32) | |
| for track, stats in report.track_stats.items(): | |
| print( | |
| f"- {track:12s} | queries={stats.get('queries', 0):5d} " | |
| f"| docs={stats.get('documents', 0):6d} " | |
| f"| qrels={stats.get('qrel_pairs', 0):6d}" | |
| ) | |
| if report.warnings: | |
| print(f"\nWarnings ({len(report.warnings)}):") | |
| for warning in report.warnings: | |
| print(f" [WARN] {warning}") | |
| if report.errors: | |
| print(f"\nErrors ({len(report.errors)}):") | |
| for err in report.errors: | |
| print(f" [ERR] {err}") | |
| return 1 | |
| print("\nValidation passed.") | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |