#!/usr/bin/env python3 """ Independent validation pass over the generated ICSThreatQA Hugging Face table. Re-derives the dataset from the original .xlsx files and compares it against the checked-in CSV/Parquet outputs, then reports data-quality findings without silently modifying anything. Usage: python scripts/validate_dataset.py Exit code is non-zero only for an *actual* data error (missing file, missing column, unexpected row-count drift, duplicate IDs, CSV/Parquet mismatch, or non-deterministic regeneration). Duplicate questions/rows that genuinely exist in the original benchmark, and the known trailing-blank-row formatting artifact in factual.xlsx, are reported but do NOT fail validation. """ from __future__ import annotations import sys from pathlib import Path import pandas as pd SCRIPT_DIR = Path(__file__).resolve().parent sys.path.insert(0, str(SCRIPT_DIR)) import prepare_dataset as prep # noqa: E402 RELEASE_DIR = SCRIPT_DIR.parent DATA_DIR = RELEASE_DIR / "data" CSV_PATH = DATA_DIR / "icsthreatqa.csv" PARQUET_PATH = DATA_DIR / "icsthreatqa.parquet" EXPECTED_TOTAL = 620 def section(title: str) -> None: print() print(f"--- {title} ---") def main() -> int: errors: list[str] = [] notes: list[str] = [] if not CSV_PATH.exists(): print(f"VALIDATION FAILED: {CSV_PATH} not found. Run prepare_dataset.py first.") return 1 if not PARQUET_PATH.exists(): print(f"VALIDATION FAILED: {PARQUET_PATH} not found. Run prepare_dataset.py first.") return 1 csv_df = pd.read_csv(CSV_PATH, dtype=str, keep_default_na=False) parquet_df = pd.read_parquet(PARQUET_PATH).astype(str) # ------------------------------------------------------------------ # 1. Deterministic regeneration: rebuild independently from raw xlsx # and confirm it matches the checked-in CSV exactly. # ------------------------------------------------------------------ section("Deterministic regeneration") frames = [] per_category_counts = {} try: for category, (filename, prefix) in prep.CATEGORIES.items(): df = prep.load_category(category, filename, prefix) per_category_counts[category] = len(df) frames.append(df) rebuilt = pd.concat(frames, ignore_index=True) except prep.ValidationError as e: errors.append(f"Could not regenerate dataset from raw files: {e}") rebuilt = None if rebuilt is not None: rebuilt_str = rebuilt.astype(str) if rebuilt_str.equals(csv_df.reset_index(drop=True)): print("OK: regenerating from raw .xlsx files reproduces the checked-in CSV exactly.") else: errors.append( "Regenerating from raw .xlsx files does NOT match the checked-in CSV. " "The dataset may be stale relative to the source files." ) # ------------------------------------------------------------------ # 2. Record counts # ------------------------------------------------------------------ section("Record counts") total = len(csv_df) print(f"Total QA records: {total}") for cat, n in per_category_counts.items(): print(f" {cat}: {n}") if total != EXPECTED_TOTAL: notes.append( f"Total record count is {total}, not the {EXPECTED_TOTAL} pairs described " f"in the project README. Verified against raw .xlsx row counts (see below); " f"this is reported as a discrepancy, not corrected." ) print( f"NOTE: expected {EXPECTED_TOTAL} per README, found {total}. " f"Not auto-corrected -- see report." ) else: print(f"Matches expected total of {EXPECTED_TOTAL}.") # ------------------------------------------------------------------ # 3. Missing questions / answers # ------------------------------------------------------------------ section("Missing values") missing_q = (csv_df["question"].str.strip() == "").sum() missing_a = (csv_df["answer"].str.strip() == "").sum() print(f"Missing/empty questions: {missing_q}") print(f"Missing/empty answers: {missing_a}") if missing_q or missing_a: errors.append(f"Found missing question/answer fields: {missing_q} / {missing_a}") # ------------------------------------------------------------------ # 4. Duplicates -- reported, not removed # ------------------------------------------------------------------ section("Duplicate analysis (informational -- originals are preserved)") dup_questions_overall = csv_df["question"].duplicated().sum() print(f"Duplicate questions (exact text, across entire dataset): {dup_questions_overall}") for cat in per_category_counts: sub = csv_df[csv_df["question_type"] == cat] d = sub["question"].duplicated().sum() if d: print(f" within {cat}: {d} duplicate question(s) -- present in original {cat}.xlsx") dup_full_rows = csv_df.duplicated(subset=["question", "answer", "question_type"]).sum() print(f"Duplicate full rows (question+answer+category): {dup_full_rows}") notes.append( f"{dup_questions_overall} duplicate question(s) and {dup_full_rows} duplicate " f"full row(s) exist in the original benchmark workbooks and were intentionally " f"preserved (not deduplicated)." ) dup_ids = csv_df["id"].duplicated().sum() print(f"Duplicate stable IDs: {dup_ids}") if dup_ids: errors.append(f"Found {dup_ids} duplicate stable ID(s) -- this IS an error.") # ------------------------------------------------------------------ # 5. Category values # ------------------------------------------------------------------ section("Category values") valid_categories = set(prep.CATEGORIES.keys()) found_categories = set(csv_df["question_type"].unique()) print(f"question_type values found: {sorted(found_categories)}") if found_categories - valid_categories: errors.append(f"Unexpected question_type value(s): {found_categories - valid_categories}") if valid_categories - found_categories: errors.append(f"Missing expected question_type value(s): {valid_categories - found_categories}") # ------------------------------------------------------------------ # 6. CSV / Parquet equality # ------------------------------------------------------------------ section("CSV / Parquet equality") parquet_df_filled = parquet_df.fillna("") if csv_df.reset_index(drop=True).equals(parquet_df_filled.reset_index(drop=True)): print("OK: CSV and Parquet contain identical data.") else: errors.append("CSV and Parquet outputs do not contain identical data.") # ------------------------------------------------------------------ # Final report # ------------------------------------------------------------------ section("Summary") if notes: print("Notes (non-fatal, documented discrepancies / known duplicates):") for n in notes: print(f" - {n}") if errors: print("\nERRORS (actual data-quality problems):") for e in errors: print(f" - {e}") print("\nVALIDATION FAILED.") return 1 print("\nVALIDATION PASSED (with the documented notes above, if any).") return 0 if __name__ == "__main__": raise SystemExit(main())