Created
June 16, 2019 02:15
-
-
Save mattbillenstein/75aa123dacad7c6ae347cd5815b3db94 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# sudo apt-get install libcairo2 | |
# pip install requests python-chess Pillow CairoSVG | |
import io | |
import sys | |
import time | |
import cairosvg | |
import chess.pgn | |
import chess.svg | |
import requests | |
from PIL import Image | |
def fetch_pgn(game_id): | |
r = requests.get('https://lichess.org/game/export/' + game_id) | |
assert r.ok, r.content | |
return r.content.decode('utf8').strip() | |
def board_to_png(board, move=None): | |
check = None | |
if board.is_check(): | |
check = board.king(board.turn) | |
b = chess.svg.board(board, lastmove=move, coordinates=False, check=check) | |
return cairosvg.svg2png(b) | |
def export_gif(images, fname): | |
duration = [450] * len(images) | |
duration[-1] = 2000 | |
images[0].save(fname, format='GIF', append_images=images[1:], save_all=True, duration=duration, loop=0) | |
def main(args): | |
pgn = fetch_pgn(args[0]) | |
game = chess.pgn.read_game(io.StringIO(pgn)) | |
assert game.headers['Variant'] == 'Standard' | |
board = game.board() | |
png = board_to_png(board) | |
images = [] | |
im = Image.open(io.BytesIO(png)) | |
images.append(im) | |
for i, move in enumerate(game.mainline_moves()): | |
board.push(move) | |
png = board_to_png(board, move) | |
im = Image.open(io.BytesIO(png)) | |
images.append(im) | |
export_gif(images, args[1]) | |
if __name__ == '__main__': | |
main(sys.argv[1:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment