#!/usr/bin/env python3 """Deterministic format gate + answer extraction for the gov-docgen deliverable. Hard gate (reward 0 when it fails): the .docx exists, opens with python-docx, and yields non-empty text. Scored format component: the rendered page count stays within the task's page budget (LibreOffice render + pypdf count). A task without a page budget (max_pages null/absent) skips the page check — pages are still counted for reporting, but format_score equals the gate. A render failure is recorded as a warning and does not punish the agent; the gate already proved the file is a real document. Outputs: --format-out format.json {gate, format_score, pages, max_pages, ...} --answer-out extracted text of the deliverable (empty file when gate fails) Also persists the deliverable itself to /logs/verifier/deliverable__. The gate/score assembly lives in evaluate_deliverable(), with the docx, text and page probes injectable, so the truth table is unit-testable outside the sandbox image (tests/envs/test_gov_docgen_materializer.py). """ from __future__ import annotations import argparse import json import shutil import subprocess import sys import tempfile from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) from extract_docx import extract_docx_text # noqa: E402 def find_deliverable(filename: str) -> Path | None: candidates = [Path("/app/outputs") / filename, Path("/app/app/outputs") / filename] for candidate in candidates: if candidate.is_file() and candidate.stat().st_size > 0: return candidate return None def validate_docx(path: Path) -> None: """Raise when the file is not a document python-docx can open.""" from docx import Document Document(str(path)) def count_pages(docx_path: Path, warnings: list[str]) -> int | None: with tempfile.TemporaryDirectory(prefix="docgen-render-") as scratch: try: proc = subprocess.run( ["soffice", "--headless", "--convert-to", "pdf", "--outdir", scratch, str(docx_path)], capture_output=True, text=True, timeout=300, ) except (OSError, subprocess.TimeoutExpired) as exc: warnings.append(f"page render failed: {exc}") return None rendered = list(Path(scratch).glob("*.pdf")) if proc.returncode != 0 or not rendered: warnings.append(f"page render failed: soffice exit {proc.returncode}: {proc.stderr[:300]}") return None try: from pypdf import PdfReader return len(PdfReader(str(rendered[0])).pages) except Exception as exc: # noqa: BLE001 · a broken render must not crash the gate warnings.append(f"page count failed: {exc}") return None def evaluate_deliverable( deliverable: Path | None, filename: str, max_pages: int | None, *, validate=validate_docx, extract=extract_docx_text, pages=count_pages, ) -> tuple[dict, str]: """The gate/score truth table. Returns (format result, extracted text). gate = found AND valid docx AND non-empty text; false zeroes the whole reward in normalize_docgen_reward.py. format_score = 1.0 when the gate holds and the page budget is met, else 0.0. A None max_pages means no budget: every page count is within it. An unknown page count (render infra failure) counts as within budget: the agent is not punished for our tooling. """ warnings: list[str] = [] result: dict = { "deliverable": filename, "found": False, "valid_docx": False, "has_text": False, "pages": None, "max_pages": max_pages, "page_ok": None, "gate": False, "format_score": 0.0, "warnings": warnings, } text = "" if deliverable is None: warnings.append(f"deliverable {filename} missing or empty under /app/outputs") else: result["found"] = True try: validate(deliverable) result["valid_docx"] = True except Exception as exc: # noqa: BLE001 · any parse failure means an invalid docx warnings.append(f"not a valid .docx: {exc}") if result["valid_docx"]: try: text = extract(deliverable) except Exception as exc: # noqa: BLE001 warnings.append(f"text extraction failed: {exc}") result["has_text"] = bool(text.strip()) page_count = pages(deliverable, warnings) result["pages"] = page_count result["page_ok"] = ( True if (page_count is None or max_pages is None) else page_count <= max_pages ) result["gate"] = bool(result["found"] and result["valid_docx"] and result["has_text"]) result["format_score"] = 1.0 if (result["gate"] and result["page_ok"]) else 0.0 return result, text def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--config", required=True) parser.add_argument("--format-out", required=True) parser.add_argument("--answer-out", required=True) args = parser.parse_args() config = json.loads(Path(args.config).read_text()) filename = config["deliverable_filename"] deliverable = find_deliverable(filename) if deliverable is not None: persisted = Path("/logs/verifier") / f"deliverable__{filename}" persisted.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(deliverable, persisted) raw_max_pages = config.get("max_pages") result, text = evaluate_deliverable( deliverable, filename, None if raw_max_pages is None else int(raw_max_pages) ) answer_out = Path(args.answer_out) answer_out.parent.mkdir(parents=True, exist_ok=True) answer_out.write_text(text if not text or text.endswith("\n") else f"{text}\n") format_out = Path(args.format_out) format_out.parent.mkdir(parents=True, exist_ok=True) format_out.write_text(json.dumps(result, indent=2) + "\n") print(json.dumps({k: result[k] for k in ("gate", "format_score", "pages", "max_pages")})) return 0 if __name__ == "__main__": raise SystemExit(main())