valentin-ub commited on
Commit
9c3e344
·
1 Parent(s): bc1c948

added UI for chess openings dataset

Browse files
Files changed (2) hide show
  1. app.py +66 -50
  2. chess_board.py +28 -17
app.py CHANGED
@@ -2,41 +2,29 @@ import os
2
  os.environ["KERAS_BACKEND"] = "torch" # "jax", "torch" or "tensorflow"
3
 
4
  import gradio as gr
5
- import keras_nlp
6
- import keras
7
- import spaces
8
- import torch
9
 
10
  from typing import Iterator
11
  import time
12
 
13
  from chess_board import Game
 
 
14
 
15
- import google.generativeai as genai
16
 
 
 
17
 
18
- print(f"Is CUDA available: {torch.cuda.is_available()}")
19
- print(f"CUDA device: {torch.cuda.get_device_name(torch.cuda.current_device())}")
20
-
21
- MAX_INPUT_TOKEN_LENGTH = 4096
22
-
23
- MAX_NEW_TOKENS = 2048
24
- DEFAULT_MAX_NEW_TOKENS = 128
25
-
26
- # model_id = "hf://google/gemma-2b-keras"
27
- # model_id = "hf://google/gemma-2-2b-it"
28
-
29
- # model_id = 'kaggle://valentinbaltazar/gemma-chess/keras/gemma_2b_en_chess'
30
-
31
-
32
- # model = keras_nlp.models.GemmaCausalLM.from_preset(model_id)
33
- # tokenizer = model.preprocessor.tokenizer
34
 
35
  DESCRIPTION = """
36
  # Chess Tutor AI
37
  **Welcome to the Chess Chatbot!**
38
 
39
- The goal of this project is to showcase the use of AI in learning chess. This app allows you to play a game against a custom fine-tuned model (Gemma 2B). The challenge is that input must be in *algebraic notation*.
 
40
 
41
  ## Features
42
 
@@ -46,20 +34,17 @@ The goal of this project is to showcase the use of AI in learning chess. This ap
46
  ### For Advanced Users
47
  - Pick an opening to play, and ask Gemini for more info.
48
 
49
-
50
- <br>
51
-
52
  Enjoy your game!
53
  **- Valentin**
54
  """
55
 
56
- api_key = os.getenv("GEMINI_API_KEY")
57
- genai.configure(api_key = api_key)
58
 
59
- model = genai.GenerativeModel(model_name='gemini-1.5-flash-latest')
60
 
61
  # Chat
62
- chat = model.start_chat()
63
 
64
  # @spaces.GPU
65
  def generate(
@@ -68,23 +53,36 @@ def generate(
68
  max_new_tokens: int = 1024,
69
  ) -> Iterator[str]:
70
 
71
- # input_ids = tokenizer.tokenize(message)
72
-
73
- # if len(input_ids) > MAX_INPUT_TOKEN_LENGTH:
74
- # input_ids = input_ids[-MAX_INPUT_TOKEN_LENGTH:]
75
- # gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
76
-
77
- # response = model.generate(message, max_length=max_new_tokens)
78
-
79
- response = chat.send_message(message)
80
 
81
  outputs = ""
82
 
83
- for char in response.text:
84
  outputs += char
85
  yield outputs
86
 
87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  chat_interface = gr.ChatInterface(
89
  fn=generate,
90
  stop_btn=None,
@@ -98,7 +96,9 @@ chat_interface = gr.ChatInterface(
98
  )
99
 
100
 
101
- with gr.Blocks(css_paths="styles.css", fill_height=True) as demo:
 
 
102
  gr.Markdown(DESCRIPTION)
103
 
104
  play_match = Game()
@@ -110,19 +110,35 @@ with gr.Blocks(css_paths="styles.css", fill_height=True) as demo:
110
  with gr.Column():
111
  chat_interface.render()
112
 
113
- game_logs = gr.Label(label="Game Logs", elem_id="game_logs_label")
114
-
115
- move_input = gr.Textbox(label="Enter your move in algebraic notation (e.g., e4, Nf3, Bxc4)")
116
- btn = gr.Button("Submit Move")
117
- btn.click(play_match.generate_moves, inputs=move_input, outputs=[board_image, game_logs])
118
- btn.click(lambda x: gr.update(value=''), [],[move_input])
119
-
120
- # btn.click(display_text, inputs=play_match.get_move_logs, outputs=text_output)
121
 
 
 
 
122
 
123
- reset_btn = gr.Button("Reset Game")
124
- reset_btn.click(play_match.reset_board, outputs=board_image)
 
 
125
 
 
 
 
126
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
  if __name__ == "__main__":
128
  demo.queue(max_size=20).launch()
 
2
  os.environ["KERAS_BACKEND"] = "torch" # "jax", "torch" or "tensorflow"
3
 
4
  import gradio as gr
5
+ # import keras_nlp
6
+ # import keras
7
+ # import spaces
8
+ # import torch
9
 
10
  from typing import Iterator
11
  import time
12
 
13
  from chess_board import Game
14
+ from datasets import load_dataset
15
+ # import google.generativeai as genai
16
 
 
17
 
18
+ # print(f"Is CUDA available: {torch.cuda.is_available()}")
19
+ # print(f"CUDA device: {torch.cuda.get_device_name(torch.cuda.current_device())}")
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
  DESCRIPTION = """
23
  # Chess Tutor AI
24
  **Welcome to the Chess Chatbot!**
25
 
26
+ The goal of this project is to showcase the use of AI in learning chess. This app allows you to play a game against a custom fine-tuned model (Gemma 2B).\n
27
+ The challenge is that input must be in *algebraic notation*.
28
 
29
  ## Features
30
 
 
34
  ### For Advanced Users
35
  - Pick an opening to play, and ask Gemini for more info.
36
 
 
 
 
37
  Enjoy your game!
38
  **- Valentin**
39
  """
40
 
41
+ # api_key = os.getenv("GEMINI_API_KEY")
42
+ # genai.configure(api_key = api_key)
43
 
44
+ # model = genai.GenerativeModel(model_name='gemini-1.5-flash-latest')
45
 
46
  # Chat
47
+ # chat = model.start_chat()
48
 
49
  # @spaces.GPU
50
  def generate(
 
53
  max_new_tokens: int = 1024,
54
  ) -> Iterator[str]:
55
 
56
+ response = "hi there" #chat.send_message(message)
 
 
 
 
 
 
 
 
57
 
58
  outputs = ""
59
 
60
+ for char in response:
61
  outputs += char
62
  yield outputs
63
 
64
 
65
+ # Load the dataset and convert to pandas DataFrame
66
+ ds = load_dataset("Lichess/chess-openings", split="train")
67
+ df = ds.to_pandas()
68
+
69
+ # Function to retrieve moves and name for a selected opening
70
+ def get_opening_details(opening_name):
71
+ opening_data = df[df['name'] == opening_name].iloc[0]
72
+ moves = opening_data['pgn']
73
+ return f"Opening: {opening_data['name']}\nMoves: {moves}"
74
+
75
+ def get_move_list(opening_name):
76
+ opening_data = df[df['name'] == opening_name].iloc[0]
77
+ moves = opening_data['pgn']
78
+ pgn_string = moves.split()
79
+ return [move for idx,move in enumerate(pgn_string[1:],1) if idx%3!=0]
80
+ # return ['e4', 'e5', 'Nf3']
81
+
82
+ # Create a list of unique opening names
83
+ opening_names = df['name'].unique().tolist()
84
+
85
+
86
  chat_interface = gr.ChatInterface(
87
  fn=generate,
88
  stop_btn=None,
 
96
  )
97
 
98
 
99
+ with gr.Blocks(css=""".big-text {
100
+ font-size: 2px !important;
101
+ }""", fill_height=True) as demo:
102
  gr.Markdown(DESCRIPTION)
103
 
104
  play_match = Game()
 
110
  with gr.Column():
111
  chat_interface.render()
112
 
113
+ game_logs = gr.Label(label="Game Logs", elem_classes=["big-text"])
 
 
 
 
 
 
 
114
 
115
+ with gr.Row():
116
+ with gr.Column():
117
+ gr.Markdown("### Play a Match vs Gemma")
118
 
119
+ move_input = gr.Textbox(label="Enter your move in algebraic notation: (e.g., e4, Nf3, Bxc4)")
120
+ submit_move = gr.Button("Submit Move")
121
+ submit_move.click(play_match.generate_moves, inputs=move_input, outputs=[board_image, game_logs])
122
+ submit_move.click(lambda x: gr.update(value=''), [],[move_input])
123
 
124
+ reset_board = gr.Button("Reset Game")
125
+ reset_board.click(play_match.reset_board, outputs=board_image)
126
+ reset_board.click(lambda x: gr.update(value=''), [],[game_logs])
127
 
128
+ with gr.Column():
129
+ gr.Markdown("### Chess Openings Explorer")
130
+
131
+ opening_choice = gr.Dropdown(label="Choose a Chess Opening", choices=opening_names)
132
+ opening_output = gr.Textbox(label="Opening Details", lines=4)
133
+ opening_moves = gr.State()
134
+
135
+ opening_choice.change(fn=get_opening_details, inputs=opening_choice, outputs=opening_output)
136
+ opening_choice.change(fn=get_move_list, inputs=opening_choice, outputs=opening_moves)
137
+
138
+
139
+ load_opening = gr.Button("Load Opening")
140
+ load_opening.click(play_match.reset_board, outputs=board_image)
141
+ load_opening.click(play_match.load_opening, inputs=[opening_choice, opening_moves], outputs=game_logs)
142
+
143
  if __name__ == "__main__":
144
  demo.queue(max_size=20).launch()
chess_board.py CHANGED
@@ -1,9 +1,9 @@
1
  # import os
2
  # os.environ["KERAS_BACKEND"] = "torch" # "jax", "torch" or "tensorflow"
3
 
4
- import keras_nlp
5
- import keras
6
- import torch
7
 
8
  import chess
9
  import chess.svg
@@ -17,27 +17,29 @@ class Game:
17
  self.counter = 0
18
  self.arrow= None
19
 
20
- self.model_id = 'kaggle://valentinbaltazar/gemma-chess/keras/gemma_2b_en_chess'
21
- self.sampler = keras_nlp.samplers.TopKSampler(k=50, temperature=0.7)
22
- self.model = keras_nlp.models.GemmaCausalLM.from_preset(self.model_id)
23
- self.compile_model()
24
 
25
  def compile_model(self):
26
  self.model.compile(sampler=self.sampler)
27
 
28
- def call_gemma(self):
29
  template = "Instruction:\n{instruction}\n\nResponse:\n{response}"
30
 
 
 
 
 
31
 
32
- prompt = template.format(
33
- instruction=f"Predict the next chess move in the sequence {str(self.sequence)}",
34
- response="",)
35
-
36
- output = self.model.generate(prompt, max_length=256)
37
-
38
- gemma_move = output.split(' ')[-1].strip("'")
39
 
40
- # gemma_move = 'e5'
 
 
41
 
42
  if self.make_move(gemma_move):
43
  print(f'Gemma plays {self.sequence[-1]}! (Current Sequence: {self.sequence} {len(self.sequence)})')
@@ -54,7 +56,10 @@ class Game:
54
  def gemma_moves(self):
55
  # print(f"Gemma is thinking...(Current Sequence: {self.sequence} {len(self.sequence)})")
56
  # time.sleep(3)
57
- return self.call_gemma()
 
 
 
58
 
59
  def player_moves(self, move):
60
  return self.make_move(move)
@@ -105,6 +110,12 @@ class Game:
105
 
106
  def get_move_logs(self):
107
  return self.sequence
 
 
 
 
 
 
108
 
109
 
110
  def main():
 
1
  # import os
2
  # os.environ["KERAS_BACKEND"] = "torch" # "jax", "torch" or "tensorflow"
3
 
4
+ # import keras_nlp
5
+ # import keras
6
+ # import torch
7
 
8
  import chess
9
  import chess.svg
 
17
  self.counter = 0
18
  self.arrow= None
19
 
20
+ # self.model_id = 'kaggle://valentinbaltazar/gemma-chess/keras/gemma_2b_en_chess'
21
+ # self.sampler = keras_nlp.samplers.TopKSampler(k=50, temperature=0.7)
22
+ # self.model = keras_nlp.models.GemmaCausalLM.from_preset(self.model_id)
23
+ # self.compile_model()
24
 
25
  def compile_model(self):
26
  self.model.compile(sampler=self.sampler)
27
 
28
+ def call_gemma(self, opening_move):
29
  template = "Instruction:\n{instruction}\n\nResponse:\n{response}"
30
 
31
+ if opening_move:
32
+ gemma_move = opening_move
33
+ else:
34
+ template = "Instruction:\n{instruction}\n\nResponse:\n{response}"
35
 
36
+ prompt = template.format(
37
+ instruction=f"Predict the next chess move in the sequence {str(self.sequence)}",
38
+ response="",)
 
 
 
 
39
 
40
+ # output = self.model.generate(prompt, max_length=256)
41
+
42
+ # gemma_move = output.split(' ')[-1].strip("'")
43
 
44
  if self.make_move(gemma_move):
45
  print(f'Gemma plays {self.sequence[-1]}! (Current Sequence: {self.sequence} {len(self.sequence)})')
 
56
  def gemma_moves(self):
57
  # print(f"Gemma is thinking...(Current Sequence: {self.sequence} {len(self.sequence)})")
58
  # time.sleep(3)
59
+ if self.opening_moves and len(self.sequence)<len(self.opening_moves):
60
+ return self.call_gemma(self.opening_moves[len(self.sequence)])
61
+ else:
62
+ return self.call_gemma(None)
63
 
64
  def player_moves(self, move):
65
  return self.make_move(move)
 
110
 
111
  def get_move_logs(self):
112
  return self.sequence
113
+
114
+ def load_opening(self, opening_name, opening_moves):
115
+ self.opening = True
116
+ self.opening_name = opening_name
117
+ self.opening_moves = opening_moves
118
+ return f"Ok, lets play the {opening_name}! {opening_moves} Make your first move."
119
 
120
 
121
  def main():