Data update? <3

#6
by cekrse - opened

Hi @christopher ,

First, thank you a lot for preparing and providing this data.
Could you please update the data? I personally would be very happy to have the full year 2025 (Jan-Dec) covered.

Best,
cekrse

lichess org

Hi cekrse, thank you for the kind words!

We're currently rethinking how best to represent huge PGN files in .parquet and have paused exports. Hopefully this doesn't take too long. We're hoping to be back to exporting all PGNs by the end of June.

In the meantime, you can download the raw PGN files here: https://database.lichess.org/

Thank you for the quick response!

I was working with the already existing .parquet files until now, which worked well for me. Do you have a script or anything to share how to generate them from the raw files from the lichess database? Then I could potentially generate the files I need myself (monthly files up to the end of 2025).

lichess org

sure thing, i'll do that later tonight!

Also curious about your usage patterns for the data, if you're willing to share.

Thanks! I am working on a research paper - happy to share with you when a draft is ready.

Hi @christopher , just a friendly nudge 😃 and one additional thought: For my research, it would be incredibly useful to have recorded draw offers in the data. They are not in the monthly files provided on https://database.lichess.org/. Just in case you have access to the raw data, thinking about this would be great.

lichess org

Let me ask about draw offers and get back to you.

This is the script, sorry for the delay! (Bit messy because it was copied from a notebook :) )

SEVEN_TAG_ROSTER = {
    "Event": Value(dtype="string"),
    "Site": Value(dtype="string"),
    "White": Value(dtype="string"),
    "Black": Value(dtype="string"),
    "Result": Value(dtype="string")
}

PLAYER_TAGS = {
    "WhiteTitle": Value(dtype="string"),
    "BlackTitle": Value(dtype="string"),
    "WhiteElo": Value(dtype="int16"),
    "BlackElo": Value(dtype="int16"),
    "WhiteRatingDiff": Value(dtype="int16"),
    "BlackRatingDiff": Value(dtype="int16"),
}

DATE_TIME_TAGS = {
    "UTCDate": Value(dtype="date32"),
    "UTCTime": Value(dtype="time32[s]"),
}

GAME_TAGS = {
    "ECO": Value(dtype="string"), # https://github.com/lichess-org/scalachess/blob/ea0fc5c6e1b1c2ea9525c9b580c5b034decabd15/core/src/main/scala/variant/Variant.scala#L197-L200
    "Opening": Value(dtype="string"), # https://github.com/lichess-org/scalachess/blob/ea0fc5c6e1b1c2ea9525c9b580c5b034decabd15/core/src/main/scala/variant/Variant.scala#L197-L200
    "Termination": Value(dtype="string"),
    "TimeControl": Value(dtype="string"),
}

CHESS960_TAGS = {
    "FEN": Value(dtype="string"),
    "Termination": Value(dtype="string"),
    "TimeControl": Value(dtype="string"),
}

features = Features({**SEVEN_TAG_ROSTER, **PLAYER_TAGS, **DATE_TIME_TAGS, **GAME_TAGS, "movetext": Value(dtype="string")})
# features = Features({**SEVEN_TAG_ROSTER, **PLAYER_TAGS, **DATE_TIME_TAGS, **CHESS960_TAGS, "movetext": Value(dtype="string")})

def pgn_game_generator(pgn_file):
    with open(pgn_file, 'r') as file:
        current_game = []
        in_game = False
        for line in file:
            if line.startswith('[') and not in_game:
                # Start of a new game
                if ''.join(current_game).strip():
                    yield {"PGN": ''.join(current_game).strip()}
                    current_game = []
                in_game = True
            elif line.strip() == '' and in_game:
                # Empty line after header section
                in_game = False
            
            current_game.append(line)

        # Flush last game
        if ''.join(current_game).strip():
            yield {"PGN":''.join(current_game).strip()}


def batch_pgn_game_generator(pgn_files):
    for pgn_file in pgn_files:
        with open(pgn_file, 'r') as file:
            current_game = []
            in_game = False
            for line in file:
                if line.startswith('[') and not in_game:
                    # Start of a new game
                    if ''.join(current_game).strip():
                        yield {"PGN": ''.join(current_game).strip()}
                        current_game = []
                    in_game = True
                elif line.strip() == '' and in_game:
                    # Empty line after header section
                    in_game = False
                
                current_game.append(line)
    
            # Flush last game
            if ''.join(current_game).strip():
                yield {"PGN":''.join(current_game).strip()}

def split_pgn_file(input_file, output_folder, output_prefix, num_parts):
    os.makedirs(output_folder, exist_ok=True)
    
    # Calculate the number of digits needed for the part number
    num_digits = math.ceil(math.log10(num_parts))
    
    # First, count the total number of games
    total_games = 0
    with open(input_file, 'r') as infile:
        for line in infile:
            if line.startswith('[Event "'):
                total_games += 1
    
    # Calculate games per file
    games_per_file = math.ceil(total_games / num_parts)
    
    output_files = []
    current_part = 1
    game_count = 0
    current_game = []
    
    def write_part():
        nonlocal current_part, output_files
        if current_game:
            part_num = str(current_part).zfill(num_digits)
            output_file = os.path.join(output_folder, f"{output_prefix}_{part_num}.pgn")
            with open(output_file, 'w') as outfile:
                outfile.writelines(current_game)
            output_files.append(output_file)
            current_part += 1

    with open(input_file, 'r') as infile:
        for line in infile:
            if line.startswith('[Event "'):
                if game_count == games_per_file:
                    write_part()
                    game_count = 0
                    current_game = []
                game_count += 1
            
            current_game.append(line)
    
    # Write any remaining games
    if current_game:
        write_part()

    # print(f"Split completed. Check the output files in the '{output_folder}' directory.")
    return output_files


FEATURE_NAMES = list(features.keys())

def parse_row(row):
    pgn_string = row["PGN"]    
    headers, movetext = pgn_string.split("\n\n")
    headers = headers.split("\n")
    headers = {**dict([i[1:-1].split(" ",1) for i in [i.replace('"', '') for i in headers]])}

        
    HEADER_DICT = dict()
    for FEATURE in FEATURE_NAMES:
        HEADER_DICT[FEATURE] = headers.get(FEATURE, None)

    try:
        HEADER_DICT["WhiteElo"] =  int(HEADER_DICT["WhiteElo"])
    
    except:
        HEADER_DICT["WhiteElo"] = None
    
    try:
        HEADER_DICT["BlackElo"] =  int(HEADER_DICT["BlackElo"])
    
    except:
        HEADER_DICT["BlackElo"] = None
    
    try:
        HEADER_DICT["WhiteRatingDiff"] =  int(HEADER_DICT["WhiteRatingDiff"])
    
    except:
        HEADER_DICT["WhiteRatingDiff"] = None
    
    try:
        HEADER_DICT["BlackRatingDiff"] =  int(HEADER_DICT["BlackRatingDiff"])
    
    except:
        HEADER_DICT["BlackRatingDiff"] = None

    if HEADER_DICT["UTCDate"]:
        HEADER_DICT["UTCDate"] = date(*[int(i) for i in HEADER_DICT["UTCDate"].split(".")])
    
    if HEADER_DICT["UTCTime"]:
        HEADER_DICT["UTCTime"] = time(*[int(i) for i in HEADER_DICT["UTCTime"].split(":")], tzinfo=timezone.utc)
    
    if "?" in HEADER_DICT["ECO"]:
        HEADER_DICT["ECO"] = None

    if "?" in HEADER_DICT["Opening"]:
        HEADER_DICT["ECO"] = None
        
    return {**HEADER_DICT, "movetext": movetext}

variants = {"antichess": "antichess-chess-games" ,
            "atomic" :"atomic-chess-games",
            "chess960": "chess960-chess-games", # check features
            "crazyhouse": "crazyhouse-chess-games",
            "horde": "horde-chess-games",
            "kingOfTheHill": "king-of-the-hill-chess-games",
            "racingKings": "racing-kings-chess-games",
            "standard": "standard-chess-games", # check features
            "threeCheck": "three-check-chess-games" 
           }

VARIANT = "standard"
response = requests.get(f"https://database.lichess.org/{VARIANT}/list.txt")
zst_files = response.text.split("\n")
zst = [zst_file for zst_file in zst_files if "_2025-09" in zst_file]


for zst_file in tqdm(zst):
    try:
    # download file to folder
        filename = zst_file.split("/")[-1].split(".pgn.zst")[0]
        response = requests.get(zst_file, stream=True)
        os.mkdir(filename)
        with open(f"{filename}/{filename}.pgn.zst", mode="wb") as f:
            for chunk in response.iter_content(chunk_size=10 * 1024):
                f.write(chunk)
    # decompress bash
        !pzstd -d {filename}/{filename}.pgn.zst -p 64
    
    # load data + cache in same folder
        # dset = Dataset.from_generator(
        #         pgn_game_generator,
        #         gen_kwargs={"pgn_file": f"{filename}/{filename}.pgn"},
        #         cache_dir=f"{filename}/cache",
        #     )
        input_file = f"{filename}/{filename}.pgn"
        output_folder = f"{filename}/pgns"
        output_prefix = "partial_pgns"
        num_parts = 64

        split_files = split_pgn_file(input_file, output_folder, output_prefix, num_parts)
        # print(f"Created {len(split_files)} files: {', '.join(split_files)}")

        dset = Dataset.from_generator(
                batch_pgn_game_generator,
                num_proc=len(split_files),
                gen_kwargs={"pgn_files": split_files},
                cache_dir=f"{filename}/cache",
)
    # map + cache in same folder
        dset = dset.map(parse_row, num_proc=64, remove_columns=["PGN"], features=features, cache_file_name=f"{filename}/cache/cache.arrow")
    # push to hub
        year, month = filename.split("_")[-1].split("-")
        dset.push_to_hub(f"Lichess/{variants[VARIANT]}", data_dir=f"data/year={year}/month={month}", max_shard_size="3GB")
    # delete folder
        try:
            shutil.rmtree(filename)
        except:
            pass
    except:
        shutil.rmtree(filename)
lichess org

You can definitely simplify most of it and adapt it to your needs.

We'll start uploading / converting old parquet files soon.

I look forward to reading your paper! Feel free to submit a preprint here when it's ready: https://github.com/lichess-org/papers

Sign up or log in to comment