AI-Chess-Player / app.py
ashish-001's picture
Upload app.py
f29f094 verified
import chess
import chess.svg
import gradio as gr
import tempfile
import tensorflow as tf
import numpy as np
# Initializing the board
board = chess.Board()
model = tf.keras.models.load_model('test.h5')
def display_board(board_):
board_svg = chess.svg.board(board=board_)
with tempfile.NamedTemporaryFile(delete=False, suffix=".svg") as f:
f.write(board_svg.encode('utf-8'))
return f.name
def one_hot_encode_pieces(piece):
pieces = list('rnbqkpRNBQKP.')
arr = np.zeros(len(pieces))
piece_to_index = {p: i for i, p in enumerate(pieces)}
index = piece_to_index[piece]
arr[index] = 1
return arr
def encode_board(board__):
board_str = str(board__)
board_str = board_str.replace(" ", "")
board_list = []
for row in board_str.split("\n"):
row_list = []
for i in row:
row_list.append(one_hot_encode_pieces(i))
board_list.append(row_list)
return np.array(board_list)
def play_nn(curr_fen, model):
board__ = chess.Board(curr_fen)
moves = []
input_vectors = []
for move in board__.legal_moves:
curr_board = board.copy()
moves.append(move)
curr_board.push(move)
input_vectors.append(encode_board(curr_board))
input_vectors = np.stack(input_vectors)
scores = model.predict(input_vectors, verbose=0)
if board.turn == chess.BLACK:
return moves[np.argmax(scores)]
else:
return moves[np.argmax(~scores)]
def make_move(move):
global board
if len(move) > 3:
turn = "White"
new_turn = "Black"
if chess.Move.from_uci(move) in board.legal_moves:
board.push(chess.Move.from_uci(move))
if board.outcome():
return f"White won", display_board(board)
ai_move = str(play_nn(board.fen(), model))
board.push(chess.Move.from_uci(ai_move))
if board.outcome():
return f"Black won", display_board(board)
message = f"{turn} move: {move},move accepted\nAI moved: {ai_move}\n\n{turn}'s move."
else:
message = f"{turn} move: Illegal move. Please try again."
return message, display_board(board)
else:
winner = "White" if board.outcome() == chess.WHITE else "Black"
return f"{winner} won", display_board(board)
def reset_board():
global board
board = chess.Board()
return "Board reset.", display_board(board)
# Setting up gradio interface
with gr.Blocks() as demo:
gr.Markdown("## Chess board game")
with gr.Row():
with gr.Column():
move_input = gr.Textbox(placeholder="Enter your move in UCI format (e.g. e2e3)", lines=1)
move_button = gr.Button("Make move")
reset_button = gr.Button("Reset Board")
status_output = gr.Textbox(label='Status', interactive=False)
with gr.Column():
board_output = gr.Image(type='filepath', label='Chess Board', value=display_board(board))
move_button.click(make_move, inputs=move_input, outputs=[status_output, board_output])
reset_button.click(reset_board, inputs=None, outputs=[status_output, board_output])
demo.launch()