Eng-Musa commited on
Commit
aa5d8fe
·
1 Parent(s): 860fadf

optimize the cv processor and the matcher

Browse files
__pycache__/main.cpython-312.pyc CHANGED
Binary files a/__pycache__/main.cpython-312.pyc and b/__pycache__/main.cpython-312.pyc differ
 
main.py CHANGED
@@ -1,10 +1,11 @@
1
  from __future__ import annotations
2
 
3
  import tempfile
 
4
  import httpx
5
  from datetime import datetime, timezone
6
  from pathlib import Path
7
- from typing import Any, Optional
8
 
9
  from contextlib import asynccontextmanager
10
 
@@ -20,25 +21,55 @@ from services.cv_converter import CVConverter
20
  from services.job_matcher import JobInput, JobMatcher
21
  from services.workers import CvWorker, QueueManager, CvTask
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  # ---------------------------------------------------------------------------
24
  # App setup
25
  # ---------------------------------------------------------------------------
26
 
27
- converter = CVConverter()
28
- matcher = JobMatcher() # SentenceTransformer loaded once at startup
29
- cv_worker = CvWorker(converter)
30
  queue_manager = QueueManager(cv_worker, concurrency=1)
31
 
 
32
  @asynccontextmanager
33
  async def lifespan(app: FastAPI):
34
  await queue_manager.start()
35
  yield
36
  await queue_manager.stop()
37
 
 
38
  app = FastAPI(
39
  title="Job Processor API",
40
  description="CV parsing, chunking, and job-match prediction service.",
41
- version="2.0.0",
42
  lifespan=lifespan,
43
  )
44
 
@@ -48,96 +79,142 @@ app = FastAPI(
48
  # ---------------------------------------------------------------------------
49
 
50
  class APIResponse(BaseModel):
51
- message: str
52
  statusCode: int
53
- payload: Optional[Any] = None
54
 
 
 
55
  # Exception handlers
 
 
56
  @app.exception_handler(RequestValidationError)
57
  async def validation_exception_handler(request, exc):
58
  return JSONResponse(
59
  status_code=400,
60
  content=APIResponse(
61
  message="Invalid request: " + str(exc.errors()),
62
- statusCode=400
63
- ).model_dump()
64
  )
65
 
 
66
  @app.exception_handler(StarletteHTTPException)
67
  async def http_exception_handler(request, exc):
68
  return JSONResponse(
69
  status_code=exc.status_code,
70
  content=APIResponse(
71
  message=str(exc.detail),
72
- statusCode=exc.status_code
73
- ).model_dump()
74
  )
75
 
 
76
  @app.exception_handler(Exception)
77
  async def global_exception_handler(request, exc):
78
  return JSONResponse(
79
  status_code=500,
80
  content=APIResponse(
81
  message="Internal server error: " + str(exc),
82
- statusCode=500
83
- ).model_dump()
84
  )
85
 
86
 
87
  # ---------------------------------------------------------------------------
88
  # Health check
 
 
89
  @app.get("/", response_model=APIResponse)
90
  def home():
91
  return APIResponse(message="Job Processor API is running", statusCode=200)
92
 
93
 
 
 
 
94
 
95
- # POST /process-cv (synchronous)
96
- _ALLOWED_EXT = (".pdf", ".docx", ".doc")
97
  @app.post("/process-cv", response_model=APIResponse)
98
  async def process_cv(file: UploadFile = File(...)):
99
  """
100
  Upload a CV file (PDF, DOCX, DOC) and receive:
101
  - Raw Markdown text
102
- - Structured chunks (summary, experience, education, skills, projects)
103
  - Detected CV metadata (title, seniority, category, years of experience)
104
- - File metadata (type, method used, page count, warnings)
 
 
 
105
  """
 
 
106
  if not file.filename:
107
  return APIResponse(message="No file uploaded", statusCode=400)
108
 
109
- if not file.filename.lower().endswith(_ALLOWED_EXT):
 
110
  return APIResponse(
111
- message=f"Invalid file format. Allowed formats: {', '.join(_ALLOWED_EXT)}",
112
  statusCode=400,
113
  )
114
 
115
  tmp_path: Optional[Path] = None
 
 
116
  try:
117
- start_time = datetime.now(timezone.utc).isoformat()
118
  file_bytes = await file.read()
119
 
120
- suffix = Path(file.filename).suffix.lower()
121
- with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  tmp.write(file_bytes)
123
  tmp_path = Path(tmp.name)
124
 
 
 
125
  conversion = converter.convert(tmp_path)
 
 
 
126
  if not conversion.success:
127
- return APIResponse(message=conversion.error or "Conversion failed", statusCode=422)
 
 
 
 
 
 
 
 
 
128
 
129
- chunks = chunk_cv(conversion.markdown)
130
- end_time = datetime.now(timezone.utc).isoformat()
131
 
132
  return APIResponse(
133
  message="CV processed successfully",
134
  statusCode=200,
135
  payload={
136
- "markdown": conversion.markdown,
137
- "cv_title": chunks["cv_title"],
138
- "seniority": chunks["seniority"],
139
- "years_experience": chunks["years_experience"],
140
- "category": chunks["category"],
 
 
141
  "chunks": {
142
  "summary": chunks["chunks"]["summary"],
143
  "contact": chunks["chunks"]["contact"],
@@ -148,13 +225,20 @@ async def process_cv(file: UploadFile = File(...)):
148
  "projects": chunks["chunks"]["projects"],
149
  "awards": chunks["chunks"]["awards"],
150
  },
151
- "file_type": conversion.file_type,
152
- "method_used": conversion.method_used,
153
- "is_scanned": conversion.is_scanned,
154
- "page_count": conversion.page_count,
155
- "warnings": conversion.warnings,
156
- "start_time": start_time,
157
- "end_time": end_time,
 
 
 
 
 
 
 
158
  },
159
  )
160
 
@@ -165,19 +249,18 @@ async def process_cv(file: UploadFile = File(...)):
165
  )
166
 
167
  finally:
168
- if tmp_path and tmp_path.exists():
169
- tmp_path.unlink()
 
 
 
 
170
 
171
 
172
  # ---------------------------------------------------------------------------
173
- # POST /process-cv-async (NEW — used by Java async worker)
174
- #
175
- # Accepts the CV file plus job_id and callback_url as form fields.
176
- # Returns 202 immediately and processes the CV in a BackgroundTask.
177
- # On completion (success or failure) POSTs the result to callback_url.
178
  # ---------------------------------------------------------------------------
179
 
180
-
181
  @app.post("/process-cv-async", response_model=APIResponse)
182
  async def process_cv_async(
183
  file: UploadFile = File(...),
@@ -187,22 +270,35 @@ async def process_cv_async(
187
  ):
188
  """
189
  Async entry point called by the Java async worker.
190
- Accepts the CV file + job_id + callback_url as multipart form fields.
191
  Returns 202 immediately; processes the CV in a queued background task.
192
  """
193
  if not file.filename:
194
  return APIResponse(message="No file uploaded", statusCode=400)
195
 
196
- if not file.filename.lower().endswith(_ALLOWED_EXT):
 
197
  return APIResponse(
198
- message=f"Invalid file format. Allowed formats: {', '.join(_ALLOWED_EXT)}",
199
  statusCode=400,
200
  )
201
 
202
- # Read bytes before the background task starts (request closes after response)
203
  file_bytes = await file.read()
204
- filename = file.filename
205
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
  job_store.create_job(job_id)
207
 
208
  task = CvTask(
@@ -210,7 +306,7 @@ async def process_cv_async(
210
  file_bytes=file_bytes,
211
  filename=filename,
212
  callback_url=callback_url,
213
- callback_secret=callback_secret
214
  )
215
 
216
  try:
@@ -219,7 +315,10 @@ async def process_cv_async(
219
  return APIResponse(
220
  message=str(exc),
221
  statusCode=409,
222
- payload={"job_id": job_id, "status": job_store.get_job(job_id)["status"]},
 
 
 
223
  )
224
 
225
  return APIResponse(
@@ -229,13 +328,13 @@ async def process_cv_async(
229
  )
230
 
231
 
232
- # GET /job-status/{job_id} (Python-side status check)
 
 
 
233
  @app.get("/job-status/{job_id}", response_model=APIResponse)
234
  def get_job_status(job_id: str):
235
- """
236
- Returns the current status of a CV processing job from the in-memory store.
237
- Primarily useful for debugging; Java tracks state authoritatively in its DB.
238
- """
239
  job = job_store.get_job(job_id)
240
  if job is None:
241
  return APIResponse(message="Job not found", statusCode=404)
@@ -243,10 +342,7 @@ def get_job_status(job_id: str):
243
  status = job["status"]
244
  if status == "QUEUED":
245
  pos = queue_manager.get_queue_position(job_id)
246
- if pos is not None:
247
- status = f"QUEUE({pos})"
248
- else:
249
- status = "QUEUE(1)"
250
 
251
  return APIResponse(
252
  message=f"Job status: {status}",
@@ -255,29 +351,37 @@ def get_job_status(job_id: str):
255
  )
256
 
257
 
258
- # POST /match-cv (ORIGINAL — unchanged)
 
 
259
 
260
  class MatchCVRequest(BaseModel):
261
  """Request body for POST /match-cv."""
262
  job: JobInput = Field(..., description="Structured job posting to match against.")
263
- cv_markdown: str = Field(..., min_length=20, description="The candidate's CV as a Markdown string.")
 
 
 
 
 
 
 
264
 
265
 
266
  @app.post("/match-cv", response_model=APIResponse)
267
  def match_cv_to_job(payload: MatchCVRequest):
268
  """
269
- Match a Markdown CV against a structured job posting.
270
 
271
- Returns a detailed qualification prediction including:
272
- - Overall match score (0–100 %)
273
- - Match level label (e.g. "Strong Match")
274
- - Per-dimension score breakdown (skill, semantic, title, category, seniority, experience)
275
- - Mismatch analysis and improvement advice
276
  """
277
  try:
278
  result = matcher.predict(
279
  job_json=payload.job.model_dump(),
280
  cv_markdown=payload.cv_markdown,
 
281
  )
282
  return APIResponse(
283
  message="Match prediction completed successfully",
@@ -288,4 +392,63 @@ def match_cv_to_job(payload: MatchCVRequest):
288
  return APIResponse(
289
  message=f"An error occurred during matching: {exc}",
290
  statusCode=500,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
291
  )
 
1
  from __future__ import annotations
2
 
3
  import tempfile
4
+ import uuid
5
  import httpx
6
  from datetime import datetime, timezone
7
  from pathlib import Path
8
+ from typing import Any, List, Optional
9
 
10
  from contextlib import asynccontextmanager
11
 
 
21
  from services.job_matcher import JobInput, JobMatcher
22
  from services.workers import CvWorker, QueueManager, CvTask
23
 
24
+ # ---------------------------------------------------------------------------
25
+ # Configuration
26
+ # ---------------------------------------------------------------------------
27
+
28
+ MAX_FILE_BYTES = 20 * 1024 * 1024 # 20 MB
29
+
30
+ # Magic byte signatures for MIME sniffing
31
+ _MIME_SIGS = {
32
+ b"%PDF": ".pdf",
33
+ b"PK\x03\x04": ".docx", # DOCX (ZIP-based)
34
+ b"\xd0\xcf\x11\xe0": ".doc", # Legacy OLE compound (DOC, XLS)
35
+ }
36
+
37
+ _ALLOWED_EXT = (".pdf", ".docx", ".doc")
38
+
39
+
40
+ def _check_mime(file_bytes: bytes, declared_ext: str) -> bool:
41
+ """Return True when magic bytes agree with the declared extension."""
42
+ sig = file_bytes[:4]
43
+ for magic, expected_ext in _MIME_SIGS.items():
44
+ if sig.startswith(magic):
45
+ # DOCX declared but is actually a ZIP: both .docx and (rarely) .doc
46
+ if expected_ext == ".docx":
47
+ return declared_ext in (".docx", ".doc")
48
+ return declared_ext == expected_ext
49
+ return True # unknown signature — let the converter decide
50
+
51
+
52
  # ---------------------------------------------------------------------------
53
  # App setup
54
  # ---------------------------------------------------------------------------
55
 
56
+ converter = CVConverter()
57
+ matcher = JobMatcher() # SentenceTransformer loaded once at startup
58
+ cv_worker = CvWorker(converter, matcher)
59
  queue_manager = QueueManager(cv_worker, concurrency=1)
60
 
61
+
62
  @asynccontextmanager
63
  async def lifespan(app: FastAPI):
64
  await queue_manager.start()
65
  yield
66
  await queue_manager.stop()
67
 
68
+
69
  app = FastAPI(
70
  title="Job Processor API",
71
  description="CV parsing, chunking, and job-match prediction service.",
72
+ version="3.0.0",
73
  lifespan=lifespan,
74
  )
75
 
 
79
  # ---------------------------------------------------------------------------
80
 
81
  class APIResponse(BaseModel):
82
+ message: str
83
  statusCode: int
84
+ payload: Optional[Any] = None
85
 
86
+
87
+ # ---------------------------------------------------------------------------
88
  # Exception handlers
89
+ # ---------------------------------------------------------------------------
90
+
91
  @app.exception_handler(RequestValidationError)
92
  async def validation_exception_handler(request, exc):
93
  return JSONResponse(
94
  status_code=400,
95
  content=APIResponse(
96
  message="Invalid request: " + str(exc.errors()),
97
+ statusCode=400,
98
+ ).model_dump(),
99
  )
100
 
101
+
102
  @app.exception_handler(StarletteHTTPException)
103
  async def http_exception_handler(request, exc):
104
  return JSONResponse(
105
  status_code=exc.status_code,
106
  content=APIResponse(
107
  message=str(exc.detail),
108
+ statusCode=exc.status_code,
109
+ ).model_dump(),
110
  )
111
 
112
+
113
  @app.exception_handler(Exception)
114
  async def global_exception_handler(request, exc):
115
  return JSONResponse(
116
  status_code=500,
117
  content=APIResponse(
118
  message="Internal server error: " + str(exc),
119
+ statusCode=500,
120
+ ).model_dump(),
121
  )
122
 
123
 
124
  # ---------------------------------------------------------------------------
125
  # Health check
126
+ # ---------------------------------------------------------------------------
127
+
128
  @app.get("/", response_model=APIResponse)
129
  def home():
130
  return APIResponse(message="Job Processor API is running", statusCode=200)
131
 
132
 
133
+ # ---------------------------------------------------------------------------
134
+ # POST /process-cv (synchronous, blocking — intentional during testing)
135
+ # ---------------------------------------------------------------------------
136
 
 
 
137
  @app.post("/process-cv", response_model=APIResponse)
138
  async def process_cv(file: UploadFile = File(...)):
139
  """
140
  Upload a CV file (PDF, DOCX, DOC) and receive:
141
  - Raw Markdown text
142
+ - Structured chunks (summary, experience, education, skills, projects, awards)
143
  - Detected CV metadata (title, seniority, category, years of experience)
144
+ - CV quality completeness_score (0–100)
145
+ - section_embeddings — pre-computed ML vectors for fast /match-cv reuse
146
+ - File metadata (type, method, page count, warnings)
147
+ - Per-phase timing (conversion_ms, chunking_ms, total_ms)
148
  """
149
+ request_id = str(uuid.uuid4())
150
+
151
  if not file.filename:
152
  return APIResponse(message="No file uploaded", statusCode=400)
153
 
154
+ ext = Path(file.filename).suffix.lower()
155
+ if ext not in _ALLOWED_EXT:
156
  return APIResponse(
157
+ message=f"Invalid file format. Allowed: {', '.join(_ALLOWED_EXT)}",
158
  statusCode=400,
159
  )
160
 
161
  tmp_path: Optional[Path] = None
162
+ t_start = datetime.now(timezone.utc)
163
+
164
  try:
 
165
  file_bytes = await file.read()
166
 
167
+ # P1 — file size guard
168
+ if len(file_bytes) > MAX_FILE_BYTES:
169
+ return APIResponse(
170
+ message=f"File too large. Maximum size is {MAX_FILE_BYTES // (1024*1024)} MB.",
171
+ statusCode=413,
172
+ )
173
+
174
+ # P4 — MIME sniff
175
+ if not _check_mime(file_bytes, ext):
176
+ return APIResponse(
177
+ message="File content does not match the declared extension.",
178
+ statusCode=400,
179
+ )
180
+
181
+ # Write temp file
182
+ with tempfile.NamedTemporaryFile(delete=False, suffix=ext) as tmp:
183
  tmp.write(file_bytes)
184
  tmp_path = Path(tmp.name)
185
 
186
+ # P7 — Conversion phase timer
187
+ t_conv_start = datetime.now(timezone.utc)
188
  conversion = converter.convert(tmp_path)
189
+ t_conv_end = datetime.now(timezone.utc)
190
+ conversion_ms = int((t_conv_end - t_conv_start).total_seconds() * 1000)
191
+
192
  if not conversion.success:
193
+ return APIResponse(
194
+ message=conversion.error or "Conversion failed",
195
+ statusCode=422,
196
+ )
197
+
198
+ # P7 — Chunking phase timer (includes ML embedding)
199
+ t_chunk_start = datetime.now(timezone.utc)
200
+ chunks = chunk_cv(conversion.markdown, embedder=matcher._embed)
201
+ t_chunk_end = datetime.now(timezone.utc)
202
+ chunking_ms = int((t_chunk_end - t_chunk_start).total_seconds() * 1000)
203
 
204
+ t_end = datetime.now(timezone.utc)
205
+ total_ms = int((t_end - t_start).total_seconds() * 1000)
206
 
207
  return APIResponse(
208
  message="CV processed successfully",
209
  statusCode=200,
210
  payload={
211
+ "request_id": request_id,
212
+ "markdown": conversion.markdown,
213
+ "cv_title": chunks["cv_title"],
214
+ "seniority": chunks["seniority"],
215
+ "years_experience": chunks["years_experience"],
216
+ "category": chunks["category"],
217
+ "completeness_score": chunks["completeness_score"],
218
  "chunks": {
219
  "summary": chunks["chunks"]["summary"],
220
  "contact": chunks["chunks"]["contact"],
 
225
  "projects": chunks["chunks"]["projects"],
226
  "awards": chunks["chunks"]["awards"],
227
  },
228
+ # Pre-computed ML section vectors — pass these to /match-cv or
229
+ # /batch-match-cv to avoid re-encoding the CV on every match request.
230
+ "section_embeddings": chunks.get("section_embeddings"),
231
+ "file_type": conversion.file_type,
232
+ "method_used": conversion.method_used,
233
+ "is_scanned": conversion.is_scanned,
234
+ "page_count": conversion.page_count,
235
+ "warnings": conversion.warnings,
236
+ "timing": {
237
+ "conversion_ms": conversion_ms,
238
+ "chunking_ms": chunking_ms,
239
+ "total_ms": total_ms,
240
+ },
241
+ "processed_at": t_end.isoformat(),
242
  },
243
  )
244
 
 
249
  )
250
 
251
  finally:
252
+ # P3 — guaranteed temp file cleanup
253
+ if tmp_path is not None:
254
+ try:
255
+ tmp_path.unlink(missing_ok=True)
256
+ except Exception:
257
+ pass
258
 
259
 
260
  # ---------------------------------------------------------------------------
261
+ # POST /process-cv-async (queued, used by Java async worker)
 
 
 
 
262
  # ---------------------------------------------------------------------------
263
 
 
264
  @app.post("/process-cv-async", response_model=APIResponse)
265
  async def process_cv_async(
266
  file: UploadFile = File(...),
 
270
  ):
271
  """
272
  Async entry point called by the Java async worker.
 
273
  Returns 202 immediately; processes the CV in a queued background task.
274
  """
275
  if not file.filename:
276
  return APIResponse(message="No file uploaded", statusCode=400)
277
 
278
+ ext = Path(file.filename).suffix.lower()
279
+ if ext not in _ALLOWED_EXT:
280
  return APIResponse(
281
+ message=f"Invalid file format. Allowed: {', '.join(_ALLOWED_EXT)}",
282
  statusCode=400,
283
  )
284
 
 
285
  file_bytes = await file.read()
 
286
 
287
+ # Size guard (async path)
288
+ if len(file_bytes) > MAX_FILE_BYTES:
289
+ return APIResponse(
290
+ message=f"File too large. Maximum size is {MAX_FILE_BYTES // (1024*1024)} MB.",
291
+ statusCode=413,
292
+ )
293
+
294
+ # MIME sniff (async path)
295
+ if not _check_mime(file_bytes, ext):
296
+ return APIResponse(
297
+ message="File content does not match the declared extension.",
298
+ statusCode=400,
299
+ )
300
+
301
+ filename = file.filename
302
  job_store.create_job(job_id)
303
 
304
  task = CvTask(
 
306
  file_bytes=file_bytes,
307
  filename=filename,
308
  callback_url=callback_url,
309
+ callback_secret=callback_secret,
310
  )
311
 
312
  try:
 
315
  return APIResponse(
316
  message=str(exc),
317
  statusCode=409,
318
+ payload={
319
+ "job_id": job_id,
320
+ "status": job_store.get_job(job_id)["status"],
321
+ },
322
  )
323
 
324
  return APIResponse(
 
328
  )
329
 
330
 
331
+ # ---------------------------------------------------------------------------
332
+ # GET /job-status/{job_id}
333
+ # ---------------------------------------------------------------------------
334
+
335
  @app.get("/job-status/{job_id}", response_model=APIResponse)
336
  def get_job_status(job_id: str):
337
+ """Returns the current status of a CV processing job from the in-memory store."""
 
 
 
338
  job = job_store.get_job(job_id)
339
  if job is None:
340
  return APIResponse(message="Job not found", statusCode=404)
 
342
  status = job["status"]
343
  if status == "QUEUED":
344
  pos = queue_manager.get_queue_position(job_id)
345
+ status = f"QUEUE({pos})" if pos is not None else "QUEUE(1)"
 
 
 
346
 
347
  return APIResponse(
348
  message=f"Job status: {status}",
 
351
  )
352
 
353
 
354
+ # ---------------------------------------------------------------------------
355
+ # POST /match-cv (single job — backward-compatible)
356
+ # ---------------------------------------------------------------------------
357
 
358
  class MatchCVRequest(BaseModel):
359
  """Request body for POST /match-cv."""
360
  job: JobInput = Field(..., description="Structured job posting to match against.")
361
+ cv_markdown: str = Field(..., min_length=20, description="Candidate's CV as Markdown.")
362
+ section_embeddings: Optional[Any] = Field(
363
+ None,
364
+ description=(
365
+ "Pre-computed section embeddings from /process-cv. "
366
+ "Pass these to skip re-encoding the CV (significantly faster)."
367
+ ),
368
+ )
369
 
370
 
371
  @app.post("/match-cv", response_model=APIResponse)
372
  def match_cv_to_job(payload: MatchCVRequest):
373
  """
374
+ Match a Markdown CV against a single structured job posting.
375
 
376
+ For matching one CV against many jobs use POST /batch-match-cv instead.
377
+ Pass ``section_embeddings`` from a prior ``/process-cv`` response to skip
378
+ the embedding step and make matching significantly faster.
 
 
379
  """
380
  try:
381
  result = matcher.predict(
382
  job_json=payload.job.model_dump(),
383
  cv_markdown=payload.cv_markdown,
384
+ section_embeddings=payload.section_embeddings,
385
  )
386
  return APIResponse(
387
  message="Match prediction completed successfully",
 
392
  return APIResponse(
393
  message=f"An error occurred during matching: {exc}",
394
  statusCode=500,
395
+ )
396
+
397
+
398
+ # ---------------------------------------------------------------------------
399
+ # POST /batch-match-cv (one CV vs. array of jobs — optimised)
400
+ # ---------------------------------------------------------------------------
401
+
402
+ class BatchMatchCVRequest(BaseModel):
403
+ """Request body for POST /batch-match-cv."""
404
+ jobs: List[JobInput] = Field(
405
+ ...,
406
+ min_length=1,
407
+ max_length=100,
408
+ description="Array of job postings (1–100).",
409
+ )
410
+ cv_markdown: str = Field(..., min_length=20, description="Candidate's CV as Markdown.")
411
+ section_embeddings: Optional[Any] = Field(
412
+ None,
413
+ description=(
414
+ "Pre-computed section embeddings from /process-cv. "
415
+ "CV is parsed and embedded only ONCE for all jobs when provided."
416
+ ),
417
+ )
418
+
419
+
420
+ @app.post("/batch-match-cv", response_model=APIResponse)
421
+ def batch_match_cv(payload: BatchMatchCVRequest):
422
+ """
423
+ Match one CV against an array of job postings in a single request.
424
+
425
+ The CV is parsed and embedded **once** regardless of how many jobs
426
+ are in the array. Results are returned sorted by match_score descending.
427
+
428
+ Workflow optimisation
429
+ ---------------------
430
+ 1. User uploads CV → ``POST /process-cv``
431
+ Jobcore saves ``section_embeddings`` alongside CV in Postgres.
432
+ 2. User requests matches → ``POST /batch-match-cv``
433
+ Jobcore fetches ``section_embeddings`` from Postgres and sends them
434
+ here, completely eliminating the embedding step.
435
+ """
436
+ try:
437
+ results = matcher.predict_batch(
438
+ jobs=[j.model_dump() for j in payload.jobs],
439
+ cv_markdown=payload.cv_markdown,
440
+ section_embeddings=payload.section_embeddings,
441
+ )
442
+ return APIResponse(
443
+ message=f"Batch match completed: {len(results)} result(s)",
444
+ statusCode=200,
445
+ payload={
446
+ "matches": results,
447
+ "total": len(results),
448
+ },
449
+ )
450
+ except Exception as exc:
451
+ return APIResponse(
452
+ message=f"Batch match error: {exc}",
453
+ statusCode=500,
454
  )
services/__pycache__/cv_chunker.cpython-312.pyc CHANGED
Binary files a/services/__pycache__/cv_chunker.cpython-312.pyc and b/services/__pycache__/cv_chunker.cpython-312.pyc differ
 
services/__pycache__/cv_utils.cpython-312.pyc ADDED
Binary file (28.3 kB). View file
 
services/__pycache__/job_matcher.cpython-312.pyc CHANGED
Binary files a/services/__pycache__/job_matcher.cpython-312.pyc and b/services/__pycache__/job_matcher.cpython-312.pyc differ
 
services/__pycache__/workers.cpython-312.pyc CHANGED
Binary files a/services/__pycache__/workers.cpython-312.pyc and b/services/__pycache__/workers.cpython-312.pyc differ
 
services/cv_chunker.py CHANGED
@@ -3,120 +3,32 @@ from __future__ import annotations
3
  import re
4
  from typing import Any, Dict, List, Optional, Set, Tuple
5
 
6
- # ---------------------------------------------------------------------------
7
- # Skill taxonomy
8
- # ---------------------------------------------------------------------------
9
-
10
- DEFAULT_SKILL_ALIASES: Dict[str, List[str]] = {
11
- "microsoft word": ["microsoft word", "ms word", "word"],
12
- "microsoft excel": ["microsoft excel", "ms excel", "excel"],
13
- "microsoft powerpoint": ["microsoft powerpoint", "ms powerpoint", "powerpoint"],
14
- "inventory management": ["inventory management", "inventory", "stock control", "stock management"],
15
- "warehouse": ["warehouse", "stockroom", "store room"],
16
- "data entry": ["data entry", "typing"],
17
- "communication": ["communication", "communicate"],
18
- "teamwork": ["teamwork", "team work", "team member"],
19
- "critical thinking": ["critical thinking", "problem solving", "problem-solving"],
20
- "customer service": ["customer service", "client service"],
21
- "reporting": ["report", "reporting"],
22
- "html": ["html", "html5"],
23
- "css": ["css", "css3"],
24
- "javascript": ["javascript", "js"],
25
- "typescript": ["typescript", "ts"],
26
- "react": ["react", "react.js", "reactjs"],
27
- "next.js": ["next.js", "nextjs"],
28
- "vue": ["vue", "vue.js", "vuejs"],
29
- "angular": ["angular"],
30
- "tailwind css": ["tailwind", "tailwind css"],
31
- "node.js": ["node", "node.js", "nodejs"],
32
- "express.js": ["express", "express.js"],
33
- "python": ["python"],
34
- "java": ["java"],
35
- "kotlin": ["kotlin"],
36
- "android": ["android", "android studio"],
37
- "php": ["php"],
38
- "laravel": ["laravel"],
39
- "mysql": ["mysql"],
40
- "postgresql": ["postgresql", "postgres", "supabase"],
41
- "mongodb": ["mongodb", "mongo"],
42
- "rest api": ["rest api", "restful api", "api"],
43
- "git": ["git", "github", "gitlab"],
44
- "docker": ["docker"],
45
- "ui design": ["ui design", "user interface design"],
46
- "ux design": ["ux design", "user experience design"],
47
- "figma": ["figma"],
48
- "wireframing": ["wireframe", "wireframing"],
49
- "prototyping": ["prototype", "prototyping"],
50
- "seo": ["seo", "search engine optimization"],
51
- "content writing": ["content writing", "copywriting"],
52
- "digital marketing": ["digital marketing", "marketing campaign"],
53
- "sql": ["sql"],
54
- "machine learning": ["machine learning", "ml"],
55
- "data analysis": ["data analysis", "analytics", "data analyst"],
56
- "spring boot": ["spring boot", "spring"],
57
- "ci/cd": ["ci/cd", "ci cd", "github actions", "jenkins", "gitlab ci", "pipelines"],
58
- "kubernetes": ["kubernetes", "k8s"],
59
- "aws": ["aws", "amazon web services"],
60
- "azure": ["azure", "microsoft azure"],
61
- "gcp": ["gcp", "google cloud"],
62
- "flutter": ["flutter"],
63
- "dart": ["dart"],
64
- "swift": ["swift"],
65
- "ios": ["ios", "xcode"],
66
- "c#": ["c#", "csharp", "c sharp"],
67
- "c++": ["c++", "cpp"],
68
- "rust": ["rust"],
69
- "go": ["golang", "go lang"],
70
- "redis": ["redis"],
71
- "elasticsearch": ["elasticsearch", "elastic search"],
72
- "graphql": ["graphql"],
73
- }
74
-
75
- DEFAULT_CATEGORY_SKILLS: Dict[str, Set[str]] = {
76
- "Admin & Stock": {
77
- "microsoft word", "microsoft excel", "microsoft powerpoint", "inventory management",
78
- "warehouse", "data entry", "communication", "teamwork", "customer service", "reporting",
79
- },
80
- "Software Engineering": {
81
- "html", "css", "javascript", "typescript", "react", "next.js", "vue", "angular",
82
- "tailwind css", "node.js", "express.js", "python", "java", "kotlin", "android", "php",
83
- "laravel", "mysql", "postgresql", "mongodb", "rest api", "git", "docker",
84
- "spring boot", "ci/cd", "kubernetes", "aws", "azure", "gcp", "flutter", "dart",
85
- "swift", "ios", "c#", "c++", "rust", "go", "redis", "graphql",
86
- },
87
- "Design & Creative": {"ui design", "ux design", "figma", "wireframing", "prototyping"},
88
- "Marketing & Growth": {"seo", "content writing", "digital marketing"},
89
- "Data & Analytics": {"sql", "python", "machine learning", "data analysis", "microsoft excel", "elasticsearch"},
90
- }
91
-
92
- SENIORITY_PATTERNS: Dict[str, List[str]] = {
93
- "intern": ["intern", "internship", "trainee", "industrial attachment"],
94
- "junior": ["junior", "entry level", "entry-level", "assistant", "fresh graduate", "graduate"],
95
- "mid": ["mid", "officer", "specialist", "developer", "designer", "engineer"],
96
- "senior": ["senior", "lead", "manager", "head", "principal", "architect", "director", "vp", "vice president"],
97
- }
98
- SENIORITY_ORDER: Dict[str, int] = {"intern": 0, "junior": 1, "mid": 2, "senior": 3}
99
-
100
- # Words that look like "City, Country" but are actually tech terms — excluded from location detection
101
- _TECH_LOC_BLACKLIST: Set[str] = {
102
- "java", "spring", "boot", "sql", "python", "node", "react", "angular", "vue", "docker",
103
- "linux", "windows", "android", "swift", "kotlin", "scala", "ruby", "rails", "django",
104
- "flask", "express", "mongo", "postgres", "redis", "kafka", "hadoop", "spark", "airflow",
105
- "jenkins", "gitlab", "github", "bitbucket", "jira", "confluence", "slack", "figma",
106
- }
107
 
108
 
109
  # ---------------------------------------------------------------------------
110
  # Markdown / HTML cleanup helpers
111
  # ---------------------------------------------------------------------------
112
 
113
- # Strips **bold**, *italic*, `code`, keeping visible text; [label](url) → label
114
  _MD_INLINE_RE = re.compile(
115
- r"\*{1,3}([^*\n]*?)\*{1,3}" # bold/italic
116
- r"|_{1,2}([^_\n]*?)_{1,2}" # underscore emphasis
117
- r"|`([^`\n]+)`" # inline code
118
- r"|\[([^\]]*)\]\([^)]*\)" # [label](url) → label
119
- r"|\[([^\]]*)\]\[[^\]]*\]" # [label][ref]
120
  )
121
 
122
 
@@ -127,140 +39,27 @@ def _strip_md(text: str) -> str:
127
 
128
 
129
  def _strip_html(text: str) -> str:
130
- """Remove HTML tags; replace <br> variants with a space."""
131
  text = re.sub(r"<br\s*/?>", " ", text, flags=re.IGNORECASE)
132
  return re.sub(r"<[^>]+>", " ", text)
133
 
134
 
135
  def _clean_line(raw: str) -> str:
136
- """Strip heading markers, HTML, and inline markdown from a line."""
137
  line = re.sub(r"^#+\s*", "", raw)
138
  line = _strip_html(line)
139
  line = _strip_md(line)
140
  return re.sub(r"\s+", " ", line).strip()
141
 
142
 
143
- # ---------------------------------------------------------------------------
144
- # Normalisation & skill helpers
145
- # ---------------------------------------------------------------------------
146
-
147
- def _normalize(text: str) -> str:
148
- text = (text or "").lower()
149
- text = text.replace("/", " ").replace("_", " ")
150
- text = re.sub(r"[^a-z0-9+.#\s-]", " ", text)
151
- return re.sub(r"\s+", " ", text).strip()
152
-
153
-
154
- def _has_alias(text_norm: str, alias: str) -> bool:
155
- alias_norm = _normalize(alias)
156
- if not alias_norm:
157
- return False
158
- return re.search(rf"(?<![a-z0-9]){re.escape(alias_norm)}(?![a-z0-9])", text_norm) is not None
159
-
160
-
161
- def _extract_skills(text: str, aliases: Dict[str, List[str]]) -> Set[str]:
162
- text_norm = _normalize(text)
163
- return {canon for canon, ali_list in aliases.items() if any(_has_alias(text_norm, a) for a in ali_list)}
164
-
165
-
166
- def _infer_category(text: str, skills: Set[str], category_skills: Dict[str, Set[str]]) -> str:
167
- text_norm = _normalize(text)
168
- title_keywords = {
169
- "Admin & Stock": ["stock", "inventory", "warehouse", "admin", "office", "cashier"],
170
- "Software Engineering": ["developer", "engineer", "programmer", "frontend", "backend", "full stack", "mobile", "fullstack"],
171
- "Design & Creative": ["designer", "ui", "ux", "creative", "graphic"],
172
- "Marketing & Growth": ["marketing", "seo", "content", "social media", "growth"],
173
- "Data & Analytics": ["data", "analyst", "analytics", "machine learning", "ai", "scientist"],
174
- }
175
- best, best_score = "Other", 0.0
176
- for cat, cat_skills in category_skills.items():
177
- score = (
178
- len(skills & cat_skills) * 2.0
179
- + sum(1 for kw in title_keywords.get(cat, []) if kw in text_norm) * 1.25
180
- )
181
- if score > best_score:
182
- best_score, best = score, cat
183
- return best
184
-
185
-
186
- def _extract_years(text: str) -> int:
187
- text_norm = _normalize(text)
188
- patterns = [
189
- r"(\d+)\+?\s*(?:years|year|yrs|yr)\s*(?:of)?\s*(?:experience|exp)",
190
- r"experience\s*(?:of)?\s*(\d+)\+?\s*(?:years|year|yrs|yr)",
191
- r"(\d+)\+?\s*(?:years|year|yrs|yr)\s+(?:in\s+)?(?:the\s+)?(?:industry|field|software|development)",
192
- ]
193
- years = [int(m.group(1)) for p in patterns for m in re.finditer(p, text_norm)]
194
- return max(years) if years else 0
195
-
196
-
197
- def _detect_seniority(text: str, *, is_cv: bool = False) -> str:
198
- text_norm = _normalize(text)
199
- order = ["senior", "junior", "intern", "mid"] if is_cv else ["senior", "intern", "junior", "mid"]
200
- for level in order:
201
- if any(_has_alias(text_norm, term) for term in SENIORITY_PATTERNS[level]):
202
- return level
203
- years = _extract_years(text)
204
- if years >= 5:
205
- return "senior"
206
- if years >= 2:
207
- return "mid"
208
- return "junior" if is_cv else "mid"
209
-
210
-
211
- # ---------------------------------------------------------------------------
212
- # CV title extractor
213
- # Handles: standalone title line, title embedded in summary, "Name\nTitle" format
214
- # ---------------------------------------------------------------------------
215
-
216
- _TITLE_ROLE_WORDS = [
217
- "officer", "developer", "engineer", "designer", "assistant", "accountant",
218
- "manager", "marketing", "stock", "cashier", "admin", "student", "intern",
219
- "analyst", "teacher", "architect", "consultant", "programmer", "researcher",
220
- "specialist", "technician", "coordinator", "director", "executive", "lead",
221
- "scientist", "strategist", "advisor", "trainer",
222
- ]
223
-
224
- _TITLE_PHRASE_RE = re.compile(
225
- r"\b((?:(?:full[\s\-]?stack|front[\s\-]?end|back[\s\-]?end|senior|junior|lead|"
226
- r"mid[\s\-]?level|entry[\s\-]?level)\s+)?(?:[\w\-]+\s){0,3}"
227
- r"(?:developer|engineer|designer|analyst|manager|specialist|consultant|architect|"
228
- r"programmer|researcher|officer|director|executive|scientist|trainer))\b",
229
- re.IGNORECASE,
230
- )
231
-
232
-
233
- def _extract_cv_title(cv_text: str) -> str:
234
- clean_lines = [_clean_line(x) for x in cv_text.splitlines() if x.strip()]
235
-
236
- # Pass 1: short standalone line with a role keyword (skip the very first line — usually the name)
237
- for line in clean_lines[1:16]:
238
- stripped = line.strip("| \t")
239
- if (
240
- len(stripped) <= 80
241
- and any(w in stripped.lower() for w in _TITLE_ROLE_WORDS)
242
- # Must not look like a contact / URL / date line
243
- and not re.search(r"[@http://|+\d{6}]", stripped)
244
- and not re.search(r"\d{4}\s*[-–]\s*(?:\d{4}|present)", stripped, re.IGNORECASE)
245
- ):
246
- return stripped.title()
247
-
248
- # Pass 2: extract role phrase from the first ~600 chars of visible text
249
- head = " ".join(clean_lines[:30])[:600]
250
- m = _TITLE_PHRASE_RE.search(head)
251
- if m:
252
- return m.group(1).strip().title()
253
-
254
- return "Unknown"
255
 
256
 
257
  # ---------------------------------------------------------------------------
258
- # Date helpers (shared across parsers)
259
  # ---------------------------------------------------------------------------
260
 
261
  _MONTH_PAT = r"(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)"
262
- _YEAR_PAT = r"\d{4}"
263
- _DATE_PAT = rf"(?:{_MONTH_PAT}\s+)?{_YEAR_PAT}"
264
 
265
  _PERIOD_RE = re.compile(
266
  rf"({_DATE_PAT})\s*[-–—to]+\s*({_DATE_PAT}|Present|Current|Now|Till\s+date|To\s+date|Ongoing)",
@@ -285,12 +84,11 @@ def _extract_period(text: str) -> Optional[str]:
285
  def _strip_period(text: str) -> str:
286
  text = _PERIOD_RE.sub("", text)
287
  text = _YEAR_ONLY_RE.sub("", text)
288
- return re.sub(r"[\|·•]\s*$", "", text).strip(" |·•–—-,()")
289
 
290
 
291
  # ---------------------------------------------------------------------------
292
  # Section splitter
293
- # Guards against false positives: bullets, digits, date lines, long prose
294
  # ---------------------------------------------------------------------------
295
 
296
  _SECTION_KEYWORDS: Dict[str, List[str]] = {
@@ -311,27 +109,28 @@ _SECTION_KEYWORDS: Dict[str, List[str]] = {
311
  "skills", "technical skills", "core skills", "competencies",
312
  "key skills", "areas of expertise", "technologies", "tech stack",
313
  "tools", "expertise", "capabilities", "core competencies",
314
- "technical expertise", "skills & tools",
 
315
  ],
316
  "experience": [
317
  "experience", "work experience", "professional experience", "employment",
318
  "work history", "career history", "career", "employment history",
319
  "relevant experience", "professional background", "internship",
320
- "internships", "volunteer", "volunteering",
321
  ],
322
  "education": [
323
  "education", "academic background", "academic history", "qualifications",
324
  "educational background", "academics", "training", "certifications",
325
- "degrees", "academic qualifications", "schools",
326
  ],
327
  "projects": [
328
  "projects", "personal projects", "key projects", "notable projects",
329
  "open source", "portfolio", "side projects", "selected projects",
330
- "technical projects",
331
  ],
332
  "awards": [
333
  "awards", "honors", "honours", "achievements", "accomplishments",
334
- "recognition", "publications", "research",
335
  ],
336
  "languages": [
337
  "languages spoken", "spoken languages", "human languages",
@@ -339,38 +138,42 @@ _SECTION_KEYWORDS: Dict[str, List[str]] = {
339
  ],
340
  }
341
 
342
- _BULLET_RE = re.compile(r"^[-•*▪►▸>]\s+")
343
-
344
 
345
  def _detect_section(stripped_line: str, raw_line: str) -> Optional[str]:
346
  """
347
  Return the section key if this line is a section header, else None.
348
 
349
- Heuristics applied before keyword matching to prevent false positives:
350
- - Bullet lines are never headers
351
- - Lines starting with digits (dates, phone numbers) are never headers
352
- - Lines containing date ranges are never headers
353
- - Lines longer than 60 normalised chars are likely prose, not headers
354
- - Lines with more than 7 words are likely prose
 
 
 
355
  """
356
  if _BULLET_RE.match(raw_line.strip()):
357
  return None
358
 
359
- line_norm = _normalize(_strip_md(_strip_html(stripped_line)))
 
 
 
360
 
 
361
  if not line_norm:
362
  return None
363
- if re.match(r"^\d", line_norm): # starts with digit
364
  return None
365
- if _PERIOD_RE.search(stripped_line): # contains date range
366
  return None
367
- if _YEAR_ONLY_RE.search(stripped_line): # year-only range
368
  return None
369
- if len(line_norm) > 60: # too long to be a header
370
  return None
371
- if len(line_norm.split()) > 7: # too many words
372
  return None
373
- # Must contain at least one alphabetic character
374
  if not re.search(r"[a-z]", line_norm):
375
  return None
376
 
@@ -382,52 +185,47 @@ def _detect_section(stripped_line: str, raw_line: str) -> Optional[str]:
382
  or kw in line_norm
383
  ):
384
  return section
385
-
386
  return None
387
 
388
 
389
  def _parse_cv_sections(cv_text: str) -> Dict[str, str]:
390
  current = "summary"
391
  sections: Dict[str, List[str]] = {k: [] for k in _SECTION_KEYWORDS}
392
-
393
  for raw_line in cv_text.splitlines():
394
  stripped = re.sub(r"^#+\s*", "", raw_line).strip()
395
  if not stripped:
396
  continue
397
-
398
  section = _detect_section(stripped, raw_line)
399
  if section:
400
  current = section
401
  continue
402
-
403
  sections[current].append(raw_line)
404
-
405
  return {k: "\n".join(v).strip() for k, v in sections.items()}
406
 
407
 
408
  # ---------------------------------------------------------------------------
409
  # Experience parser
410
- # Handles:
411
- # A) "Role at Company | Date" (single line)
412
- # B) "### Company\n**Role** | Date" (company header, role sub-header)
413
- # C) "Company\nRole\nDate" (three separate lines)
414
- # D) Table rows with pipe separators
415
  # ---------------------------------------------------------------------------
416
 
417
  _ROLE_WORDS = {
418
- "engineer", "developer", "manager", "designer", "analyst", "intern", "officer",
419
- "lead", "head", "director", "consultant", "assistant", "specialist", "coordinator",
420
- "technician", "architect", "programmer", "researcher", "executive", "trainer",
421
- "scientist", "strategist", "advisor", "supervisor", "associate", "fellow",
 
 
 
 
 
 
 
 
 
 
422
  }
423
 
424
 
425
  def _split_role_company(text: str) -> Tuple[str, str]:
426
- """
427
- Split 'Role at Company', 'Company | Role', 'Role — Company', etc.
428
- Returns (role, company). If unclear, treats first part as role.
429
- """
430
- # Try various separators in priority order
431
  for pat in [r"\s+(?:at|@|with)\s+", r"\s*\|\s*", r"\s*[—–,]\s+"]:
432
  parts = re.split(pat, text, maxsplit=1)
433
  if len(parts) == 2:
@@ -438,7 +236,6 @@ def _split_role_company(text: str) -> Tuple[str, str]:
438
  return a, b
439
  if b_is_role and not a_is_role:
440
  return b, a
441
- # Both or neither match — assume role | company order
442
  return a, b
443
  return "", text
444
 
@@ -455,39 +252,30 @@ def _parse_experience(raw: str) -> List[Dict[str, Any]]:
455
  line = _clean_line(raw_line)
456
  if not line:
457
  continue
458
-
459
- # Skip lines that are obviously sub-section labels (e.g. "Key Achievements:")
460
  if re.match(r"^[\w\s]+:\s*$", line) and len(line) < 40:
461
  continue
462
 
463
- period = _extract_period(line)
464
- is_bullet = bool(_BULLET_RE.match(line))
465
- clean = _strip_period(_BULLET_RE.sub("", line)).strip()
466
 
467
- # ── Bullet / responsibility line ──────────────────────────────────
468
  if is_bullet:
469
  if current is not None and clean:
470
  current["responsibilities"].append(clean)
471
  continue
472
 
473
- # ── Stand-alone date line ─────────────────────────────────────────
474
  if period and not clean:
475
  if current is not None and not current["period"]:
476
  current["period"] = period
477
  continue
478
 
479
- # ── Line with both content and a date ────────────────────────────
480
  if period and clean:
481
  role, company = _split_role_company(clean)
482
-
483
- # If current entry is incomplete (missing period), fill it in
484
  if (
485
  current is not None
486
  and not current["period"]
487
  and (current["role"] or current["company"])
488
  ):
489
- # The date belongs to the already-open entry; the content may
490
- # supply the missing role or company
491
  if not current["role"] and role:
492
  current["role"] = role
493
  if not current["company"] and company:
@@ -502,39 +290,29 @@ def _parse_experience(raw: str) -> List[Dict[str, Any]]:
502
  current["period"] = period
503
  continue
504
 
505
- # ── Plain header line (no date, no bullet) ────────────────────────
506
- # Could be company name, job title, or continuation of previous header
507
  is_role_line = any(w in clean.lower() for w in _ROLE_WORDS)
508
 
509
  if current is None:
510
- # Start first entry
511
  role, company = _split_role_company(clean)
512
  current = _new()
513
  current["role"] = role
514
  current["company"] = company
515
-
516
  elif not current["role"] and not current["company"]:
517
- # Completely empty entry — fill it
518
  role, company = _split_role_company(clean)
519
  current["role"] = role
520
  current["company"] = company
521
-
522
  elif (not current["role"] or not current["company"]) and not current["period"]:
523
- # Incomplete entry (only company OR only role) — try to complete it
524
  if not current["role"] and is_role_line:
525
  current["role"] = clean
526
  elif not current["company"] and not is_role_line:
527
  current["company"] = clean
528
  else:
529
- # Ambiguous — start a new entry
530
  entries.append(current)
531
  role, company = _split_role_company(clean)
532
  current = _new()
533
  current["role"] = role
534
  current["company"] = company
535
-
536
  else:
537
- # Current entry already complete — start a new one
538
  entries.append(current)
539
  role, company = _split_role_company(clean)
540
  current = _new()
@@ -543,37 +321,29 @@ def _parse_experience(raw: str) -> List[Dict[str, Any]]:
543
 
544
  if current:
545
  entries.append(current)
546
-
547
  return [e for e in entries if e.get("company") or e.get("role")]
548
 
549
 
550
  # ---------------------------------------------------------------------------
551
  # Education parser
552
- # Handles:
553
- # A) "University DEGREE, Field | Date" (all on one line)
554
- # B) "University\nBSc Computer Science\n2018-2022" (three lines)
555
- # C) Markdown table rows "| University | Degree | Date |"
556
- # D) Degree then institution on separate lines
557
  # ---------------------------------------------------------------------------
558
 
559
  _DEGREE_RE = re.compile(
560
  r"\b(bachelor(?:'s)?|master(?:'s)?|phd|ph\.d|doctorate|diploma|certificate|"
561
  r"degree|bsc|msc|b\.sc|m\.sc|ba|ma|mba|hnd|hons|honours|kcse|kcpe|btec|"
562
- r"associate(?:'s)?|advanced\s+diploma)\b",
563
  re.IGNORECASE,
564
  )
565
  _INSTITUTION_RE = re.compile(
566
  r"\b(university|college|school|institute|polytechnic|academy|"
567
- r"institution|faculty|campus)\b",
568
  re.IGNORECASE,
569
  )
570
- # Sub-section labels to skip (volunteer, leadership, etc. within education block)
571
  _EDU_SKIP_RE = re.compile(
572
  r"^(volunteer|leadership|activities|honors?|awards?|publications?|"
573
- r"extracurricular|memberships?|certifications?)\b",
574
  re.IGNORECASE,
575
  )
576
- # Table separator rows like "| --- | --- |"
577
  _TABLE_SEP_RE = re.compile(r"^\|[\s\-|:]+\|$")
578
 
579
 
@@ -591,19 +361,19 @@ def _parse_education(raw: str) -> List[Dict[str, str]]:
591
  current.clear()
592
 
593
  for raw_line in raw.splitlines():
594
- # Strip table separators
595
  stripped_raw = raw_line.strip()
596
  if _TABLE_SEP_RE.match(stripped_raw):
597
  continue
598
-
599
- # Handle pipe-delimited table cells: split, clean each cell
600
  if stripped_raw.startswith("|") and stripped_raw.endswith("|"):
601
  cells = [_clean_line(c) for c in stripped_raw.strip("|").split("|")]
602
  cells = [c for c in cells if c]
603
  if not cells:
604
  continue
605
- # Treat first cell as institution/degree, last cell as period
606
- line = cells[0]
 
 
 
607
  extra_period = _extract_period(cells[-1]) if len(cells) > 1 else None
608
  else:
609
  line = _clean_line(raw_line)
@@ -612,8 +382,6 @@ def _parse_education(raw: str) -> List[Dict[str, str]]:
612
  line = _BULLET_RE.sub("", line).strip()
613
  if not line:
614
  continue
615
-
616
- # Skip volunteer/leadership sub-sections embedded in education
617
  if _EDU_SKIP_RE.match(line) and len(line) < 60:
618
  _flush()
619
  continue
@@ -629,7 +397,6 @@ def _parse_education(raw: str) -> List[Dict[str, str]]:
629
  has_inst = bool(_INSTITUTION_RE.search(clean))
630
 
631
  if has_degree and has_inst:
632
- # Both on same line → split at degree keyword boundary
633
  deg_m = _DEGREE_RE.search(clean)
634
  institution = clean[:deg_m.start()].strip(" ,–—|") if deg_m else ""
635
  degree = clean[deg_m.start():].strip() if deg_m else clean
@@ -637,10 +404,8 @@ def _parse_education(raw: str) -> List[Dict[str, str]]:
637
  current["institution"] = institution
638
  current["degree"] = degree
639
  current["period"] = period or ""
640
-
641
  elif has_degree:
642
  if current.get("institution") and not current.get("degree"):
643
- # Institution already collected → complement it with degree
644
  current["degree"] = clean
645
  if period:
646
  current["period"] = period
@@ -649,10 +414,8 @@ def _parse_education(raw: str) -> List[Dict[str, str]]:
649
  current["degree"] = clean
650
  current["institution"] = ""
651
  current["period"] = period or ""
652
-
653
  elif has_inst:
654
  if current.get("degree") and not current.get("institution"):
655
- # Degree already collected → complement it with institution
656
  current["institution"] = clean
657
  if period:
658
  current["period"] = period
@@ -661,9 +424,7 @@ def _parse_education(raw: str) -> List[Dict[str, str]]:
661
  current["institution"] = clean
662
  current["degree"] = ""
663
  current["period"] = period or ""
664
-
665
  elif period:
666
- # Date-only or plain line with date
667
  if current:
668
  current["period"] = period
669
  if clean and not current.get("degree"):
@@ -671,9 +432,7 @@ def _parse_education(raw: str) -> List[Dict[str, str]]:
671
  else:
672
  current["institution"] = clean
673
  current["period"] = period
674
-
675
  else:
676
- # Plain line — could be field of study, GPA, or institution continuation
677
  if current and not current.get("institution") and not has_degree:
678
  current["institution"] = clean
679
  elif current and not current.get("degree"):
@@ -689,10 +448,6 @@ def _parse_education(raw: str) -> List[Dict[str, str]]:
689
 
690
  # ---------------------------------------------------------------------------
691
  # Contact parser
692
- # Handles various contact line formats:
693
- # "email | phone | City, Country"
694
- # "Email: ...", "Phone: ...", "Location: ..."
695
- # Contact info embedded in CV header
696
  # ---------------------------------------------------------------------------
697
 
698
  _EMAIL_RE = re.compile(r"[\w.+-]+@[\w-]+\.[a-zA-Z]{2,}")
@@ -700,7 +455,6 @@ _PHONE_RE = re.compile(r"(?:\+?[\d][\d\s().\-]{6,}\d)")
700
  _LOCATION_RE = re.compile(
701
  r"\b([A-Z][a-zA-Z]{2,}(?:\s[A-Z][a-zA-Z]{2,})*)\s*,\s*([A-Z][a-zA-Z]{2,}(?:\s[A-Z][a-zA-Z]{2,})*)\b"
702
  )
703
- # Labelled patterns: "Location: Nairobi, Kenya"
704
  _LABELLED_RE = re.compile(
705
  r"\b(?:location|address|city|based\s+in|residing\s+in|located\s+in)\s*[:\-]?\s*([^\n|•·,]+(?:,\s*[^\n|•·]+)?)",
706
  re.IGNORECASE,
@@ -708,21 +462,10 @@ _LABELLED_RE = re.compile(
708
 
709
 
710
  def _parse_contact(raw: str, cv_full: str) -> Dict[str, Any]:
711
- """
712
- Extract email, phone, and location.
713
-
714
- Strategy:
715
- - Email/phone: search the dedicated contact section, or the first 600 chars of the CV.
716
- - Location: first try labelled patterns ("Location: X"), then "City, Country" pattern
717
- restricted to the contact section or first 8 header lines to avoid
718
- false positives from technical skills text.
719
- """
720
  search_text = raw if raw.strip() else cv_full[:600]
721
-
722
  email_m = _EMAIL_RE.search(search_text)
723
  phone_m = _PHONE_RE.search(search_text)
724
 
725
- # Location search area — never scan deep into CV body
726
  if raw.strip():
727
  loc_text = raw
728
  else:
@@ -730,18 +473,15 @@ def _parse_contact(raw: str, cv_full: str) -> Dict[str, Any]:
730
  loc_text = "\n".join(header_lines)
731
 
732
  location = ""
733
-
734
- # 1. Labelled location ("Location: Nairobi, Kenya")
735
  lbl_m = _LABELLED_RE.search(loc_text)
736
  if lbl_m:
737
  location = lbl_m.group(1).strip()
738
  else:
739
- # 2. "City, Country" pattern — exclude tech blacklist words
740
  loc_m = _LOCATION_RE.search(loc_text)
741
  if loc_m:
742
- word1 = (loc_m.group(1) or "").lower()
743
- word2 = (loc_m.group(2) or "").lower()
744
- if word1 not in _TECH_LOC_BLACKLIST and word2 not in _TECH_LOC_BLACKLIST:
745
  location = loc_m.group(0).strip()
746
 
747
  return {
@@ -753,7 +493,6 @@ def _parse_contact(raw: str, cv_full: str) -> Dict[str, Any]:
753
 
754
  # ---------------------------------------------------------------------------
755
  # Links parser
756
- # Handles: full URLs, bare domains, mailto: links, markdown [label](url) links
757
  # ---------------------------------------------------------------------------
758
 
759
  _URL_RE = re.compile(r"(?:https?://|www\.)[^\s,;\"'>()\]]+", re.IGNORECASE)
@@ -763,7 +502,6 @@ _BARE_DOMAIN_RE = re.compile(
763
  r"[^\s,;\"'>()\]]*",
764
  re.IGNORECASE,
765
  )
766
- _MAILTO_RE = re.compile(r"mailto:([\w.+-]+@[\w-]+\.[a-zA-Z]{2,})", re.IGNORECASE)
767
 
768
  _PLATFORM_MAP: List[Tuple[str, str]] = [
769
  ("github.com", "GitHub"),
@@ -790,15 +528,10 @@ _LABEL_HINTS = {
790
 
791
 
792
  def _label_url(url: str, context_line: str) -> str:
793
- """Identify platform from URL first, then from markdown label text."""
794
  url_lower = url.lower()
795
-
796
- # 1. Match by URL domain (most reliable — avoids cross-contamination)
797
  for domain, label in _PLATFORM_MAP:
798
  if domain in url_lower:
799
  return label
800
-
801
- # 2. Match by markdown link label text: [Label](url)
802
  escaped = re.escape(url.split("?")[0].rstrip("/"))
803
  md_m = re.search(r"\[([^\]]+)\]\s*\(" + escaped, context_line, re.IGNORECASE)
804
  if md_m:
@@ -806,40 +539,26 @@ def _label_url(url: str, context_line: str) -> str:
806
  for hint, label in _LABEL_HINTS.items():
807
  if hint in label_text:
808
  return label
809
-
810
- # 3. Infer from surrounding context text on the same line
811
  ctx = context_line.lower()
812
  for hint, label in _LABEL_HINTS.items():
813
  if hint in ctx:
814
  return label
815
-
816
  return "Website"
817
 
818
 
819
  def _parse_links(raw: str, cv_full: str) -> List[Dict[str, str]]:
820
- """
821
- Extract URLs from the dedicated links section or the CV header.
822
- Handles full URLs, bare domains, and mailto: links.
823
- Returns [{"label": str, "url": str}, ...].
824
- """
825
- # Search dedicated links section first; fall back to first 1500 chars of CV
826
  search_text = raw if raw.strip() else cv_full[:1500]
827
  results: List[Dict[str, str]] = []
828
  seen: Set[str] = set()
829
 
830
  for line in search_text.splitlines():
831
- # Collect URLs from this line — process each independently so labels don't bleed
832
  found: List[str] = []
833
-
834
  for m in _URL_RE.finditer(line):
835
  found.append(m.group(0).rstrip(".,:;)\"'"))
836
-
837
- # Bare domain links not already captured by full URL regex
838
  for m in _BARE_DOMAIN_RE.finditer(line):
839
  url = m.group(0).rstrip(".,:;)\"'")
840
  if not any(url in u for u in found):
841
  found.append(url)
842
-
843
  for url in found:
844
  normalised = url if url.startswith("http") else f"https://{url}"
845
  if normalised in seen:
@@ -851,36 +570,32 @@ def _parse_links(raw: str, cv_full: str) -> List[Dict[str, str]]:
851
 
852
 
853
  # ---------------------------------------------------------------------------
854
- # Skills parser
855
- # Handles: comma-separated, pipe-separated, bullet per skill, "Category: x, y, z"
856
  # ---------------------------------------------------------------------------
857
 
858
- # Strip "Languages:", "**Frameworks:**", "Tools & Technologies:" prefixes
859
  _SKILL_PREFIX_RE = re.compile(r"^\*{0,2}[\w][\w\s&/()+\-]+:\*{0,2}\s*")
860
 
861
 
862
  def _parse_skills(raw: str, cv_full: str) -> Dict[str, Any]:
863
  canonical = sorted(_extract_skills(cv_full, DEFAULT_SKILL_ALIASES))
 
 
864
 
865
  raw_items: List[str] = []
866
  for line in raw.splitlines():
867
- line = _clean_line(line) # strip #, HTML, markdown
868
  line = _BULLET_RE.sub("", line).strip()
869
- line = _SKILL_PREFIX_RE.sub("", line).strip() # strip "Languages: " etc.
870
-
871
- # Split on common skill delimiters including bullet-like separators
872
  for item in re.split(r"[,|;•·/]", line):
873
- item = re.sub(r"^\W+|\W+$", "", item).strip() # strip leading/trailing non-word chars
874
- # Skip empty, too-long, or obviously non-skill strings
875
  if (
876
  item
877
  and 1 < len(item) < 60
878
- and not re.match(r"^\d+$", item) # pure numbers
879
- and not re.search(r"@|http|www\.", item) # emails/URLs
880
  ):
881
  raw_items.append(item)
882
 
883
- # Deduplicate while preserving order
884
  seen_items: Set[str] = set()
885
  deduped: List[str] = []
886
  for item in raw_items:
@@ -889,127 +604,234 @@ def _parse_skills(raw: str, cv_full: str) -> Dict[str, Any]:
889
  seen_items.add(key)
890
  deduped.append(item)
891
 
892
- return {"items": deduped, "canonical": canonical}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
893
 
894
 
895
  # ---------------------------------------------------------------------------
896
  # Public API
897
  # ---------------------------------------------------------------------------
898
 
899
- def chunk_cv(cv_markdown: str) -> Dict[str, Any]:
900
  """
901
  Parse any CV markdown string into structured, cleaned chunks.
902
 
 
 
 
 
 
 
 
 
 
 
903
  Returns
904
  -------
905
- {
906
- "cv_title": str,
907
- "seniority": str,
908
- "years_experience": int,
909
- "category": str,
910
- "chunks": {
911
- "summary": str,
912
- "contact": {"email", "phone", "location"},
913
- "links": [{"label", "url"}, ...],
914
- "skills": {"items": [...], "canonical": [...]},
915
- "experience": [{"role", "company", "period", "responsibilities"}, ...],
916
- "education": [{"institution", "degree", "period"}, ...],
917
- "projects": str,
918
- "awards": str,
919
- }
920
- }
921
  """
922
  sections = _parse_cv_sections(cv_markdown)
923
 
924
- cv_title = _extract_cv_title(cv_markdown)
925
- cv_years = _extract_years(cv_markdown)
926
- cv_skills = _extract_skills(cv_markdown, DEFAULT_SKILL_ALIASES)
 
 
927
  cv_category = _infer_category(cv_markdown, cv_skills, DEFAULT_CATEGORY_SKILLS)
928
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
929
  seniority_text = (
930
  cv_title + "\n"
931
  + sections.get("experience", "")
932
  + "\n" + cv_markdown[:600]
933
  )
934
  cv_seniority = _detect_seniority(seniority_text, is_cv=True)
 
935
 
936
- return {
937
- "cv_title": cv_title,
938
- "seniority": cv_seniority,
939
- "years_experience": cv_years,
940
- "category": cv_category,
 
 
 
 
 
 
 
 
941
  "chunks": {
942
  "summary": sections.get("summary", "").strip(),
943
- "contact": _parse_contact(sections.get("contact", ""), cv_markdown),
944
- "links": _parse_links(sections.get("links", ""), cv_markdown),
945
- "skills": _parse_skills(sections.get("skills", ""), cv_markdown),
946
- "experience": _parse_experience(sections.get("experience", "")),
947
- "education": _parse_education(sections.get("education", "")),
948
- "projects": sections.get("projects", "").strip(),
949
- "awards": sections.get("awards", "").strip(),
950
  },
951
  }
952
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
953
 
954
- # ---------------------------------------------------------------------------
955
- # CLI — python cv_chunker.py [file.md]
956
- # ---------------------------------------------------------------------------
957
-
958
- if __name__ == "__main__":
959
- import json
960
- import sys
961
-
962
- if len(sys.argv) > 1:
963
- with open(sys.argv[1], encoding="utf-8") as f:
964
- md = f.read()
965
- else:
966
- md = """\
967
- # Jane Doe
968
- Senior Software Engineer
969
- jane@example.com | +254 712 345 678 | Nairobi, Kenya
970
- https://github.com/jane | https://linkedin.com/in/jane | https://jane.dev
971
-
972
- ## Summary
973
- Results-driven full-stack engineer with 6 years of experience building
974
- scalable APIs and cloud-native applications.
975
-
976
- ## Technical Skills
977
- - **Languages:** Python, JavaScript, TypeScript, Go
978
- - **Frameworks:** Django, FastAPI, React, Next.js
979
- - **Databases:** PostgreSQL, MongoDB, Redis
980
- - **DevOps:** Docker, Kubernetes, GitHub Actions (CI/CD), AWS
981
- - **Tools:** Git, Figma, Jira
982
-
983
- ## Professional Experience
984
-
985
- ### Safaricom PLC
986
- **Senior Software Engineer** | Jan 2021 – Present
987
- - Led migration of monolithic payment service to microservices, reducing p99 latency by 40 %
988
- - Designed and shipped REST API used by 2 M+ customers
989
-
990
- Andela — Software Engineer | Mar 2019 – Dec 2020
991
- - Built React dashboards for internal analytics
992
- - Wrote integration tests with Jest, achieving 90 % coverage
993
-
994
- ### Freelance
995
- Junior Developer | Jan 2018 – Feb 2019
996
- - Delivered 5 client websites using WordPress and PHP
997
-
998
- ## Education
999
- University of Nairobi
1000
- BSc Computer Science | 2014 – 2018
1001
-
1002
- Strathmore University
1003
- Certificate, Data Science | 2019
1004
-
1005
- ## Projects
1006
- - **PayLink**: Real-time payment gateway built with Node.js and Stripe API
1007
- - **JobScraper**: Open-source CLI tool — github.com/jane/jobscraper
1008
-
1009
- ## Awards
1010
- - Andela Fellowship Recipient, 2019
1011
- - Finalist, Safaricom Hackathon, 2022
1012
- """
1013
-
1014
- result = chunk_cv(md)
1015
- print(json.dumps(result, indent=2))
 
3
  import re
4
  from typing import Any, Dict, List, Optional, Set, Tuple
5
 
6
+ from services.cv_utils import (
7
+ DEFAULT_SKILL_ALIASES,
8
+ DEFAULT_CATEGORY_SKILLS,
9
+ SOFT_SKILL_KEYS,
10
+ _TECH_LOC_BLACKLIST,
11
+ _normalize,
12
+ _extract_skills,
13
+ _infer_category,
14
+ _extract_years,
15
+ compute_years_from_experience,
16
+ _detect_seniority,
17
+ refine_seniority_with_years,
18
+ _extract_cv_title,
19
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
 
22
  # ---------------------------------------------------------------------------
23
  # Markdown / HTML cleanup helpers
24
  # ---------------------------------------------------------------------------
25
 
 
26
  _MD_INLINE_RE = re.compile(
27
+ r"\*{1,3}([^*\n]*?)\*{1,3}"
28
+ r"|_{1,2}([^_\n]*?)_{1,2}"
29
+ r"|`([^`\n]+)`"
30
+ r"|\[([^\]]*)\]\([^)]*\)"
31
+ r"|\[([^\]]*)\]\[[^\]]*\]"
32
  )
33
 
34
 
 
39
 
40
 
41
  def _strip_html(text: str) -> str:
 
42
  text = re.sub(r"<br\s*/?>", " ", text, flags=re.IGNORECASE)
43
  return re.sub(r"<[^>]+>", " ", text)
44
 
45
 
46
  def _clean_line(raw: str) -> str:
 
47
  line = re.sub(r"^#+\s*", "", raw)
48
  line = _strip_html(line)
49
  line = _strip_md(line)
50
  return re.sub(r"\s+", " ", line).strip()
51
 
52
 
53
+ _BULLET_RE = re.compile(r"^[-•*▪►▸>]\s+")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
 
56
  # ---------------------------------------------------------------------------
57
+ # Date helpers
58
  # ---------------------------------------------------------------------------
59
 
60
  _MONTH_PAT = r"(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)"
61
+ _YEAR_PAT = r"\d{4}"
62
+ _DATE_PAT = rf"(?:{_MONTH_PAT}\s+)?{_YEAR_PAT}"
63
 
64
  _PERIOD_RE = re.compile(
65
  rf"({_DATE_PAT})\s*[-–—to]+\s*({_DATE_PAT}|Present|Current|Now|Till\s+date|To\s+date|Ongoing)",
 
84
  def _strip_period(text: str) -> str:
85
  text = _PERIOD_RE.sub("", text)
86
  text = _YEAR_ONLY_RE.sub("", text)
87
+ return re.sub(r"[|·•]\s*$", "", text).strip(" |·•–—-,()")
88
 
89
 
90
  # ---------------------------------------------------------------------------
91
  # Section splitter
 
92
  # ---------------------------------------------------------------------------
93
 
94
  _SECTION_KEYWORDS: Dict[str, List[str]] = {
 
109
  "skills", "technical skills", "core skills", "competencies",
110
  "key skills", "areas of expertise", "technologies", "tech stack",
111
  "tools", "expertise", "capabilities", "core competencies",
112
+ "technical expertise", "skills & tools", "professional skills",
113
+ "key competencies",
114
  ],
115
  "experience": [
116
  "experience", "work experience", "professional experience", "employment",
117
  "work history", "career history", "career", "employment history",
118
  "relevant experience", "professional background", "internship",
119
+ "internships", "volunteer", "volunteering", "work",
120
  ],
121
  "education": [
122
  "education", "academic background", "academic history", "qualifications",
123
  "educational background", "academics", "training", "certifications",
124
+ "degrees", "academic qualifications", "schools", "certificates",
125
  ],
126
  "projects": [
127
  "projects", "personal projects", "key projects", "notable projects",
128
  "open source", "portfolio", "side projects", "selected projects",
129
+ "technical projects", "case studies",
130
  ],
131
  "awards": [
132
  "awards", "honors", "honours", "achievements", "accomplishments",
133
+ "recognition", "publications", "research", "accolades",
134
  ],
135
  "languages": [
136
  "languages spoken", "spoken languages", "human languages",
 
138
  ],
139
  }
140
 
 
 
141
 
142
  def _detect_section(stripped_line: str, raw_line: str) -> Optional[str]:
143
  """
144
  Return the section key if this line is a section header, else None.
145
 
146
+ Guards applied (in order):
147
+ - Bullet lines → never headers
148
+ - Table rows (≥2 pipe chars, line starts with |) → never headers.
149
+ This prevents markdown table cells like "| VOLUNTEER & LEADERSHIP |"
150
+ from being mistaken for section headers and redirecting the parser.
151
+ - Lines starting with digits → never headers
152
+ - Lines containing date ranges → never headers
153
+ - Lines longer than 60 normalised chars → too long to be a header
154
+ - Lines with > 7 words → likely prose
155
  """
156
  if _BULLET_RE.match(raw_line.strip()):
157
  return None
158
 
159
+ # ── Table-row guard (root cause of volunteer entries bleeding into experience)
160
+ raw_stripped = raw_line.strip()
161
+ if raw_stripped.startswith("|") and raw_stripped.count("|") >= 2:
162
+ return None
163
 
164
+ line_norm = _normalize(_strip_md(_strip_html(stripped_line)))
165
  if not line_norm:
166
  return None
167
+ if re.match(r"^\d", line_norm):
168
  return None
169
+ if _PERIOD_RE.search(stripped_line):
170
  return None
171
+ if _YEAR_ONLY_RE.search(stripped_line):
172
  return None
173
+ if len(line_norm) > 60:
174
  return None
175
+ if len(line_norm.split()) > 7:
176
  return None
 
177
  if not re.search(r"[a-z]", line_norm):
178
  return None
179
 
 
185
  or kw in line_norm
186
  ):
187
  return section
 
188
  return None
189
 
190
 
191
  def _parse_cv_sections(cv_text: str) -> Dict[str, str]:
192
  current = "summary"
193
  sections: Dict[str, List[str]] = {k: [] for k in _SECTION_KEYWORDS}
 
194
  for raw_line in cv_text.splitlines():
195
  stripped = re.sub(r"^#+\s*", "", raw_line).strip()
196
  if not stripped:
197
  continue
 
198
  section = _detect_section(stripped, raw_line)
199
  if section:
200
  current = section
201
  continue
 
202
  sections[current].append(raw_line)
 
203
  return {k: "\n".join(v).strip() for k, v in sections.items()}
204
 
205
 
206
  # ---------------------------------------------------------------------------
207
  # Experience parser
 
 
 
 
 
208
  # ---------------------------------------------------------------------------
209
 
210
  _ROLE_WORDS = {
211
+ "engineer", "developer", "manager", "designer", "analyst", "intern",
212
+ "officer", "lead", "head", "director", "consultant", "assistant",
213
+ "specialist", "coordinator", "technician", "architect", "programmer",
214
+ "researcher", "executive", "trainer", "scientist", "strategist",
215
+ "advisor", "supervisor", "associate", "fellow",
216
+ # Healthcare
217
+ "nurse", "doctor", "pharmacist", "therapist", "teacher", "lecturer",
218
+ "instructor", "physiotherapist", "midwife", "clinician",
219
+ # Finance
220
+ "auditor", "accountant",
221
+ # Sales / other
222
+ "recruiter", "representative", "salesperson", "buyer",
223
+ # Intern variants
224
+ "attachment", "placement", "apprentice",
225
  }
226
 
227
 
228
  def _split_role_company(text: str) -> Tuple[str, str]:
 
 
 
 
 
229
  for pat in [r"\s+(?:at|@|with)\s+", r"\s*\|\s*", r"\s*[—–,]\s+"]:
230
  parts = re.split(pat, text, maxsplit=1)
231
  if len(parts) == 2:
 
236
  return a, b
237
  if b_is_role and not a_is_role:
238
  return b, a
 
239
  return a, b
240
  return "", text
241
 
 
252
  line = _clean_line(raw_line)
253
  if not line:
254
  continue
 
 
255
  if re.match(r"^[\w\s]+:\s*$", line) and len(line) < 40:
256
  continue
257
 
258
+ period = _extract_period(line)
259
+ is_bullet = bool(_BULLET_RE.match(line))
260
+ clean = _strip_period(_BULLET_RE.sub("", line)).strip()
261
 
 
262
  if is_bullet:
263
  if current is not None and clean:
264
  current["responsibilities"].append(clean)
265
  continue
266
 
 
267
  if period and not clean:
268
  if current is not None and not current["period"]:
269
  current["period"] = period
270
  continue
271
 
 
272
  if period and clean:
273
  role, company = _split_role_company(clean)
 
 
274
  if (
275
  current is not None
276
  and not current["period"]
277
  and (current["role"] or current["company"])
278
  ):
 
 
279
  if not current["role"] and role:
280
  current["role"] = role
281
  if not current["company"] and company:
 
290
  current["period"] = period
291
  continue
292
 
 
 
293
  is_role_line = any(w in clean.lower() for w in _ROLE_WORDS)
294
 
295
  if current is None:
 
296
  role, company = _split_role_company(clean)
297
  current = _new()
298
  current["role"] = role
299
  current["company"] = company
 
300
  elif not current["role"] and not current["company"]:
 
301
  role, company = _split_role_company(clean)
302
  current["role"] = role
303
  current["company"] = company
 
304
  elif (not current["role"] or not current["company"]) and not current["period"]:
 
305
  if not current["role"] and is_role_line:
306
  current["role"] = clean
307
  elif not current["company"] and not is_role_line:
308
  current["company"] = clean
309
  else:
 
310
  entries.append(current)
311
  role, company = _split_role_company(clean)
312
  current = _new()
313
  current["role"] = role
314
  current["company"] = company
 
315
  else:
 
316
  entries.append(current)
317
  role, company = _split_role_company(clean)
318
  current = _new()
 
321
 
322
  if current:
323
  entries.append(current)
 
324
  return [e for e in entries if e.get("company") or e.get("role")]
325
 
326
 
327
  # ---------------------------------------------------------------------------
328
  # Education parser
 
 
 
 
 
329
  # ---------------------------------------------------------------------------
330
 
331
  _DEGREE_RE = re.compile(
332
  r"\b(bachelor(?:'s)?|master(?:'s)?|phd|ph\.d|doctorate|diploma|certificate|"
333
  r"degree|bsc|msc|b\.sc|m\.sc|ba|ma|mba|hnd|hons|honours|kcse|kcpe|btec|"
334
+ r"associate(?:'s)?|advanced\s+diploma|form|grade)\b",
335
  re.IGNORECASE,
336
  )
337
  _INSTITUTION_RE = re.compile(
338
  r"\b(university|college|school|institute|polytechnic|academy|"
339
+ r"institution|faculty|campus|seminary)\b",
340
  re.IGNORECASE,
341
  )
 
342
  _EDU_SKIP_RE = re.compile(
343
  r"^(volunteer|leadership|activities|honors?|awards?|publications?|"
344
+ r"extracurricular|memberships?|certifications?)\\b",
345
  re.IGNORECASE,
346
  )
 
347
  _TABLE_SEP_RE = re.compile(r"^\|[\s\-|:]+\|$")
348
 
349
 
 
361
  current.clear()
362
 
363
  for raw_line in raw.splitlines():
 
364
  stripped_raw = raw_line.strip()
365
  if _TABLE_SEP_RE.match(stripped_raw):
366
  continue
 
 
367
  if stripped_raw.startswith("|") and stripped_raw.endswith("|"):
368
  cells = [_clean_line(c) for c in stripped_raw.strip("|").split("|")]
369
  cells = [c for c in cells if c]
370
  if not cells:
371
  continue
372
+ # Skip volunteer/leadership table rows
373
+ if re.match(r"^(volunteer|leadership)", cells[0], re.IGNORECASE):
374
+ _flush()
375
+ continue
376
+ line = cells[0]
377
  extra_period = _extract_period(cells[-1]) if len(cells) > 1 else None
378
  else:
379
  line = _clean_line(raw_line)
 
382
  line = _BULLET_RE.sub("", line).strip()
383
  if not line:
384
  continue
 
 
385
  if _EDU_SKIP_RE.match(line) and len(line) < 60:
386
  _flush()
387
  continue
 
397
  has_inst = bool(_INSTITUTION_RE.search(clean))
398
 
399
  if has_degree and has_inst:
 
400
  deg_m = _DEGREE_RE.search(clean)
401
  institution = clean[:deg_m.start()].strip(" ,–—|") if deg_m else ""
402
  degree = clean[deg_m.start():].strip() if deg_m else clean
 
404
  current["institution"] = institution
405
  current["degree"] = degree
406
  current["period"] = period or ""
 
407
  elif has_degree:
408
  if current.get("institution") and not current.get("degree"):
 
409
  current["degree"] = clean
410
  if period:
411
  current["period"] = period
 
414
  current["degree"] = clean
415
  current["institution"] = ""
416
  current["period"] = period or ""
 
417
  elif has_inst:
418
  if current.get("degree") and not current.get("institution"):
 
419
  current["institution"] = clean
420
  if period:
421
  current["period"] = period
 
424
  current["institution"] = clean
425
  current["degree"] = ""
426
  current["period"] = period or ""
 
427
  elif period:
 
428
  if current:
429
  current["period"] = period
430
  if clean and not current.get("degree"):
 
432
  else:
433
  current["institution"] = clean
434
  current["period"] = period
 
435
  else:
 
436
  if current and not current.get("institution") and not has_degree:
437
  current["institution"] = clean
438
  elif current and not current.get("degree"):
 
448
 
449
  # ---------------------------------------------------------------------------
450
  # Contact parser
 
 
 
 
451
  # ---------------------------------------------------------------------------
452
 
453
  _EMAIL_RE = re.compile(r"[\w.+-]+@[\w-]+\.[a-zA-Z]{2,}")
 
455
  _LOCATION_RE = re.compile(
456
  r"\b([A-Z][a-zA-Z]{2,}(?:\s[A-Z][a-zA-Z]{2,})*)\s*,\s*([A-Z][a-zA-Z]{2,}(?:\s[A-Z][a-zA-Z]{2,})*)\b"
457
  )
 
458
  _LABELLED_RE = re.compile(
459
  r"\b(?:location|address|city|based\s+in|residing\s+in|located\s+in)\s*[:\-]?\s*([^\n|•·,]+(?:,\s*[^\n|•·]+)?)",
460
  re.IGNORECASE,
 
462
 
463
 
464
  def _parse_contact(raw: str, cv_full: str) -> Dict[str, Any]:
 
 
 
 
 
 
 
 
 
465
  search_text = raw if raw.strip() else cv_full[:600]
 
466
  email_m = _EMAIL_RE.search(search_text)
467
  phone_m = _PHONE_RE.search(search_text)
468
 
 
469
  if raw.strip():
470
  loc_text = raw
471
  else:
 
473
  loc_text = "\n".join(header_lines)
474
 
475
  location = ""
 
 
476
  lbl_m = _LABELLED_RE.search(loc_text)
477
  if lbl_m:
478
  location = lbl_m.group(1).strip()
479
  else:
 
480
  loc_m = _LOCATION_RE.search(loc_text)
481
  if loc_m:
482
+ w1 = (loc_m.group(1) or "").lower()
483
+ w2 = (loc_m.group(2) or "").lower()
484
+ if w1 not in _TECH_LOC_BLACKLIST and w2 not in _TECH_LOC_BLACKLIST:
485
  location = loc_m.group(0).strip()
486
 
487
  return {
 
493
 
494
  # ---------------------------------------------------------------------------
495
  # Links parser
 
496
  # ---------------------------------------------------------------------------
497
 
498
  _URL_RE = re.compile(r"(?:https?://|www\.)[^\s,;\"'>()\]]+", re.IGNORECASE)
 
502
  r"[^\s,;\"'>()\]]*",
503
  re.IGNORECASE,
504
  )
 
505
 
506
  _PLATFORM_MAP: List[Tuple[str, str]] = [
507
  ("github.com", "GitHub"),
 
528
 
529
 
530
  def _label_url(url: str, context_line: str) -> str:
 
531
  url_lower = url.lower()
 
 
532
  for domain, label in _PLATFORM_MAP:
533
  if domain in url_lower:
534
  return label
 
 
535
  escaped = re.escape(url.split("?")[0].rstrip("/"))
536
  md_m = re.search(r"\[([^\]]+)\]\s*\(" + escaped, context_line, re.IGNORECASE)
537
  if md_m:
 
539
  for hint, label in _LABEL_HINTS.items():
540
  if hint in label_text:
541
  return label
 
 
542
  ctx = context_line.lower()
543
  for hint, label in _LABEL_HINTS.items():
544
  if hint in ctx:
545
  return label
 
546
  return "Website"
547
 
548
 
549
  def _parse_links(raw: str, cv_full: str) -> List[Dict[str, str]]:
 
 
 
 
 
 
550
  search_text = raw if raw.strip() else cv_full[:1500]
551
  results: List[Dict[str, str]] = []
552
  seen: Set[str] = set()
553
 
554
  for line in search_text.splitlines():
 
555
  found: List[str] = []
 
556
  for m in _URL_RE.finditer(line):
557
  found.append(m.group(0).rstrip(".,:;)\"'"))
 
 
558
  for m in _BARE_DOMAIN_RE.finditer(line):
559
  url = m.group(0).rstrip(".,:;)\"'")
560
  if not any(url in u for u in found):
561
  found.append(url)
 
562
  for url in found:
563
  normalised = url if url.startswith("http") else f"https://{url}"
564
  if normalised in seen:
 
570
 
571
 
572
  # ---------------------------------------------------------------------------
573
+ # Skills parser — returns technical / soft split
 
574
  # ---------------------------------------------------------------------------
575
 
 
576
  _SKILL_PREFIX_RE = re.compile(r"^\*{0,2}[\w][\w\s&/()+\-]+:\*{0,2}\s*")
577
 
578
 
579
  def _parse_skills(raw: str, cv_full: str) -> Dict[str, Any]:
580
  canonical = sorted(_extract_skills(cv_full, DEFAULT_SKILL_ALIASES))
581
+ technical = [s for s in canonical if s not in SOFT_SKILL_KEYS]
582
+ soft = [s for s in canonical if s in SOFT_SKILL_KEYS]
583
 
584
  raw_items: List[str] = []
585
  for line in raw.splitlines():
586
+ line = _clean_line(line)
587
  line = _BULLET_RE.sub("", line).strip()
588
+ line = _SKILL_PREFIX_RE.sub("", line).strip()
 
 
589
  for item in re.split(r"[,|;•·/]", line):
590
+ item = re.sub(r"^\W+|\W+$", "", item).strip()
 
591
  if (
592
  item
593
  and 1 < len(item) < 60
594
+ and not re.match(r"^\d+$", item)
595
+ and not re.search(r"@|http|www\.", item)
596
  ):
597
  raw_items.append(item)
598
 
 
599
  seen_items: Set[str] = set()
600
  deduped: List[str] = []
601
  for item in raw_items:
 
604
  seen_items.add(key)
605
  deduped.append(item)
606
 
607
+ return {
608
+ "items": deduped,
609
+ "canonical": canonical,
610
+ "technical": technical,
611
+ "soft": soft,
612
+ }
613
+
614
+
615
+ # ---------------------------------------------------------------------------
616
+ # Projects parser → [{name, description, tech_stack, url}]
617
+ # ---------------------------------------------------------------------------
618
+
619
+ def _parse_projects(raw: str) -> List[Dict[str, Any]]:
620
+ entries: List[Dict[str, Any]] = []
621
+
622
+ def _new_proj() -> Dict[str, Any]:
623
+ return {"name": "", "description": "", "tech_stack": [], "url": ""}
624
+
625
+ current: Optional[Dict[str, Any]] = None
626
+
627
+ for raw_line in raw.splitlines():
628
+ line = _clean_line(raw_line)
629
+ if not line:
630
+ continue
631
+ is_bullet = bool(_BULLET_RE.match(line))
632
+ clean = _BULLET_RE.sub("", line).strip()
633
+
634
+ url_m = _URL_RE.search(raw_line) or _BARE_DOMAIN_RE.search(raw_line)
635
+ url = url_m.group(0).rstrip(".,:;)\"'") if url_m else ""
636
+ if url and not url.startswith("http"):
637
+ url = f"https://{url}"
638
+
639
+ if is_bullet or current is None:
640
+ if current and current["name"]:
641
+ entries.append(current)
642
+ current = _new_proj()
643
+
644
+ tech_m = re.search(r"\(([^)]{2,80})\)", clean)
645
+ if tech_m:
646
+ current["tech_stack"] = [
647
+ t.strip() for t in tech_m.group(1).split(",") if t.strip()
648
+ ]
649
+ clean = clean.replace(tech_m.group(0), "").strip()
650
+
651
+ for sep in [":", "–", "—", " - "]:
652
+ if sep in clean:
653
+ parts = clean.split(sep, 1)
654
+ current["name"] = parts[0].strip()
655
+ current["description"] = parts[1].strip()
656
+ break
657
+ else:
658
+ clean_no_url = re.sub(r"(?:https?://|www\.)\S+", "", clean).strip()
659
+ current["name"] = clean_no_url or clean
660
+
661
+ current["url"] = url
662
+
663
+ elif current is not None:
664
+ if not current["description"] and clean:
665
+ current["description"] = clean
666
+ if url and not current["url"]:
667
+ current["url"] = url
668
+
669
+ if current and current["name"]:
670
+ entries.append(current)
671
+
672
+ return entries
673
+
674
+
675
+ # ---------------------------------------------------------------------------
676
+ # Awards parser → [{title, year, issuer}]
677
+ # ---------------------------------------------------------------------------
678
+
679
+ def _parse_awards(raw: str) -> List[Dict[str, str]]:
680
+ entries: List[Dict[str, str]] = []
681
+
682
+ for raw_line in raw.splitlines():
683
+ line = _clean_line(raw_line)
684
+ line = _BULLET_RE.sub("", line).strip()
685
+ if not line:
686
+ continue
687
+
688
+ period = _extract_period(line)
689
+ year = ""
690
+ if period:
691
+ year_m = re.search(r"\d{4}", period)
692
+ year = year_m.group(0) if year_m else ""
693
+
694
+ clean = _strip_period(line).strip()
695
+ if not clean:
696
+ continue
697
+
698
+ issuer = ""
699
+ title = clean
700
+ for sep in [" by ", " from ", ", ", " — ", " – ", " - "]:
701
+ if sep.lower() in clean.lower():
702
+ idx = clean.lower().index(sep.lower())
703
+ title = clean[:idx].strip()
704
+ issuer = clean[idx + len(sep):].strip()
705
+ break
706
+
707
+ entries.append({"title": title, "year": year, "issuer": issuer})
708
+
709
+ return entries
710
+
711
+
712
+ # ---------------------------------------------------------------------------
713
+ # Completeness score
714
+ # ---------------------------------------------------------------------------
715
+
716
+ def _compute_completeness(
717
+ cv_title: str,
718
+ years: int,
719
+ contact: Dict[str, Any],
720
+ skills_chunk: Dict[str, Any],
721
+ experience: List[Dict[str, Any]],
722
+ education: List[Dict[str, Any]],
723
+ summary: str,
724
+ links: List[Dict[str, str]],
725
+ ) -> int:
726
+ """Returns 0–100 score indicating how complete the parsed CV is."""
727
+ score = 0
728
+ if summary and len(summary) > 50: score += 20
729
+ if experience: score += 25
730
+ if len(skills_chunk.get("items", [])) >= 3: score += 15
731
+ if education: score += 15
732
+ if contact.get("email"): score += 10
733
+ if years > 0: score += 5
734
+ if links: score += 5
735
+ if cv_title and cv_title != "Unknown": score += 5
736
+ return min(100, score)
737
 
738
 
739
  # ---------------------------------------------------------------------------
740
  # Public API
741
  # ---------------------------------------------------------------------------
742
 
743
+ def chunk_cv(cv_markdown: str, embedder=None) -> Dict[str, Any]:
744
  """
745
  Parse any CV markdown string into structured, cleaned chunks.
746
 
747
+ Parameters
748
+ ----------
749
+ cv_markdown : str
750
+ Raw markdown output from CVConverter.
751
+ embedder : callable, optional
752
+ A function ``(text: str) -> np.ndarray`` (e.g. ``matcher._embed``).
753
+ When provided, section-aware embeddings are computed once here and
754
+ returned under ``section_embeddings`` so ``/match-cv`` can reuse
755
+ them without re-encoding.
756
+
757
  Returns
758
  -------
759
+ dict with keys:
760
+ cv_title, seniority, years_experience, category,
761
+ completeness_score, chunks{...},
762
+ section_embeddings (only when embedder is given)
 
 
 
 
 
 
 
 
 
 
 
 
763
  """
764
  sections = _parse_cv_sections(cv_markdown)
765
 
766
+ # ── Title ──────────────────────────────────────────────────────────────
767
+ cv_title = _extract_cv_title(cv_markdown, clean_line_fn=_clean_line)
768
+
769
+ # ── Skills & category ──────────────────────────────────────────────────
770
+ cv_skills = _extract_skills(cv_markdown, DEFAULT_SKILL_ALIASES)
771
  cv_category = _infer_category(cv_markdown, cv_skills, DEFAULT_CATEGORY_SKILLS)
772
 
773
+ # ── Parse structured sections ─────────────────────────────────────────
774
+ contact_chunk = _parse_contact(sections.get("contact", ""), cv_markdown)
775
+ links_chunk = _parse_links(sections.get("links", ""), cv_markdown)
776
+ skills_chunk = _parse_skills(sections.get("skills", ""), cv_markdown)
777
+ experience_entries = _parse_experience(sections.get("experience", ""))
778
+ education_entries = _parse_education(sections.get("education", ""))
779
+ projects_entries = _parse_projects(sections.get("projects", ""))
780
+ awards_entries = _parse_awards(sections.get("awards", ""))
781
+
782
+ # ── Years of experience: date-ranges primary, text mention fallback ────
783
+ computed_years = compute_years_from_experience(experience_entries)
784
+ text_years = _extract_years(cv_markdown)
785
+ cv_years = computed_years if computed_years > 0 else text_years
786
+
787
+ # ── Seniority: keyword detection then refine with years ────────────────
788
  seniority_text = (
789
  cv_title + "\n"
790
  + sections.get("experience", "")
791
  + "\n" + cv_markdown[:600]
792
  )
793
  cv_seniority = _detect_seniority(seniority_text, is_cv=True)
794
+ cv_seniority = refine_seniority_with_years(cv_seniority, cv_years)
795
 
796
+ # ── Completeness ───────────────────────────────────────────────────────
797
+ completeness = _compute_completeness(
798
+ cv_title, cv_years, contact_chunk, skills_chunk,
799
+ experience_entries, education_entries,
800
+ sections.get("summary", ""), links_chunk,
801
+ )
802
+
803
+ result: Dict[str, Any] = {
804
+ "cv_title": cv_title,
805
+ "seniority": cv_seniority,
806
+ "years_experience": cv_years,
807
+ "category": cv_category,
808
+ "completeness_score": completeness,
809
  "chunks": {
810
  "summary": sections.get("summary", "").strip(),
811
+ "contact": contact_chunk,
812
+ "links": links_chunk,
813
+ "skills": skills_chunk,
814
+ "experience": experience_entries,
815
+ "education": education_entries,
816
+ "projects": projects_entries,
817
+ "awards": awards_entries,
818
  },
819
  }
820
 
821
+ # ── Optional: section-aware ML embeddings ─────────────────────────────
822
+ if embedder is not None:
823
+ summary_text = sections.get("summary", "").strip()
824
+ skills_text = " ".join(skills_chunk["items"])[:2000]
825
+ exp_text = " ".join(
826
+ f"{e.get('role', '')} at {e.get('company', '')} "
827
+ + " ".join(e.get("responsibilities", []))
828
+ for e in experience_entries
829
+ )[:3000]
830
+
831
+ result["section_embeddings"] = {
832
+ "summary": embedder(summary_text).tolist() if summary_text else None,
833
+ "skills": embedder(skills_text).tolist() if skills_text else None,
834
+ "experience": embedder(exp_text).tolist() if exp_text else None,
835
+ }
836
 
837
+ return result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
services/cv_utils.py ADDED
@@ -0,0 +1,613 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ cv_utils.py
3
+ ===========
4
+ Shared taxonomy data and pure helper functions used by both
5
+ cv_chunker.py and job_matcher.py.
6
+
7
+ All skill aliases, category mappings, seniority patterns, and
8
+ normalisation utilities live here so both consumers stay in sync.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import re
13
+ from datetime import datetime as _dt
14
+ from typing import Any, Dict, List, Optional, Set, Tuple
15
+
16
+
17
+ # ---------------------------------------------------------------------------
18
+ # Universal Skill Taxonomy
19
+ # ---------------------------------------------------------------------------
20
+
21
+ DEFAULT_SKILL_ALIASES: Dict[str, List[str]] = {
22
+ # ── Office / Admin ──────────────────────────────────────────────────────
23
+ "microsoft word": ["microsoft word", "ms word", "word"],
24
+ "microsoft excel": ["microsoft excel", "ms excel", "excel", "spreadsheets"],
25
+ "microsoft powerpoint": ["microsoft powerpoint", "ms powerpoint", "powerpoint", "power point"],
26
+ "microsoft outlook": ["microsoft outlook", "ms outlook", "outlook"],
27
+ "microsoft office": ["microsoft office", "ms office", "office suite", "office 365", "microsoft 365"],
28
+ "google workspace": ["google workspace", "google docs", "google sheets", "google slides", "gsuite", "g suite"],
29
+ "data entry": ["data entry", "typing", "data input", "data capture"],
30
+ "filing": ["filing", "document management", "records management", "file management", "document control"],
31
+ "scheduling": ["scheduling", "calendar management", "appointment setting", "diary management"],
32
+ "communication": ["communication", "communicate", "interpersonal", "verbal communication", "written communication"],
33
+ "teamwork": ["teamwork", "team work", "team player", "collaboration", "team member"],
34
+ "customer service": ["customer service", "client service", "customer support", "client relations"],
35
+ "problem solving": ["problem solving", "problem-solving", "critical thinking", "analytical thinking"],
36
+ "time management": ["time management", "prioritization", "prioritisation", "multitasking"],
37
+ "reporting": ["reporting", "report writing", "report generation", "daily report", "weekly report"],
38
+ "inventory management": ["inventory management", "inventory", "stock control", "stock management", "stock checking"],
39
+ "warehouse": ["warehouse", "stockroom", "store room", "stores"],
40
+ "leadership": ["leadership", "team leadership", "people management"],
41
+ "attention to detail": ["attention to detail", "accuracy", "meticulous"],
42
+ "adaptability": ["adaptability", "adaptable", "flexible"],
43
+
44
+ # ── Finance & Accounting ────────────────────────────────────────────────
45
+ "accounting": ["accounting", "accountancy", "bookkeeping", "accounts"],
46
+ "financial analysis": ["financial analysis", "financial modelling", "financial modeling", "financial reporting", "financial planning"],
47
+ "auditing": ["auditing", "internal audit", "external audit", "audit", "statutory audit"],
48
+ "taxation": ["taxation", "tax", "tax compliance", "tax preparation", "tax returns", "vat"],
49
+ "payroll": ["payroll", "payroll processing", "payroll management", "payroll administration"],
50
+ "budgeting": ["budgeting", "budget management", "budget planning", "forecasting", "variance analysis"],
51
+ "accounts payable": ["accounts payable", "vendor payments", "creditors"],
52
+ "accounts receivable": ["accounts receivable", "invoicing", "debtors", "collections"],
53
+ "quickbooks": ["quickbooks", "quick books"],
54
+ "sage": ["sage", "sage accounting", "sage 50", "sage 200"],
55
+ "sap": ["sap", "sap finance", "sap erp", "sap s/4hana", "sap fico"],
56
+ "xero": ["xero"],
57
+ "ifrs": ["ifrs", "international financial reporting standards"],
58
+ "gaap": ["gaap", "generally accepted accounting principles"],
59
+ "reconciliation": ["reconciliation", "bank reconciliation", "account reconciliation"],
60
+ "cash flow": ["cash flow", "cash management", "treasury"],
61
+
62
+ # ── Human Resources ─────────────────────────────────────────────────────
63
+ "recruitment": ["recruitment", "recruiting", "talent acquisition", "hiring", "staffing", "talent sourcing"],
64
+ "onboarding": ["onboarding", "new hire orientation", "induction"],
65
+ "performance management":["performance management", "performance review", "appraisal", "kpi management"],
66
+ "employee relations": ["employee relations", "labour relations", "labor relations", "grievance handling"],
67
+ "training and development": ["training", "learning and development", "l&d", "employee training", "talent development"],
68
+ "hris": ["hris", "hr information system", "workday", "bamboohr", "zoho hr", "oracle hcm"],
69
+ "compensation": ["compensation", "benefits", "compensation and benefits", "remuneration", "total rewards"],
70
+ "hr compliance": ["hr compliance", "compliance", "regulatory compliance", "employment law"],
71
+ "job analysis": ["job analysis", "job description", "job evaluation"],
72
+
73
+ # ── Sales & Business Development ────────────────────────────────────────
74
+ "sales": ["sales", "selling", "business development", "b2b sales", "b2c sales", "direct sales"],
75
+ "crm": ["crm", "salesforce", "hubspot", "zoho crm", "customer relationship management", "pipedrive"],
76
+ "negotiation": ["negotiation", "contract negotiation", "deal closing"],
77
+ "lead generation": ["lead generation", "prospecting", "cold calling", "cold outreach"],
78
+ "account management": ["account management", "key account management", "client management"],
79
+ "retail": ["retail", "retail sales", "merchandising", "point of sale", "pos"],
80
+ "business analysis": ["business analysis", "business analyst", "requirements gathering", "process improvement"],
81
+
82
+ # ── Customer Support ────────────────────────────────────────────────────
83
+ "help desk": ["help desk", "helpdesk", "it support", "technical support", "service desk"],
84
+ "ticketing systems": ["ticketing", "zendesk", "freshdesk", "jira service desk", "servicenow"],
85
+ "call centre": ["call centre", "call center", "contact centre", "contact center", "inbound calls", "outbound calls"],
86
+
87
+ # ── Healthcare ──────────────────────────────────────────────────────────
88
+ "patient care": ["patient care", "patient management", "bedside manner", "patient assessment"],
89
+ "nursing": ["nursing", "registered nurse", "rn", "clinical nursing", "enrolled nurse"],
90
+ "clinical skills": ["clinical", "clinical skills", "clinical assessment", "clinical procedures"],
91
+ "pharmacy": ["pharmacy", "dispensing", "pharmaceutical", "pharmacology"],
92
+ "first aid": ["first aid", "cpr", "bls", "basic life support", "acls", "emergency response"],
93
+ "medical records": ["medical records", "ehr", "electronic health records", "emr", "medical documentation"],
94
+ "infection control": ["infection control", "infection prevention", "ips", "sterilization"],
95
+ "midwifery": ["midwifery", "obstetrics", "maternity", "antenatal", "postnatal"],
96
+ "physiotherapy": ["physiotherapy", "physical therapy", "rehabilitation"],
97
+ "laboratory": ["laboratory", "lab technician", "medical laboratory", "specimen processing"],
98
+
99
+ # ── Legal ───────────────────────────────────────────────────────────────
100
+ "legal research": ["legal research", "case research", "statute interpretation"],
101
+ "contract drafting": ["contract drafting", "contract review", "drafting agreements", "legal drafting"],
102
+ "litigation": ["litigation", "court proceedings", "legal proceedings", "advocacy"],
103
+ "legal compliance": ["legal compliance", "regulatory affairs", "regulatory compliance"],
104
+ "conveyancing": ["conveyancing", "property law", "land transactions"],
105
+ "corporate law": ["corporate law", "company law", "corporate governance"],
106
+ "legal writing": ["legal writing", "pleadings", "legal opinions", "memoranda"],
107
+
108
+ # ── Education & Training ────────────────────────────────────────────────
109
+ "teaching": ["teaching", "instruction", "lecturing", "tutoring", "classroom teaching"],
110
+ "curriculum development":["curriculum development", "curriculum design", "lesson planning", "scheme of work"],
111
+ "classroom management": ["classroom management", "student management", "behaviour management"],
112
+ "e-learning": ["e-learning", "elearning", "lms", "moodle", "online learning", "instructional design"],
113
+ "assessment": ["assessment", "grading", "marking", "examination", "evaluation"],
114
+ "mentoring": ["mentoring", "mentorship", "coaching", "academic guidance"],
115
+
116
+ # ── Operations & Logistics ──────────────────────────────────────────────
117
+ "supply chain": ["supply chain", "supply chain management", "scm"],
118
+ "procurement": ["procurement", "purchasing", "vendor management", "sourcing", "tendering"],
119
+ "logistics": ["logistics", "fleet management", "transportation management", "freight", "delivery"],
120
+ "quality control": ["quality control", "qc", "quality assurance", "qa", "iso", "quality management"],
121
+ "project management": ["project management", "pmp", "prince2", "agile project management", "project planning"],
122
+ "lean": ["lean", "lean manufacturing", "lean six sigma", "continuous improvement", "kaizen"],
123
+ "six sigma": ["six sigma", "6 sigma", "dmaic"],
124
+
125
+ # ── Software Engineering ────────────────────────────────────────────────
126
+ "html": ["html", "html5"],
127
+ "css": ["css", "css3"],
128
+ "javascript": ["javascript", "js"],
129
+ "typescript": ["typescript", "ts"],
130
+ "react": ["react", "react.js", "reactjs"],
131
+ "next.js": ["next.js", "nextjs"],
132
+ "vue": ["vue", "vue.js", "vuejs"],
133
+ "angular": ["angular"],
134
+ "tailwind css": ["tailwind", "tailwind css"],
135
+ "node.js": ["node", "node.js", "nodejs"],
136
+ "express.js": ["express", "express.js"],
137
+ "python": ["python"],
138
+ "java": ["java"],
139
+ "kotlin": ["kotlin"],
140
+ "android": ["android", "android studio"],
141
+ "php": ["php"],
142
+ "laravel": ["laravel"],
143
+ "mysql": ["mysql"],
144
+ "postgresql": ["postgresql", "postgres", "supabase"],
145
+ "mongodb": ["mongodb", "mongo"],
146
+ "rest api": ["rest api", "restful api", "api development"],
147
+ "git": ["git", "github", "gitlab"],
148
+ "docker": ["docker"],
149
+ "spring boot": ["spring boot", "spring", "spring framework"],
150
+ "ci/cd": ["ci/cd", "ci cd", "github actions", "jenkins", "gitlab ci", "pipelines", "devops"],
151
+ "kubernetes": ["kubernetes", "k8s"],
152
+ "aws": ["aws", "amazon web services"],
153
+ "azure": ["azure", "microsoft azure"],
154
+ "gcp": ["gcp", "google cloud"],
155
+ "flutter": ["flutter"],
156
+ "dart": ["dart"],
157
+ "swift": ["swift"],
158
+ "ios": ["ios", "xcode"],
159
+ "c#": ["c#", "csharp", "c sharp"],
160
+ "c++": ["c++", "cpp"],
161
+ "rust": ["rust"],
162
+ "go": ["golang", "go lang"],
163
+ "redis": ["redis"],
164
+ "elasticsearch": ["elasticsearch", "elastic search"],
165
+ "graphql": ["graphql"],
166
+ "machine learning": ["machine learning", "ml", "deep learning", "neural networks"],
167
+ "sql": ["sql", "pl/sql", "t-sql"],
168
+ "data analysis": ["data analysis", "analytics", "data analytics"],
169
+
170
+ # ── Design & Creative ───────────────────────────────────────────────────
171
+ "ui design": ["ui design", "user interface design", "ui"],
172
+ "ux design": ["ux design", "user experience design", "ux", "usability"],
173
+ "figma": ["figma"],
174
+ "wireframing": ["wireframe", "wireframing"],
175
+ "prototyping": ["prototype", "prototyping"],
176
+ "adobe photoshop": ["photoshop", "adobe photoshop"],
177
+ "adobe illustrator": ["illustrator", "adobe illustrator"],
178
+ "adobe xd": ["adobe xd", "xd"],
179
+ "graphic design": ["graphic design", "graphics", "visual design"],
180
+ "video editing": ["video editing", "video production", "premiere pro", "final cut pro", "davinci resolve"],
181
+ "photography": ["photography", "photo editing", "lightroom", "photo retouching"],
182
+
183
+ # ── Marketing ───────────────────────────────────────────────────────────
184
+ "seo": ["seo", "search engine optimization", "search engine optimisation"],
185
+ "content writing": ["content writing", "copywriting", "content creation", "blog writing"],
186
+ "digital marketing": ["digital marketing", "online marketing", "marketing campaigns", "marketing strategy"],
187
+ "social media": ["social media", "social media management", "instagram", "facebook marketing", "tiktok", "twitter"],
188
+ "email marketing": ["email marketing", "mailchimp", "email campaigns", "newsletter"],
189
+ "google analytics": ["google analytics", "ga4", "web analytics"],
190
+ "google ads": ["google ads", "google adwords", "ppc", "pay per click", "sem"],
191
+ "facebook ads": ["facebook ads", "meta ads", "social media advertising"],
192
+ "brand management": ["brand management", "branding", "brand strategy"],
193
+
194
+ # ── Data & Analytics ────────────────────────────────────────────────────
195
+ "power bi": ["power bi", "powerbi", "power bi desktop"],
196
+ "tableau": ["tableau"],
197
+ "r": ["r programming", "r language", "rstudio"],
198
+ "data science": ["data science", "data scientist"],
199
+ "statistics": ["statistics", "statistical analysis", "spss", "stata"],
200
+ "data visualization": ["data visualization", "data visualisation", "data viz"],
201
+ }
202
+
203
+
204
+ DEFAULT_CATEGORY_SKILLS: Dict[str, Set[str]] = {
205
+ "Admin & Office": {
206
+ "microsoft word", "microsoft excel", "microsoft powerpoint", "microsoft office",
207
+ "google workspace", "data entry", "filing", "scheduling", "communication",
208
+ "teamwork", "customer service", "reporting", "inventory management",
209
+ "warehouse", "time management", "attention to detail",
210
+ },
211
+ "Software Engineering": {
212
+ "html", "css", "javascript", "typescript", "react", "next.js", "vue",
213
+ "angular", "tailwind css", "node.js", "express.js", "python", "java",
214
+ "kotlin", "android", "php", "laravel", "mysql", "postgresql", "mongodb",
215
+ "rest api", "git", "docker", "spring boot", "ci/cd", "kubernetes",
216
+ "aws", "azure", "gcp", "flutter", "dart", "swift", "ios", "c#", "c++",
217
+ "rust", "go", "redis", "elasticsearch", "graphql", "sql",
218
+ },
219
+ "Design & Creative": {
220
+ "ui design", "ux design", "figma", "wireframing", "prototyping",
221
+ "adobe photoshop", "adobe illustrator", "adobe xd", "graphic design",
222
+ "video editing", "photography",
223
+ },
224
+ "Marketing & Growth": {
225
+ "seo", "content writing", "digital marketing", "social media",
226
+ "email marketing", "google analytics", "google ads", "facebook ads",
227
+ "brand management",
228
+ },
229
+ "Data & Analytics": {
230
+ "sql", "python", "machine learning", "data analysis", "microsoft excel",
231
+ "power bi", "tableau", "r", "data science", "statistics", "data visualization",
232
+ "elasticsearch",
233
+ },
234
+ "Finance & Accounting": {
235
+ "accounting", "financial analysis", "auditing", "taxation", "payroll",
236
+ "budgeting", "accounts payable", "accounts receivable", "quickbooks",
237
+ "sage", "sap", "xero", "ifrs", "gaap", "reconciliation", "cash flow",
238
+ "microsoft excel",
239
+ },
240
+ "Human Resources": {
241
+ "recruitment", "onboarding", "performance management", "employee relations",
242
+ "training and development", "hris", "compensation", "hr compliance",
243
+ "job analysis", "communication", "microsoft excel",
244
+ },
245
+ "Sales & Business Dev": {
246
+ "sales", "crm", "negotiation", "lead generation", "account management",
247
+ "retail", "communication", "customer service",
248
+ },
249
+ "Healthcare": {
250
+ "patient care", "nursing", "clinical skills", "pharmacy", "first aid",
251
+ "medical records", "infection control", "midwifery", "physiotherapy",
252
+ "laboratory",
253
+ },
254
+ "Legal": {
255
+ "legal research", "contract drafting", "litigation", "legal compliance",
256
+ "conveyancing", "corporate law", "legal writing",
257
+ },
258
+ "Education & Training": {
259
+ "teaching", "curriculum development", "classroom management", "e-learning",
260
+ "assessment", "mentoring", "communication",
261
+ },
262
+ "Operations & Logistics": {
263
+ "supply chain", "procurement", "logistics", "quality control",
264
+ "project management", "lean", "six sigma", "inventory management",
265
+ "reporting",
266
+ },
267
+ "Customer Support": {
268
+ "customer service", "help desk", "ticketing systems", "call centre",
269
+ "communication", "crm", "reporting",
270
+ },
271
+ }
272
+
273
+
274
+ SENIORITY_PATTERNS: Dict[str, List[str]] = {
275
+ "intern": [
276
+ "intern", "internship", "trainee", "industrial attachment",
277
+ "attachment student", "graduate trainee", "pupil",
278
+ ],
279
+ "junior": [
280
+ "junior", "entry level", "entry-level", "assistant", "fresh graduate",
281
+ "graduate", "associate", "junior officer", "junior analyst",
282
+ ],
283
+ "mid": [
284
+ "mid", "middle", "officer", "specialist", "developer", "designer",
285
+ "engineer", "analyst", "coordinator", "technician", "executive",
286
+ "consultant", "representative",
287
+ ],
288
+ "senior": [
289
+ "senior", "lead", "manager", "head", "principal", "architect",
290
+ "director", "vp", "vice president", "chief", "cto", "ceo", "coo",
291
+ "cfo", "superintendent", "supervisor", "managing",
292
+ ],
293
+ }
294
+
295
+ SENIORITY_ORDER: Dict[str, int] = {"intern": 0, "junior": 1, "mid": 2, "senior": 3}
296
+
297
+
298
+ # Words that look like "City, Country" but are actually tech terms
299
+ _TECH_LOC_BLACKLIST: Set[str] = {
300
+ "java", "spring", "boot", "sql", "python", "node", "react", "angular",
301
+ "vue", "docker", "linux", "windows", "android", "swift", "kotlin",
302
+ "scala", "ruby", "rails", "django", "flask", "express", "mongo",
303
+ "postgres", "redis", "kafka", "hadoop", "spark", "airflow", "jenkins",
304
+ "gitlab", "github", "bitbucket", "jira", "confluence", "slack", "figma",
305
+ "oracle", "mysql", "azure", "aws", "gcp",
306
+ }
307
+
308
+
309
+ # ---------------------------------------------------------------------------
310
+ # Soft-skill keys (used by chunker to split canonical list)
311
+ # ---------------------------------------------------------------------------
312
+
313
+ SOFT_SKILL_KEYS: Set[str] = {
314
+ "communication", "teamwork", "problem solving", "time management",
315
+ "customer service", "mentoring", "negotiation", "leadership",
316
+ "reporting", "scheduling", "filing", "adaptability", "attention to detail",
317
+ }
318
+
319
+
320
+ # ---------------------------------------------------------------------------
321
+ # Title role words & phrase regex (universal)
322
+ # ---------------------------------------------------------------------------
323
+
324
+ TITLE_ROLE_WORDS: List[str] = [
325
+ # Tech
326
+ "developer", "engineer", "programmer", "architect", "devops",
327
+ # General
328
+ "officer", "designer", "assistant", "accountant", "manager", "analyst",
329
+ "specialist", "coordinator", "director", "executive", "lead", "scientist",
330
+ "strategist", "advisor", "trainer", "consultant", "researcher", "technician",
331
+ "supervisor", "associate", "administrator",
332
+ # Healthcare
333
+ "nurse", "doctor", "physician", "pharmacist", "therapist", "clinician",
334
+ "midwife", "radiographer", "physiotherapist",
335
+ # Finance
336
+ "auditor", "bookkeeper", "controller", "treasurer",
337
+ # HR
338
+ "recruiter",
339
+ # Sales
340
+ "salesperson", "representative", "agent", "broker",
341
+ # Education
342
+ "teacher", "instructor", "lecturer", "professor", "tutor",
343
+ # Other
344
+ "admin", "intern", "student", "cashier", "marketing",
345
+ "procurement", "buyer", "dispatcher",
346
+ ]
347
+
348
+ TITLE_PHRASE_RE = re.compile(
349
+ r"\b((?:(?:full[\s\-]?stack|front[\s\-]?end|back[\s\-]?end|senior|junior|lead|"
350
+ r"mid[\s\-]?level|entry[\s\-]?level|chief|head\s+of)\s+)?(?:[\w\-]+\s){0,3}"
351
+ r"(?:developer|engineer|designer|analyst|manager|specialist|consultant|architect|"
352
+ r"programmer|researcher|officer|director|executive|scientist|trainer|accountant|"
353
+ r"nurse|doctor|pharmacist|therapist|teacher|instructor|lecturer|recruiter|"
354
+ r"coordinator|supervisor|administrator|technician|advisor|auditor|bookkeeper|"
355
+ r"physiotherapist|midwife|clinician|representative|salesperson|buyer|dispatcher))\b",
356
+ re.IGNORECASE,
357
+ )
358
+
359
+
360
+ # ---------------------------------------------------------------------------
361
+ # Normalisation helpers
362
+ # ---------------------------------------------------------------------------
363
+
364
+ def _normalize(text: str) -> str:
365
+ text = (text or "").lower()
366
+ text = text.replace("/", " ").replace("_", " ")
367
+ text = re.sub(r"[^a-z0-9+.#\s-]", " ", text)
368
+ return re.sub(r"\s+", " ", text).strip()
369
+
370
+
371
+ def _has_alias(text_norm: str, alias: str) -> bool:
372
+ alias_norm = _normalize(alias)
373
+ if not alias_norm:
374
+ return False
375
+ return re.search(rf"(?<![a-z0-9]){re.escape(alias_norm)}(?![a-z0-9])", text_norm) is not None
376
+
377
+
378
+ # ---------------------------------------------------------------------------
379
+ # Skill extraction
380
+ # ---------------------------------------------------------------------------
381
+
382
+ def _extract_skills(
383
+ text: str,
384
+ aliases: Optional[Dict[str, List[str]]] = None,
385
+ ) -> Set[str]:
386
+ if aliases is None:
387
+ aliases = DEFAULT_SKILL_ALIASES
388
+ text_norm = _normalize(text)
389
+ return {
390
+ canon
391
+ for canon, ali_list in aliases.items()
392
+ if any(_has_alias(text_norm, a) for a in ali_list)
393
+ }
394
+
395
+
396
+ # ---------------------------------------------------------------------------
397
+ # Category inference (universal)
398
+ # ---------------------------------------------------------------------------
399
+
400
+ _CATEGORY_TITLE_KEYWORDS: Dict[str, List[str]] = {
401
+ "Admin & Office": ["admin", "office", "stock", "inventory", "warehouse", "cashier", "receptionist", "clerk"],
402
+ "Software Engineering": ["developer", "engineer", "programmer", "frontend", "backend", "full stack", "mobile", "fullstack", "software", "devops"],
403
+ "Design & Creative": ["designer", "ui", "ux", "creative", "graphic", "visual", "illustrator", "photographer"],
404
+ "Marketing & Growth": ["marketing", "seo", "content", "social media", "growth", "digital", "brand"],
405
+ "Data & Analytics": ["data", "analyst", "analytics", "machine learning", "ai", "scientist", "bi", "intelligence"],
406
+ "Finance & Accounting": ["accountant", "finance", "accounting", "auditor", "bookkeeper", "treasurer", "payroll", "tax", "financial"],
407
+ "Human Resources": ["hr", "human resource", "recruitment", "recruiter", "talent", "people", "hris"],
408
+ "Sales & Business Dev": ["sales", "business development", "account manager", "sales executive", "representative"],
409
+ "Healthcare": ["nurse", "doctor", "clinical", "medical", "pharmacy", "patient", "health", "therapist", "midwife", "radiographer"],
410
+ "Legal": ["legal", "lawyer", "attorney", "advocate", "counsel", "paralegal", "solicitor"],
411
+ "Education & Training": ["teacher", "lecturer", "tutor", "instructor", "educator", "academic", "trainer", "professor"],
412
+ "Operations & Logistics":["logistics", "supply chain", "procurement", "operations", "fleet", "warehouse manager", "quality"],
413
+ "Customer Support": ["customer support", "help desk", "call centre", "contact centre", "customer care"],
414
+ }
415
+
416
+
417
+ def _infer_category(
418
+ text: str,
419
+ skills: Set[str],
420
+ category_skills: Optional[Dict[str, Set[str]]] = None,
421
+ ) -> str:
422
+ if category_skills is None:
423
+ category_skills = DEFAULT_CATEGORY_SKILLS
424
+ text_norm = _normalize(text)
425
+ best, best_score = "Other", 0.0
426
+ for cat, cat_skills in category_skills.items():
427
+ skill_overlap = len(skills & cat_skills)
428
+ kw_hits = sum(1 for kw in _CATEGORY_TITLE_KEYWORDS.get(cat, []) if kw in text_norm)
429
+ score = skill_overlap * 2.0 + kw_hits * 1.25
430
+ if score > best_score:
431
+ best_score, best = score, cat
432
+ return best
433
+
434
+
435
+ # ---------------------------------------------------------------------------
436
+ # Years-of-experience extraction (text mention)
437
+ # ---------------------------------------------------------------------------
438
+
439
+ def _extract_years(text: str) -> int:
440
+ text_norm = _normalize(text)
441
+ patterns = [
442
+ r"(\d+)\+?\s*(?:years|year|yrs|yr)\s*(?:of)?\s*(?:experience|exp)",
443
+ r"experience\s*(?:of)?\s*(\d+)\+?\s*(?:years|year|yrs|yr)",
444
+ r"(\d+)\+?\s*(?:years|year|yrs|yr)\s+(?:in\s+)?(?:the\s+)?(?:industry|field|software|development|practice|profession)",
445
+ ]
446
+ years = [int(m.group(1)) for p in patterns for m in re.finditer(p, text_norm)]
447
+ return max(years) if years else 0
448
+
449
+
450
+ # ---------------------------------------------------------------------------
451
+ # Years computed from parsed experience date ranges (more accurate)
452
+ # ---------------------------------------------------------------------------
453
+
454
+ _MONTH_SHORT: Dict[str, int] = {
455
+ "jan": 1, "feb": 2, "mar": 3, "apr": 4, "may": 5, "jun": 6,
456
+ "jul": 7, "aug": 8, "sep": 9, "oct": 10, "nov": 11, "dec": 12,
457
+ }
458
+
459
+
460
+ def _parse_date_token(token: str) -> Optional[_dt]:
461
+ token = token.strip().lower()
462
+ if re.match(r"present|current|now|ongoing|till\s*date|to\s*date", token):
463
+ return _dt.now()
464
+ m = re.match(r"([a-z]+)\s+(\d{4})", token)
465
+ if m:
466
+ month = _MONTH_SHORT.get(m.group(1)[:3], 1)
467
+ try:
468
+ return _dt(int(m.group(2)), month, 1)
469
+ except ValueError:
470
+ return None
471
+ m = re.match(r"(\d{4})", token)
472
+ if m:
473
+ return _dt(int(m.group(1)), 6, 1) # mid-year when month unknown
474
+ return None
475
+
476
+
477
+ def compute_years_from_experience(entries: List[Dict[str, Any]]) -> int:
478
+ """Sum date-range durations across all experience entries → total years."""
479
+ total_months = 0
480
+ for entry in entries:
481
+ period = (entry.get("period") or "").strip()
482
+ if not period:
483
+ continue
484
+ parts = re.split(r"\s*[-–—]\s*", period, maxsplit=1)
485
+ if len(parts) != 2:
486
+ continue
487
+ start = _parse_date_token(parts[0])
488
+ end = _parse_date_token(parts[1])
489
+ if start and end and end > start:
490
+ months = (end.year - start.year) * 12 + (end.month - start.month)
491
+ total_months += max(0, months)
492
+ return total_months // 12
493
+
494
+
495
+ # ---------------------------------------------------------------------------
496
+ # Seniority detection
497
+ # ---------------------------------------------------------------------------
498
+
499
+ def _detect_seniority(text: str, *, is_cv: bool = False) -> str:
500
+ text_norm = _normalize(text)
501
+ order = ["senior", "junior", "intern", "mid"] if is_cv else ["senior", "intern", "junior", "mid"]
502
+ for level in order:
503
+ if any(_has_alias(text_norm, term) for term in SENIORITY_PATTERNS[level]):
504
+ return level
505
+ years = _extract_years(text)
506
+ if years >= 7:
507
+ return "senior"
508
+ if years >= 3:
509
+ return "mid"
510
+ return "junior" if is_cv else "mid"
511
+
512
+
513
+ def refine_seniority_with_years(detected: str, years: int) -> str:
514
+ """
515
+ Override a weakly-detected seniority using computed years.
516
+
517
+ 'mid' is the weakest keyword signal (matches many generic job titles).
518
+ 'intern' can appear from a past role and should not dominate once the
519
+ candidate has accumulated meaningful professional experience.
520
+ """
521
+ if detected == "mid":
522
+ if years >= 7:
523
+ return "senior"
524
+ if years >= 3:
525
+ return "mid"
526
+ if 0 < years < 2:
527
+ return "junior"
528
+ return detected
529
+
530
+ if detected == "intern" and years >= 2:
531
+ # A past intern title should not override the current career level.
532
+ if years >= 7:
533
+ return "senior"
534
+ if years >= 3:
535
+ return "mid"
536
+ return "junior"
537
+
538
+ return detected
539
+
540
+
541
+ # ---------------------------------------------------------------------------
542
+ # CV title extractor (universal, scans more lines)
543
+ # ---------------------------------------------------------------------------
544
+
545
+ def _extract_cv_title(cv_text: str, clean_line_fn=None) -> str:
546
+ """
547
+ Extract the candidate's professional title from the top of the CV.
548
+
549
+ Parameters
550
+ ----------
551
+ cv_text : str
552
+ Raw markdown string.
553
+ clean_line_fn : callable, optional
554
+ A function(raw_line) -> str that strips markdown / HTML.
555
+ Falls back to a simple regex strip if not provided.
556
+ """
557
+ def _simple_clean(raw: str) -> str:
558
+ line = re.sub(r"^#+\s*", "", raw)
559
+ line = re.sub(r"\*{1,3}|\_{1,2}|`", "", line)
560
+ return re.sub(r"\s+", " ", line).strip()
561
+
562
+ clean = clean_line_fn or _simple_clean
563
+ clean_lines = [clean(x) for x in cv_text.splitlines() if x.strip()]
564
+
565
+ # Pass 1: scan lines 1–30, find a short standalone title line.
566
+ # Use word-boundary regex so "lead" does NOT match inside "leadership",
567
+ # "developer" does NOT match inside "redevelopment", etc.
568
+ _role_wb_re = re.compile(
569
+ r"\b(" + "|".join(re.escape(w) for w in TITLE_ROLE_WORDS) + r")\b",
570
+ re.IGNORECASE,
571
+ )
572
+ for line in clean_lines[1:30]:
573
+ stripped = line.strip("| \t")
574
+ if (
575
+ len(stripped) <= 80
576
+ and bool(_role_wb_re.search(stripped))
577
+ and "|" not in stripped # skip leftover table cells
578
+ and not re.search(r"[@http]", stripped)
579
+ and not re.search(r"\d{4}\s*[-–]\s*(?:\d{4}|present)", stripped, re.IGNORECASE)
580
+ ):
581
+ return stripped.title()
582
+
583
+
584
+ # Pass 2: phrase regex over filtered ~1000 chars.
585
+ # Strip known section-header lines first so that patterns like
586
+ # "CAREER SUMMARY" never bleed into the matched title phrase.
587
+ _SECTION_HDR_RE = re.compile(
588
+ r"^(career\s*summary|professional\s*summary|executive\s*summary|"
589
+ r"personal\s*statement|career\s*objective|professional\s*profile|"
590
+ r"personal\s*profile|about\s*me|work\s*experience|"
591
+ r"professional\s*experience|technical\s*skills?|core\s*skills?|"
592
+ r"key\s*skills?|educational?\s*background|academic\s*background|"
593
+ r"employment\s*history|career\s*history|skills?\s*&?\s*tools?|"
594
+ r"skills?|summary|profile|experience|education|projects?|awards?|"
595
+ r"achievements?|contact|links?|certifications?)$",
596
+ re.IGNORECASE,
597
+ )
598
+ non_header = [
599
+ ln for ln in clean_lines[:40]
600
+ if not _SECTION_HDR_RE.match(
601
+ re.sub(r"[^a-zA-Z\s&]", " ", ln).strip()
602
+ )
603
+ ]
604
+ # Join with '. ' so the phrase regex CANNOT span across line boundaries.
605
+ # Without this, "... LinkedIn Portolio Full-stack developer ..." gets joined
606
+ # into one string and the greedy {0,3}-word prefix matches "Portolio" as a
607
+ # title prefix word on any CV whose contact/links line precedes the summary.
608
+ head = ". ".join(non_header)[:1000]
609
+ m = TITLE_PHRASE_RE.search(head)
610
+ if m:
611
+ return m.group(1).strip().title()
612
+
613
+ return "Unknown"
services/job_matcher.py CHANGED
@@ -7,91 +7,27 @@ import numpy as np
7
  from pydantic import BaseModel, Field
8
  from sentence_transformers import SentenceTransformer
9
 
10
- # ---------------------------------------------------------------------------
11
- # Built-in skill taxonomy (mirrors joblink2's defaults)
12
- # ---------------------------------------------------------------------------
13
- DEFAULT_SKILL_ALIASES: Dict[str, List[str]] = {
14
- # Office / Admin / Stock
15
- "microsoft word": ["microsoft word", "ms word", "word"],
16
- "microsoft excel": ["microsoft excel", "ms excel", "excel"],
17
- "microsoft powerpoint": ["microsoft powerpoint", "ms powerpoint", "powerpoint", "power point"],
18
- "inventory management": ["inventory management", "inventory", "stock control", "stock management", "stock checking"],
19
- "warehouse": ["warehouse", "stockroom", "store room"],
20
- "data entry": ["data entry", "typing"],
21
- "communication": ["communication", "communicate", "good communication"],
22
- "teamwork": ["teamwork", "team work", "team member"],
23
- "critical thinking": ["critical thinking", "problem solving", "problem-solving"],
24
- "customer service": ["customer service", "client service"],
25
- "reporting": ["report", "reporting", "daily report", "weekly report"],
26
- # Software
27
- "html": ["html", "html5"],
28
- "css": ["css", "css3"],
29
- "javascript": ["javascript", "js"],
30
- "typescript": ["typescript", "ts"],
31
- "react": ["react", "react.js", "reactjs"],
32
- "next.js": ["next.js", "nextjs"],
33
- "vue": ["vue", "vue.js", "vuejs"],
34
- "angular": ["angular"],
35
- "tailwind css": ["tailwind", "tailwind css"],
36
- "node.js": ["node", "node.js", "nodejs"],
37
- "express.js": ["express", "express.js"],
38
- "python": ["python"],
39
- "java": ["java"],
40
- "kotlin": ["kotlin"],
41
- "android": ["android", "android studio"],
42
- "php": ["php"],
43
- "laravel": ["laravel"],
44
- "mysql": ["mysql"],
45
- "postgresql": ["postgresql", "postgres", "supabase"],
46
- "mongodb": ["mongodb", "mongo"],
47
- "rest api": ["rest api", "restful api", "api"],
48
- "git": ["git", "github", "gitlab"],
49
- "docker": ["docker"],
50
- # Design / Marketing / Data
51
- "ui design": ["ui", "ui design", "user interface"],
52
- "ux design": ["ux", "ux design", "user experience"],
53
- "figma": ["figma"],
54
- "wireframing": ["wireframe", "wireframing"],
55
- "prototyping": ["prototype", "prototyping"],
56
- "seo": ["seo", "search engine optimization"],
57
- "content writing": ["content writing", "copywriting", "writing"],
58
- "digital marketing": ["digital marketing", "marketing campaign", "campaigns"],
59
- "sql": ["sql"],
60
- "machine learning": ["machine learning", "ml"],
61
- "data analysis": ["data analysis", "analytics", "data analyst"],
62
- }
63
-
64
- DEFAULT_CATEGORY_SKILLS: Dict[str, Set[str]] = {
65
- "Admin & Stock": {
66
- "microsoft word", "microsoft excel", "microsoft powerpoint", "inventory management",
67
- "warehouse", "data entry", "communication", "teamwork", "customer service", "reporting",
68
- },
69
- "Software Engineering": {
70
- "html", "css", "javascript", "typescript", "react", "next.js", "vue", "angular",
71
- "tailwind css", "node.js", "express.js", "python", "java", "kotlin", "android", "php",
72
- "laravel", "mysql", "postgresql", "mongodb", "rest api", "git", "docker",
73
- },
74
- "Design & Creative": {"ui design", "ux design", "figma", "wireframing", "prototyping"},
75
- "Marketing & Growth": {"seo", "content writing", "digital marketing"},
76
- "Data & Analytics": {"sql", "python", "machine learning", "data analysis", "microsoft excel"},
77
- }
78
-
79
- SENIORITY_PATTERNS: Dict[str, List[str]] = {
80
- "intern": ["intern", "internship", "trainee"],
81
- "junior": ["junior", "entry level", "entry-level", "assistant", "fresh graduate"],
82
- "mid": ["mid", "middle", "officer", "specialist", "developer", "designer", "engineer"],
83
- "senior": ["senior", "lead", "manager", "head", "principal", "architect"],
84
- }
85
- SENIORITY_ORDER: Dict[str, int] = {"intern": 0, "junior": 1, "mid": 2, "senior": 3}
86
 
87
 
88
  # ---------------------------------------------------------------------------
89
- # Pydantic models — enforced input structure
90
  # ---------------------------------------------------------------------------
91
 
92
  class JobInput(BaseModel):
93
- """Strictly typed job posting that must be passed to JobMatcher.predict()."""
94
-
95
  job_id: str
96
  job_title: str
97
  company_name: str
@@ -124,13 +60,11 @@ class MismatchAnalysis(BaseModel):
124
 
125
 
126
  class MatchPrediction(BaseModel):
127
- """Output of JobMatcher.predict()."""
128
-
129
  job_id: str
130
  job_title: str
131
  company_name: str
132
- match_score: str # e.g. "72.45%"
133
- match_level: str # e.g. "Strong Match"
134
  cv_title: str
135
  cv_seniority: str
136
  cv_category: str
@@ -141,114 +75,10 @@ class MatchPrediction(BaseModel):
141
 
142
 
143
  # ---------------------------------------------------------------------------
144
- # Internal helpers (ported from joblink2 with no external deps)
145
  # ---------------------------------------------------------------------------
146
 
147
- def _normalize(text: str) -> str:
148
- text = (text or "").lower()
149
- text = text.replace("/", " ").replace("_", " ")
150
- text = re.sub(r"[^a-z0-9+.#\s-]", " ", text)
151
- return re.sub(r"\s+", " ", text).strip()
152
-
153
-
154
- def _has_alias(text_norm: str, alias: str) -> bool:
155
- alias_norm = _normalize(alias)
156
- if not alias_norm:
157
- return False
158
- return re.search(rf"(?<![a-z0-9]){re.escape(alias_norm)}(?![a-z0-9])", text_norm) is not None
159
-
160
-
161
- def _extract_skills(text: str, aliases: Dict[str, List[str]]) -> Set[str]:
162
- text_norm = _normalize(text)
163
- return {canon for canon, ali_list in aliases.items() if any(_has_alias(text_norm, a) for a in ali_list)}
164
-
165
-
166
- def _infer_category(text: str, skills: Set[str], category_skills: Dict[str, Set[str]]) -> str:
167
- text_norm = _normalize(text)
168
- title_keywords = {
169
- "Admin & Stock": ["stock", "inventory", "warehouse", "admin", "office", "cashier"],
170
- "Software Engineering": ["developer", "engineer", "programmer", "frontend", "backend", "full stack", "mobile"],
171
- "Design & Creative": ["designer", "ui", "ux", "creative"],
172
- "Marketing & Growth": ["marketing", "seo", "content", "social media"],
173
- "Data & Analytics": ["data", "analyst", "analytics", "machine learning", "ai"],
174
- }
175
- best, best_score = "Other", 0.0
176
- for cat, cat_skills in category_skills.items():
177
- score = len(skills & cat_skills) * 2.0 + sum(1 for kw in title_keywords.get(cat, []) if kw in text_norm) * 1.25
178
- if score > best_score:
179
- best_score, best = score, cat
180
- return best
181
-
182
-
183
- def _extract_years(text: str) -> int:
184
- text_norm = _normalize(text)
185
- patterns = [
186
- r"(\d+)\+?\s*(?:years|year|yrs|yr)\s*(?:of)?\s*(?:experience|exp)",
187
- r"experience\s*(?:of)?\s*(\d+)\+?\s*(?:years|year|yrs|yr)",
188
- ]
189
- years = [int(m.group(1)) for p in patterns for m in re.finditer(p, text_norm)]
190
- return max(years) if years else 0
191
-
192
-
193
- def _detect_seniority(text: str, *, is_cv: bool = False) -> str:
194
- text_norm = _normalize(text)
195
- order = ["senior", "junior", "intern", "mid"] if is_cv else ["senior", "intern", "junior", "mid"]
196
- for level in order:
197
- if any(_has_alias(text_norm, term) for term in SENIORITY_PATTERNS[level]):
198
- return level
199
- years = _extract_years(text)
200
- if years >= 5:
201
- return "senior"
202
- if years >= 2:
203
- return "mid"
204
- return "junior" if is_cv else "mid"
205
-
206
-
207
- def _extract_cv_title(cv_text: str) -> str:
208
- title_words = [
209
- "officer", "developer", "engineer", "designer", "assistant", "accountant",
210
- "manager", "marketing", "stock", "cashier", "admin", "student", "intern",
211
- "analyst", "teacher",
212
- ]
213
- lines = [re.sub(r"\s+", " ", x).strip() for x in cv_text.splitlines() if x.strip()]
214
- for line in lines[:15]:
215
- if len(line) <= 60 and any(w in line.lower() for w in title_words):
216
- return line.title()
217
- return "Unknown"
218
-
219
-
220
- def _parse_cv_sections(cv_text: str) -> Dict[str, str]:
221
- """Parse markdown CV into labelled sections."""
222
- section_headers = {
223
- "skills": ["skills", "technical skills", "core skills", "competencies"],
224
- "experience": ["experience", "employment", "work history", "career", "volunteer"],
225
- "education": ["education", "university", "school"],
226
- "projects": ["projects", "portfolio", "github"],
227
- "summary": ["summary", "profile", "about me", "objective"],
228
- }
229
- current = "summary"
230
- sections: Dict[str, List[str]] = {k: [] for k in section_headers}
231
- for raw_line in cv_text.splitlines():
232
- # Strip markdown heading markers (# ## ###) for matching
233
- line = re.sub(r"^#+\s*", "", raw_line).strip()
234
- if not line:
235
- continue
236
- line_norm = _normalize(line)
237
- matched = None
238
- if len(line_norm) <= 40:
239
- for section, headers in section_headers.items():
240
- if any(line_norm == h or line_norm.replace(" ", "") == h.replace(" ", "") for h in headers):
241
- matched = section
242
- break
243
- if matched:
244
- current = matched
245
- continue
246
- sections[current].append(line)
247
- return {k: "\n".join(v).strip() for k, v in sections.items()}
248
-
249
-
250
  def _cosine_similarity(a: np.ndarray, b: np.ndarray) -> float:
251
- """Pure-numpy cosine similarity (no faiss needed)."""
252
  norm_a = np.linalg.norm(a)
253
  norm_b = np.linalg.norm(b)
254
  if norm_a == 0 or norm_b == 0:
@@ -257,21 +87,21 @@ def _cosine_similarity(a: np.ndarray, b: np.ndarray) -> float:
257
 
258
 
259
  def _seniority_fit(cv_seniority: str, job_seniority: str) -> Tuple[float, str]:
260
- cv_rank = SENIORITY_ORDER.get(cv_seniority, 1)
261
  job_rank = SENIORITY_ORDER.get(job_seniority, 2)
262
  diff = cv_rank - job_rank
263
  if diff == 0:
264
- return 1.0, f"Good seniority fit ({cv_seniority} -> {job_seniority})."
265
  if diff == -1:
266
- return 0.65, f"Slightly under the requested level ({cv_seniority} -> {job_seniority})."
267
  if diff < -1:
268
  return 0.25, f"Seniority mismatch ({cv_seniority} CV for {job_seniority} role)."
269
- return 0.85, f"Candidate may be more experienced than required ({cv_seniority} -> {job_seniority})."
270
 
271
 
272
  def _title_score(cv_title: str, job_title: str) -> float:
273
- cv_tokens = {t for t in _normalize(cv_title).split() if len(t) > 2}
274
- job_tokens = {t for t in _normalize(job_title).split() if len(t) > 2}
275
  if not cv_tokens or cv_title == "Unknown":
276
  return 0.35
277
  overlap = len(cv_tokens & job_tokens) / max(1, len(job_tokens))
@@ -286,33 +116,61 @@ def _experience_fit(cv_years: int, required_years: int) -> float:
286
  return max(0.1, min(1.0, cv_years / required_years))
287
 
288
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
289
  def _match_level(score: float) -> str:
290
- if score >= 80:
291
- return "Excellent Match"
292
- if score >= 70:
293
- return "Strong Match"
294
- if score >= 55:
295
- return "Good Match"
296
- if score >= 40:
297
- return "Moderate Match"
298
- if score >= 25:
299
- return "Weak Match"
300
  return "Very Weak Match"
301
 
302
 
303
- def _build_advice(missing: List[str], job: JobInput, cv_category: str) -> List[str]:
 
 
 
 
304
  advice: List[str] = []
305
  if missing:
306
- advice.append("Add evidence for these required skills if you have them: " + ", ".join(missing[:5]) + ".")
 
 
 
307
  if cv_category != job.category:
308
  advice.append(
309
- f"This CV looks closer to {cv_category}; tailor the summary and projects "
310
- f"toward {job.category} for this job."
311
  )
312
  if job.seniority == "senior":
313
- advice.append("For senior roles, include years of experience, leadership responsibilities, and measurable achievements.")
 
 
 
314
  if not advice:
315
- advice.append("The CV is aligned; improve it by adding measurable achievements and recent project/work examples.")
 
 
 
316
  return advice[:4]
317
 
318
 
@@ -322,12 +180,21 @@ def _build_advice(missing: List[str], job: JobInput, cv_category: str) -> List[s
322
 
323
  class JobMatcher:
324
  """
325
- Standalone CV-to-job matcher.
326
-
327
- Usage
328
- -----
329
- matcher = JobMatcher() # loads model once
330
- result = matcher.predict(job_dict, cv_markdown_string)
 
 
 
 
 
 
 
 
 
331
  """
332
 
333
  def __init__(
@@ -337,75 +204,189 @@ class JobMatcher:
337
  category_skills: Optional[Dict[str, Set[str]]] = None,
338
  ) -> None:
339
  self._model = SentenceTransformer(model_name)
340
- self._aliases: Dict[str, List[str]] = skill_aliases or DEFAULT_SKILL_ALIASES
341
- self._category_skills: Dict[str, Set[str]] = category_skills or DEFAULT_CATEGORY_SKILLS
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
342
 
343
  # ------------------------------------------------------------------
344
- # Public API
345
  # ------------------------------------------------------------------
346
 
347
- def predict(self, job_json: Dict[str, Any], cv_markdown: str) -> Dict[str, Any]:
 
 
 
 
 
348
  """
349
- Predict the qualification match between a job and a CV.
 
 
 
 
350
 
351
  Parameters
352
  ----------
353
- job_json : dict
354
- Must conform to the JobInput schema:
355
- {
356
- "job_id": str,
357
- "job_title": str,
358
- "company_name": str,
359
- "description": str,
360
- "required_skills": [str, ...],
361
- "nice_to_have_skills": [str, ...],
362
- "category": str,
363
- "seniority": str, # "intern"|"junior"|"mid"|"senior"
364
- "min_years_experience": int
365
- }
366
-
367
  cv_markdown : str
368
- Raw markdown text of the candidate's CV.
 
 
 
369
 
370
  Returns
371
  -------
372
- dict
373
- A JSON-serialisable MatchPrediction dictionary.
374
  """
375
- # Step 1 – Validate job structure
376
- job = JobInput(**job_json)
377
-
378
- # Step 2 – Parse CV markdown
379
- sections = _parse_cv_sections(cv_markdown)
380
- cv_title = _extract_cv_title(cv_markdown)
381
- cv_years = _extract_years(cv_markdown)
382
 
383
- seniority_input = cv_title + "\n" + sections.get("experience", "") + "\n" + cv_markdown[:600]
384
- cv_seniority = _detect_seniority(seniority_input, is_cv=True)
 
385
 
386
- # Step 3 – Extract skills from CV
387
- cv_skills: Set[str] = _extract_skills(cv_markdown, self._aliases)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
388
 
389
- # Step 4 – Infer CV category
390
  cv_category = _infer_category(cv_markdown, cv_skills, self._category_skills)
391
 
392
- # Step 5 – Semantic score (cosine similarity between embeddings)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393
  job_index_text = (
394
  f"{job.job_title}\nCompany: {job.company_name}\n{job.description}\n"
395
  f"Required skills: {', '.join(job.required_skills)}\n"
396
  f"Nice to have: {', '.join(job.nice_to_have_skills)}"
397
  )
398
- cv_vec = self._embed(cv_markdown)
399
- job_vec = self._embed(job_index_text)
400
- semantic = _cosine_similarity(cv_vec, job_vec)
401
 
402
- # Step 6 – Component scores
403
  required = set(job.required_skills)
404
- nice = set(job.nice_to_have_skills)
 
405
  matched_required = sorted(cv_skills & required)
406
  missing_required = sorted(required - cv_skills)
 
 
 
 
 
 
 
 
 
 
407
  matched_nice = sorted(cv_skills & nice)
408
- extra = sorted(cv_skills - required - nice)[:8]
409
 
410
  if required:
411
  skill_base = len(matched_required) / len(required)
@@ -414,13 +395,13 @@ class JobMatcher:
414
  nice_bonus = min(0.10, len(matched_nice) * 0.025)
415
  skill = min(1.0, skill_base + nice_bonus)
416
 
417
- semantic = max(0.0, min(1.0, semantic))
418
- cat_score = 1.0 if cv_category == job.category else 0.30
419
- seniority, seniority_reason = _seniority_fit(cv_seniority, job.seniority)
420
- title = _title_score(cv_title, job.job_title)
421
- experience = _experience_fit(cv_years, job.min_years_experience)
422
 
423
- # Step 7 – Weighted aggregation (no cross-encoder branch)
424
  final = (
425
  0.42 * skill
426
  + 0.23 * semantic
@@ -435,22 +416,25 @@ class JobMatcher:
435
  final = min(final, 34.0)
436
  if cv_category != job.category and skill < 0.30:
437
  final = min(final, 42.0)
438
- if job.seniority == "senior" and SENIORITY_ORDER.get(cv_seniority, 1) < SENIORITY_ORDER["mid"]:
 
 
 
439
  final = min(final, 45.0)
440
 
441
  final = round(max(0.0, min(100.0, final)), 2)
442
  level = _match_level(final)
443
 
444
- # Step 8 – Build reason string
445
  if matched_required:
446
  reason = (
447
- f"{level}: matched {len(matched_required)}/{len(required)} required skill(s), "
448
- f"including {', '.join(matched_required[:5])}."
449
  )
450
  else:
451
  reason = (
452
- f"{level}: the CV does not show the main required skills for this role. "
453
- f"It looks closer to {cv_category}."
454
  )
455
 
456
  prediction = MatchPrediction(
@@ -478,7 +462,7 @@ class JobMatcher:
478
  missing_required_skills=missing_required[:10],
479
  matched_nice_to_have_skills=matched_nice,
480
  cv_extra_strengths=extra,
481
- seniority_fit=seniority_reason,
482
  category_fit=f"CV category: {cv_category}; Job category: {job.category}.",
483
  improvement_advice=_build_advice(missing_required, job, cv_category),
484
  ),
@@ -490,13 +474,37 @@ class JobMatcher:
490
  # ------------------------------------------------------------------
491
 
492
  def _embed(self, text: str) -> np.ndarray:
493
- """Encode text into a normalised embedding vector."""
494
  words = text.split()
495
- # Chunk into windows of 180 words with 45-word overlap to handle long CVs
496
  if len(words) <= 180:
497
  parts = [text]
498
  else:
499
- step = 135 # 180 - 45
500
  parts = [" ".join(words[i: i + 180]) for i in range(0, len(words), step)]
501
- vectors = self._model.encode(parts, normalize_embeddings=True, show_progress_bar=False)
 
 
502
  return np.mean(vectors, axis=0).astype("float32")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  from pydantic import BaseModel, Field
8
  from sentence_transformers import SentenceTransformer
9
 
10
+ from services.cv_utils import (
11
+ DEFAULT_SKILL_ALIASES,
12
+ DEFAULT_CATEGORY_SKILLS,
13
+ SENIORITY_ORDER,
14
+ _extract_skills,
15
+ _infer_category,
16
+ _extract_years,
17
+ _detect_seniority,
18
+ refine_seniority_with_years,
19
+ _extract_cv_title,
20
+ compute_years_from_experience,
21
+ )
22
+ from services.cv_chunker import _parse_cv_sections, _parse_experience
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
 
25
  # ---------------------------------------------------------------------------
26
+ # Pydantic models
27
  # ---------------------------------------------------------------------------
28
 
29
  class JobInput(BaseModel):
30
+ """Strictly typed job posting for JobMatcher.predict()."""
 
31
  job_id: str
32
  job_title: str
33
  company_name: str
 
60
 
61
 
62
  class MatchPrediction(BaseModel):
 
 
63
  job_id: str
64
  job_title: str
65
  company_name: str
66
+ match_score: str
67
+ match_level: str
68
  cv_title: str
69
  cv_seniority: str
70
  cv_category: str
 
75
 
76
 
77
  # ---------------------------------------------------------------------------
78
+ # Pure scoring helpers
79
  # ---------------------------------------------------------------------------
80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  def _cosine_similarity(a: np.ndarray, b: np.ndarray) -> float:
 
82
  norm_a = np.linalg.norm(a)
83
  norm_b = np.linalg.norm(b)
84
  if norm_a == 0 or norm_b == 0:
 
87
 
88
 
89
  def _seniority_fit(cv_seniority: str, job_seniority: str) -> Tuple[float, str]:
90
+ cv_rank = SENIORITY_ORDER.get(cv_seniority, 1)
91
  job_rank = SENIORITY_ORDER.get(job_seniority, 2)
92
  diff = cv_rank - job_rank
93
  if diff == 0:
94
+ return 1.0, f"Good seniority fit ({cv_seniority} → {job_seniority})."
95
  if diff == -1:
96
+ return 0.65, f"Slightly under the requested level ({cv_seniority} → {job_seniority})."
97
  if diff < -1:
98
  return 0.25, f"Seniority mismatch ({cv_seniority} CV for {job_seniority} role)."
99
+ return 0.85, f"Candidate may be more experienced than required ({cv_seniority} → {job_seniority})."
100
 
101
 
102
  def _title_score(cv_title: str, job_title: str) -> float:
103
+ cv_tokens = {t for t in re.sub(r"[^a-z0-9 ]", " ", cv_title.lower()).split() if len(t) > 2}
104
+ job_tokens = {t for t in re.sub(r"[^a-z0-9 ]", " ", job_title.lower()).split() if len(t) > 2}
105
  if not cv_tokens or cv_title == "Unknown":
106
  return 0.35
107
  overlap = len(cv_tokens & job_tokens) / max(1, len(job_tokens))
 
116
  return max(0.1, min(1.0, cv_years / required_years))
117
 
118
 
119
+ def _soft_category_score(
120
+ cv_skills: Set[str],
121
+ job_category: str,
122
+ category_skills: Dict[str, Set[str]],
123
+ ) -> float:
124
+ """
125
+ Jaccard-based soft category match instead of binary 1.0 / 0.30.
126
+ Scores range from 0.30 (no overlap) to 1.0 (exact match).
127
+ """
128
+ job_cat_skills = category_skills.get(job_category, set())
129
+ if not job_cat_skills:
130
+ return 0.30
131
+ intersection = len(cv_skills & job_cat_skills)
132
+ union = len(cv_skills | job_cat_skills)
133
+ if union == 0:
134
+ return 0.30
135
+ jaccard = intersection / union
136
+ return max(0.30, min(1.0, 0.30 + jaccard * 0.70))
137
+
138
+
139
  def _match_level(score: float) -> str:
140
+ if score >= 80: return "Excellent Match"
141
+ if score >= 70: return "Strong Match"
142
+ if score >= 55: return "Good Match"
143
+ if score >= 40: return "Moderate Match"
144
+ if score >= 25: return "Weak Match"
 
 
 
 
 
145
  return "Very Weak Match"
146
 
147
 
148
+ def _build_advice(
149
+ missing: List[str],
150
+ job: JobInput,
151
+ cv_category: str,
152
+ ) -> List[str]:
153
  advice: List[str] = []
154
  if missing:
155
+ advice.append(
156
+ "Add evidence for these required skills if you have them: "
157
+ + ", ".join(missing[:5]) + "."
158
+ )
159
  if cv_category != job.category:
160
  advice.append(
161
+ f"This CV looks closer to {cv_category}; tailor the summary and "
162
+ f"projects toward {job.category} for this job."
163
  )
164
  if job.seniority == "senior":
165
+ advice.append(
166
+ "For senior roles, highlight leadership responsibilities, team size "
167
+ "managed, and measurable achievements."
168
+ )
169
  if not advice:
170
+ advice.append(
171
+ "The CV is well aligned; strengthen it with measurable achievements "
172
+ "and recent work examples."
173
+ )
174
  return advice[:4]
175
 
176
 
 
180
 
181
  class JobMatcher:
182
  """
183
+ CV-to-job matcher using sentence embeddings + skill taxonomy scoring.
184
+
185
+ Single-job usage
186
+ ----------------
187
+ matcher = JobMatcher()
188
+ result = matcher.predict(job_dict, cv_markdown)
189
+
190
+ Batch usage (same CV, many jobs — CV processed only once)
191
+ ---------------------------------------------------------
192
+ results = matcher.predict_batch(list_of_job_dicts, cv_markdown)
193
+ # or, with pre-computed embeddings from /process-cv:
194
+ results = matcher.predict_batch(
195
+ list_of_job_dicts, cv_markdown,
196
+ section_embeddings=payload["section_embeddings"]
197
+ )
198
  """
199
 
200
  def __init__(
 
204
  category_skills: Optional[Dict[str, Set[str]]] = None,
205
  ) -> None:
206
  self._model = SentenceTransformer(model_name)
207
+ self._aliases: Dict[str, List[str]] = skill_aliases or DEFAULT_SKILL_ALIASES
208
+ self._category_skills: Dict[str, Set[str]] = category_skills or DEFAULT_CATEGORY_SKILLS
209
+
210
+ # ------------------------------------------------------------------
211
+ # Public: single-job prediction (backward-compatible)
212
+ # ------------------------------------------------------------------
213
+
214
+ def predict(
215
+ self,
216
+ job_json: Dict[str, Any],
217
+ cv_markdown: str,
218
+ section_embeddings: Optional[Dict[str, Any]] = None,
219
+ ) -> Dict[str, Any]:
220
+ """
221
+ Predict the match between one job and one CV.
222
+ Pass ``section_embeddings`` from ``/process-cv`` to skip re-encoding.
223
+ """
224
+ cv_data = self._parse_cv(cv_markdown, section_embeddings)
225
+ return self._predict_single(job_json, cv_data)
226
 
227
  # ------------------------------------------------------------------
228
+ # Public: batch prediction (one CV vs. N jobs)
229
  # ------------------------------------------------------------------
230
 
231
+ def predict_batch(
232
+ self,
233
+ jobs: List[Dict[str, Any]],
234
+ cv_markdown: str,
235
+ section_embeddings: Optional[Dict[str, Any]] = None,
236
+ ) -> List[Dict[str, Any]]:
237
  """
238
+ Match one CV against multiple jobs.
239
+
240
+ The CV is parsed and embedded **once**; every subsequent job
241
+ match reuses the same vectors — O(1) CV cost regardless of
242
+ how many jobs are compared.
243
 
244
  Parameters
245
  ----------
246
+ jobs : list of dicts
247
+ Each must conform to the JobInput schema.
 
 
 
 
 
 
 
 
 
 
 
 
248
  cv_markdown : str
249
+ Raw markdown of the candidate's CV.
250
+ section_embeddings : dict, optional
251
+ Pre-computed section vectors from ``/process-cv``.
252
+ Keys: ``summary``, ``skills``, ``experience`` (lists of floats).
253
 
254
  Returns
255
  -------
256
+ List of MatchPrediction dicts sorted by match_score descending.
 
257
  """
258
+ cv_data = self._parse_cv(cv_markdown, section_embeddings)
259
+ results = [self._predict_single(j, cv_data) for j in jobs]
260
+ results.sort(
261
+ key=lambda x: float(x["match_score"].rstrip("%")),
262
+ reverse=True,
263
+ )
264
+ return results
265
 
266
+ # ------------------------------------------------------------------
267
+ # Internal: parse + embed CV (done once per request)
268
+ # ------------------------------------------------------------------
269
 
270
+ def _parse_cv(
271
+ self,
272
+ cv_markdown: str,
273
+ section_embeddings: Optional[Dict[str, Any]] = None,
274
+ ) -> Dict[str, Any]:
275
+ """
276
+ Return a dict holding all CV-level data needed by _predict_single.
277
+ When section_embeddings are provided they are used directly;
278
+ otherwise the model encodes each section now.
279
+ """
280
+ sections = _parse_cv_sections(cv_markdown)
281
+ cv_title = _extract_cv_title(cv_markdown)
282
+ experience = _parse_experience(sections.get("experience", ""))
283
+ computed_yrs = compute_years_from_experience(experience)
284
+ text_yrs = _extract_years(cv_markdown)
285
+ cv_years = computed_yrs if computed_yrs > 0 else text_yrs
286
+
287
+ seniority_text = (
288
+ cv_title + "\n"
289
+ + sections.get("experience", "")
290
+ + "\n" + cv_markdown[:600]
291
+ )
292
+ cv_seniority = _detect_seniority(seniority_text, is_cv=True)
293
+ cv_seniority = refine_seniority_with_years(cv_seniority, cv_years)
294
 
295
+ cv_skills = _extract_skills(cv_markdown, self._aliases)
296
  cv_category = _infer_category(cv_markdown, cv_skills, self._category_skills)
297
 
298
+ # ── Embeddings ───────────────────────────────────────────────────
299
+ if section_embeddings:
300
+ raw_s = section_embeddings.get("summary")
301
+ raw_k = section_embeddings.get("skills")
302
+ raw_e = section_embeddings.get("experience")
303
+ summary_vec = np.array(raw_s, dtype="float32") if raw_s else None
304
+ skills_vec = np.array(raw_k, dtype="float32") if raw_k else None
305
+ exp_vec = np.array(raw_e, dtype="float32") if raw_e else None
306
+ else:
307
+ summary_text = sections.get("summary", "").strip()
308
+ skills_text = " ".join(sorted(cv_skills))[:2000]
309
+ exp_text = sections.get("experience", "")[:3000]
310
+ summary_vec = self._embed(summary_text) if summary_text else None
311
+ skills_vec = self._embed(skills_text) if skills_text else None
312
+ exp_vec = self._embed(exp_text) if exp_text else None
313
+
314
+ # Section-weighted combined CV vector
315
+ # summary+experience carry 60% weight, skills 40%
316
+ parts, weights = [], []
317
+ if summary_vec is not None:
318
+ parts.append(summary_vec); weights.append(0.35)
319
+ if exp_vec is not None:
320
+ parts.append(exp_vec); weights.append(0.25)
321
+ if skills_vec is not None:
322
+ parts.append(skills_vec); weights.append(0.40)
323
+
324
+ if parts:
325
+ cv_vec = np.sum(
326
+ [p * w for p, w in zip(parts, weights)], axis=0
327
+ ).astype("float32")
328
+ n = np.linalg.norm(cv_vec)
329
+ if n > 0:
330
+ cv_vec /= n
331
+ else:
332
+ cv_vec = self._embed(cv_markdown[:3000])
333
+
334
+ return {
335
+ "cv_title": cv_title,
336
+ "cv_years": cv_years,
337
+ "cv_seniority": cv_seniority,
338
+ "cv_skills": cv_skills,
339
+ "cv_category": cv_category,
340
+ "cv_vec": cv_vec,
341
+ "skills_vec": skills_vec,
342
+ }
343
+
344
+ # ------------------------------------------------------------------
345
+ # Internal: score one job against pre-parsed CV data
346
+ # ------------------------------------------------------------------
347
+
348
+ def _predict_single(
349
+ self,
350
+ job_json: Dict[str, Any],
351
+ cv_data: Dict[str, Any],
352
+ ) -> Dict[str, Any]:
353
+ job = JobInput(**job_json)
354
+
355
+ cv_title = cv_data["cv_title"]
356
+ cv_years = cv_data["cv_years"]
357
+ cv_seniority = cv_data["cv_seniority"]
358
+ cv_skills = cv_data["cv_skills"]
359
+ cv_category = cv_data["cv_category"]
360
+ cv_vec = cv_data["cv_vec"]
361
+ skills_vec = cv_data["skills_vec"]
362
+
363
+ # ── Job embedding ────────────────────────────────────────────────
364
  job_index_text = (
365
  f"{job.job_title}\nCompany: {job.company_name}\n{job.description}\n"
366
  f"Required skills: {', '.join(job.required_skills)}\n"
367
  f"Nice to have: {', '.join(job.nice_to_have_skills)}"
368
  )
369
+ job_vec = self._embed(job_index_text)
370
+ semantic = max(0.0, min(1.0, _cosine_similarity(cv_vec, job_vec)))
 
371
 
372
+ # ── Skill scoring (keyword + semantic fallback) ──────────────────
373
  required = set(job.required_skills)
374
+ nice = set(job.nice_to_have_skills)
375
+
376
  matched_required = sorted(cv_skills & required)
377
  missing_required = sorted(required - cv_skills)
378
+
379
+ # Semantic fallback for skills not matched by exact keyword
380
+ if missing_required and skills_vec is not None:
381
+ semantic_matches = self._semantic_skill_matches(
382
+ missing_required, skills_vec
383
+ )
384
+ if semantic_matches:
385
+ matched_required = sorted(set(matched_required) | semantic_matches)
386
+ missing_required = sorted(set(missing_required) - semantic_matches)
387
+
388
  matched_nice = sorted(cv_skills & nice)
389
+ extra = sorted(cv_skills - required - nice)[:8]
390
 
391
  if required:
392
  skill_base = len(matched_required) / len(required)
 
395
  nice_bonus = min(0.10, len(matched_nice) * 0.025)
396
  skill = min(1.0, skill_base + nice_bonus)
397
 
398
+ # ── Component scores ─────────────────────────────────────────────
399
+ cat_score = _soft_category_score(cv_skills, job.category, self._category_skills)
400
+ seniority, sen_reason = _seniority_fit(cv_seniority, job.seniority)
401
+ title = _title_score(cv_title, job.job_title)
402
+ experience = _experience_fit(cv_years, job.min_years_experience)
403
 
404
+ # ── Weighted aggregation ─────────────────────────────────────────
405
  final = (
406
  0.42 * skill
407
  + 0.23 * semantic
 
416
  final = min(final, 34.0)
417
  if cv_category != job.category and skill < 0.30:
418
  final = min(final, 42.0)
419
+ if (
420
+ job.seniority == "senior"
421
+ and SENIORITY_ORDER.get(cv_seniority, 1) < SENIORITY_ORDER["mid"]
422
+ ):
423
  final = min(final, 45.0)
424
 
425
  final = round(max(0.0, min(100.0, final)), 2)
426
  level = _match_level(final)
427
 
428
+ # ── Reason string ────────────────────────────────────────────────
429
  if matched_required:
430
  reason = (
431
+ f"{level}: matched {len(matched_required)}/{len(required)} "
432
+ f"required skill(s), including {', '.join(matched_required[:5])}."
433
  )
434
  else:
435
  reason = (
436
+ f"{level}: the CV does not show the main required skills for this "
437
+ f"role. It looks closer to {cv_category}."
438
  )
439
 
440
  prediction = MatchPrediction(
 
462
  missing_required_skills=missing_required[:10],
463
  matched_nice_to_have_skills=matched_nice,
464
  cv_extra_strengths=extra,
465
+ seniority_fit=sen_reason,
466
  category_fit=f"CV category: {cv_category}; Job category: {job.category}.",
467
  improvement_advice=_build_advice(missing_required, job, cv_category),
468
  ),
 
474
  # ------------------------------------------------------------------
475
 
476
  def _embed(self, text: str) -> np.ndarray:
477
+ """Encode text → normalised float32 vector, chunking long inputs."""
478
  words = text.split()
 
479
  if len(words) <= 180:
480
  parts = [text]
481
  else:
482
+ step = 135
483
  parts = [" ".join(words[i: i + 180]) for i in range(0, len(words), step)]
484
+ vectors = self._model.encode(
485
+ parts, normalize_embeddings=True, show_progress_bar=False
486
+ )
487
  return np.mean(vectors, axis=0).astype("float32")
488
+
489
+ def _semantic_skill_matches(
490
+ self,
491
+ skills: List[str],
492
+ skills_vec: np.ndarray,
493
+ threshold: float = 0.72,
494
+ ) -> Set[str]:
495
+ """
496
+ Batch-encode required skill names and compare each against the
497
+ CV's skills-section embedding. Returns skills whose cosine
498
+ similarity exceeds ``threshold``. This catches paraphrase
499
+ matches like "React" ↔ "component-based UI frameworks".
500
+ """
501
+ if not skills:
502
+ return set()
503
+ vecs = self._model.encode(
504
+ skills, normalize_embeddings=True, show_progress_bar=False
505
+ )
506
+ matched: Set[str] = set()
507
+ for i, skill in enumerate(skills):
508
+ if _cosine_similarity(vecs[i], skills_vec) >= threshold:
509
+ matched.add(skill)
510
+ return matched
services/workers.py CHANGED
@@ -12,6 +12,7 @@ from dataclasses import dataclass
12
  from services import job_store
13
  from services.cv_chunker import chunk_cv
14
  from services.cv_converter import CVConverter
 
15
 
16
 
17
  # ---------------------------------------------------------------------------
@@ -36,8 +37,9 @@ _ML_EXECUTOR = ThreadPoolExecutor(max_workers=1, thread_name_prefix="ml-worker")
36
  class CvWorker:
37
  """Handles background tasks for CV processing."""
38
 
39
- def __init__(self, converter: CVConverter):
40
  self.converter = converter
 
41
 
42
  async def run_cv_processing(
43
  self,
@@ -45,25 +47,26 @@ class CvWorker:
45
  file_bytes: bytes,
46
  filename: str,
47
  callback_url: str,
48
- callback_secret: str = None
49
  ) -> None:
50
- """Process a CV and POST the result back to Java callback endpoint."""
51
- loop = asyncio.get_running_loop()
52
  tmp_path: Optional[Path] = None
53
  try:
54
- start_time = datetime.now(timezone.utc).isoformat()
55
 
56
  suffix = Path(filename).suffix.lower() if filename else ".pdf"
57
  with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
58
  tmp.write(file_bytes)
59
  tmp_path = Path(tmp.name)
60
 
61
- # Run blocking ML work in the dedicated single-thread executor.
62
- # This keeps the asyncio event loop free to handle all other
63
- # incoming requests (job-status polls, new CV submissions, etc.)
64
  conversion = await loop.run_in_executor(
65
  _ML_EXECUTOR, self.converter.convert, tmp_path
66
  )
 
 
67
 
68
  if not conversion.success:
69
  error_msg = conversion.error or "Conversion failed"
@@ -75,17 +78,25 @@ class CvWorker:
75
  }, callback_secret)
76
  return
77
 
 
 
78
  chunks = await loop.run_in_executor(
79
- _ML_EXECUTOR, chunk_cv, conversion.markdown
 
80
  )
81
- end_time = datetime.now(timezone.utc).isoformat()
 
 
 
 
82
 
83
  payload = {
84
- "markdown": conversion.markdown,
85
- "cv_title": chunks["cv_title"],
86
- "seniority": chunks["seniority"],
87
- "years_experience": chunks["years_experience"],
88
- "category": chunks["category"],
 
89
  "chunks": {
90
  "summary": chunks["chunks"]["summary"],
91
  "contact": chunks["chunks"]["contact"],
@@ -96,13 +107,18 @@ class CvWorker:
96
  "projects": chunks["chunks"]["projects"],
97
  "awards": chunks["chunks"]["awards"],
98
  },
99
- "file_type": conversion.file_type,
100
- "method_used": conversion.method_used,
101
- "is_scanned": conversion.is_scanned,
102
- "page_count": conversion.page_count,
103
- "warnings": conversion.warnings,
104
- "start_time": start_time,
105
- "end_time": end_time,
 
 
 
 
 
106
  }
107
 
108
  job_store.set_completed(job_id, payload)
@@ -123,16 +139,23 @@ class CvWorker:
123
  }, callback_secret)
124
 
125
  finally:
126
- if tmp_path and tmp_path.exists():
127
- tmp_path.unlink()
 
 
 
128
 
129
- async def post_callback(self, callback_url: str, body: dict, callback_secret: str = None) -> None:
 
 
 
 
 
130
  """POST the processing result back to Java."""
131
  try:
132
  headers = {}
133
  if callback_secret:
134
  headers["X-Callback-Secret"] = callback_secret
135
-
136
  async with httpx.AsyncClient(timeout=30.0) as client:
137
  response = await client.post(callback_url, json=body, headers=headers)
138
  response.raise_for_status()
@@ -142,10 +165,10 @@ class CvWorker:
142
 
143
  @dataclass
144
  class CvTask:
145
- job_id: str
146
- file_bytes: bytes
147
- filename: str
148
- callback_url: str
149
  callback_secret: str = None
150
 
151
 
@@ -162,23 +185,19 @@ class QueueManager:
162
  """
163
 
164
  def __init__(self, worker: CvWorker, concurrency: int = 1):
165
- self.worker = worker
166
  self.concurrency = concurrency
167
- self.queue: asyncio.Queue = asyncio.Queue()
168
- self.tasks: list = []
169
- # Tracks job IDs currently sitting in the queue or being processed.
170
- # Used to reject duplicate submissions before they reach the ML worker.
171
  self._active_ids: set[str] = set()
172
 
173
  async def start(self) -> None:
174
- """Spawn background worker coroutines."""
175
  for _ in range(self.concurrency):
176
  task = asyncio.create_task(self._worker_loop())
177
  self.tasks.append(task)
178
  print(f"[QUEUE] Started {self.concurrency} worker(s) — one CV processed at a time.")
179
 
180
  async def stop(self) -> None:
181
- """Cancel all running workers cleanly."""
182
  for task in self.tasks:
183
  task.cancel()
184
  await asyncio.gather(*self.tasks, return_exceptions=True)
@@ -186,14 +205,15 @@ class QueueManager:
186
  print("[QUEUE] Stopped all workers.")
187
 
188
  async def _worker_loop(self) -> None:
189
- """Continuously pull tasks from the queue and process them one by one."""
190
  while True:
191
  try:
192
- task: CvTask = await self.queue.get() # suspends here — event loop stays free
193
  job_store.set_processing(task.job_id)
194
- self._active_ids.discard(task.job_id) # no longer queued, now processing
195
- print(f"[QUEUE] Worker picked up job {task.job_id}. "
196
- f"Remaining in queue: {self.queue.qsize()}")
 
 
197
  await self.worker.run_cv_processing(
198
  task.job_id,
199
  task.file_bytes,
@@ -208,18 +228,15 @@ class QueueManager:
208
  print(f"[QUEUE] Unhandled error in worker loop: {exc}")
209
 
210
  async def enqueue(self, task: CvTask) -> None:
211
- """Add a task to the queue — rejects duplicate job IDs already in-flight."""
212
  if task.job_id in self._active_ids:
213
  print(f"[QUEUE] Duplicate submission rejected: job {task.job_id} is already queued.")
214
  raise ValueError(f"Job {task.job_id} is already in the processing queue.")
215
-
216
  self._active_ids.add(task.job_id)
217
  job_store.set_queued(task.job_id)
218
- await self.queue.put(task) # asyncio.Queue with no maxsize — never blocks
219
  print(f"[QUEUE] Job {task.job_id} enqueued. Queue depth: {self.queue.qsize()}")
220
 
221
  def get_queue_position(self, job_id: str) -> Optional[int]:
222
- """Returns the position of the job in the queue (1-based), or None if not queued."""
223
  try:
224
  for idx, task in enumerate(list(self.queue._queue)):
225
  if task.job_id == job_id:
@@ -227,4 +244,3 @@ class QueueManager:
227
  except Exception as exc:
228
  print(f"[QUEUE] Error checking queue position: {exc}")
229
  return None
230
-
 
12
  from services import job_store
13
  from services.cv_chunker import chunk_cv
14
  from services.cv_converter import CVConverter
15
+ from services.job_matcher import JobMatcher
16
 
17
 
18
  # ---------------------------------------------------------------------------
 
37
  class CvWorker:
38
  """Handles background tasks for CV processing."""
39
 
40
+ def __init__(self, converter: CVConverter, matcher: JobMatcher):
41
  self.converter = converter
42
+ self.matcher = matcher
43
 
44
  async def run_cv_processing(
45
  self,
 
47
  file_bytes: bytes,
48
  filename: str,
49
  callback_url: str,
50
+ callback_secret: str = None,
51
  ) -> None:
52
+ """Process a CV and POST the result back to the Java callback endpoint."""
53
+ loop = asyncio.get_running_loop()
54
  tmp_path: Optional[Path] = None
55
  try:
56
+ t_start = datetime.now(timezone.utc)
57
 
58
  suffix = Path(filename).suffix.lower() if filename else ".pdf"
59
  with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
60
  tmp.write(file_bytes)
61
  tmp_path = Path(tmp.name)
62
 
63
+ # Conversion — CPU-bound, isolated executor
64
+ t_conv_start = datetime.now(timezone.utc)
 
65
  conversion = await loop.run_in_executor(
66
  _ML_EXECUTOR, self.converter.convert, tmp_path
67
  )
68
+ t_conv_end = datetime.now(timezone.utc)
69
+ conversion_ms = int((t_conv_end - t_conv_start).total_seconds() * 1000)
70
 
71
  if not conversion.success:
72
  error_msg = conversion.error or "Conversion failed"
 
78
  }, callback_secret)
79
  return
80
 
81
+ # chunk_cv with embedder — CPU-bound, isolated executor
82
+ t_chunk_start = datetime.now(timezone.utc)
83
  chunks = await loop.run_in_executor(
84
+ _ML_EXECUTOR,
85
+ lambda: chunk_cv(conversion.markdown, embedder=self.matcher._embed),
86
  )
87
+ t_chunk_end = datetime.now(timezone.utc)
88
+ chunking_ms = int((t_chunk_end - t_chunk_start).total_seconds() * 1000)
89
+
90
+ t_end = datetime.now(timezone.utc)
91
+ total_ms = int((t_end - t_start).total_seconds() * 1000)
92
 
93
  payload = {
94
+ "markdown": conversion.markdown,
95
+ "cv_title": chunks["cv_title"],
96
+ "seniority": chunks["seniority"],
97
+ "years_experience": chunks["years_experience"],
98
+ "category": chunks["category"],
99
+ "completeness_score": chunks["completeness_score"],
100
  "chunks": {
101
  "summary": chunks["chunks"]["summary"],
102
  "contact": chunks["chunks"]["contact"],
 
107
  "projects": chunks["chunks"]["projects"],
108
  "awards": chunks["chunks"]["awards"],
109
  },
110
+ "section_embeddings": chunks.get("section_embeddings"),
111
+ "file_type": conversion.file_type,
112
+ "method_used": conversion.method_used,
113
+ "is_scanned": conversion.is_scanned,
114
+ "page_count": conversion.page_count,
115
+ "warnings": conversion.warnings,
116
+ "timing": {
117
+ "conversion_ms": conversion_ms,
118
+ "chunking_ms": chunking_ms,
119
+ "total_ms": total_ms,
120
+ },
121
+ "processed_at": t_end.isoformat(),
122
  }
123
 
124
  job_store.set_completed(job_id, payload)
 
139
  }, callback_secret)
140
 
141
  finally:
142
+ if tmp_path is not None:
143
+ try:
144
+ tmp_path.unlink(missing_ok=True)
145
+ except Exception:
146
+ pass
147
 
148
+ async def post_callback(
149
+ self,
150
+ callback_url: str,
151
+ body: dict,
152
+ callback_secret: str = None,
153
+ ) -> None:
154
  """POST the processing result back to Java."""
155
  try:
156
  headers = {}
157
  if callback_secret:
158
  headers["X-Callback-Secret"] = callback_secret
 
159
  async with httpx.AsyncClient(timeout=30.0) as client:
160
  response = await client.post(callback_url, json=body, headers=headers)
161
  response.raise_for_status()
 
165
 
166
  @dataclass
167
  class CvTask:
168
+ job_id: str
169
+ file_bytes: bytes
170
+ filename: str
171
+ callback_url: str
172
  callback_secret: str = None
173
 
174
 
 
185
  """
186
 
187
  def __init__(self, worker: CvWorker, concurrency: int = 1):
188
+ self.worker = worker
189
  self.concurrency = concurrency
190
+ self.queue: asyncio.Queue = asyncio.Queue()
191
+ self.tasks: list = []
 
 
192
  self._active_ids: set[str] = set()
193
 
194
  async def start(self) -> None:
 
195
  for _ in range(self.concurrency):
196
  task = asyncio.create_task(self._worker_loop())
197
  self.tasks.append(task)
198
  print(f"[QUEUE] Started {self.concurrency} worker(s) — one CV processed at a time.")
199
 
200
  async def stop(self) -> None:
 
201
  for task in self.tasks:
202
  task.cancel()
203
  await asyncio.gather(*self.tasks, return_exceptions=True)
 
205
  print("[QUEUE] Stopped all workers.")
206
 
207
  async def _worker_loop(self) -> None:
 
208
  while True:
209
  try:
210
+ task: CvTask = await self.queue.get()
211
  job_store.set_processing(task.job_id)
212
+ self._active_ids.discard(task.job_id)
213
+ print(
214
+ f"[QUEUE] Worker picked up job {task.job_id}. "
215
+ f"Remaining in queue: {self.queue.qsize()}"
216
+ )
217
  await self.worker.run_cv_processing(
218
  task.job_id,
219
  task.file_bytes,
 
228
  print(f"[QUEUE] Unhandled error in worker loop: {exc}")
229
 
230
  async def enqueue(self, task: CvTask) -> None:
 
231
  if task.job_id in self._active_ids:
232
  print(f"[QUEUE] Duplicate submission rejected: job {task.job_id} is already queued.")
233
  raise ValueError(f"Job {task.job_id} is already in the processing queue.")
 
234
  self._active_ids.add(task.job_id)
235
  job_store.set_queued(task.job_id)
236
+ await self.queue.put(task)
237
  print(f"[QUEUE] Job {task.job_id} enqueued. Queue depth: {self.queue.qsize()}")
238
 
239
  def get_queue_position(self, job_id: str) -> Optional[int]:
 
240
  try:
241
  for idx, task in enumerate(list(self.queue._queue)):
242
  if task.job_id == job_id:
 
244
  except Exception as exc:
245
  print(f"[QUEUE] Error checking queue position: {exc}")
246
  return None