"""This a module for downloading games from database.lihess.org.""" import os import io import sys import chess.pgn import traceback import zstandard import requests import datasets _CITATION = """NOTTHING YET""" _DESCRIPTION = """\ Lichess.org is a free/libre, open-source chess server powered by volunteers and donations and provides all of its content in CC0. This script download all the games from the database and provide them in LLM pretraining friendly format. """ _HOMEPAGE = "" _LICENSE = "Creative Commons Zero v1.0 Universal" _URLS = { "base_url": "https://database.lichess.org/standard/", } _FILE_TEMPLATE = "lichess_db_standard_rated_{}.pgn.zst" _DOWNLOAD_LIST = "https://database.lichess.org/standard/list.txt" def get_dates_configs(): # download download_list using requests: r = requests.get(_DOWNLOAD_LIST) files = r.text.split("\n") # https://database.lichess.org/standard/lichess_db_standard_rated_2023-06.pgn.zst # split every line to get the date dates_configs = [f.split("_")[-1].split(".")[0] for f in files] return dates_configs class LichessGames(datasets.GeneratorBasedBuilder): """Lichess games""" VERSION = datasets.Version("1.0.0") configs = get_dates_configs() BUILDER_CONFIGS = [ datasets.BuilderConfig( name=d, version=datasets.Version("1.0.0"), description=f"Games of {d}", ) for d in configs ] DEFAULT_CONFIG_NAME = configs[0] def _info(self): features = datasets.Features( { "text": datasets.Value("string"), } ) return datasets.DatasetInfo( description=_DESCRIPTION, features=features, homepage=_HOMEPAGE, license=_LICENSE, citation=_CITATION, ) def _split_generators(self, dl_manager): file_name = _FILE_TEMPLATE.format(self.config.name) url = {self.config.name: _URLS["base_url"] + file_name} data_dir = dl_manager.download(url) return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, # These kwargs will be passed to _generate_examples gen_kwargs={ "filepath": data_dir[self.config.name], "split": "train", }, ), ] # method parameters are unpacked from `gen_kwargs` as given in `_split_generators` def _generate_examples(self, filepath, split): try: with open(filepath, 'rb') as f: dctx = zstandard.ZstdDecompressor() stream_reader = dctx.stream_reader(f) pgn = io.TextIOWrapper(stream_reader, encoding="utf-8") k = 0 while True: try: game = chess.pgn.read_game(pgn) except Exception as e: print(e) break if game is None: break k += 1 yield f"{self.config.name}-{k}", {'text': str(game)} except Exception as e: traceback.print_exc(file=sys.stdout) return