File size: 7,456 Bytes
5017b5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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())