# SPDX-License-Identifier: AGPL-3.0-or-later """The Rook's bridge to the tagger of Lichess's puzzles (ornicar/lichess-puzzler, tagger/cook.py, AGPL-3.0). It names the tactic in a line of moves: fork, pin, skewer, discovered attack, deflection, and so on. The tagger is used as it is, from its own folder (engine/lichess-puzzler/tagger); nothing of it is copied into The Rook. This file imports it, so this file is under the same licence. It runs as its own process and talks in lines of JSON. In: {"id": 1, "fen": "", "moves": ["", "", "", ...] (UCI), "cp": } Out: {"id": 1, "tags": ["fork", "short", ...]} or {"id": 1, "error": "..."} That is the shape of a Lichess puzzle: the position before the opponent's slip, the slip, then the solver's moves and the answers to them, ending on a move of the solver. """ import json import logging import os import sys sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "lichess-puzzler", "tagger")) import chess # noqa: E402 from chess.pgn import Game # noqa: E402 import cook # noqa: E402 from model import Puzzle # noqa: E402 cook.logger.setLevel(logging.ERROR) def tags_of(fen, moves, cp): board = chess.Board(fen) node = Game.from_board(board) for uci in moves: move = chess.Move.from_uci(uci) if move not in board.legal_moves: raise ValueError(f"{uci} cannot be played") board.push(move) node = node.add_main_variation(move) return cook.cook(Puzzle("rook", node.game(), int(cp))) def main(): print(json.dumps({"ready": True}), flush=True) for line in sys.stdin: line = line.strip() if not line: continue ask = None try: ask = json.loads(line) out = {"id": ask.get("id"), "tags": tags_of(ask["fen"], ask["moves"], ask.get("cp", 0))} except Exception as error: # one bad line must not stop the process out = {"id": ask.get("id") if isinstance(ask, dict) else None, "error": str(error) or type(error).__name__} print(json.dumps(out), flush=True) if __name__ == "__main__": main()