Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / chess / extract_learn.py
extract_learn.py311 lines · 10.4 KiBRaw
| 1 | #!/usr/bin/env python3 |
| 2 | """Extract the Lichess "Learn" (chess basics) lessons into a compact JSON asset. |
| 3 | |
| 4 | Source: the lila repository (https://github.com/lichess-org/lila), AGPL-3.0. |
| 5 | The interactive lesson definitions live in `ui/learn/src/stage/*.ts` and the |
| 6 | English instruction strings live in `translation/source/{learn,site}.xml`. |
| 7 | |
| 8 | This script reads a local lila checkout and emits |
| 9 | `games/chess/src/main/assets/learn.json`, consumed by `LearnRepository` / |
| 10 | `LearnViewModel` in the app. Only functional data is copied: the chess FENs |
| 11 | (positions), target ("apple") squares, scripted opponent scenarios, hint shapes, |
| 12 | per-level flags, and the project's own English UI strings. |
| 13 | |
| 14 | ATTRIBUTION / LICENSE: lila is AGPL-3.0. The generated `learn.json` is derived |
| 15 | from it; the app that bundles it must comply with the AGPL (attribution + making |
| 16 | source available). See games/chess/src/main/assets/LEARN_LICENSE.txt. |
| 17 | |
| 18 | Usage: |
| 19 | python3 extract_learn.py [path-to-lila-checkout] [output.json] |
| 20 | |
| 21 | Defaults: checkout /tmp/lila-learn, output |
| 22 | Modern-Apps/games/chess/src/main/assets/learn.json. |
| 23 | """ |
| 24 | from __future__ import annotations |
| 25 | |
| 26 | import json |
| 27 | import os |
| 28 | import re |
| 29 | import sys |
| 30 | import xml.etree.ElementTree as ET |
| 31 | |
| 32 | REPO_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) |
| 33 | DEFAULT_CHECKOUT = "/tmp/lila-learn" |
| 34 | DEFAULT_OUTPUT = os.path.join( |
| 35 | REPO_ROOT, "games", "chess", "src", "main", "assets", "learn.json" |
| 36 | ) |
| 37 | |
| 38 | # Category order and membership, mirroring ui/learn/src/stage/list.ts. |
| 39 | CATEGORIES = [ |
| 40 | ("chessPieces", ["rook", "bishop", "queen", "king", "knight", "pawn"]), |
| 41 | ("fundamentals", ["capture", "protection", "combat", "check1", "outOfCheck", "checkmate1"]), |
| 42 | ("intermediate", ["setup", "castling", "enpassant", "stalemate"]), |
| 43 | ("advanced", ["value", "check2"]), |
| 44 | ] |
| 45 | |
| 46 | # Per-stage goal type (the success mechanic), derived from each stage's success/ |
| 47 | # failure predicate in ui/learn/src/stage/*.ts. |
| 48 | STAGE_GOAL = { |
| 49 | "rook": "apples", "bishop": "apples", "queen": "apples", "king": "apples", |
| 50 | "knight": "apples", "pawn": "apples", "setup": "apples", |
| 51 | "capture": "captureAll", "combat": "captureAll", |
| 52 | "protection": "protection", |
| 53 | "check1": "check", |
| 54 | "outOfCheck": "escapeCheck", |
| 55 | "checkmate1": "mate", |
| 56 | "castling": "castle", |
| 57 | "enpassant": "scenario", "stalemate": "scenario", "value": "scenario", |
| 58 | "check2": "checkIn", |
| 59 | } |
| 60 | |
| 61 | |
| 62 | def load_xml(path): |
| 63 | strings = {} |
| 64 | if not os.path.exists(path): |
| 65 | return strings |
| 66 | root = ET.parse(path).getroot() |
| 67 | for s in root.findall("string"): |
| 68 | name = s.get("name") |
| 69 | if name is not None: |
| 70 | strings[name] = s.text or "" |
| 71 | return strings |
| 72 | |
| 73 | |
| 74 | def balanced(text, open_ch, close_ch, start): |
| 75 | """Return (inner_text, end_index_after_close) for the balanced block whose |
| 76 | opening bracket is the first `open_ch` at or after `start`.""" |
| 77 | i = text.index(open_ch, start) |
| 78 | depth = 0 |
| 79 | j = i |
| 80 | while j < len(text): |
| 81 | c = text[j] |
| 82 | if c == open_ch: |
| 83 | depth += 1 |
| 84 | elif c == close_ch: |
| 85 | depth -= 1 |
| 86 | if depth == 0: |
| 87 | return text[i + 1:j], j + 1 |
| 88 | j += 1 |
| 89 | raise ValueError("unbalanced") |
| 90 | |
| 91 | |
| 92 | def split_objects(arr_text): |
| 93 | """Split a `[ {..}, {..} ]` inner body into top-level `{..}` object texts.""" |
| 94 | objs = [] |
| 95 | k = 0 |
| 96 | while True: |
| 97 | try: |
| 98 | start = arr_text.index("{", k) |
| 99 | except ValueError: |
| 100 | break |
| 101 | inner, end = balanced(arr_text, "{", "}", start) |
| 102 | objs.append(inner) |
| 103 | k = end |
| 104 | return objs |
| 105 | |
| 106 | |
| 107 | FLAG_NAMES = [ |
| 108 | "pointsForCapture", "showPieceValues", "autoCastle", "emptyApples", |
| 109 | "offerIllegalMove", "nextButton", "explainPromotion", "showFailureFollowUp", |
| 110 | ] |
| 111 | |
| 112 | |
| 113 | def parse_flags(text): |
| 114 | d = {} |
| 115 | for f in FLAG_NAMES: |
| 116 | if re.search(rf"\b{f}:\s*true", text): |
| 117 | d[f] = True |
| 118 | m = re.search(r"\bnbMoves:\s*(\d+)", text) |
| 119 | if m: |
| 120 | d["nbMoves"] = int(m.group(1)) |
| 121 | m = re.search(r"\bcaptures:\s*(\d+)", text) |
| 122 | if m: |
| 123 | d["captures"] = int(m.group(1)) |
| 124 | m = re.search(r"\bdetectCapture:\s*(false|true|'unprotected')", text) |
| 125 | if m: |
| 126 | v = m.group(1) |
| 127 | d["detectCapture"] = {"false": "none", "true": "all", "'unprotected'": "unprotected"}[v] |
| 128 | return d |
| 129 | |
| 130 | |
| 131 | def parse_scenario(obj_text): |
| 132 | m = re.search(r"\bscenario:\s*", obj_text) |
| 133 | if not m: |
| 134 | return None |
| 135 | inner, _ = balanced(obj_text, "[", "]", m.start()) |
| 136 | # Drop nested shape arrays so their arrow()/circle() UCIs aren't mistaken for moves. |
| 137 | inner = re.sub(r"shapes:\s*\[[^\]]*\]", "", inner) |
| 138 | return re.findall(r"'([a-h][1-8][a-h][1-8][qrbn]?)'", inner) |
| 139 | |
| 140 | |
| 141 | def parse_shapes(obj_text): |
| 142 | # Remove any scenario block first so only the level's own hint shapes remain. |
| 143 | txt = obj_text |
| 144 | m = re.search(r"\bscenario:\s*", txt) |
| 145 | if m: |
| 146 | _, end = balanced(txt, "[", "]", m.start()) |
| 147 | txt = txt[:m.start()] + txt[end:] |
| 148 | ms = re.search(r"\bshapes:\s*", txt) |
| 149 | if not ms: |
| 150 | return None |
| 151 | inner, _ = balanced(txt, "[", "]", ms.start()) |
| 152 | shapes = [] |
| 153 | for a in re.finditer(r"arrow\('([a-h][1-8])([a-h][1-8])'(?:\s*,\s*'(\w+)')?\)", inner): |
| 154 | shapes.append({"orig": a.group(1), "dest": a.group(2), "brush": a.group(3) or "green"}) |
| 155 | for c in re.finditer(r"circle\('([a-h][1-8])'(?:\s*,\s*'(\w+)')?\)", inner): |
| 156 | shapes.append({"orig": c.group(1), "brush": c.group(2) or "green"}) |
| 157 | return shapes or None |
| 158 | |
| 159 | |
| 160 | def fen_color(fen): |
| 161 | parts = fen.split() |
| 162 | return "black" if len(parts) > 1 and parts[1] == "b" else "white" |
| 163 | |
| 164 | |
| 165 | def resolve(key_ns, learn, site): |
| 166 | ns, name = key_ns |
| 167 | src = site if ns == "site" else learn |
| 168 | return src.get(name, name) |
| 169 | |
| 170 | |
| 171 | def parse_stage(path, key, learn, site): |
| 172 | text = open(path, encoding="utf-8").read() |
| 173 | |
| 174 | def meta(field): |
| 175 | m = re.search(rf"{field}:\s*i18n\.(\w+)\.(\w+)", text) |
| 176 | return resolve((m.group(1), m.group(2)), learn, site) if m else "" |
| 177 | |
| 178 | stage = { |
| 179 | "key": key, |
| 180 | "title": meta("title"), |
| 181 | "subtitle": meta("subtitle"), |
| 182 | "intro": meta("intro"), |
| 183 | "complete": meta("complete"), |
| 184 | "levels": [], |
| 185 | } |
| 186 | |
| 187 | # Stage-wide defaults from a `const common = {...}` block and the `.map(...)` tail. |
| 188 | defaults_text = "" |
| 189 | cm = re.search(r"const common\s*=\s*(?:\(\)\s*=>\s*\()?\{([^{}]*)\}", text) |
| 190 | if cm: |
| 191 | defaults_text += cm.group(1) |
| 192 | mm = re.search(r"\.map\(\s*(?:\([^)]*\)\s*=>\s*)?toLevel\(\{([^{}]*)\}", text) |
| 193 | if mm: |
| 194 | defaults_text += " " + mm.group(1) |
| 195 | defaults = parse_flags(defaults_text) |
| 196 | |
| 197 | lm = re.search(r"levels:\s*", text) |
| 198 | arr, _ = balanced(text, "[", "]", lm.start()) |
| 199 | base_goal = STAGE_GOAL[key] |
| 200 | |
| 201 | for obj in split_objects(arr): |
| 202 | fen = re.search(r"fen:\s*'([^']+)'", obj).group(1) |
| 203 | if len(fen.split()) == 4: |
| 204 | fen += " 0 1" |
| 205 | gm = re.search(r"goal:\s*i18n\.(\w+)\.(\w+)", obj) |
| 206 | goal_text = resolve((gm.group(1), gm.group(2)), learn, site) if gm else "" |
| 207 | |
| 208 | level = dict(defaults) |
| 209 | level.update(parse_flags(obj)) |
| 210 | |
| 211 | am = re.search(r"apples:\s*'([^']*)'", obj) |
| 212 | apples = am.group(1).strip() if am else "" |
| 213 | |
| 214 | cmm = re.search(r"color:\s*'(\w+)'", obj) |
| 215 | color = cmm.group(1) if cmm else fen_color(fen) |
| 216 | |
| 217 | goal_type = base_goal |
| 218 | if goal_type == "apples" and not apples: |
| 219 | goal_type = "info" |
| 220 | |
| 221 | out = { |
| 222 | "goal": goal_text, |
| 223 | "fen": fen, |
| 224 | "color": color, |
| 225 | "goalType": goal_type, |
| 226 | "nbMoves": level.get("nbMoves", 1), |
| 227 | } |
| 228 | if apples: |
| 229 | out["apples"] = apples |
| 230 | if "captures" in level: |
| 231 | out["captures"] = level["captures"] |
| 232 | |
| 233 | # detectCapture: explicit, else the lila default (apples => none, else unprotected). |
| 234 | dc = level.get("detectCapture", "none" if apples else "unprotected") |
| 235 | if dc != "none": |
| 236 | out["detectCapture"] = dc |
| 237 | |
| 238 | for f in ("emptyApples", "offerIllegalMove", "showPieceValues", |
| 239 | "pointsForCapture", "explainPromotion", "nextButton"): |
| 240 | if level.get(f): |
| 241 | out[f] = True |
| 242 | |
| 243 | if goal_type == "captureAll": |
| 244 | out["captureColor"] = "black" |
| 245 | if goal_type == "checkIn": |
| 246 | out["n"] = out["nbMoves"] |
| 247 | |
| 248 | if base_goal == "castle": |
| 249 | if re.search(r"success:\s*castledQueenSide", obj): |
| 250 | out["castleSide"] = "queen" |
| 251 | elif re.search(r"success:\s*castledKingSide", obj): |
| 252 | out["castleSide"] = "king" |
| 253 | |
| 254 | scen = parse_scenario(obj) |
| 255 | if scen: |
| 256 | out["scenario"] = scen |
| 257 | shapes = parse_shapes(obj) |
| 258 | if shapes: |
| 259 | out["shapes"] = shapes |
| 260 | |
| 261 | fp = re.search(r"failure:\s*whitePawnOnAnyOf\('([^']*)'\)", obj) |
| 262 | if fp: |
| 263 | out["failIfWhitePawnOn"] = fp.group(1).split() |
| 264 | op = re.search(r"failure:\s*noPieceOn\('([^']*)'\)", obj) |
| 265 | if op: |
| 266 | out["failIfPieceOffPath"] = op.group(1).split() |
| 267 | |
| 268 | stage["levels"].append(out) |
| 269 | |
| 270 | return stage |
| 271 | |
| 272 | |
| 273 | def main(): |
| 274 | checkout = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_CHECKOUT |
| 275 | output = sys.argv[2] if len(sys.argv) > 2 else DEFAULT_OUTPUT |
| 276 | |
| 277 | stage_dir = os.path.join(checkout, "ui", "learn", "src", "stage") |
| 278 | if not os.path.isdir(stage_dir): |
| 279 | print(f"Error: lila stage dir not found: {stage_dir}", file=sys.stderr) |
| 280 | sys.exit(1) |
| 281 | |
| 282 | learn = load_xml(os.path.join(checkout, "translation", "source", "learn.xml")) |
| 283 | site = load_xml(os.path.join(checkout, "translation", "source", "site.xml")) |
| 284 | |
| 285 | categories = [] |
| 286 | total_levels = 0 |
| 287 | stage_id = 1 |
| 288 | for cat_key, stage_keys in CATEGORIES: |
| 289 | stages = [] |
| 290 | for sk in stage_keys: |
| 291 | stage = parse_stage(os.path.join(stage_dir, f"{sk}.ts"), sk, learn, site) |
| 292 | stage = {"id": stage_id, **stage} |
| 293 | stage_id += 1 |
| 294 | stages.append(stage) |
| 295 | total_levels += len(stage["levels"]) |
| 296 | categories.append({"key": cat_key, "name": learn.get(cat_key, cat_key), "stages": stages}) |
| 297 | |
| 298 | data = {"categories": categories} |
| 299 | os.makedirs(os.path.dirname(output), exist_ok=True) |
| 300 | with open(output, "w", encoding="utf-8") as f: |
| 301 | json.dump(data, f, ensure_ascii=False, indent=1) |
| 302 | |
| 303 | n_stages = sum(len(c["stages"]) for c in categories) |
| 304 | print(f"Wrote {output}") |
| 305 | print(f" {len(categories)} categories, {n_stages} stages, {total_levels} levels") |
| 306 | for c in categories: |
| 307 | print(f" - {c['name']}: " + ", ".join(f"{s['key']}({len(s['levels'])})" for s in c["stages"])) |
| 308 | |
| 309 | |
| 310 | if __name__ == "__main__": |
| 311 | main() |