Spaces:
Running
Running
update pipeline
Browse files- services/__pycache__/cv_pipeline.cpython-312.pyc +0 -0
- services/cv_pipeline.py +270 -56
- test_llm.py +12 -0
services/__pycache__/cv_pipeline.cpython-312.pyc
CHANGED
|
Binary files a/services/__pycache__/cv_pipeline.cpython-312.pyc and b/services/__pycache__/cv_pipeline.cpython-312.pyc differ
|
|
|
services/cv_pipeline.py
CHANGED
|
@@ -1,120 +1,334 @@
|
|
| 1 |
"""
|
| 2 |
-
|
|
|
|
|
|
|
|
|
|
| 3 |
"""
|
| 4 |
|
| 5 |
import io
|
| 6 |
import os
|
| 7 |
import re
|
| 8 |
import json
|
|
|
|
|
|
|
| 9 |
import pdfplumber
|
| 10 |
from docx import Document
|
| 11 |
from docx.oxml.ns import qn
|
| 12 |
-
from transformers import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
|
| 15 |
-
|
| 16 |
|
| 17 |
-
|
| 18 |
-
"
|
| 19 |
-
|
| 20 |
-
device_map="auto",
|
| 21 |
-
dtype="auto",
|
| 22 |
-
token=HF_TOKEN,
|
| 23 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
-
SYSTEM_PROMPT = """You are a CV parser. Extract information and return ONLY raw JSON β no markdown, no backticks, no explanation.
|
| 26 |
|
| 27 |
-
|
| 28 |
-
{
|
| 29 |
-
"contact": { "full_name": str|null, "email": str|null, "phone": str|null, "location": str|null, "linkedin": str|null, "github": str|null },
|
| 30 |
-
"summary": str|null,
|
| 31 |
-
"experience": [{ "company": str|null, "title": str|null, "start_date": str|null, "end_date": str|null, "description": [str] }],
|
| 32 |
-
"education": [{ "institution": str|null, "degree": str|null, "field_of_study": str|null, "start_date": str|null, "end_date": str|null }],
|
| 33 |
-
"skills": [str],
|
| 34 |
-
"certifications": [{ "name": str|null, "issuer": str|null, "date": str|null }],
|
| 35 |
-
"languages": [str]
|
| 36 |
-
}"""
|
| 37 |
|
| 38 |
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
| 42 |
if file_bytes[:4] == b"%PDF":
|
| 43 |
return _from_pdf(file_bytes)
|
| 44 |
if file_bytes[:2] == b"PK":
|
| 45 |
return _from_docx(file_bytes)
|
| 46 |
-
raise ValueError("Unsupported file type. Upload PDF or DOCX.")
|
| 47 |
|
| 48 |
|
| 49 |
-
def _from_pdf(data: bytes) -> str:
|
| 50 |
-
parts = []
|
|
|
|
|
|
|
| 51 |
with pdfplumber.open(io.BytesIO(data)) as pdf:
|
| 52 |
for page in pdf.pages:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
t = page.extract_text(x_tolerance=2, y_tolerance=2)
|
| 54 |
if t:
|
| 55 |
parts.append(t)
|
| 56 |
-
return "\n".join(parts)
|
| 57 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
-
|
|
|
|
| 60 |
doc = Document(io.BytesIO(data))
|
| 61 |
-
parts = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
for child in doc.element.body:
|
| 63 |
tag = child.tag.split("}")[-1]
|
| 64 |
if tag == "p":
|
| 65 |
parts.append("".join(n.text or "" for n in child.iter(qn("w:t"))))
|
| 66 |
elif tag == "tbl":
|
| 67 |
for row in child.iter(qn("w:tr")):
|
| 68 |
-
cells = [
|
|
|
|
|
|
|
|
|
|
| 69 |
parts.append("\t".join(cells))
|
| 70 |
-
return "\n".join(p for p in parts if p.strip())
|
| 71 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
-
# ββ clean βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 74 |
|
| 75 |
def clean(text: str) -> str:
|
| 76 |
text = re.sub(r"-\s*\n\s*", "", text)
|
| 77 |
-
text =
|
| 78 |
-
text =
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
return text.strip()
|
| 81 |
|
| 82 |
|
| 83 |
-
# ββ
|
| 84 |
|
| 85 |
def call_llm(text: str) -> dict:
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
{"role": "user", "content": text},
|
| 89 |
-
]
|
| 90 |
-
|
| 91 |
-
out = llm(
|
| 92 |
-
messages,
|
| 93 |
-
max_new_tokens=2000,
|
| 94 |
-
max_length=None, # suppresses max_length vs max_new_tokens warning
|
| 95 |
-
do_sample=False,
|
| 96 |
-
)
|
| 97 |
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
raw = re.sub(r"^```(?:json)?\s*|\s*```$", "", raw.strip())
|
| 100 |
-
return json.loads(raw)
|
| 101 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
-
|
|
|
|
| 104 |
|
| 105 |
def process(file_bytes: bytes) -> dict:
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
|
|
|
|
|
|
|
| 111 |
|
| 112 |
-
|
|
|
|
| 113 |
|
| 114 |
if __name__ == "__main__":
|
| 115 |
import sys
|
| 116 |
from pathlib import Path
|
| 117 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
path = Path(sys.argv[1])
|
| 119 |
-
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
"""
|
| 2 |
+
CV Parser β CPU-optimised inference (no GPU required).
|
| 3 |
+
|
| 4 |
+
Install:
|
| 5 |
+
pip install pdfplumber python-docx transformers torch accelerate
|
| 6 |
"""
|
| 7 |
|
| 8 |
import io
|
| 9 |
import os
|
| 10 |
import re
|
| 11 |
import json
|
| 12 |
+
import logging
|
| 13 |
+
import time
|
| 14 |
import pdfplumber
|
| 15 |
from docx import Document
|
| 16 |
from docx.oxml.ns import qn
|
| 17 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 18 |
+
import torch
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# ββ Logging βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 22 |
+
|
| 23 |
+
logging.basicConfig(
|
| 24 |
+
level=logging.INFO,
|
| 25 |
+
format="%(asctime)s [%(levelname)-8s] %(message)s",
|
| 26 |
+
datefmt="%H:%M:%S",
|
| 27 |
+
)
|
| 28 |
+
log = logging.getLogger("cv_parser")
|
| 29 |
+
|
| 30 |
+
DIVIDER = "β" * 60
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# ββ CPU optimisation flags ββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 34 |
+
|
| 35 |
+
torch.set_num_threads(os.cpu_count() or 4)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# ββ Constants βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 39 |
+
|
| 40 |
+
MAX_CHARS = 4_000
|
| 41 |
+
MAX_NEW_TOKENS = 400
|
| 42 |
+
HF_TOKEN = os.getenv("HF_TOKEN", "")
|
| 43 |
+
MODEL_ID = "Qwen/Qwen2.5-1.5B-Instruct"
|
| 44 |
+
|
| 45 |
+
SYSTEM_PROMPT = """\
|
| 46 |
+
You are a CV parser. Output ONLY a raw JSON object with this exact schema:
|
| 47 |
+
{"contact":{"full_name":null,"email":null,"phone":null,"location":null},
|
| 48 |
+
"links":{"linkedin":null,"github":null,"portfolio":null,"other":[]},
|
| 49 |
+
"summary":null,
|
| 50 |
+
"experience":[{"company":null,"title":null,"start_date":null,"end_date":null,"description":[]}],
|
| 51 |
+
"education":[{"institution":null,"degree":null,"field_of_study":null,"start_date":null,"end_date":null}],
|
| 52 |
+
"skills":[],"certifications":[{"name":null,"issuer":null,"date":null}],"languages":[]}
|
| 53 |
+
|
| 54 |
+
Rules:
|
| 55 |
+
- links: classify linkedin.comβlinkedin, github.comβgithub, personal siteβportfolio, elseβother[]
|
| 56 |
+
- Do NOT invent URLs absent from the text. Use null/[] when data is missing.
|
| 57 |
+
- Preserve original date formats. No markdown fences, no commentary."""
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
# ββ Model backend (loaded once at startup) ββββββββββββββββββββββββββββββββββββ
|
| 61 |
+
|
| 62 |
+
class _ModelBackend:
|
| 63 |
+
"""
|
| 64 |
+
Wraps tokenizer + model in one object so there is no risk of module-level
|
| 65 |
+
name collisions between the old `llm` pipeline variable and the new
|
| 66 |
+
`tokenizer`/`model` pair when the server hot-reloads.
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
def __init__(self):
|
| 70 |
+
log.info("Loading model %s β¦", MODEL_ID)
|
| 71 |
+
t0 = time.perf_counter()
|
| 72 |
+
|
| 73 |
+
self.tokenizer = AutoTokenizer.from_pretrained(
|
| 74 |
+
MODEL_ID, token=HF_TOKEN or None
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
| 78 |
+
MODEL_ID,
|
| 79 |
+
token=HF_TOKEN or None,
|
| 80 |
+
# bfloat16: Qwen2.5 was trained in bf16 β zero quality loss,
|
| 81 |
+
# halves memory bandwidth vs float32 (~1.8Γ faster on AVX512 CPUs)
|
| 82 |
+
torch_dtype=torch.bfloat16, # keeping torch_dtype as that is standard for transformers despite the warning
|
| 83 |
+
device_map="cpu",
|
| 84 |
+
attn_implementation="eager",
|
| 85 |
+
)
|
| 86 |
+
self.model.eval()
|
| 87 |
+
|
| 88 |
+
# torch.compile is disabled because it compiles lazily on the first
|
| 89 |
+
# generate() call, which currently throws RuntimeErrors on Windows CPU.
|
| 90 |
+
# This prevents the 500 Internal Server Error during STEP 2.
|
| 91 |
+
|
| 92 |
+
log.info("Model ready in %.1fs", time.perf_counter() - t0)
|
| 93 |
+
|
| 94 |
+
def generate(self, text: str) -> str:
|
| 95 |
+
"""Run inference and return the raw decoded output string."""
|
| 96 |
+
messages = [
|
| 97 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 98 |
+
{"role": "user", "content": text},
|
| 99 |
+
]
|
| 100 |
+
inputs = self.tokenizer.apply_chat_template(
|
| 101 |
+
messages,
|
| 102 |
+
add_generation_prompt=True,
|
| 103 |
+
return_tensors="pt",
|
| 104 |
+
return_dict=True,
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
with torch.no_grad(), torch.inference_mode():
|
| 108 |
+
output_ids = self.model.generate(
|
| 109 |
+
**inputs,
|
| 110 |
+
max_new_tokens=MAX_NEW_TOKENS,
|
| 111 |
+
do_sample=False,
|
| 112 |
+
repetition_penalty=1.1,
|
| 113 |
+
pad_token_id=self.tokenizer.eos_token_id,
|
| 114 |
+
use_cache=True,
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
# Slice off the prompt tokens β decode only what the model generated
|
| 118 |
+
new_tokens = output_ids[0][inputs["input_ids"].shape[-1]:]
|
| 119 |
+
return self.tokenizer.decode(new_tokens, skip_special_tokens=True)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
# Singleton β initialised once when the module is first imported
|
| 123 |
+
_backend = _ModelBackend()
|
| 124 |
|
| 125 |
|
| 126 |
+
# ββ URL helpers βββββββββββββββββββββββββοΏ½οΏ½οΏ½βββββββββββββββββββββββββββββββββββββ
|
| 127 |
|
| 128 |
+
_URL_RE = re.compile(
|
| 129 |
+
r"https?://[^\s,;\"'<>()\[\]]+|(?:www\.)[a-zA-Z0-9\-]+\.[a-zA-Z]{2,}[^\s,;\"'<>()\[\]]*",
|
| 130 |
+
re.I,
|
|
|
|
|
|
|
|
|
|
| 131 |
)
|
| 132 |
+
_LINKEDIN_RE = re.compile(r"linkedin\.com", re.I)
|
| 133 |
+
_GITHUB_RE = re.compile(r"github\.com", re.I)
|
| 134 |
+
# Schemes that are not navigable URLs and must never be classified as links
|
| 135 |
+
_SKIP_SCHEMES = re.compile(r"^(mailto|tel|sms|fax|callto):", re.I)
|
| 136 |
|
|
|
|
| 137 |
|
| 138 |
+
def _empty_links() -> dict:
|
| 139 |
+
return {"linkedin": None, "github": None, "portfolio": None, "other": []}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
|
| 141 |
|
| 142 |
+
def _classify_url(url: str, bucket: dict) -> None:
|
| 143 |
+
url = url.rstrip(".,;)")
|
| 144 |
+
if not url or _SKIP_SCHEMES.match(url): # drop mailto:, tel:, etc.
|
| 145 |
+
return
|
| 146 |
+
if _LINKEDIN_RE.search(url):
|
| 147 |
+
bucket["linkedin"] = bucket["linkedin"] or url
|
| 148 |
+
elif _GITHUB_RE.search(url):
|
| 149 |
+
bucket["github"] = bucket["github"] or url
|
| 150 |
+
else:
|
| 151 |
+
if bucket["portfolio"] is None:
|
| 152 |
+
bucket["portfolio"] = url
|
| 153 |
+
elif url not in bucket["other"]:
|
| 154 |
+
bucket["other"].append(url)
|
| 155 |
|
| 156 |
+
|
| 157 |
+
# ββ File extraction βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 158 |
+
|
| 159 |
+
def extract(file_bytes: bytes) -> tuple[str, dict]:
|
| 160 |
if file_bytes[:4] == b"%PDF":
|
| 161 |
return _from_pdf(file_bytes)
|
| 162 |
if file_bytes[:2] == b"PK":
|
| 163 |
return _from_docx(file_bytes)
|
| 164 |
+
raise ValueError("Unsupported file type. Upload a PDF or DOCX.")
|
| 165 |
|
| 166 |
|
| 167 |
+
def _from_pdf(data: bytes) -> tuple[str, dict]:
|
| 168 |
+
parts: list[str] = []
|
| 169 |
+
pre_links = _empty_links()
|
| 170 |
+
|
| 171 |
with pdfplumber.open(io.BytesIO(data)) as pdf:
|
| 172 |
for page in pdf.pages:
|
| 173 |
+
for h in (page.hyperlinks or []):
|
| 174 |
+
uri = h.get("uri", "")
|
| 175 |
+
if uri:
|
| 176 |
+
_classify_url(uri, pre_links)
|
| 177 |
t = page.extract_text(x_tolerance=2, y_tolerance=2)
|
| 178 |
if t:
|
| 179 |
parts.append(t)
|
|
|
|
| 180 |
|
| 181 |
+
text = "\n".join(parts)
|
| 182 |
+
for url in _URL_RE.findall(text):
|
| 183 |
+
_classify_url(url, pre_links)
|
| 184 |
+
|
| 185 |
+
log.info("STEP 1 β PDF: %d chars | links: %s", len(text), pre_links)
|
| 186 |
+
return text, pre_links
|
| 187 |
|
| 188 |
+
|
| 189 |
+
def _from_docx(data: bytes) -> tuple[str, dict]:
|
| 190 |
doc = Document(io.BytesIO(data))
|
| 191 |
+
parts: list[str] = []
|
| 192 |
+
pre_links = _empty_links()
|
| 193 |
+
|
| 194 |
+
for hl in doc.element.body.iter(qn("w:hyperlink")):
|
| 195 |
+
r_id = hl.get(qn("r:id"))
|
| 196 |
+
if r_id and r_id in doc.part.rels:
|
| 197 |
+
rel = doc.part.rels[r_id]
|
| 198 |
+
if "hyperlink" in rel.reltype:
|
| 199 |
+
_classify_url(rel.target_ref, pre_links)
|
| 200 |
+
|
| 201 |
for child in doc.element.body:
|
| 202 |
tag = child.tag.split("}")[-1]
|
| 203 |
if tag == "p":
|
| 204 |
parts.append("".join(n.text or "" for n in child.iter(qn("w:t"))))
|
| 205 |
elif tag == "tbl":
|
| 206 |
for row in child.iter(qn("w:tr")):
|
| 207 |
+
cells = [
|
| 208 |
+
"".join(n.text or "" for n in cell.iter(qn("w:tc")))
|
| 209 |
+
for cell in row.iter(qn("w:tc"))
|
| 210 |
+
]
|
| 211 |
parts.append("\t".join(cells))
|
|
|
|
| 212 |
|
| 213 |
+
text = "\n".join(p for p in parts if p.strip())
|
| 214 |
+
for url in _URL_RE.findall(text):
|
| 215 |
+
_classify_url(url, pre_links)
|
| 216 |
+
|
| 217 |
+
log.info("STEP 1 β DOCX: %d chars | links: %s", len(text), pre_links)
|
| 218 |
+
return text, pre_links
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
# ββ Clean βββββββββββββββββββββββββββββββββββββββοΏ½οΏ½οΏ½βββββββββββββββββββββββββββββ
|
| 222 |
+
|
| 223 |
+
_BULLET_RE = re.compile(r"^[\sβ’Β·βͺβΈβΊβΆβ£β¦\-ββ]+", re.MULTILINE)
|
| 224 |
+
_BLANK_RE = re.compile(r"\n{3,}")
|
| 225 |
+
_CONTROL_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f]")
|
| 226 |
+
_MULTI_SP_RE = re.compile(r" +")
|
| 227 |
|
|
|
|
| 228 |
|
| 229 |
def clean(text: str) -> str:
|
| 230 |
text = re.sub(r"-\s*\n\s*", "", text)
|
| 231 |
+
text = _CONTROL_RE.sub("", text)
|
| 232 |
+
text = (
|
| 233 |
+
text
|
| 234 |
+
.replace("\u00a0", " ")
|
| 235 |
+
.replace("\u2013", "-")
|
| 236 |
+
.replace("\u2014", "-")
|
| 237 |
+
.replace("\u2022", "")
|
| 238 |
+
.replace("\u25cf", "")
|
| 239 |
+
)
|
| 240 |
+
text = _BULLET_RE.sub("", text)
|
| 241 |
+
text = _MULTI_SP_RE.sub(" ", text)
|
| 242 |
+
text = _BLANK_RE.sub("\n\n", text)
|
| 243 |
return text.strip()
|
| 244 |
|
| 245 |
|
| 246 |
+
# ββ LLM call ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 247 |
|
| 248 |
def call_llm(text: str) -> dict:
|
| 249 |
+
if len(text) > MAX_CHARS:
|
| 250 |
+
text = text[:MAX_CHARS]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 251 |
|
| 252 |
+
log.info("STEP 2 β LLM input (%d chars)\n%s\n%s\n%s", len(text), DIVIDER, text, DIVIDER)
|
| 253 |
+
|
| 254 |
+
t0 = time.perf_counter()
|
| 255 |
+
raw = _backend.generate(text)
|
| 256 |
+
log.info("STEP 3 β LLM finished in %.1fs", time.perf_counter() - t0)
|
| 257 |
+
log.info("LLM output:\n%s\n%s\n%s", DIVIDER, raw, DIVIDER)
|
| 258 |
+
|
| 259 |
+
# Strip accidental markdown fences
|
| 260 |
raw = re.sub(r"^```(?:json)?\s*|\s*```$", "", raw.strip())
|
|
|
|
| 261 |
|
| 262 |
+
try:
|
| 263 |
+
return json.loads(raw)
|
| 264 |
+
except json.JSONDecodeError as exc:
|
| 265 |
+
log.error("JSON parse failed: %s\nOffending:\n%s", exc, raw[:500])
|
| 266 |
+
raise ValueError(f"LLM returned invalid JSON: {exc}") from exc
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
# ββ Normalize & merge links βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 270 |
+
|
| 271 |
+
def _normalize_llm_links(raw_links) -> dict:
|
| 272 |
+
out = _empty_links()
|
| 273 |
+
if isinstance(raw_links, dict):
|
| 274 |
+
out["linkedin"] = raw_links.get("linkedin") or None
|
| 275 |
+
out["github"] = raw_links.get("github") or None
|
| 276 |
+
out["portfolio"] = raw_links.get("portfolio") or None
|
| 277 |
+
for url in (raw_links.get("other") or []):
|
| 278 |
+
if isinstance(url, str) and url not in out["other"]:
|
| 279 |
+
out["other"].append(url)
|
| 280 |
+
elif isinstance(raw_links, list):
|
| 281 |
+
for url in raw_links:
|
| 282 |
+
if isinstance(url, str):
|
| 283 |
+
_classify_url(url, out)
|
| 284 |
+
return out
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def _merge_links(llm_result: dict, pre_links: dict) -> dict:
|
| 288 |
+
llm_links = _normalize_llm_links(llm_result.get("links"))
|
| 289 |
+
merged = {
|
| 290 |
+
"linkedin": pre_links["linkedin"] or llm_links["linkedin"],
|
| 291 |
+
"github": pre_links["github"] or llm_links["github"],
|
| 292 |
+
"portfolio": pre_links["portfolio"] or llm_links["portfolio"],
|
| 293 |
+
"other": sorted({*llm_links["other"], *pre_links["other"]}),
|
| 294 |
+
}
|
| 295 |
+
llm_result["links"] = merged
|
| 296 |
+
log.info("STEP 4 β Merged links: %s", merged)
|
| 297 |
+
return llm_result
|
| 298 |
|
| 299 |
+
|
| 300 |
+
# ββ Main pipeline βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 301 |
|
| 302 |
def process(file_bytes: bytes) -> dict:
|
| 303 |
+
t_start = time.perf_counter()
|
| 304 |
+
|
| 305 |
+
raw_text, pre_links = extract(file_bytes)
|
| 306 |
+
if not raw_text.strip():
|
| 307 |
+
raise ValueError("No text could be extracted from the document.")
|
| 308 |
+
|
| 309 |
+
cleaned = clean(raw_text)
|
| 310 |
+
result = call_llm(cleaned)
|
| 311 |
+
result = _merge_links(result, pre_links)
|
| 312 |
+
result["raw_text"] = cleaned
|
| 313 |
|
| 314 |
+
log.info("Pipeline complete in %.1fs", time.perf_counter() - t_start)
|
| 315 |
+
return result
|
| 316 |
|
| 317 |
+
|
| 318 |
+
# ββ CLI βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 319 |
|
| 320 |
if __name__ == "__main__":
|
| 321 |
import sys
|
| 322 |
from pathlib import Path
|
| 323 |
|
| 324 |
+
if len(sys.argv) < 2:
|
| 325 |
+
print("Usage: python cv_parser.py <path/to/cv.pdf|.docx>")
|
| 326 |
+
sys.exit(1)
|
| 327 |
+
|
| 328 |
path = Path(sys.argv[1])
|
| 329 |
+
if not path.exists():
|
| 330 |
+
print(f"File not found: {path}")
|
| 331 |
+
sys.exit(1)
|
| 332 |
+
|
| 333 |
+
parsed = process(path.read_bytes())
|
| 334 |
+
print(json.dumps(parsed, indent=2, ensure_ascii=False))
|
test_llm.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
sys.path.append(r"d:\Job\processor")
|
| 3 |
+
|
| 4 |
+
from services.cv_pipeline import call_llm
|
| 5 |
+
|
| 6 |
+
try:
|
| 7 |
+
print("Calling LLM...")
|
| 8 |
+
res = call_llm("This is a dummy CV for testing. My name is John Doe and I work at Google.")
|
| 9 |
+
print("Result:", res)
|
| 10 |
+
except Exception as e:
|
| 11 |
+
import traceback
|
| 12 |
+
traceback.print_exc()
|