Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

feat(export): name the opening, glyphs instead of NAG numbers on the HTML page

public

feat(export): name the opening, glyphs instead of NAG numbers on the HTML page

PGN exports get ECO/Opening headers and a comment 'Bis hier: C55 …' at the last
move whose position eco.db knows; the opening also appears in the meta line of
HTML, PDF, LaTeX and ASCII. The HTML page shows !, ?, ?! … in colour (also in
the copied PGN) and drops the [%wp] comments, which are already shown as bars.
opening.Names gains exact_eco() for code and name.

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

modified schach/export.py +88 −20

@@ -13,6 +13,7 @@ import datetime
1313
 import html as html_mod
1414
 import io
1515
 import json
16
+import re
1617
 import os
1718
 import shutil
1819
 import subprocess
@@ -22,7 +23,7 @@ import textwrap
2223
 import chess
2324
 import chess.pgn
2425
 
25
-from . import notation, savegames
26
+from . import notation, opening, savegames
2627
 from .diagram import (
2728
     BADGE, BAR_BLACK, BAR_WHITE, BUILTIN_THEME, CHECK, DEFAULT_SCHEME, Diagram, hex_color, piece_svg,
2829
     scheme_colors,
@@ -101,6 +102,12 @@ class Info:
101102
     date: str  # TT.MM.JJJJ
102103
     result: str  # "1-0", "0-1", "1/2-1/2", "*"
103104
     end_text: str  # z. B. "Schwarz hat aufgegeben."
105
+    opening: str = ""  # „C55 Zweispringerspiel“
106
+
107
+    def meta(self):
108
+        """Zeile unter der Überschrift: Anlass · Datum · Ergebnis · Ende · Eröffnung."""
109
+        parts = (self.event, self.date, RESULT_TEXT.get(self.result, ""), self.end_text, self.opening)
110
+        return " · ".join(p for p in parts if p and p != "?")
104111
 
105112
     @property
106113
     def title(self):
@@ -115,9 +122,42 @@ def info(state):
115122
         white=headers.get("White", "?"), black=headers.get("Black", "?"),
116123
         event=headers.get("Event", ""), date=date, result=headers.get("Result", "*"),
117124
         end_text=state.final_text or "",
125
+        opening=" ".join(book_end(state)[1:]),
118126
     )
119127
 
120128
 
129
+_NAMES = None
130
+BOOK_SEARCH_PLIES = 60  # weiter hinten stehen keine Eröffnungen mehr in eco.db
131
+
132
+
133
+def _names():
134
+    global _NAMES
135
+    if _NAMES is None:
136
+        _NAMES = opening.Names()
137
+    return _NAMES
138
+
139
+
140
+def book_end(state, plies=None):
141
+    """(Halbzug-Index, ECO, Name) des letzten Zugs, dessen Stellung eco.db kennt; sonst (None, "", "").
142
+
143
+    ``plies``: nur bis zu dieser Stellung suchen (für den Export einer Stellung).
144
+    """
145
+    names = _names()
146
+    found = (None, "", "")
147
+    board = state.board.root()
148
+    stop = len(state.board.move_stack) if plies is None else plies
149
+    for ply, move in enumerate(state.board.move_stack[:min(stop, BOOK_SEARCH_PLIES)]):
150
+        board.push(move)
151
+        entry = names.exact_eco(board)
152
+        if entry:
153
+            found = (ply, *entry)
154
+    return found
155
+
156
+
157
+def book_comment(eco, name):
158
+    return f"Bis hier: {eco} {name}".replace("  ", " ")
159
+
160
+
121161
 RESULT_TEXT = {"1-0": "1–0", "0-1": "0–1", "1/2-1/2": "½–½", "*": ""}
122162
 
123163
 
@@ -194,23 +234,53 @@ def to_fen(state, opts):
194234
 
195235
 
196236
 def to_pgn(state, opts):
237
+    """PGN mit Eröffnung (Kopfzeilen ECO/Opening, Kommentar „Bis hier: …“ am letzten Buchzug)."""
197238
     game = chess.pgn.read_game(io.StringIO(savegames.to_pgn(state)))
198239
     if opts.scope == "position":
199
-        board = board_at(state, _plies(state, opts))
240
+        plies = _plies(state, opts)
241
+        board = board_at(state, plies)
200242
         position = chess.pgn.Game()
201243
         for key in ("Event", "Date", "White", "Black"):
202244
             position.headers[key] = game.headers.get(key, "?")
203245
         position.headers["Result"] = "*"
246
+        _, eco, name = book_end(state, plies)
247
+        if name:
248
+            position.headers["ECO"], position.headers["Opening"] = eco or "?", name
204249
         position.setup(board)
205250
         return str(position) + "\n"
206
-    for node in game.mainline():
251
+    book_ply, eco, name = book_end(state)
252
+    if name:
253
+        game.headers["ECO"], game.headers["Opening"] = eco or "?", name
254
+    for ply, node in enumerate(game.mainline()):
207255
         if not opts.symbols:
208256
             node.nags.clear()
209257
         if not opts.evals:
210258
             node.comment = ""
259
+        if ply == book_ply:
260
+            node.comment = " ".join(filter(None, [book_comment(eco, name), node.comment]))
211261
     return str(game) + "\n"
212262
 
213263
 
264
+_NAG_GLYPH = savegames.SYMBOL_FOR_NAG  # 4 → "??"
265
+
266
+
267
+def page_pgn(state, opts):
268
+    """PGN für die HTML-Seite: Zeichen statt NAG-Nummern, ohne [%wp] und ohne Schach…-Kopfzeilen;
269
+    ohne Spielerköpfe auch ohne Namen."""
270
+    game = chess.pgn.read_game(io.StringIO(to_pgn(state, opts)))
271
+    for key in [k for k in game.headers if k.startswith("Schach")]:
272
+        del game.headers[key]
273
+    if not opts.players:
274
+        for key in ("Event", "White", "Black"):
275
+            game.headers[key] = "?"
276
+    for node in game.mainline():
277
+        node.comment = " ".join(savegames.WP_RE.sub("", node.comment or "").split())
278
+    text = str(game) + "\n"
279
+    head, _, moves = text.partition("\n\n")
280
+    moves = re.sub(r" \$(\d+)", lambda m: _NAG_GLYPH.get(int(m.group(1)), m.group(0)), moves)
281
+    return head + "\n\n" + moves
282
+
283
+
214284
 _ASCII_DE = {"K": "K", "Q": "D", "R": "T", "B": "L", "N": "S", "P": "B"}
215285
 
216286
 
@@ -242,7 +312,7 @@ def to_ascii(state, opts):
242312
     i = info(state)
243313
     if opts.players:
244314
         result = RESULT_TEXT.get(i.result, "")
245
-        lines += [f"{i.title}{'  ' + result if result else ''}", i.date, ""]
315
+        lines += [f"{i.title}{'  ' + result if result else ''}", " · ".join(filter(None, [i.date, i.opening])), ""]
246316
     lines += _ascii_board(board, opts)
247317
     lines += ["", caption(board, opts.notation), "FEN: " + board.fen()]
248318
     if opts.scope == "game" and state.board.move_stack:
@@ -295,7 +365,7 @@ def to_latex(state, opts):
295365
     ]
296366
     if opts.players:
297367
         out.append(f"\\section*{{{_tex(i.white)} -- {_tex(i.black)}}}")
298
-        meta = [m for m in (i.event, i.date) if m and m != "?"]
368
+        meta = [m for m in (i.event, i.date, i.opening) if m and m != "?"]
299369
         out.append("\\noindent " + _tex(" · ".join(meta)).replace("·", "\\textperiodcentered{}") + "\n")
300370
     root = state.board.root()
301371
     setfen = "" if root.fen() == chess.STARTING_FEN else f"[setfen={root.fen()}]"
@@ -390,8 +460,7 @@ def to_pdf(state, opts):
390460
     y = PDF_MARGIN
391461
     if opts.players:
392462
         y += text(html_mod.escape(i.title), left, y, size=18, bold=True, w=text_width)
393
-        meta = [m for m in (i.event, i.date, RESULT_TEXT.get(i.result, ""), i.end_text) if m and m != "?"]
394
-        y += text(html_mod.escape(" · ".join(meta)), left, y + 2, size=10, w=text_width) + 14
463
+        y += text(html_mod.escape(i.meta()), left, y + 2, size=10, w=text_width) + 14
395464
 
396465
     plies = _plies(state, opts)
397466
     board = board_at(state, plies)
@@ -607,6 +676,8 @@ h1 { font-size: 1.4em; margin: 0 0 2px;
607676
 .pgn .mv.sel { background: var(--accent); color: var(--accent-fg); }
608677
 .pgn .c, .pgn .h { color: var(--muted); }
609678
 .pgn .u { white-space: nowrap; }
679
+.pgn b.s { font-weight: 800; }
680
+.pgn .mv.sel b.s { color: inherit !important; }
610681
 button { font: inherit; color: inherit; background: var(--card); border: 1px solid var(--line);
611682
   border-radius: 6px; padding: 4px 10px; cursor: pointer; }
612683
 button:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
@@ -713,9 +784,15 @@ def _html_pgn(pgn_text, selected):
713784
             parts.append(f"{board.fullmove_number}.")
714785
         elif ply == 1:
715786
             parts.append(f"{board.fullmove_number}...")
716
-        san = board.san(node.move) + "".join(f" ${nag}" for nag in sorted(node.nags))
787
+        san = esc(board.san(node.move))
788
+        for nag in sorted(node.nags):
789
+            glyph = _NAG_GLYPH.get(nag)
790
+            if glyph:
791
+                san += f'<b class="s" style="color:{hex_color(BADGE[glyph])}">{esc(glyph)}</b>'
792
+            else:
793
+                san += f" ${nag}"
717794
         sel = " sel" if ply == selected else ""
718
-        parts.append(f'<span class="mv{sel}" data-ply="{ply}">{esc(san)}</span>')
795
+        parts.append(f'<span class="mv{sel}" data-ply="{ply}">{san}</span>')
719796
         comment = f'<span class="c">{{ {esc(node.comment)} }}</span>' if node.comment else ""
720797
         if comment and len(node.comment) <= PGN_COMMENT_INLINE:
721798
             parts.append(comment)
@@ -746,23 +823,14 @@ def to_html(state, opts):
746823
         b = board_at(state, p)
747824
         entries.append({"p": p, "fen": b.fen(), "caption": caption(b, opts.notation),
748825
                         "wp": _eval(state, p, opts)})
749
-    # PGN für die Seite: ohne die programminternen Schach…-Kopfzeilen,
750
-    # ohne Spielerköpfe auch ohne Namen
751
-    pgn_game = chess.pgn.read_game(io.StringIO(to_pgn(state, opts)))
752
-    for key in [k for k in pgn_game.headers if k.startswith("Schach")]:
753
-        del pgn_game.headers[key]
754
-    if not opts.players:
755
-        for key in ("Event", "White", "Black"):
756
-            pgn_game.headers[key] = "?"
757
-    pgn_text = str(pgn_game) + "\n"
826
+    pgn_text = page_pgn(state, opts)
758827
     data = {"plies": entries, "start": plies_list.index(plies), "flipped": opts.flipped, "pgn": pgn_text}
759828
     data_json = json.dumps(data, ensure_ascii=False).replace("</", "<\\/")
760829
 
761830
     title = i.title if opts.players else "Schachstellung" if not game else "Schachpartie"
762831
     head = ""
763832
     if opts.players:
764
-        meta = [m for m in (i.event, i.date, RESULT_TEXT.get(i.result, ""), i.end_text) if m and m != "?"]
765
-        head = f'<header><h1>{esc(i.title)}</h1><p class="meta">{esc(" · ".join(meta))}</p></header>'
833
+        head = f'<header><h1>{esc(i.title)}</h1><p class="meta">{esc(i.meta())}</p></header>'
766834
 
767835
     bar = ""
768836
     wp = _eval(state, plies, opts)

modified schach/opening.py +10 −3

@@ -142,20 +142,27 @@ class Names:
142142
                 self._conn = None
143143
 
144144
     def exact(self, board):
145
+        found = self.exact_eco(board)
146
+        return found[1] if found else None
147
+
148
+    def exact_eco(self, board):
149
+        """(ECO-Code, Name) für genau diese Stellung oder None."""
145150
         if self._conn is None:
146151
             return None
147152
         h = f"{key(board):016x}"
148153
         rows = self._conn.execute(
149
-            "select lang, endline, opening, variation from openings where hash=? and hkey=?",
154
+            "select lang, endline, opening, variation, eco from openings where hash=? and hkey=?",
150155
             (h, int(h[-2:], 16)),
151156
         ).fetchall()
152157
         # Nur Einträge, die genau diese Stellung benennen (endline=1); die anderen gehören zu
153158
         # Linien, die hier nur durchlaufen, und tragen deren Namen.
154159
         for lang, endline in (("de", 1), ("en", 1)):
155
-            for row_lang, row_end, opening, variation in rows:
160
+            for row_lang, row_end, opening, variation, eco in rows:
156161
                 if row_lang == lang and row_end == endline:
157162
                     name = _clean(opening, variation)
158
-                    return _german(name) if name and lang == "en" else name
163
+                    if not name:
164
+                        return None
165
+                    return (eco or "").strip(), _german(name) if lang == "en" else name
159166
         return None
160167
 
161168
     def name(self, board):

modified tests/test_export.py +45 −8

@@ -1,4 +1,5 @@
11
 import io
2
+from html import escape as html_escape
23
 import re
34
 import shutil
45
 import subprocess
@@ -142,18 +143,24 @@ class ImageAndPageTest(unittest.TestCase
142143
         # PGN mit Zügen als Spans, der gezeigte (8. Halbzug) ist markiert
143144
         self.assertIn('<span class="mv sel" data-ply="8">Qg5</span>', page)
144145
         self.assertEqual(len(re.findall(r'<span class="mv', page)), len(MOVES))
145
-        self.assertIn('data-ply="7">Nxe5 $4</span>', page)
146
+        # Zugzeichen farbig statt NAG-Nummer, auch im kopierbaren PGN
147
+        self.assertRegex(page, r'data-ply="7">Nxe5<b class="s" style="color:#[0-9a-f]{6}">\?\?</b></span>')
146148
         self.assertIn('"pgn": "[Event', page)
149
+        self.assertIn("Nxe5??", page)
150
+        self.assertNotIn("$4", page)
147151
         self.assertNotIn("SchachHuman", page)
148
-        # Nummer, Zug, Kommentar und Ergebnis bleiben zusammen
149
-        self.assertIn('<span class="u">1. <span class="mv" data-ply="1">e4</span> <span class="c">{ [%wp 50.0] }</span></span>', page)
150
-        self.assertRegex(page, r'data-ply="14">Nf3# \$3</span> <span class="c">\{ \[%wp 63\.0\] \}</span> 0-1</span>')
152
+        # Gewinnchance nur als Balken, nicht im PGN der Seite
153
+        self.assertNotIn("[%wp", page)
154
+        # Nummer, Zug und Ergebnis bleiben zusammen
155
+        self.assertIn('<span class="u">1. <span class="mv" data-ply="1">e4</span></span>', page)
156
+        # (Die Testpartie ist die Falle des Blackburne-Shilling-Gambits: eco.db kennt sie bis zum Matt,
157
+        # der lange Kommentar „Bis hier: …“ steht daher als eigener Teil vor dem Ergebnis.)
158
+        self.assertRegex(page, r'data-ply="14">Nf3#<b[^>]*>!!</b></span></span> <span class="c">\{ Bis hier: C50 [^<]*\}</span> <span class="u">0-1</span>')
151159
 
152160
     def test_html_pgn_long_comment_may_wrap(self):
153
-        state = sample()
154
-        text = export.export("pgn", state, opts(scope="game"))
155
-        text = text.replace("{ [%wp 63.0] }", "{ " + "sehr langer Kommentar " * 5 + "}")
156
-        html = export._html_pgn(text, None)
161
+        game = chess.pgn.read_game(io.StringIO(export.export("pgn", sample(), opts(scope="game"))))
162
+        game.end().comment = "sehr langer Kommentar " * 5
163
+        html = export._html_pgn(str(game), None)
157164
         self.assertRegex(html, r'</span> <span class="c">\{ sehr langer')  # nicht in der Einheit
158165
         self.assertTrue(html.endswith('<span class="u">0-1</span>'))
159166
 
@@ -170,6 +177,36 @@ class ImageAndPageTest(unittest.TestCase
170177
         self.assertEqual(page.count("</script>"), 2)
171178
 
172179
 
180
+class OpeningTest(unittest.TestCase):
181
+    def setUp(self):
182
+        if export._names()._conn is None:
183
+            self.skipTest("eco.db von PyChess fehlt")
184
+
185
+    def test_game_pgn_names_opening_and_marks_book_end(self):
186
+        text = export.export("pgn", sample(), opts(scope="game"))
187
+        game = chess.pgn.read_game(io.StringIO(text))
188
+        self.assertRegex(game.headers["ECO"], r"^[A-E]\d\d$")
189
+        self.assertTrue(game.headers["Opening"])
190
+        ply, eco, name = export.book_end(sample())
191
+        self.assertIsNotNone(ply)
192
+        node = list(game.mainline())[ply]
193
+        self.assertTrue(node.comment.startswith(f"Bis hier: {eco} {name}"))
194
+        self.assertIn("[%wp", node.comment)  # Bewertung bleibt in der Datei erhalten
195
+        # Wieder einlesen: Balkenwert kommt trotz Eröffnungskommentar zurück
196
+        self.assertEqual(savegames.from_pgn(text).evals[ply], sample().evals[ply])
197
+
198
+    def test_position_at_start_has_no_opening(self):
199
+        text = export.export("pgn", sample(), opts(plies=0))
200
+        self.assertNotIn("[ECO", text)
201
+        self.assertIn("[Opening", export.export("pgn", sample(), opts(plies=5)))
202
+
203
+    def test_html_meta_shows_opening(self):
204
+        page = export.export("html", sample(), opts(scope="game"))
205
+        _, eco, name = export.book_end(sample())
206
+        self.assertIn(html_escape(f"{eco} {name}"), page)
207
+        self.assertIn("Bis hier:", page)
208
+
209
+
173210
 class MetaTest(unittest.TestCase):
174211
     def test_filename(self):
175212
         self.assertRegex(export.filename("pdf", sample(), opts(scope="game")), r"^partie-\d{4}-\d\d-\d\d\.pdf$")