Lyte commited on
Commit
5071575
·
verified ·
1 Parent(s): 27d555c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +139 -10
app.py CHANGED
@@ -3,11 +3,13 @@ import gradio as gr
3
  from llama_cpp import Llama
4
  from huggingface_hub import hf_hub_download
5
  import numpy as np
 
 
6
 
7
  model = Llama(
8
  model_path=hf_hub_download(
9
- repo_id=os.environ.get("REPO_ID", "Lyte/QuadConnect2.5-0.5B-v0.0.6b"),#"Lyte/QuadConnect2.5-0.5B-v0.0.5b"),
10
- filename=os.environ.get("MODEL_FILE", "quadconnect.Q8_0.gguf"),#"unsloth.Q8_0.gguf"),
11
  ),
12
  n_ctx=16384
13
  )
@@ -35,11 +37,95 @@ Specify the column letter (a–g) for your next move.
35
  </move>
36
  """
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  class ConnectFour:
39
  def __init__(self):
40
  self.board = np.zeros((6, 7))
41
  self.current_player = 1 # 1 for player (X), 2 for AI (O)
42
  self.game_over = False
 
 
43
 
44
  def make_move(self, col):
45
  if self.game_over:
@@ -47,9 +133,17 @@ class ConnectFour:
47
 
48
  # Find the lowest empty row in the selected column
49
  for row in range(5, -1, -1):
50
- if self.board[row][col] == 0:
51
- self.board[row][col] = self.current_player
52
- return True, row
 
 
 
 
 
 
 
 
53
  return False, -1
54
 
55
  def check_winner(self):
@@ -96,7 +190,17 @@ class ConnectFour:
96
  row_num = str(6 - row) # Convert to 1-based indexing
97
  piece = "X" if self.board[row][col] == 1 else "O"
98
  moves.append(f"{col_letter}{row_num}({piece})")
99
- return ", ".join(moves) if moves else ""
 
 
 
 
 
 
 
 
 
 
100
 
101
  def parse_ai_move(self, move_str):
102
  # Parse move like 'a', 'b', etc.
@@ -107,6 +211,25 @@ class ConnectFour:
107
  return -1
108
  except:
109
  return -1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
 
111
  def create_interface():
112
  game = ConnectFour()
@@ -228,15 +351,15 @@ def create_interface():
228
 
229
  # AI move
230
  game.current_player = 2
231
- board_state = game.board_to_string()
232
 
233
- prompt = f"Current board state (you are O, opponent is X):\n{board_state}\n\nMake your move."
 
234
 
235
  # Get AI response
236
  response = model.create_chat_completion(
237
  messages=[
238
  {"role": "system", "content": SYSTEM_PROMPT},
239
- {"role": "user", "content": prompt}
240
  ],
241
  temperature=0.8,
242
  top_p=0.95,
@@ -249,7 +372,11 @@ def create_interface():
249
  # Extract reasoning and move
250
  try:
251
  reasoning = ai_response.split("<reasoning>")[1].split("</reasoning>")[0].strip()
252
- move_str = ai_response.split("<move>")[1].split("</move>")[0].strip()
 
 
 
 
253
  ai_col = game.parse_ai_move(move_str)
254
 
255
  if ai_col == -1:
@@ -298,6 +425,8 @@ def create_interface():
298
  game.board = np.zeros((6, 7))
299
  game.current_player = 1
300
  game.game_over = False
 
 
301
  return [
302
  render_board(),
303
  "Your turn! Click a button to drop your piece!",
 
3
  from llama_cpp import Llama
4
  from huggingface_hub import hf_hub_download
5
  import numpy as np
6
+ from typing import List
7
+ import re
8
 
9
  model = Llama(
10
  model_path=hf_hub_download(
11
+ repo_id=os.environ.get("REPO_ID", "Lyte/QuadConnect2.5-0.5B-v0.0.6b"),
12
+ filename=os.environ.get("MODEL_FILE", "quadconnect.Q8_0.gguf"),
13
  ),
14
  n_ctx=16384
15
  )
 
37
  </move>
38
  """
39
 
40
+ def extract_xml_move(text: str) -> str:
41
+ """
42
+ Extracts the move (a single column letter a–g) from the XML format
43
+ using regex.
44
+ """
45
+ match = re.search(r'<move>\s*([a-g])\s*</move>', text)
46
+ if match:
47
+ return match.group(1)
48
+ return ""
49
+
50
+ def convert_moves_to_coordinate_list(moves_list: List[str]) -> str:
51
+ """
52
+ Converts a list of moves to a coordinate list representation.
53
+ Each move is formatted as <column><row>(<piece>).
54
+ Returns "Empty Board" if no moves are present.
55
+ """
56
+ # Create an empty 6x7 grid (row 1 is at index 0)
57
+ grid = [['.' for _ in range(7)] for _ in range(6)]
58
+
59
+ for i, move in enumerate(moves_list):
60
+ if not move:
61
+ continue
62
+ col = ord(move[0]) - ord('a')
63
+ # Find the lowest available row in this column:
64
+ for row in range(6):
65
+ if grid[row][col] == '.':
66
+ grid[row][col] = 'X' if i % 2 == 0 else 'O'
67
+ break
68
+
69
+ # Build coordinate list: Only include cells with a piece
70
+ coords = []
71
+ for row in range(6):
72
+ for col in range(7):
73
+ if grid[row][col] != '.':
74
+ # Convert row index to board row number (row 0 -> 1, etc.)
75
+ coords.append(f"{chr(col + ord('a'))}{row+1}({grid[row][col]})")
76
+
77
+ return ", ".join(coords) if coords else "Empty Board"
78
+
79
+ def parse_coordinate_list(board_str: str) -> List[List[str]]:
80
+ """
81
+ Converts a coordinate list representation (e.g., "a1(O), a2(X), b1(O)")
82
+ into a 6x7 grid (list of lists) with row index 0 as the bottom.
83
+ """
84
+ grid = [['.' for _ in range(7)] for _ in range(6)]
85
+ if not board_str.strip() or board_str == "Empty Board":
86
+ return grid
87
+
88
+ coords = board_str.split(",")
89
+ for coord in coords:
90
+ coord = coord.strip()
91
+ # Expecting format: a1(O)
92
+ if len(coord) < 4:
93
+ continue
94
+ col_letter = coord[0]
95
+ try:
96
+ row_number = int(coord[1])
97
+ except ValueError:
98
+ continue
99
+ piece = coord[3] # The piece inside the parentheses
100
+ col = ord(col_letter) - ord('a')
101
+ row = row_number - 1
102
+ if 0 <= row < 6 and 0 <= col < 7:
103
+ grid[row][col] = piece
104
+ return grid
105
+
106
+ def get_available_positions(grid: List[List[str]]) -> str:
107
+ """Returns the next available position (lowest empty spot) for each column."""
108
+ available = []
109
+ for col in range(7):
110
+ col_letter = chr(ord('a') + col)
111
+ # Search from bottom (row 0) to top (row 5)
112
+ next_pos = None
113
+ for row in range(6):
114
+ if grid[row][col] == '.': # Found empty spot
115
+ next_pos = f"{col_letter}{row + 1}" # +1 because grid is 0-based
116
+ break
117
+ if next_pos: # Only add if column isn't full
118
+ available.append(f"{col_letter}: {next_pos}")
119
+
120
+ return "\n ".join(available) # Format with newlines and indentation
121
+
122
  class ConnectFour:
123
  def __init__(self):
124
  self.board = np.zeros((6, 7))
125
  self.current_player = 1 # 1 for player (X), 2 for AI (O)
126
  self.game_over = False
127
+ self.player_moves = []
128
+ self.ai_moves = []
129
 
130
  def make_move(self, col):
131
  if self.game_over:
 
133
 
134
  # Find the lowest empty row in the selected column
135
  for row in range(5, -1, -1):
136
+ if self.board[5-row][col] == 0: # Flip the row index to match the display
137
+ self.board[5-row][col] = self.current_player
138
+
139
+ # Record the move
140
+ move = f"{chr(ord('a') + col)}{row+1}"
141
+ if self.current_player == 1:
142
+ self.player_moves.append(move)
143
+ else:
144
+ self.ai_moves.append(move)
145
+
146
+ return True, 5-row
147
  return False, -1
148
 
149
  def check_winner(self):
 
190
  row_num = str(6 - row) # Convert to 1-based indexing
191
  piece = "X" if self.board[row][col] == 1 else "O"
192
  moves.append(f"{col_letter}{row_num}({piece})")
193
+ return ", ".join(moves) if moves else "Empty Board"
194
+
195
+ def get_grid_from_board(self):
196
+ grid = [['.' for _ in range(7)] for _ in range(6)]
197
+ for row in range(6):
198
+ for col in range(7):
199
+ if self.board[row][col] == 1:
200
+ grid[5-row][col] = 'X' # Convert to the format used by helper functions
201
+ elif self.board[row][col] == 2:
202
+ grid[5-row][col] = 'O'
203
+ return grid
204
 
205
  def parse_ai_move(self, move_str):
206
  # Parse move like 'a', 'b', etc.
 
211
  return -1
212
  except:
213
  return -1
214
+
215
+ def format_game_state(self):
216
+ board_str = self.board_to_string()
217
+ grid = self.get_grid_from_board()
218
+ available_positions = get_available_positions(grid)
219
+
220
+ # Format the player and AI moves
221
+ player_moves_str = ", ".join(self.player_moves) if self.player_moves else ""
222
+ ai_moves_str = ", ".join(self.ai_moves) if self.ai_moves else ""
223
+
224
+ return f"""Game State:
225
+ - You are playing as: O
226
+ - Your previous moves: {ai_moves_str}
227
+ - Opponent's moves: {player_moves_str}
228
+ - Current board state: {board_str}
229
+ - Next available position per column:
230
+ {available_positions}
231
+
232
+ Make your move."""
233
 
234
  def create_interface():
235
  game = ConnectFour()
 
351
 
352
  # AI move
353
  game.current_player = 2
 
354
 
355
+ # Format game state using the new format
356
+ game_state = game.format_game_state()
357
 
358
  # Get AI response
359
  response = model.create_chat_completion(
360
  messages=[
361
  {"role": "system", "content": SYSTEM_PROMPT},
362
+ {"role": "user", "content": game_state}
363
  ],
364
  temperature=0.8,
365
  top_p=0.95,
 
372
  # Extract reasoning and move
373
  try:
374
  reasoning = ai_response.split("<reasoning>")[1].split("</reasoning>")[0].strip()
375
+ move_str = extract_xml_move(ai_response)
376
+
377
+ if not move_str:
378
+ raise ValueError("Invalid move format from AI")
379
+
380
  ai_col = game.parse_ai_move(move_str)
381
 
382
  if ai_col == -1:
 
425
  game.board = np.zeros((6, 7))
426
  game.current_player = 1
427
  game.game_over = False
428
+ game.player_moves = []
429
+ game.ai_moves = []
430
  return [
431
  render_board(),
432
  "Your turn! Click a button to drop your piece!",