Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

schach / tools / readme_bilder.py · 11.6 KB · at 3c63b1d52560 · raw

Outline: 13 definitions
1
"""Bilder für die README: App isoliert starten, Szenen durchspielen, Fenster als SVG oder WebP speichern.
2
3
Am besten ohne eigenen Bildschirm und mit dem Python aus dem venv von schach.sh (wegen fsrs):
4
5
    xvfb-run -a -s "-screen 0 2560x1600x24" env GDK_BACKEND=x11 \
6
        ~/.local/share/schach/venv/bin/python tools/readme_bilder.py --svg [SZENE …]
7
8
Szenen: spielen, kurs, fehler, besprechung, menue, lichess (ohne Angabe: alle). Ergebnis in
9
``docs/bilder/`` als WebP in doppelter Auflösung (verlustfrei), mit ``--svg`` stattdessen als SVG –
10
das nutzt die README. Das SVG zeichnet GTKs Software-Ausgabe (cairo) aus denselben Render-Nodes wie
11
das WebP: Brett, Figuren und Knöpfe bleiben Vektoren und auf jeder Zoomstufe scharf, Schrift wird zu
12
Umrissen, nur Schatten und Abdunkelung kommen als eingebettetes Rasterbild. ourforge liefert SVG
13
als Bild aus, wenn der Browser es für ein ``<img>`` lädt (``Sec-Fetch-Dest: image``). Einstellungen, Spielstände und training.sqlite liegen in einem leeren
14
Wegwerf-Ordner; Lichess bleibt abgemeldet (das Konto im Menü und im Herausforderungsdialog ist nur
15
vorgetäuscht, es geht nichts ans Netz). Die Nachbesprechung spielt stillen Ton. Braucht Stockfish,
16
das Maia-Modell im Cache, ffmpeg und für WebP ImageMagick (``magick``).
17
"""
18
19
import os
20
import re
21
import shutil
22
import subprocess
23
import sys
24
import tempfile
25
26
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
27
OUT = os.path.join(REPO, "docs", "bilder")
28
SVG = "--svg" in sys.argv[1:]
29
ONLY = {arg for arg in sys.argv[1:] if not arg.startswith("--")}
30
HOME = tempfile.mkdtemp(prefix="schach-bilder-")
31
os.environ["XDG_CONFIG_HOME"] = os.path.join(HOME, "config")
32
os.environ["XDG_DATA_HOME"] = os.path.join(HOME, "data")
33
os.makedirs(OUT, exist_ok=True)
34
sys.path.insert(0, REPO)
35
36
import cairo  # noqa: E402
37
import chess  # noqa: E402
38
import chess.engine  # noqa: E402
39
import gi  # noqa: E402
40
41
gi.require_version("Gtk", "4.0")
42
gi.require_version("Adw", "1")
43
gi.require_version("Graphene", "1.0")
44
from gi.repository import Adw, Gio, GLib, Graphene, Gtk  # noqa: E402
45
46
import schach.lichess  # noqa: E402
47
48
schach.lichess.load_token = lambda: None  # nie mit dem echten Konto
49
from schach import app as schach_app, opening, recording, repetition, savegames, training  # noqa: E402
50
51
W, H = 1180, 780
52
53
54
def popup_offset(win, popover):
55
    """Lage eines aufgeklappten Popovers im Fenster (eigene Oberfläche, deshalb über die Surfaces)."""
56
    surface = popover.get_surface()
57
    win_x, win_y = win.get_surface_transform()
58
    pop_x, pop_y = popover.get_surface_transform()
59
    return surface.get_position_x() - win_x + pop_x, surface.get_position_y() - win_y + pop_y
60
61
62
def window_node(win, popover=None, scale=1):
63
    """Render-Node des Fensters, auf Wunsch mit einem aufgeklappten Popover darüber."""
64
    snap = Gtk.Snapshot()
65
    snap.scale(scale, scale)
66
    Gtk.WidgetPaintable.new(win).snapshot(snap, win.get_width(), win.get_height())
67
    if popover is not None:
68
        x, y = popup_offset(win, popover)
69
        snap.translate(Graphene.Point().init(x, y))
70
        Gtk.WidgetPaintable.new(popover).snapshot(snap, popover.get_width(), popover.get_height())
71
    return snap.to_node()
72
73
74
COMPOSITE = re.compile(
75
    r'<filter id="(?P<id>[^"]+)"[^>]*>\s*'
76
    r'<feImage xlink:href="#(?P<src>[^"]+)" result="source"[^>]*/>\s*'
77
    r'<feImage xlink:href="#(?P<dst>[^"]+)" result="destination"[^>]*/>\s*'
78
    r'<feComposite in="source" in2="destination" operator="arithmetic" k1="0" k2="1" k3="1" k4="0"[^>]*/>\s*'
79
    r'</filter>\s*')
80
81
82
def without_feimage(svg):
83
    """Firefox-taugliches SVG: cairo setzt manche beschnittene Zeichnung als Filter zusammen, der zwei
84
    Gruppen addiert und sie per ``feImage`` aus dem eigenen Dokument holt – das zeichnet nur Chrome,
85
    Firefox lässt die Fläche leer. Die Masken der beiden Gruppen ergänzen sich, also gibt Übereinander-
86
    zeichnen dasselbe Bild (bis auf Kantenglättung)."""
87
    filters = {m["id"]: (m["src"], m["dst"]) for m in COMPOSITE.finditer(svg)}
88
    svg = COMPOSITE.sub("", svg)
89
90
    def replace(match):
91
        src, dst = filters[match["id"]]
92
        return f'<g{match["rest"]}><use xlink:href="#{dst}"/><use xlink:href="#{src}"/></g>'
93
94
    ids = "|".join(map(re.escape, filters)) or "(?!)"
95
    svg = re.sub(rf'<g filter="url\(#(?P<id>{ids})\)"(?P<rest>[^>]*)>\s*<rect [^>]*/>\s*</g>', replace, svg)
96
    if "<feImage" in svg:
97
        print("Achtung: SVG enthält noch feImage – Firefox zeigt es womöglich nicht an", flush=True)
98
    return svg
99
100
101
def shot(win, name, popover=None):
102
    """Fenster als WebP in doppelter Auflösung, mit ``--svg`` stattdessen als SVG."""
103
    w, h = win.get_width(), win.get_height()
104
    if SVG:
105
        path = os.path.join(OUT, name + ".svg")
106
        surface = cairo.SVGSurface(path, w, h)
107
        window_node(win, popover).draw(cairo.Context(surface))
108
        surface.finish()
109
        with open(path) as f:
110
            svg = without_feimage(f.read())
111
        with open(path, "w") as f:
112
            f.write(svg)
113
    else:
114
        scale = 2  # wie auf einem HiDPI-Bildschirm
115
        rect = Graphene.Rect().init(0, 0, w * scale, h * scale)
116
        texture = win.get_renderer().render_texture(window_node(win, popover, scale), rect)
117
        png = os.path.join(HOME, name + ".png")
118
        texture.save_to_png(png)
119
        path = os.path.join(OUT, name + ".webp")
120
        subprocess.run(["magick", png, "-define", "webp:lossless=true", "-define", "webp:method=6", path],
121
                       check=True)
122
    print("geschrieben:", os.path.relpath(path, REPO), flush=True)
123
124
125
def find(widget, kind):
126
    if isinstance(widget, kind):
127
        return widget
128
    child = widget.get_first_child()
129
    while child is not None:
130
        hit = find(child, kind)
131
        if hit is not None:
132
            return hit
133
        child = child.get_next_sibling()
134
    return None
135
136
137
def mistake_card():
138
    """Blackburne-Shilling-Falle: 3…Sd4, und man schlägt 4.Sxe5?? – Stockfish rechnet die guten Züge."""
139
    start = chess.Board()
140
    for san in ("e4", "e5", "Nf3", "Nc6", "Bc4"):
141
        start.push_san(san)
142
    last = start.parse_san("Nd4")
143
    before = start.copy()
144
    before.push(last)
145
    played = before.parse_san("Nxe5")
146
    with chess.engine.SimpleEngine.popen_uci("stockfish") as sf:
147
        infos = sf.analyse(before, chess.engine.Limit(depth=18), multipv=6)
148
    scores = {i["pv"][0]: i["score"].white().wdl().expectation() * 100 for i in infos}
149
    best = max(scores, key=scores.get)
150
    good = [m.uci() for m, s in scores.items() if s >= scores[best] - 2 and m != played]
151
    print("beste Züge:", [before.san(m) for m in scores], good, flush=True)
152
    content = {"fen": start.fen(), "last": last.uci(), "solution": [best.uci()], "accepted": good,
153
               "played": played.uci(), "symbol": "??"}
154
    return repetition.position_key(before), content, best
155
156
157
def review_file(folder):
158
    """Nachbesprechung einer kurzen Partie: stiller Ton, alle 1,5 s ein Zug, dazu Pfeile wie beim Erklären."""
159
    audio = os.path.join(folder, "ton.opus")
160
    subprocess.run(["ffmpeg", "-loglevel", "error", "-y", "-f", "lavfi", "-i", "anullsrc=r=48000:cl=mono",
161
                    "-t", "30", "-c:a", "libopus", audio], check=True)
162
    board = chess.Board()
163
    for san in "e4 e5 Nf3 Nc6 Bc4 Nf6 Ng5 d5 exd5 Na5 Bb5+ c6 dxc6 bxc6 Qf3".split():
164
        board.push_san(san)
165
    state = savegames.GameState(board=board, human=chess.WHITE, elo=1200)
166
    timeline = recording.Timeline()
167
    moves = list(board.move_stack)
168
    ms = 0
169
    for i in range(len(moves) + 1):
170
        timeline.show(ms, moves[:i], ())
171
        ms += 500
172
        if i == 6:  # nach 4.Sg5: Doppelangriff auf f7 einzeichnen
173
            timeline.show(ms, moves[:i], ((chess.G5, chess.F7, "red"), (chess.C4, chess.F7, "red"),
174
                                          (chess.F7, chess.F7, "red")))
175
            ms += 6000
176
        ms += 300
177
    header, _, body = savegames.to_pgn(state).partition("\n\n")
178
    with open(audio, "rb") as f:
179
        data = recording.write_pgn(f.read(), f'{header}\n[Replay "{timeline.encode()}"]\n\n{body}')
180
    path = os.path.join(folder, "nachbesprechung.opus")
181
    with open(path, "wb") as f:
182
        f.write(data)
183
    return path
184
185
186
def scenes(app):
187
    win = schach_app.Window(app, None)
188
    win.set_default_size(W, H)
189
    win.present()
190
    yield 4000
191
192
    # --- 1. Einfach spielen: Partie gegen Maia mit Hinweis -------------------------------------
193
    if not ONLY or "spielen" in ONLY:
194
        board = chess.Board()
195
        for san in "e4 e5 Nf3 Nc6 Bc4 Nf6 d3 Bc5 O-O d6 c3 O-O Bg5 h6 Bh4 Bg4 Nbd2 Nh5".split():
196
            board.push_san(san)
197
        state = savegames.GameState(board=board, human=chess.WHITE, elo=1200)
198
        win.load_state(state)
199
        win.list_btn.set_active(True)
200
        yield 25000  # Stockfish denkt mit, Balken und Zeichen
201
        win.activate_action("win.hint", None)
202
        yield 1500
203
        win.activate_action("win.hint", None)
204
        yield 2500
205
        shot(win, "spielen")
206
207
    # --- 2. Eröffnung üben -------------------------------------------------------------------------
208
    if not ONLY or "kurs" in ONLY:
209
        course = next(c for c in opening.load_courses() if c.title == "Italienisch")
210
        win.start_opening(course)
211
        yield 3000
212
        for _ in range(3):
213
            if win.board.turn == win.human:
214
                options = win.course.options(win.board)
215
                if options:
216
                    win._on_board_move(options[0].move.from_square, options[0].move.to_square)
217
            yield 4500
218
        shot(win, "kurs")
219
220
    # --- 3. Eigener Fehler als Rätsel, kommt nach FSRS wieder --------------------------------------
221
    if not ONLY or "fehler" in ONLY:
222
        key, content, best = mistake_card()
223
        training.progress().add_found(repetition.KIND_MISTAKE, key, content)
224
        win.activate_action("win.puzzle", None)
225
        yield 2500
226
        win._on_board_move(best.from_square, best.to_square)
227
        yield 2500
228
        shot(win, "fehler")
229
230
    # --- 3b. Nachbesprechung: vertonte Durchsicht abspielen (stummer Ton) ---------------------------
231
    if not ONLY or "besprechung" in ONLY:
232
        path = review_file(HOME)
233
        win.new_game(chess.WHITE)
234
        yield 1000
235
        win.open_review(path)
236
        yield 9000
237
        win.playback["media"].pause()
238
        yield 800
239
        shot(win, "nachbesprechung")
240
        win.activate_action("win.playback-stop", None)
241
        yield 800
242
243
    # --- 4. Neu-Menü mit allen Spielarten --------------------------------------------------------
244
    if not ONLY or "menue" in ONLY:
245
        app.lichess_user = {"username": "Papa_Schach", "id": "papa_schach"}
246
        win.new_game(chess.WHITE)
247
        win.update_lichess_menu()
248
        win._refresh()
249
        yield 1500
250
        split = find(win.header, Adw.SplitButton)
251
        split.popup()
252
        yield 1200
253
        popover = find(split, Gtk.PopoverMenu)
254
        shot(win, "menue", popover)
255
        popover.popdown()
256
        yield 500
257
258
    # --- 5. Freund auf Lichess herausfordern (Konto nur vorgetäuscht) -----------------------------
259
    if not ONLY or "lichess" in ONLY:
260
        app.lichess_user = {"username": "Papa_Schach", "id": "papa_schach"}
261
        win.settings["friend"] = "Lena2016"
262
        win._challenge_dialog()
263
        yield 1500
264
        shot(win, "lichess")
265
266
    app.quit()
267
268
269
class App(schach_app.SchachApp):
270
    def __init__(self):
271
        super().__init__()
272
        self.set_flags(Gio.ApplicationFlags.NON_UNIQUE)
273
274
    def do_activate(self):
275
        steps = scenes(self)
276
277
        def step():
278
            try:
279
                delay = next(steps)
280
            except StopIteration:
281
                return False
282
            GLib.timeout_add(delay, step)
283
            return False
284
285
        step()
286
287
288
App().run([])
289
shutil.rmtree(HOME, ignore_errors=True)