docx_template.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/env python3
  2. # MIT License. Part of the Hermes docx skill.
  3. """Fill {{placeholder}} tokens in a .docx from a JSON mapping.
  4. Tokens are replaced everywhere: body paragraphs, tables (including nested
  5. tables), headers and footers. Run formatting is preserved; tokens split
  6. across runs are handled.
  7. Usage:
  8. docx_template.py template.docx values.json output.docx
  9. docx_template.py template.docx values.json output.docx --strict
  10. values.json: {"name": "Ada", "date": "2026-01-01"} fills {{name}}, {{date}}.
  11. With --strict, exits 1 if any {{token}} remains unfilled after processing.
  12. """
  13. from __future__ import annotations
  14. import argparse
  15. import json
  16. import re
  17. import sys
  18. from docx import Document
  19. from docx_common import iter_all_paragraphs, replace_in_paragraph
  20. TOKEN_RE = re.compile(r"\{\{\s*([A-Za-z0-9_.-]+)\s*\}\}")
  21. def main() -> int:
  22. ap = argparse.ArgumentParser(
  23. description="Fill {{token}} placeholders in a .docx from JSON.")
  24. ap.add_argument("template", help="input .docx with {{tokens}}")
  25. ap.add_argument("values", help="JSON file of token -> value")
  26. ap.add_argument("output", help="output .docx path")
  27. ap.add_argument("--strict", action="store_true",
  28. help="fail if any token remains unfilled")
  29. args = ap.parse_args()
  30. with open(args.values, encoding="utf-8") as f:
  31. values = json.load(f)
  32. doc = Document(args.template)
  33. filled = {}
  34. for para in iter_all_paragraphs(doc):
  35. # Normalize whitespace variants like {{ name }} first.
  36. for m in set(TOKEN_RE.findall(para.text)):
  37. if m in values:
  38. # Replace any spacing variant with canonical token, then fill.
  39. for variant in set(
  40. t.group(0) for t in TOKEN_RE.finditer(para.text)
  41. if t.group(1) == m):
  42. n = replace_in_paragraph(para, variant, str(values[m]))
  43. filled[m] = filled.get(m, 0) + n
  44. remaining = sorted({m for para in iter_all_paragraphs(doc)
  45. for m in TOKEN_RE.findall(para.text)})
  46. doc.save(args.output)
  47. result = {"ok": True, "output": args.output, "filled": filled,
  48. "unfilled_tokens": remaining}
  49. if args.strict and remaining:
  50. result["ok"] = False
  51. print(json.dumps(result, ensure_ascii=False))
  52. return 1
  53. print(json.dumps(result, ensure_ascii=False))
  54. return 0
  55. if __name__ == "__main__":
  56. sys.exit(main())