-
Notifications
You must be signed in to change notification settings - Fork 7
/
pgn_base.py
280 lines (243 loc) · 9.7 KB
/
pgn_base.py
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
"""chess dataset builder."""
import dataclasses
import logging
import os
import re
import chess
import chess.pgn
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
from tensorflow_datasets.core import beam_utils
from chess_ai import feature_converter
_ANNOTATION_PATTERN = re.compile(
r"""
(?P<prefix>\s?)
\[%(?:evp|cal|eval|clk|csl|emt|tqu)\s.*\]
(?P<suffix>\s?)
""",
re.VERBOSE,
)
class LanguageIdentification:
def __init__(self, model_path):
pretrained_lang_model = model_path
import fasttext
self.model = fasttext.load_model(pretrained_lang_model)
def predict_lang(self, text, k=3):
text = text.replace("\n", " ")
predictions = self.model.predict(
text, k=k
) # returns top-k matching languages
output = []
for lang, _ in zip(*predictions):
output.append(lang.replace("__label__", ""))
return set(output)
try:
lang_detector = LanguageIdentification('/nvme2/filter_models/lid.176.bin')
except:
print('error loading language detector, skip')
def is_english(comment, k=2):
def remove_all_pgn_moves(pgn_string):
pattern = r"([PNBRQK]?[a-h]?[1-8]?x?[a-h][1-8](?:=[NBRQ])?[+#]?|[O-]{3,5})"
return re.sub(pattern, '', pgn_string)
lang_ids = lang_detector.predict_lang(remove_all_pgn_moves(comment), k)
if "en" not in lang_ids:
return False
else:
return True
def _mirror_move(move: chess.Move) -> chess.Move:
return chess.Move(
chess.square_mirror(move.from_square),
chess.square_mirror(move.to_square),
move.promotion,
)
def _get_probs(board: chess.Board, move: str):
if board.turn == chess.WHITE:
move = board.parse_uci(move)
probs = [-1] * len(feature_converter.LC0_POLICY_INDEX)
for legal_move in board.legal_moves:
probs[feature_converter.as_lc0_policy_index(legal_move.uci())] = 0
probs[feature_converter.as_lc0_policy_index(move.uci())] = 1
else:
move = _mirror_move(board.parse_uci(move))
board = board.copy(stack=False)
board.apply_mirror()
probs = [-1] * len(feature_converter.LC0_POLICY_INDEX)
for legal_move in board.legal_moves:
probs[feature_converter.as_lc0_policy_index(legal_move.uci())] = 0
probs[feature_converter.as_lc0_policy_index(move.uci())] = 1
return np.asarray(probs, np.float32)
def generate_examples_from_game(game: chess.pgn.Game, filter_en=False):
game_result = game.headers["Result"].strip()
if game_result in ("*", "1/2-1/2", "1/2"):
winner = None
elif game_result == "1-0":
winner = chess.WHITE
elif game_result == "0-1":
winner = chess.BLACK
else:
winner = None#raise ValueError(f"Unknown result {game_result}")
history = []
while True:
board = game.board()
# Add last board to history
history.append(feature_converter.get_board_features(board))
# Advance to the next game state
next_game = game.next()
if next_game is None:
break
else:
# game.move is the move that leads to the game state
move = next_game.move.uci()
comment = next_game.comment.strip()
# Filter annotation pattern
comment = _ANNOTATION_PATTERN.sub("", comment)
if filter_en:
if not comment or not is_english(comment, k=2):
game = next_game
continue
else:
if not comment:
game = next_game
continue
# Add last board to history
features = feature_converter.stack_observations(history, history_size=8)
features["probs"] = _get_probs(board, move)
features["comment"] = comment
if winner is None:
result = 0
elif board.turn == chess.WHITE:
result = 1 if winner == chess.WHITE else -1
else:
result = 1 if winner == chess.BLACK else -1
features["result"] = result
yield features
game = next_game
def generate_examples_from_game_no_comment(game: chess.pgn.Game):
game_result = game.headers["Result"].strip()
if game_result in ("*", "1/2-1/2", "1/2"):
winner = None
elif game_result == "1-0":
winner = chess.WHITE
elif game_result == "0-1":
winner = chess.BLACK
else:
winner = None#raise ValueError(f"Unknown result {game_result}")
history = []
while True:
board = game.board()
# Add last board to history
history.append(feature_converter.get_board_features(board))
# Advance to the next game state
next_game = game.next()
if next_game is None:
break
else:
# game.move is the move that leads to the game state
move = next_game.move.uci()
comment = next_game.comment.strip()
# Add last board to history
features = feature_converter.stack_observations(history, history_size=8)
features["probs"] = _get_probs(board, move)
features["comment"] = comment
if winner is None:
result = 0
elif board.turn == chess.WHITE:
result = 1 if winner == chess.WHITE else -1
else:
result = 1 if winner == chess.BLACK else -1
features["result"] = result
yield features
game = next_game
def _iter_games(filename, encoding="utf-8"):
key_prefix = os.path.basename(filename)
counter = 0
with open(filename, mode="rt", encoding=encoding, errors='ignore') as handle:
game = chess.pgn.read_game(handle)
yield f"{key_prefix}/{counter}", game
while game is not None:
counter += 1
try:
game = chess.pgn.read_game(handle)
if game.errors:
raise game.errors[0]
except Exception:
beam_utils.inc_counter("read:failed", 1)
continue
else:
yield f"{key_prefix}/{counter}", game
def generate_beam_examples(paths, encoding="utf-8", filter_en=False):
beam = tfds.core.lazy_imports.apache_beam
if not isinstance(paths, (tuple, list)):
paths = (paths,)
filenames = []
for path in paths:
filenames.extend(list(path.glob("*.pgn")))
filenames = [str(f) for f in filenames]
def process_example(filename):
for key, game in _iter_games(filename, encoding=encoding):
try:
if game.errors:
raise game.errors[0]
for i, example in enumerate(generate_examples_from_game(game, filter_en=filter_en)):
yield f"{key}/{i}", example
logging.debug("Finished processing %s", filename)
beam_utils.inc_counter("parsing:success", 1)
except Exception: # pylint: disable=broad-except
logging.exception("Unable to process %s", filename)
beam_utils.inc_counter("parsing:failed", 1)
return beam.Create(filenames) | "ParsePGN" >> beam.FlatMap(process_example)
@dataclasses.dataclass
class DatasetConfig:
description: str = ""
citation: str = ""
homepage: str = ""
def build_info(builder, config: DatasetConfig):
features = tfds.features.FeaturesDict(
{
# TFDS does not support uint64 in the serialized format so we have to
# use uint8
"planes": tfds.features.Tensor(
shape=(13 * 8 * 8,),
dtype=tf.uint8,
encoding=tfds.features.Encoding.ZLIB,
),
"probs": tfds.features.Tensor(
shape=(len(feature_converter.LC0_POLICY_INDEX),),
dtype=tf.float32,
encoding=tfds.features.Encoding.ZLIB,
),
"us_black": tfds.features.Tensor(shape=(), dtype=tf.bool),
"move_count": tfds.features.Tensor(shape=(), dtype=tf.uint32),
"rule50_counter": tfds.features.Tensor(shape=(), dtype=tf.uint32),
"castling_us_ooo": tfds.features.Tensor(shape=(), dtype=tf.bool),
"castling_us_oo": tfds.features.Tensor(shape=(), dtype=tf.bool),
"castling_them_ooo": tfds.features.Tensor(shape=(), dtype=tf.bool),
"castling_them_oo": tfds.features.Tensor(shape=(), dtype=tf.bool),
"comment": tfds.features.Tensor(shape=(), dtype=tf.string),
"result": tfds.features.Tensor(shape=(), dtype=tf.int32),
}
)
return tfds.core.DatasetInfo(
builder=builder,
description=config.description,
features=features,
# If there's a common (input, target) tuple from the
# features, specify them here. They'll be used if
# `as_supervised=True` in `builder.as_dataset`.
# supervised_keys=("image", "label"), # Set to `None` to disable
supervised_keys=None,
homepage=config.homepage,
citation=config.citation,
)
class PGNDatasetBuilder(tfds.core.GeneratorBasedBuilder, skip_registration=True):
"""DatasetBuilder for chess_crawl dataset."""
MANUAL_DOWNLOAD_INSTRUCTIONS = """
Preparation of the chess_crawl dataset requires manual download.
Download the crawled dataset and place. Place the `game_pgn.zip`
file in the `manual_dir/`. For more information, please refer to
https://www.tensorflow.org/datasets/add_dataset#manual_download_and_extraction
"""
def _process_pipeline_result(self, pipeline_result):
# TODO(yl): Maybe store the metrics somewhere
logging.info("Metrics %r", pipeline_result.metrics().query())