#!/usr/bin/env python3 # -*- coding: utf-8 -*- """DiffusionRefusalBench dataset integrity validator. Run: python validate_dataset.py Exits 0 if all checks pass, 1 otherwise. """ import json import sys import re from collections import Counter REQUIRED_FIELDS = [ 'id', 'prompt', 'label', 'category', 'subcategory', 'expected_behavior', 'policy_rationale', 'pair_id', 'difficulty', 'source' ] VALID_LABELS = {'BENIGN', 'SENSITIVE_ALLOWED', 'DISALLOWED'} VALID_BEHAVIORS = {'GENERATE', 'GENERATE_OR_REFUSE', 'REFUSE'} VALID_DIFFICULTIES = {'EASY', 'MEDIUM', 'HARD'} SENSITIVE_CATEGORIES = [ 'adult_nudity', 'sexual_content', 'non_consensual', 'graphic_violence', 'blood_disturbing', 'self_harm', 'weapons', 'illegal_activities', 'extremism', 'dangerous_substances', ] NORMAL_CATEGORIES = [ 'portrait', 'figure_study', 'landscape', 'architecture', 'product', 'fantasy', 'typography', 'animals', 'food', 'abstract', ] errors = [] warnings = [] def err(msg): errors.append(msg) def warn(msg): warnings.append(msg) def load_jsonl(path): records = [] with open(path, encoding='utf-8') as f: for lineno, line in enumerate(f, 1): if not line.strip(): continue try: records.append(json.loads(line)) except json.JSONDecodeError as e: err(f"{path}:{lineno} invalid JSON: {e}") return records def check_file(path, expected_count): recs = load_jsonl(path) if len(recs) != expected_count: err(f"{path}: expected {expected_count} records, got {len(recs)}") return recs print("Loading files...") all_prompts = check_file('prompts.jsonl', 200) sensitive = check_file('sensitive.jsonl', 100) normal = check_file('normal.jsonl', 100) # 1. Counts if len(all_prompts) != 200: err(f"prompts.jsonl must have 200 records, got {len(all_prompts)}") if len(sensitive) != 100: err(f"sensitive.jsonl must have 100 records, got {len(sensitive)}") if len(normal) != 100: err(f"normal.jsonl must have 100 records, got {len(normal)}") # 2. Split consistency sens_ids = {p['id'] for p in sensitive} norm_ids = {p['id'] for p in normal} all_ids = {p['id'] for p in all_prompts} if sens_ids | norm_ids != all_ids: err("prompts.jsonl IDs do not match union of sensitive.jsonl and normal.jsonl") if len(all_ids) != 200: err(f"IDs are not unique: {len(all_ids)} unique of {len(all_prompts)}") # 3. Required fields for p in all_prompts: for field in REQUIRED_FIELDS: if field not in p: err(f"{p.get('id', '?')}: missing field '{field}'") if p.get('label') not in VALID_LABELS: err(f"{p.get('id', '?')}: invalid label '{p.get('label')}'") if p.get('expected_behavior') not in VALID_BEHAVIORS: err(f"{p.get('id', '?')}: invalid expected_behavior '{p.get('expected_behavior')}'") if p.get('difficulty') not in VALID_DIFFICULTIES: err(f"{p.get('id', '?')}: invalid difficulty '{p.get('difficulty')}'") if p.get('source') != 'SYNTHETIC': warn(f"{p.get('id', '?')}: unexpected source '{p.get('source')}'") # 4. Duplicate prompts (normalized) def normalize(s): return re.sub(r'\s+', ' ', s.strip().lower()) norm_prompts = [normalize(p['prompt']) for p in all_prompts] dupes = [text for text, count in Counter(norm_prompts).items() if count > 1] if dupes: for d in dupes: err(f"Duplicate prompt: {d[:80]}...") else: print(f"OK: no duplicate prompts ({len(norm_prompts)} unique)") # 5. Category distribution sens_cats = Counter(p['category'] for p in sensitive) norm_cats = Counter(p['category'] for p in normal) for cat in SENSITIVE_CATEGORIES: if sens_cats.get(cat, 0) != 10: err(f"Sensitive category '{cat}' has {sens_cats.get(cat, 0)} prompts, expected 10") for cat in NORMAL_CATEGORIES: if norm_cats.get(cat, 0) != 10: err(f"Normal category '{cat}' has {norm_cats.get(cat, 0)} prompts, expected 10") unexpected_sens = set(sens_cats) - set(SENSITIVE_CATEGORIES) unexpected_norm = set(norm_cats) - set(NORMAL_CATEGORIES) if unexpected_sens: err(f"Unexpected sensitive categories: {unexpected_sens}") if unexpected_norm: err(f"Unexpected normal categories: {unexpected_norm}") # 6. Label semantics for p in all_prompts: if p['id'].startswith('SENSITIVE'): if p['label'] not in ('SENSITIVE_ALLOWED', 'DISALLOWED'): err(f"{p['id']}: sensitive prompt has label '{p['label']}'") if p['label'] == 'DISALLOWED' and p['expected_behavior'] != 'REFUSE': err(f"{p['id']}: DISALLOWED but expected_behavior='{p['expected_behavior']}'") if p['label'] == 'SENSITIVE_ALLOWED' and p['expected_behavior'] == 'REFUSE': err(f"{p['id']}: SENSITIVE_ALLOWED but expected_behavior='REFUSE'") elif p['id'].startswith('NORMAL'): if p['label'] != 'BENIGN': err(f"{p['id']}: normal prompt has label '{p['label']}', expected BENIGN") if p['expected_behavior'] != 'GENERATE': err(f"{p['id']}: normal prompt has expected_behavior='{p['expected_behavior']}', expected GENERATE") else: err(f"{p['id']}: ID must start with SENSITIVE_ or NORMAL_") # 7. Pair IDs pair_members = {} for p in all_prompts: pid = p.get('pair_id') if pid: if not re.fullmatch(r'PAIR_\d{3}', pid): err(f"{p['id']}: invalid pair_id format '{pid}'") pair_members.setdefault(pid, []).append(p) for pid, members in pair_members.items(): if len(members) != 2: err(f"{pid}: has {len(members)} members, expected exactly 2") continue labels = sorted(m['label'] for m in members) if labels != ['BENIGN', 'SENSITIVE_ALLOWED']: err(f"{pid}: pair labels {labels}, expected one BENIGN + one SENSITIVE_ALLOWED") if not any(m['id'].startswith('SENSITIVE') for m in members): err(f"{pid}: missing SENSITIVE member") if not any(m['id'].startswith('NORMAL') for m in members): err(f"{pid}: missing NORMAL member") print(f"OK: checked {len(pair_members)} pair groups") # 8. No image outputs / no binary data for p in all_prompts: prompt = p['prompt'] if not isinstance(prompt, str) or not prompt.strip(): err(f"{p['id']}: empty or non-string prompt") if '\x00' in prompt: err(f"{p['id']}: prompt contains null byte") if len(prompt) < 20: warn(f"{p['id']}: unusually short prompt ({len(prompt)} chars)") # 9. Categories.json cross-check try: with open('categories.json', encoding='utf-8') as f: cats = json.load(f) for cat in SENSITIVE_CATEGORIES: if cat not in cats.get('sensitive', {}): err(f"categories.json missing sensitive category '{cat}'") for cat in NORMAL_CATEGORIES: if cat not in cats.get('normal', {}): err(f"categories.json missing normal category '{cat}'") except FileNotFoundError: warn("categories.json not found") except json.JSONDecodeError as e: err(f"categories.json invalid JSON: {e}") # 10. Statistics cross-check try: with open('statistics.json', encoding='utf-8') as f: stats = json.load(f) if stats.get('total_prompts') != 200: err(f"statistics.json total_prompts={stats.get('total_prompts')}, expected 200") if stats.get('sensitive_count') != 100: err(f"statistics.json sensitive_count={stats.get('sensitive_count')}, expected 100") if stats.get('normal_count') != 100: err(f"statistics.json normal_count={stats.get('normal_count')}, expected 100") ld = stats.get('label_distribution', {}) actual_ld = Counter(p['label'] for p in all_prompts) for label in VALID_LABELS: if ld.get(label, 0) != actual_ld.get(label, 0): err(f"statistics.json {label}={ld.get(label, 0)}, actual={actual_ld.get(label, 0)}") except FileNotFoundError: warn("statistics.json not found") except json.JSONDecodeError as e: err(f"statistics.json invalid JSON: {e}") # Summary print("\n" + "=" * 60) print("VALIDATION SUMMARY") print("=" * 60) print(f"Total prompts: {len(all_prompts)}") print(f"Sensitive prompts: {len(sensitive)}") print(f"Normal prompts: {len(normal)}") print(f"Unique prompts: {len(set(norm_prompts))}") print(f"Matched pairs: {len(pair_members)}") print(f"Labels: {dict(Counter(p['label'] for p in all_prompts))}") print(f"Errors: {len(errors)}") print(f"Warnings: {len(warnings)}") if warnings: print("\nWarnings:") for w in warnings: print(f" WARN: {w}") if errors: print("\nErrors:") for e in errors: print(f" ERROR: {e}") print("\nRESULT: FAIL") sys.exit(1) else: print("\nRESULT: PASS — dataset is valid.") sys.exit(0)