silentengine 1.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
silentengine/engine.py ADDED
@@ -0,0 +1,293 @@
1
+ from __future__ import annotations
2
+ import threading
3
+ import time
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+
7
+ import chess
8
+ import chess.engine
9
+ import chess.pgn
10
+ import chess.polyglot
11
+ import chess.svg
12
+ from PySide6.QtCore import (
13
+ QThread,
14
+ Signal,
15
+ )
16
+
17
+ from silentengine.review import line_fraction
18
+ from silentengine.constants import POPEN_KW
19
+
20
+
21
+ @dataclass
22
+ class Job:
23
+ fen: str
24
+ path: str
25
+ multipv: int
26
+ seconds: int
27
+ threads: int
28
+ hash_mb: int
29
+
30
+
31
+ def analyse_fen(engine: chess.engine.SimpleEngine, fen: str, ms: int) -> dict:
32
+ board = chess.Board(fen)
33
+ if board.is_game_over():
34
+ mate = board.is_checkmate()
35
+ return {
36
+ "frac": (1.0 if board.turn == chess.BLACK else 0.0) if mate else 0.5,
37
+ "best": None,
38
+ "cp": None,
39
+ "mate": None,
40
+ "second": None,
41
+ "pv": [],
42
+ }
43
+ infos = engine.analyse(board, chess.engine.Limit(time=ms / 1000), multipv=2)
44
+ info = infos[0]
45
+ sc = info["score"].white()
46
+ line = {
47
+ "cp": None if sc.is_mate() else sc.score(),
48
+ "mate": sc.mate() if sc.is_mate() else None,
49
+ }
50
+ pv = list(info.get("pv") or [])
51
+ second = None
52
+ if len(infos) > 1 and "score" in infos[1]:
53
+ s2 = infos[1]["score"].white()
54
+ second = line_fraction(
55
+ {
56
+ "cp": None if s2.is_mate() else s2.score(),
57
+ "mate": s2.mate() if s2.is_mate() else None,
58
+ }
59
+ )
60
+ return {
61
+ "frac": line_fraction(line),
62
+ "best": pv[0] if pv else None,
63
+ "cp": line["cp"],
64
+ "mate": line["mate"],
65
+ "second": second,
66
+ "pv": pv[:6],
67
+ }
68
+
69
+
70
+ class EngineWorker(QThread):
71
+ update = Signal(str, object) # fen, list[dict] (white's point of view)
72
+ message = Signal(str)
73
+ engine_name = Signal(str)
74
+
75
+ def __init__(self) -> None:
76
+ super().__init__()
77
+ self._event = threading.Event()
78
+ self._lock = threading.Lock()
79
+ self._job: Job | None = None
80
+ self._gen = 0
81
+ self._alive = True
82
+ self._engine: chess.engine.SimpleEngine | None = None
83
+ self._path: str | None = None
84
+ self._applied: tuple | None = None
85
+
86
+ def submit(self, job: Job | None) -> None:
87
+ """Start analysing `job` (cancelling any running search); None just stops."""
88
+ with self._lock:
89
+ self._gen += 1
90
+ self._job = job
91
+ self._event.set()
92
+
93
+ def shutdown(self) -> None:
94
+ self._alive = False
95
+ self.submit(None)
96
+ self.wait(5000)
97
+
98
+ def run(self) -> None:
99
+ while self._alive:
100
+ with self._lock:
101
+ job, gen = self._job, self._gen
102
+ self._job = None
103
+ if job is None:
104
+ self._event.wait()
105
+ self._event.clear()
106
+ continue
107
+ try:
108
+ self._run_job(job, gen)
109
+ except chess.engine.EngineTerminatedError:
110
+ self.message.emit("Engine stopped unexpectedly")
111
+ self._drop_engine()
112
+ except Exception as exc: # bad path, permissions, protocol errors...
113
+ self.message.emit(f"Engine error: {exc}")
114
+ self._drop_engine()
115
+ self._drop_engine()
116
+
117
+ def _run_job(self, job: Job, gen: int) -> None:
118
+ board = chess.Board(job.fen)
119
+ if board.is_game_over():
120
+ return
121
+ self._ensure_engine(job)
122
+ limit = (
123
+ chess.engine.Limit(time=job.seconds)
124
+ if job.seconds > 0
125
+ else chess.engine.Limit()
126
+ )
127
+ lines: dict[int, dict] = {}
128
+ last_emit = 0.0
129
+ with self._engine.analysis(board, limit, multipv=job.multipv) as analysis:
130
+ for info in analysis:
131
+ if not self._alive or self._gen != gen:
132
+ return
133
+ if "pv" not in info or "score" not in info:
134
+ continue
135
+ lines[info.get("multipv", 1)] = self._convert(board, info)
136
+ now = time.monotonic()
137
+ if now - last_emit > 0.12:
138
+ last_emit = now
139
+ self.update.emit(job.fen, [lines[k] for k in sorted(lines)])
140
+ if lines and self._alive and self._gen == gen:
141
+ self.update.emit(job.fen, [lines[k] for k in sorted(lines)])
142
+
143
+ @staticmethod
144
+ def _convert(board: chess.Board, info) -> dict:
145
+ score = info["score"].white()
146
+ pv, sans, b = [], [], board.copy(stack=False)
147
+ try:
148
+ for m in list(info["pv"][:7]):
149
+ sans.append(b.san(m))
150
+ b.push(m)
151
+ pv.append(m)
152
+ except ValueError:
153
+ pass
154
+ if not pv:
155
+ pv = [info["pv"][0]]
156
+ return {
157
+ "cp": score.score() if not score.is_mate() else None,
158
+ "mate": score.mate() if score.is_mate() else None,
159
+ "depth": info.get("depth", 0),
160
+ "nps": info.get("nps", 0),
161
+ "sans": sans,
162
+ "pv": pv,
163
+ "first": pv[0],
164
+ }
165
+
166
+ def _ensure_engine(self, job: Job) -> None:
167
+ if self._engine is not None and self._path != job.path:
168
+ self._drop_engine()
169
+ if self._engine is None:
170
+ self.message.emit("Starting engine…")
171
+ self._engine = chess.engine.SimpleEngine.popen_uci(job.path, **POPEN_KW)
172
+ self._path = job.path
173
+ self._applied = None
174
+ self.engine_name.emit(self._engine.id.get("name", Path(job.path).stem))
175
+ want = (job.threads, job.hash_mb)
176
+ if self._applied != want:
177
+ options = self._engine.options
178
+ cfg = {}
179
+ for name, value in (("Threads", job.threads), ("Hash", job.hash_mb)):
180
+ if name in options:
181
+ opt = options[name]
182
+ cfg[name] = min(value, opt.max) if opt.max else value
183
+ if cfg:
184
+ self._engine.configure(cfg)
185
+ self._applied = want
186
+
187
+ def _drop_engine(self) -> None:
188
+ if self._engine is not None:
189
+ try:
190
+ self._engine.quit()
191
+ except Exception:
192
+ pass
193
+ self._engine, self._path, self._applied = None, None, None
194
+
195
+
196
+ # --------------------------------------------------------------------------- #
197
+ # --------------------------------------------------------------------------- #
198
+
199
+
200
+ class ReviewWorker(QThread):
201
+ progress = Signal(int, int)
202
+ done = Signal(object)
203
+ failed = Signal(str)
204
+
205
+ def __init__(
206
+ self, fens: list[str], path: str, ms: int, threads: int, hash_mb: int
207
+ ) -> None:
208
+ super().__init__()
209
+ self.fens, self.path, self.ms = fens, path, ms
210
+ self.threads, self.hash_mb = threads, hash_mb
211
+ self._cancel = False
212
+
213
+ def cancel(self) -> None:
214
+ self._cancel = True
215
+
216
+ def run(self) -> None:
217
+ engine = None
218
+ try:
219
+ engine = chess.engine.SimpleEngine.popen_uci(self.path, **POPEN_KW)
220
+ cfg = {}
221
+ for name, value in (("Threads", self.threads), ("Hash", self.hash_mb)):
222
+ if name in engine.options:
223
+ opt = engine.options[name]
224
+ cfg[name] = min(value, opt.max) if opt.max else value
225
+ if cfg:
226
+ engine.configure(cfg)
227
+ results = []
228
+ for i, fen in enumerate(self.fens):
229
+ if self._cancel:
230
+ return
231
+ board = chess.Board(fen)
232
+ if board.is_checkmate():
233
+ results.append(
234
+ {
235
+ "frac": 1.0 if board.turn == chess.BLACK else 0.0,
236
+ "best": None,
237
+ "cp": None,
238
+ "mate": None,
239
+ "second": None,
240
+ "pv": [],
241
+ }
242
+ )
243
+ elif board.is_game_over():
244
+ results.append(
245
+ {
246
+ "frac": 0.5,
247
+ "best": None,
248
+ "cp": None,
249
+ "mate": None,
250
+ "second": None,
251
+ "pv": [],
252
+ }
253
+ )
254
+ else:
255
+ infos = engine.analyse(
256
+ board, chess.engine.Limit(time=self.ms / 1000), multipv=2
257
+ )
258
+ info = infos[0]
259
+ sc = info["score"].white()
260
+ line = {
261
+ "cp": None if sc.is_mate() else sc.score(),
262
+ "mate": sc.mate() if sc.is_mate() else None,
263
+ }
264
+ pv = list(info.get("pv") or [])
265
+ second = None
266
+ if len(infos) > 1 and "score" in infos[1]:
267
+ s2 = infos[1]["score"].white()
268
+ second = line_fraction(
269
+ {
270
+ "cp": None if s2.is_mate() else s2.score(),
271
+ "mate": s2.mate() if s2.is_mate() else None,
272
+ }
273
+ )
274
+ results.append(
275
+ {
276
+ "frac": line_fraction(line),
277
+ "best": pv[0] if pv else None,
278
+ "cp": line["cp"],
279
+ "mate": line["mate"],
280
+ "second": second,
281
+ "pv": pv[:6],
282
+ }
283
+ )
284
+ self.progress.emit(i + 1, len(self.fens))
285
+ self.done.emit(results)
286
+ except Exception as exc:
287
+ self.failed.emit(str(exc))
288
+ finally:
289
+ if engine is not None:
290
+ try:
291
+ engine.quit()
292
+ except Exception:
293
+ pass
@@ -0,0 +1,263 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import shutil
5
+ import sys
6
+ import tarfile
7
+ import tempfile
8
+ import urllib.request
9
+ import zipfile
10
+ import platform
11
+ from pathlib import Path
12
+
13
+ from PySide6.QtCore import Qt, QThread, Signal
14
+ from PySide6.QtWidgets import (
15
+ QDialog,
16
+ QFileDialog,
17
+ QHBoxLayout,
18
+ QLabel,
19
+ QProgressBar,
20
+ QToolButton,
21
+ QVBoxLayout,
22
+ )
23
+
24
+ from silentengine.constants import DATA_DIR
25
+
26
+ TAG = "sf_19"
27
+ BASE = f"https://github.com/official-stockfish/Stockfish/releases/download/{TAG}/"
28
+ # asset name -> sha256 (hex). Fill these in; an entry that's missing skips the check.
29
+ SHA256: dict[str, str] = {
30
+ "stockfish-windows-x86-64-universal.zip": "3C8BF1F9EA66A09350A40DF4F632288285AC206D99F33AB5842C408FC30B48A7",
31
+ "stockfish-windows-arm64-universal.zip": "8372ad3f0d7276deb2c70f801f541ec7db463219fc6d9c7592864e542aa4f401",
32
+ "stockfish-linux-x86-64-universal.tar.gz": "9defc0d4e55d49c65a6d042f3e571a39fcea499ade6dbe741b53b8c65e03611f",
33
+ "stockfish-linux-arm64-universal.tar.gz": "fe26cfd1d9db4c8af3d21e24d9ff34cacb31c1f940085a7583da11796f2bac01",
34
+ "stockfish-macos-universal.tar.gz": "a1f0e3bcc5a6927a11fe6fc8e54a779754645f3c2bae2cf13420fd1957adaa77",
35
+ }
36
+
37
+
38
+ def asset_name() -> str | None:
39
+ machine = platform.machine().lower()
40
+ arm = machine in ("arm64", "aarch64")
41
+ if sys.platform.startswith("win"):
42
+ return f"stockfish-windows-{'arm64' if arm else 'x86-64'}-universal.zip"
43
+ if sys.platform == "darwin":
44
+ return "stockfish-macos-universal.tar.gz"
45
+ if sys.platform.startswith("linux"):
46
+ if arm:
47
+ return "stockfish-linux-arm64-universal.tar.gz"
48
+ if machine in ("x86_64", "amd64"):
49
+ return "stockfish-linux-x86-64-universal.tar.gz"
50
+ return None
51
+
52
+
53
+ def unpack(archive: Path, out: Path) -> None:
54
+ base = out.resolve()
55
+
56
+ def safe(name: str) -> bool:
57
+ return (base / name).resolve().is_relative_to(base)
58
+
59
+ if archive.suffix == ".zip":
60
+ with zipfile.ZipFile(archive) as z:
61
+ if not all(safe(n) for n in z.namelist()):
62
+ raise RuntimeError("unsafe path inside the archive")
63
+ z.extractall(out)
64
+ else:
65
+ with tarfile.open(archive) as t:
66
+ members = t.getmembers()
67
+ for m in members:
68
+ if not safe(m.name) or not (m.isfile() or m.isdir()):
69
+ raise RuntimeError("unexpected item inside the archive")
70
+ kw = {"filter": "data"} if hasattr(tarfile, "data_filter") else {}
71
+ t.extractall(out, members=members, **kw)
72
+
73
+
74
+ def find_binary(root: Path) -> Path | None:
75
+ best = None
76
+ for p in root.rglob("*"):
77
+ if (
78
+ p.is_file()
79
+ and "stockfish" in p.name.lower()
80
+ and p.suffix.lower() in ("", ".exe")
81
+ and p.stat().st_size > 5_000_000
82
+ ):
83
+ if best is None or p.stat().st_size > best.stat().st_size:
84
+ best = p
85
+ return best
86
+
87
+
88
+ class DownloadWorker(QThread):
89
+ progress = Signal(int, int)
90
+ status = Signal(str)
91
+ done = Signal(str)
92
+ failed = Signal(str)
93
+
94
+ def __init__(self, asset: str) -> None:
95
+ super().__init__()
96
+ self.asset = asset
97
+ self._cancel = False
98
+
99
+ def cancel(self) -> None:
100
+ self._cancel = True
101
+
102
+ def run(self) -> None:
103
+ tmp = Path(tempfile.mkdtemp(prefix="silentengine_"))
104
+ result: str | None = None
105
+ error: str | None = None
106
+ try:
107
+ archive = tmp / self.asset
108
+ sha = hashlib.sha256()
109
+ req = urllib.request.Request(
110
+ BASE + self.asset, headers={"User-Agent": "SilentEngine"}
111
+ )
112
+ with urllib.request.urlopen(req, timeout=30) as r, open(archive, "wb") as f:
113
+ total = int(r.headers.get("Content-Length") or 0)
114
+ got = 0
115
+ while True:
116
+ if self._cancel:
117
+ raise RuntimeError("cancelled")
118
+ chunk = r.read(1 << 16)
119
+ if not chunk:
120
+ break
121
+ f.write(chunk)
122
+ sha.update(chunk)
123
+ got += len(chunk)
124
+ self.progress.emit(got, total)
125
+ want = SHA256.get(self.asset)
126
+ if want and sha.hexdigest().lower() != want.lower():
127
+ raise RuntimeError("checksum mismatch, the file was rejected")
128
+ self.status.emit("Unpacking…")
129
+ out = tmp / "unpacked"
130
+ out.mkdir()
131
+ unpack(archive, out)
132
+ binary = find_binary(out)
133
+ if binary is None:
134
+ raise RuntimeError("no engine found inside the download")
135
+ dest_dir = DATA_DIR / "engines"
136
+ dest_dir.mkdir(parents=True, exist_ok=True)
137
+ dest = dest_dir / binary.name
138
+ shutil.move(str(binary), dest)
139
+ dest.chmod(dest.stat().st_mode | 0o111)
140
+ result = str(dest)
141
+ except Exception as exc:
142
+ error = str(exc)
143
+ finally:
144
+ shutil.rmtree(tmp, ignore_errors=True)
145
+ # emit only after cleanup, so the thread is basically finished
146
+ if error is not None:
147
+ self.failed.emit(error)
148
+ else:
149
+ self.done.emit(result)
150
+
151
+
152
+ class EngineSetupDialog(QDialog):
153
+ chosen = Signal(str) # path of the engine to use
154
+
155
+ def __init__(self, parent=None) -> None:
156
+ super().__init__(parent)
157
+ self.setWindowTitle("SilentEngine")
158
+ self.setMinimumWidth(480)
159
+ self.asset = asset_name()
160
+ self.worker: DownloadWorker | None = None
161
+
162
+ lay = QVBoxLayout(self)
163
+ lay.setSpacing(10)
164
+ text = QLabel(
165
+ "SilentEngine analyzes games with a UCI chess engine. "
166
+ "Stockfish is free and open source.<br><br>"
167
+ "<b>Download</b> gets Stockfish 19 from the official GitHub releases "
168
+ "(about 80 MB). It's the only network request SilentEngine makes, and "
169
+ "only if you click it.<br>"
170
+ "<b>Choose file…</b> uses an engine you already have."
171
+ )
172
+ text.setTextFormat(Qt.RichText)
173
+ text.setWordWrap(True)
174
+ lay.addWidget(text)
175
+ self.status = QLabel("")
176
+ self.status.setStyleSheet("color:#888;")
177
+ self.status.setWordWrap(True)
178
+ self.bar = QProgressBar()
179
+ self.bar.setTextVisible(False)
180
+ self.bar.hide()
181
+ lay.addWidget(self.status)
182
+ lay.addWidget(self.bar)
183
+
184
+ self.dl_btn = QToolButton()
185
+ self.dl_btn.setText("Download Stockfish 19")
186
+ self.dl_btn.setProperty("role", "primary")
187
+ self.dl_btn.clicked.connect(self._download)
188
+ self.file_btn = QToolButton()
189
+ self.file_btn.setText("Choose file…")
190
+ self.file_btn.setProperty("role", "chip")
191
+ self.file_btn.clicked.connect(self._choose)
192
+ self.later_btn = QToolButton()
193
+ self.later_btn.setText("Not now")
194
+ self.later_btn.setProperty("role", "chip")
195
+ self.later_btn.clicked.connect(self._later)
196
+ if self.asset is None:
197
+ self.dl_btn.setEnabled(False)
198
+ self.status.setText(
199
+ "No automatic download for this system. Get Stockfish from "
200
+ "stockfishchess.org, then use Choose file…"
201
+ )
202
+ row = QHBoxLayout()
203
+ row.addStretch(1)
204
+ for b in (self.dl_btn, self.file_btn, self.later_btn):
205
+ row.addWidget(b)
206
+ lay.addLayout(row)
207
+
208
+ def _choose(self) -> None:
209
+ path, _ = QFileDialog.getOpenFileName(self, "Select a UCI engine executable")
210
+ if path:
211
+ self.chosen.emit(path)
212
+ self.accept()
213
+
214
+ def _download(self) -> None:
215
+ self.dl_btn.setEnabled(False)
216
+ self.file_btn.setEnabled(False)
217
+ self.later_btn.setText("Cancel")
218
+ self.bar.show()
219
+ self.status.setText("Downloading…")
220
+ self.worker = DownloadWorker(self.asset)
221
+ self.worker.progress.connect(self._on_progress)
222
+ self.worker.status.connect(self.status.setText)
223
+ self.worker.done.connect(self._on_done)
224
+ self.worker.failed.connect(self._on_failed)
225
+ self.worker.start()
226
+
227
+ def _on_progress(self, got: int, total: int) -> None:
228
+ if total:
229
+ self.bar.setMaximum(total)
230
+ self.bar.setValue(got)
231
+ self.status.setText(f"Downloading… {got / 1e6:.0f} / {total / 1e6:.0f} MB")
232
+ else:
233
+ self.bar.setMaximum(0) # unknown size: busy bar
234
+
235
+ def _on_done(self, path: str) -> None:
236
+ if self.worker is not None:
237
+ self.worker.wait()
238
+ self.chosen.emit(path)
239
+ self.accept()
240
+
241
+ def _on_failed(self, message: str) -> None:
242
+ if self.worker is not None:
243
+ self.worker.wait()
244
+ self.bar.hide()
245
+ self.later_btn.setText("Not now")
246
+ self.dl_btn.setEnabled(True)
247
+ self.file_btn.setEnabled(True)
248
+ self.status.setText(
249
+ "Cancelled." if message == "cancelled" else f"Download failed: {message}"
250
+ )
251
+
252
+ def _later(self) -> None:
253
+ if self.worker is not None and self.worker.isRunning():
254
+ self.worker.cancel()
255
+ self.status.setText("Cancelling…")
256
+ else:
257
+ self.reject()
258
+
259
+ def reject(self) -> None:
260
+ if self.worker is not None and self.worker.isRunning():
261
+ self.worker.cancel()
262
+ self.worker.wait(5000)
263
+ super().reject()
silentengine/main.py ADDED
@@ -0,0 +1,35 @@
1
+ import sys
2
+
3
+ from PySide6.QtWidgets import QApplication
4
+
5
+ from silentengine.theme import STYLE
6
+ from silentengine.window import MainWindow
7
+
8
+ import zstandard as zstd
9
+ from silentengine.constants import DATA_DIR, PKG_DIR
10
+
11
+
12
+ def ensure_stats() -> None:
13
+ """On first launch, unpack the bundled move database into the user's data folder."""
14
+ dst = DATA_DIR / "stats.db"
15
+ src = PKG_DIR / "resources" / "stats.db.zst"
16
+ if dst.exists() or not src.is_file():
17
+ return
18
+ tmp = dst.with_suffix(".tmp")
19
+ with open(src, "rb") as f_in, open(tmp, "wb") as f_out:
20
+ zstd.ZstdDecompressor().copy_stream(f_in, f_out)
21
+ tmp.replace(dst) # the real file only appears once it's complete
22
+
23
+
24
+ def main() -> None:
25
+ ensure_stats()
26
+ app = QApplication(sys.argv)
27
+ app.setStyle("Fusion")
28
+ app.setStyleSheet(STYLE)
29
+ win = MainWindow()
30
+ win.showMaximized()
31
+ sys.exit(app.exec())
32
+
33
+
34
+ if __name__ == "__main__":
35
+ main()