Files
Rpa_Skills/skills/rpa-bot-handoff/templates/to_docx.py
T
VasanthandClaude Opus 5.5 ff2f7fcd4a rpa-bot-handoff: one short Handover SOP (max 4 pages) instead of the 11-section guide
The first real handover (MEK Charge Reconciliation) came out at 9 pages.
Ops want it short: which URL to open and what to click, what shows where
after the click, what to do when an exception comes, and how to email us.

- Output is "<Project Name> Handover SOP" (HANDOVER-SOP.md + .docx) with
  5 sections: how to run, what you see while it runs, result, when
  something goes wrong, email us. HANDOVER-DEV.md is dropped; dev-team
  findings go in the chat.
- At most ~1,400 words; to_docx.py prints the word count and flags overflow,
  and renders *italic* for the variable parts of messages.
- Every quoted message, label and URL is checked against the code. The SOP
  must say what clicking Run again does to the data.
- One scan subagent; failure classes stay as a scan checklist.
- Tebra reference rewritten in the SOP format; test, README, glossary
  updated; ADR-0005 supersedes ADR-0004.

The handoff eval runner (tests/evals/run_handoff_eval.py) still grades an
older 13-section format and was already out of date; not touched here.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 16:57:48 +05:30

127 lines
5.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Turn the Handover SOP (HANDOVER-SOP.md) into a Word document ops can open, print and pass around.
python to_docx.py HANDOVER-SOP.md # writes HANDOVER-SOP.docx next to it
python to_docx.py HANDOVER-SOP.md -o "<Project Name> Handover SOP.docx"
python to_docx.py --selfcheck
Prints the word count: the SOP must stay at or under MAX_WORDS (about 4 pages).
Handles what the template uses: # headings, paragraphs, - bullets, - [ ] checkboxes, 1. steps,
| tables |, ``` blocks, **bold**, *italic* and `code`. Needs python-docx (pip install python-docx).
"""
import argparse
import re
import sys
import tempfile
from pathlib import Path
from docx import Document
from docx.shared import Pt
MAX_WORDS = 1400 # about 4 pages with tables
INLINE = re.compile(r"(\*\*[^*]+\*\*|\*[^*\s][^*]*\*|`[^`]+`)")
def add_runs(par, text):
for part in INLINE.split(text):
if part.startswith("**") and part.endswith("**"):
par.add_run(part[2:-2]).bold = True
elif len(part) > 2 and part.startswith("*") and part.endswith("*"):
par.add_run(part[1:-1]).italic = True
elif part.startswith("`") and part.endswith("`"):
par.add_run(part[1:-1]).font.name = "Consolas"
elif part:
par.add_run(part)
def cells(line):
return [c.strip() for c in line.strip().strip("|").split("|")]
def convert(md_text, out_path):
doc = Document()
doc.styles["Normal"].font.name = "Calibri"
doc.styles["Normal"].font.size = Pt(10.5)
lines = md_text.splitlines()
i = 0
while i < len(lines):
line = lines[i]
if line.startswith("```"):
block = []
i += 1
while i < len(lines) and not lines[i].startswith("```"):
block.append(lines[i])
i += 1
run = doc.add_paragraph().add_run("\n".join(block))
run.font.name = "Consolas"
run.font.size = Pt(9.5)
elif line.startswith("|"):
rows = []
while i < len(lines) and lines[i].startswith("|"):
if not re.match(r"^\|[\s:|-]+\|\s*$", lines[i]): # skip the |---| separator
rows.append(cells(lines[i]))
i += 1
i -= 1
width = max(len(r) for r in rows)
table = doc.add_table(rows=len(rows), cols=width)
table.style = "Table Grid"
for r, row in enumerate(rows):
for c, text in enumerate(row):
par = table.cell(r, c).paragraphs[0]
add_runs(par, text)
if r == 0:
for run in par.runs:
run.bold = True
elif m := re.match(r"^(#{1,3})\s+(.*)", line):
doc.add_heading(m[2], level=len(m[1]) - 1 if len(m[1]) > 1 else 0)
elif m := re.match(r"^\s*- \[ \]\s+(.*)", line):
add_runs(doc.add_paragraph(style="List Bullet"), "☐ " + m[1])
elif m := re.match(r"^\s*[-*]\s+(.*)", line):
add_runs(doc.add_paragraph(style="List Bullet"), m[1])
elif m := re.match(r"^\s*\d+\.\s+(.*)", line):
add_runs(doc.add_paragraph(style="List Number"), m[1])
elif line.strip() and line.strip() != "---":
add_runs(doc.add_paragraph(), line.strip())
i += 1
doc.save(out_path)
return doc
def words(md_text):
return len(re.findall(r"[A-Za-z0-9][\w'’.-]*", re.sub(r"^\|[\s:|-]+\|\s*$", "", md_text, flags=re.M)))
def selfcheck():
example = Path(__file__).parent / "reference" / "tebra-auto-post.md"
sop = "# " + example.read_text(encoding="utf-8").split("\n---\n", 1)[1].split("\n# ", 1)[1]
out = Path(tempfile.mkdtemp()) / "HANDOVER-SOP.docx"
convert(sop, out)
doc = Document(out)
heads = [p.text for p in doc.paragraphs if p.style.name.startswith("Heading")]
assert doc.paragraphs[0].text.endswith("Handover SOP"), doc.paragraphs[0].text
assert [h.split(".")[0] for h in heads if h[:1].isdigit()] == [str(n) for n in range(1, 6)], heads
assert len(doc.tables) >= 4, len(doc.tables)
assert doc.tables[0].cell(0, 0).text == "Where on the screen", doc.tables[0].cell(0, 0).text
assert not any("**" in p.text or "|---" in p.text for p in doc.paragraphs)
assert words(sop) <= MAX_WORDS, words(sop)
print(f"selfcheck ok: {len(heads)} headings, {len(doc.tables)} tables, {words(sop)} words -> {out}")
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("md", nargs="?")
ap.add_argument("-o", "--out")
ap.add_argument("--selfcheck", action="store_true")
a = ap.parse_args()
if a.selfcheck:
selfcheck()
sys.exit(0)
if not a.md:
ap.error("give the HANDOVER.md path, or --selfcheck")
src = Path(a.md)
out = Path(a.out) if a.out else src.with_suffix(".docx")
text = src.read_text(encoding="utf-8")
convert(text, out)
n = words(text)
print(f"wrote {out} ({n} words{'' if n <= MAX_WORDS else f', OVER the {MAX_WORDS}-word limit: cut it'})")