Ghostbot commited on
Commit
64f40d7
ยท
verified ยท
1 Parent(s): 5eef525

Upload 3 files

Browse files
Files changed (3) hide show
  1. Dockerfile +21 -0
  2. app.py +77 -0
  3. requirements.txt +3 -0
Dockerfile ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ WORKDIR /app
4
+
5
+ # Install dependencies needed for python execution
6
+ COPY requirements.txt .
7
+ RUN pip install --no-cache-dir -r requirements.txt
8
+
9
+ # Download, extract, and install Stockfish using Python to bypass wget issues
10
+ RUN set -ex && \
11
+ python -c "import urllib.request; urllib.request.urlretrieve('https://github.com/official-stockfish/Stockfish/releases/download/sf_18/stockfish-ubuntu-x86-64-avx2.tar', 'stockfish.tar')" && \
12
+ tar -xf stockfish.tar && \
13
+ STOCKFISH_BIN=$(find . -type f -name "*stockfish*x86-64*" -executable | head -n 1) && \
14
+ mv "$STOCKFISH_BIN" /usr/local/bin/stockfish && \
15
+ rm -rf stockfish.tar stockfish* && \
16
+ chmod +x /usr/local/bin/stockfish
17
+
18
+ COPY app.py .
19
+
20
+ EXPOSE 7860
21
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
app.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ from fastapi import FastAPI, WebSocket, WebSocketDisconnect
3
+ import subprocess
4
+ import logging
5
+
6
+ # Configure basic logging
7
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
8
+ logger = logging.getLogger(__name__)
9
+
10
+ app = FastAPI()
11
+
12
+ STOCKFISH_PATH = "/usr/local/bin/stockfish"
13
+
14
+ @app.get("/")
15
+ def read_root():
16
+ return {"status": "Stockfish 18 Cloud API is running"}
17
+
18
+ @app.websocket("/ws")
19
+ async def websocket_endpoint(websocket: WebSocket):
20
+ await websocket.accept()
21
+ client_ip = websocket.client.host
22
+ logger.info(f"WebSocket connection OPENED from {client_ip}")
23
+
24
+ try:
25
+ process = subprocess.Popen(
26
+ [STOCKFISH_PATH],
27
+ stdin=subprocess.PIPE,
28
+ stdout=subprocess.PIPE,
29
+ stderr=subprocess.STDOUT,
30
+ text=True,
31
+ bufsize=1 # Line-buffered
32
+ )
33
+ logger.info(f"Stockfish process started with PID: {process.pid}")
34
+ except Exception as e:
35
+ logger.error(f"Error starting engine: {e}")
36
+ await websocket.send_text(f"Error starting engine: {e}")
37
+ await websocket.close()
38
+ return
39
+
40
+ async def read_from_stockfish():
41
+ loop = asyncio.get_event_loop()
42
+ try:
43
+ while True:
44
+ line = await loop.run_in_executor(None, process.stdout.readline)
45
+ if not line:
46
+ break
47
+ line_str = line.strip()
48
+ # Log only important lines or every line if debugging heavily.
49
+ # logger.debug(f"[Engine -> WS]: {line_str}")
50
+ await websocket.send_text(line_str)
51
+ except Exception as e:
52
+ logger.error(f"Error reading from stockfish: {e}")
53
+
54
+ task = asyncio.create_task(read_from_stockfish())
55
+
56
+ try:
57
+ while True:
58
+ data = await websocket.receive_text()
59
+ # logger.info(f"[WS -> Engine]: {data}") # Uncomment to see every command sent to engine
60
+ if data.startswith("position"):
61
+ logger.info(f"๐Ÿ“ Received Position FEN -> Ready for analysis")
62
+ elif data.startswith("go"):
63
+ logger.info(f"๐Ÿš€ Started Engine Search: {data}")
64
+ elif data.startswith("stop"):
65
+ logger.info(f"๐Ÿ›‘ Received Stop Command -> Aborting search")
66
+
67
+ if process.poll() is None:
68
+ process.stdin.write(data + "\n")
69
+ process.stdin.flush()
70
+ except WebSocketDisconnect:
71
+ logger.info(f"WebSocket connection CLOSED by client {client_ip}")
72
+ finally:
73
+ task.cancel()
74
+ if process.poll() is None:
75
+ logger.info(f"Terminating Stockfish process {process.pid}")
76
+ process.terminate()
77
+ process.wait()
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ fastapi
2
+ uvicorn
3
+ websockets