Yaoyeeng commited on
Commit
b823bf0
·
verified ·
1 Parent(s): 492c300

Use robust PDF extraction for work experience parsing

Browse files
Files changed (2) hide show
  1. app.py +81 -17
  2. requirements.txt +2 -1
app.py CHANGED
@@ -3,6 +3,8 @@ import html
3
  import json
4
  import os
5
  import re
 
 
6
  import tempfile
7
  import uuid
8
  from pathlib import Path
@@ -10,7 +12,14 @@ from typing import List, Optional, Sequence
10
 
11
  import gradio as gr
12
  from openai import OpenAI
13
- from pypdf import PdfReader
 
 
 
 
 
 
 
14
  from reportlab.lib import colors
15
  from reportlab.lib.enums import TA_RIGHT
16
  from reportlab.lib.pagesizes import A4
@@ -82,9 +91,43 @@ LINE = colors.HexColor("#D9DFEA")
82
  HEADER_HEIGHT = 78 * mm
83
 
84
 
85
- def _extract_pdf_text(path: Path) -> str:
86
- reader = PdfReader(str(path))
87
- return "\n".join(page.extract_text() or "" for page in reader.pages)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
 
89
 
90
  def _clean_pdf_lines(text: str) -> List[str]:
@@ -202,19 +245,7 @@ def _parse_skills(lines: Sequence[str]) -> list:
202
  return parsed
203
 
204
 
205
- def parse_cv_content(path: Optional[str]) -> dict:
206
- if not path:
207
- raise ValueError("Upload a CV PDF first.")
208
-
209
- pdf_path = Path(path)
210
- if not pdf_path.exists():
211
- raise ValueError("Uploaded CV file could not be found.")
212
-
213
- try:
214
- lines = _clean_pdf_lines(_extract_pdf_text(pdf_path))
215
- except Exception as exc:
216
- raise ValueError("Could not read text from the uploaded CV PDF.") from exc
217
-
218
  if len(lines) < 3:
219
  raise ValueError("The uploaded CV does not contain enough readable text.")
220
 
@@ -262,6 +293,39 @@ def parse_cv_content(path: Optional[str]) -> dict:
262
  return content
263
 
264
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265
  def _asset_data_url(path: Path, mime: str) -> str:
266
  data = base64.b64encode(path.read_bytes()).decode("utf-8")
267
  return f"data:{mime};base64,{data}"
 
3
  import json
4
  import os
5
  import re
6
+ import shutil
7
+ import subprocess
8
  import tempfile
9
  import uuid
10
  from pathlib import Path
 
12
 
13
  import gradio as gr
14
  from openai import OpenAI
15
+ try:
16
+ from pypdf import PdfReader
17
+ except Exception:
18
+ PdfReader = None
19
+ try:
20
+ from pdfminer.high_level import extract_text as pdfminer_extract_text
21
+ except Exception:
22
+ pdfminer_extract_text = None
23
  from reportlab.lib import colors
24
  from reportlab.lib.enums import TA_RIGHT
25
  from reportlab.lib.pagesizes import A4
 
91
  HEADER_HEIGHT = 78 * mm
92
 
93
 
94
+ def _extract_pdf_text_candidates(path: Path) -> List[str]:
95
+ candidates = []
96
+
97
+ if PdfReader is not None:
98
+ try:
99
+ reader = PdfReader(str(path))
100
+ candidates.append("\n".join(page.extract_text() or "" for page in reader.pages))
101
+ except Exception:
102
+ pass
103
+
104
+ if pdfminer_extract_text is not None:
105
+ try:
106
+ candidates.append(pdfminer_extract_text(str(path)) or "")
107
+ except Exception:
108
+ pass
109
+
110
+ if shutil.which("pdftotext"):
111
+ try:
112
+ result = subprocess.run(
113
+ ["pdftotext", str(path), "-"],
114
+ check=True,
115
+ capture_output=True,
116
+ text=True,
117
+ timeout=15,
118
+ )
119
+ candidates.append(result.stdout)
120
+ except Exception:
121
+ pass
122
+
123
+ unique = []
124
+ seen = set()
125
+ for text in candidates:
126
+ normalized = text.strip()
127
+ if normalized and normalized not in seen:
128
+ unique.append(normalized)
129
+ seen.add(normalized)
130
+ return unique
131
 
132
 
133
  def _clean_pdf_lines(text: str) -> List[str]:
 
245
  return parsed
246
 
247
 
248
+ def _parse_cv_content_from_lines(lines: Sequence[str]) -> dict:
 
 
 
 
 
 
 
 
 
 
 
 
249
  if len(lines) < 3:
250
  raise ValueError("The uploaded CV does not contain enough readable text.")
251
 
 
293
  return content
294
 
295
 
296
+ def _cv_parse_score(content: dict) -> tuple:
297
+ experience = content.get("experience", [])
298
+ bullet_count = sum(len(item.get("bullets", [])) for item in experience)
299
+ summary_len = len(content.get("summary", ""))
300
+ return (len(experience), bullet_count, summary_len)
301
+
302
+
303
+ def parse_cv_content(path: Optional[str]) -> dict:
304
+ if not path:
305
+ raise ValueError("Upload a CV PDF first.")
306
+
307
+ pdf_path = Path(path)
308
+ if not pdf_path.exists():
309
+ raise ValueError("Uploaded CV file could not be found.")
310
+
311
+ candidates = _extract_pdf_text_candidates(pdf_path)
312
+ if not candidates:
313
+ raise ValueError("Could not read text from the uploaded CV PDF.")
314
+
315
+ parsed_candidates = []
316
+ errors = []
317
+ for text in candidates:
318
+ try:
319
+ parsed_candidates.append(_parse_cv_content_from_lines(_clean_pdf_lines(text)))
320
+ except ValueError as exc:
321
+ errors.append(str(exc))
322
+
323
+ if not parsed_candidates:
324
+ raise ValueError(errors[0] if errors else "Could not parse the uploaded CV PDF.")
325
+
326
+ return max(parsed_candidates, key=_cv_parse_score)
327
+
328
+
329
  def _asset_data_url(path: Path, mime: str) -> str:
330
  data = base64.b64encode(path.read_bytes()).decode("utf-8")
331
  return f"data:{mime};base64,{data}"
requirements.txt CHANGED
@@ -3,4 +3,5 @@ openai>=1.40.0
3
  reportlab>=4.2.0
4
  Pillow>=10.0.0
5
  spaces>=0.37.0
6
- pypdf>=4.3.0
 
 
3
  reportlab>=4.2.0
4
  Pillow>=10.0.0
5
  spaces>=0.37.0
6
+ pypdf>=4.3.0,<5
7
+ pdfminer.six>=20240706