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/batch.py ADDED
@@ -0,0 +1,758 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import io
5
+ from collections import Counter
6
+ from pathlib import Path
7
+
8
+ import chess
9
+ import chess.engine
10
+ import chess.pgn
11
+ from PySide6.QtCore import Qt, QThread, Signal
12
+ from PySide6.QtGui import QColor
13
+ from PySide6.QtWidgets import (
14
+ QAbstractItemView,
15
+ QDialog,
16
+ QFileDialog,
17
+ QHBoxLayout,
18
+ QHeaderView,
19
+ QLabel,
20
+ QLineEdit,
21
+ QProgressBar,
22
+ QSpinBox,
23
+ QTableWidget,
24
+ QTableWidgetItem,
25
+ QTabWidget,
26
+ QToolButton,
27
+ QVBoxLayout,
28
+ )
29
+
30
+ from silentengine.config import save_config
31
+ from silentengine.constants import MAX_PGN_GAMES, POPEN_KW
32
+ from silentengine.data import GameLibrary, ReviewCache
33
+ from silentengine.engine import analyse_fen
34
+ from silentengine.review import (
35
+ BAD_LABELS,
36
+ classify_line,
37
+ game_accuracy,
38
+ move_accuracy,
39
+ volatility_weight,
40
+ )
41
+
42
+ LOW_CLOCK = 30 # seconds left that counts as time trouble
43
+ PHASES = ("Opening", "Middlegame", "Endgame")
44
+ COLS = [
45
+ "Date",
46
+ "Opponent",
47
+ "Side",
48
+ "Result",
49
+ "Acc",
50
+ "Inacc.",
51
+ "Mistakes",
52
+ "Misses",
53
+ "Blunders",
54
+ "Opening",
55
+ ]
56
+ OPEN_COLS = [
57
+ "Side",
58
+ "Opening",
59
+ "Games",
60
+ "W",
61
+ "D",
62
+ "L",
63
+ "Score %",
64
+ "Acc",
65
+ "1st bad move",
66
+ ]
67
+
68
+
69
+ # --------------------------------------------------------------------------- #
70
+ # Per-game analysis (pure functions, no Qt)
71
+ # --------------------------------------------------------------------------- #
72
+ def phase_of(fullmove: int) -> int:
73
+ return 0 if fullmove <= 10 else 1 if fullmove <= 30 else 2
74
+
75
+
76
+ def user_color(headers, username: str) -> bool | None:
77
+ u = username.strip().lower()
78
+ if not u:
79
+ return None
80
+ if headers.get("White", "").strip().lower() == u:
81
+ return chess.WHITE
82
+ if headers.get("Black", "").strip().lower() == u:
83
+ return chess.BLACK
84
+ return None
85
+
86
+
87
+ def result_score(headers, color: bool) -> float | None:
88
+ s = {"1-0": 1.0, "0-1": 0.0, "1/2-1/2": 0.5}.get(headers.get("Result", "*"))
89
+ if s is not None and color == chess.BLACK:
90
+ s = 1.0 - s
91
+ return s
92
+
93
+
94
+ def entry_id(game: chess.pgn.Game, username: str) -> str:
95
+ h = game.headers
96
+ raw = "|".join(
97
+ h.get(k, "") for k in ("Site", "Link", "Date", "UTCTime", "White", "Black")
98
+ )
99
+ moves = " ".join(m.uci() for m in game.mainline_moves())
100
+ return hashlib.sha1(f"{username.lower()}|{raw}|{moves}".encode()).hexdigest()
101
+
102
+
103
+ def replay(game: chess.pgn.Game):
104
+ """boards[i] = position after i plies, moves[i] = the move that led to boards[i + 1]."""
105
+ board = game.board()
106
+ boards, moves = [board.copy(stack=False)], []
107
+ for node in game.mainline():
108
+ moves.append(node.move)
109
+ board.push(node.move)
110
+ boards.append(board.copy(stack=False))
111
+ return boards, moves
112
+
113
+
114
+ def summarize(game: chess.pgn.Game, results: list, color: bool, book) -> dict:
115
+ nodes = list(game.mainline())
116
+ boards, moves = replay(game)
117
+ in_book = [book.loaded and book.lookup(b) is not None for b in boards]
118
+ info = classify_line(boards, moves, results, in_book)
119
+ fracs = [r["frac"] for r in results]
120
+
121
+ acc = {chess.WHITE: [], chess.BLACK: []}
122
+ wts = {chess.WHITE: [], chess.BLACK: []}
123
+ counts: Counter = Counter()
124
+ phases = [0, 0, 0]
125
+ n_moves = n_low = bad_low = 0
126
+ has_clock = False
127
+ first_bad = None
128
+ for i, c in enumerate(info, start=1):
129
+ b0 = boards[i - 1]
130
+ mover = b0.turn
131
+ acc[mover].append(move_accuracy(c["loss"]))
132
+ wts[mover].append(volatility_weight(fracs, i - 1))
133
+ if mover != color:
134
+ continue
135
+ n_moves += 1
136
+ counts[c["label"]] += 1
137
+ clk = nodes[i - 1].clock() # time left after that move
138
+ low = clk is not None and clk < LOW_CLOCK
139
+ has_clock = has_clock or clk is not None
140
+ n_low += low
141
+ if c["label"] in BAD_LABELS:
142
+ phases[phase_of(b0.fullmove_number)] += 1
143
+ bad_low += low
144
+ if first_bad is None:
145
+ first_bad = b0.fullmove_number
146
+
147
+ hit = None
148
+ if book.loaded:
149
+ for b in boards:
150
+ hit = book.lookup(b) or hit
151
+ opening = hit[1] if hit else "Unknown"
152
+ return {
153
+ "color": color,
154
+ "score": result_score(game.headers, color),
155
+ "acc": game_accuracy(acc[color], wts[color]),
156
+ "inacc": counts["Inaccuracy"],
157
+ "mistakes": counts["Mistake"],
158
+ "misses": counts["Miss"],
159
+ "blunders": counts["Blunder"],
160
+ "bad": sum(counts[label] for label in BAD_LABELS),
161
+ "phases": phases,
162
+ "first_bad": first_bad,
163
+ "moves": n_moves,
164
+ "low": n_low,
165
+ "bad_low": bad_low,
166
+ "has_clock": has_clock,
167
+ "opening": opening,
168
+ "family": opening.split(":")[0].strip(),
169
+ }
170
+
171
+
172
+ # --------------------------------------------------------------------------- #
173
+ # Worker: one engine process for the whole batch
174
+ # --------------------------------------------------------------------------- #
175
+ class BatchWorker(QThread):
176
+ status = Signal(str)
177
+ progress = Signal(int, int)
178
+ row = Signal(str, object) # game id, summary dict or {"error": ...}
179
+ failed = Signal(str)
180
+
181
+ def __init__(
182
+ self, items, engine_path, ms, threads, hash_mb, username, book, cache_path
183
+ ) -> None:
184
+ super().__init__()
185
+ self.items = items # [(id, pgn text)]
186
+ self.engine_path, self.ms = engine_path, ms
187
+ self.threads, self.hash_mb = threads, hash_mb
188
+ self.username, self.book, self.cache_path = username, book, cache_path
189
+ self._cancel = False
190
+
191
+ def cancel(self) -> None:
192
+ self._cancel = True
193
+
194
+ def run(self) -> None:
195
+ engine = None
196
+ cache = ReviewCache(
197
+ self.cache_path
198
+ ) # own connection: sqlite objects can't cross threads
199
+ try:
200
+ engine = chess.engine.SimpleEngine.popen_uci(self.engine_path, **POPEN_KW)
201
+ cfg = {}
202
+ for name, value in (("Threads", self.threads), ("Hash", self.hash_mb)):
203
+ if name in engine.options:
204
+ opt = engine.options[name]
205
+ cfg[name] = min(value, opt.max) if opt.max else value
206
+ if cfg:
207
+ engine.configure(cfg)
208
+ engine_name = Path(self.engine_path).name
209
+ total = len(self.items)
210
+ for k, (gid, pgn) in enumerate(self.items):
211
+ if self._cancel:
212
+ return
213
+ self.progress.emit(k, total)
214
+ try:
215
+ game = chess.pgn.read_game(io.StringIO(pgn))
216
+ color = user_color(game.headers, self.username) if game else None
217
+ if game is None or game.errors or color is None:
218
+ self.row.emit(gid, {"error": "unreadable"})
219
+ continue
220
+ boards, moves = replay(game)
221
+ except Exception:
222
+ self.row.emit(gid, {"error": "unsupported"})
223
+ continue
224
+ if len(moves) < 4:
225
+ self.row.emit(gid, {"error": "too short"})
226
+ continue
227
+ fens = [b.fen() for b in boards]
228
+ key = ReviewCache.make_key(fens, self.ms, engine_name)
229
+ results = cache.get(key)
230
+ if results is None or len(results) != len(fens):
231
+ results = []
232
+ for j, fen in enumerate(fens):
233
+ if self._cancel:
234
+ return
235
+ results.append(analyse_fen(engine, fen, self.ms))
236
+ self.status.emit(
237
+ f"Game {k + 1}/{total} · position {j + 1}/{len(fens)}"
238
+ )
239
+ cache.put(key, results)
240
+ self.row.emit(gid, summarize(game, results, color, self.book))
241
+ self.progress.emit(total, total)
242
+ except Exception as exc:
243
+ self.failed.emit(str(exc))
244
+ finally:
245
+ if engine is not None:
246
+ try:
247
+ engine.quit()
248
+ except Exception:
249
+ pass
250
+ if cache.conn is not None:
251
+ cache.conn.close()
252
+
253
+
254
+ # --------------------------------------------------------------------------- #
255
+ # Dialog
256
+ # --------------------------------------------------------------------------- #
257
+ def _btn(text: str) -> QToolButton:
258
+ b = QToolButton()
259
+ b.setText(text)
260
+ b.setProperty("role", "primary")
261
+ return b
262
+
263
+
264
+ class BatchDialog(QDialog):
265
+ openGame = Signal(str) # PGN text of the chosen game
266
+ started = Signal()
267
+ stopped = Signal()
268
+
269
+ def __init__(
270
+ self, cfg: dict, book, cache_path: Path, lib_path: Path, parent=None
271
+ ) -> None:
272
+ super().__init__(parent)
273
+ self.setWindowTitle("Batch review · your games")
274
+ self.resize(940, 660)
275
+ self.cfg, self.book, self.cache_path = cfg, book, cache_path
276
+ self.lib = GameLibrary(lib_path)
277
+ self.meta: dict = {} # id -> game dict (with summary) for the current username
278
+ self.row_of: dict = {} # id -> table row while a run is active
279
+ self.worker: BatchWorker | None = None
280
+ self._stopping = False
281
+
282
+ lay = QVBoxLayout(self)
283
+ top = QHBoxLayout()
284
+ self.add_btn = _btn("Add PGN files…")
285
+ self.add_btn.clicked.connect(self._add_files)
286
+ self.remove_btn = _btn("Remove selected")
287
+ self.remove_btn.clicked.connect(self._remove_selected)
288
+ self.lib_lbl = QLabel("")
289
+ self.lib_lbl.setStyleSheet("color:#888;")
290
+ top.addWidget(self.add_btn)
291
+ top.addWidget(self.remove_btn)
292
+ top.addWidget(self.lib_lbl, 1)
293
+ lay.addLayout(top)
294
+
295
+ opts = QHBoxLayout()
296
+ self.user = QLineEdit(cfg.get("username", ""))
297
+ self.user.setPlaceholderText("your username as written in the PGN")
298
+ self.user.setFixedWidth(230)
299
+ self.user.editingFinished.connect(self._load_library)
300
+ self.count = QSpinBox()
301
+ self.count.setRange(1, 9999)
302
+ self.count.setValue(20)
303
+ self.count.setPrefix("analyze up to ")
304
+ self.count.setSuffix(" new games")
305
+ self.count.valueChanged.connect(self._estimate)
306
+ self.ms = QSpinBox()
307
+ self.ms.setRange(100, 3000)
308
+ self.ms.setSingleStep(100)
309
+ self.ms.setSuffix(" ms / move")
310
+ self.ms.setValue(max(100, cfg["review_ms"]))
311
+ self.ms.valueChanged.connect(self._estimate)
312
+ self.est = QLabel("")
313
+ self.est.setStyleSheet("color:#888;")
314
+ for w in (QLabel("You:"), self.user, self.count, self.ms):
315
+ opts.addWidget(w)
316
+ opts.addWidget(self.est, 1)
317
+ lay.addLayout(opts)
318
+
319
+ run = QHBoxLayout()
320
+ self.start_btn = _btn("Start")
321
+ self.start_btn.clicked.connect(self._start)
322
+ self.stop_btn = _btn("Stop")
323
+ self.stop_btn.clicked.connect(self._stop)
324
+ self.stop_btn.setEnabled(False)
325
+ self.bar = QProgressBar()
326
+ self.bar.setTextVisible(False)
327
+ run.addWidget(self.start_btn)
328
+ run.addWidget(self.stop_btn)
329
+ run.addWidget(self.bar, 1)
330
+ lay.addLayout(run)
331
+ self.status = QLabel("")
332
+ self.status.setStyleSheet("color:#888;")
333
+ lay.addWidget(self.status)
334
+
335
+ self.summary = QLabel()
336
+ self.summary.setTextFormat(Qt.RichText)
337
+ self.summary.setWordWrap(True)
338
+ lay.addWidget(self.summary)
339
+
340
+ self.games_tbl = self._table(COLS, stretch_last=True)
341
+ self.games_tbl.cellDoubleClicked.connect(self._open_row)
342
+ self.opens_tbl = self._table(OPEN_COLS, stretch_col=1)
343
+ tabs = QTabWidget()
344
+ tabs.addTab(self.games_tbl, "Games (double-click to open)")
345
+ tabs.addTab(self.opens_tbl, "Openings")
346
+ lay.addWidget(tabs, 1)
347
+ self._load_library()
348
+
349
+ # ---- helpers -------------------------------------------------------- #
350
+ @staticmethod
351
+ def _table(cols, stretch_last=False, stretch_col=None) -> QTableWidget:
352
+ t = QTableWidget(0, len(cols))
353
+ t.setHorizontalHeaderLabels(cols)
354
+ t.verticalHeader().setVisible(False)
355
+ t.setEditTriggers(QAbstractItemView.NoEditTriggers)
356
+ t.setSelectionBehavior(QAbstractItemView.SelectRows)
357
+ t.setShowGrid(False)
358
+ hh = t.horizontalHeader()
359
+ for c in range(len(cols)):
360
+ hh.setSectionResizeMode(c, QHeaderView.ResizeToContents)
361
+ if stretch_last:
362
+ hh.setSectionResizeMode(len(cols) - 1, QHeaderView.Stretch)
363
+ if stretch_col is not None:
364
+ hh.setSectionResizeMode(stretch_col, QHeaderView.Stretch)
365
+ return t
366
+
367
+ @staticmethod
368
+ def _item(text: str, align=Qt.AlignCenter) -> QTableWidgetItem:
369
+ it = QTableWidgetItem(text)
370
+ it.setTextAlignment(align)
371
+ return it
372
+
373
+ @staticmethod
374
+ def _num(value: float, nd: int = 0) -> QTableWidgetItem:
375
+ it = QTableWidgetItem()
376
+ it.setData(Qt.DisplayRole, round(value, nd) if nd else int(value))
377
+ it.setTextAlignment(Qt.AlignCenter)
378
+ return it
379
+
380
+ def _running(self) -> bool:
381
+ return self.worker is not None and self.worker.isRunning()
382
+
383
+ def _username(self) -> str:
384
+ return self.user.text().strip()
385
+
386
+ # ---- library -------------------------------------------------------- #
387
+ def _load_library(self) -> None:
388
+ user = self._username()
389
+ games = self.lib.games(user) if user else []
390
+ self.meta = {g["id"]: g for g in games}
391
+ t = self.games_tbl
392
+ t.setSortingEnabled(False)
393
+ t.setRowCount(len(games))
394
+ for r, g in enumerate(games):
395
+ self._fill_game_row(r, g)
396
+ t.setSortingEnabled(True)
397
+ t.sortByColumn(0, Qt.DescendingOrder)
398
+ self._refresh_stats()
399
+
400
+ def _fill_game_row(self, r: int, g: dict) -> None:
401
+ t = self.games_tbl
402
+ left = Qt.AlignLeft | Qt.AlignVCenter
403
+ date = self._item(g["date"])
404
+ date.setData(Qt.UserRole, g["id"])
405
+ t.setItem(r, 0, date)
406
+ t.setItem(r, 1, self._item(g["opponent"], left))
407
+ t.setItem(r, 2, self._item("White" if g["color"] else "Black"))
408
+ text, col = {
409
+ 1.0: ("Win", "#81b64c"),
410
+ 0.0: ("Loss", "#d14343"),
411
+ 0.5: ("Draw", "#aaaaaa"),
412
+ }.get(g["score"], ("?", "#aaaaaa"))
413
+ res = self._item(text)
414
+ res.setForeground(QColor(col))
415
+ t.setItem(r, 3, res)
416
+ s = g["summary"]
417
+ if s is None:
418
+ for c in range(4, 9):
419
+ t.setItem(r, c, self._item("…"))
420
+ t.setItem(r, 9, self._item("not analyzed yet", left))
421
+ elif "error" in s:
422
+ for c in range(4, 9):
423
+ t.setItem(r, c, self._item("–"))
424
+ t.setItem(r, 9, self._item(f"skipped: {s['error']}", left))
425
+ else:
426
+ t.setItem(
427
+ r,
428
+ 4,
429
+ self._num(s["acc"], 1) if s["acc"] is not None else self._item("–"),
430
+ )
431
+ for c, key in (
432
+ (5, "inacc"),
433
+ (6, "mistakes"),
434
+ (7, "misses"),
435
+ (8, "blunders"),
436
+ ):
437
+ t.setItem(r, c, self._num(s[key]))
438
+ t.setItem(r, 9, self._item(s["opening"], left))
439
+
440
+ def _add_files(self) -> None:
441
+ if self._running():
442
+ return
443
+ start = self.cfg.get("last_dir") or str(Path.home())
444
+ paths, _ = QFileDialog.getOpenFileNames(
445
+ self, "Add PGN files", start, "PGN files (*.pgn);;All files (*)"
446
+ )
447
+ if not paths:
448
+ return
449
+ per_file = []
450
+ for path in paths:
451
+ entries = []
452
+ try:
453
+ with open(path, encoding="utf-8", errors="replace") as f:
454
+ while len(entries) < MAX_PGN_GAMES:
455
+ offset = f.tell()
456
+ headers = chess.pgn.read_headers(f)
457
+ if headers is None:
458
+ break
459
+ entries.append((offset, headers))
460
+ except OSError as exc:
461
+ self.status.setText(f"Could not open {Path(path).name}: {exc}")
462
+ continue
463
+ per_file.append((path, entries))
464
+ if not self._username(): # guess: the name that appears in the most games
465
+ names = Counter(
466
+ h.get(side, "")
467
+ for _p, entries in per_file
468
+ for _o, h in entries
469
+ for side in ("White", "Black")
470
+ )
471
+ names.pop("", None)
472
+ names.pop("?", None)
473
+ if names:
474
+ self.user.setText(names.most_common(1)[0][0])
475
+ user = self._username()
476
+ if not user:
477
+ self.status.setText("Type your username first")
478
+ return
479
+ self.cfg["username"] = user
480
+ self.cfg["last_dir"] = str(Path(paths[0]).parent)
481
+ save_config(self.cfg)
482
+
483
+ u = user.lower()
484
+ rows = []
485
+ for path, entries in per_file:
486
+ mine = [
487
+ off
488
+ for off, h in entries
489
+ if u in (h.get("White", "").lower(), h.get("Black", "").lower())
490
+ ]
491
+ if not mine:
492
+ continue
493
+ try:
494
+ with open(path, encoding="utf-8", errors="replace") as f:
495
+ for offset in mine:
496
+ f.seek(offset)
497
+ game = chess.pgn.read_game(f)
498
+ color = user_color(game.headers, user) if game else None
499
+ if game is None or color is None:
500
+ continue
501
+ h = game.headers
502
+ rows.append(
503
+ {
504
+ "id": entry_id(game, user),
505
+ "username": u,
506
+ "date": h.get("Date", "?"),
507
+ "opponent": h.get(
508
+ "Black" if color == chess.WHITE else "White", "?"
509
+ ),
510
+ "color": int(color),
511
+ "score": result_score(h, color),
512
+ "pgn": game.accept(
513
+ chess.pgn.StringExporter(
514
+ headers=True, variations=True, comments=True
515
+ )
516
+ ),
517
+ }
518
+ )
519
+ except OSError as exc:
520
+ self.status.setText(f"Could not read {Path(path).name}: {exc}")
521
+ added = self.lib.add(rows)
522
+ self.status.setText(
523
+ f"Added {added} new games"
524
+ + (
525
+ f" ({len(rows) - added} were already in your library)"
526
+ if len(rows) > added
527
+ else ""
528
+ )
529
+ if rows
530
+ else "No games for that username in the selected files"
531
+ )
532
+ self._load_library()
533
+
534
+ def _remove_selected(self) -> None:
535
+ if self._running():
536
+ return
537
+ sel = self.games_tbl.selectionModel().selectedRows()
538
+ ids = []
539
+ for idx in sel:
540
+ it = self.games_tbl.item(idx.row(), 0)
541
+ if it is not None:
542
+ ids.append(it.data(Qt.UserRole))
543
+ if ids:
544
+ self.lib.remove(ids)
545
+ self.status.setText(f"Removed {len(ids)} games from the library")
546
+ self._load_library()
547
+
548
+ # ---- estimate / running --------------------------------------------- #
549
+ def _estimate(self) -> None:
550
+ user = self._username()
551
+ pending = self.lib.pending_count(user) if user else 0
552
+ n = min(self.count.value(), pending)
553
+ mins = n * 80 * self.ms.value() / 60000
554
+ self.est.setText(
555
+ f"{pending} waiting · about {mins:.0f} min if none are cached"
556
+ if pending
557
+ else "nothing waiting"
558
+ )
559
+ self.start_btn.setEnabled(
560
+ bool(pending) and bool(self.cfg["engine"]) and not self._running()
561
+ )
562
+
563
+ def _start(self) -> None:
564
+ user = self._username()
565
+ items = self.lib.pending(user, self.count.value()) if user else []
566
+ if not items or not self.cfg["engine"] or self._running():
567
+ return
568
+ self.cfg["username"] = user
569
+ save_config(self.cfg)
570
+ self._stopping = False
571
+ t = self.games_tbl
572
+ t.setSortingEnabled(False) # rows must not move while results come in
573
+ self.row_of = {}
574
+ for r in range(t.rowCount()):
575
+ it = t.item(r, 0)
576
+ if it is not None:
577
+ self.row_of[it.data(Qt.UserRole)] = r
578
+
579
+ self.worker = BatchWorker(
580
+ items,
581
+ self.cfg["engine"],
582
+ self.ms.value(),
583
+ self.cfg["threads"],
584
+ self.cfg["hash"],
585
+ user,
586
+ self.book,
587
+ self.cache_path,
588
+ )
589
+ self.worker.status.connect(self.status.setText)
590
+ self.worker.progress.connect(self._on_progress)
591
+ self.worker.row.connect(self._on_row)
592
+ self.worker.failed.connect(lambda m: self.status.setText(f"Failed: {m}"))
593
+ self.worker.finished.connect(self._on_finished)
594
+ self.start_btn.setEnabled(False)
595
+ self.stop_btn.setEnabled(True)
596
+ self.add_btn.setEnabled(False)
597
+ self.remove_btn.setEnabled(False)
598
+ self.started.emit() # the main window pauses its own engine
599
+ self.worker.start()
600
+
601
+ def _stop(self) -> None:
602
+ if self._running():
603
+ self._stopping = True
604
+ self.worker.cancel()
605
+ self.status.setText("Stopping…")
606
+
607
+ def _on_progress(self, k: int, total: int) -> None:
608
+ self.bar.setMaximum(total)
609
+ self.bar.setValue(k)
610
+
611
+ def _on_row(self, gid: str, data: dict) -> None:
612
+ self.lib.set_summary(gid, data)
613
+ g = self.meta.get(gid)
614
+ if g is None:
615
+ return
616
+ g["summary"] = data
617
+ r = self.row_of.get(gid)
618
+ if r is not None:
619
+ self._fill_game_row(r, g)
620
+ self._refresh_stats()
621
+
622
+ def _on_finished(self) -> None:
623
+ analyzed = sum(1 for g in self.meta.values() if g["summary"] is not None)
624
+ self.status.setText(
625
+ f"{'Stopped' if self._stopping else 'Finished'} · {analyzed} of "
626
+ f"{len(self.meta)} games analyzed"
627
+ )
628
+ self.stop_btn.setEnabled(False)
629
+ self.add_btn.setEnabled(True)
630
+ self.remove_btn.setEnabled(True)
631
+ self.games_tbl.setSortingEnabled(True)
632
+ self.games_tbl.sortByColumn(0, Qt.DescendingOrder)
633
+ self._estimate()
634
+ self.stopped.emit()
635
+
636
+ def _open_row(self, row: int, _col: int) -> None:
637
+ it = self.games_tbl.item(row, 0)
638
+ if it is None or it.data(Qt.UserRole) is None:
639
+ return
640
+ pgn = self.lib.pgn(it.data(Qt.UserRole))
641
+ if pgn:
642
+ self.openGame.emit(pgn)
643
+
644
+ # ---- results -------------------------------------------------------- #
645
+ def _done(self) -> list:
646
+ return [
647
+ g["summary"]
648
+ for g in self.meta.values()
649
+ if g["summary"] and "error" not in g["summary"]
650
+ ]
651
+
652
+ def _refresh_stats(self) -> None:
653
+ total = len(self.meta)
654
+ analyzed = len(self._done())
655
+ self.lib_lbl.setText(
656
+ f"Library: {total} games · {analyzed} analyzed"
657
+ if total
658
+ else "Library is empty: add PGN files with your games"
659
+ )
660
+ self._fill_openings()
661
+ self._fill_summary()
662
+ self._estimate()
663
+
664
+ def _groups(self) -> list:
665
+ groups: dict = {}
666
+ for r in self._done():
667
+ groups.setdefault((r["color"], r["family"]), []).append(r)
668
+ out = []
669
+ for (color, fam), rs in groups.items():
670
+ scored = [r["score"] for r in rs if r["score"] is not None]
671
+ accs = [r["acc"] for r in rs if r["acc"] is not None]
672
+ fb = [r["first_bad"] for r in rs if r["first_bad"] is not None]
673
+ out.append(
674
+ {
675
+ "color": color,
676
+ "family": fam,
677
+ "games": len(rs),
678
+ "w": sum(1 for s in scored if s == 1.0),
679
+ "d": sum(1 for s in scored if s == 0.5),
680
+ "l": sum(1 for s in scored if s == 0.0),
681
+ "score": sum(scored) / len(scored) * 100 if scored else None,
682
+ "acc": sum(accs) / len(accs) if accs else None,
683
+ "first_bad": sum(fb) / len(fb) if fb else None,
684
+ "bad": sum(r["bad"] for r in rs) / len(rs),
685
+ }
686
+ )
687
+ out.sort(key=lambda g: -g["games"])
688
+ return out
689
+
690
+ def _fill_openings(self) -> None:
691
+ t = self.opens_tbl
692
+ groups = self._groups()
693
+ t.setSortingEnabled(False)
694
+ t.setRowCount(len(groups))
695
+ for r, g in enumerate(groups):
696
+ t.setItem(r, 0, self._item("White" if g["color"] else "Black"))
697
+ t.setItem(r, 1, self._item(g["family"], Qt.AlignLeft | Qt.AlignVCenter))
698
+ for c, key in ((2, "games"), (3, "w"), (4, "d"), (5, "l")):
699
+ t.setItem(r, c, self._num(g[key]))
700
+ for c, key, nd in ((6, "score", 0), (7, "acc", 1), (8, "first_bad", 1)):
701
+ t.setItem(
702
+ r,
703
+ c,
704
+ self._num(g[key], nd) if g[key] is not None else self._item("–"),
705
+ )
706
+ t.setSortingEnabled(True)
707
+ t.sortByColumn(2, Qt.DescendingOrder)
708
+
709
+ def _fill_summary(self) -> None:
710
+ done = self._done()
711
+ if not done:
712
+ self.summary.setText("")
713
+ return
714
+ scored = [r["score"] for r in done if r["score"] is not None]
715
+ accs = [r["acc"] for r in done if r["acc"] is not None]
716
+ w = sum(1 for s in scored if s == 1.0)
717
+ d = sum(1 for s in scored if s == 0.5)
718
+ lo = sum(1 for s in scored if s == 0.0)
719
+ head = f"<b>{len(done)} games</b> · {w}W {d}D {lo}L"
720
+ if accs:
721
+ head += f" · average accuracy <b>{sum(accs) / len(accs):.1f}</b>"
722
+ lines = [head]
723
+ bad = sum(r["bad"] for r in done)
724
+ lines.append(
725
+ f"Mistakes + misses + blunders: <b>{bad / len(done):.1f}</b> per game"
726
+ )
727
+ ph = [sum(r["phases"][i] for r in done) for i in range(3)]
728
+ if sum(ph):
729
+ lines.append(
730
+ "Where they happen: "
731
+ + " · ".join(
732
+ f"{n} {v * 100 / sum(ph):.0f}%" for n, v in zip(PHASES, ph)
733
+ )
734
+ )
735
+ clk = [r for r in done if r["has_clock"]]
736
+ if clk:
737
+ moves, low = sum(r["moves"] for r in clk), sum(r["low"] for r in clk)
738
+ bad_c, bad_low = sum(r["bad"] for r in clk), sum(r["bad_low"] for r in clk)
739
+ if low and bad_c:
740
+ lines.append(
741
+ f"With under {LOW_CLOCK} s left: {low * 100 / moves:.0f}% of your moves, "
742
+ f"{bad_low * 100 / bad_c:.0f}% of your bad moves"
743
+ )
744
+ weak = [g for g in self._groups() if g["games"] >= 3 and g["score"] is not None]
745
+ if weak:
746
+ g = min(weak, key=lambda g: (g["score"], -g["bad"]))
747
+ side = "White" if g["color"] else "Black"
748
+ lines.append(
749
+ f"Weakest opening (3+ games): as {side}, {g['family']} · "
750
+ f"{g['score']:.0f}% in {g['games']} games"
751
+ )
752
+ self.summary.setText("<br>".join(lines))
753
+
754
+ def closeEvent(self, event) -> None:
755
+ if self._running():
756
+ self.worker.cancel()
757
+ self.worker.wait(8000)
758
+ super().closeEvent(event)