codegood Claude Sonnet 5.5 commited on
Commit
e785c0a
Β·
1 Parent(s): 4848d0e

Add one-page ATS resume generator with JD alignment checks

Browse files

Render LLM Markdown into a .docx matching the reference resume template
(Times New Roman, tight margins, right-aligned dates, hyperlinks, Skills
first). After each draft, measure page count and compare JD keywords with
the candidate documents, then ask the model to repair missing keywords,
fabricated tools, extra pages or placeholders (up to 3 attempts). Wire a
Generate Resume button into the app and let build_llm take a model.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

Files changed (6) hide show
  1. app.py +40 -1
  2. graph.py +2 -2
  3. requirements.txt +1 -0
  4. resume.py +468 -0
  5. skills/generate-resume.md +108 -0
  6. tests/test_resume.py +491 -0
app.py CHANGED
@@ -10,8 +10,9 @@ from openai import LengthFinishReasonError
10
 
11
  from config import ConfigError, get_settings
12
  from dataloader import convert_uploaded_documents
13
- from graph import ATS_NODE, build_graph
14
  from observability import build_run_config, flush
 
15
  from skills import ACTIONS
16
  import spaces
17
 
@@ -152,6 +153,34 @@ def run_action(key, chat_history, job_description, thread_id, session_id):
152
  )
153
 
154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
  def stream_response(
156
  chat_history, job_description, thread_id, session_id=None, model_query=None, action=""
157
  ):
@@ -272,6 +301,8 @@ with gr.Blocks(title="job-chat", fill_height=True, analytics_enabled=False) as d
272
  key: gr.Button(label, size="sm")
273
  for key, (label, _) in ACTIONS.items()
274
  }
 
 
275
 
276
  chatbot = gr.Chatbot(height=520, show_label=False, resizable=True)
277
  with gr.Row():
@@ -283,6 +314,8 @@ with gr.Blocks(title="job-chat", fill_height=True, analytics_enabled=False) as d
283
  )
284
  stop_btn = gr.Button("Stop", variant="stop", scale=1)
285
  clear_chat_btn = gr.Button("Reset conversation")
 
 
286
 
287
  jd_box.change(jd_status, inputs=jd_box, outputs=jd_state)
288
  clear_jd_btn.click(lambda: "", outputs=jd_box)
@@ -332,6 +365,12 @@ with gr.Blocks(title="job-chat", fill_height=True, analytics_enabled=False) as d
332
 
333
  stop_btn.click(fn=None, cancels=generation_events, queue=False)
334
 
 
 
 
 
 
 
335
 
336
  if __name__ == "__main__":
337
  logger.info("Model: %s | tracing: %s", SETTINGS.model, SETTINGS.tracing_enabled)
 
10
 
11
  from config import ConfigError, get_settings
12
  from dataloader import convert_uploaded_documents
13
+ from graph import ATS_NODE, build_graph, build_llm
14
  from observability import build_run_config, flush
15
+ from resume import RESUME_MODEL, generate_resume_docx
16
  from skills import ACTIONS
17
  import spaces
18
 
 
153
  )
154
 
155
 
156
+ def generate_resume_handler(session_id, job_description):
157
+ """Generate an ATS-friendly .docx resume and return it as a downloadable file."""
158
+ import tempfile
159
+
160
+ session = SESSION_DATA.get(session_id) or {}
161
+ profile_data = session.get("profile_data")
162
+ api_key = session.get("api_key") or SETTINGS.openrouter_api_key
163
+
164
+ if not profile_data:
165
+ return gr.update(visible=False), "Upload profile documents first."
166
+ if not (job_description or "").strip():
167
+ return gr.update(visible=False), "Paste a job description before generating a resume."
168
+ if not api_key:
169
+ return gr.update(visible=False), "Connect an OpenRouter API key first."
170
+
171
+ try:
172
+ llm = build_llm(api_key=api_key, model=RESUME_MODEL, max_tokens=8000)
173
+ docx_bytes = generate_resume_docx(profile_data, job_description, llm)
174
+ with tempfile.NamedTemporaryFile(suffix=".docx", delete=False) as tmp:
175
+ tmp.write(docx_bytes)
176
+ tmp_path = tmp.name
177
+ return gr.update(value=tmp_path, visible=True), "Resume ready β€” click the file to download."
178
+ except Exception as exc:
179
+ logger.exception("Resume generation failed")
180
+ detail = request_error_detail(exc)
181
+ return gr.update(visible=False), f"**Resume generation failed.** {detail}"
182
+
183
+
184
  def stream_response(
185
  chat_history, job_description, thread_id, session_id=None, model_query=None, action=""
186
  ):
 
301
  key: gr.Button(label, size="sm")
302
  for key, (label, _) in ACTIONS.items()
303
  }
304
+ with gr.Row():
305
+ generate_resume_btn = gr.Button("Generate Resume (.docx)", size="sm", variant="secondary")
306
 
307
  chatbot = gr.Chatbot(height=520, show_label=False, resizable=True)
308
  with gr.Row():
 
314
  )
315
  stop_btn = gr.Button("Stop", variant="stop", scale=1)
316
  clear_chat_btn = gr.Button("Reset conversation")
317
+ resume_status = gr.Markdown("")
318
+ resume_file = gr.File(label="Download resume", visible=False, interactive=False)
319
 
320
  jd_box.change(jd_status, inputs=jd_box, outputs=jd_state)
321
  clear_jd_btn.click(lambda: "", outputs=jd_box)
 
365
 
366
  stop_btn.click(fn=None, cancels=generation_events, queue=False)
367
 
368
+ generate_resume_btn.click(
369
+ generate_resume_handler,
370
+ inputs=[session_id, jd_box],
371
+ outputs=[resume_file, resume_status],
372
+ )
373
+
374
 
375
  if __name__ == "__main__":
376
  logger.info("Model: %s | tracing: %s", SETTINGS.model, SETTINGS.tracing_enabled)
graph.py CHANGED
@@ -95,7 +95,7 @@ def route_action(state, semantic_router=None) -> str:
95
  return NODE_BY_ROUTE[semantic_router.route(query)]
96
 
97
 
98
- def build_llm(temperature=None, max_tokens=None, api_key=None):
99
  settings = get_settings(require_api_key=False)
100
  api_key = api_key or settings.openrouter_api_key
101
  if not api_key:
@@ -103,7 +103,7 @@ def build_llm(temperature=None, max_tokens=None, api_key=None):
103
  return ChatOpenAI(
104
  api_key=api_key,
105
  base_url=OPENROUTER_BASE_URL,
106
- model=settings.model,
107
  temperature=settings.temperature if temperature is None else temperature,
108
  max_tokens=settings.max_tokens if max_tokens is None else max_tokens,
109
  )
 
95
  return NODE_BY_ROUTE[semantic_router.route(query)]
96
 
97
 
98
+ def build_llm(temperature=None, max_tokens=None, api_key=None, model=None):
99
  settings = get_settings(require_api_key=False)
100
  api_key = api_key or settings.openrouter_api_key
101
  if not api_key:
 
103
  return ChatOpenAI(
104
  api_key=api_key,
105
  base_url=OPENROUTER_BASE_URL,
106
+ model=model or settings.model,
107
  temperature=settings.temperature if temperature is None else temperature,
108
  max_tokens=settings.max_tokens if max_tokens is None else max_tokens,
109
  )
requirements.txt CHANGED
@@ -1,3 +1,4 @@
 
1
  fastembed==0.8.0
2
  bm25s==0.3.15
3
  faiss-cpu==1.15.1
 
1
+ python-docx==1.1.2
2
  fastembed==0.8.0
3
  bm25s==0.3.15
4
  faiss-cpu==1.15.1
resume.py ADDED
@@ -0,0 +1,468 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Resume generator: LLM β†’ structured Markdown β†’ one-page ATS-friendly .docx.
2
+
3
+ The LLM returns a resume in a strict Markdown format; this module renders it in
4
+ the candidate's house layout (tight margins, SKILLS first, right-aligned dates,
5
+ no tables/text boxes/images), then checks the result against the job
6
+ description and asks the model to repair it when it falls short:
7
+
8
+ * page count must be 1 (measured with LibreOffice when installed, else estimated)
9
+ * every JD keyword the candidate honestly has must appear (>= 90%)
10
+ * no JD keyword the candidate does NOT have may appear (no fabrication)
11
+ * no leftover [ADD METRIC] placeholders or markdown noise
12
+ """
13
+
14
+ import logging
15
+ import math
16
+ import re
17
+ import shutil
18
+ import subprocess
19
+ import tempfile
20
+ import time
21
+ from io import BytesIO
22
+ from pathlib import Path
23
+
24
+ from docx import Document
25
+ from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_LINE_SPACING, WD_TAB_ALIGNMENT
26
+ from docx.oxml import OxmlElement
27
+ from docx.oxml.ns import qn
28
+ from docx.shared import Inches, Pt, RGBColor
29
+ from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
30
+
31
+ from config import PROJECT_ROOT
32
+ from observability import get_callbacks
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+ # Free model with 131K context β€” handles the full profile+JD prompt reliably.
37
+ # The default openrouter/free model silently returns empty content for large prompts.
38
+ RESUME_MODEL = "nvidia/nemotron-3-nano-omni-30b-a3b-reasoning:free"
39
+
40
+ MAX_ATTEMPTS = 3
41
+ COVERAGE_TARGET = 0.9
42
+
43
+ _SKILLS_DIR = PROJECT_ROOT / "skills"
44
+ _FONT = "Times New Roman"
45
+ _BLACK = RGBColor(0, 0, 0)
46
+ _LINK = RGBColor(0x05, 0x63, 0xC1)
47
+
48
+ # Geometry copied from the reference resume template (Letter, one page).
49
+ _MARGIN_TB = Inches(0.34)
50
+ _MARGIN_LR = Inches(0.44)
51
+ _TEXT_WIDTH = Inches(7.62)
52
+ _LINE = Pt(12) # exact line height of body text (0.1665in)
53
+ _BULLET_INDENT = Inches(0.2154)
54
+ _BULLET_HANG = Inches(0.1319)
55
+
56
+
57
+ def _load_prompt() -> str:
58
+ return (_SKILLS_DIR / "generate-resume.md").read_text(encoding="utf-8").strip()
59
+
60
+
61
+ def _strip_code_fence(text: str) -> str:
62
+ """Remove outer ``` wrapper that many models add despite being told not to."""
63
+ stripped = text.strip()
64
+ if not stripped.startswith("```"):
65
+ return text
66
+ lines = stripped.splitlines()
67
+ lines = lines[1:] # opening fence (``` or ```markdown)
68
+ if lines and lines[-1].strip() == "```":
69
+ lines = lines[:-1]
70
+ return "\n".join(lines)
71
+
72
+
73
+ def _clean_markdown(raw_text: str) -> str:
74
+ """Drop fences, any preamble before the name, and stray inline markdown."""
75
+ text = _strip_code_fence(raw_text)
76
+ lines = text.splitlines()
77
+ first_h1 = next((i for i, l in enumerate(lines) if l.strip().startswith("# ")), 0)
78
+ text = "\n".join(lines[first_h1:])
79
+ return text.replace("**", "").replace("`", "")
80
+
81
+
82
+ # ── Job-description alignment checks ─────────────────────────────────────────
83
+
84
+ # Lower-case technical vocabulary that CamelCase/acronym detection cannot see.
85
+ _SINGLE = set(
86
+ "python agentic rag docker kubernetes pytorch tensorflow aws azure gcp embedding embeddings "
87
+ "quantization inference observability microservice microservices orchestration evaluation "
88
+ "evaluations monitoring fastapi postgresql react".split()
89
+ )
90
+ _MULTI = [
91
+ "multi-agent", "knowledge graph", "fine-tuning", "vector search", "vector database",
92
+ "semantic search", "tool calling", "human-in-the-loop", "llm-as-judge", "prompt engineering",
93
+ "context engineering", "hugging face", "generative ai", "open-source", "on-premise",
94
+ "model context protocol", "edge deployment", "multi-agent systems",
95
+ ]
96
+ _TOKEN = re.compile(r"[A-Za-z][A-Za-z0-9+#]*(?:[./-][A-Za-z0-9+#]+)*")
97
+
98
+
99
+ def jd_keywords(job_description: str) -> list[str]:
100
+ """Technical terms in a JD: CamelCase, acronyms, dotted/digit names, known vocabulary."""
101
+ found: dict[str, str] = {}
102
+ low = job_description.lower()
103
+ for phrase in _MULTI:
104
+ if re.search(r"(?<![a-z0-9])" + re.escape(phrase) + r"(?![a-z0-9])", low):
105
+ found.setdefault(phrase, phrase)
106
+ for tok in _TOKEN.findall(job_description):
107
+ tail = tok[1:]
108
+ techy = (
109
+ any(c.isupper() for c in tail) # LangChain, vLLM, ONNX, GGML
110
+ or any(c.isdigit() or c in "+#." for c in tok) # llama.cpp, Next.js
111
+ or tok.lower() in _SINGLE
112
+ )
113
+ if techy and len(tok) > 1:
114
+ found.setdefault(tok.lower(), tok)
115
+ return list(found.values())
116
+
117
+
118
+ def _pattern(term: str) -> re.Pattern:
119
+ parts = [re.escape(p) for p in re.split(r"[\s\-_.]+", term.lower()) if p]
120
+ body = r"[\s\-_.]*".join(parts)
121
+ return re.compile(r"(?<![a-z0-9])" + body + r"s?(?![a-z0-9])", re.I)
122
+
123
+
124
+ def _contains(text: str, term: str) -> bool:
125
+ return bool(_pattern(term.rstrip("s") if term.lower().endswith("s") and len(term) > 3 else term).search(text))
126
+
127
+
128
+ def keyword_report(job_description: str, profile: str, resume_text: str) -> dict:
129
+ """Which honestly-supported JD keywords made it in, and which unsupported ones leaked in."""
130
+ terms = jd_keywords(job_description)
131
+ supported = [t for t in terms if _contains(profile, t)]
132
+ missing = [t for t in supported if not _contains(resume_text, t)]
133
+ # Only named tools/protocols count as fabrication; generic phrases ("multi-agent") are style.
134
+ generic = set(_MULTI) | _SINGLE
135
+ invented = [t for t in terms if t not in supported and t.lower() not in generic and _contains(resume_text, t)]
136
+ coverage = 1.0 if not supported else 1 - len(missing) / len(supported)
137
+ return {"coverage": coverage, "missing": missing, "invented": invented, "supported": supported}
138
+
139
+
140
+ # ── Page-fit measurement ─────────────────────────────────────────────────────
141
+
142
+ def _soffice() -> str | None:
143
+ found = shutil.which("soffice") or shutil.which("libreoffice")
144
+ if found:
145
+ return found
146
+ for p in (r"C:\Program Files\LibreOffice\program\soffice.exe", "/usr/bin/soffice"):
147
+ if Path(p).exists():
148
+ return p
149
+ return None
150
+
151
+
152
+ def _count_pages_libreoffice(docx_bytes: bytes) -> int | None:
153
+ exe = _soffice()
154
+ if not exe:
155
+ return None
156
+ try:
157
+ with tempfile.TemporaryDirectory() as tmp:
158
+ src = Path(tmp) / "r.docx"
159
+ src.write_bytes(docx_bytes)
160
+ subprocess.run(
161
+ [exe, "--headless", "--convert-to", "pdf", "--outdir", tmp, str(src)],
162
+ capture_output=True, timeout=90, check=True,
163
+ )
164
+ pdf = (Path(tmp) / "r.pdf").read_bytes()
165
+ return len(re.findall(rb"/Type\s*/Page(?![a-zA-Z])", pdf)) or None
166
+ except Exception: # noqa: BLE001 - measurement is best-effort
167
+ logger.warning("LibreOffice page count failed; falling back to estimate", exc_info=True)
168
+ return None
169
+
170
+
171
+ def _estimate_pages(docx_bytes: bytes) -> int:
172
+ """Rough fallback: ~122 chars/line at 10pt Times over 7.62in; ~118 for bullets."""
173
+ doc = Document(BytesIO(docx_bytes))
174
+ height = 0.0
175
+ for p in doc.paragraphs:
176
+ text = p.text.strip()
177
+ if not text:
178
+ continue
179
+ indented = p.paragraph_format.left_indent is not None
180
+ lines = max(1, math.ceil(len(text) / (118 if indented else 122)))
181
+ pf = p.paragraph_format
182
+ height += lines * 12 + (pf.space_before or 0) / 12700 + (pf.space_after or 0) / 12700
183
+ return max(1, math.ceil(height / 743)) # 10.32in usable = 743pt
184
+
185
+
186
+ def count_pages(docx_bytes: bytes) -> int:
187
+ return _count_pages_libreoffice(docx_bytes) or _estimate_pages(docx_bytes)
188
+
189
+
190
+ def _resume_issues(markdown_text: str, docx_bytes: bytes, profile: str, jd: str) -> list[str]:
191
+ issues = []
192
+ pages = count_pages(docx_bytes)
193
+ if pages > 1:
194
+ issues.append(
195
+ f"The resume renders on {pages} pages; it MUST fit on exactly 1 page. Cut the least "
196
+ "JD-relevant bullets, projects and volunteer roles, and shorten long bullets."
197
+ )
198
+ if "[ADD METRIC" in markdown_text:
199
+ issues.append("Remove every [ADD METRIC ...] placeholder; use only numbers from the documents or omit the figure.")
200
+ if jd.strip():
201
+ rep = keyword_report(jd, profile, markdown_text)
202
+ if rep["coverage"] < COVERAGE_TARGET and rep["missing"]:
203
+ issues.append(
204
+ f"Keyword coverage is {rep['coverage']:.0%}, below 90%. These job-description terms ARE "
205
+ f"supported by the candidate documents but missing from the resume: {', '.join(rep['missing'])}. "
206
+ "Work them into the Skills lines or relevant bullets."
207
+ )
208
+ if rep["invented"]:
209
+ issues.append(
210
+ "These job-description terms appear in the resume but are NOT in the candidate documents; "
211
+ f"remove them: {', '.join(rep['invented'])}."
212
+ )
213
+ return issues
214
+
215
+
216
+ # ── Pipeline ─────────────────────────────────────────────────────────────────
217
+
218
+ def _response_text(response) -> str:
219
+ # .text handles both plain-string and list-of-blocks content shapes
220
+ if hasattr(response, "text"):
221
+ return str(response.text)
222
+ if hasattr(response, "content"):
223
+ return str(response.content)
224
+ return str(response)
225
+
226
+
227
+ def generate_resume_docx(profile_data: str, job_description: str, llm) -> bytes:
228
+ """Draft a resume with the LLM, render it, and repair it until it passes the checks."""
229
+ t0 = time.monotonic()
230
+ callbacks = get_callbacks()
231
+
232
+ from config import get_settings
233
+ candidate_name = get_settings(require_api_key=False).candidate_name
234
+
235
+ messages = [
236
+ SystemMessage(content=_load_prompt()),
237
+ HumanMessage(content=(
238
+ f"Generate a complete one-page ATS-optimised resume for {candidate_name}.\n\n"
239
+ f"<candidate_documents>\n{profile_data}\n</candidate_documents>\n\n"
240
+ f"<job_description>\n{job_description}\n</job_description>"
241
+ )),
242
+ ]
243
+ config = {"callbacks": callbacks, "run_name": "resume-generation",
244
+ "metadata": {"candidate": candidate_name, "langfuse_tags": ["resume"]}}
245
+
246
+ best: tuple[int, bytes] | None = None
247
+ for attempt in range(1, MAX_ATTEMPTS + 1):
248
+ t_llm = time.monotonic()
249
+ raw_text = _response_text(llm.invoke(messages, config=config))
250
+ logger.info("[resume %d/%d] LLM responded β€” %.1fs, %d chars (model=%s)",
251
+ attempt, MAX_ATTEMPTS, time.monotonic() - t_llm, len(raw_text), RESUME_MODEL)
252
+
253
+ markdown_text = _clean_markdown(raw_text)
254
+ if not markdown_text.strip():
255
+ if attempt < MAX_ATTEMPTS:
256
+ logger.warning("[resume %d/%d] empty response; retrying", attempt, MAX_ATTEMPTS)
257
+ continue
258
+ raise ValueError(
259
+ "The model returned an empty response. "
260
+ "The free model may be rate-limited β€” try again in a moment, or switch to a paid model."
261
+ )
262
+
263
+ docx_bytes = _build_docx(markdown_text)
264
+ issues = _resume_issues(markdown_text, docx_bytes, profile_data, job_description)
265
+ if best is None or len(issues) < best[0]:
266
+ best = (len(issues), docx_bytes)
267
+ if not issues:
268
+ break
269
+ logger.info("[resume %d/%d] %d issue(s): %s", attempt, MAX_ATTEMPTS, len(issues), " | ".join(issues))
270
+ messages += [
271
+ AIMessage(content=raw_text),
272
+ HumanMessage(content=(
273
+ "Fix these problems and output the full corrected resume in the same format "
274
+ "(resume only, no commentary):\n- " + "\n- ".join(issues)
275
+ )),
276
+ ]
277
+
278
+ logger.info("[resume] done β€” docx=%d bytes, remaining issues=%d, total=%.1fs",
279
+ len(best[1]), best[0], time.monotonic() - t0)
280
+ return best[1]
281
+
282
+
283
+ # ── Document helpers ──────────────────────────────────────────────────────────
284
+
285
+ _INLINE = re.compile(
286
+ r"\[(?P<label>[^\]]+)\]\((?P<url>(?:https?://|mailto:)[^)\s]+)\)"
287
+ r"|(?P<bare>https?://[^\s,;|]+)"
288
+ r"|(?P<mail>[\w.+-]+@[\w-]+(?:\.[\w-]+)+)"
289
+ )
290
+
291
+
292
+ def _add_hyperlink(para, text: str, url: str, size: Pt) -> None:
293
+ rid = para.part.relate_to(
294
+ url, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",
295
+ is_external=True,
296
+ )
297
+ link = OxmlElement("w:hyperlink")
298
+ link.set(qn("r:id"), rid)
299
+ run = para.add_run(text)
300
+ run.font.name, run.font.size = _FONT, size
301
+ run.font.color.rgb = _LINK
302
+ run.font.underline = True
303
+ link.append(run._r)
304
+ para._p.append(link)
305
+
306
+
307
+ def _run(para, text: str, *, size: Pt, bold=False, italic=False) -> None:
308
+ """Add text, turning [label](url), bare URLs and emails into real hyperlinks."""
309
+ pos = 0
310
+ for m in _INLINE.finditer(text):
311
+ if m.start() > pos:
312
+ _plain(para, text[pos:m.start()], size, bold, italic)
313
+ if m.group("label"):
314
+ _add_hyperlink(para, m.group("label"), m.group("url"), size)
315
+ elif m.group("bare"):
316
+ url = m.group("bare").rstrip(".)")
317
+ _add_hyperlink(para, url, url, size)
318
+ _plain(para, m.group("bare")[len(url):], size, bold, italic)
319
+ else:
320
+ _add_hyperlink(para, m.group("mail"), "mailto:" + m.group("mail"), size)
321
+ pos = m.end()
322
+ if pos < len(text):
323
+ _plain(para, text[pos:], size, bold, italic)
324
+
325
+
326
+ def _plain(para, text: str, size: Pt, bold: bool, italic: bool) -> None:
327
+ r = para.add_run(text)
328
+ r.font.name = _FONT
329
+ r._r.get_or_add_rPr().rFonts.set(qn("w:eastAsia"), _FONT)
330
+ r.font.size = size
331
+ r.font.bold = bold
332
+ r.font.italic = italic
333
+ r.font.color.rgb = _BLACK
334
+
335
+
336
+ def _para(doc: Document, *, before=0, after=0, align=None, line=_LINE):
337
+ p = doc.add_paragraph()
338
+ pf = p.paragraph_format
339
+ pf.space_before, pf.space_after = Pt(before), Pt(after)
340
+ pf.line_spacing_rule, pf.line_spacing = WD_LINE_SPACING.EXACTLY, line
341
+ if align is not None:
342
+ p.alignment = align
343
+ return p
344
+
345
+
346
+ def _add_name(doc: Document, text: str) -> None:
347
+ p = _para(doc, after=1.9, align=WD_ALIGN_PARAGRAPH.CENTER, line=Pt(18))
348
+ _run(p, text.strip(), size=Pt(16), bold=True)
349
+
350
+
351
+ def _add_contact(doc: Document, text: str) -> None:
352
+ p = _para(doc, after=3.9, align=WD_ALIGN_PARAGRAPH.CENTER, line=Pt(11))
353
+ _run(p, text.strip(), size=Pt(9))
354
+
355
+
356
+ def _add_section_heading(doc: Document, text: str) -> None:
357
+ p = _para(doc, before=6, after=2.9, line=Pt(13))
358
+ _run(p, text.strip().upper(), size=Pt(11), bold=True)
359
+ pBdr = OxmlElement("w:pBdr")
360
+ bottom = OxmlElement("w:bottom")
361
+ for k, v in (("val", "single"), ("sz", "6"), ("space", "1"), ("color", "000000")):
362
+ bottom.set(qn(f"w:{k}"), v)
363
+ pBdr.append(bottom)
364
+ p._p.get_or_add_pPr().append(pBdr)
365
+
366
+
367
+ def _add_row(doc: Document, text: str, *, bold: bool, italic: bool = False) -> None:
368
+ """`left | right` β†’ left text with the right part flush to the right margin."""
369
+ left, sep, right = text.strip().rpartition(" | ")
370
+ if not sep:
371
+ left, right = right, ""
372
+ p = _para(doc, before=1.5 if bold else 0)
373
+ p.paragraph_format.keep_with_next = True
374
+ p.paragraph_format.tab_stops.add_tab_stop(_TEXT_WIDTH, WD_TAB_ALIGNMENT.RIGHT)
375
+ _run(p, left, size=Pt(10), bold=bold, italic=italic)
376
+ if right:
377
+ _run(p, "\t" + right, size=Pt(10), italic=italic)
378
+
379
+
380
+ def _add_bullet(doc: Document, text: str) -> None:
381
+ p = _para(doc)
382
+ pf = p.paragraph_format
383
+ pf.left_indent, pf.first_line_indent = _BULLET_INDENT, -_BULLET_HANG
384
+ pf.tab_stops.add_tab_stop(_BULLET_INDENT)
385
+ _run(p, "β€’\t" + text.strip(), size=Pt(10))
386
+
387
+
388
+ def _add_body(doc: Document, text: str) -> None:
389
+ """Body line; a leading `Label:` is bolded (Skills lines)."""
390
+ p = _para(doc)
391
+ label, sep, rest = text.strip().partition(":")
392
+ if sep and 0 < len(label) <= 40 and "http" not in label:
393
+ _run(p, label + ":", size=Pt(10), bold=True)
394
+ _run(p, rest, size=Pt(10))
395
+ else:
396
+ _run(p, text.strip(), size=Pt(10))
397
+
398
+
399
+ def _configure_document(doc: Document) -> None:
400
+ for section in doc.sections:
401
+ section.page_width, section.page_height = Inches(8.5), Inches(11)
402
+ section.top_margin = section.bottom_margin = _MARGIN_TB
403
+ section.left_margin = section.right_margin = _MARGIN_LR
404
+ normal = doc.styles["Normal"]
405
+ normal.font.name = _FONT
406
+ normal.font.size = Pt(10)
407
+
408
+
409
+ # ── Core parser ───────────────────────────────────────────────────────────────
410
+
411
+ def _build_docx(markdown_text: str) -> bytes:
412
+ """Pure function: structured Markdown resume β†’ .docx bytes.
413
+
414
+ The format contract is defined in skills/generate-resume.md; this function
415
+ is the corresponding decoder.
416
+ """
417
+ doc = Document()
418
+ _configure_document(doc)
419
+
420
+ # Remove the default blank paragraph python-docx may start with.
421
+ if doc.paragraphs and not doc.paragraphs[0].text.strip():
422
+ p = doc.paragraphs[0]
423
+ p._element.getparent().remove(p._element)
424
+
425
+ found_name = False
426
+ expect_contact = False # True immediately after the H1 name line
427
+ in_skills = False
428
+
429
+ # Models sometimes drop the "# " on the name; treat a plain first line as the name.
430
+ first = next((l.strip() for l in markdown_text.splitlines() if l.strip()), "")
431
+ if first and not first.startswith("#") and "|" not in first and "@" not in first and len(first) < 60:
432
+ markdown_text = markdown_text.replace(first, "# " + first, 1)
433
+
434
+ for line in markdown_text.splitlines():
435
+ stripped = line.strip()
436
+
437
+ if not stripped:
438
+ expect_contact = False
439
+ continue
440
+
441
+ if stripped.startswith("# ") and not found_name:
442
+ _add_name(doc, stripped[2:])
443
+ found_name = True
444
+ expect_contact = True
445
+ continue
446
+
447
+ if expect_contact and not stripped.startswith("#"):
448
+ _add_contact(doc, stripped)
449
+ expect_contact = False
450
+ continue
451
+
452
+ expect_contact = False
453
+
454
+ if stripped.startswith("## "):
455
+ in_skills = "skill" in stripped.lower()
456
+ _add_section_heading(doc, stripped[3:])
457
+ elif stripped.startswith("#### "):
458
+ _add_row(doc, stripped[5:], bold=False, italic=True)
459
+ elif stripped.startswith("### "):
460
+ _add_row(doc, stripped[4:], bold=True)
461
+ elif stripped.startswith(("- ", "* ")):
462
+ (_add_body if in_skills else _add_bullet)(doc, stripped[2:])
463
+ else:
464
+ _add_body(doc, stripped)
465
+
466
+ buf = BytesIO()
467
+ doc.save(buf)
468
+ return buf.getvalue()
skills/generate-resume.md ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Resume Generator Skill
2
+
3
+ You are an expert resume writer and ATS optimisation specialist. Produce a
4
+ ONE-PAGE, ATS-compliant resume tailored to the job description, using only the
5
+ candidate documents as the source of truth, in the exact Markdown format the
6
+ document builder expects.
7
+
8
+ ## Keyword coverage rule (highest priority)
9
+
10
+ Before writing, extract every meaningful technical keyword, tool, protocol,
11
+ methodology and role-specific term from the job description. Your resume MUST
12
+ surface at least 90% of those the candidate documents honestly support, using
13
+ the job description's own wording where the candidate has the skill (for
14
+ example write "Model Context Protocol (MCP)" or "Retrieval-Augmented
15
+ Generation (RAG)" if that is how the job description says it).
16
+ Place them in the Skills lines, and inside experience/project bullets where the
17
+ work really involved them. If a keyword has no support in the candidate
18
+ documents, leave it out: never add it to Skills "to match".
19
+
20
+ ## Tailoring rules (what makes it job-aligned, not just keyword-stuffed)
21
+
22
+ - Order the Skills lines, and the items inside each line, so the terms the job
23
+ description asks for come first. Rename the three category labels if a
24
+ better-fitting label is supported (e.g. "Agentic AI & GenAI").
25
+ - Within each role, put the bullets most relevant to the job description first,
26
+ and reword them to emphasise the matching technologies and outcomes.
27
+ - Keep every role, but trim the least relevant bullets to fit one page.
28
+ Choose which Volunteer and Project entries to keep by relevance to the job.
29
+ - Reuse the real numbers from the documents (percentages, accuracy, counts).
30
+ Never invent a number.
31
+
32
+ ## Strict output rules
33
+
34
+ 1. Output ONLY the resume. No preamble, no explanation, no closing note, no code fences.
35
+ 2. No markdown bold (`**`), italics, code spans or tables anywhere.
36
+ 3. No first-person pronouns (I, me, my).
37
+ 4. No placeholders such as [ADD METRIC]. If a number is not in the documents, write the bullet without one.
38
+ 5. Follow the exact structure below; the formatter parses it line by line.
39
+ 6. The result MUST fit on one US Letter page (0.44in side margins, 10pt Times New Roman).
40
+
41
+ ## Line length
42
+
43
+ - Full-width lines: 120 characters maximum.
44
+ - Bullets: 115 characters maximum including the leading "- ". Split or shorten longer ones.
45
+ - Skills lines may wrap to two rendered lines; keep each category under 330 characters.
46
+ - Row lines (`### Left | Right`): keep Left + Right under 120 characters.
47
+
48
+ ## Required output format
49
+
50
+ ```
51
+ # Full Name
52
+ City, State | [Email](mailto:email) | Phone | [LinkedIn](url) | [GitHub](url)
53
+
54
+ ## Skills
55
+ - Category Label: item, item, item
56
+ - Category Label: item, item, item
57
+ - Category Label: item, item, item
58
+
59
+ ## Experience
60
+ ### Company - Job Title, City, State | Month Year – Month Year
61
+ - Past-tense action verb, what was built, with technologies and a real metric.
62
+
63
+ ## Volunteer Experiences & Leadership
64
+ ### Organisation: Role | Remote | Month Year – Month Year
65
+ - Bullet.
66
+
67
+ ## Projects
68
+ ### Project Name https://github.com/user/repo | Month Year
69
+ - Bullet naming impact and key technologies.
70
+
71
+ ## Awards & Honors
72
+ - Award or publication title | Month Year
73
+ - Award sentence.
74
+
75
+ ## Education
76
+ ### University Name | City, Country
77
+ #### Degree, Major | Month Year
78
+ ```
79
+
80
+ Details:
81
+
82
+ - `### Left | Right`: everything after the LAST " | " is pushed to the right margin
83
+ (dates, or location for education). Anything before it stays bold on the left.
84
+ - `#### Left | Right` is the same row, in italics (used for the degree line).
85
+ - Section order is fixed: Skills, Experience, Volunteer Experiences & Leadership,
86
+ Projects, Awards & Honors, Education. Omit a section only if the documents
87
+ have nothing for it.
88
+ - Experience roles in reverse-chronological order, 3-4 bullets each, every bullet
89
+ starting with a strong past-tense verb (Built, Deployed, Reduced, Engineered...).
90
+ - Contact line: keep exactly the details found in the documents, with the
91
+ LinkedIn and GitHub URLs as `[LinkedIn](url)` / `[GitHub](url)` links.
92
+ Keep the name's wording; no blank line between name and contact line.
93
+ - Skills: exactly three labelled lines taken from the candidate's own skills
94
+ (e.g. ML & GenAI / Languages & Frameworks / MLOps, Cloud & Data).
95
+ - Awards: one line per item, trailing " | Month Year" is not required.
96
+
97
+ ## Grounding rules
98
+
99
+ These override everything else:
100
+
101
+ - The candidate documents are the only source of truth about the candidate.
102
+ Never invent employers, titles, dates, metrics, technologies or outcomes.
103
+ - The job description describes what the employer wants, not what the
104
+ candidate has. A requirement is never evidence of a skill the candidate has.
105
+ Requirements such as security clearance, citizenship or degrees the
106
+ candidate lacks are NOT mentioned.
107
+ - If no job description is provided, produce the best general resume from the
108
+ documents alone and skip the keyword step.
tests/test_resume.py ADDED
@@ -0,0 +1,491 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Rigorous tests for resume.py β€” ATS format rules, document structure, pipeline."""
2
+
3
+ from io import BytesIO
4
+ from unittest.mock import MagicMock
5
+
6
+ import pytest
7
+ from docx import Document
8
+ from docx.enum.text import WD_ALIGN_PARAGRAPH
9
+ from docx.shared import Pt
10
+
11
+ from resume import _build_docx, _strip_code_fence, generate_resume_docx
12
+
13
+ # ── Fixtures ──────────────────────────────────────────────────────────────────
14
+
15
+ FULL_MARKDOWN = """\
16
+ # Jane Smith
17
+ jane@example.com | +1 555-000-0000 | New York, NY | linkedin.com/in/jane
18
+
19
+ ## Summary
20
+ Experienced software engineer with 5 years building scalable distributed systems.
21
+
22
+ ## Skills
23
+ - Languages: Python, Go, TypeScript
24
+ - Infrastructure: AWS, Docker, Kubernetes, PostgreSQL
25
+
26
+ ## Experience
27
+
28
+ ### Senior Software Engineer β€” Acme Corp | Jan 2022 – Present
29
+ - Led migration of monolith to microservices, reducing p99 latency by 40%
30
+ - Built CI/CD pipeline with GitHub Actions serving 50 engineers
31
+
32
+ ### Software Engineer β€” Beta Inc | Jun 2019 – Dec 2021
33
+ - Developed REST APIs handling 1M daily requests
34
+ - Mentored 3 junior engineers through onboarding
35
+
36
+ ## Education
37
+
38
+ ### B.S. Computer Science β€” State University | 2019
39
+ - Dean's List, GPA 3.9
40
+
41
+ ## Projects
42
+
43
+ ### OpenMetrics Dashboard | 2021
44
+ - Built real-time Prometheus dashboard with Grafana used by 200+ engineers
45
+
46
+ ## Certifications
47
+ - AWS Certified Developer β€” Amazon | 2022
48
+ """.strip()
49
+
50
+ MINIMAL_MARKDOWN = "# John Doe\njohn@example.com"
51
+
52
+ SKILLS_ONLY_MARKDOWN = """\
53
+ # Pat Jones
54
+ pat@example.com | 555-111-2222
55
+
56
+ ## Skills
57
+ - Tools: Git, Linux, Bash
58
+ """.strip()
59
+
60
+
61
+ @pytest.fixture(autouse=True)
62
+ def _no_libreoffice(monkeypatch):
63
+ """Keep unit tests fast: use the estimator; a dedicated test exercises LibreOffice."""
64
+ monkeypatch.setattr("resume._count_pages_libreoffice", lambda _b: None)
65
+
66
+
67
+ def _doc(raw: bytes) -> Document:
68
+ return Document(BytesIO(raw))
69
+
70
+
71
+ # ── Basic output ──────────────────────────────────────────────────────────────
72
+
73
+ def test_returns_bytes():
74
+ assert isinstance(_build_docx(FULL_MARKDOWN), bytes)
75
+
76
+
77
+ def test_non_empty_output():
78
+ assert len(_build_docx(FULL_MARKDOWN)) > 1000
79
+
80
+
81
+ def test_empty_markdown_does_not_crash():
82
+ result = _build_docx("")
83
+ _doc(result) # must not raise
84
+
85
+
86
+ def test_minimal_markdown_does_not_crash():
87
+ result = _build_docx(MINIMAL_MARKDOWN)
88
+ doc = _doc(result)
89
+ assert any("John Doe" in p.text for p in doc.paragraphs)
90
+
91
+
92
+ # ── ATS hard rules ────────────────────────────────────────────────────────────
93
+
94
+ def test_no_tables():
95
+ doc = _doc(_build_docx(FULL_MARKDOWN))
96
+ assert len(doc.tables) == 0, "ATS rule: tables are forbidden"
97
+
98
+
99
+ def test_no_text_in_header():
100
+ doc = _doc(_build_docx(FULL_MARKDOWN))
101
+ for section in doc.sections:
102
+ header_text = " ".join(p.text for p in section.header.paragraphs).strip()
103
+ assert not header_text, "Name/contact must be in the body, not the Word header"
104
+
105
+
106
+ def test_no_text_in_footer():
107
+ doc = _doc(_build_docx(FULL_MARKDOWN))
108
+ for section in doc.sections:
109
+ footer_text = " ".join(p.text for p in section.footer.paragraphs).strip()
110
+ assert not footer_text, "Content must be in the body, not the Word footer"
111
+
112
+
113
+ def test_no_inline_images():
114
+ # Inline images appear as <a:blip> elements; a proper text-only resume has none.
115
+ from lxml import etree
116
+ doc = _doc(_build_docx(FULL_MARKDOWN))
117
+ xml = etree.tostring(doc.element)
118
+ assert b"a:blip" not in xml, "ATS rule: no images allowed"
119
+
120
+
121
+ def test_font_is_template_font():
122
+ doc = _doc(_build_docx(FULL_MARKDOWN))
123
+ for para in doc.paragraphs:
124
+ for run in para.runs:
125
+ if run.text.strip():
126
+ assert run.font.name in ("Times New Roman", None), (
127
+ f"Unexpected font {run.font.name!r} in: {run.text[:40]!r}"
128
+ )
129
+
130
+
131
+ def test_body_font_size_in_range():
132
+ doc = _doc(_build_docx(FULL_MARKDOWN))
133
+ for para in doc.paragraphs:
134
+ for run in para.runs:
135
+ if run.font.size and run.text.strip():
136
+ assert Pt(9) <= run.font.size <= Pt(20), (
137
+ f"Font size {run.font.size / 12700:.1f}pt out of range in: {run.text[:40]!r}"
138
+ )
139
+
140
+
141
+ # ── Name and contact ──────────────────────────────────────────────────────────
142
+
143
+ def test_name_is_first_paragraph():
144
+ doc = _doc(_build_docx(FULL_MARKDOWN))
145
+ first = doc.paragraphs[0]
146
+ assert "Jane Smith" in first.text
147
+
148
+
149
+ def test_name_paragraph_is_centered():
150
+ doc = _doc(_build_docx(FULL_MARKDOWN))
151
+ assert doc.paragraphs[0].alignment == WD_ALIGN_PARAGRAPH.CENTER
152
+
153
+
154
+ def test_name_font_size_at_least_16pt():
155
+ doc = _doc(_build_docx(FULL_MARKDOWN))
156
+ name_para = doc.paragraphs[0]
157
+ assert any(
158
+ r.font.size and r.font.size >= Pt(16)
159
+ for r in name_para.runs
160
+ ), "Name must be at least 16pt"
161
+
162
+
163
+ def test_name_is_bold():
164
+ doc = _doc(_build_docx(FULL_MARKDOWN))
165
+ assert any(r.font.bold for r in doc.paragraphs[0].runs)
166
+
167
+
168
+ def test_contact_line_is_second_paragraph():
169
+ doc = _doc(_build_docx(FULL_MARKDOWN))
170
+ second = doc.paragraphs[1]
171
+ assert "jane@example.com" in second.text
172
+
173
+
174
+ def test_contact_paragraph_is_centered():
175
+ doc = _doc(_build_docx(FULL_MARKDOWN))
176
+ assert doc.paragraphs[1].alignment == WD_ALIGN_PARAGRAPH.CENTER
177
+
178
+
179
+ def test_contact_font_size_is_small():
180
+ doc = _doc(_build_docx(FULL_MARKDOWN))
181
+ contact_para = doc.paragraphs[1]
182
+ for run in contact_para.runs:
183
+ if run.font.size:
184
+ assert run.font.size <= Pt(11), "Contact line should be compact (≀ 11pt)"
185
+
186
+
187
+ # ── Section headings ──────────────────────────────────────────────────────────
188
+
189
+ @pytest.mark.parametrize("section", ["SUMMARY", "SKILLS", "EXPERIENCE", "EDUCATION"])
190
+ def test_required_section_headings_present(section):
191
+ doc = _doc(_build_docx(FULL_MARKDOWN))
192
+ texts = [p.text.upper() for p in doc.paragraphs]
193
+ assert any(section in t for t in texts), f"Section '{section}' not found"
194
+
195
+
196
+ def test_optional_sections_present_when_in_markdown():
197
+ doc = _doc(_build_docx(FULL_MARKDOWN))
198
+ texts = [p.text.upper() for p in doc.paragraphs]
199
+ assert any("PROJECTS" in t for t in texts)
200
+ assert any("CERTIFICATIONS" in t for t in texts)
201
+
202
+
203
+ def test_section_headings_are_bold():
204
+ doc = _doc(_build_docx(FULL_MARKDOWN))
205
+ for para in doc.paragraphs:
206
+ if para.text.strip().upper() in ("SUMMARY", "SKILLS", "EXPERIENCE", "EDUCATION"):
207
+ assert any(r.font.bold for r in para.runs), f"Section heading '{para.text}' must be bold"
208
+
209
+
210
+ def test_section_heading_font_size():
211
+ doc = _doc(_build_docx(FULL_MARKDOWN))
212
+ for para in doc.paragraphs:
213
+ if para.text.strip().upper() in ("SUMMARY", "SKILLS", "EXPERIENCE", "EDUCATION"):
214
+ for run in para.runs:
215
+ if run.font.size:
216
+ assert run.font.size >= Pt(11), "Section headings should be β‰₯ 11pt"
217
+
218
+
219
+ # ── Subsections and bullets ───────────────────────────────────────────────────
220
+
221
+ def test_job_titles_present():
222
+ doc = _doc(_build_docx(FULL_MARKDOWN))
223
+ texts = [p.text for p in doc.paragraphs]
224
+ assert any("Acme Corp" in t for t in texts)
225
+ assert any("Beta Inc" in t for t in texts)
226
+
227
+
228
+ def test_subsections_are_bold():
229
+ doc = _doc(_build_docx(FULL_MARKDOWN))
230
+ for para in doc.paragraphs:
231
+ if "Acme Corp" in para.text or "Beta Inc" in para.text:
232
+ assert any(r.font.bold for r in para.runs), f"Subsection '{para.text}' must be bold"
233
+
234
+
235
+ def test_bullets_start_with_unicode_bullet():
236
+ doc = _doc(_build_docx(FULL_MARKDOWN))
237
+ bullet_paras = [p for p in doc.paragraphs if p.text.startswith("β€’")]
238
+ assert len(bullet_paras) >= 4, f"Expected β‰₯ 4 bullets, got {len(bullet_paras)}"
239
+
240
+
241
+ def test_bullet_font_size():
242
+ doc = _doc(_build_docx(FULL_MARKDOWN))
243
+ for para in doc.paragraphs:
244
+ if para.text.startswith("β€’"):
245
+ for run in para.runs:
246
+ if run.font.size:
247
+ assert Pt(9) <= run.font.size <= Pt(12), (
248
+ f"Bullet font size {run.font.size / 12700:.1f}pt out of range"
249
+ )
250
+
251
+
252
+ def test_bullets_have_left_indent():
253
+ doc = _doc(_build_docx(FULL_MARKDOWN))
254
+ for para in doc.paragraphs:
255
+ if para.text.startswith("β€’"):
256
+ assert para.paragraph_format.left_indent is not None
257
+ assert para.paragraph_format.left_indent > 0
258
+
259
+
260
+ # ── Margins ───────────────────────────────────────────────────────────────────
261
+
262
+ def test_page_margins_match_template():
263
+ from docx.shared import Inches
264
+ doc = _doc(_build_docx(FULL_MARKDOWN))
265
+ for section in doc.sections:
266
+ assert abs(section.top_margin - Inches(0.34)) < 5000
267
+ assert abs(section.left_margin - Inches(0.44)) < 5000
268
+
269
+
270
+ # ── Paragraph ordering ────────────────────────────────────────────────────────
271
+
272
+ def test_section_order_summary_before_experience():
273
+ doc = _doc(_build_docx(FULL_MARKDOWN))
274
+ texts = [p.text.upper() for p in doc.paragraphs]
275
+ summary_idx = next((i for i, t in enumerate(texts) if "SUMMARY" in t), None)
276
+ experience_idx = next((i for i, t in enumerate(texts) if "EXPERIENCE" in t), None)
277
+ assert summary_idx is not None and experience_idx is not None
278
+ assert summary_idx < experience_idx, "Summary must appear before Experience"
279
+
280
+
281
+ def test_section_order_experience_before_education():
282
+ doc = _doc(_build_docx(FULL_MARKDOWN))
283
+ texts = [p.text.upper() for p in doc.paragraphs]
284
+ experience_idx = next((i for i, t in enumerate(texts) if "EXPERIENCE" in t), None)
285
+ education_idx = next((i for i, t in enumerate(texts) if "EDUCATION" in t), None)
286
+ assert experience_idx is not None and education_idx is not None
287
+ assert experience_idx < education_idx, "Experience must appear before Education"
288
+
289
+
290
+ # ── Edge cases ────────────────────────────────────────────────────────────────
291
+
292
+ def test_skills_only_does_not_crash():
293
+ doc = _doc(_build_docx(SKILLS_ONLY_MARKDOWN))
294
+ texts = [p.text for p in doc.paragraphs]
295
+ assert any("Pat Jones" in t for t in texts)
296
+ assert any("Skills" in t.title() for t in texts)
297
+
298
+
299
+ def test_extra_blank_lines_do_not_create_empty_paragraphs_at_start():
300
+ md = "\n\n\n" + FULL_MARKDOWN
301
+ doc = _doc(_build_docx(md))
302
+ assert doc.paragraphs[0].text.strip(), "First paragraph should not be blank"
303
+
304
+
305
+ def test_stray_h1_after_name_is_rendered_as_body():
306
+ md = "# Jane Doe\njane@example.com\n# Stray Heading\n## Summary\nText."
307
+ doc = _doc(_build_docx(md))
308
+ texts = [p.text for p in doc.paragraphs]
309
+ assert any("Stray Heading" in t for t in texts)
310
+
311
+
312
+ # ── LLM pipeline (mocked) ────────────────────────────────────────────────────
313
+
314
+ def _mock_llm(text: str) -> MagicMock:
315
+ mock_llm = MagicMock()
316
+ mock_response = MagicMock()
317
+ mock_response.text = text
318
+ mock_llm.invoke.return_value = mock_response
319
+ return mock_llm
320
+
321
+
322
+ def test_generate_resume_docx_calls_llm_with_both_inputs():
323
+ mock_llm = _mock_llm(FULL_MARKDOWN)
324
+
325
+ result = generate_resume_docx("my profile text", "job description text", mock_llm)
326
+
327
+ assert isinstance(result, bytes)
328
+ mock_llm.invoke.assert_called_once()
329
+ call_args = mock_llm.invoke.call_args[0][0] # list of messages
330
+ assert any("resume" in str(m.content).lower() for m in call_args)
331
+ human_content = call_args[-1].content
332
+ assert "my profile text" in human_content
333
+ assert "job description text" in human_content
334
+
335
+
336
+ def test_generate_resume_docx_returns_valid_docx():
337
+ raw = generate_resume_docx("profile", "jd", _mock_llm(FULL_MARKDOWN))
338
+ doc = _doc(raw)
339
+ assert any("Jane Smith" in p.text for p in doc.paragraphs)
340
+
341
+
342
+ def test_generate_resume_docx_handles_response_without_text_or_content():
343
+ """Object with neither .text nor .content β€” falls back to str()."""
344
+ class _Resp:
345
+ def __str__(self):
346
+ return MINIMAL_MARKDOWN
347
+
348
+ mock_llm = MagicMock()
349
+ mock_llm.invoke.return_value = _Resp()
350
+
351
+ result = generate_resume_docx("profile", "jd", mock_llm)
352
+ assert isinstance(result, bytes)
353
+
354
+
355
+ # ── Code-fence stripping ─────────────────────────────────────────────────────
356
+
357
+ def test_strip_code_fence_plain():
358
+ assert _strip_code_fence("# Jane\njane@x.com") == "# Jane\njane@x.com"
359
+
360
+
361
+ def test_strip_code_fence_removes_backtick_wrapper():
362
+ fenced = "```\n# Jane\njane@x.com\n```"
363
+ assert _strip_code_fence(fenced) == "# Jane\njane@x.com"
364
+
365
+
366
+ def test_strip_code_fence_removes_language_tag():
367
+ fenced = "```markdown\n# Jane\njane@x.com\n```"
368
+ assert _strip_code_fence(fenced) == "# Jane\njane@x.com"
369
+
370
+
371
+ def test_strip_code_fence_no_closing_fence():
372
+ fenced = "```\n# Jane\njane@x.com"
373
+ assert _strip_code_fence(fenced) == "# Jane\njane@x.com"
374
+
375
+
376
+ def test_strip_code_fence_with_preamble_is_unchanged():
377
+ # Preamble outside fence is NOT stripped β€” caller should not pass mixed text
378
+ text = "Here's your resume:\n\n```\n# Jane\n```"
379
+ assert "Here's your resume:" in _strip_code_fence(text)
380
+
381
+
382
+ def test_build_docx_with_fenced_input():
383
+ fenced = "```\n" + FULL_MARKDOWN + "\n```"
384
+ doc = _doc(_build_docx(_strip_code_fence(fenced)))
385
+ assert any("Jane Smith" in p.text for p in doc.paragraphs)
386
+
387
+
388
+ # ── Empty LLM response guard ──────────────────────────────────────────────────
389
+
390
+ def test_generate_resume_docx_raises_on_empty_llm_response():
391
+ with pytest.raises(ValueError, match="empty response"):
392
+ generate_resume_docx("profile", "jd", _mock_llm(""))
393
+
394
+
395
+ def test_generate_resume_docx_raises_on_whitespace_only_response():
396
+ with pytest.raises(ValueError, match="empty response"):
397
+ generate_resume_docx("profile", "jd", _mock_llm(" \n\n "))
398
+
399
+
400
+ # ── Skill file ────────────────────────────────────────────────────────────────
401
+
402
+ def test_resume_skill_file_exists_and_has_content():
403
+ from config import PROJECT_ROOT
404
+ path = PROJECT_ROOT / "skills" / "generate-resume.md"
405
+ assert path.exists(), "skills/generate-resume.md must exist"
406
+ assert len(path.read_text(encoding="utf-8").strip()) > 500
407
+
408
+
409
+ def test_resume_skill_file_forbids_invented_facts():
410
+ from config import PROJECT_ROOT
411
+ text = (PROJECT_ROOT / "skills" / "generate-resume.md").read_text(encoding="utf-8")
412
+ assert "Never invent" in text or "never invent" in text
413
+
414
+
415
+ def test_resume_skill_file_bans_metric_placeholders():
416
+ from config import PROJECT_ROOT
417
+ text = (PROJECT_ROOT / "skills" / "generate-resume.md").read_text(encoding="utf-8")
418
+ assert "No placeholders" in text
419
+
420
+
421
+ def test_resume_skill_file_forbids_markdown_tables():
422
+ from config import PROJECT_ROOT
423
+ text = (PROJECT_ROOT / "skills" / "generate-resume.md").read_text(encoding="utf-8")
424
+ assert "table" in text.lower()
425
+
426
+
427
+ def test_resume_skill_file_requires_keyword_coverage():
428
+ from config import PROJECT_ROOT
429
+ text = (PROJECT_ROOT / "skills" / "generate-resume.md").read_text(encoding="utf-8")
430
+ assert "90%" in text, "Prompt must instruct 90% keyword coverage"
431
+
432
+
433
+ def test_resume_skill_file_has_line_length_guidance():
434
+ from config import PROJECT_ROOT
435
+ text = (PROJECT_ROOT / "skills" / "generate-resume.md").read_text(encoding="utf-8")
436
+ assert "115" in text or "120" in text, "Prompt must specify max chars per line"
437
+
438
+
439
+ # ── Template layout ───────────────────────────────────────────────────────────
440
+
441
+ def test_row_date_is_right_aligned_via_tab():
442
+ doc = _doc(_build_docx(FULL_MARKDOWN))
443
+ row = next(p for p in doc.paragraphs if "Acme Corp" in p.text)
444
+ assert "\t" in row.text and row.text.endswith("Present")
445
+ assert row.paragraph_format.tab_stops[0].alignment is not None
446
+
447
+
448
+ def test_skills_lines_have_no_bullet_and_bold_label():
449
+ doc = _doc(_build_docx(FULL_MARKDOWN))
450
+ line = next(p for p in doc.paragraphs if p.text.startswith("Languages:"))
451
+ assert line.runs[0].font.bold and not line.runs[1].font.bold
452
+
453
+
454
+ def test_markdown_links_become_hyperlinks():
455
+ md = "\n".join(["# A B", "[LinkedIn](https://linkedin.com/in/x) | a@b.com", "## Skills", "- X: y"])
456
+ doc = _doc(_build_docx(md))
457
+ assert len(doc.paragraphs[1]._p.findall(".//" + "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}hyperlink")) == 2
458
+ assert "LinkedIn" in doc.paragraphs[1].text
459
+
460
+
461
+ # ── JD alignment checks ───────────────────────────────────────────────────────
462
+
463
+ def test_keyword_report_flags_missing_and_invented():
464
+ from resume import keyword_report
465
+ jd = "Need LangChain, Neo4j, Docker and RAG experience."
466
+ profile = "Built RAG with LangChain and Docker."
467
+ rep = keyword_report(jd, profile, "Used LangChain. Also Neo4j.")
468
+ assert set(rep["missing"]) == {"Docker", "RAG"}
469
+ assert rep["invented"] == ["Neo4j"]
470
+
471
+
472
+ def test_retry_loop_repairs_missing_keywords():
473
+ bad = "\n".join(["# A B", "x@y.com", "## Skills", "- Tools: Git"])
474
+ good = bad + ", LangChain"
475
+ llm = MagicMock()
476
+ llm.invoke.side_effect = [MagicMock(text=bad), MagicMock(text=good)]
477
+ out = generate_resume_docx("uses LangChain", "We need LangChain.", llm)
478
+ assert llm.invoke.call_count == 2
479
+ assert "LangChain" in " ".join(p.text for p in _doc(out).paragraphs)
480
+
481
+
482
+ def test_plain_first_line_is_promoted_to_name():
483
+ doc = _doc(_build_docx("Jane Doe\njane@x.com | 555\n## Skills\n- A: b"))
484
+ assert doc.paragraphs[0].alignment == WD_ALIGN_PARAGRAPH.CENTER
485
+ assert doc.paragraphs[0].runs[0].font.size >= Pt(16)
486
+
487
+
488
+ def test_generic_phrases_are_not_flagged_as_invented():
489
+ from resume import keyword_report
490
+ rep = keyword_report("Multi-agent systems, open-source models, AutoGen", "Python", "multi-agent open-source AutoGen")
491
+ assert rep["invented"] == ["AutoGen"]