Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

feat(engines): download Stockfish when it is not installed

public

feat(engines): download Stockfish when it is not installed

Use the system stockfish if it is on PATH (or SCHACH_STOCKFISH), else fetch the
official Stockfish 19 universal build for Linux, Windows or macOS once into the
cache, pinned by SHA-256, and keep only the binary and its licence. The model
download moves to a shared downloads module; the title bar shows the progress of
all running downloads, and a failing Stockfish start shows a toast.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Changeset6e92c96637e06d7fd60c481e671f1c3bc6689952
Author (claimed)Timo Stolz <timo.stolz@nullachtvierzehn.de>,
Parents178dcfc6ab1c
Children73a17f08e784
Pushlog
by timo via ssh
by timo via ssh

modified schach/app.py +36 −10

@@ -22,7 +22,7 @@ from .board import BoardView, available_
2222
 from .endbar import EndBar  # noqa: E402
2323
 from .movelist import MoveList  # noqa: E402
2424
 from .prefs import Preferences  # noqa: E402
25
-from .engines import MAIA_CMD, MAIA_CWD, MAIA_PREPARE, STOCKFISH_CMD, EngineWorker, maia_candidates, maia_move, maia_probabilities, maia_wdl  # noqa: E402
25
+from .engines import MAIA_CMD, MAIA_CWD, MAIA_PREPARE, STOCKFISH_CMD, STOCKFISH_PREPARE, EngineWorker, maia_candidates, maia_move, maia_probabilities, maia_wdl  # noqa: E402
2626
 from .threat import null_board, threat_job  # noqa: E402
2727
 from .explain import explain_job, explore_job, graft_move, why_not_job  # noqa: E402
2828
 from .online import OnlineMixin  # noqa: E402
@@ -742,7 +742,7 @@ class Window(OnlineMixin, PuzzleMixin, O
742742
             self.title.set_subtitle("Nachspielen")
743743
         elif self.mode == "review":
744744
             self.title.set_subtitle(f"gegen {self.opponent} · du warst {side}" if self.opponent else "Nachspielen")
745
-        elif not self.maia_ready:
745
+        elif not self.maia_ready or self.get_application().downloads:
746746
             self.title.set_subtitle(self.get_application().maia_status)
747747
         else:
748748
             clock = f" · {self.clock_label}" if self.clock is not None else ""
@@ -2404,6 +2404,7 @@ class SchachApp(Adw.Application):
24042404
         super().__init__(application_id=APP_ID, flags=Gio.ApplicationFlags.DEFAULT_FLAGS)
24052405
         self.maia_ready = False
24062406
         self.maia_status = "Maia wird geladen …"  # Untertitel, solange Maia nicht bereit ist
2407
+        self.downloads = {}  # Name → (fertig, gesamt) während einmaliger Downloads
24072408
         self.maia = None
24082409
         self.stockfish = None
24092410
         self.stockfish_side = None  # zweiter, kleiner Stockfish für Bedrohungen (das Mitdenken läuft weiter)
@@ -2422,9 +2423,11 @@ class SchachApp(Adw.Application):
24222423
         # eigene Symbole (z. B. das Schwert für Drohungen), eingefärbt wie die GNOME-Symbole
24232424
         Gtk.IconTheme.get_for_display(Gdk.Display.get_default()).add_search_path(ICON_DIR)
24242425
         self.maia = EngineWorker(MAIA_CMD, on_ready=self._on_maia_ready, cwd=MAIA_CWD,
2425
-                                 prepare=MAIA_PREPARE, on_progress=self._on_maia_progress)
2426
+                                 prepare=MAIA_PREPARE, on_progress=self._progress_for("Maia"))
24262427
         self.stockfish = EngineWorker(
2427
-            STOCKFISH_CMD, options={"Threads": energy.think_settings(load_settings())[0], "Hash": 256}
2428
+            STOCKFISH_CMD, options={"Threads": energy.think_settings(load_settings())[0], "Hash": 256},
2429
+            prepare=STOCKFISH_PREPARE, on_progress=self._progress_for("Stockfish"),
2430
+            on_ready=self._on_stockfish_ready,
24282431
         )
24292432
         token = lichess.load_token()
24302433
         if token:
@@ -2506,7 +2509,8 @@ class SchachApp(Adw.Application):
25062509
 
25072510
     def side_engine(self):
25082511
         if self.stockfish_side is None:
2509
-            self.stockfish_side = EngineWorker(STOCKFISH_CMD, options={"Threads": 2, "Hash": 64})
2512
+            self.stockfish_side = EngineWorker(STOCKFISH_CMD, options={"Threads": 2, "Hash": 64},
2513
+                                               prepare=STOCKFISH_PREPARE)
25102514
         return self.stockfish_side
25112515
 
25122516
     def update_setting(self, key, value):
@@ -2571,19 +2575,41 @@ class SchachApp(Adw.Application):
25712575
                 dialog.force_close()
25722576
                 self._toast(Adw.Toast(title="Herausforderung zurückgezogen", timeout=3))
25732577
 
2574
-    def _on_maia_progress(self, stage, done, total):
2575
-        mb = f"{done / 1e6:.0f} von {total / 1e6:.0f} MB" if total else f"{done / 1e6:.0f} MB"
2576
-        percent = f"{100 * done // total} % · " if total else ""
2577
-        text = f"Maia wird heruntergeladen (einmalig) … {percent}{mb}"
2578
+    def _progress_for(self, name):
2579
+        return lambda stage, done, total: self._on_download_progress(name, done, total)
2580
+
2581
+    def _on_download_progress(self, name, done, total):
2582
+        self.downloads[name] = (done, total)
2583
+        self._show_downloads()
2584
+
2585
+    def _show_downloads(self):
2586
+        parts = []
2587
+        for name, (done, total) in self.downloads.items():
2588
+            mb = f"{done / 1e6:.0f} von {total / 1e6:.0f} MB" if total else f"{done / 1e6:.0f} MB"
2589
+            parts.append(f"{name} {100 * done // total} % · {mb}" if total else f"{name} {mb}")
2590
+        text = ("Einmaliger Download: " + " – ".join(parts)) if parts else "Maia wird geladen …"
25782591
         if text == self.maia_status:
25792592
             return
25802593
         self.maia_status = text
25812594
         for win in self.get_windows():
2582
-            if isinstance(win, Window) and not win.maia_ready:
2595
+            if isinstance(win, Window) and (not win.maia_ready or self.downloads):
25832596
                 win._refresh_chrome()
25842597
 
2598
+    def _download_done(self, name):
2599
+        if self.downloads.pop(name, None) is not None:
2600
+            self._show_downloads()
2601
+            for win in self._windows():
2602
+                win._refresh_chrome()
2603
+
2604
+    def _on_stockfish_ready(self, error):
2605
+        self._download_done("Stockfish")
2606
+        if error:
2607
+            self._toast(Adw.Toast(title=f"Stockfish konnte nicht gestartet werden: {error}", timeout=0))
2608
+        return False
2609
+
25852610
     def _on_maia_ready(self, error):
25862611
         self.maia_ready = error is None
2612
+        self._download_done("Maia")
25872613
         for win in self.get_windows():
25882614
             if isinstance(win, Window):
25892615
                 win._on_maia_ready(error)

added schach/downloads.py +61 −0

@@ -0,0 +1,61 @@
1
+"""Einmalige Downloads (Maia-Modell, Stockfish) in den Cache, mit Fortsetzen und Prüfsumme."""
2
+
3
+import hashlib
4
+import os
5
+import sys
6
+
7
+USER_AGENT = "schach-gtk/1.0"
8
+
9
+
10
+def cache_dir():
11
+    """Cache-Ordner des Programms, je nach System (``~/.cache/schach`` unter Linux)."""
12
+    base = os.environ.get("XDG_CACHE_HOME") or os.path.join(os.path.expanduser("~"), ".cache")
13
+    if sys.platform == "win32":
14
+        base = os.environ.get("LOCALAPPDATA", base)
15
+    elif sys.platform == "darwin":
16
+        base = os.path.join(os.path.expanduser("~"), "Library", "Caches")
17
+    return os.path.join(base, "schach")
18
+
19
+
20
+def download(url, target, sha256, progress=None, chunk=1 << 20, what="Download"):
21
+    """Datei laden, nach ``target.part``; ein abgebrochener Download wird fortgesetzt.
22
+    Erst nach geprüfter Prüfsumme heißt die Datei ``target``. Kein Gesamt-Zeitlimit –
23
+    nur eine Frist, falls die Verbindung minutenlang steht.
24
+
25
+    ``progress("download", fertig, gesamt)`` in Bytes; gesamt kann None sein."""
26
+    import requests
27
+
28
+    os.makedirs(os.path.dirname(target), exist_ok=True)
29
+    partial = target + ".part"
30
+    have = os.path.getsize(partial) if os.path.exists(partial) else 0
31
+    headers = {"User-Agent": USER_AGENT}
32
+    if have:
33
+        headers["Range"] = f"bytes={have}-"
34
+    with requests.get(url, headers=headers, stream=True, timeout=(20, 120)) as resp:
35
+        if resp.status_code == 416:  # schon vollständig
36
+            have, mode = os.path.getsize(partial), None
37
+        elif resp.status_code == 206:
38
+            mode = "ab"
39
+        else:
40
+            resp.raise_for_status()
41
+            have, mode = 0, "wb"  # Server kann nicht fortsetzen: von vorn
42
+        if mode:
43
+            total = have + int(resp.headers.get("Content-Length", 0)) or None
44
+            with open(partial, mode) as fh:
45
+                for block in resp.iter_content(chunk):
46
+                    fh.write(block)
47
+                    have += len(block)
48
+                    if progress:
49
+                        progress("download", have, total)
50
+    if file_sha256(partial, chunk) != sha256:
51
+        os.remove(partial)
52
+        raise ValueError(f"{what}: Prüfsumme stimmt nicht – Download verworfen")
53
+    os.replace(partial, target)
54
+
55
+
56
+def file_sha256(path, chunk=1 << 20):
57
+    digest = hashlib.sha256()
58
+    with open(path, "rb") as fh:
59
+        while block := fh.read(chunk):
60
+            digest.update(block)
61
+    return digest.hexdigest()

modified schach/engines.py +3 −2

@@ -13,9 +13,10 @@ import chess
1313
 import chess.engine
1414
 from gi.repository import GLib
1515
 
16
-from . import wdl
16
+from . import stockfish, wdl
1717
 
18
-STOCKFISH_CMD = ["stockfish"]
18
+# Stockfish vom System oder einmalig heruntergeladen (dann liefert die Vorbereitung den Pfad)
19
+STOCKFISH_CMD, STOCKFISH_PREPARE = stockfish.command()
1920
 MAIA3_UCI_CMD = ["maia3-uci", "--model", "79m", "--use-uci-history"]  # Original mit PyTorch
2021
 _PACKAGE_PARENT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
2122
 

modified schach/maia_onnx.py +4 −48

@@ -29,13 +29,14 @@ from collections import deque
2929
 import chess
3030
 import numpy as np
3131
 
32
+from .downloads import cache_dir, download
33
+
3234
 MODEL_REPO = "bqrio/maia3-onnx"
3335
 MODEL_FILE = "maia3-79m.fp16.history.onnx"
3436
 MODEL_REVISION = "923df9a2e9396b54a09b168bb858ebbd5e5b76bc"
3537
 MODEL_SHA256 = "7cbad622698119e446a86ba9be8b50c0164c1755c8ac8a3a8fea478859f1df51"
3638
 MODEL_SIZE = 156_141_348
3739
 MODEL_URL = f"https://huggingface.co/{MODEL_REPO}/resolve/{MODEL_REVISION}/{MODEL_FILE}"
38
-USER_AGENT = "schach-gtk/1.0"
3940
 HISTORY = 8
4041
 DEFAULT_ELO = 1500
4142
 
@@ -132,58 +133,13 @@ def _fp16_path(progress, local_only):
132133
         pass
133134
     if local_only:
134135
         raise FileNotFoundError(f"Maia-Modell nicht im Cache: {ours}")
135
-    download(MODEL_URL, ours, MODEL_SHA256, progress)
136
+    download(MODEL_URL, ours, MODEL_SHA256, progress, what="Maia-Modell")
136137
     return ours
137138
 
138139
 
139
-def download(url, target, sha256, progress=None, chunk=1 << 20):
140
-    """Datei laden, nach ``target.part``; ein abgebrochener Download wird fortgesetzt.
141
-    Erst nach geprüfter Prüfsumme heißt die Datei ``target``. Kein Gesamt-Zeitlimit –
142
-    nur eine Frist, falls die Verbindung minutenlang steht."""
143
-    import hashlib
144
-
145
-    import requests
146
-
147
-    os.makedirs(os.path.dirname(target), exist_ok=True)
148
-    partial = target + ".part"
149
-    have = os.path.getsize(partial) if os.path.exists(partial) else 0
150
-    headers = {"User-Agent": USER_AGENT}
151
-    if have:
152
-        headers["Range"] = f"bytes={have}-"
153
-    with requests.get(url, headers=headers, stream=True, timeout=(20, 120)) as resp:
154
-        if resp.status_code == 416:  # schon vollständig
155
-            have, mode = os.path.getsize(partial), None
156
-        elif resp.status_code == 206:
157
-            mode = "ab"
158
-        else:
159
-            resp.raise_for_status()
160
-            have, mode = 0, "wb"  # Server kann nicht fortsetzen: von vorn
161
-        if mode:
162
-            total = have + int(resp.headers.get("Content-Length", 0)) or None
163
-            with open(partial, mode) as fh:
164
-                for block in resp.iter_content(chunk):
165
-                    fh.write(block)
166
-                    have += len(block)
167
-                    if progress:
168
-                        progress("download", have, total)
169
-    digest = hashlib.sha256()
170
-    with open(partial, "rb") as fh:
171
-        while block := fh.read(chunk):
172
-            digest.update(block)
173
-    if digest.hexdigest() != sha256:
174
-        os.remove(partial)
175
-        raise ValueError("Maia-Modell: Prüfsumme stimmt nicht – Download verworfen")
176
-    os.replace(partial, target)
177
-
178
-
179140
 def _cache_path(filename):
180141
     """Cache-Datei mit der Modell-Revision im Namen (neue Revision → neue Datei)."""
181
-    base = os.environ.get("XDG_CACHE_HOME") or os.path.join(os.path.expanduser("~"), ".cache")
182
-    if sys.platform == "win32":
183
-        base = os.environ.get("LOCALAPPDATA", base)
184
-    elif sys.platform == "darwin":
185
-        base = os.path.join(os.path.expanduser("~"), "Library", "Caches")
186
-    return os.path.join(base, "schach", filename.replace(".onnx", f".{MODEL_REVISION[:7]}.onnx"))
142
+    return os.path.join(cache_dir(), filename.replace(".onnx", f".{MODEL_REVISION[:7]}.onnx"))
187143
 
188144
 
189145
 def _options(ort):

added schach/stockfish.py +116 −0

@@ -0,0 +1,116 @@
1
+"""Stockfish finden oder einmalig herunterladen.
2
+
3
+Reihenfolge: ``SCHACH_STOCKFISH`` (Pfad zu einem Programm), dann ``stockfish`` auf dem PATH
4
+(z. B. aus der Paketverwaltung), sonst die offizielle Ausgabe von GitHub in den Cache. Die
5
+„universal“-Programme ab Stockfish 19 wählen selbst die schnellste Variante für den Prozessor.
6
+Lizenz: GPL-3.0 (mit der AGPL dieses Programms vereinbar); Lizenztext liegt im Cache daneben.
7
+"""
8
+
9
+import os
10
+import platform
11
+import shutil
12
+import sys
13
+import tarfile
14
+import threading
15
+import zipfile
16
+
17
+from .downloads import cache_dir, download
18
+
19
+VERSION = "sf_19"
20
+BASE_URL = f"https://github.com/official-stockfish/Stockfish/releases/download/{VERSION}/"
21
+# (System, Prozessor) → (Archiv, SHA-256 laut GitHub-Release)
22
+BUILDS = {
23
+    ("linux", "x86_64"): ("stockfish-linux-x86-64-universal.tar.gz",
24
+                          "9defc0d4e55d49c65a6d042f3e571a39fcea499ade6dbe741b53b8c65e03611f"),
25
+    ("linux", "aarch64"): ("stockfish-linux-arm64-universal.tar.gz",
26
+                           "fe26cfd1d9db4c8af3d21e24d9ff34cacb31c1f940085a7583da11796f2bac01"),
27
+    ("linux", "riscv64"): ("stockfish-linux-riscv64-universal.tar.gz",
28
+                           "d4b4d118c003bc669a939d9fb208e3ef6b367730fd79a70dbc278b18475df3d1"),
29
+    ("darwin", "x86_64"): ("stockfish-macos-universal.tar.gz",
30
+                           "a1f0e3bcc5a6927a11fe6fc8e54a779754645f3c2bae2cf13420fd1957adaa77"),
31
+    ("darwin", "arm64"): ("stockfish-macos-universal.tar.gz",
32
+                          "a1f0e3bcc5a6927a11fe6fc8e54a779754645f3c2bae2cf13420fd1957adaa77"),
33
+    ("win32", "x86_64"): ("stockfish-windows-x86-64-universal.zip",
34
+                          "3c8bf1f9ea66a09350a40df4f632288285ac206d99f33ab5842c408fc30b48a7"),
35
+    ("win32", "arm64"): ("stockfish-windows-arm64-universal.zip",
36
+                         "8372ad3f0d7276deb2c70f801f541ec7db463219fc6d9c7592864e542aa4f401"),
37
+}
38
+_MACHINES = {"amd64": "x86_64", "x64": "x86_64", "arm64": "arm64", "aarch64": "aarch64"}
39
+_lock = threading.Lock()  # Haupt- und Neben-Stockfish starten gleichzeitig: nur ein Download
40
+
41
+
42
+def command():
43
+    """(Befehl, Vorbereitung oder None) für ``EngineWorker``."""
44
+    own = os.environ.get("SCHACH_STOCKFISH")
45
+    if own:
46
+        return [own], None
47
+    found = shutil.which("stockfish")
48
+    if found:
49
+        return [found], None
50
+    return [], prepare
51
+
52
+
53
+def build(system=None, machine=None):
54
+    """(Archiv, SHA-256) für dieses System oder None."""
55
+    system = system or sys.platform
56
+    system = "linux" if system.startswith("linux") else system
57
+    machine = (machine or platform.machine()).lower()
58
+    machine = _MACHINES.get(machine, machine)
59
+    if system == "darwin" and machine == "aarch64":
60
+        machine = "arm64"
61
+    if system == "linux" and machine == "arm64":
62
+        machine = "aarch64"
63
+    return BUILDS.get((system, machine))
64
+
65
+
66
+def binary_path(archive, base=None):
67
+    stem = archive.removesuffix(".tar.gz").removesuffix(".zip")
68
+    suffix = ".exe" if archive.endswith(".zip") else ""
69
+    return os.path.join(base or cache_dir(), f"stockfish-{VERSION}", stem + suffix)
70
+
71
+
72
+def prepare(progress=None, base=None):
73
+    """Stockfish aus dem Cache oder herunterladen → [Pfad] (Zusatzargument für den Befehl)."""
74
+    entry = build()
75
+    if entry is None:
76
+        raise FileNotFoundError(
77
+            f"Stockfish fehlt, und für {sys.platform}/{platform.machine()} gibt es keinen Download – "
78
+            "bitte Stockfish installieren (oder SCHACH_STOCKFISH=Pfad setzen)")
79
+    archive, sha256 = entry
80
+    target = binary_path(archive, base)
81
+    with _lock:
82
+        if not os.path.isfile(target):
83
+            folder = os.path.dirname(target)
84
+            packed = os.path.join(folder, archive)
85
+            download(BASE_URL + archive, packed, sha256, progress, what="Stockfish")
86
+            extract(packed, folder, os.path.basename(target))
87
+            os.remove(packed)
88
+    return [target]
89
+
90
+
91
+def extract(packed, folder, name):
92
+    """Nur das Programm und den Lizenztext aus dem Archiv holen (ohne die Ordner darin)."""
93
+    wanted = {name: name, "Copying.txt": "COPYING.txt"}
94
+    if packed.endswith(".zip"):
95
+        with zipfile.ZipFile(packed) as zf:
96
+            members = [(m, os.path.basename(m)) for m in zf.namelist()]
97
+            for member, base in members:
98
+                if base in wanted:
99
+                    _write(zf.open(member), os.path.join(folder, wanted[base]))
100
+    else:
101
+        with tarfile.open(packed) as tf:
102
+            for member in tf.getmembers():
103
+                base = os.path.basename(member.name)
104
+                if member.isfile() and base in wanted:
105
+                    _write(tf.extractfile(member), os.path.join(folder, wanted[base]))
106
+    path = os.path.join(folder, name)
107
+    if not os.path.isfile(path):
108
+        raise FileNotFoundError(f"Stockfish: {name} fehlt im Archiv")
109
+    os.chmod(path, 0o755)
110
+
111
+
112
+def _write(src, path):
113
+    partial = path + ".part"
114
+    with src, open(partial, "wb") as out:
115
+        shutil.copyfileobj(src, out, 1 << 20)
116
+    os.replace(partial, path)