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.
@@ -0,0 +1,21 @@
1
+ from __future__ import annotations
2
+ from pathlib import Path
3
+ import os
4
+ import subprocess
5
+ import sys
6
+ from platformdirs import user_data_dir
7
+
8
+ DATA_DIR = Path(user_data_dir("SilentEngine", appauthor=False))
9
+ DATA_DIR.mkdir(parents=True, exist_ok=True)
10
+ PKG_DIR = Path(__file__).resolve().parent
11
+ OPENINGS = PKG_DIR / "resources" / "openings.tsv"
12
+
13
+ APP_NAME = "SilentEngine"
14
+ MAX_PGN_GAMES = 20000 # games listed when opening a multi-game PGN
15
+ HASH_STEPS = [16, 32, 64, 128, 256, 512, 1024, 2048, 4096]
16
+ CPU_COUNT = os.cpu_count() or 2
17
+
18
+ # Windows: stop engine processes from opening their own console window
19
+ POPEN_KW = (
20
+ {"creationflags": subprocess.CREATE_NO_WINDOW} if sys.platform == "win32" else {}
21
+ )
silentengine/data.py ADDED
@@ -0,0 +1,259 @@
1
+ from __future__ import annotations
2
+ import hashlib
3
+ import json
4
+ import sqlite3
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
+
13
+
14
+ class OpeningBook:
15
+ def __init__(self, path: Path) -> None:
16
+ self.table: dict[str, tuple[str, str]] = {}
17
+ try:
18
+ lines = path.read_text(encoding="utf-8").splitlines()
19
+ except OSError:
20
+ return
21
+ for line in lines[1:]:
22
+ parts = line.split("\t")
23
+ if len(parts) < 3:
24
+ continue
25
+ eco, name, pgn = parts[:3]
26
+ board = chess.Board()
27
+ try:
28
+ for tok in pgn.split():
29
+ if "." not in tok: # skip move numbers like "1." / "1..."
30
+ board.push_san(tok)
31
+ except ValueError:
32
+ continue
33
+ self.table.setdefault(board.epd(), (eco, name))
34
+
35
+ @property
36
+ def loaded(self) -> bool:
37
+ return bool(self.table)
38
+
39
+ def lookup(self, board: chess.Board) -> tuple[str, str] | None:
40
+ return self.table.get(board.epd())
41
+
42
+ def next_moves(self, board: chess.Board) -> list[tuple[chess.Move, str, str, str]]:
43
+ """Legal moves that lead to a named opening: (move, san, eco, name)."""
44
+ out = []
45
+ b = board.copy(stack=False)
46
+ for move in board.legal_moves:
47
+ san = b.san(move)
48
+ b.push(move)
49
+ hit = self.table.get(b.epd())
50
+ b.pop()
51
+ if hit:
52
+ out.append((move, san, hit[0], hit[1]))
53
+ out.sort(key=lambda r: (r[2], r[1]))
54
+ return out
55
+
56
+
57
+ class StatsDB:
58
+ """Read-only move statistics built by build_stats_db.py."""
59
+
60
+ def __init__(self, path: Path) -> None:
61
+ self.conn: sqlite3.Connection | None = None
62
+ self.games = 0
63
+ if not path.is_file():
64
+ return
65
+ try:
66
+ conn = sqlite3.connect(f"{path.resolve().as_uri()}?mode=ro", uri=True)
67
+ conn.execute("SELECT 1 FROM stats LIMIT 1")
68
+ row = conn.execute("SELECT value FROM meta WHERE key='games'").fetchone()
69
+ self.games = int(row[0]) if row else 0
70
+ self.conn = conn
71
+ except (sqlite3.Error, ValueError):
72
+ self.conn = None
73
+
74
+ @property
75
+ def loaded(self) -> bool:
76
+ return self.conn is not None
77
+
78
+ def moves(self, board: chess.Board, limit: int = 12):
79
+ """Returns ([(move, san, white, draws, black), ...], total_games)."""
80
+ pos = chess.polyglot.zobrist_hash(board)
81
+ pos = pos - (1 << 64) if pos >= (1 << 63) else pos
82
+ rows = self.conn.execute(
83
+ "SELECT move, white, draws, black FROM stats WHERE pos=? "
84
+ "ORDER BY white + draws + black DESC",
85
+ (pos,),
86
+ ).fetchall()
87
+ out, total = [], 0
88
+ for uci, w, d, b in rows:
89
+ move = chess.Move.from_uci(uci)
90
+ if move not in board.legal_moves: # hash collision guard
91
+ continue
92
+ total += w + d + b
93
+ if len(out) < limit:
94
+ out.append((move, board.san(move), w, d, b))
95
+ return out, total
96
+
97
+
98
+ class ReviewCache:
99
+ """Raw engine results per reviewed line, so reopening a game skips the analysis."""
100
+
101
+ def __init__(self, path: Path) -> None:
102
+ self.conn: sqlite3.Connection | None = None
103
+ try:
104
+ path.parent.mkdir(exist_ok=True)
105
+ self.conn = sqlite3.connect(path)
106
+ self.conn.execute(
107
+ "CREATE TABLE IF NOT EXISTS reviews (key TEXT PRIMARY KEY, data TEXT)"
108
+ )
109
+ self.conn.commit()
110
+ except (OSError, sqlite3.Error):
111
+ self.conn = None
112
+
113
+ @staticmethod
114
+ def make_key(fens: list[str], ms: int, engine: str) -> str:
115
+ raw = "\n".join(fens) + f"|{ms}|{engine}"
116
+ return hashlib.sha256(raw.encode()).hexdigest()
117
+
118
+ def get(self, key: str) -> list | None:
119
+ if self.conn is None:
120
+ return None
121
+ try:
122
+ row = self.conn.execute(
123
+ "SELECT data FROM reviews WHERE key=?", (key,)
124
+ ).fetchone()
125
+ if not row:
126
+ return None
127
+ out = json.loads(row[0])
128
+ for r in out:
129
+ r["best"] = chess.Move.from_uci(r["best"]) if r["best"] else None
130
+ r["pv"] = [chess.Move.from_uci(m) for m in r["pv"]]
131
+ return out
132
+ except (sqlite3.Error, ValueError, KeyError):
133
+ return None
134
+
135
+ def put(self, key: str, results: list) -> None:
136
+ if self.conn is None:
137
+ return
138
+ try:
139
+ data = [
140
+ {
141
+ **r,
142
+ "best": r["best"].uci() if r["best"] else None,
143
+ "pv": [m.uci() for m in r["pv"]],
144
+ }
145
+ for r in results
146
+ ]
147
+ self.conn.execute(
148
+ "INSERT OR REPLACE INTO reviews VALUES (?, ?)", (key, json.dumps(data))
149
+ )
150
+ self.conn.commit()
151
+ except sqlite3.Error:
152
+ pass
153
+
154
+
155
+ class GameLibrary:
156
+ """The user's imported games plus their review summaries (kept between sessions)."""
157
+
158
+ def __init__(self, path: Path) -> None:
159
+ self.conn: sqlite3.Connection | None = None
160
+ try:
161
+ path.parent.mkdir(exist_ok=True)
162
+ self.conn = sqlite3.connect(path)
163
+ self.conn.execute(
164
+ "CREATE TABLE IF NOT EXISTS games ("
165
+ "id TEXT PRIMARY KEY, username TEXT, date TEXT, opponent TEXT, "
166
+ "color INTEGER, score REAL, pgn TEXT, summary TEXT)"
167
+ )
168
+ self.conn.commit()
169
+ except (OSError, sqlite3.Error):
170
+ self.conn = None
171
+
172
+ def add(self, rows: list[dict]) -> int:
173
+ """Insert new games; ones already in the library are ignored. Returns how many were new."""
174
+ if self.conn is None or not rows:
175
+ return 0
176
+ before = self.conn.total_changes
177
+ try:
178
+ self.conn.executemany(
179
+ "INSERT OR IGNORE INTO games (id, username, date, opponent, color, score, pgn) "
180
+ "VALUES (:id, :username, :date, :opponent, :color, :score, :pgn)",
181
+ rows,
182
+ )
183
+ self.conn.commit()
184
+ except sqlite3.Error:
185
+ return 0
186
+ return self.conn.total_changes - before
187
+
188
+ def games(self, username: str) -> list[dict]:
189
+ if self.conn is None:
190
+ return []
191
+ try:
192
+ rows = self.conn.execute(
193
+ "SELECT id, date, opponent, color, score, summary FROM games "
194
+ "WHERE username=? ORDER BY date DESC",
195
+ (username.lower(),),
196
+ ).fetchall()
197
+ except sqlite3.Error:
198
+ return []
199
+ out = []
200
+ for gid, date, opp, color, score, summ in rows:
201
+ try:
202
+ summary = json.loads(summ) if summ else None
203
+ except ValueError:
204
+ summary = None
205
+ out.append(
206
+ {
207
+ "id": gid,
208
+ "date": date,
209
+ "opponent": opp,
210
+ "color": bool(color),
211
+ "score": score,
212
+ "summary": summary,
213
+ }
214
+ )
215
+ return out
216
+
217
+ def pgn(self, gid: str) -> str | None:
218
+ if self.conn is None:
219
+ return None
220
+ row = self.conn.execute("SELECT pgn FROM games WHERE id=?", (gid,)).fetchone()
221
+ return row[0] if row else None
222
+
223
+ def pending(self, username: str, limit: int) -> list[tuple[str, str]]:
224
+ """(id, pgn) of games not analyzed yet, newest first."""
225
+ if self.conn is None:
226
+ return []
227
+ return self.conn.execute(
228
+ "SELECT id, pgn FROM games WHERE username=? AND summary IS NULL "
229
+ "ORDER BY date DESC LIMIT ?",
230
+ (username.lower(), limit),
231
+ ).fetchall()
232
+
233
+ def pending_count(self, username: str) -> int:
234
+ if self.conn is None:
235
+ return 0
236
+ return self.conn.execute(
237
+ "SELECT COUNT(*) FROM games WHERE username=? AND summary IS NULL",
238
+ (username.lower(),),
239
+ ).fetchone()[0]
240
+
241
+ def set_summary(self, gid: str, summary: dict) -> None:
242
+ if self.conn is None:
243
+ return
244
+ try:
245
+ self.conn.execute(
246
+ "UPDATE games SET summary=? WHERE id=?", (json.dumps(summary), gid)
247
+ )
248
+ self.conn.commit()
249
+ except sqlite3.Error:
250
+ pass
251
+
252
+ def remove(self, ids: list[str]) -> None:
253
+ if self.conn is None or not ids:
254
+ return
255
+ try:
256
+ self.conn.executemany("DELETE FROM games WHERE id=?", [(i,) for i in ids])
257
+ self.conn.commit()
258
+ except sqlite3.Error:
259
+ pass
@@ -0,0 +1,152 @@
1
+ from __future__ import annotations
2
+ from pathlib import Path
3
+
4
+ from PySide6.QtCore import (
5
+ Qt,
6
+ )
7
+ from PySide6.QtWidgets import (
8
+ QComboBox,
9
+ QDialog,
10
+ QDialogButtonBox,
11
+ QFileDialog,
12
+ QFormLayout,
13
+ QHBoxLayout,
14
+ QLabel,
15
+ QLineEdit,
16
+ QListWidget,
17
+ QListWidgetItem,
18
+ QSlider,
19
+ QToolButton,
20
+ QVBoxLayout,
21
+ QWidget,
22
+ )
23
+
24
+ from silentengine.constants import MAX_PGN_GAMES, HASH_STEPS, CPU_COUNT
25
+
26
+
27
+ class GamePickerDialog(QDialog):
28
+ def __init__(self, entries: list, capped: bool, parent=None) -> None:
29
+ super().__init__(parent)
30
+ self.setWindowTitle("Choose a game")
31
+ self.resize(640, 480)
32
+ lay = QVBoxLayout(self)
33
+ note = f"{len(entries):,} games" + (
34
+ f" (showing the first {MAX_PGN_GAMES:,})" if capped else ""
35
+ )
36
+ lay.addWidget(QLabel(note))
37
+ self.filter = QLineEdit()
38
+ self.filter.setPlaceholderText("Filter by player, event, result…")
39
+ lay.addWidget(self.filter)
40
+ self.list = QListWidget()
41
+ for i, (_offset, h) in enumerate(entries):
42
+
43
+ def who(name_key: str, elo_key: str) -> str:
44
+ name, elo = h.get(name_key, "?"), h.get(elo_key, "")
45
+ return f"{name} ({elo})" if elo not in ("", "?") else name
46
+
47
+ text = (
48
+ f"{i + 1}. {who('White', 'WhiteElo')} – {who('Black', 'BlackElo')} "
49
+ f"{h.get('Result', '*')} {h.get('Date', '')} {h.get('Event', '')[:30]}"
50
+ )
51
+ item = QListWidgetItem(text)
52
+ item.setData(Qt.UserRole, i)
53
+ self.list.addItem(item)
54
+ self.list.setCurrentRow(0)
55
+ self.list.itemDoubleClicked.connect(lambda _i: self.accept())
56
+ self.filter.textChanged.connect(self._apply_filter)
57
+ lay.addWidget(self.list, 1)
58
+ buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
59
+ buttons.accepted.connect(self.accept)
60
+ buttons.rejected.connect(self.reject)
61
+ lay.addWidget(buttons)
62
+
63
+ def _apply_filter(self, text: str) -> None:
64
+ needle = text.lower()
65
+ for r in range(self.list.count()):
66
+ item = self.list.item(r)
67
+ item.setHidden(needle not in item.text().lower())
68
+
69
+ def chosen(self) -> int:
70
+ item = self.list.currentItem()
71
+ return item.data(Qt.UserRole) if item else 0
72
+
73
+
74
+ class SettingsDialog(QDialog):
75
+ def __init__(self, cfg: dict, parent=None) -> None:
76
+ super().__init__(parent)
77
+ self.setWindowTitle("Engine settings")
78
+ self.setMinimumWidth(420)
79
+ self.engines = list(cfg["engines"])
80
+
81
+ form = QFormLayout(self)
82
+
83
+ self.engine_box = QComboBox()
84
+ for path in self.engines:
85
+ self.engine_box.addItem(Path(path).name, path)
86
+ if cfg["engine"] in self.engines:
87
+ self.engine_box.setCurrentIndex(self.engines.index(cfg["engine"]))
88
+ add = QToolButton()
89
+ add.setText("Add…")
90
+ add.clicked.connect(self._add_engine)
91
+ row = QHBoxLayout()
92
+ row.addWidget(self.engine_box, 1)
93
+ row.addWidget(add)
94
+ form.addRow("Engine", row)
95
+
96
+ self.time_s, time_row = self._slider(
97
+ 0, 60, cfg["search_time"], lambda v: "∞" if v == 0 else f"{v} s"
98
+ )
99
+ self.pv_s, pv_row = self._slider(1, 5, cfg["multipv"], lambda v: f"{v}")
100
+ self.threads_s, thr_row = self._slider(
101
+ 1, CPU_COUNT, cfg["threads"], lambda v: f"{v}"
102
+ )
103
+ hash_idx = HASH_STEPS.index(cfg["hash"]) if cfg["hash"] in HASH_STEPS else 4
104
+ self.hash_s, hash_row = self._slider(
105
+ 0, len(HASH_STEPS) - 1, hash_idx, lambda v: f"{HASH_STEPS[v]} MB"
106
+ )
107
+ form.addRow("Search time", time_row)
108
+ form.addRow("Multiple lines", pv_row)
109
+ form.addRow("Threads", thr_row)
110
+ form.addRow("Memory", hash_row)
111
+ self.review_s, review_row = self._slider(
112
+ 1, 30, max(1, min(30, cfg["review_ms"] // 100)), lambda v: f"{v / 10:.1f} s"
113
+ )
114
+ form.addRow("Review time / move", review_row)
115
+
116
+ buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
117
+ buttons.accepted.connect(self.accept)
118
+ buttons.rejected.connect(self.reject)
119
+ form.addRow(buttons)
120
+
121
+ @staticmethod
122
+ def _slider(lo: int, hi: int, value: int, fmt):
123
+ slider = QSlider(Qt.Horizontal)
124
+ slider.setRange(lo, hi)
125
+ slider.setValue(min(max(value, lo), hi))
126
+ label = QLabel(fmt(slider.value()))
127
+ label.setMinimumWidth(56)
128
+ slider.valueChanged.connect(lambda v: label.setText(fmt(v)))
129
+ box = QWidget()
130
+ lay = QHBoxLayout(box)
131
+ lay.setContentsMargins(0, 0, 0, 0)
132
+ lay.addWidget(slider, 1)
133
+ lay.addWidget(label)
134
+ return slider, box
135
+
136
+ def _add_engine(self) -> None:
137
+ path, _ = QFileDialog.getOpenFileName(self, "Select a UCI engine executable")
138
+ if path and path not in self.engines:
139
+ self.engines.append(path)
140
+ self.engine_box.addItem(Path(path).name, path)
141
+ self.engine_box.setCurrentIndex(len(self.engines) - 1)
142
+
143
+ def values(self) -> dict:
144
+ return {
145
+ "engines": self.engines,
146
+ "engine": self.engine_box.currentData() or "",
147
+ "search_time": self.time_s.value(),
148
+ "multipv": self.pv_s.value(),
149
+ "threads": self.threads_s.value(),
150
+ "hash": HASH_STEPS[self.hash_s.value()],
151
+ "review_ms": self.review_s.value() * 100,
152
+ }