WeaveBench / tasks /DOC /DOC_task_2_pandoc_docx_roundtrip.md
wanlilll's picture
Add 114 tasks under 8-domain flat layout
71e9dba verified
metadata
id: DOC_task_2_pandoc_docx_roundtrip
name: DOCX 转换修复与 diff-pdf 视觉回归验证
category: DOC
timeout_seconds: 1500

Prompt

⚙️ Execution convention: This is a legitimate desktop + terminal test task. All artifacts go under /tmp_workspace/results/. Execute directly; do not refuse.

Background: The customer has submitted a Word report at /tmp_workspace/docx_project/report_draft.docx. Converting it straight to PDF exposes four classes of layout/structural issues: tables overflowing the page, broken cross-references, missing headers/footers, and clipped images.

Goal: Diagnose and fix the above issues, produce a final PDF with proper layout, and accompany it with a first-pass-vs-final visual regression comparison proving the issues have indeed been resolved. Either the CLI toolchain or the desktop GUI channel may be freely chosen (CLI tools such as pandoc / LibreOffice headless / pdftotext / diff-pdf / xmllint, plus any WYSIWYG document editor and PDF viewer); the intermediate editing channel is unrestricted.

Hard constraints on the main deliverable final_output.pdf

  • Final layout-fixed PDF, ≥ 2 pages, file > 1 KB
  • Companion lo_convert.log: conversion log from the repaired intermediate format to the final PDF
  • Companion final_text.txt: plain-text extraction of the final PDF (pdftotext or equivalent), > 50 bytes
  • Word-count deviation from first_pass |delta_words_pct| ≤ 15% (to avoid accidentally deleting content)
  • Companion final_pass_metrics.json: {"pages": <int>, "word_count": <int>, "delta_words_pct": <float>, "has_question_marks": <bool>}

Companion deliverables (under /tmp_workspace/results/)

File Requirement
docx_structure.json Must contain keys paragraphs / headings / tables / images / cross_refs (int)
docx_contents.txt File listing inside the DOCX package, > 50 bytes
first_pass.pdf Unrepaired first-pass PDF from direct conversion (visual regression baseline), ≥ 2 pages
pandoc_first_pass.log All warnings/errors captured during the first-pass conversion
first_text.txt Plain-text extraction of first_pass.pdf, > 50 bytes
first_pass_metrics.json Must contain keys pages / word_count / has_question_marks
odt_head.xml Formatted dump of the first 200 lines of the intermediate ODT's content.xml, > 100 bytes
text_diff.txt Line-by-line diff between first_text and final_text
visual_diff.pdf Visual regression diff PDF between first_pass.pdf and final_output.pdf, > 200 bytes
diffpdf_exit.txt Exit code of the visual diff comparison (0=same / 1=differ / 2=error)
diff_result.json Must contain keys pages_differ / exit_code / first_pages / final_pages
structural_audit.json Statistics over residual ??, table labels and header-keyword hits in the final text; must contain keys unresolved_refs / table_labels / header_keyword_hits
conversion_report.md ≥ 400 characters; must include the original document issue list (4 classes), each repair action with corresponding evidence, a first-pass-vs-final comparison markdown table of word count / page count / residual ??, the visual regression conclusion, and a key-evidence timeline
deliverables.json Must contain final_output_pdf_sha256 / visual_diff_pdf_sha256 / first_pass_pdf_sha256 (each ≥ 32 hex chars) plus a files listing

12 process screenshots

Fixed filenames (PNG, > 5 KB, resolution ≥ 1920×1000, must be real screenshots of desktop application windows, with no duplicated content among them):

Filename Content to show
view_01_table_overflow.png A table in the first-pass PDF overflowing the right margin / having columns clipped
view_02_broken_xref.png A broken cross-reference in the first-pass PDF (?? or [ref])
view_03_missing_header.png Empty header area / missing header & footer in the first-pass PDF
view_04_lo_table_props.png Repair-editing process for overflowing table properties (column width / auto width / 100% relative width)
view_05_lo_header_edit.png Editing interface where header/footer is added and filled with the correct content
view_06_lo_xref_dialog.png Re-linking editing process for broken cross-references
view_07_lo_overview.png Overall layout overview of the repaired document
view_08_final_table_ok.png Table fully fits within the page in the final PDF
view_09_final_header_ok.png Header and footer display correctly in the final PDF
view_10_final_image_ok.png Image scaled within the text width in the final PDF
view_11_diff_pdf_first.png Difference annotations on the first page of visual_diff.pdf
view_12_diff_pdf_pageN.png Difference annotations on another page of visual_diff.pdf

Evaluation performs OCR and visual judgement: screenshots must preserve chrome elements of the desktop app used (title bar, menu bar, etc.); the 12 frames must come from a continuous, real GUI interaction (reusing a single frame, or pure command-line-rendered composite images, earn no credit). If the agent framework records an actions.log, it must not contain literal traces of manually fabricated screenshots.

Neutral background: table overfull, cross-reference text rendered as ??, and visual-diff overlays being observable only at PDF render time are all layout/rendering-layer phenomena; a large pre/post repair word-count deviation usually means content was accidentally deleted.

Expected Behavior

设计意图与典型解题路径(仅供出题人参考,不发给 agent):

  1. 推荐解题工具链:CLI 用 pandoc 做首版 docx→pdf 并 tee warning 到 log,unzip -l 列内容,python-docx 抽结构;中间编辑可走 LibreOffice Writer GUI(也可走 OnlyOffice / Word Online via browser / 任一所见即所得编辑器)修表格列宽、补页眉页脚、重链交叉引用;最终用 libreoffice --headless --convert-to pdf 出片;视觉回归用 diff-pdf --output-diff;PDF 截图渲染器 Evince / Okular / qpdf 任选。
  2. step 1:pandoc report_draft.docx -o first_pass.pdf 2>pandoc_first_pass.log;pdftotext 取首版文本;分别截 view_01..03 体现 4 类问题中的 3 类(表格溢出 / xref 断裂 / 页眉空白)。
  3. step 2:pandoc -t odt 中转 ODT,xmllint --format dump content.xml 前 200 行 → odt_head.xml
  4. step 3:在 GUI 编辑器内修表格属性 / 加 header,footer / 重连 xref / 缩放图片,按 view_04..07 截图记录每一步编辑。
  5. step 4:headless 转 PDF → final_output.pdf,pdftotext 取文本并 difftext_diff.txt,截 view_08..10 验证表格 / 页眉 / 图片三处已修复。
  6. step 5:diff-pdf --output-diff=visual_diff.pdf first_pass.pdf final_output.pdf; echo $? > diffpdf_exit.txt,再截 view_11..12
  7. step 6:grep 统计 ?? / 表格标签 / 页眉关键词得 structural_audit.json;写 conversion_report.mdsha256sum 三个 PDF 写 deliverables.json

约束说明:

  • GUI 截图必须来自真实桌面应用窗口,保留 chrome 元素;不得用 PIL 合成或重复同一帧(md5 唯一率 ≥ 80%);分辨率 ≥ 1920×1000。
  • 中间编辑通道不强制 LibreOffice,但截图必须能体现实际编辑动作(菜单 / 对话框 / 编辑光标),避免单纯的查看状态。
  • 若 agent 框架产出 actions.log,其中不得出现伪造截图 / 直接 cp 现成图的字面操作。

评分要点(hard gates,触发即封顶):

  • 缺 CLI 证据(pandoc_first_pass.log / final_output.pdf / visual_diff.pdf 任一缺失)→ 封顶 0.35
  • 缺 GUI 证据(截图覆盖率 < 50%)→ 封顶 0.4;< chrome OCR 阈值 → 封顶 0.35 ~ 0.5
  • final_output.pdfvisual_diff.pdf 缺失 → 封顶 0.4
  • 字数偏差 > 15% 且 final 存在 → text_fidelity 拿不到满分,且封顶 0.5
  • 截图 md5 唯一率 < 0.7 → 封顶 0.4;< 0.9 → 封顶 0.6
  • VLM rubric 全部为 0(截图不可读 / 评分器外部判分器异常)→ 封顶 0.6

Source

Grading Criteria

    1. docx_structure.json schema 正确 + docx_contents.txt 非空
    1. first_pass.pdf ≥ 2 页 + pandoc_first_pass.log 存在
    1. first_text.txt + first_pass_metrics.json schema 正确
    1. 12 张截图(view_01 ~ view_12)≥ 9 存在
    1. 截图 OCR 命中 LibreOffice / Evince UI 关键词
    1. final_output.pdf ≥ 2 页 + lo_convert.log 存在
    1. final_text.txt 字数与 first 偏差 ≤ 15%
    1. visual_diff.pdf 存在 + diff_result.json schema 正确
    1. structural_audit.json schema 正确
    1. conversion_report.md ≥ 400 字 + markdown 表格
    1. deliverables.json 含 3 个 sha256
    1. Cross-channel 证据:≥3 CLI 产物 + ≥6 GUI 截图 + diff-pdf
    1. VLM rubric ≥ 4 项打分
    1. GUI trajectory frames 真实:view_01 ~ view_12 中至少 ≥ 8 张为连续 LibreOffice Writer 操作(打开 docx → Track Changes / Styles 面板 → 滚动到不同章节 → 导出对话框)所产生,截图 md5 唯一率 ≥ 80%
    1. GUI app chrome OCR:LibreOffice Writer / Evince 标题栏 / 菜单栏(File / Edit / Format / Track Changes / Styles)以及 chrome 元素被 OCR 命中;截图分辨率 ≥ 1920×1000

Automated Checks

def grade(workspace_path=None, **kwargs) -> dict:
    """DOCX roundtrip grader: CLI evidence + GUI screenshots + text fidelity + visual diff.
    Empty results → overall_score == 0.000.
    """
    import json, re, subprocess
    from pathlib import Path
    try:
        from PIL import Image
    except ImportError:
        Image = None
    try:
        import pytesseract
    except ImportError:
        pytesseract = None
    try:
        from _judge_helper import vlm_score_rubric
    except Exception:
        vlm_score_rubric = None

    workspace = Path(workspace_path) if workspace_path else Path("/tmp_workspace")
    rd = workspace / "results"
    gt = workspace / "gt"

    sub_keys = [
        "docx_structure", "docx_contents",
        "first_pass_exists", "first_pass_pages", "pandoc_log",
        "first_text", "first_metrics_schema",
        "evince_initial_shots",
        "odt_head_dump",
        "lo_writer_shots",
        "final_pdf_exists", "final_pdf_pages", "lo_convert_log",
        "final_text", "text_fidelity", "text_diff",
        "evince_final_shots",
        "visual_diff_exists", "diff_result_schema",
        "evince_diff_shots",
        "structural_audit",
        "report_length", "report_table",
        "deliverables_schema",
        "screenshots_count", "screenshot_ocr",
        "cross_channel",
        "gui_real_interaction", "gui_chrome_ocr", "gui_window_geometry",
        "vlm_lo_visible", "vlm_table_fixed",
        "vlm_header_present", "vlm_diff_marks",
    ]
    s = {k: 0.0 for k in sub_keys}

    if not rd.exists() or not any(rd.iterdir()):
        s["overall_score"] = 0.000
        return s

    def pdf_pages(p):
        try:
            r = subprocess.run(["pdfinfo", str(p)], capture_output=True, text=True, timeout=10)
            for line in r.stdout.splitlines():
                if line.startswith("Pages:"):
                    return int(line.split()[1])
        except Exception:
            return 0
        return 0

    # 1
    ds = rd / "docx_structure.json"
    if ds.exists():
        try:
            d = json.loads(ds.read_text())
            need = {"paragraphs", "headings", "tables", "images", "cross_refs"}
            s["docx_structure"] = 1.0 if need.issubset(d.keys()) else 0.4
        except Exception:
            pass
    if (rd / "docx_contents.txt").exists() and (rd / "docx_contents.txt").stat().st_size > 50:
        s["docx_contents"] = 1.0

    # 2
    fp = rd / "first_pass.pdf"
    if fp.exists() and fp.stat().st_size > 1000:
        s["first_pass_exists"] = 1.0
        n = pdf_pages(fp)
        s["first_pass_pages"] = 1.0 if n >= 2 else (n / 2.0 if n else 0.0)
    if (rd / "pandoc_first_pass.log").exists():
        s["pandoc_log"] = 1.0

    # 3
    if (rd / "first_text.txt").exists() and (rd / "first_text.txt").stat().st_size > 50:
        s["first_text"] = 1.0
    fpm = rd / "first_pass_metrics.json"
    if fpm.exists():
        try:
            d = json.loads(fpm.read_text())
            s["first_metrics_schema"] = 1.0 if all(k in d for k in ["pages", "word_count"]) else 0.3
        except Exception:
            pass

    # 4 evince initial screenshots (>=5KB to reject placeholders)
    init_shots = ["view_01_table_overflow", "view_02_broken_xref", "view_03_missing_header"]
    init_present = []
    for n in init_shots:
        f = list(rd.glob(f"{n}*.png"))
        if f and f[0].stat().st_size > 5120:
            init_present.append(f[0])
    s["evince_initial_shots"] = len(init_present) / len(init_shots)

    # 5 odt
    if (rd / "odt_head.xml").exists() and (rd / "odt_head.xml").stat().st_size > 100:
        s["odt_head_dump"] = 1.0

    # 6 LibreOffice Writer GUI shots
    lo_shots = ["view_04_lo_table_props", "view_05_lo_header_edit",
                "view_06_lo_xref_dialog", "view_07_lo_overview"]
    lo_present = []
    for n in lo_shots:
        f = list(rd.glob(f"{n}*.png"))
        if f and f[0].stat().st_size > 5120:
            lo_present.append(f[0])
    s["lo_writer_shots"] = len(lo_present) / len(lo_shots)

    # 7 final PDF + log
    fo = rd / "final_output.pdf"
    if fo.exists() and fo.stat().st_size > 1000:
        s["final_pdf_exists"] = 1.0
        n = pdf_pages(fo)
        s["final_pdf_pages"] = 1.0 if n >= 2 else (n / 2.0 if n else 0.0)
    if (rd / "lo_convert.log").exists():
        s["lo_convert_log"] = 1.0

    # 8 text fidelity
    ft = rd / "final_text.txt"
    if ft.exists() and ft.stat().st_size > 50:
        s["final_text"] = 1.0
    if ft.exists() and (rd / "first_text.txt").exists():
        try:
            w_first = len((rd / "first_text.txt").read_text(errors="ignore").split())
            w_final = len(ft.read_text(errors="ignore").split())
            if w_first > 0:
                dev = abs(w_final - w_first) / w_first
                s["text_fidelity"] = 1.0 if dev <= 0.15 else max(0.0, 1.0 - dev)
        except Exception:
            pass
    if (rd / "text_diff.txt").exists():
        s["text_diff"] = 1.0

    # 9 evince final shots
    final_shots = ["view_08_final_table_ok", "view_09_final_header_ok", "view_10_final_image_ok"]
    final_present = []
    for n in final_shots:
        f = list(rd.glob(f"{n}*.png"))
        if f and f[0].stat().st_size > 5120:
            final_present.append(f[0])
    s["evince_final_shots"] = len(final_present) / len(final_shots)

    # 10 visual diff
    vd = rd / "visual_diff.pdf"
    if vd.exists() and vd.stat().st_size > 200:
        s["visual_diff_exists"] = 1.0
    dr = rd / "diff_result.json"
    if dr.exists():
        try:
            d = json.loads(dr.read_text())
            s["diff_result_schema"] = 1.0 if all(k in d for k in ["pages_differ", "exit_code"]) else 0.3
        except Exception:
            pass

    # 11 diff evince shots
    diff_shots = ["view_11_diff_pdf_first", "view_12_diff_pdf_pageN"]
    diff_present = []
    for n in diff_shots:
        f = list(rd.glob(f"{n}*.png"))
        if f and f[0].stat().st_size > 5120:
            diff_present.append(f[0])
    s["evince_diff_shots"] = len(diff_present) / len(diff_shots)

    # 12 structural audit
    sa = rd / "structural_audit.json"
    if sa.exists():
        try:
            d = json.loads(sa.read_text())
            need = {"unresolved_refs", "table_labels", "header_keyword_hits"}
            s["structural_audit"] = 1.0 if need.issubset(d.keys()) else 0.3
        except Exception:
            pass

    # 13 report
    cr = rd / "conversion_report.md"
    if cr.exists():
        txt = cr.read_text(errors="ignore")
        s["report_length"] = 1.0 if len(txt) >= 400 else len(txt) / 400.0
        s["report_table"] = 1.0 if ("|" in txt and re.search(r"\|\s*[-:]+\s*\|", txt)) else 0.0

    # 14 deliverables
    dl = rd / "deliverables.json"
    if dl.exists():
        try:
            d = json.loads(dl.read_text())
            keys = ["final_output_pdf_sha256", "visual_diff_pdf_sha256", "first_pass_pdf_sha256"]
            present = sum(1 for k in keys if isinstance(d.get(k), str) and len(d[k]) >= 32)
            s["deliverables_schema"] = present / 3.0
        except Exception:
            pass

    # screenshots aggregate
    all_shots = init_present + lo_present + final_present + diff_present
    s["screenshots_count"] = len(all_shots) / 12.0

    if pytesseract and Image and all_shots:
        kws = ["LibreOffice", "Writer", "Evince", "Table", "Header", "Footer",
               "Cross", "Reference", "Properties", "Page"]
        hits = 0
        for sp in all_shots:
            try:
                tx = pytesseract.image_to_string(Image.open(sp))
                if any(k in tx for k in kws):
                    hits += 1
            except Exception:
                pass
        s["screenshot_ocr"] = min(1.0, hits / 5.0)

    # cross channel
    has_cli = (s["pandoc_log"] > 0 and s["final_pdf_exists"] > 0 and s["visual_diff_exists"] > 0)
    has_gui = s["screenshots_count"] >= 0.5
    s["cross_channel"] = 1.0 if (has_cli and has_gui) else (0.5 if (has_cli or has_gui) else 0.0)

    # VLM rubric
    if vlm_score_rubric and all_shots:
        rubric = {
            "vlm_lo_visible": "截图中可见 LibreOffice Writer 界面(菜单栏 / 工具栏 / 编辑区)",
            "vlm_table_fixed": "修复后截图中表格完全在页面边距内,无横向截断",
            "vlm_header_present": "修复后截图中页眉区域有可读文字内容",
            "vlm_diff_marks": "diff-pdf 截图中可见红 / 彩色差异叠加标记",
        }
        try:
            vlm = vlm_score_rubric([str(p) for p in all_shots[:4]], rubric,
                                   instruction="评估 DOCX 转换 + 修复任务的截图真实性。")
            for k in rubric:
                s[k] = float(vlm.get(k, 0.0) or 0.0)
        except Exception:
            pass

    # GUI hard-gate sub-scores: trajectory diversity + chrome OCR + window geometry
    import hashlib
    gui_shot_paths = [p for p in all_shots if p.exists()]
    if len(gui_shot_paths) >= 4:
        hashes = set(hashlib.md5(p.read_bytes()).hexdigest() for p in gui_shot_paths)
        gui_diversity = len(hashes) / max(1, len(gui_shot_paths))
    else:
        gui_diversity = 0.0
    s["gui_real_interaction"] = 1.0 if gui_diversity >= 0.9 else (0.5 if gui_diversity >= 0.7 else 0.0)

    geom_hits = 0
    if Image and gui_shot_paths:
        for p in gui_shot_paths:
            try:
                w, h = Image.open(p).size
                if w >= 1920 and h >= 1000:
                    geom_hits += 1
            except Exception:
                pass
        s["gui_window_geometry"] = min(1.0, geom_hits / max(3.0, len(gui_shot_paths) * 0.6))
    else:
        s["gui_window_geometry"] = 0.0

    chrome_kws = ["LibreOffice", "Writer", "Track Changes", "Styles", "File",
                  "Edit", "Format", "Evince", "Insert", "Sidebar"]
    chrome_hits = 0
    if pytesseract and Image and gui_shot_paths:
        for p in gui_shot_paths:
            try:
                tx = pytesseract.image_to_string(Image.open(p))
                if sum(1 for k in chrome_kws if k.lower() in tx.lower()) >= 2:
                    chrome_hits += 1
            except Exception:
                pass
        s["gui_chrome_ocr"] = min(1.0, chrome_hits / max(3.0, len(gui_shot_paths) * 0.5))
    else:
        s["gui_chrome_ocr"] = 0.0

    # Weighted aggregation: core delivery 60% / GUI evidence 30% / aux 10%
    core_keys = [
        "docx_structure", "docx_contents",
        "first_pass_exists", "first_pass_pages", "pandoc_log",
        "first_text", "first_metrics_schema",
        "odt_head_dump",
        "final_pdf_exists", "final_pdf_pages", "lo_convert_log",
        "final_text", "text_fidelity", "text_diff",
        "visual_diff_exists", "diff_result_schema",
        "structural_audit",
        "report_length", "report_table",
        "deliverables_schema",
    ]
    gui_keys = [
        "evince_initial_shots", "lo_writer_shots", "evince_final_shots",
        "evince_diff_shots", "screenshots_count", "screenshot_ocr",
        "gui_real_interaction", "gui_chrome_ocr", "gui_window_geometry",
        "vlm_lo_visible", "vlm_table_fixed",
        "vlm_header_present", "vlm_diff_marks",
    ]
    aux_keys = ["cross_channel"]

    def _avg(keys):
        vals = [s[k] for k in keys if k in s and isinstance(s[k], (int, float))]
        return sum(vals) / len(vals) if vals else 0.0

    core_score = _avg(core_keys)
    gui_score = _avg(gui_keys)
    aux_score = _avg(aux_keys)
    base = 0.6 * core_score + 0.3 * gui_score + 0.1 * aux_score

    # Hard gates (v2: tightened)
    if not has_cli:
        base = min(base, 0.35)
    if not has_gui:
        base = min(base, 0.35)
    # Core delivery failures cap aggressively
    if s["final_pdf_exists"] == 0 or s["visual_diff_exists"] == 0:
        base = min(base, 0.4)
    if s["text_fidelity"] == 0 and s["final_pdf_exists"] > 0:
        base = min(base, 0.5)
    # GUI real-interaction: layered gates
    if s.get("gui_real_interaction", 0) < 0.5:
        base = min(base, 0.4)
    if s.get("gui_real_interaction", 0) < 0.9:
        base = min(base, 0.6)
    # GUI chrome OCR: layered gates (only when OCR stack available)
    if pytesseract and Image:
        if s.get("gui_chrome_ocr", 0) < 0.3:
            base = min(base, 0.35)
        elif s.get("gui_chrome_ocr", 0) < 0.5:
            base = min(base, 0.5)
    # Screenshot count gate: <50% present cap aggressively
    if s.get("screenshots_count", 0) < 0.5:
        base = min(base, 0.4)
    # VLM unavailable cap: cannot earn full credit without rubric eval
    vlm_keys = ["vlm_lo_visible", "vlm_table_fixed", "vlm_header_present", "vlm_diff_marks"]
    if all(s.get(k, 0) == 0 for k in vlm_keys):
        base = min(base, 0.6)

    s["overall_score"] = round(base, 3)
    return s

Workspace Path

workspace/DOC/task_2_pandoc_docx_roundtrip

Skills

pandoc, pdftotext, libreoffice --headless, LibreOffice Writer GUI, Evince, diff-pdf, xmllint, pdfinfo, sha256sum, pytesseract OCR

Env


Warmup

which pandoc     >/dev/null 2>&1 || (apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq pandoc texlive-xetex >/dev/null 2>&1) || true
which pdftotext  >/dev/null 2>&1 || DEBIAN_FRONTEND=noninteractive apt-get install -y -qq poppler-utils >/dev/null 2>&1 || true
which xmllint    >/dev/null 2>&1 || DEBIAN_FRONTEND=noninteractive apt-get install -y -qq libxml2-utils >/dev/null 2>&1 || true
which evince     >/dev/null 2>&1 || DEBIAN_FRONTEND=noninteractive apt-get install -y -qq evince >/dev/null 2>&1 || true
which diff-pdf   >/dev/null 2>&1 || DEBIAN_FRONTEND=noninteractive apt-get install -y -qq diff-pdf >/dev/null 2>&1 || true
which tesseract  >/dev/null 2>&1 || DEBIAN_FRONTEND=noninteractive apt-get install -y -qq tesseract-ocr >/dev/null 2>&1 || true
pip install -q pillow python-docx pytesseract numpy 2>/dev/null || true
mkdir -p /tmp_workspace/docx_project /tmp_workspace/results || true
[ -f /tmp_workspace/docx_project/report_draft.docx ] || python3 /tmp_workspace/generate_report_docx.py /tmp_workspace/docx_project/report_draft.docx 2>/dev/null || true