mbhosale commited on
Commit
02a6fb5
·
verified ·
1 Parent(s): 4fc0c09

Upload validators/chess_validator.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. validators/chess_validator.py +228 -0
validators/chess_validator.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Training-free hallucination detector for the ChessImages dataset.
2
+
3
+ A generated 256x256 chessboard is parsed back to a FEN piece-placement string
4
+ via template matching, and its legality is checked with ``python-chess``
5
+ (``chess.Board.is_valid()``). A board that fails legality (e.g. two white kings,
6
+ >8 pawns, pawns on the back rank, ...) is counted as *hallucinated*.
7
+
8
+ This mirrors the "ChessImages" detection module described in the paper
9
+ (Section 5.1 / Appendix E). Only ``<PiecePlacement>`` is recovered from the
10
+ image, so rules that need the rest of a FEN (castling / en-passant / side-to-move
11
+ checks) are not used by the legality test.
12
+
13
+ Usage
14
+ -----
15
+ python -m evaluation.chess_validator \
16
+ --gen-dir /path/to/generated/images \
17
+ [--gt-json train_fen.json --conditional] \
18
+ [--template-dir evaluation/templates/chess] \
19
+ [--threshold 0.50]
20
+
21
+ ``--gen-dir`` may be passed multiple times (e.g. one folder per seed); the
22
+ hallucination rate is reported per folder and aggregated (mean +/- std).
23
+ """
24
+ import argparse
25
+ import json
26
+ import os
27
+ from difflib import SequenceMatcher
28
+
29
+ import chess
30
+ import cv2
31
+ import numpy as np
32
+ from tqdm import tqdm
33
+
34
+ # Bundled 32x32 piece templates ship alongside this file.
35
+ DEFAULT_TEMPLATE_DIR = os.path.join(os.path.dirname(__file__), "templates", "chess")
36
+
37
+ # Map python-chess status flags to a human-readable violation name. Used to
38
+ # bucket hallucinated boards by the rule they break (see paper Appendix E).
39
+ STATUS_FOLDERS = {
40
+ chess.STATUS_NO_WHITE_KING: "NO_WHITE_KING",
41
+ chess.STATUS_NO_BLACK_KING: "NO_BLACK_KING",
42
+ chess.STATUS_TOO_MANY_KINGS: "TOO_MANY_KINGS",
43
+ chess.STATUS_TOO_MANY_WHITE_PAWNS: "TOO_MANY_WHITE_PAWNS",
44
+ chess.STATUS_TOO_MANY_BLACK_PAWNS: "TOO_MANY_BLACK_PAWNS",
45
+ chess.STATUS_PAWNS_ON_BACKRANK: "PAWNS_ON_BACKRANK",
46
+ chess.STATUS_TOO_MANY_WHITE_PIECES: "TOO_MANY_WHITE_PIECES",
47
+ chess.STATUS_TOO_MANY_BLACK_PIECES: "TOO_MANY_BLACK_PIECES",
48
+ chess.STATUS_BAD_CASTLING_RIGHTS: "BAD_CASTLING_RIGHTS",
49
+ chess.STATUS_INVALID_EP_SQUARE: "INVALID_EP_SQUARE",
50
+ chess.STATUS_OPPOSITE_CHECK: "OPPOSITE_CHECK",
51
+ chess.STATUS_EMPTY: "EMPTY",
52
+ chess.STATUS_RACE_CHECK: "RACE_CHECK",
53
+ chess.STATUS_RACE_OVER: "RACE_OVER",
54
+ chess.STATUS_RACE_MATERIAL: "RACE_MATERIAL",
55
+ chess.STATUS_TOO_MANY_CHECKERS: "TOO_MANY_CHECKERS",
56
+ chess.STATUS_IMPOSSIBLE_CHECK: "IMPOSSIBLE_CHECK",
57
+ }
58
+
59
+ PIECE_MAP = {"king": "K", "queen": "Q", "rook": "R", "bishop": "B", "knight": "N", "pawn": "P"}
60
+
61
+
62
+ def load_templates(template_dir, target_size=(32, 32)):
63
+ """Load piece templates keyed by (square color -> FEN char -> [images]).
64
+
65
+ Template files are named ``{piece}_{pc}{sc}.png`` where ``pc`` is the piece
66
+ color (w/b) and ``sc`` the square color (w/b), e.g. ``king_ww.png``.
67
+ """
68
+ templates = {"b": {}, "w": {}}
69
+
70
+ def process_image(path):
71
+ img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
72
+ if img is None:
73
+ return None
74
+ if img.shape != target_size:
75
+ img = cv2.resize(img, target_size)
76
+ return img
77
+
78
+ loaded = 0
79
+ for fname in os.listdir(template_dir):
80
+ if not fname.endswith(".png"):
81
+ continue
82
+ try:
83
+ piece, colors = fname[:-4].split("_")
84
+ if len(colors) != 2:
85
+ continue
86
+ piece_color, square_color = colors[0].lower(), colors[1].lower()
87
+ if piece.lower() not in PIECE_MAP or piece_color not in "wb" or square_color not in "wb":
88
+ continue
89
+ fen_char = PIECE_MAP[piece.lower()]
90
+ fen_char = fen_char.upper() if piece_color == "w" else fen_char.lower()
91
+ template = process_image(os.path.join(template_dir, fname))
92
+ if template is not None:
93
+ templates[square_color].setdefault(fen_char, []).append(template)
94
+ loaded += 1
95
+ except ValueError:
96
+ continue
97
+
98
+ if loaded != 24:
99
+ raise ValueError(f"Loaded {loaded}/24 templates from {template_dir}. Check filenames/format.")
100
+ return templates
101
+
102
+
103
+ def image_to_fen(image_path, templates, confidence_threshold=0.50, img_size=256):
104
+ """Reconstruct the FEN piece-placement string from a rendered board image."""
105
+ board_img = cv2.imread(image_path)
106
+ if board_img is None:
107
+ raise FileNotFoundError(f"Image not found: {image_path}")
108
+ board_img = cv2.resize(board_img, (img_size, img_size))
109
+ gray = cv2.cvtColor(board_img, cv2.COLOR_BGR2GRAY)
110
+
111
+ square_size = img_size // 8
112
+ fen_rows = []
113
+ for rank in reversed(range(8)):
114
+ fen_row, empty_count = [], 0
115
+ for file in range(8):
116
+ y, x = (7 - rank) * square_size, file * square_size
117
+ square = gray[y:y + square_size, x:x + square_size]
118
+ square_color = "b" if (file + rank) % 2 == 0 else "w"
119
+
120
+ best_match = ("", -1)
121
+ for fen_char, char_templates in templates[square_color].items():
122
+ for template in char_templates:
123
+ result = cv2.matchTemplate(square, template, cv2.TM_CCOEFF_NORMED)
124
+ _, max_val, _, _ = cv2.minMaxLoc(result)
125
+ if max_val > best_match[1]:
126
+ best_match = (fen_char, max_val)
127
+
128
+ if best_match[1] >= confidence_threshold:
129
+ if empty_count:
130
+ fen_row.append(str(empty_count))
131
+ empty_count = 0
132
+ fen_row.append(best_match[0])
133
+ else:
134
+ empty_count += 1
135
+ if empty_count:
136
+ fen_row.append(str(empty_count))
137
+ fen_rows.append("".join(fen_row))
138
+ return "/".join(fen_rows)
139
+
140
+
141
+ def is_fuzzy_match(extracted, gt, threshold=0.95):
142
+ return SequenceMatcher(None, extracted, gt).ratio() >= threshold
143
+
144
+
145
+ def validate_dirs(images_dirs, template_dir=DEFAULT_TEMPLATE_DIR, gt_json=None,
146
+ conditional=False, fuzzy_threshold=0.8, confidence_threshold=0.50,
147
+ save_buckets=False):
148
+ """Validate every image folder and return a metrics dict.
149
+
150
+ Set ``conditional=True`` together with ``gt_json`` (a ``{name: FEN}`` map) to
151
+ additionally report exact / fuzzy FEN reconstruction accuracy against the
152
+ ground truth. Otherwise only validity / hallucination rate is reported.
153
+ """
154
+ templates = load_templates(template_dir)
155
+ ground_truth = json.load(open(gt_json)) if gt_json else {}
156
+
157
+ metrics = {"valid_acc": [], "hallucination": []}
158
+ if conditional:
159
+ metrics["exact_acc"] = []
160
+ metrics[f"{fuzzy_threshold * 100:g}%_match_acc"] = []
161
+
162
+ for images_dir in images_dirs:
163
+ if not os.path.isdir(images_dir):
164
+ print(f"[warn] not a directory, skipping: {images_dir}")
165
+ continue
166
+ files = [f for f in os.listdir(images_dir) if f.lower().endswith(".png")]
167
+ if conditional:
168
+ files = [f for f in files if os.path.splitext(f)[0] in ground_truth]
169
+
170
+ matches = valid_count = fuzzy_count = total = 0
171
+ for fname in tqdm(files, desc=os.path.basename(images_dir.rstrip("/")) or "images"):
172
+ path = os.path.join(images_dir, fname)
173
+ try:
174
+ fen = image_to_fen(path, templates, confidence_threshold)
175
+ if conditional:
176
+ gt_fen = ground_truth[os.path.splitext(fname)[0]].split()[0]
177
+ matches += int(fen == gt_fen)
178
+ fuzzy_count += int(is_fuzzy_match(fen, gt_fen, fuzzy_threshold))
179
+
180
+ board = chess.Board(fen)
181
+ if board.is_valid():
182
+ valid_count += 1
183
+ elif save_buckets:
184
+ status_mask = board.status()
185
+ for flag, folder in STATUS_FOLDERS.items():
186
+ if status_mask & flag:
187
+ rule_dir = os.path.join(images_dir, "hallucinated", folder)
188
+ os.makedirs(rule_dir, exist_ok=True)
189
+ cv2.imwrite(os.path.join(rule_dir, fname), cv2.imread(path))
190
+ total += 1
191
+ except Exception as e: # noqa: BLE001 - keep going on a bad file
192
+ print(f"[warn] error on {fname}: {e}")
193
+
194
+ if total == 0:
195
+ continue
196
+ metrics["valid_acc"].append(100 * valid_count / total)
197
+ metrics["hallucination"].append(100 - 100 * valid_count / total)
198
+ if conditional:
199
+ metrics["exact_acc"].append(100 * matches / total)
200
+ metrics[f"{fuzzy_threshold * 100:g}%_match_acc"].append(100 * fuzzy_count / total)
201
+
202
+ print("\n=== ChessImages validation ===")
203
+ for k, v in metrics.items():
204
+ print(f" {k}: {np.mean(v):.2f} +/- {np.std(v):.2f} (per-folder: {[round(x, 2) for x in v]})")
205
+ return metrics
206
+
207
+
208
+ def main():
209
+ p = argparse.ArgumentParser(description="ChessImages hallucination detector (FEN legality).")
210
+ p.add_argument("--gen-dir", action="append", required=True,
211
+ help="Folder of generated PNG boards. Repeat for multiple seeds.")
212
+ p.add_argument("--template-dir", default=DEFAULT_TEMPLATE_DIR,
213
+ help="Piece templates (defaults to bundled evaluation/templates/chess).")
214
+ p.add_argument("--gt-json", default=None, help="Optional {name: FEN} ground-truth map.")
215
+ p.add_argument("--conditional", action="store_true",
216
+ help="Also report exact/fuzzy FEN reconstruction accuracy (requires --gt-json).")
217
+ p.add_argument("--fuzzy-threshold", type=float, default=0.8)
218
+ p.add_argument("--threshold", type=float, default=0.50, help="Template-match confidence threshold.")
219
+ p.add_argument("--save-buckets", action="store_true",
220
+ help="Save hallucinated boards into per-rule subfolders under each gen-dir.")
221
+ args = p.parse_args()
222
+
223
+ validate_dirs(args.gen_dir, args.template_dir, args.gt_json, args.conditional,
224
+ args.fuzzy_threshold, args.threshold, args.save_buckets)
225
+
226
+
227
+ if __name__ == "__main__":
228
+ main()