Add resume autofill exports and application answers

This commit is contained in:
StormRunner06106
2026-10-02 05:30:06 -07:00
parent eddfa8bd4f
commit bf1bf7b9f8
24 changed files with 3072 additions and 11 deletions
+181 -11
View File
@@ -6,6 +6,7 @@
"""Generate a versioned HTML/PDF resume pair from Markdown.
Install: python -m pip install Markdown==3.10.3 playwright==1.62.0
Word: python -m pip install python-docx==1.2.0
python -m playwright install chromium
Run: python scripts/generate_resume.py
python scripts/generate_resume.py --version 2026-09 --browser msedge
@@ -121,6 +122,156 @@ li { margin-bottom: 3pt; break-inside: avoid; }
"""
AUTOFILL_CSS = """
@page { size: Letter; margin: 40pt 43pt; }
* { box-sizing: border-box; }
body { max-width: 612pt; margin: 24px auto; padding: 40pt 43pt;
color: #111; background: white; font: 10.5pt/1.18 Arial, sans-serif; }
h1 { font-size: 22pt; margin: 0 0 6pt; }
h2 { font-size: 12pt; margin: 10pt 0 6pt; border-bottom: 1pt solid #777;
padding-bottom: 3pt; }
h3 { font-size: 11pt; margin: 6pt 0 3pt; }
h4, h5, h6 { font-size: 10.5pt; margin: 7pt 0 3pt; }
h1, h2, h3, h4, h5, h6 { break-after: avoid; }
p { margin: 0 0 3pt; orphans: 2; widows: 2; }
a { color: inherit; text-decoration: none; }
ul, ol { padding-left: 15pt; margin: 4pt 0 8pt; }
li { margin-bottom: 1.5pt; break-inside: avoid; }
li:has(> ul), li:has(> ol) { break-inside: auto; }
li > p:has(+ ul), li > p:has(+ ol) { break-after: avoid; }
.job-heading { break-inside: avoid; break-after: avoid; }
.job-heading p { margin-bottom: 2pt; }
em { font-style: italic; }
.dates, em.dates { color: #555; font-size: 9pt; font-style: normal; }
@media print { body { max-width: none; margin: 0; padding: 0; } }
"""
def is_date_text(text):
return re.fullmatch(r"[A-Za-z]+ \d{4} - (?:[A-Za-z]+ \d{4}|Present)", text.strip()) is not None
def is_date_paragraph(node):
return node.tag == "p" and is_date_text("".join(node.itertext()))
def autofill_body(document):
"""Keep job title, employer, location and date together in normal flow."""
document = deepcopy(document)
for node in document.iter():
if node.tag in ("em", "p") and is_date_text("".join(node.itertext())):
node.set("class", "dates")
nodes = list(document)
result = []
index = 0
while index < len(nodes):
node = nodes[index]
end = index + 1
if node.tag == "h3":
while end < len(nodes) and nodes[end].tag == "p":
if is_date_paragraph(nodes[end]):
end += 1
break
end += 1
# Only group metadata ending with a date, not entire descriptions.
if end > index + 1 and is_date_paragraph(nodes[end - 1]):
result.append('<div class="job-heading">' +
"".join(serialize(n) for n in nodes[index:end]) + '</div>')
index = end
continue
result.append(serialize(node))
index += 1
return "".join(result)
def write_docx(source, target):
"""Write ordinary Word paragraphs, with no tables, text boxes or headers."""
import markdown
from docx import Document
from docx.shared import Inches, Pt, RGBColor
document = Document()
section = document.sections[0]
section.page_width, section.page_height = Inches(8.5), Inches(11)
section.top_margin = section.bottom_margin = Pt(40)
section.left_margin = section.right_margin = Pt(43)
normal = document.styles["Normal"]
normal.font.name, normal.font.size = "Arial", Pt(10.5)
normal.paragraph_format.space_after = Pt(3)
normal.paragraph_format.line_spacing = 1.18
root = ET.fromstring("<div>" + markdown.markdown(source, extensions=["extra"],
output_format="xhtml") + "</div>")
grouped = ET.fromstring("<div>" + autofill_body(root) + "</div>")
metadata = {"".join(p.itertext()).strip()
for group in grouped.findall("./div[@class='job-heading']")
for p in group.findall("p")}
def add_inline(paragraph, node, bold=False, italic=False, date=False):
bold = bold or node.tag == "strong"
date = date or (node.tag == "em" and is_date_text("".join(node.itertext())))
italic = (italic or node.tag == "em") and not date
def add_run(text):
if not text or (text.isspace() and "\n" in text):
return
run = paragraph.add_run(text)
run.bold, run.italic = bold, italic
if date:
run.font.size = Pt(9)
run.font.color.rgb = RGBColor.from_string("555555")
add_run(node.text)
for child in node:
if child.tag not in ("ul", "ol"):
add_inline(paragraph, child, bold, italic, date)
add_run(child.tail)
def add_list(list_node, depth=0):
for item in list_node:
# Exclude child lists from the parent's text, then render each child
# as its own indented Word paragraph in the same reading order.
children = []
for child in item:
if child.tag in ("ul", "ol"):
children.append(child)
style = "List Bullet" if list_node.tag == "ul" else "List Number"
if depth:
style += f" {min(depth + 1, 3)}"
paragraph = document.add_paragraph(style=style)
add_inline(paragraph, item)
paragraph.paragraph_format.left_indent = Pt(15 * (depth + 1))
paragraph.paragraph_format.first_line_indent = Pt(-7.5)
paragraph.paragraph_format.keep_together = True
paragraph.paragraph_format.keep_with_next = bool(children)
for child in children:
add_list(child, depth + 1)
for node in root:
text = "".join(node.itertext()).strip()
if node.tag in ("ul", "ol"):
add_list(node)
elif re.fullmatch(r"h[1-6]", node.tag):
paragraph = document.add_paragraph()
add_inline(paragraph, node, bold=True)
for run in paragraph.runs:
run.font.size = Pt(22 if node.tag == "h1" else 12 if node.tag == "h2" else 11)
paragraph.paragraph_format.space_before = Pt(10 if node.tag != "h1" else 0)
paragraph.paragraph_format.keep_with_next = True
elif node.tag == "p":
paragraph = document.add_paragraph()
add_inline(paragraph, node)
if node.find("strong") is not None and len(node) == 1 and not node.text:
paragraph.paragraph_format.keep_with_next = True
if text in metadata or is_date_paragraph(node):
paragraph.paragraph_format.keep_with_next = True
else:
raise ValueError(f"Unsupported Word resume element: {node.tag}")
name = "".join(root.find("h1").itertext()).strip()
document.core_properties.title = f"{name} | Resume"
document.core_properties.author = name
document.save(target)
def serialize(element):
return ET.tostring(element, encoding="unicode", method="html")
@@ -149,8 +300,8 @@ def build_html(source: str, layout: str = "original") -> str:
"""Render Markdown in normal reading order or the original two-column layout."""
import markdown
if layout not in ("ats", "original"):
raise ValueError("Layout must be ats or original.")
if layout not in ("ats", "original", "autofill"):
raise ValueError("Layout must be ats, original or autofill.")
try:
document = ET.fromstring(
@@ -171,6 +322,15 @@ def build_html(source: str, layout: str = "original") -> str:
name = "".join(name_node.itertext()).strip()
if not name or any(node.tag == "h1" for node in nodes):
raise ValueError("The resume must have exactly one nonempty # name heading.")
if layout == "autofill":
return (
'<!doctype html>\n<html lang="en"><head><meta charset="utf-8">'
'<meta name="viewport" content="width=device-width, initial-scale=1">'
f'<meta name="source-sha256" content="{hashlib.sha256(source.encode("utf-8")).hexdigest()}">'
'<meta name="resume-layout" content="autofill">'
f'<title>{escape(name)} | Resume</title><style>{AUTOFILL_CSS}</style></head>'
'<body><main>' + autofill_body(document) + '</main></body></html>\n'
)
intro = []
while nodes and nodes[0].tag != "h2":
intro.append(nodes.pop(0))
@@ -267,19 +427,23 @@ def build_html(source: str, layout: str = "original") -> str:
)
def generate(source: Path, output: Path, version: str | None, browser: str, layout: str = "original"):
def generate(source: Path, output: Path, version: str | None, browser: str, layout: str = "original", docx: bool = False):
from playwright.sync_api import sync_playwright
html = build_html(source.read_text(encoding="utf-8-sig"), layout)
if docx and layout != "autofill":
raise ValueError("Word output requires --layout autofill.")
source_text = source.read_text(encoding="utf-8-sig")
html = build_html(source_text, layout)
output.mkdir(parents=True, exist_ok=True)
if version is None:
number = 1
while any((output / f"resume-v{number}.{ext}").exists() for ext in ("html", "pdf")):
while any((output / f"resume-v{number}.{ext}").exists() for ext in ("html", "pdf", "docx")):
number += 1
version = f"v{number}"
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]{0,79}", version):
raise ValueError("Version must be 1–80 letters, digits, dots, underscores or hyphens, starting with a letter or digit.")
targets = [output / f"resume-{version}.{ext}" for ext in ("html", "pdf")]
extensions = ("html", "pdf", "docx") if docx else ("html", "pdf")
targets = [output / f"resume-{version}.{ext}" for ext in extensions]
if any(path.exists() for path in targets):
raise ValueError(f"Version {version!r} already exists. Choose a new version.")
@@ -297,10 +461,15 @@ def generate(source: Path, output: Path, version: str | None, browser: str, layo
display_header_footer=False, tagged=True, outline=True)
finally:
chromium.close()
# Publish only a complete pair, and never overwrite an earlier version.
staged_paths = [html_path, pdf_path]
if docx:
docx_path = Path(temporary) / targets[2].name
write_docx(source_text, docx_path)
staged_paths.append(docx_path)
# Publish only a complete set, and never overwrite an earlier version.
created = []
try:
for target, staged in zip(targets, (html_path, pdf_path)):
for target, staged in zip(targets, staged_paths):
with target.open("xb") as handle:
created.append(target)
handle.write(staged.read_bytes())
@@ -317,13 +486,14 @@ def main():
parser.add_argument("--output-dir", type=Path, default=ROOT / "resumes")
parser.add_argument("--version", help="Version label; defaults to the next available v1, v2, ...")
parser.add_argument("--browser", choices=["chromium", "msedge", "chrome"], default="chromium")
parser.add_argument("--layout", choices=["ats", "original"], default="original",
parser.add_argument("--layout", choices=["ats", "original", "autofill"], default="original",
help="Original sidebar design (default) or single-column application layout")
parser.add_argument("--docx", action="store_true", help="Also create a Word document (autofill layout; requires python-docx)")
args = parser.parse_args()
try:
paths = generate(args.source.resolve(), args.output_dir.resolve(), args.version, args.browser, args.layout)
paths = generate(args.source.resolve(), args.output_dir.resolve(), args.version, args.browser, args.layout, args.docx)
except ImportError as exc:
parser.exit(1, f"Missing dependency: {exc}. Install Markdown==3.10.3 and playwright==1.62.0.\n")
parser.exit(1, f"Missing dependency: {exc}. Install Markdown==3.10.3 and playwright==1.62.0; --docx also needs python-docx==1.2.0.\n")
except (ValueError, OSError) as exc:
parser.exit(1, f"Resume generation failed: {exc}\n")
except Exception as exc:
+112
View File
@@ -0,0 +1,112 @@
"""Check v16 extraction: python -m unittest discover -s scripts -p test_resume_autofill.py."""
from pathlib import Path
import re
import unittest
import xml.etree.ElementTree as ET
import markdown
import pymupdf
from docx import Document
from pypdf import PdfReader
from generate_resume import build_html
ROOT = Path(__file__).resolve().parents[1]
def normalized(text):
return re.sub(r"[\s\u2022\u00b7]+", "", text)
class AutofillResumeTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.source = (ROOT / "resumes/resume-v16.md").read_text(encoding="utf-8")
cls.html = (ROOT / "resumes/resume-v16.html").read_text(encoding="utf-8")
tree = ET.fromstring("<div>" + markdown.markdown(
cls.source, extensions=["extra"], output_format="xhtml") + "</div>")
cls.expected = normalized("".join(tree.itertext()))
def test_reproducible_plain_html(self):
self.assertEqual(self.html, build_html(self.source, "autofill"))
body = self.html.split("<body>")[1]
for markup in ("<header", "<footer", "<table", "<nav", "<span", "<img"):
self.assertNotIn(markup, body)
tree = ET.fromstring(self.html.split("<body>")[1].split("</body>")[0])
groups = tree.findall("./div[@class='job-heading']")
self.assertEqual(len(groups), 8) # Seven roles and the dated university entry.
work = groups[:7]
self.assertEqual([g.find("p/em").text for g in work], [
"Self-employed", "Covius, LLC", "SEAD Software",
"Clarity Diagnostics & Lab Solutions", "MyTap, aka Which Craft",
"TriCore Reference Laboratories", "Desert Digital Consulting"])
self.assertEqual([g.findall("p")[-1].find("em").text for g in work], [
"June 2024 - Present", "January 2022 - April 2024",
"April 2021 - July 2022", "September 2020 - January 2022",
"January 2016 - April 2020", "April 2013 - January 2017",
"October 2010 - January 2021"])
def test_projects_are_children_of_self_employment(self):
tree = ET.fromstring(self.html.split("<body>")[1].split("</body>")[0])
nodes = list(tree)
jobs = tree.findall("./div[@class='job-heading']")
between = nodes[nodes.index(jobs[0]) + 1:nodes.index(jobs[1])]
projects = next(node for node in between if node.tag == "ul")
names = ["IIPM.ie", "SafeSchoolz", "Equity Funding Source"]
self.assertEqual(len(projects), 3)
for item, name in zip(projects, names):
self.assertIn(name, "".join(item.itertext()))
self.assertFalse("".join(item.itertext()).strip().startswith(name))
self.assertEqual(item.findall(".//em"), [])
self.assertNotRegex("".join(item.itertext()), r"[A-Za-z]+ \d{4} -")
self.assertIsNone(item.find("ul"))
self.assertEqual(item.findall(".//strong"), [])
self.assertNotIn("Projects", [h.text for h in tree.findall("h2")])
doc = Document(ROOT / "resumes/resume-v16.docx")
for name in names:
paragraph = next(p for p in doc.paragraphs if name in p.text)
self.assertEqual(paragraph.style.name, "List Bullet")
self.assertFalse(any(run.bold for run in paragraph.runs))
self.assertIn("freelance client project", paragraph.text)
def test_two_pdf_extractors_preserve_all_text_in_order(self):
path = ROOT / "resumes/resume-v16.pdf"
with pymupdf.open(path) as doc:
self.assertEqual(normalized("".join(p.get_text() for p in doc)), self.expected)
for page in doc:
words = page.get_text("words")
self.assertTrue(words)
self.assertTrue(all(0 <= w[0] < w[2] <= page.rect.width and
0 <= w[1] < w[3] <= page.rect.height for w in words))
self.assertEqual(normalized("".join(p.extract_text() for p in PdfReader(path).pages)),
self.expected)
def test_word_body_preserves_all_text(self):
doc = Document(ROOT / "resumes/resume-v16.docx")
self.assertEqual(normalized("".join(p.text for p in doc.paragraphs)), self.expected)
self.assertEqual(len(doc.tables), 0)
self.assertFalse(any(p.text for section in doc.sections for p in section.header.paragraphs))
self.assertFalse(any(p.text for section in doc.sections for p in section.footer.paragraphs))
def test_organization_dates_degree_and_references(self):
doc = Document(ROOT / "resumes/resume-v16.docx")
for company in ("Desert Digital Consulting", "Covius, LLC", "University of New Mexico"):
paragraph = next(p for p in doc.paragraphs if p.text == company)
self.assertTrue(all(run.italic for run in paragraph.runs if run.text.strip()))
for date in ("October 2010 - January 2021", "September 2003 - September 2008"):
paragraph = next(p for p in doc.paragraphs if p.text == date)
for run in paragraph.runs:
self.assertEqual(run.font.size.pt, 9)
self.assertEqual(str(run.font.color.rgb), "555555")
self.assertFalse(run.italic)
self.assertIn("BS, Computer Science", [p.text for p in doc.paragraphs])
reference_index = next(i for i, p in enumerate(doc.paragraphs) if p.text == "References")
references = doc.paragraphs[reference_index + 1:]
self.assertEqual(len(references), 4)
self.assertTrue(references[0].text.startswith("David Foy"))
self.assertTrue(references[-1].text.startswith("Douglas Radecki"))
if __name__ == "__main__":
unittest.main()