bettermint commited on
Commit
98de093
·
verified ·
1 Parent(s): dfac5b8

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +44 -96
main.py CHANGED
@@ -1,6 +1,5 @@
1
- from fastapi import FastAPI, WebSocket
2
- from fastapi.middleware.cors import CORSMiddleware
3
- from fastapi.responses import HTMLResponse
4
  import subprocess
5
  import asyncio
6
  import os
@@ -10,6 +9,12 @@ from queue import Queue, Empty
10
 
11
  os.environ['LD_LIBRARY_PATH'] = '/engines/maia/lib:' + os.environ.get('LD_LIBRARY_PATH', '')
12
 
 
 
 
 
 
 
13
  def enqueue_output(out, queue):
14
  for line in iter(out.readline, b''):
15
  queue.put(line)
@@ -29,9 +34,9 @@ class EngineChess:
29
  self.thread = Thread(target=enqueue_output, args=(self._stockfish.stdout, self.queueOutput))
30
  self.thread.daemon = True # thread dies with the program
31
  self.thread.start()
32
-
33
  self._has_quit_command_been_sent = False
34
- self._debug_view = True
35
 
36
  def _put(self, command):
37
  if not self._stockfish.stdin:
@@ -41,150 +46,93 @@ class EngineChess:
41
  self._stockfish.stdin.flush()
42
  if command == "quit":
43
  self._has_quit_command_been_sent = True
44
-
45
  def _read_line(self) -> str:
46
  if not self._stockfish.stdout:
47
  raise BrokenPipeError()
48
  if self._stockfish.poll() is not None:
49
  raise StockfishException("The Stockfish process has crashed")
50
-
51
  try:
52
  line = self.queueOutput.get_nowait() # or q.get(timeout=.1)
53
  except Empty:
54
  return ""
55
-
56
  if self._debug_view:
57
  print(f"Engine {self.path_engine[0]}:", line.strip())
58
  return line.strip()
59
-
60
  def _is_ready(self) -> None:
61
  self._put("isready")
62
  while self._read_line() != "readyok":
63
  pass
64
-
65
  def put(self, cmd):
66
  return self._put(cmd)
67
-
68
  def read_line(self) -> str:
69
  return self._read_line()
70
 
71
  app = FastAPI()
 
72
 
73
- app.add_middleware(
74
- CORSMiddleware,
75
- allow_origins=["*"],
76
- allow_credentials=True,
77
- allow_methods=["*"],
78
- allow_headers=["*"],
79
- )
80
-
81
  @app.websocket("/stockfish-{version}")
82
  async def websocket_endpoint(websocket: WebSocket, version: str):
83
  await websocket.accept()
84
-
85
- stockfish = EngineChess([f"./engines/stockfish/stockfish-{version}-uci"])
 
86
 
87
  async def read_from_socket(websocket: WebSocket):
88
  async for data in websocket.iter_text():
89
  print(f"Stockfish Client: {data}")
90
  stockfish.put(data)
91
-
92
  asyncio.create_task(read_from_socket(websocket))
93
 
94
- while True:
95
  while True:
96
  res = stockfish.read_line()
97
  if res:
98
  await websocket.send_text(f"{res}")
99
  else:
100
  break
101
- await asyncio.sleep(0.1)
 
 
102
 
103
  @app.websocket("/maia-{elo}")
104
  async def websocket_endpoint(websocket: WebSocket, elo: str):
105
  await websocket.accept()
106
-
107
- stockfish = EngineChess([f"./engines/maia/maia-{elo}/lc0", "--backend=trivial"])
 
108
 
109
  async def read_from_socket(websocket: WebSocket):
110
  async for data in websocket.iter_text():
111
  print(f"Maia Client: {data}")
112
  stockfish.put(data)
113
-
114
  asyncio.create_task(read_from_socket(websocket))
115
 
116
- while True:
117
  while True:
118
  res = stockfish.read_line()
119
  if res:
120
  await websocket.send_text(f"{res}")
121
  else:
122
  break
123
- await asyncio.sleep(0.1)
124
-
125
-
126
-
127
-
128
-
129
- ########################
130
- async def get_prompt():
131
- # Get current working directory
132
- cwd = os.getcwd()
133
- # Shorten path if it is too long
134
- if len(cwd) > 30:
135
- cwd = os.path.basename(cwd)
136
- cwd = f".../{cwd}"
137
- return f"{cwd}$ "
138
-
139
- async def exec_command(command):
140
- try:
141
- # Execute command using subprocess
142
- process = await asyncio.create_subprocess_shell(
143
- command,
144
- stdout=subprocess.PIPE,
145
- stderr=subprocess.PIPE,
146
- shell=True,
147
- executable='/bin/bash'
148
- )
149
-
150
- # Wait for command to complete
151
- stdout, stderr = await process.communicate()
152
-
153
- # Prepare output to send back
154
- output = stdout.decode() + stderr.decode()
155
-
156
- except Exception as e:
157
- output = str(e)
158
-
159
- return output
160
-
161
- async def send_prompt(websocket):
162
- # Send initial prompt to client
163
- prompt = await get_prompt()
164
- await websocket.send_text(prompt)
165
-
166
- @app.websocket("/shell")
167
- async def websocket_endpoint(websocket: WebSocket):
168
- await websocket.accept()
169
- await send_prompt(websocket)
170
-
171
- try:
172
- while True:
173
- # Receive command from client
174
- command = await websocket.receive_text()
175
-
176
- if command == "exit":
177
- await websocket.send_text("Goodbye!")
178
- break
179
-
180
- # Execute command
181
- output = await exec_command(command)
182
-
183
- # Send output to client
184
- await websocket.send_text(output)
185
-
186
- # Send updated prompt to client
187
- await send_prompt(websocket)
188
-
189
- except websockets.exceptions.ConnectionClosedError:
190
- pass
 
1
+ from fastapi import FastAPI, Request, WebSocket
2
+ from fastapi.templating import Jinja2Templates
 
3
  import subprocess
4
  import asyncio
5
  import os
 
9
 
10
  os.environ['LD_LIBRARY_PATH'] = '/engines/maia/lib:' + os.environ.get('LD_LIBRARY_PATH', '')
11
 
12
+ user_playing = {
13
+ 'total': 0,
14
+ 'stockfish': 0,
15
+ 'maia': 0
16
+ }
17
+
18
  def enqueue_output(out, queue):
19
  for line in iter(out.readline, b''):
20
  queue.put(line)
 
34
  self.thread = Thread(target=enqueue_output, args=(self._stockfish.stdout, self.queueOutput))
35
  self.thread.daemon = True # thread dies with the program
36
  self.thread.start()
37
+
38
  self._has_quit_command_been_sent = False
39
+ self._debug_view = False
40
 
41
  def _put(self, command):
42
  if not self._stockfish.stdin:
 
46
  self._stockfish.stdin.flush()
47
  if command == "quit":
48
  self._has_quit_command_been_sent = True
49
+
50
  def _read_line(self) -> str:
51
  if not self._stockfish.stdout:
52
  raise BrokenPipeError()
53
  if self._stockfish.poll() is not None:
54
  raise StockfishException("The Stockfish process has crashed")
55
+
56
  try:
57
  line = self.queueOutput.get_nowait() # or q.get(timeout=.1)
58
  except Empty:
59
  return ""
60
+
61
  if self._debug_view:
62
  print(f"Engine {self.path_engine[0]}:", line.strip())
63
  return line.strip()
64
+
65
  def _is_ready(self) -> None:
66
  self._put("isready")
67
  while self._read_line() != "readyok":
68
  pass
69
+
70
  def put(self, cmd):
71
  return self._put(cmd)
72
+
73
  def read_line(self) -> str:
74
  return self._read_line()
75
 
76
  app = FastAPI()
77
+ templates = Jinja2Templates(directory="templates")
78
 
79
+ # WebSocket endpoints
 
 
 
 
 
 
 
80
  @app.websocket("/stockfish-{version}")
81
  async def websocket_endpoint(websocket: WebSocket, version: str):
82
  await websocket.accept()
83
+
84
+ user_playing['total'] += 1
85
+ user_playing['stockfish'] += 1
86
 
87
  async def read_from_socket(websocket: WebSocket):
88
  async for data in websocket.iter_text():
89
  print(f"Stockfish Client: {data}")
90
  stockfish.put(data)
91
+
92
  asyncio.create_task(read_from_socket(websocket))
93
 
94
+ try:
95
  while True:
96
  res = stockfish.read_line()
97
  if res:
98
  await websocket.send_text(f"{res}")
99
  else:
100
  break
101
+ finally:
102
+ user_playing['total'] -= 1
103
+ user_playing['stockfish'] -= 1
104
 
105
  @app.websocket("/maia-{elo}")
106
  async def websocket_endpoint(websocket: WebSocket, elo: str):
107
  await websocket.accept()
108
+
109
+ user_playing['total'] += 1
110
+ user_playing['maia'] += 1
111
 
112
  async def read_from_socket(websocket: WebSocket):
113
  async for data in websocket.iter_text():
114
  print(f"Maia Client: {data}")
115
  stockfish.put(data)
116
+
117
  asyncio.create_task(read_from_socket(websocket))
118
 
119
+ try:
120
  while True:
121
  res = stockfish.read_line()
122
  if res:
123
  await websocket.send_text(f"{res}")
124
  else:
125
  break
126
+ finally:
127
+ user_playing['total'] -= 1
128
+ user_playing['maia'] -= 1
129
+
130
+
131
+ @app.get("/")
132
+ async def root(request: Request):
133
+ return templates.TemplateResponse("index.html", {
134
+ "request": request,
135
+ "total_users": user_playing['total'],
136
+ "stockfish_users": user_playing['stockfish'],
137
+ "maia_users": user_playing['maia']
138
+ })