File size: 5,067 Bytes
045d76c
 
 
 
 
de84014
045d76c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e53525f
045d76c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fdf4637
045d76c
12a270b
045d76c
 
 
f4e8ffa
045d76c
 
 
 
 
 
 
 
 
128d193
045d76c
 
 
 
 
 
 
 
 
 
 
 
 
128d193
045d76c
 
128d193
045d76c
 
 
 
 
 
 
 
 
 
 
 
128d193
045d76c
 
 
8e6ff6d
 
 
 
e53525f
 
 
 
8e6ff6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fdf4637
8e6ff6d
 
045d76c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Interface to play against the model.
"""

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"}
client = huggingface_hub.InferenceClient(
    model=model_name, headers=headers
)
inference_fn = client.text_generation


def plot_board(
    board: chess.Board,
):
    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,
        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,
):
    fen = current_board.fen()
    pgn = current_board.root().variation_san(current_board.move_stack)
    image_board = plot_board(current_board)
    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,
    top_k: int = 3,
):
    print(f"Playing AI move with temperature {temperature}")
    uci_move = inference_fn(
        prompt=f"FEN: {current_board.fen()}\nMOVE:",
        temperature=temperature,
        top_k=top_k,
    )
    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), current_board
    try:
        current_board = play_user_move(move_to_play, 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.variation_san(current_board.move_stack),
                    }
                )
                run.finish()
            return *render_board(current_board), 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")
        current_board.pop()
        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="",
            )
            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,
        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],
    )

    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])