Skip to content

FIX: Support tables, headers/footers, JSON templates, and async offload in WordDocConverter - #4835

Open
G.YASWANTH SAI (yaswanth2501) wants to merge 2 commits into
microsoft:mainfrom
yaswanth2501:fix/word-doc-converter-injection
Open

G.YASWANTH SAI (yaswanth2501) wants to merge 2 commits into
microsoft:mainfrom
yaswanth2501:fix/word-doc-converter-injection

Conversation

@yaswanth2501

@yaswanth2501 G.YASWANTH SAI (yaswanth2501) commented Dec 4, 2026 •

Copy link
Copy Markdown

Description

WordDocConverter (pyrit/converter/word_doc_converter.py) had four defects when injecting placeholders into .docx templates, parsing JSON template parameters, and running inside async pipelines:

  • _inject_into_existing_docx only iterated document.paragraphs, silently skipping placeholders inside tables, nested tables, headers, and footers.
  • _replace_placeholder_in_paragraph returned True immediately after updating the first matching run, leaving any subsequent matching runs in the same paragraph unreplaced.
  • _prepare_content only called ast.literal_eval(prompt) even though __init__ documents JSON-encoded mappings, so valid JSON payloads containing true, false, or null raised ValueError.
  • convert_async ran synchronous python-docx file reads, XML parsing, and serialization (_generate_new_docx and _inject_into_existing_docx) directly on the asyncio event loop.

Changes:

  • Added _iter_table_paragraphs and _iter_document_paragraphs to traverse body paragraphs, tables/nested tables (deduplicating merged cells via cell._tc), and section headers/footers/tables (header, first_page_header, even_page_header, footer, first_page_footer, even_page_footer, deduplicating linked containers via container._element).
  • Updated _replace_placeholder_in_paragraph to replace all matching runs in a paragraph before returning whether any replacement occurred.
  • Extracted _parse_template_mapping to parse with json.loads first and fall back to ast.literal_eval, wrapping (ValueError, KeyError, TypeError) in _prepare_content as ValueError.
  • Offloaded _generate_new_docx and _inject_into_existing_docx in convert_async using asyncio.to_thread(...), matching PDFConverter.
  • Updated the class docstring to reflect table, header, and footer placeholder support.

Before / after for JSON template input {"name": "Alice", "active": true, "note": null}:

# before
ValueError: Failed to render the prompt for Word document: name 'true' is not defined

# after
"name=Alice, active=True, note=None"

Tests and Documentation

  • Added 9 unit tests in tests/unit/converter/test_word_doc_converter.py covering multi-run paragraphs, JSON true/false/null payloads, non-dict / non-string-key rejection, tables/nested tables/merged cells, headers/footers (including linked sections), asyncio.to_thread worker-thread offloading, and concurrent end-to-end JSON + .docx injection.
  • Ran uv run --frozen --no-sync -m pytest -q tests/unit/converter/test_word_doc_converter.py --cov=pyrit.converter.word_doc_converter --cov-report=term-missing: 36 passed, 100% statement coverage (132/132 statements).
  • Ran uv run --frozen --no-sync -m pytest -q tests/unit/converter/test_word_doc_converter.py tests/unit/backend/test_converter_service.py tests/unit/registry/test_converter_identifier_contract.py -k "word_doc or WordDocConverter": 40 passed, 100% diff coverage (47/47 lines).
  • Ran uv run --frozen --no-sync -m pytest -q tests/unit/converter/ tests/unit/backend/test_converter_service.py: 4,137 passed, 57 skipped.
  • Ran ruff check, ruff format --check, ty check, build_scripts.check_keyword_only_params, and build_scripts.check_public_imports: all passed.
  • No documentation notebooks were changed.

This change and its tests were prepared with AI assistance.

Copilot AI balanced review requested due to automatic review settings December 4, 2026 16:27

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Tracking only integer cell IDs allows lxml proxy ID reuse, which can cause distinct cells to be skipped and their placeholders left unchanged.

1 open issue
What changed in this PR

Improves PyRIT’s WordDocConverter template handling and moves document processing off the event loop.

Changes:

  • Expands placeholder replacement to tables, headers, footers, and all matching runs.
  • Supports JSON template parameters with Python-literal fallback.
  • Adds regression tests for document traversal, parsing, and asynchronous execution.
File Description
tests/​unit/​converter/​test_word_doc_converter.py Adds parsing, traversal, thread-offloading, and concurrent conversion tests.
pyrit/​converter/​word_doc_converter.py Extends placeholder traversal, parses JSON parameters, and offloads document processing.

Review effort: Balanced

Comment thread pyrit/converter/word_doc_converter.py Outdated
Comment on lines +282 to +297
def _iter_table_paragraphs(cls, *, tables: Any, seen_cells: set[int]) -> Iterator[Any]:
"""Yield paragraphs across tables and nested tables, deduplicating merged cells."""
for table in tables:
for row in table.rows:
for cell in row.cells:
cell_id = id(cell._tc)
if cell_id in seen_cells:
continue
seen_cells.add(cell_id)
yield from cell.paragraphs
yield from cls._iter_table_paragraphs(tables=cell.tables, seen_cells=seen_cells)

@classmethod
def _iter_document_paragraphs(cls, *, document: Any) -> Iterator[Any]:
"""Yield paragraphs across the document body, tables, headers, and footers."""
seen_cells: set[int] = set()

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated _iter_table_paragraphs and _iter_document_paragraphs to store cell._tc and container._element directly in seen_cells and seen_containers rather than id(...), keeping lxml proxies alive throughout traversal.

@yaswanth2501

Copy link
Copy Markdown
Author

@microsoft-github-policy-service agree

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants