File size: 3,288 Bytes
da93298
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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