")
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")
def gradient_text(text: str) -> str:
"""Use colored text runs so gradients print cleanly and remain selectable."""
start, end = (40, 100, 20), (138, 191, 105)
result = []
offset = 0
for word in re.split(r"(\s+)", text):
if word.isspace():
result.append(escape(word))
offset += len(word)
continue
letters = []
for character in word:
fraction = offset / max(len(text) - 1, 1)
color = "#" + "".join(f"{round(a + (b - a) * fraction):02x}" for a, b in zip(start, end))
letters.append(f'{escape(character)}')
offset += 1
result.append('' + "".join(letters) + '')
return "".join(result)
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", "autofill"):
raise ValueError("Layout must be ats, original or autofill.")
try:
document = ET.fromstring(
"
"
)
except ET.ParseError as exc:
raise ValueError("Markdown contains malformed raw HTML; use Markdown or valid XHTML.") from exc
# Content edits belong in Markdown, never silently in a generated version.
for node in document.iter():
for attribute in ("text", "tail"):
value = getattr(node, attribute)
if value and ("\u2014" in value or "\u2013" in value):
raise ValueError("Replace long dashes in the source Markdown before generating the resume.")
nodes = list(document)
if not nodes or nodes[0].tag != "h1":
raise ValueError("Start the Markdown with a single # heading containing the name.")
name_node = nodes.pop(0)
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 (
'\n'
''
f''
''
f'{escape(name)} | Resume'
'' + autofill_body(document) + '\n'
)
intro = []
while nodes and nodes[0].tag != "h2":
intro.append(nodes.pop(0))
if not nodes:
raise ValueError("Add resume sections using ## headings.")
subtitle = ""
if intro and intro[0].tag == "p" and intro[0].find("strong") is not None:
title = "".join(intro.pop(0).itertext())
primary, separator, secondary = title.partition("·")
subtitle = '
"
contact_links = []
for node in intro:
for parent in node.iter():
for child in list(parent):
if child.tag != "a":
continue
href = child.get("href", "")
label = ("Phone" if href.startswith("tel:") else
"Email" if href.startswith("mailto:") else
"Profile" if "linkedin.com/" in href else
"Code" if "github.com/" in href else "Website")
direct = ' class="direct"' if label in ("Phone", "Email") else ""
contact_links.append(
f''
f'{label}'
''
+ gradient_text("".join(child.itertext())) + ''
)
tail = (child.tail or "").strip(" ·|\n\t")
if tail:
position = list(parent).index(child)
if position:
previous = parent[position - 1]
previous.tail = (previous.tail or "") + tail
else:
parent.text = (parent.text or "") + tail
parent.remove(child)
for br in list(node):
if br.tag == "br" and not (br.tail or "").strip():
node.remove(br)
contact_details = "".join(serialize(node) for node in intro if "".join(node.itertext()).strip())
contact_grid = '' if contact_links else ""
header = (
"
" + serialize(name_node) + subtitle + '
'
+ '
' + escape(name) + "
"
+ contact_details + contact_grid + "
"
)
sections = []
for node in nodes:
if node.tag == "h2":
sections.append((node, []))
else:
sections[-1][1].append(node)
rendered = []
for heading, content in sections:
if not content:
raise ValueError(f"Section {''.join(heading.itertext())!r} has no content.")
for node in content:
# Dates follow role/project headings in the source Markdown.
if node.tag == "p" and len(node) == 1 and node[0].tag == "em" and not (node.text or "").strip() and not (node[0].tail or "").strip():
node.set("class", "dates")
# The reference lists each contact on its own line, rather than a grid.
if "".join(heading.itertext()).strip().lower() == "references":
for index, node in enumerate(content):
if node.tag != "table":
continue
rows = node.findall("./tbody/tr")
if not rows or any(len(row) != 4 for row in rows):
continue
listing = ET.Element("ul", {"class": "references"})
for row in rows:
item = ET.SubElement(listing, "li")
for column, cell in enumerate(row):
span = ET.SubElement(item, "strong" if column == 0 else "span")
span.text = cell.text
span.extend(deepcopy(list(cell)))
span.tail = " · " if column < 2 else (": " if column == 2 else "")
content[index] = listing
# Keep the label with the first content block when a section crosses pages.
start = '