Eng-Musa commited on
Commit
0d2be35
Β·
1 Parent(s): aa5d8fe

refactr match processing

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
@@ -351,48 +351,6 @@ def get_job_status(job_id: str):
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",
388
- statusCode=200,
389
- payload=result,
390
- )
391
- except Exception as exc:
392
- return APIResponse(
393
- message=f"An error occurred during matching: {exc}",
394
- statusCode=500,
395
- )
396
 
397
 
398
  # ---------------------------------------------------------------------------
@@ -407,7 +365,7 @@ class BatchMatchCVRequest(BaseModel):
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=(
@@ -415,29 +373,28 @@ class BatchMatchCVRequest(BaseModel):
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)",
 
351
  )
352
 
353
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
354
 
355
 
356
  # ---------------------------------------------------------------------------
 
365
  max_length=100,
366
  description="Array of job postings (1–100).",
367
  )
368
+ cv_markdown: Optional[str] = Field(None, description="Candidate's CV as Markdown.")
369
  section_embeddings: Optional[Any] = Field(
370
  None,
371
  description=(
 
373
  "CV is parsed and embedded only ONCE for all jobs when provided."
374
  ),
375
  )
376
+ cv_title: Optional[str] = None
377
+ cv_years: Optional[int] = None
378
+ cv_seniority: Optional[str] = None
379
+ cv_skills: Optional[List[str]] = None
380
+ cv_category: Optional[str] = None
381
 
382
 
383
  @app.post("/batch-match-cv", response_model=APIResponse)
384
  def batch_match_cv(payload: BatchMatchCVRequest):
385
  """
386
  Match one CV against an array of job postings in a single request.
 
 
 
 
 
 
 
 
 
 
 
387
  """
388
  try:
389
  results = matcher.predict_batch(
390
  jobs=[j.model_dump() for j in payload.jobs],
391
  cv_markdown=payload.cv_markdown,
392
  section_embeddings=payload.section_embeddings,
393
+ cv_title=payload.cv_title,
394
+ cv_years=payload.cv_years,
395
+ cv_seniority=payload.cv_seniority,
396
+ cv_skills=payload.cv_skills,
397
+ cv_category=payload.cv_category,
398
  )
399
  return APIResponse(
400
  message=f"Batch match completed: {len(results)} result(s)",
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/job_matcher.py CHANGED
@@ -214,14 +214,27 @@ class JobMatcher:
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
  # ------------------------------------------------------------------
@@ -231,8 +244,13 @@ class JobMatcher:
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.
@@ -240,22 +258,16 @@ class JobMatcher:
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("%")),
@@ -269,31 +281,45 @@ class JobMatcher:
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:
@@ -304,9 +330,15 @@ class JobMatcher:
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
@@ -329,13 +361,13 @@ class JobMatcher:
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,
 
214
  def predict(
215
  self,
216
  job_json: Dict[str, Any],
217
+ cv_markdown: Optional[str] = None,
218
  section_embeddings: Optional[Dict[str, Any]] = None,
219
+ cv_title: Optional[str] = None,
220
+ cv_years: Optional[int] = None,
221
+ cv_seniority: Optional[str] = None,
222
+ cv_skills: Optional[List[str]] = None,
223
+ cv_category: Optional[str] = None,
224
  ) -> Dict[str, Any]:
225
  """
226
  Predict the match between one job and one CV.
227
  Pass ``section_embeddings`` from ``/process-cv`` to skip re-encoding.
228
  """
229
+ cv_data = self._parse_cv(
230
+ cv_markdown=cv_markdown,
231
+ section_embeddings=section_embeddings,
232
+ cv_title=cv_title,
233
+ cv_years=cv_years,
234
+ cv_seniority=cv_seniority,
235
+ cv_skills=cv_skills,
236
+ cv_category=cv_category,
237
+ )
238
  return self._predict_single(job_json, cv_data)
239
 
240
  # ------------------------------------------------------------------
 
244
  def predict_batch(
245
  self,
246
  jobs: List[Dict[str, Any]],
247
+ cv_markdown: Optional[str] = None,
248
  section_embeddings: Optional[Dict[str, Any]] = None,
249
+ cv_title: Optional[str] = None,
250
+ cv_years: Optional[int] = None,
251
+ cv_seniority: Optional[str] = None,
252
+ cv_skills: Optional[List[str]] = None,
253
+ cv_category: Optional[str] = None,
254
  ) -> List[Dict[str, Any]]:
255
  """
256
  Match one CV against multiple jobs.
 
258
  The CV is parsed and embedded **once**; every subsequent job
259
  match reuses the same vectors β€” O(1) CV cost regardless of
260
  how many jobs are compared.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
261
  """
262
+ cv_data = self._parse_cv(
263
+ cv_markdown=cv_markdown,
264
+ section_embeddings=section_embeddings,
265
+ cv_title=cv_title,
266
+ cv_years=cv_years,
267
+ cv_seniority=cv_seniority,
268
+ cv_skills=cv_skills,
269
+ cv_category=cv_category,
270
+ )
271
  results = [self._predict_single(j, cv_data) for j in jobs]
272
  results.sort(
273
  key=lambda x: float(x["match_score"].rstrip("%")),
 
281
 
282
  def _parse_cv(
283
  self,
284
+ cv_markdown: Optional[str] = None,
285
  section_embeddings: Optional[Dict[str, Any]] = None,
286
+ cv_title: Optional[str] = None,
287
+ cv_years: Optional[int] = None,
288
+ cv_seniority: Optional[str] = None,
289
+ cv_skills: Optional[List[str]] = None,
290
+ cv_category: Optional[str] = None,
291
  ) -> Dict[str, Any]:
292
  """
293
  Return a dict holding all CV-level data needed by _predict_single.
294
  When section_embeddings are provided they are used directly;
295
  otherwise the model encodes each section now.
296
  """
297
+ # Fallbacks for metadata parsing if not pre-computed:
298
+ if cv_title is None or cv_years is None or cv_seniority is None or cv_skills is None or cv_category is None:
299
+ if not cv_markdown:
300
+ raise ValueError("Either cv_markdown or all pre-computed metadata fields must be provided.")
301
+ sections = _parse_cv_sections(cv_markdown)
302
+ if cv_title is None:
303
+ cv_title = _extract_cv_title(cv_markdown)
304
+ if cv_years is None:
305
+ experience = _parse_experience(sections.get("experience", ""))
306
+ computed_yrs = compute_years_from_experience(experience)
307
+ text_yrs = _extract_years(cv_markdown)
308
+ cv_years = computed_yrs if computed_yrs > 0 else text_yrs
309
+ if cv_seniority is None:
310
+ seniority_text = (
311
+ cv_title + "\n"
312
+ + sections.get("experience", "")
313
+ + "\n" + cv_markdown[:600]
314
+ )
315
+ cv_seniority = _detect_seniority(seniority_text, is_cv=True)
316
+ cv_seniority = refine_seniority_with_years(cv_seniority, cv_years)
317
+ if cv_skills is None:
318
+ cv_skills = list(_extract_skills(cv_markdown, self._aliases))
319
+ if cv_category is None:
320
+ cv_category = _infer_category(cv_markdown, set(cv_skills), self._category_skills)
321
+
322
+ cv_skills_set = set(cv_skills)
323
 
324
  # ── Embeddings ───────────────────────────────────────────────────
325
  if section_embeddings:
 
330
  skills_vec = np.array(raw_k, dtype="float32") if raw_k else None
331
  exp_vec = np.array(raw_e, dtype="float32") if raw_e else None
332
  else:
333
+ if not cv_markdown:
334
+ summary_text = ""
335
+ skills_text = " ".join(sorted(cv_skills_set))[:2000]
336
+ exp_text = ""
337
+ else:
338
+ sections = _parse_cv_sections(cv_markdown)
339
+ summary_text = sections.get("summary", "").strip()
340
+ skills_text = " ".join(sorted(cv_skills_set))[:2000]
341
+ exp_text = sections.get("experience", "")[:3000]
342
  summary_vec = self._embed(summary_text) if summary_text else None
343
  skills_vec = self._embed(skills_text) if skills_text else None
344
  exp_vec = self._embed(exp_text) if exp_text else None
 
361
  if n > 0:
362
  cv_vec /= n
363
  else:
364
+ cv_vec = self._embed(cv_markdown[:3000]) if cv_markdown else np.zeros(384, dtype="float32")
365
 
366
  return {
367
  "cv_title": cv_title,
368
  "cv_years": cv_years,
369
  "cv_seniority": cv_seniority,
370
+ "cv_skills": cv_skills_set,
371
  "cv_category": cv_category,
372
  "cv_vec": cv_vec,
373
  "skills_vec": skills_vec,