akhaliq HF staff commited on
Commit
a97f2da
1 Parent(s): b3a61ba

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -44
app.py CHANGED
@@ -1,51 +1,62 @@
1
  import gradio as gr
2
  import chess
3
  import chess.svg
4
- import io
5
- import random
6
- from PIL import Image
7
- import cairosvg
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
- def make_move(move_san, board_fen):
10
- board = chess.Board(fen=board_fen)
11
  try:
12
- move = board.parse_san(move_san)
13
- if move in board.legal_moves:
14
- board.push(move)
15
- if board.is_game_over():
16
- message = "Game over. You win!"
17
- else:
18
- # Computer makes a random move
19
- computer_move = random.choice(list(board.legal_moves))
20
- board.push(computer_move)
21
- message = f"Computer played: {board.san(computer_move)}"
22
- if board.is_game_over():
23
- message += "\nGame over. Computer wins."
24
- # Generate board image
25
- svg_data = chess.svg.board(board=board, size=400)
26
- png_data = cairosvg.svg2png(bytestring=svg_data)
27
- image = Image.open(io.BytesIO(png_data))
28
- return image, board.fen(), message
29
  else:
30
- return gr.update(), board_fen, "Illegal move."
 
31
  except Exception as e:
32
- return gr.update(), board_fen, f"Error: {str(e)}"
33
-
34
- def get_initial_board():
35
- board = chess.Board()
36
- svg_data = chess.svg.board(board=board, size=400)
37
- png_data = cairosvg.svg2png(bytestring=svg_data)
38
- image = Image.open(io.BytesIO(png_data))
39
- return image, board.fen()
40
-
41
- with gr.Blocks() as demo:
42
- initial_image, initial_fen = get_initial_board()
43
- img = gr.Image(value=initial_image, interactive=False)
44
- move_input = gr.Textbox(label="Enter your move in standard notation (e.g., e4, Nf3, Bb5)")
45
- output = gr.Textbox(label="Message")
46
- board_state = gr.State(value=initial_fen)
47
- submit_button = gr.Button("Submit Move")
48
-
49
- submit_button.click(fn=make_move, inputs=[move_input, board_state], outputs=[img, board_state, output])
50
-
51
- demo.launch()
 
1
  import gradio as gr
2
  import chess
3
  import chess.svg
4
+ import os
5
+ import google.generativeai as genai
6
+
7
+ # Configure the Google Generative AI client
8
+ genai.configure(api_key=os.environ["API_KEY"])
9
+
10
+ board = chess.Board()
11
+
12
+ def get_ai_move(fen):
13
+ """
14
+ Gets the AI's next move using Google Gemini via google.generativeai.
15
+
16
+ Args:
17
+ fen (str): The current board position in FEN notation.
18
+
19
+ Returns:
20
+ str or None: The AI's move in UCI format, or None if an error occurs.
21
+ """
22
+ # Prepare the prompt for the AI
23
+ prompt = f"""You are a chess engine. Given the following board position in FEN notation:
24
+ {fen}
25
+ It's your turn to move. Provide the best move in UCI format (e.g., 'e2e4'). Only provide the move, without any additional text."""
26
 
 
 
27
  try:
28
+ # Generate the response from the AI model
29
+ response = genai.generate_text(
30
+ model="gemini-1.5-flash", # Use the Gemini model
31
+ prompt=prompt,
32
+ temperature=0, # To make the output more deterministic
33
+ max_output_tokens=5
34
+ )
35
+ ai_move = response.result.strip()
36
+
37
+ # Validate the move
38
+ legal_moves = [move.uci() for move in board.legal_moves]
39
+ if ai_move in legal_moves:
40
+ return ai_move
 
 
 
 
41
  else:
42
+ print(f"Invalid move received from the AI: {ai_move}")
43
+ return None
44
  except Exception as e:
45
+ print(f"Error occurred: {e}")
46
+ return None
47
+
48
+ def board_to_svg(board):
49
+ return chess.svg.board(board=board)
50
+
51
+ def make_move(user_move):
52
+ global board
53
+ try:
54
+ # Player's move
55
+ board.push_san(user_move)
56
+ except ValueError:
57
+ return gr.update(value=board_to_svg(board)), "Invalid move. Try again."
58
+
59
+ # Check for game over
60
+ if board.is_game_over():
61
+ result = board.result()
62
+ board_svg = board_to_svg(b