WeaveBench / tasks /GAM /GAM_task_10_gnuchess_pgn_blunder_hunt.md
wanlilll's picture
Add 114 tasks under 8-domain flat layout
71e9dba verified
|
Raw History Blame Contribute Delete
17.8 kB
metadata
id: GAM_task_10_gnuchess_pgn_blunder_hunt
name: gnuchess + xboard 录谱审计:识别非法走子与盲棋失误
category: GAM
timeout_seconds: 5400

Prompt

Task background: /tmp_workspace/exec/broken.pgn is a hand-transcribed PGN of a club rapid game. A member reports that the scoresheet may contain SAN moves that cannot be legally played, that the evaluation may swing sharply around one of the moves, and that the [Result "..."] tag may disagree with the final position. The goal is to audit the original PGN, locate illegal moves and suspected blunders, produce a fully replayable corrected version, and provide image evidence that backs up the key states.

Write the following deliverables under /tmp_workspace/results/, preserving the field and file names:

  • before/broken.pgn: an unmodified copy of the original /tmp_workspace/exec/broken.pgn.
  • illegal_moves.json: a JSON list; each illegal-move record contains ply (half-move index), side (w or b), san (original SAN text), and error (why it cannot be legally applied).
  • evals.csv: a CSV with at least 30 rows, with columns ply,side,san,score_cp,best_san,fen; score_cp is the centipawn evaluation from White's perspective, best_san is the engine's suggested move for that position, and fen is the corresponding position.
  • blunders.json: a JSON list of length 1 to 4; each record contains ply,side,san,best_san,cp_before,cp_after,swing, where swing is the centipawn loss caused by that move and must be at least 180.
  • view_xboard_initial.png: image evidence showing the 8×8 board after the original score is loaded, with chess/XBoard-related menu items or status text visible (such as xboard, white, black, move, game, file).
  • view_xboard_blunder.png: image evidence showing the board at the ply corresponding to the first record in blunders.json; the image must not be a black screen or unrelated background, and the pieces should clearly be in that middlegame state.
  • result_check.json: a JSON object with fields declared (the result declared in the original PGN), engine_suggests (the result inferred from the final evaluation, one of 1-0, 0-1, or 1/2-1/2), and match (a boolean for whether the two agree).
  • fixed.pgn: the corrected PGN; it must be fully replayable, illegal SAN must be replaced with legal moves, [Result "..."] must be one of 1-0, 0-1, or 1/2-1/2, and the scope of edits should stay minimal.
  • view_xboard_fixed_final.png: image evidence showing the final-position board for fixed.pgn, with result text consistent with the Result tag visible, e.g. 1-0, 0-1, 1/2-1/2, wins, or draw.
  • evals_after.csv: a CSV with at least 3 rows containing a re-check of the closing segment of the corrected version; at minimum it must include the columns ply,san,score_cp.
  • diff.txt: the textual diff between the original scoresheet and fixed.pgn, with line count between 4 and 80.
  • report.json: a JSON object containing at least illegal_moves, blunders, result_tag_before, result_tag_after, engine_used, engine_version, fixed_pgn, evals_csv, screenshots; screenshots lists view_xboard_initial.png, view_xboard_blunder.png, and view_xboard_fixed_final.png.

Expected Behavior

成功时,/tmp_workspace/results/ 包含一份非法走子报告,逐项列出无法合法应用的 ply/side/san/error;一张覆盖至少 30 个合法局面的 evals.csv,列齐 ply,side,san,score_cp,best_san,fen;以及 1 到 4 条 blunder 记录,每条都有 ply,side,san,best_san,cp_before,cp_after,swing 且厘兵损失幅度达到阈值。

修正结果应包括可完整重放的 fixed.pgn、末段复核表 evals_after.csv、 精简的 diff.txt、声明结果与评估归纳结果对照的 result_check.json,以及键齐全的 report.json。三张图像证据分别应显示原始棋谱的棋盘与识别文字、首个 blunder 对应的中局局面、修正版末态棋盘及可见的胜负或和棋结果文本。

Source

Grading Criteria

    1. illegal_moves.json 存在,是 list,且每条含 ply/side/san/error
    1. evals.csv 存在且 ≥ 30 行(schema: ply,side,san,score_cp,best_san,fen)
    1. blunders.json 存在,长度在 [1, 4],每条 swing ≥ 180
    1. view_xboard_initial.png 存在且 OCR 命中 xboard 关键词
    1. view_xboard_blunder.png 存在且像 xboard 棋盘截图(非黑屏 / 非桌面)
    1. view_xboard_fixed_final.png 存在且 OCR 命中 "1-0"/"0-1"/"1/2-1/2"/"wins"/"draw" 之一
    1. result_check.json 存在且字段齐全
    1. fixed.pgn 能被 python-chess read_game(...).end() 完整重放 不抛异常,且 Result 标签 ∈ {1-0, 0-1, 1/2-1/2}
    1. evals_after.csv 存在 ≥ 3 行
    1. diff.txt 存在,行数在 [4, 80]
    1. report.json 存在且 required keys 齐
    1. VLM rubric 4 项 ≥ 0.6

Automated Checks

def grade(workspace_path=None, **kwargs) -> dict:
    """gnuchess + xboard PGN audit grader.

    12 sub-scores + 4 hard gates.  Real signal channels:
      - Engine: gnuchess UCI eval + python-chess SAN legality.
      - GUI   : 3 xboard screenshots OCR for board / blunder / result text.
      - File  : evals.csv schema + diff.txt size + result tag invariant.
    No GT leakage: gt/expected.json holds only invariant counts /
    OCR keyword set / diff line bounds / required JSON keys.
    """
    import csv, json, os, re, subprocess
    from pathlib import Path

    ws  = Path(workspace_path) if workspace_path else Path("/tmp_workspace")
    rd  = ws / "results"
    gtd = ws / "gt"
    expected = {}
    if (gtd/"expected.json").exists():
        try:    expected = json.loads((gtd/"expected.json").read_text())
        except Exception: expected = {}
    s = {}

    # ---- 1. illegal_moves.json schema ----
    im = rd/"illegal_moves.json"
    illegal_ok = 0.0
    illegal_count = 0
    if im.exists():
        try:
            d = json.loads(im.read_text())
            if isinstance(d, list):
                illegal_count = len(d)
                gt_illegal = set(tuple(x) for x in expected.get("illegal_truth", []))
                got = {(int(x["ply"]), x["san"]) for x in d if isinstance(x, dict) and "ply" in x and "san" in x}
                keys_ok = bool(d) and all({"ply","side","san","error"}.issubset(x.keys()) for x in d)
                if gt_illegal:
                    if keys_ok and got == gt_illegal and len(d) == len(gt_illegal):
                        illegal_ok = 1.0
                    elif keys_ok:
                        illegal_ok = 0.4
                    elif not d:
                        illegal_ok = 0.0
                else:
                    if keys_ok:
                        illegal_ok = 1.0
                    elif not d:
                        illegal_ok = 0.3  # empty list = scanned but found none
        except Exception: pass
    s["illegal_moves_schema"] = illegal_ok

    # ---- 2. evals.csv length + schema ----
    ec = rd/"evals.csv"
    evals_rows = []
    evals_score = 0.0
    if ec.exists():
        try:
            evals_rows = list(csv.DictReader(ec.open()))
            need = {"ply","side","san","score_cp","best_san","fen"}
            if evals_rows and need.issubset(evals_rows[0].keys()):
                import chess, random
                n = len(evals_rows)
                target = expected.get("min_evals_rows", 40)
                size_ok = min(1.0, n/target)
                sample = random.Random(0).sample(evals_rows, min(5, n)) if n else []
                def _fen_valid(r):
                    try: return chess.Board(r["fen"]).is_valid()
                    except Exception: return False
                fen_ok = (sum(1 for r in sample if _fen_valid(r)) / len(sample)) if sample else 0.0
                evals_score = round(0.5*size_ok + 0.5*fen_ok, 3)
        except Exception: pass
    s["evals_csv_len_schema"] = evals_score

    # ---- 3. blunders.json detected with cp swing ----
    bj = rd/"blunders.json"
    blunders_ok = 0.0
    blunder_count = 0
    if bj.exists():
        try:
            b = json.loads(bj.read_text())
            if isinstance(b, list):
                blunder_count = len(b)
                lo = expected.get("min_blunders", 1)
                hi = expected.get("max_blunders", 4)
                swing_min = expected.get("blunder_min_cp_swing", 180)
                def _b_ok(x):
                    try:
                        cb, ca, sw = int(x["cp_before"]), int(x["cp_after"]), int(x["swing"])
                        return (abs(sw) >= swing_min
                                and abs((ca - cb) - sw) <= 25
                                and 1 <= int(x["ply"]) <= 60
                                and isinstance(x.get("best_san"), str)
                                and len(x["best_san"]) >= 2)
                    except Exception:
                        return False
                req = {"ply","side","san","best_san","cp_before","cp_after","swing"}
                if lo <= blunder_count <= hi and all(req.issubset(x.keys()) and _b_ok(x) for x in b):
                    blunders_ok = 1.0
                elif blunder_count >= 1:
                    blunders_ok = 0.5
        except Exception: pass
    s["blunders_detected"] = blunders_ok

    # ---- 4-6. xboard screenshots ----
    shots = ["view_xboard_initial.png",
             "view_xboard_blunder.png",
             "view_xboard_fixed_final.png"]
    present = sum(1 for n in shots if (rd/n).exists())
    s["xboard_shots_present"] = present / 3.0

    ocr_kw = expected.get("ocr_keywords_xboard",
        ["xboard","white","black","move","game","file"])
    finish_kw = ["1-0","0-1","1/2-1/2","wins","draw","mates","stalemate"]
    try:
        import pytesseract
        from PIL import Image
        def _ocr(p):
            try:    return pytesseract.image_to_string(Image.open(p)).lower()
            except Exception: return ""
        # initial: any xboard menu word
        t = _ocr(rd/"view_xboard_initial.png") if (rd/"view_xboard_initial.png").exists() else ""
        s["xboard_initial_ocr"] = 1.0 if any(k in t for k in ocr_kw) else 0.0
        # blunder shot: must look like a chess board image (heuristic: variance + OCR)
        from PIL import Image as PI
        def _looks_like_board(p):
            try:
                im = PI.open(p).convert("L")
                import numpy as np
                a = np.array(im); h,w = a.shape
                if h<360 or w<360: return False
                hist,_ = np.histogram(a, bins=8, range=(0,256))
                top2 = sorted(hist, reverse=True)[:2]
                return float(a.std()) > 45 and (sum(top2) / a.size) > 0.55
            except Exception: return False
        s["xboard_blunder_shot_real"] = 1.0 if _looks_like_board(rd/"view_xboard_blunder.png") else 0.0
        # final: result text overlay
        t2 = _ocr(rd/"view_xboard_fixed_final.png") if (rd/"view_xboard_fixed_final.png").exists() else ""
        s["xboard_final_result_ocr"] = 1.0 if any(k in t2 for k in finish_kw) else 0.0
    except ImportError:
        # OCR libs missing — give half credit so the test isn't a total zero
        s["xboard_initial_ocr"]      = 0.5 if (rd/"view_xboard_initial.png").exists() else 0.0
        s["xboard_blunder_shot_real"]= 0.5 if (rd/"view_xboard_blunder.png").exists() else 0.0
        s["xboard_final_result_ocr"] = 0.5 if (rd/"view_xboard_fixed_final.png").exists() else 0.0

    # ---- 7. result_check.json ----
    rcj = rd/"result_check.json"
    rc_ok = 0.0
    if rcj.exists():
        try:
            r = json.loads(rcj.read_text())
            choices = expected.get("result_tag_choices",["1-0","0-1","1/2-1/2"])
            if all(k in r for k in ["declared","engine_suggests","match"]) and \
               r["declared"] in choices and r["engine_suggests"] in choices and \
               bool(r["match"]) == (r["declared"] == r["engine_suggests"]) and \
               r["declared"] == expected.get("declared_truth", r["declared"]):
                rc_ok = 1.0
        except Exception: pass
    s["result_check_schema"] = rc_ok

    # ---- 8. fixed.pgn re-replays cleanly ----
    fp = rd/"fixed.pgn"
    fp_ok = 0.0
    fp_result_tag = None
    fp_plies = 0
    if fp.exists():
        try:
            import chess.pgn, io
            game = chess.pgn.read_game(io.StringIO(fp.read_text()))
            if game is not None:
                board = game.board()
                ok = True
                for mv in game.mainline_moves():
                    if mv not in board.legal_moves:
                        ok = False; break
                    board.push(mv); fp_plies += 1
                fp_result_tag = game.headers.get("Result","")
                if ok and fp_plies >= expected.get("fixed_pgn_min_plies",30) \
                   and fp_result_tag in expected.get("result_tag_choices",["1-0","0-1","1/2-1/2"]) \
                   and all(t in game.headers for t in expected.get("fixed_pgn_required_tags",[])):
                    fp_ok = 1.0
                elif ok:
                    fp_ok = 0.5
        except Exception: pass
    s["fixed_pgn_replays"] = fp_ok

    # ---- 9. evals_after.csv ----
    eca = rd/"evals_after.csv"
    eca_ok = 0.0
    if eca.exists():
        try:
            rows = list(csv.DictReader(eca.open()))
            if len(rows) >= 3 and {"ply","san","score_cp"}.issubset(rows[0].keys()):
                eca_ok = 1.0
        except Exception: pass
    s["evals_after_ok"] = eca_ok

    # ---- 10. diff.txt size band ----
    df = rd/"diff.txt"
    dlines = 0
    if df.exists():
        try: dlines = sum(1 for _ in df.open())
        except Exception: dlines = 0
    lo = expected.get("diff_min_lines", 4)
    hi = expected.get("diff_max_lines", 80)
    s["diff_in_range"] = 1.0 if lo <= dlines <= hi else 0.0

    # ---- 11. report.json required keys ----
    rj = rd/"report.json"
    rep_ok = 0.0
    if rj.exists():
        try:
            r = json.loads(rj.read_text())
            need = expected.get("report_required_keys", [
                "illegal_moves","blunders","result_tag_before",
                "result_tag_after","engine_used","fixed_pgn","evals_csv"])
            eng = str(r.get("engine_used","")).lower()
            ver = str(r.get("engine_version",""))
            keys_ok = all(k in r for k in need)
            engine_ok = ("gnuchess" in eng) and bool(re.search(r"\d", ver))
            rep_ok = 1.0 if (keys_ok and engine_ok) else (0.4 if keys_ok else 0.0)
        except Exception: pass
    s["report_keys_ok"] = rep_ok

    # ---- 12. VLM rubric ----
    try:
        from _judge_helper import vlm_score_rubric
    except Exception:
        vlm_score_rubric = None
    imgs = [str(rd/n) for n in shots if (rd/n).exists()]
    if vlm_score_rubric and imgs:
        rubric = {
            "vlm_xboard_real":   "图像确实是 GNU XBoard 棋盘 GUI(含 8x8 棋盘 + 菜单栏),不是黑屏 / 桌面 / 终端",
            "vlm_blunder_pos":   "blunder 截屏里盘面与第 N 步局面一致(棋子在合理位置而非起始局面)",
            "vlm_finish_text":   "fixed_final 截屏里能看到 1-0 / 0-1 / 1/2-1/2 / wins / draw 的结果文本",
            "vlm_no_cheat":      "全程是真用 xboard 加载 PGN 的截屏,不是 PowerPoint 假图或棋盘网图",
        }
        vlm = vlm_score_rubric(imgs[:3], rubric,
            instruction="评估 xboard 三张棋盘截屏的真实性、局面对应与结果文本可见性")
        for k in rubric: s[k] = vlm.get(k, 0.0)
        s["judge_method"] = vlm.get("judge_method","failed")
    else:
        for k in ["vlm_xboard_real","vlm_blunder_pos","vlm_finish_text","vlm_no_cheat"]:
            s[k] = 0.5

    # ---- aggregate + hard gates ----
    nums = [v for v in s.values() if isinstance(v,(int,float))]
    base = sum(nums)/len(nums) if nums else 0.0
    cli_evidence = (rd/"evals.csv").exists() and (rd/"blunders.json").exists() \
                   and (rd/"diff.txt").exists()
    gui_screenshot = any((rd/n).exists() for n in shots)
    vlm_avg = sum(s.get(k,0.0) for k in
        ["vlm_xboard_real","vlm_blunder_pos","vlm_finish_text","vlm_no_cheat"]) / 4.0
    if not cli_evidence:    base = min(base, 0.4)
    # GUI hard cap dropped: missing screenshot already penalised via xboard_shots_present.
    if vlm_score_rubric is not None and vlm_avg < 0.6:
        base = min(base, 0.6)
    if s.get("fixed_pgn_replays",0) < 1.0: base = min(base, 0.55)
    s["overall_score"] = round(base, 3)
    return s

Workspace Path

workspace/GAM/task_10_gnuchess_pgn_blunder_hunt

Skills


Env


Warmup

mkdir -p /tmp_workspace/results /tmp_workspace/state /tmp_workspace/exec
which tesseract || (apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=10 install -y -qq imagemagick tesseract-ocr python3-pip) || true
pip install -q chess pillow numpy pytesseract 2>/dev/null || pip3 install -q --break-system-packages chess pillow numpy pytesseract 2>/dev/null || true
command -v stockfish >/dev/null 2>&1 || true