import base64
import html
import json
import os
import re
import shutil
import subprocess
import tempfile
import uuid
from pathlib import Path
from typing import List, Optional, Sequence
import gradio as gr
from openai import OpenAI
try:
from pypdf import PdfReader
except Exception:
PdfReader = None
try:
from pdfminer.high_level import extract_text as pdfminer_extract_text
except Exception:
pdfminer_extract_text = None
from reportlab.lib import colors
from reportlab.lib.enums import TA_RIGHT
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
from reportlab.lib.units import mm
from reportlab.platypus import (
Image,
KeepTogether,
Paragraph,
SimpleDocTemplate,
Spacer,
Table,
TableStyle,
)
try:
import spaces
except Exception:
class _SpacesFallback:
@staticmethod
def GPU(*args, **kwargs):
def decorator(func):
return func
return decorator
spaces = _SpacesFallback()
@spaces.GPU(duration=1)
def zerogpu_startup_check() -> str:
return "ok"
ROOT = Path(__file__).resolve().parent
ASSETS_DIR = ROOT / "assets"
LOGO_PATH = ASSETS_DIR / "lengthwise_logo_blue.png"
WORQ_ENV_PATH = ROOT.parents[2] / ".env"
def load_env_file(path: Path) -> None:
if not path.exists():
return
for raw_line in path.read_text(encoding="utf-8", errors="ignore").splitlines():
line = raw_line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
key = key.strip()
value = value.strip().strip('"').strip("'")
if key and key not in os.environ:
os.environ[key] = value
load_env_file(WORQ_ENV_PATH)
OPENAI_MODEL = os.getenv("OPENAI_MODEL", "gpt-5.4-mini")
PAGE_WIDTH, PAGE_HEIGHT = A4
MARGIN_X = 18 * mm
MARGIN_Y = 18 * mm
NAVY = colors.HexColor("#212936")
BLUE = colors.HexColor("#384F94")
HEADER_BLUE = colors.HexColor("#E5EBFF")
BODY = colors.HexColor("#5A626E")
MUTED = colors.HexColor("#8C949C")
LINE = colors.HexColor("#D9DFEA")
HEADER_HEIGHT = 78 * mm
def _extract_pdf_text_candidates(path: Path) -> List[str]:
candidates = []
if PdfReader is not None:
try:
reader = PdfReader(str(path))
candidates.append("\n".join(page.extract_text() or "" for page in reader.pages))
except Exception:
pass
if pdfminer_extract_text is not None:
try:
candidates.append(pdfminer_extract_text(str(path)) or "")
except Exception:
pass
if shutil.which("pdftotext"):
try:
result = subprocess.run(
["pdftotext", str(path), "-"],
check=True,
capture_output=True,
text=True,
timeout=15,
)
candidates.append(result.stdout)
except Exception:
pass
unique = []
seen = set()
for text in candidates:
normalized = text.strip()
if normalized and normalized not in seen:
unique.append(normalized)
seen.add(normalized)
return unique
def _clean_pdf_lines(text: str) -> List[str]:
return [line.strip() for line in text.splitlines() if line.strip() and not re.fullmatch(r"Page \d+", line.strip())]
def _parse_experience(lines: Sequence[str]) -> list:
month_pattern = (
r"Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|"
r"Aug(?:ust)?|Sep(?:t|tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?"
)
date_pattern = rf"(?:(?:{month_pattern})\s+)?\d{{4}}"
period_re = re.compile(
rf"\b{date_pattern}\s+(?:to|-|–)\s+(?:Present|Current|Now|{date_pattern})"
r"(?:\s*\([^)]*\))?",
re.IGNORECASE,
)
role_tail_re = re.compile(
r"\b((?:(?:Assistant|Associate|Clinical|Deputy|Emergency|Enrolled|Executive|Health|Healthcare|"
r"Inpatient|Intensive|Junior|Lead|Locum|Manager|Medical|Mental|Nurse|Nursing|Operating|"
r"Patient|Radiology|Registered|Senior|Specialist|Staff|Theatre|Ward)\s+){1,8}"
r"(?:Assistant|Associate|Clinician|Executive|Manager|Nurse|Practitioner|Specialist|Supervisor|"
r"Technician|Therapist|Trainee|Ward)(?:\s+(?:I|II|III|IV|V|VI|\d+))?)\b$",
re.IGNORECASE,
)
def split_combined_company_role(before_period: str) -> tuple[str, str]:
before_period = re.sub(r"\s+", " ", before_period).strip(" ,;-–")
if not before_period:
return "", ""
match = role_tail_re.search(before_period)
if match:
company = before_period[: match.start()].strip(" ,;-–")
role = match.group(1).strip(" ,;-–")
if company and role:
return company, role
return "", before_period
def parse_header(header_lines: Sequence[str]) -> tuple[str, str, str]:
header_text = re.sub(r"\s+", " ", " ".join(header_lines)).strip()
match = period_re.search(header_text)
if not match:
return "", "", ""
period = re.sub(r"\s+", " ", match.group(0)).strip()
before_period = header_text[: match.start()].strip()
after_period = header_text[match.end() :].strip()
first_line_has_period = bool(header_lines and period_re.search(header_lines[0]))
if len(header_lines) >= 2 and not first_line_has_period:
company = header_lines[0].strip()
role_parts = [line.strip() for line in header_lines[1:] if line.strip()]
role_text = re.sub(period_re, " ", " ".join(role_parts)).strip()
role = re.sub(r"\s+", " ", " ".join(part for part in [role_text, after_period] if part)).strip()
return company, role, period
company, role = split_combined_company_role(before_period)
if after_period:
role = re.sub(r"\s+", " ", f"{role} {after_period}").strip()
return company, role, period
def starts_next_entry(index: int) -> bool:
line = lines[index].strip()
if not line or line.startswith("-") or line.endswith("."):
return False
if period_re.search(" ".join(lines[index : index + 2])):
return True
lookahead = lines[index + 1 : index + 4]
return any(period_re.search(candidate) for candidate in lookahead)
entries = []
i = 0
while i < len(lines):
if lines[i].startswith("-"):
i += 1
continue
header_lines = []
while i < len(lines) and not lines[i].startswith("-"):
header_lines.append(lines[i])
i += 1
company, role, period = parse_header(header_lines)
if not (company and role and period):
continue
bullets = []
while i < len(lines) and lines[i].startswith("-"):
bullet_parts = [lines[i][1:].strip()]
i += 1
while i < len(lines) and not lines[i].startswith("-"):
if period_re.search(lines[i]) or (starts_next_entry(i) and not lines[i][0].islower()):
break
bullet_parts.append(lines[i])
i += 1
bullets.append(" ".join(part for part in bullet_parts if part).strip())
entries.append({"company": company, "role": role, "period": period, "bullets": bullets})
return entries
def _parse_education(lines: Sequence[str]) -> list:
month_pattern = (
r"Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|"
r"Aug(?:ust)?|Sep(?:t|tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?"
)
date_pattern = rf"(?:(?:{month_pattern})\s+)?\d{{4}}"
period_re = re.compile(
rf"\b{date_pattern}(?:\s*(?:to|-|–)\s*(?:{date_pattern}|Present|Current|Now))?\b",
flags=re.IGNORECASE,
)
entries = []
i = 0
while i < len(lines):
line = lines[i].strip()
if not line:
i += 1
continue
next_line = lines[i + 1].strip() if i + 1 < len(lines) else ""
following_line = lines[i + 2].strip() if i + 2 < len(lines) else ""
line_match = period_re.search(line)
next_match = period_re.search(next_line)
if line_match:
credential = line[: line_match.start()].strip()
if not credential and next_line and not period_re.search(next_line):
credential = next_line
i += 1
period = re.sub(r"\s+", " ", line_match.group(0)).strip()
entries.append(("", credential, period))
i += 1
elif next_match:
school = line
credential = next_line[: next_match.start()].strip()
if not credential and following_line and not period_re.search(following_line):
credential = following_line
i += 1
period = re.sub(r"\s+", " ", next_match.group(0)).strip()
entries.append((school, credential, period))
i += 2
else:
entries.append(("", line, ""))
i += 1
return entries
def _parse_skills(lines: Sequence[str]) -> list:
text = " ".join(lines)
known_skills = [
"Blood-Taking",
"Medication Administration",
"Chemotherapy Administration",
"Wound Care",
"Patient Care",
"Interpersonal Relationships",
]
parsed = [skill for skill in known_skills if skill in text]
return parsed
def _parse_cv_content_from_lines(lines: Sequence[str]) -> dict:
if len(lines) < 3:
raise ValueError("The uploaded CV does not contain enough readable text.")
content = {
"name": lines[0],
"title": lines[1],
"summary": "",
"experience": [],
"education": [],
"skills": [],
"languages": "",
}
try:
exp_idx = lines.index("PROFESSIONAL EXPERIENCE")
edu_idx = lines.index("EDUCATION & QUALIFICATIONS")
except ValueError as exc:
raise ValueError(
"The uploaded CV must contain PROFESSIONAL EXPERIENCE and EDUCATION & QUALIFICATIONS sections."
) from exc
skills_idx = lines.index("CORE HEALTHCARE SKILLS") if "CORE HEALTHCARE SKILLS" in lines else None
languages_idx = lines.index("LANGUAGES") if "LANGUAGES" in lines else None
summary = " ".join(lines[2:exp_idx]).strip()
if not summary:
raise ValueError("Could not find summary text in the uploaded CV.")
content["summary"] = summary
experience = _parse_experience(lines[exp_idx + 1 : edu_idx])
if not experience:
raise ValueError("Could not parse professional experience from the uploaded CV.")
content["experience"] = experience
optional_section_indices = [idx for idx in [skills_idx, languages_idx] if idx is not None and idx > edu_idx]
education_end = min(optional_section_indices) if optional_section_indices else len(lines)
education = _parse_education(lines[edu_idx + 1 : education_end])
content["education"] = education
if skills_idx is not None:
skills_end = languages_idx if languages_idx is not None and languages_idx > skills_idx else len(lines)
content["skills"] = _parse_skills(lines[skills_idx + 1 : skills_end])
if languages_idx is not None and languages_idx + 1 < len(lines):
content["languages"] = lines[languages_idx + 1]
return content
def _cv_parse_score(content: dict) -> tuple:
experience = content.get("experience", [])
bullet_count = sum(len(item.get("bullets", [])) for item in experience)
summary_len = len(content.get("summary", ""))
return (len(experience), bullet_count, summary_len)
def parse_cv_content(path: Optional[str]) -> dict:
if not path:
raise ValueError("Upload a CV PDF first.")
pdf_path = Path(path)
if not pdf_path.exists():
raise ValueError("Uploaded CV file could not be found.")
candidates = _extract_pdf_text_candidates(pdf_path)
if not candidates:
raise ValueError("Could not read text from the uploaded CV PDF.")
parsed_candidates = []
errors = []
for text in candidates:
try:
parsed_candidates.append(_parse_cv_content_from_lines(_clean_pdf_lines(text)))
except ValueError as exc:
errors.append(str(exc))
if not parsed_candidates:
raise ValueError(errors[0] if errors else "Could not parse the uploaded CV PDF.")
return max(parsed_candidates, key=_cv_parse_score)
def _asset_data_url(path: Path, mime: str) -> str:
data = base64.b64encode(path.read_bytes()).decode("utf-8")
return f"data:{mime};base64,{data}"
def pdf_embed(path: Optional[str], height: int = 620) -> str:
if not path:
return empty_cv_embed()
pdf_path = Path(path)
if not pdf_path.exists():
return "
CV PDF is missing.
"
src = _asset_data_url(pdf_path, "application/pdf")
return (
''
)
def empty_cv_embed() -> str:
return (
'Upload a CV PDF to preview it here.
'
)
def empty_generated_preview() -> str:
return (
'Upload a CV PDF before generating a preview.
'
)
def error_generated_preview(message: str) -> str:
return (
''
f"CV parse error: {html.escape(message)}
"
)
def uploaded_cv_embed(cv_file: object) -> str:
if cv_file is None:
return empty_cv_embed()
file_path = Path(cv_file.name if hasattr(cv_file, "name") else str(cv_file))
if not file_path.exists():
raise gr.Error("The uploaded CV file could not be found.")
return pdf_embed(str(file_path))
def normalize_table_rows(rows: object) -> List[List[str]]:
if rows is None:
return []
normalized: List[List[str]] = []
if isinstance(rows, dict):
rows = rows.get("data", [])
for row in rows if isinstance(rows, list) else []:
job_title = ""
company = ""
period = ""
if isinstance(row, dict):
job_title = str(row.get("Job title", row.get("job_title", ""))).strip()
company = str(row.get("Company", row.get("company", ""))).strip()
period = str(row.get("Period", row.get("period", ""))).strip()
elif isinstance(row, (list, tuple)) and len(row) >= 3:
job_title = str(row[0] or "").strip()
company = str(row[1] or "").strip()
period = str(row[2] or "").strip()
elif isinstance(row, (list, tuple)) and len(row) >= 2:
job_title = str(row[0] or "").strip()
period = str(row[1] or "").strip()
if job_title and period:
period = re.sub(r"\s+", " ", period)
normalized.append([job_title, company, period])
return normalized
def editable_table_rows(rows: object) -> List[List[str]]:
if rows is None:
return []
if isinstance(rows, dict):
rows = rows.get("data", [])
editable: List[List[str]] = []
for row in rows if isinstance(rows, list) else []:
if isinstance(row, dict):
editable.append(
[
str(row.get("Job title", row.get("job_title", "")) or "").strip(),
str(row.get("Company", row.get("company", "")) or "").strip(),
str(row.get("Period", row.get("period", "")) or "").strip(),
]
)
elif isinstance(row, (list, tuple)):
values = [str(value or "").strip() for value in row[:3]]
editable.append((values + ["", "", ""])[:3])
return editable
MONTHS = {
"jan": 1,
"january": 1,
"feb": 2,
"february": 2,
"mar": 3,
"march": 3,
"apr": 4,
"april": 4,
"may": 5,
"jun": 6,
"june": 6,
"jul": 7,
"july": 7,
"aug": 8,
"august": 8,
"sep": 9,
"sept": 9,
"september": 9,
"oct": 10,
"october": 10,
"nov": 11,
"november": 11,
"dec": 12,
"december": 12,
}
def _month_year_values(period: str) -> list:
values = []
month_pattern = (
r"Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|"
r"Aug(?:ust)?|Sep(?:t|tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?"
)
for month, year in re.findall(rf"\b({month_pattern})\s+(\d{{4}})\b", period, flags=re.IGNORECASE):
values.append((int(year), MONTHS[month.lower()]))
return values
def period_sort_key(row: Sequence[str]) -> tuple:
period = row[2] if len(row) > 2 else ""
dates = _month_year_values(period)
start = dates[0] if dates else (0, 0)
if re.search(r"\b(?:present|current|now)\b", period, flags=re.IGNORECASE):
end = (9999, 12)
else:
end = dates[-1] if dates else start
return end, start
def sort_rows_by_period_desc(rows: object) -> List[List[str]]:
complete_rows = sort_rows_by_period_desc_for_export(rows)
incomplete_rows = [row for row in editable_table_rows(rows) if not (row[0] and row[2])]
return complete_rows + incomplete_rows
def sort_rows_by_period_desc_for_export(rows: object) -> List[List[str]]:
return sorted(normalize_table_rows(rows), key=period_sort_key, reverse=True)
def add_progression_row(rows: object) -> List[List[str]]:
table_rows = editable_table_rows(rows)
table_rows.append(["", "", ""])
return table_rows
def _row_index(row_number: object, row_count: int) -> int:
try:
index = int(row_number) - 1
except (TypeError, ValueError):
index = row_count - 1
return max(0, min(index, max(row_count - 1, 0)))
def remove_progression_row(rows: object, row_number: object) -> List[List[str]]:
table_rows = editable_table_rows(rows)
if not table_rows:
return table_rows
table_rows.pop(_row_index(row_number, len(table_rows)))
return table_rows
def move_progression_row(rows: object, row_number: object, direction: int) -> List[List[str]]:
table_rows = editable_table_rows(rows)
if len(table_rows) < 2:
return table_rows
index = _row_index(row_number, len(table_rows))
new_index = max(0, min(index + direction, len(table_rows) - 1))
table_rows[index], table_rows[new_index] = table_rows[new_index], table_rows[index]
return table_rows
DATE_RANGE_RE = re.compile(
r"\b(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Sept|Oct|Nov|Dec|"
r"January|February|March|April|June|July|August|September|October|November|December)"
r"\s+\d{4}\s+(?:to|-|–)\s+(?:Present|Current|Now|"
r"(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Sept|Oct|Nov|Dec|"
r"January|February|March|April|June|July|August|September|October|November|December)\s+\d{4})"
r"(?:\s*\([^)]*\))?",
re.IGNORECASE,
)
def parse_career_progression_locally(source_text: str) -> List[List[str]]:
rows: List[List[str]] = []
lines = [line.strip() for line in source_text.splitlines() if line.strip()]
for line in lines:
match = DATE_RANGE_RE.search(line)
if not match:
continue
period = match.group(0).strip()
before_period = re.sub(r"[\s,|–-]+$", "", line[: match.start()]).strip()
parts = [part.strip() for part in before_period.split(",") if part.strip()]
if parts:
rows.append([parts[0], ", ".join(parts[1:]), period])
if rows:
return normalize_table_rows(rows)
for index, line in enumerate(lines):
match = DATE_RANGE_RE.search(line)
if not match:
continue
period = match.group(0).strip()
company = lines[index - 1] if index >= 1 else ""
job_title = lines[index - 2] if index >= 2 else ""
if job_title:
rows.append([job_title, company, period])
return normalize_table_rows(rows)
def _json_from_text(text: str) -> object:
try:
return json.loads(text)
except json.JSONDecodeError:
match = re.search(r"\[[\s\S]*\]", text)
if match:
return json.loads(match.group(0))
raise
def extract_career_progression(source_text: str) -> List[List[str]]:
if not source_text or not source_text.strip():
raise gr.Error("Paste career progression or work-history text before extracting.")
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
raise gr.Error("OPENAI_API_KEY is not set. Add it as a Hugging Face Space secret or local environment variable.")
client = OpenAI(api_key=api_key)
prompt = (
"Extract a career progression table from the pasted CV/work-history text.\n"
"Return strict JSON only, with this exact shape:\n"
'[{"Job title":"Senior Staff Nurse II","Company":"Example Hospital","Period":"Nov 2019 to Present"}]\n\n'
"Rules:\n"
"- Use exactly three keys: Job title, Company, and Period.\n"
"- Copy the job title exactly as written in the pasted text. Do not shorten, normalize, re-rank, or drop suffixes such as I, II, III, Senior, Lead, Assistant, Trainee, or Specialist.\n"
"- For example, if the text says 'Senior Staff Nurse II', return exactly 'Senior Staff Nurse II'. Do not return 'Senior Staff Nurse'.\n"
"- Preserve the company wording exactly where possible.\n"
"- If company is missing or unclear, return an empty string for Company instead of omitting the row.\n"
"- Preserve period wording where possible, but keep the entire period on one line as a single string.\n"
"- A Period must include the complete date range shown in the text, such as 'Nov 2019 to Present' or 'Nov 2019 to Present (6 years 7 months)'.\n"
"- Remove entries only when job title or period is missing.\n"
"- If a company is not provided for a row, infer it only when obvious from nearby text.\n\n"
f"Text:\n{source_text.strip()}"
)
response = client.chat.completions.create(
model=OPENAI_MODEL,
messages=[
{
"role": "system",
"content": "You extract structured CV data. Return valid JSON only, no markdown.",
},
{"role": "user", "content": prompt},
],
temperature=0,
)
content = response.choices[0].message.content or ""
try:
parsed = _json_from_text(content)
except Exception as exc:
fallback_rows = parse_career_progression_locally(source_text)
if fallback_rows:
return sort_rows_by_period_desc(fallback_rows)
raise gr.Error(f"The model did not return valid JSON. Try clearer input. Details: {exc}") from exc
rows = normalize_table_rows(parsed)
if not rows:
fallback_rows = parse_career_progression_locally(source_text)
if fallback_rows:
return sort_rows_by_period_desc(fallback_rows)
raise gr.Error("No Job title and Period rows were found. Try pasting each role with its date range.")
return sort_rows_by_period_desc(rows)
def section_title(title: str) -> str:
return (
''
''
f"{html.escape(title)}"
"
"
)
def build_cv_html(rows: Sequence[Sequence[str]], cv_file: Optional[str] = None) -> str:
if not cv_file:
return empty_generated_preview()
table_rows = normalize_table_rows(list(rows))
try:
cv_content = parse_cv_content(cv_file)
except ValueError as exc:
return error_generated_preview(str(exc))
logo_src = _asset_data_url(LOGO_PATH, "image/png") if LOGO_PATH.exists() else ""
table_html = "".join(
""
f"| {html.escape(job_title)} | "
f"{html.escape(company)} | "
f"{html.escape(period)} | "
"
"
for job_title, company, period in table_rows
)
experience_html = ""
for item in cv_content["experience"]:
bullets = "".join(f"{html.escape(bullet)}" for bullet in item["bullets"])
experience_html += (
''
f'
{html.escape(item["company"])}
'
'
'
f'
{html.escape(item["role"])}
'
f'
{html.escape(item["period"])}'
"
"
f"
"
"
"
)
education_html = ""
for school, credential, period in cv_content["education"]:
school_html = f"{html.escape(school)}
" if school else ""
period_html = f"{html.escape(period)}" if period else ""
education_html += (
''
f"{school_html}"
'
'
f"
{html.escape(credential)}
"
f"{period_html}"
"
"
"
"
)
skill_html = "".join(f"{html.escape(skill)}" for skill in cv_content["skills"])
skills_section = (
f'{section_title("CORE HEALTHCARE SKILLS")}{skill_html}
'
if skill_html
else ""
)
languages_section = (
f'{section_title("LANGUAGES")}{html.escape(cv_content["languages"])}
'
if cv_content["languages"]
else ""
)
return f"""
{section_title("CAREER PROGRESSION")}
| Job title | Company | Period |
{table_html or '| No career progression rows added yet. |
'}
{section_title("PROFESSIONAL EXPERIENCE")}
{experience_html}
{section_title("EDUCATION & QUALIFICATIONS") if education_html else ""}
{education_html}
{skills_section}
{languages_section}
"""
def _styles() -> dict:
base = getSampleStyleSheet()
return {
"name": ParagraphStyle(
"Name",
parent=base["Normal"],
fontName="Helvetica-Bold",
fontSize=18,
leading=22,
textColor=BLUE,
spaceAfter=6,
),
"subtitle": ParagraphStyle(
"Subtitle",
parent=base["Normal"],
fontName="Helvetica",
fontSize=11.5,
leading=15,
textColor=BLUE,
),
"body": ParagraphStyle(
"Body",
parent=base["Normal"],
fontName="Helvetica",
fontSize=10.3,
leading=15,
textColor=BODY,
),
"summary": ParagraphStyle(
"Summary",
parent=base["Normal"],
fontName="Helvetica",
fontSize=10.5,
leading=15,
textColor=BLUE,
),
"section": ParagraphStyle(
"Section",
parent=base["Normal"],
fontName="Helvetica-Bold",
fontSize=14,
leading=17,
textColor=NAVY,
spaceBefore=10,
spaceAfter=8,
),
"company": ParagraphStyle(
"Company",
parent=base["Normal"],
fontName="Helvetica-Bold",
fontSize=12,
leading=14,
textColor=NAVY,
spaceAfter=2,
),
"role": ParagraphStyle(
"Role",
parent=base["Normal"],
fontName="Helvetica",
fontSize=10.5,
leading=13,
textColor=BODY,
),
"period": ParagraphStyle(
"Period",
parent=base["Normal"],
fontName="Helvetica",
fontSize=9,
leading=11,
textColor=MUTED,
alignment=TA_RIGHT,
wordWrap=None,
splitLongWords=False,
),
"table_period": ParagraphStyle(
"TablePeriod",
parent=base["Normal"],
fontName="Helvetica",
fontSize=9.2,
leading=12,
textColor=BODY,
wordWrap=None,
splitLongWords=False,
),
"bullet": ParagraphStyle(
"Bullet",
parent=base["Normal"],
fontName="Helvetica",
fontSize=10,
leading=14,
leftIndent=11,
firstLineIndent=-8,
textColor=BODY,
),
}
def _header(canvas, doc) -> None:
canvas.saveState()
canvas.setFillColor(HEADER_BLUE)
canvas.rect(0, PAGE_HEIGHT - HEADER_HEIGHT, PAGE_WIDTH, HEADER_HEIGHT, stroke=0, fill=1)
canvas.restoreState()
def _no_header(canvas, doc) -> None:
return None
def _section_flowable(title: str, styles: dict) -> Table:
marker = Table([[""]], colWidths=[9], rowHeights=[14])
marker.setStyle(TableStyle([("BACKGROUND", (0, 0), (-1, -1), NAVY)]))
table = Table(
[[marker, Paragraph(title, styles["section"])]],
colWidths=[16, PAGE_WIDTH - (MARGIN_X * 2) - 16],
)
table.setStyle(TableStyle([("VALIGN", (0, 0), (-1, -1), "MIDDLE"), ("LEFTPADDING", (0, 0), (-1, -1), 0)]))
return table
def _entry_flowable(item: dict, styles: dict) -> KeepTogether:
role_period = Paragraph(
f'{html.escape(item["role"])} {html.escape(item["period"])}',
styles["role"],
)
header = Table(
[
[Paragraph(item["company"], styles["company"])],
[role_period],
],
colWidths=[480],
)
header.setStyle(
TableStyle(
[
("VALIGN", (0, 0), (-1, -1), "TOP"),
("LEFTPADDING", (0, 0), (-1, -1), 0),
]
)
)
parts = [header, Spacer(1, 5)]
for bullet in item["bullets"]:
parts.append(Paragraph(f"- {bullet}", styles["bullet"]))
parts.append(Spacer(1, 9))
return KeepTogether(parts)
def _education_flowable(school: str, credential: str, period: str, styles: dict) -> KeepTogether:
credential_text = html.escape(credential)
if period:
credential_text += f' {html.escape(period)}'
rows = []
if school:
rows.append([Paragraph(school, styles["company"])])
if credential_text:
rows.append([Paragraph(credential_text, styles["role"])])
if not rows:
rows.append([Paragraph("", styles["role"])])
table = Table(rows, colWidths=[480])
table.setStyle(
TableStyle(
[
("VALIGN", (0, 0), (-1, -1), "TOP"),
("LEFTPADDING", (0, 0), (-1, -1), 0),
]
)
)
return KeepTogether([table, Spacer(1, 8)])
def generate_pdf(rows: object, cv_file: Optional[str] = None) -> str:
if not cv_file:
raise gr.Error("Upload a CV PDF before generating the edited CV.")
table_rows = normalize_table_rows(rows)
if not table_rows:
raise gr.Error("Add at least one complete Job title, Company, and Period row before generating the PDF.")
try:
cv_content = parse_cv_content(cv_file)
except ValueError as exc:
raise gr.Error(str(exc)) from exc
output_path = Path(tempfile.gettempdir()) / f"generated_cv_{uuid.uuid4().hex[:8]}.pdf"
styles = _styles()
doc = SimpleDocTemplate(
str(output_path),
pagesize=A4,
leftMargin=MARGIN_X,
rightMargin=MARGIN_X,
topMargin=34 * mm,
bottomMargin=MARGIN_Y,
)
story = []
logo = Image(str(LOGO_PATH), width=56 * mm, height=13.35 * mm) if LOGO_PATH.exists() else ""
header_table = Table(
[
[
[Paragraph(cv_content["name"], styles["name"]), Paragraph(cv_content["title"], styles["subtitle"])],
logo,
]
],
colWidths=[PAGE_WIDTH - (MARGIN_X * 2) - 75 * mm, 65 * mm],
)
header_table.setStyle(
TableStyle(
[
("VALIGN", (0, 0), (-1, -1), "TOP"),
("ALIGN", (1, 0), (1, 0), "RIGHT"),
("LEFTPADDING", (0, 0), (-1, -1), 0),
("RIGHTPADDING", (0, 0), (-1, -1), 0),
]
)
)
story.append(header_table)
story.append(Spacer(1, 20))
story.append(Paragraph(cv_content["summary"], styles["summary"]))
story.append(Spacer(1, 42))
story.append(_section_flowable("CAREER PROGRESSION", styles))
progress_table = Table(
[[Paragraph("Job title", styles["company"]), Paragraph("Company", styles["company"]), Paragraph("Period", styles["company"])]]
+ [[Paragraph(job_title, styles["body"]), Paragraph(company, styles["body"]), Paragraph(period, styles["table_period"])] for job_title, company, period in table_rows],
colWidths=[130, 130, 220],
hAlign="LEFT",
)
progress_table.setStyle(
TableStyle(
[
("BACKGROUND", (0, 0), (-1, -1), colors.white),
("BOX", (0, 0), (-1, -1), 0.6, LINE),
("INNERGRID", (0, 0), (-1, -1), 0.4, LINE),
("VALIGN", (0, 0), (-1, -1), "TOP"),
("LEFTPADDING", (0, 0), (-1, -1), 8),
("RIGHTPADDING", (0, 0), (-1, -1), 8),
("TOPPADDING", (0, 0), (-1, -1), 7),
("BOTTOMPADDING", (0, 0), (-1, -1), 7),
]
)
)
story.append(progress_table)
story.append(Spacer(1, 12))
story.append(_section_flowable("PROFESSIONAL EXPERIENCE", styles))
for item in cv_content["experience"]:
story.append(_entry_flowable(item, styles))
if cv_content["education"]:
story.append(_section_flowable("EDUCATION & QUALIFICATIONS", styles))
for school, credential, period in cv_content["education"]:
story.append(_education_flowable(school, credential, period, styles))
skills = cv_content["skills"]
if skills:
story.append(_section_flowable("CORE HEALTHCARE SKILLS", styles))
skill_rows = [[Paragraph(skill, styles["body"]) for skill in skills[i : i + 2]] for i in range(0, len(skills), 2)]
skill_table = Table(skill_rows, colWidths=[235, 235])
skill_table.setStyle(TableStyle([("VALIGN", (0, 0), (-1, -1), "TOP"), ("BOTTOMPADDING", (0, 0), (-1, -1), 5)]))
story.append(skill_table)
story.append(Spacer(1, 8))
if cv_content["languages"]:
story.append(_section_flowable("LANGUAGES", styles))
story.append(Paragraph(cv_content["languages"], styles["body"]))
doc.build(story, onFirstPage=_header, onLaterPages=_no_header)
return str(output_path)
def generate_pdf_download(rows: object, cv_file: Optional[str] = None):
path = generate_pdf(rows, cv_file)
return gr.update(value=path, visible=True), path
def update_preview(rows: object, cv_file: Optional[str] = None) -> str:
return build_cv_html(normalize_table_rows(rows), cv_file)
def refresh_uploaded_cv(cv_file: Optional[str], rows: object) -> tuple:
return uploaded_cv_embed(cv_file), update_preview(rows, cv_file)
def example_rows() -> List[List[str]]:
return [
["Senior Staff Nurse II", "Example Hospital", "Nov 2019 to Present"],
["Staff Nurse", "Example Clinic", "Feb 2018 to Apr 2018"],
["Clinical Attachment", "Example Medical Centre", "Mar 2016 to Apr 2016"],
["Retail Assistant", "Example Retail", "Nov 2013 to Feb 2014"],
]
with gr.Blocks(title="CV Editor") as demo:
gr.Markdown(
"# CV Editor\n"
"Upload a CV PDF as a reference, paste career history, generate a career progression table with OpenAI, "
"then download the regenerated CV PDF."
)
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("## Uploaded CV")
cv_file = gr.File(label="Upload CV PDF", file_types=[".pdf"], type="filepath")
cv_preview = gr.HTML(empty_cv_embed())
with gr.Column(scale=1):
gr.Markdown("## Career Progression")
source_text = gr.Textbox(
label="Paste CV/work-history text",
lines=12,
placeholder="Paste role, company, and date details here. Example: Senior Staff Nurse II, Example Hospital, Nov 2019 to Present",
)
with gr.Row():
extract_btn = gr.Button("Generate table from text", variant="primary")
example_btn = gr.Button("Load sample rows")
progression_table = gr.Dataframe(
headers=["Job title", "Company", "Period"],
datatype=["str", "str", "str"],
type="array",
row_count=(4, "dynamic"),
column_count=3,
label="Review/edit career progression",
interactive=True,
)
with gr.Row():
row_number = gr.Number(label="Row number", value=1, precision=0, minimum=1)
add_row_btn = gr.Button("Add row")
remove_row_btn = gr.Button("Remove row")
with gr.Row():
move_up_btn = gr.Button("Move row up")
move_down_btn = gr.Button("Move row down")
sort_period_btn = gr.Button("Sort newest first")
generate_btn = gr.Button("Generate CV PDF", variant="primary")
output_download = gr.DownloadButton(label="Download generated CV", visible=True)
output_pdf = gr.File(label="Generated CV PDF backup link", visible=True)
gr.Markdown("## Generated CV Preview")
preview = gr.HTML(empty_generated_preview())
cv_file.change(refresh_uploaded_cv, inputs=[cv_file, progression_table], outputs=[cv_preview, preview])
extract_btn.click(extract_career_progression, inputs=source_text, outputs=progression_table).then(
update_preview, inputs=[progression_table, cv_file], outputs=preview
)
example_btn.click(example_rows, outputs=progression_table).then(update_preview, inputs=[progression_table, cv_file], outputs=preview)
progression_table.change(update_preview, inputs=[progression_table, cv_file], outputs=preview)
add_row_btn.click(add_progression_row, inputs=progression_table, outputs=progression_table).then(
update_preview, inputs=[progression_table, cv_file], outputs=preview
)
remove_row_btn.click(remove_progression_row, inputs=[progression_table, row_number], outputs=progression_table).then(
update_preview, inputs=[progression_table, cv_file], outputs=preview
)
move_up_btn.click(
lambda rows, selected_row: move_progression_row(rows, selected_row, -1),
inputs=[progression_table, row_number],
outputs=progression_table,
).then(update_preview, inputs=[progression_table, cv_file], outputs=preview)
move_down_btn.click(
lambda rows, selected_row: move_progression_row(rows, selected_row, 1),
inputs=[progression_table, row_number],
outputs=progression_table,
).then(update_preview, inputs=[progression_table, cv_file], outputs=preview)
sort_period_btn.click(sort_rows_by_period_desc, inputs=progression_table, outputs=progression_table).then(
update_preview, inputs=[progression_table, cv_file], outputs=preview
)
generate_btn.click(generate_pdf_download, inputs=[progression_table, cv_file], outputs=[output_download, output_pdf])
if __name__ == "__main__":
demo.launch()