--- id: DOC_task_2_pdf_form_fill name: 复杂 PDF 交互表单填写与签名 category: DOC timeout_seconds: 1200 --- ## Prompt > ⚙️ **Execution convention**: This task is graded on deliverable files; **no one is approving anything**. Just execute — do not ask "if you want me to…" questions, do not wait for approval. All deliverables must land in the **`/tmp_workspace/` root**: `lease_signed.pdf`, `step_*.png`, `actions.log`. Input assets are in `/tmp_workspace/inputs/`. When done, run `ls -la /tmp_workspace/` as a self-check before exiting. Background: `/tmp_workspace/lease_agreement.pdf` is a multi-page interactive form PDF — 18 pages and ~1265 AcroForm fields (text / checkbox / radio / signature). Tenant data is in `/tmp_workspace/inputs/tenant.json`; the signature image is `inputs/signature.png` and the initials image is `inputs/initials.png`. Goal: fill out this lease form, add the e-signature and initials images, and export `lease_signed.pdf`. ### Hard constraints on `lease_signed.pdf` - File exists at `/tmp_workspace/lease_signed.pdf`, page count remains 18 - **AcroForm structure must be preserved** (PDF root contains `/AcroForm`); must not be flattened into a static PDF - At least **50** text fields actually filled (the number of fields with a non-empty value via `pypdf.PdfReader.get_form_text_fields()` must be ≥ 50) - At least **5** button / checkbox / radio fields set (`/FT == /Btn` and `/V` is not `/Off`) - Page 4 has at least 1 radio / button field selected - The PDF contains at least **5** embedded images (`/Subtype /Image` appearing in the XObject of page resources) — used to carry the e-signature plus multiple initials stamps - At least a few field values from `tenant.json` (name / SSN / address / phone / move-in date / monthly rent / deposit / bank account / emergency contact, etc.) can be matched literally inside the PDF field values ### Anti-cheat / action log - `/tmp_workspace/actions.log` is an action log (any text format) recording the steps used to fill the form - `actions.log` **must not contain** any of these literals: `pdftk fill_form`, `update_page_form_field_values`, `cli_fill` — the pure-CLI bulk-fill shortcut is not allowed - Use a PDF editor with form support (Master PDF Editor / Okular / LibreOffice Draw, etc.) to genuinely type values into the fields ### 5 progress screenshots (located in `/tmp_workspace/`) - File naming: `step_*.png` (any name, at least 5) - Each ≥ 5 KB - All 5 md5 hashes distinct - Screenshots overall must show a genuine, readable PDF editor UI (an OCR check is performed): - At least 1 screenshot showing a form editing panel such as field properties / Form Fields / Annotation - At least 1 screenshot showing recognizable PDF editor UI (editor name / Insert Image / Stamp / Edit Form, etc.) ## Expected Behavior 设计意图与典型解题路径(仅供出题人参考,不发给 agent): 1. PDF 实际内容是 IRS Form 1040 + 1065 + 1120-S + 706 拼接(18 页 / ~1265 个 AcroForm 字段)。 2. 推荐 GUI:Master PDF Editor / Okular(带表单支持)/ LibreOffice Draw 等任一带表单支持的 PDF 编辑器,逐字段填值。 3. 按 `tenant.json` 填入 ≥ 50 个 text 字段(姓名 / SSN / 地址 / 电话 / 入住日期 / 月租金 / 押金 / 银行账户 / 紧急联系人)。 4. checkbox 任选 5 处勾上(宠物押金、停车位、家电附带、保险、转租条款;可在 1040 / 1065 / 1120-S Schedule B 的 Yes/No checkbox 中挑)。 5. 第 4 页:在 1065 Schedule B 第 1 题("What type of entity is filing this return")选 "Domestic general partnership" radio。 6. 用 PDF 编辑器的 "Add Image" / "Stamp" 功能: - 第 14 页 706 Form "Signature of executor" 位置贴 `inputs/signature.png` - 在第 6 / 8 / 10 / 12 / 17 页(任选 5 处 "Initial here")贴 `inputs/initials.png` 7. **保存** 为 `lease_signed.pdf`(用编辑器的 Save,不要 Print to PDF —— Print to PDF 会 flatten AcroForm 结构,flatten 后 grader 读不到字段值)。 8. 截 5 张关键步骤截图 `step_*.png`,至少有一张能看到字段属性面板,至少一张能看到编辑器名称 / Insert Image / Stamp 等关键 UI。 9. 写 `actions.log` 记录操作历史(任何文本格式都行)。 约束说明: - 不要走 `pdftk fill_form` / `pypdf.update_page_form_field_values` 这条 CLI 批量 fill 路径 —— grader 检 `actions.log` 是否含这些字面量 - AcroForm 必须保留:grader 检 PDF root 含 `/AcroForm` + 用 `get_form_text_fields()` 读非空字段 ≥ 50 评分要点(hard gates): - `lease_signed.pdf` 不存在 → cap 0.10 - text fields 填值率 < 60% → cap 0.40 - buttons 勾选率 < 60% → cap 0.45 - 第 4 页 radio 未选 → cap 0.55 - 内嵌图 < 60%(即 < 3 张)→ cap 0.45 - AcroForm 被 flatten → cap 0.40 - 截图无字段属性面板 → cap 0.50 - `actions.log` 含禁止字面量 → cap 0.30 - 没截图 OCR 命中 PDF 编辑器名 → cap 0.40 - 5 张截图 md5 不唯一 → cap 0.55 - OCR 不可用 → cap 0.60 ## Source - Reddit: https://www.reddit.com/r/legaltech/comments/1bxxxxx/llm_pdf_form_fill_fail/ - 原文引用:「I tried having an agent fill a 60-field lease. Without a real PDF editor GUI, it kept producing flattened printouts; the landlord's e-sign software rejected them.」 - 对应 benchmark case: 法律 / DOC 新增 ## Grading Criteria - [ ] `lease_signed.pdf` 存在 - [ ] `pypdf.get_form_text_fields()` 返回**已填**字段数 ≥ 50 - [ ] `tenant.json` 中至少 8 个值能在表单字段中找到 - [ ] PDF 中包含 ≥ 5 张嵌入图(pypdf 检查 `/XObject /Image`,覆盖签名 + 4 个 initials 位置) - [ ] AcroForm 仍存在(`/AcroForm` in pdf root),未 flatten - [ ] `step_*.png` ≥ 5 张,且 md5 互不相同、每张 ≥ 5 KB - [ ] 至少 1 张截图含字段属性词汇(OCR "Field"/"属性"/"Properties") - [ ] 至少勾选 5 处 button/checkbox 字段(pypdf `get_fields()` 中 `/Btn` 类型且值非空/非 Off) - [ ] 第 4 页 radio 选择了一个非空选项 ## Automated Checks ```python def grade(**kwargs) -> dict: """Strict grader against REAL IRS f1040+f1065+f1120s+f706 (1265 fields, 18 pages). Scoring: weighted 0.6*core + 0.3*gui + 0.1*aux, with multi-layer hard gates (no-cli-fill, fields_filled, buttons, images, AcroForm-kept, OCR proof of GUI). """ from pathlib import Path import json, subprocess s = {} pdf = Path("/tmp_workspace/lease_signed.pdf") inp = Path("/tmp_workspace/inputs/tenant.json") gt = Path("/tmp_workspace/gt/expected.json") expected = json.loads(gt.read_text()) if gt.exists() else {} tenant = json.loads(inp.read_text()) if inp.exists() else {} s["pdf_exists"] = 1.0 if pdf.exists() else 0.0 n_filled = n_data_hits = n_images = pages_ok = acroform_ok = 0 n_buttons_checked = 0 page4_radio_set = 0 if pdf.exists(): try: from pypdf import PdfReader R = PdfReader(str(pdf)) pages_ok = 1 if len(R.pages) >= 18 else 0 fields_dict = R.get_form_text_fields() or {} # strict: ≥50 text fields actually filled (≥4% of 1265 fields, hard-gate at 0.6 = 30) n_filled = sum(1 for v in fields_dict.values() if v and str(v).strip()) tenant_strs = [str(v).strip() for v in tenant.values() if v] for ts in tenant_strs: if any(ts in (str(v) or "") for v in fields_dict.values()): n_data_hits += 1 root = R.trailer["/Root"] acroform_ok = 1 if "/AcroForm" in root else 0 # Count button/checkbox/radio fields that are toggled on (value not empty/Off) try: all_fields = R.get_fields() or {} for fname, fobj in all_fields.items(): try: ftype = fobj.get("/FT") fval = fobj.get("/V") if ftype == "/Btn" and fval is not None: sval = str(fval) if sval and sval not in ("/Off", "Off", "/", ""): n_buttons_checked += 1 except Exception: pass # Detect any radio/button selection on page 4 try: p4 = R.pages[3] annots = p4.get("/Annots") or [] for a in annots: try: ao = a.get_object() if ao.get("/Subtype") == "/Widget" and ao.get("/FT") == "/Btn": v = ao.get("/V") or ao.get("/AS") if v is not None and str(v) not in ("/Off", "Off", "/", ""): page4_radio_set = 1 break except Exception: pass except Exception: pass except Exception: pass for p in R.pages: xo = (p.get("/Resources") or {}).get("/XObject") or {} for k in xo: try: if xo[k].get_object().get("/Subtype")=="/Image": n_images += 1 except Exception: pass except Exception as e: s["pdf_error"] = str(e)[:100] # Stricter: require ≥50 actually-filled text fields (was 30) — agent must really sit and type s["fields_filled"] = min(1.0, n_filled / 50.0) s["buttons_checked"] = min(1.0, n_buttons_checked / 5.0) s["page4_radio"] = float(page4_radio_set) s["data_value_hits"] = min(1.0, n_data_hits / max(1,min(10,len(tenant)))) s["page_count"] = pages_ok * 1.0 s["acroform_kept"] = acroform_ok * 1.0 # Stricter: 1 signature + 4 initials = 5 image overlays s["images_embedded"] = min(1.0, n_images / 5.0) # screenshots — require 5 unique, non-trivial PNGs (anti-cheat: md5 dedup + size floor) import hashlib steps_all = sorted(Path("/tmp_workspace").glob("step_*.png")) seen_md5 = set(); good_steps = [] for p in steps_all: try: data = p.read_bytes() if len(data) < 5120: # < 5KB → almost certainly a placeholder continue h = hashlib.md5(data).hexdigest() if h in seen_md5: continue seen_md5.add(h); good_steps.append(p) except Exception: pass steps = good_steps s["screenshots"] = min(1.0, len(steps) / 5.0) s["screenshots_unique"] = 1.0 if len(seen_md5) >= 5 else (len(seen_md5) / 5.0) panel_screen = False ocr_available = False try: import pytesseract from PIL import Image ocr_available = True for p in steps: tx = pytesseract.image_to_string(Image.open(p)) if any(k in tx for k in ["Field","属性","Properties","Form Fields","Annotation", "Master PDF","Okular","Edit","Tools","Document"]): panel_screen = True; break except Exception: # OCR unavailable — do NOT auto-credit (Warmup installs tesseract+pytesseract) panel_screen = False s["field_panel_visible"] = 1.0 if panel_screen else 0.0 # No-cheat: forbid pdftk fill_form / pypdf update_page_form_field_values usage log = Path("/tmp_workspace/actions.log") forbidden = False if log.exists(): t = log.read_text(errors="ignore") if any(b in t for b in ["pdftk fill_form","update_page_form_field_values","cli_fill"]): forbidden = True s["no_cli_fill"] = 0.0 if forbidden else 1.0 # Hard GUI gate: at least one screenshot must OCR to a real PDF editor name # (Master PDF Editor / Okular form panel / LibreOffice Draw form fields). pdf_ui_ocr = 0.0 try: import pytesseract as _pt from PIL import Image as _PI for p in steps: try: tx = _pt.image_to_string(_PI.open(p)) if any(k in tx for k in ["Master PDF","Okular","Form Fields", "Edit Form","Annotation","LibreOffice Draw", "Insert Image","Stamp"]): pdf_ui_ocr = 1.0; break except Exception: pass except ImportError: pdf_ui_ocr = 0.0 # OCR unavailable — no credit (Warmup 已要求安装 tesseract+pytesseract) s["pdf_editor_ocr"] = pdf_ui_ocr nums = [s[k] for k in s if isinstance(s[k],(int,float))] # Weighted aggregate — core deliverable 60%, GUI evidence 30%, aux 10% core_keys = ["pdf_exists","fields_filled","buttons_checked","page4_radio", "data_value_hits","acroform_kept","images_embedded"] gui_keys = ["screenshots","screenshots_unique","field_panel_visible", "pdf_editor_ocr","no_cli_fill"] aux_keys = ["page_count"] def _avg(keys): vs = [s[k] for k in keys if k in s and isinstance(s[k],(int,float))] return sum(vs)/len(vs) if vs else 0.0 base = 0.6*_avg(core_keys) + 0.3*_avg(gui_keys) + 0.1*_avg(aux_keys) # Hard gates — agent must really do the work, not just produce shells if s.get("pdf_exists",0) < 1.0: base = min(base, 0.10) if s.get("fields_filled",0) < 0.6: base = min(base, 0.40) # was 0.45 if s.get("buttons_checked",0) < 0.6: base = min(base, 0.45) # was 0.6 if s.get("page4_radio",0) < 1.0: base = min(base, 0.55) if s.get("images_embedded",0) < 0.6: base = min(base, 0.45) if s.get("acroform_kept",0) < 1.0: base = min(base, 0.40) # flatten = fail core if s.get("field_panel_visible",0) < 1.0: base = min(base, 0.50) # was 0.55 if s.get("no_cli_fill",0) < 1.0: base = min(base, 0.30) # was 0.4 if s.get("pdf_editor_ocr",0) < 0.5: base = min(base, 0.40) # was 0.55 if s.get("screenshots_unique",0) < 1.0: base = min(base, 0.55) # md5 dedup gate # If OCR pipeline unavailable, cap overall at 0.6 (don't let infra gap = full marks) if not ocr_available: base = min(base, 0.60) s["overall_score"] = round(base, 3) return s ``` ## Workspace Path `workspace/DOC/task_2_pdf_form_fill/` ## Skills ``` ``` ## Env ``` ``` ## Warmup ```bash which okular >/dev/null 2>&1 || (apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq okular okular-extra-backends) || true which masterpdfeditor5 >/dev/null 2>&1 || (curl -fsSLo /tmp/mpe.deb https://get.code-industry.net/public/master-pdf-editor-5.9.91-qt5.x86_64.deb && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq /tmp/mpe.deb) || true pip install -q pypdf pillow reportlab || true pdfinfo /tmp_workspace/lease_agreement.pdf >/dev/null 2>&1 || true apt-get install -y -qq tesseract-ocr || true pip install -q pytesseract pillow numpy || true ```