doc.add_picture("/home/user/image.png", width=Inches(4))
# In a table cell
run = table.cell(1, 2).paragraphs[0].add_run()
run.add_picture("/home/user/image.png", width=Inches(1.5))
Page Breaks
doc.add_page_break() # simplest# Or via run
run = para.add_run()
br = run._element.makeelement(qn('w:br'), {qn('w:type'): 'page'})
run._element.append(br)
run = para.add_run("Highlighted")
run.font.highlight_color = WD_COLOR_INDEX.YELLOW # GREEN, CYAN, PINK, RED, etc.
run.font.highlight_color = None# remove
Modifying Existing Files
shutil.copy("/home/user/original.docx", "/home/user/modified.docx") # ALWAYS copy first
doc = Document("/home/user/modified.docx")
for para in doc.paragraphs:
for run in para.runs:
run.font.name = "Calibri"
doc.save("/home/user/modified.docx")
2. Reading & Verifying Files (reward-gen)
Loading & Structure
from docx import Document
from docx.shared import Pt, RGBColor
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT, WD_TAB_ALIGNMENT
doc = Document("/path/to/file.docx")
num_paras = len(doc.paragraphs)
num_tables = len(doc.tables)
num_sections = len(doc.sections)
Reading Text & Font Properties
for para in doc.paragraphs:
# para.text — full text (all runs concatenated)for run in para.runs:
run.text # run text
run.font.name # "Arial" or None
run.font.size # EMU value; use .pt for float (e.g. 12.0)
run.font.bold # True / False / None (None=inherit)
run.font.italic # True / False / None
run.font.underline # True / False / None
run.font.strike # True / False / None (strikethrough)
run.font.subscript # True / False / None
run.font.superscript # True / False / None
run.font.color.rgb # RGBColor or None
run.font.highlight_color # WD_COLOR_INDEX or None
Verifying Paragraph Format
pf = para.paragraph_format
pf.alignment # WD_PARAGRAPH_ALIGNMENT enum or None
pf.line_spacing # float (1.0, 2.0) or Pt or None
pf.space_before # Pt or None
pf.space_after # Pt or None
pf.left_indent # EMU or None
pf.first_line_indent # EMU or None
pf.page_break_before # True / False / None
Verifying Tab Stops
for ts in para.paragraph_format.tab_stops:
# Filter defaults: skip CLEAR and LEFT+position=0if ts.alignment == WD_TAB_ALIGNMENT.CLEAR: continueif ts.alignment == WD_TAB_ALIGNMENT.LEFT and ts.position == 0: continueprint(f"Alignment={ts.alignment}, Position={ts.position}")
Verifying Tables
for table in doc.tables:
for i, row inenumerate(table.rows):
for j, cell inenumerate(row.cells):
text = cell.text.strip()
for para in cell.paragraphs:
for run in para.runs:
# run.font.bold, .color.rgb, etc.pass
Verifying Images
from io import BytesIO
from PIL import Image
defextract_images(doc):
images = []
for rel in doc.part.rels.values():
if"image"in rel.reltype:
images.append(BytesIO(rel.target_part.blob))
return images
# Check inline image in run via XML
has_image = 'graphicData'in run._element.xml
Verifying Page Breaks
defcount_page_breaks(doc):
ns = {'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'}
count = 0for para in doc.paragraphs:
for run in para.runs:
for br in run.element.findall('.//w:br', ns):
if br.attrib.get(f'{{{ns["w"]}}}type') == 'page':
count += 1return count
Verifying Headers, Footers & Page Numbers
section = doc.sections[0]
header_text = section.header.paragraphs[0].text if section.header.paragraphs else""
footer_text = section.footer.paragraphs[0].text if section.footer.paragraphs else""
has_page_num = any(c.isdigit() for c in footer_text)
# Highlight checkfor run in para.runs:
if run.font.highlight_color isnotNone:
print(f"Highlighted: '{run.text}' color={run.font.highlight_color}")
# Strikethrough on last paragraph
last_para = doc.paragraphs[-1]
all_strike = all(run.font.strike for run in last_para.runs if run.text.strip())
Verifying Case Conversion
defhas_uppercase(doc):
for para in doc.paragraphs:
for run in para.runs:
if run.text.strip() and run.text.isupper(): returnTruefor table in doc.tables:
for row in table.rows:
for cell in row.cells:
for para in cell.paragraphs:
for run in para.runs:
if run.text.strip() and run.text.isupper(): returnTruereturnFalse
Verifying Colored Words in Tables
from math import sqrt
defcolor_distance(c1, c2):
return sqrt(sum((a - b) ** 2for a, b inzip(c1, c2)))
for table in doc.tables:
for row in table.rows:
for cell in row.cells:
for para in cell.paragraphs:
for run in para.runs:
if run.text and run.font.color.rgb:
first = run.text[0].lower()
if first in'aeiou':
assert color_distance(run.font.color.rgb, RGBColor(255,0,0)) < 50else:
assert color_distance(run.font.color.rgb, RGBColor(0,0,255)) < 50
ODF (.odt) File Verification
from odf.opendocument import load
from odf.text import P, Span
odt_doc = load("/path/to/file.odt")
for para in odt_doc.getElementsByType(P):
text_parts = []
for node in para.childNodes:
if node.nodeType == node.TEXT_NODE:
text_parts.append(node.data)
elif node.nodeType == node.ELEMENT_NODE and node.tagName == 'text:span':
for child in node.childNodes:
if child.nodeType == child.TEXT_NODE:
text_parts.append(child.data)
# Check ODT highlighting (background color in automatic styles)for span in odt_doc.getElementsByType(Span):
style_name = span.getAttribute('stylename')
if style_name:
for auto_style in odt_doc.automaticstyles.childNodes:
if auto_style.getAttribute('name') == style_name:
for prop in auto_style.childNodes:
if prop.getAttribute('backgroundcolor') == '#ffff00':
print("Yellow highlight found!")
Common Helpers for reward.py
import re
defcompare_text(doc1, doc2, ignore_blanks=True):
p1 = [p.text for p in doc1.paragraphs]
p2 = [p.text for p in doc2.paragraphs]
if ignore_blanks:
return re.sub(r'\s+', ' ', '\n'.join(p1)).strip() == re.sub(r'\s+', ' ', '\n'.join(p2)).strip()
return p1 == p2
defcheck_all_font_name(doc, expected):
returnall(run.font.name == expected for para in doc.paragraphs for run in para.runs if run.font.name)
defcheck_italic_size(doc, expected_pt):
returnall(run.font.size and run.font.size.pt == expected_pt
for para in doc.paragraphs for run in para.runs if run.italic)
3. Bitter Lessons
run.font.size is EMU, not points.run.font.size == 14 fails. Use run.font.size.pt == 14 or run.font.size == Pt(14).
para.text concatenates runs, losing formatting. To check per-run formatting (bold word + normal), iterate para.runs. Never rely on para.text for style checks.
None means "inherited" for font properties.run.font.bold is None means "inherit from style". If the style is bold, None means bold. Usually treat None as False, but be aware.
Page breaks are inside runs, not paragraphs. Manual breaks are <w:br w:type="page"/> in run elements. Use XML parsing: run.element.findall('.//w:br', ns). Cannot detect via para.text.
Highlighting differs between .docx and .odt.run.font.highlight_color works for .docx. ODT stores highlights in automatic styles as backgroundcolor. Need different code paths.
Copy-then-modify for golden files.shutil.copy(initial, golden) then modify. Scratch files lack styles, numbering, and metadata causing comparison failures.
Tab stop comparison must filter defaults. LibreOffice adds default LEFT@0 and CLEAR stops. Filter them out to avoid false mismatches.
ignore_blanks=True collapses all whitespace. When paragraph structure (empty lines) matters, use ignore_blanks=False and compare paragraph-by-paragraph.
Footer page numbers are field codes, not text.<w:fldChar> + <w:instrText> PAGE </w:instrText>. The .text property shows cached values. Check for digit presence, not exact number.
doc.part.rels images include ALL images. Headers, footers, textboxes too. Not just body. Filter if needed.
para.runs may miss hyperlink/field text.para.text includes all text, but ''.join(r.text for r in para.runs) may be shorter. Use para.text for full text comparison.
Color comparison: use perceptual distance. The evaluator uses CIEDE2000 (Delta E) with threshold ~3.5 from skimage.color.deltaE_ciede2000. Simple RGB distance is imprecise.
Equations are OLE objects. Detect with run.element.xpath('.//w:object'). No readable text via python-docx.
Multiple gold files for tolerance. LibreOffice formatting varies by version/fonts. Provide 2-4 gold files with OR logic in reward scripts.