bettermint commited on
Commit
c03517d
·
verified ·
1 Parent(s): 51b6ec0

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +96 -8
main.py CHANGED
@@ -1,11 +1,99 @@
1
- from fastapi import FastAPI
2
- import platform
3
- import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  app = FastAPI()
6
 
7
- @app.get("/")
8
- def index():
9
- for v in range(1, 17):
10
- os.system(f"./engines/stockfish-{v}-uci")
11
- return platform.machine()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
7
+ from threading import Thread
8
+ from queue import Queue, Empty
9
+
10
+ def enqueue_output(out, queue):
11
+ for line in iter(out.readline, b''):
12
+ queue.put(line)
13
+ out.close()
14
+
15
+ class EngineChess:
16
+ def __init__(self, path_engine):
17
+ self._stockfish = subprocess.Popen(
18
+ path_engine,
19
+ universal_newlines=True,
20
+ stdin=subprocess.PIPE,
21
+ stdout=subprocess.PIPE,
22
+ stderr=subprocess.STDOUT,
23
+ )
24
+ self.queueOutput = Queue()
25
+ self.thread = Thread(target=enqueue_output, args=(self._stockfish.stdout, self.queueOutput))
26
+ self.thread.daemon = True # thread dies with the program
27
+ self.thread.start()
28
+
29
+ self._has_quit_command_been_sent = False
30
+ self._debug_view = False
31
+
32
+ def _put(self, command):
33
+ if not self._stockfish.stdin:
34
+ raise BrokenPipeError()
35
+ if self._stockfish.poll() is None and not self._has_quit_command_been_sent:
36
+ if self._debug_view:
37
+ print(f">>> {command}\n")
38
+ self._stockfish.stdin.write(f"{command}\n")
39
+ self._stockfish.stdin.flush()
40
+ if command == "quit":
41
+ self._has_quit_command_been_sent = True
42
+
43
+ def _read_line(self) -> str:
44
+ if not self._stockfish.stdout:
45
+ raise BrokenPipeError()
46
+ if self._stockfish.poll() is not None:
47
+ raise StockfishException("The Stockfish process has crashed")
48
+
49
+ try:
50
+ line = self.queueOutput.get_nowait() # or q.get(timeout=.1)
51
+ except Empty:
52
+ return ""
53
+
54
+ if self._debug_view:
55
+ print(line.strip())
56
+ return line.strip()
57
+
58
+ def _is_ready(self) -> None:
59
+ self._put("isready")
60
+ while self._read_line() != "readyok":
61
+ pass
62
+
63
+ def put(self, cmd):
64
+ return self._put(cmd)
65
+
66
+ def read_line(self) -> str:
67
+ return self._read_line()
68
 
69
  app = FastAPI()
70
 
71
+ app.add_middleware(
72
+ CORSMiddleware,
73
+ allow_origins=["*"],
74
+ allow_credentials=True,
75
+ allow_methods=["*"],
76
+ allow_headers=["*"],
77
+ )
78
+
79
+ @app.websocket("/stockfish-{version}")
80
+ async def websocket_endpoint(websocket: WebSocket, version: str):
81
+ await websocket.accept()
82
+
83
+ stockfish = EngineChess(f"engines/stockfish-{version}-uci")
84
+
85
+ async def read_from_socket(websocket: WebSocket):
86
+ async for data in websocket.iter_text():
87
+ print(f"Client: {data}")
88
+ stockfish.put(data)
89
+
90
+ asyncio.create_task(read_from_socket(websocket))
91
+
92
+ while True:
93
+ while True:
94
+ res = stockfish.read_line()
95
+ if res != "":
96
+ await websocket.send_text(f"{res}")
97
+ else:
98
+ break
99
+ await asyncio.sleep(0.1)