Add resume autofill exports and application answers
This commit is contained in:
+181
-11
@@ -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:
|
||||
|
||||
Reference in New Issue
Block a user