Danielzapirtan commited on
Commit
2a5b4cb
·
verified ·
1 Parent(s): 8553273

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +227 -0
app.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import subprocess
3
+ import threading
4
+ import queue
5
+ import os
6
+ import tempfile
7
+ import chess
8
+ import chess.pgn
9
+ import io
10
+
11
+ # Global dict to track running processes by session
12
+ running_processes = {}
13
+
14
+ def parse_input(text):
15
+ """Parse input as either PGN or FEN and return FEN position"""
16
+ text = text.strip()
17
+
18
+ # Check if it's a FEN (contains slashes and spaces typical of FEN)
19
+ if '/' in text and len(text.split()) >= 4:
20
+ try:
21
+ # Validate FEN
22
+ chess.Board(text)
23
+ return text, "fen"
24
+ except:
25
+ pass
26
+
27
+ # Try to parse as PGN
28
+ try:
29
+ pgn = io.StringIO(text)
30
+ game = chess.pgn.read_game(pgn)
31
+ if game:
32
+ board = game.end().board()
33
+ return board.fen(), "pgn"
34
+ except:
35
+ pass
36
+
37
+ return None, None
38
+
39
+ def read_output(process, output_queue, stop_event):
40
+ """Read output from process line by line"""
41
+ try:
42
+ for line in iter(process.stdout.readline, ''):
43
+ if stop_event.is_set():
44
+ break
45
+ output_queue.put(line)
46
+ process.stdout.close()
47
+ except:
48
+ pass
49
+
50
+ def run_engine(input_text, compile_mode, session_id, progress=gr.Progress()):
51
+ """Run the chess engine with the given input"""
52
+
53
+ # Parse input
54
+ fen, input_type = parse_input(input_text)
55
+
56
+ if not fen:
57
+ yield "Error: Could not parse input as valid PGN or FEN\n"
58
+ return
59
+
60
+ # Create temporary files for this session
61
+ temp_dir = tempfile.mkdtemp()
62
+
63
+ try:
64
+ if compile_mode == "PGN Mode (D_NOEDIT=1)":
65
+ # Create a PGN file with the position
66
+ pgn_path = os.path.join(temp_dir, "bench.pgn")
67
+ board = chess.Board(fen)
68
+ game = chess.pgn.Game()
69
+ game.setup(board)
70
+ with open(pgn_path, 'w') as f:
71
+ f.write(str(game))
72
+
73
+ # Copy or symlink the engine expecting pgn/bench.pgn
74
+ os.makedirs(os.path.join(temp_dir, "pgn"), exist_ok=True)
75
+ pgn_target = os.path.join(temp_dir, "pgn", "bench.pgn")
76
+ with open(pgn_target, 'w') as f:
77
+ f.write(str(game))
78
+
79
+ else: # FEN Mode (D_NOEDIT=2)
80
+ # Create start.fen file
81
+ fen_path = os.path.join(temp_dir, "start.fen")
82
+ with open(fen_path, 'w') as f:
83
+ f.write(fen)
84
+
85
+ # Start the engine process
86
+ engine_path = "./baeagn" # Adjust if needed
87
+ process = subprocess.Popen(
88
+ [engine_path],
89
+ stdout=subprocess.PIPE,
90
+ stderr=subprocess.STDOUT,
91
+ text=True,
92
+ bufsize=1,
93
+ cwd=temp_dir
94
+ )
95
+
96
+ # Store process for this session
97
+ running_processes[session_id] = process
98
+
99
+ # Setup queue and thread for reading output
100
+ output_queue = queue.Queue()
101
+ stop_event = threading.Event()
102
+ reader_thread = threading.Thread(
103
+ target=read_output,
104
+ args=(process, output_queue, stop_event)
105
+ )
106
+ reader_thread.daemon = True
107
+ reader_thread.start()
108
+
109
+ # Stream output
110
+ full_output = f"Input type: {input_type.upper()}\nFEN: {fen}\n\n--- Engine Output ---\n"
111
+ yield full_output
112
+
113
+ while True:
114
+ try:
115
+ # Check if process is still running
116
+ if process.poll() is not None:
117
+ # Process finished, drain queue
118
+ while not output_queue.empty():
119
+ line = output_queue.get_nowait()
120
+ full_output += line
121
+ yield full_output
122
+ break
123
+
124
+ # Get output with timeout
125
+ try:
126
+ line = output_queue.get(timeout=0.1)
127
+ full_output += line
128
+ yield full_output
129
+ except queue.Empty:
130
+ continue
131
+
132
+ except Exception as e:
133
+ full_output += f"\nError: {str(e)}\n"
134
+ yield full_output
135
+ break
136
+
137
+ # Cleanup
138
+ stop_event.set()
139
+ if session_id in running_processes:
140
+ del running_processes[session_id]
141
+
142
+ finally:
143
+ # Cleanup temp directory
144
+ try:
145
+ import shutil
146
+ shutil.rmtree(temp_dir)
147
+ except:
148
+ pass
149
+
150
+ def stop_engine(session_id):
151
+ """Stop the running engine for this session"""
152
+ if session_id in running_processes:
153
+ process = running_processes[session_id]
154
+ process.terminate()
155
+ try:
156
+ process.wait(timeout=2)
157
+ except:
158
+ process.kill()
159
+ del running_processes[session_id]
160
+ return "Engine stopped."
161
+ return "No running engine to stop."
162
+
163
+ def create_interface():
164
+ """Create the Gradio interface"""
165
+
166
+ with gr.Blocks(title="Baeagn Chess Engine") as demo:
167
+ gr.Markdown("# Baeagn Chess Engine Analyzer")
168
+ gr.Markdown("Paste a PGN game or FEN position to analyze the final/current position.")
169
+
170
+ with gr.Row():
171
+ with gr.Column(scale=1):
172
+ input_text = gr.Textbox(
173
+ label="Input (PGN or FEN)",
174
+ placeholder="Paste PGN game or FEN position here...",
175
+ lines=10
176
+ )
177
+
178
+ compile_mode = gr.Radio(
179
+ choices=["PGN Mode (D_NOEDIT=1)", "FEN Mode (D_NOEDIT=2)"],
180
+ value="FEN Mode (D_NOEDIT=2)",
181
+ label="Engine Compile Mode"
182
+ )
183
+
184
+ with gr.Row():
185
+ analyze_btn = gr.Button("Analyze", variant="primary")
186
+ stop_btn = gr.Button("Stop", variant="stop")
187
+
188
+ # Hidden session ID
189
+ session_id = gr.State(value=lambda: os.urandom(16).hex())
190
+
191
+ with gr.Column(scale=1):
192
+ output_text = gr.Textbox(
193
+ label="Engine Output",
194
+ lines=20,
195
+ max_lines=30,
196
+ autoscroll=True
197
+ )
198
+
199
+ # Examples
200
+ gr.Examples(
201
+ examples=[
202
+ ["rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"],
203
+ ["rnbqkb1r/pppp1ppp/5n2/4p3/4P3/5N2/PPPP1PPP/RNBQKB1R w KQkq - 4 3"],
204
+ ['[Event "Example"]\n[Site "?"]\n[Date "????.??.??"]\n[Round "?"]\n[White "?"]\n[Black "?"]\n[Result "*"]\n\n1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *']
205
+ ],
206
+ inputs=input_text
207
+ )
208
+
209
+ # Event handlers
210
+ analyze_btn.click(
211
+ fn=run_engine,
212
+ inputs=[input_text, compile_mode, session_id],
213
+ outputs=output_text
214
+ )
215
+
216
+ stop_btn.click(
217
+ fn=stop_engine,
218
+ inputs=session_id,
219
+ outputs=output_text
220
+ )
221
+
222
+ return demo
223
+
224
+ if __name__ == "__main__":
225
+ demo = create_interface()
226
+ demo.queue() # Enable queuing for streaming
227
+ demo.launch()