lichess_sf / lichess_sf.py
mauricett's picture
Update lichess_sf.py
845c38f verified
raw
history blame
4.24 kB
#%%
import datasets
import zstandard as zstd
import io
#%%
class LichessConfig(datasets.BuilderConfig):
def __init__(self, features, **kwargs):
super(LichessConfig, self).__init__(**kwargs)
self.features = features
class Lichess(datasets.GeneratorBasedBuilder):
BUILDER_CONFIG_CLASS = LichessConfig
BUILDER_CONFIGS = [LichessConfig(name="pgn",
features=["WhiteElo",
"BlackElo",
"pgn"]),
LichessConfig(name="fen",
features=["WhiteElo",
"BlackElo",
"fens",
"moves",
"scores"]),]
def _info(self):
features_dict = {feature: datasets.Value("uint16") for feature in self.config.features}
if self.config.name == "pgn":
features_dict["pgn"] = datasets.Value("string")
if self.config.name == "fen":
features_dict["fens"] = datasets.Value("string")
features_dict["moves"] = datasets.Value("string")
features_dict["scores"] = datasets.Value("string")
info = datasets.DatasetInfo(datasets.Features(features_dict))
return info
def _get_filepaths(self):
#months = ["01", "02", "03", "04", "05", "06",
# "07", "08", "09", "10", "11", "12"]
months = ["04"]
shards = ["0", "1", "2", "3"]
filepaths = [ self.config.name + "/2023/" + m for m in months]
if self.config.name == "pgn":
paths = []
for shard in shards:
paths.extend([filepath + "/" + shard + ".zst" for filepath in filepaths])
if self.config.name == "fen":
paths = []
for shard in shards:
paths.extend([filepath + "/" + shard + "_fen.zst" for filepath in filepaths])
return paths
def _split_generators(self, dl_manager: datasets.DownloadManager):
filepaths = self._get_filepaths()
downloaded_files = dl_manager.download(filepaths)
generator = datasets.SplitGenerator(name=datasets.Split.TRAIN,
gen_kwargs={'filepaths': downloaded_files})
return [generator]
def _generate_examples(self, filepaths):
dctx = zstd.ZstdDecompressor()
for filepath in filepaths:
n = 0
with open(filepath, "rb") as file:
with dctx.stream_reader(file) as sr:
pgn = io.TextIOWrapper(sr)
if self.config.name == "pgn":
while True:
white_elo, black_elo = pgn.readline().split(" ")
game_pgn = pgn.readline()
next_line = pgn.readline()
if game_pgn:
_id = n
n += 1
yield _id, {"WhiteElo": int(white_elo),
"BlackElo": int(black_elo),
"pgn": game_pgn}
else:
break
elif self.config.name == "fen":
while True:
white_elo, black_elo = pgn.readline().split(" ")
game = pgn.readline()
fens, moves, scores = game.split(";")
if game:
_id = n
n += 1
yield _id, {"WhiteElo": white_elo,
"BlackElo": black_elo,
"fens": fens,
"moves": moves,
"scores": scores}
else:
break