File size: 6,118 Bytes
045d76c
 
 
c82f95d
 
045d76c
 
de84014
045d76c
 
 
 
 
 
 
 
 
55ecc31
 
 
 
 
045d76c
 
 
 
 
55ecc31
045d76c
55ecc31
 
045d76c
 
 
 
 
 
 
 
 
 
 
c82f95d
045d76c
 
 
 
 
 
 
 
 
55ecc31
045d76c
 
55ecc31
045d76c
 
e53525f
c82f95d
dd4125a
045d76c
55ecc31
045d76c
 
 
 
 
 
 
55ecc31
045d76c
 
 
 
 
12a270b
045d76c
 
f4e8ffa
045d76c
 
55ecc31
045d76c
 
 
 
 
 
 
55ecc31
 
 
 
045d76c
e468937
045d76c
 
 
 
 
 
 
55ecc31
 
 
045d76c
 
 
55ecc31
 
 
 
045d76c
 
128d193
55ecc31
045d76c
 
 
 
 
 
 
 
d053bab
 
 
128d193
56114a5
045d76c
 
 
8e6ff6d
 
 
 
e53525f
 
 
 
c50cbfd
 
 
 
8e6ff6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fdf4637
8e6ff6d
 
045d76c
 
 
 
 
 
 
 
dd4125a
045d76c
 
 
 
 
 
 
 
 
 
fdf4637
 
d053bab
 
 
 
 
fdf4637
 
 
 
 
 
 
55ecc31
fdf4637
 
 
045d76c
128d193
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
"""Interface to play against the model.
"""

from typing import Optional

import huggingface_hub
import chess
import chess.svg
import uuid
import random
import wandb

import gradio as gr

from . import constants

model_name = "yp-edu/gpt2-stockfish-debug"
headers = {
    "X-Wait-For-Model": "true",
    "X-Use-Cache": "false",
}
client = huggingface_hub.InferenceClient(model=model_name, headers=headers)
inference_fn = client.text_generation


def plot_board(
    board: chess.Board,
    orientation: Optional[bool] = None,
):
    if orientation is None:
        orientation = board.turn
    try:
        last_move = board.peek()
        arrows = [(last_move.from_square, last_move.to_square)]
    except IndexError:
        arrows = []
    if board.is_check():
        check = board.king(board.turn)
    else:
        check = None
    svg_board = chess.svg.board(
        board,
        orientation=orientation,
        check=check,
        size=350,
        arrows=arrows,
    )
    id = str(uuid.uuid4())
    with open(f"{constants.FIGURE_DIRECTORY}/board_{id}.svg", "w") as f:
        f.write(svg_board)
    return f"{constants.FIGURE_DIRECTORY}/board_{id}.svg"


def render_board(
    current_board: chess.Board,
    orientation: Optional[bool] = None,
):
    fen = current_board.fen()
    pgn = current_board.root().variation_san(current_board.move_stack)
    image_board = plot_board(current_board, orientation=orientation)
    return fen, pgn, "", image_board


def play_user_move(
    uci_move: str,
    current_board: chess.Board,
):
    current_board.push_uci(uci_move)
    return current_board


def play_ai_move(
    current_board: chess.Board,
    temperature: float = 0.1,
):
    uci_move = inference_fn(
        prompt=f"FEN: {current_board.fen()}\nMOVE:",
        temperature=temperature,
    )
    current_board.push_uci(uci_move.strip())
    return current_board


def try_play_move(
    username: str,
    move_to_play: str,
    current_board: chess.Board,
):
    if current_board.is_game_over():
        gr.Warning("The game is already over")
        return (
            *render_board(current_board, orientation=not current_board.turn),
            current_board,
        )
    try:
        current_board = play_user_move(move_to_play.strip(), current_board)
        if current_board.is_game_over():
            gr.Info(f"Congratulations, {username}!")
            with wandb.init(project="gpt2-stockfish-debug", entity="yp-edu") as run:
                run.log(
                    {
                        "username": username,
                        "winin": current_board.fullmove_number,
                        "pgn": current_board.root().variation_san(
                            current_board.move_stack
                        ),
                    }
                )
                run.finish()
            return (
                *render_board(current_board, orientation=not current_board.turn),
                current_board,
            )
    except:
        gr.Warning("Invalid move")
        return *render_board(current_board), current_board
    temperature_retries = [(i + 1) / 10 for i in range(10)]
    for temperature in temperature_retries:
        try:
            current_board = play_ai_move(current_board, temperature=temperature)
            break
        except:
            gr.Warning(f"AI move failed with temperature {temperature}")
    else:
        gr.Warning("AI move failed with all temperatures")
        random_move = random.choice(list(current_board.legal_moves))
        gr.Warning(f"Playing random move {random_move}")
        current_board.push(random_move)
        return *render_board(current_board), current_board
    return *render_board(current_board), current_board


with gr.Blocks() as interface:
    with gr.Row():
        with gr.Column():
            username = gr.Textbox(
                label="Username to record on leaderboard (should you win)",
                lines=1,
                max_lines=1,
                value="",
            )
            leaderboard_md = gr.Markdown(
                label="Leaderboard",
                value="See the leaderboard [here](https://wandb.ai/yp-edu/gpt2-stockfish-debug/reports/Leaderboard--Vmlldzo2OTU0NDc2?accessToken=xito8t675j3e55owwer09hp3kk9emdg8620kesufhbng0ap4uodlulrny0t0o15n).",
            )
            current_fen = gr.Textbox(
                label="Board FEN",
                lines=1,
                max_lines=1,
                value=chess.STARTING_FEN,
            )
            current_pgn = gr.Textbox(
                label="Action sequence",
                lines=1,
                value="",
            )
            with gr.Row():
                move_to_play = gr.Textbox(
                    label="Move to play (UCI)",
                    lines=1,
                    max_lines=1,
                    value="",
                )
                play_button = gr.Button("Play")
            reset_button = gr.Button("Reset")
        with gr.Column():
            image_board = gr.Image(label="Board")

    static_inputs = [
        username,
        move_to_play,
    ]
    static_outputs = [
        current_fen,
        current_pgn,
        move_to_play,
        image_board,
    ]
    is_ai_white = random.choice([True, False])
    init_board = chess.Board()
    if is_ai_white:
        init_board = play_ai_move(init_board)
    state_board = gr.State(value=init_board)
    play_button.click(
        try_play_move,
        inputs=[*static_inputs, state_board],
        outputs=[*static_outputs, state_board],
    )
    move_to_play.submit(
        try_play_move,
        inputs=[*static_inputs, state_board],
        outputs=[*static_outputs, state_board],
    )

    def reset_board():
        board = chess.Board()
        is_ai_white = random.choice([True, False])
        if is_ai_white:
            board = play_ai_move(board)
        return *render_board(board), board

    reset_button.click(
        reset_board,
        outputs=[*static_outputs, state_board],
    )
    interface.load(render_board, inputs=[state_board], outputs=[*static_outputs])