Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

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

draft paket obsolete

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>
Changeset2023f76409eec2ebd2139b6cd39be58d28bae39e
Author (claimed)Timo Stolz <timo.stolz@nullachtvierzehn.de>,
Parentsc1ab5ff75ae7
Children1c7bda939dc7
Pushlog
by timo via ssh

modified schach/app.py +36 −10

@@ -19,7 +19,7 @@ from . import annotate, clipboard, liche
1919
 from .board import BoardView, available_themes  # noqa: E402
2020
 from .movelist import MoveList  # noqa: E402
2121
 from .prefs import Preferences  # noqa: E402
22
-from .engines import MAIA_CMD, MAIA_CWD, MAIA_PREPARE, STOCKFISH_CMD, EngineWorker, maia_candidates, maia_move  # noqa: E402
22
+from .engines import MAIA_CMD, MAIA_CWD, MAIA_PREPARE, STOCKFISH_CMD, STOCKFISH_PREPARE, EngineWorker, maia_candidates, maia_move  # noqa: E402
2323
 from .threat import null_board, threat_job  # noqa: E402
2424
 from .online import OnlineMixin  # noqa: E402
2525
 from .puzzles import PuzzleMixin  # noqa: E402
@@ -623,7 +623,7 @@ class Window(OnlineMixin, PuzzleMixin, O
623623
             self.title.set_subtitle("Analyse")
624624
         elif self.mode == "review":
625625
             self.title.set_subtitle(f"gegen {self.opponent} · du warst {side}" if self.opponent else "Analyse")
626
-        elif not self.maia_ready:
626
+        elif not self.maia_ready or self.get_application().downloads:
627627
             self.title.set_subtitle(self.get_application().maia_status)
628628
         else:
629629
             clock = f" · {self.clock_label}" if self.clock is not None else ""
@@ -1802,6 +1802,7 @@ class SchachApp(Adw.Application):
18021802
         super().__init__(application_id=APP_ID, flags=Gio.ApplicationFlags.DEFAULT_FLAGS)
18031803
         self.maia_ready = False
18041804
         self.maia_status = "Maia wird geladen …"  # Untertitel, solange Maia nicht bereit ist
1805
+        self.downloads = {}  # Name → (fertig, gesamt) während einmaliger Downloads
18051806
         self.maia = None
18061807
         self.stockfish = None
18071808
         self.stockfish_side = None  # zweiter, kleiner Stockfish für Bedrohungen (das Mitdenken läuft weiter)
@@ -1819,9 +1820,11 @@ class SchachApp(Adw.Application):
18191820
         # eigene Symbole (z. B. das Schwert für Drohungen), eingefärbt wie die GNOME-Symbole
18201821
         Gtk.IconTheme.get_for_display(Gdk.Display.get_default()).add_search_path(ICON_DIR)
18211822
         self.maia = EngineWorker(MAIA_CMD, on_ready=self._on_maia_ready, cwd=MAIA_CWD,
1822
-                                 prepare=MAIA_PREPARE, on_progress=self._on_maia_progress)
1823
+                                 prepare=MAIA_PREPARE, on_progress=self._progress_for("Maia"))
18231824
         self.stockfish = EngineWorker(
1824
-            STOCKFISH_CMD, options={"Threads": min(8, os.cpu_count() or 2), "Hash": 256}
1825
+            STOCKFISH_CMD, options={"Threads": min(8, os.cpu_count() or 2), "Hash": 256},
1826
+            prepare=STOCKFISH_PREPARE, on_progress=self._progress_for("Stockfish"),
1827
+            on_ready=self._on_stockfish_ready,
18251828
         )
18261829
         token = lichess.load_token()
18271830
         if token:
@@ -1903,7 +1906,8 @@ class SchachApp(Adw.Application):
19031906
 
19041907
     def side_engine(self):
19051908
         if self.stockfish_side is None:
1906
-            self.stockfish_side = EngineWorker(STOCKFISH_CMD, options={"Threads": 2, "Hash": 64})
1909
+            self.stockfish_side = EngineWorker(STOCKFISH_CMD, options={"Threads": 2, "Hash": 64},
1910
+                                               prepare=STOCKFISH_PREPARE)
19071911
         return self.stockfish_side
19081912
 
19091913
     def update_setting(self, key, value):
@@ -1966,19 +1970,41 @@ class SchachApp(Adw.Application):
19661970
                 dialog.force_close()
19671971
                 self._toast(Adw.Toast(title="Herausforderung zurückgezogen", timeout=3))
19681972
 
1969
-    def _on_maia_progress(self, stage, done, total):
1970
-        mb = f"{done / 1e6:.0f} von {total / 1e6:.0f} MB" if total else f"{done / 1e6:.0f} MB"
1971
-        percent = f"{100 * done // total} % · " if total else ""
1972
-        text = f"Maia wird heruntergeladen (einmalig) … {percent}{mb}"
1973
+    def _progress_for(self, name):
1974
+        return lambda stage, done, total: self._on_download_progress(name, done, total)
1975
+
1976
+    def _on_download_progress(self, name, done, total):
1977
+        self.downloads[name] = (done, total)
1978
+        self._show_downloads()
1979
+
1980
+    def _show_downloads(self):
1981
+        parts = []
1982
+        for name, (done, total) in self.downloads.items():
1983
+            mb = f"{done / 1e6:.0f} von {total / 1e6:.0f} MB" if total else f"{done / 1e6:.0f} MB"
1984
+            parts.append(f"{name} {100 * done // total} % · {mb}" if total else f"{name} {mb}")
1985
+        text = ("Einmaliger Download: " + " – ".join(parts)) if parts else "Maia wird geladen …"
19731986
         if text == self.maia_status:
19741987
             return
19751988
         self.maia_status = text
19761989
         for win in self.get_windows():
1977
-            if isinstance(win, Window) and not win.maia_ready:
1990
+            if isinstance(win, Window) and (not win.maia_ready or self.downloads):
19781991
                 win._refresh_chrome()
19791992
 
1993
+    def _download_done(self, name):
1994
+        if self.downloads.pop(name, None) is not None:
1995
+            self._show_downloads()
1996
+            for win in self._windows():
1997
+                win._refresh_chrome()
1998
+
1999
+    def _on_stockfish_ready(self, error):
2000
+        self._download_done("Stockfish")
2001
+        if error:
2002
+            self._toast(Adw.Toast(title=f"Stockfish konnte nicht gestartet werden: {error}", timeout=0))
2003
+        return False
2004
+
19802005
     def _on_maia_ready(self, error):
19812006
         self.maia_ready = error is None
2007
+        self._download_done("Maia")
19822008
         for win in self.get_windows():
19832009
             if isinstance(win, Window):
19842010
                 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 +4 −1

@@ -12,7 +12,10 @@ import chess
1212
 import chess.engine
1313
 from gi.repository import GLib
1414
 
15
-STOCKFISH_CMD = ["stockfish"]
15
+from . import stockfish
16
+
17
+# Stockfish vom System oder einmalig heruntergeladen (dann liefert die Vorbereitung den Pfad)
18
+STOCKFISH_CMD, STOCKFISH_PREPARE = stockfish.command()
1619
 MAIA3_UCI_CMD = ["maia3-uci", "--model", "79m", "--use-uci-history"]  # Original mit PyTorch
1720
 _PACKAGE_PARENT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
1821
 

modified schach/maia_onnx.py +4 −48

@@ -28,13 +28,14 @@ from collections import deque
2828
 import chess
2929
 import numpy as np
3030
 
31
+from .downloads import cache_dir, download
32
+
3133
 MODEL_REPO = "bqrio/maia3-onnx"
3234
 MODEL_FILE = "maia3-79m.fp16.history.onnx"
3335
 MODEL_REVISION = "923df9a2e9396b54a09b168bb858ebbd5e5b76bc"
3436
 MODEL_SHA256 = "7cbad622698119e446a86ba9be8b50c0164c1755c8ac8a3a8fea478859f1df51"
3537
 MODEL_SIZE = 156_141_348
3638
 MODEL_URL = f"https://huggingface.co/{MODEL_REPO}/resolve/{MODEL_REVISION}/{MODEL_FILE}"
37
-USER_AGENT = "schach-gtk/1.0"
3839
 HISTORY = 8
3940
 DEFAULT_ELO = 1500
4041
 
@@ -120,58 +121,13 @@ def _fp16_path(progress, local_only):
120121
         pass
121122
     if local_only:
122123
         raise FileNotFoundError(f"Maia-Modell nicht im Cache: {ours}")
123
-    download(MODEL_URL, ours, MODEL_SHA256, progress)
124
+    download(MODEL_URL, ours, MODEL_SHA256, progress, what="Maia-Modell")
124125
     return ours
125126
 
126127
 
127
-def download(url, target, sha256, progress=None, chunk=1 << 20):
128
-    """Datei laden, nach ``target.part``; ein abgebrochener Download wird fortgesetzt.
129
-    Erst nach geprüfter Prüfsumme heißt die Datei ``target``. Kein Gesamt-Zeitlimit –
130
-    nur eine Frist, falls die Verbindung minutenlang steht."""
131
-    import hashlib
132
-
133
-    import requests
134
-
135
-    os.makedirs(os.path.dirname(target), exist_ok=True)
136
-    partial = target + ".part"
137
-    have = os.path.getsize(partial) if os.path.exists(partial) else 0
138
-    headers = {"User-Agent": USER_AGENT}
139
-    if have:
140
-        headers["Range"] = f"bytes={have}-"
141
-    with requests.get(url, headers=headers, stream=True, timeout=(20, 120)) as resp:
142
-        if resp.status_code == 416:  # schon vollständig
143
-            have, mode = os.path.getsize(partial), None
144
-        elif resp.status_code == 206:
145
-            mode = "ab"
146
-        else:
147
-            resp.raise_for_status()
148
-            have, mode = 0, "wb"  # Server kann nicht fortsetzen: von vorn
149
-        if mode:
150
-            total = have + int(resp.headers.get("Content-Length", 0)) or None
151
-            with open(partial, mode) as fh:
152
-                for block in resp.iter_content(chunk):
153
-                    fh.write(block)
154
-                    have += len(block)
155
-                    if progress:
156
-                        progress("download", have, total)
157
-    digest = hashlib.sha256()
158
-    with open(partial, "rb") as fh:
159
-        while block := fh.read(chunk):
160
-            digest.update(block)
161
-    if digest.hexdigest() != sha256:
162
-        os.remove(partial)
163
-        raise ValueError("Maia-Modell: Prüfsumme stimmt nicht – Download verworfen")
164
-    os.replace(partial, target)
165
-
166
-
167128
 def _cache_path(filename):
168129
     """Cache-Datei mit der Modell-Revision im Namen (neue Revision → neue Datei)."""
169
-    base = os.environ.get("XDG_CACHE_HOME") or os.path.join(os.path.expanduser("~"), ".cache")
170
-    if sys.platform == "win32":
171
-        base = os.environ.get("LOCALAPPDATA", base)
172
-    elif sys.platform == "darwin":
173
-        base = os.path.join(os.path.expanduser("~"), "Library", "Caches")
174
-    return os.path.join(base, "schach", filename.replace(".onnx", f".{MODEL_REVISION[:7]}.onnx"))
130
+    return os.path.join(cache_dir(), filename.replace(".onnx", f".{MODEL_REVISION[:7]}.onnx"))
175131
 
176132
 
177133
 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)