Spaces:
Running
Running
add match cv endpoint new using llm
Browse files- __pycache__/main.cpython-312.pyc +0 -0
- main.py +63 -0
- requirements.txt +7 -0
- services/new/__init__.py +1 -0
- services/new/__pycache__/__init__.cpython-312.pyc +0 -0
- services/new/__pycache__/config.cpython-312.pyc +0 -0
- services/new/__pycache__/cv_converter_v2.cpython-312.pyc +0 -0
- services/new/__pycache__/cv_llm_extractor.cpython-312.pyc +0 -0
- services/new/__pycache__/cv_processor_v2.cpython-312.pyc +0 -0
- services/new/config.py +64 -0
- services/new/cv_converter_v2.py +190 -0
- services/new/cv_llm_extractor.py +203 -0
- services/new/cv_processor_v2.py +74 -0
__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
|
@@ -20,6 +20,7 @@ from services.cv_chunker import chunk_cv
|
|
| 20 |
from services.cv_converter import CVConverter
|
| 21 |
from services.job_matcher import JobInput, JobMatcher
|
| 22 |
from services.workers import CvWorker, QueueManager, CvTask
|
|
|
|
| 23 |
|
| 24 |
# ---------------------------------------------------------------------------
|
| 25 |
# Configuration
|
|
@@ -57,6 +58,7 @@ 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
|
|
@@ -412,3 +414,64 @@ def batch_match_cv(payload: BatchMatchCVRequest):
|
|
| 412 |
message=f"Batch match error: {exc}",
|
| 413 |
statusCode=500,
|
| 414 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
from services.cv_converter import CVConverter
|
| 21 |
from services.job_matcher import JobInput, JobMatcher
|
| 22 |
from services.workers import CvWorker, QueueManager, CvTask
|
| 23 |
+
from services.new.cv_processor_v2 import CvProcessorV2
|
| 24 |
|
| 25 |
# ---------------------------------------------------------------------------
|
| 26 |
# Configuration
|
|
|
|
| 58 |
matcher = JobMatcher() # SentenceTransformer loaded once at startup
|
| 59 |
cv_worker = CvWorker(converter, matcher)
|
| 60 |
queue_manager = QueueManager(cv_worker, concurrency=1)
|
| 61 |
+
cv_processor_v2 = CvProcessorV2() # V2 β LLM extractor lazy-loads on first request
|
| 62 |
|
| 63 |
|
| 64 |
@asynccontextmanager
|
|
|
|
| 414 |
message=f"Batch match error: {exc}",
|
| 415 |
statusCode=500,
|
| 416 |
)
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
# ---------------------------------------------------------------------------
|
| 420 |
+
# POST /v2/process-cv β LLM-powered extraction (pymupdf4llm + local GGUF)
|
| 421 |
+
# ---------------------------------------------------------------------------
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
@app.post("/v2/process-cv", response_model=APIResponse)
|
| 425 |
+
async def process_cv_v2(file: UploadFile = File(...)):
|
| 426 |
+
"""
|
| 427 |
+
V2 CV processing endpoint.
|
| 428 |
+
Converts the uploaded file to Markdown then extracts all fields using a
|
| 429 |
+
local LLM (Phi-3-mini Q4 by default). Returns markdown, structured fields,
|
| 430 |
+
and a sections[] array that preserves the original CV heading titles.
|
| 431 |
+
"""
|
| 432 |
+
if not file.filename:
|
| 433 |
+
return APIResponse(message="No file uploaded.", statusCode=400)
|
| 434 |
+
|
| 435 |
+
ext = Path(file.filename).suffix.lower()
|
| 436 |
+
if ext not in _ALLOWED_EXT:
|
| 437 |
+
return APIResponse(
|
| 438 |
+
message=f"Invalid file format. Allowed: {', '.join(_ALLOWED_EXT)}",
|
| 439 |
+
statusCode=400,
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
file_bytes = await file.read()
|
| 443 |
+
|
| 444 |
+
if len(file_bytes) > MAX_FILE_BYTES:
|
| 445 |
+
return APIResponse(
|
| 446 |
+
message=f"File too large. Maximum size is {MAX_FILE_BYTES // (1024 * 1024)} MB.",
|
| 447 |
+
statusCode=413,
|
| 448 |
+
)
|
| 449 |
+
|
| 450 |
+
if not _check_mime(file_bytes, ext):
|
| 451 |
+
return APIResponse(
|
| 452 |
+
message="File content does not match the declared extension.",
|
| 453 |
+
statusCode=400,
|
| 454 |
+
)
|
| 455 |
+
|
| 456 |
+
t_start = datetime.now(timezone.utc)
|
| 457 |
+
|
| 458 |
+
try:
|
| 459 |
+
payload = cv_processor_v2.process(file_bytes, file.filename)
|
| 460 |
+
except ValueError as exc:
|
| 461 |
+
# Covers scanned PDF rejection and conversion failures
|
| 462 |
+
return APIResponse(message=str(exc), statusCode=422)
|
| 463 |
+
except Exception as exc:
|
| 464 |
+
return APIResponse(message=f"Processing error: {exc}", statusCode=500)
|
| 465 |
+
|
| 466 |
+
t_end = datetime.now(timezone.utc)
|
| 467 |
+
total_ms = int((t_end - t_start).total_seconds() * 1000)
|
| 468 |
+
|
| 469 |
+
return APIResponse(
|
| 470 |
+
message="CV processed successfully",
|
| 471 |
+
statusCode=200,
|
| 472 |
+
payload={
|
| 473 |
+
**payload,
|
| 474 |
+
"timing": {"total_ms": total_ms},
|
| 475 |
+
"processed_at": t_end.isoformat(),
|
| 476 |
+
},
|
| 477 |
+
)
|
requirements.txt
CHANGED
|
@@ -16,6 +16,13 @@ marker-pdf
|
|
| 16 |
pypandoc
|
| 17 |
pandoc
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
# AI / ML Models
|
| 20 |
transformers
|
| 21 |
accelerate
|
|
|
|
| 16 |
pypandoc
|
| 17 |
pandoc
|
| 18 |
|
| 19 |
+
# V2 β lightweight PDF extraction (no ML models)
|
| 20 |
+
pymupdf4llm
|
| 21 |
+
|
| 22 |
+
# V2 β local LLM inference + model download
|
| 23 |
+
llama-cpp-python
|
| 24 |
+
huggingface_hub
|
| 25 |
+
|
| 26 |
# AI / ML Models
|
| 27 |
transformers
|
| 28 |
accelerate
|
services/new/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# V2 CV processing pipeline β LLM-powered extraction
|
services/new/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (138 Bytes). View file
|
|
|
services/new/__pycache__/config.cpython-312.pyc
ADDED
|
Binary file (1.02 kB). View file
|
|
|
services/new/__pycache__/cv_converter_v2.cpython-312.pyc
ADDED
|
Binary file (10.3 kB). View file
|
|
|
services/new/__pycache__/cv_llm_extractor.cpython-312.pyc
ADDED
|
Binary file (9.78 kB). View file
|
|
|
services/new/__pycache__/cv_processor_v2.cpython-312.pyc
ADDED
|
Binary file (4.12 kB). View file
|
|
|
services/new/config.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
config.py
|
| 3 |
+
=========
|
| 4 |
+
Model configuration for the V2 LLM-powered CV extraction pipeline.
|
| 5 |
+
|
| 6 |
+
The processor will attempt to use the model at index 0.
|
| 7 |
+
If its download fails, it falls back to index 1.
|
| 8 |
+
Put your preferred model first.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
# ---------------------------------------------------------------------------
|
| 14 |
+
# Model priority list
|
| 15 |
+
# ---------------------------------------------------------------------------
|
| 16 |
+
# Each entry:
|
| 17 |
+
# repo_id β HuggingFace repo (must be ungated / publicly accessible)
|
| 18 |
+
# filename β exact GGUF filename inside that repo
|
| 19 |
+
# n_ctx β context window in tokens (input + output combined)
|
| 20 |
+
# n_threads β CPU threads to use during inference (match your vCPU count)
|
| 21 |
+
# max_tokens β max tokens the LLM may generate in one response
|
| 22 |
+
# ---------------------------------------------------------------------------
|
| 23 |
+
|
| 24 |
+
MODELS = [
|
| 25 |
+
{
|
| 26 |
+
"label": "Phi-3-mini-4k Q4_K_M",
|
| 27 |
+
"repo_id": "bartowski/Phi-3-mini-4k-instruct-GGUF",
|
| 28 |
+
"filename": "Phi-3-mini-4k-instruct-Q4_K_M.gguf",
|
| 29 |
+
"n_ctx": 4096,
|
| 30 |
+
"n_threads": 2,
|
| 31 |
+
"max_tokens": 2048,
|
| 32 |
+
},
|
| 33 |
+
{
|
| 34 |
+
"label": "TinyLlama-1.1B Q4_K_M",
|
| 35 |
+
"repo_id": "TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF",
|
| 36 |
+
"filename": "tinyllama-1.1b-chat-v1.0.Q4_K_M.gguf",
|
| 37 |
+
"n_ctx": 2048,
|
| 38 |
+
"n_threads": 2,
|
| 39 |
+
"max_tokens": 1024,
|
| 40 |
+
},
|
| 41 |
+
]
|
| 42 |
+
|
| 43 |
+
# ---------------------------------------------------------------------------
|
| 44 |
+
# Cache directory β GGUF files are downloaded here once and reused
|
| 45 |
+
# ---------------------------------------------------------------------------
|
| 46 |
+
# On HuggingFace Spaces free tier the filesystem is ephemeral, so the model
|
| 47 |
+
# re-downloads on cold start. Point this to a mounted persistent volume
|
| 48 |
+
# (e.g. /data/model_cache) if you have one.
|
| 49 |
+
# ---------------------------------------------------------------------------
|
| 50 |
+
|
| 51 |
+
MODEL_CACHE_DIR = str(Path(__file__).parent.parent.parent / "model_cache")
|
| 52 |
+
|
| 53 |
+
# ---------------------------------------------------------------------------
|
| 54 |
+
# CV truncation limit
|
| 55 |
+
# ---------------------------------------------------------------------------
|
| 56 |
+
# Maximum characters of CV markdown sent to the LLM.
|
| 57 |
+
# Keeps input within the context window while fitting the prompt + output.
|
| 58 |
+
# Phi-3-mini 4k: ~4096 tokens total; 1 token β 4 chars.
|
| 59 |
+
# Prompt template β 400 tokens β ~1596 tokens left for CV + output.
|
| 60 |
+
# Safe CV budget β 2800 tokens β ~11 200 chars; we cap at 8000 to leave
|
| 61 |
+
# breathing room for the JSON output (~1500β2000 tokens).
|
| 62 |
+
# ---------------------------------------------------------------------------
|
| 63 |
+
|
| 64 |
+
MAX_CV_CHARS = 8000
|
services/new/cv_converter_v2.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""V2 PDF/DOCX/DOC β Markdown converter using pymupdf4llm. Scanned PDFs are rejected."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import logging
|
| 6 |
+
import re
|
| 7 |
+
import subprocess
|
| 8 |
+
import tempfile
|
| 9 |
+
from dataclasses import dataclass, field
|
| 10 |
+
from enum import Enum
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from typing import Optional
|
| 13 |
+
|
| 14 |
+
logger = logging.getLogger(__name__)
|
| 15 |
+
|
| 16 |
+
_MIN_CHARS_PER_PAGE: int = 50
|
| 17 |
+
_LIBREOFFICE_TIMEOUT: int = 60
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class FileTypeV2(str, Enum):
|
| 21 |
+
PDF = "pdf"
|
| 22 |
+
DOCX = "docx"
|
| 23 |
+
DOC = "doc"
|
| 24 |
+
UNKNOWN = "unknown"
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@dataclass
|
| 28 |
+
class ConversionResultV2:
|
| 29 |
+
success: bool
|
| 30 |
+
markdown: Optional[str] = None
|
| 31 |
+
file_type: Optional[str] = None
|
| 32 |
+
is_scanned: bool = False
|
| 33 |
+
page_count: int = 0
|
| 34 |
+
warnings: list[str] = field(default_factory=list)
|
| 35 |
+
error: Optional[str] = None
|
| 36 |
+
|
| 37 |
+
def __bool__(self) -> bool:
|
| 38 |
+
return self.success
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class CvConverterV2:
|
| 42 |
+
"""PDF β pymupdf4llm, DOCX/DOC β pypandoc. No ML dependencies."""
|
| 43 |
+
|
| 44 |
+
def convert(self, file_path: str | Path) -> ConversionResultV2:
|
| 45 |
+
"""Convert a CV file to Markdown. Never raises; errors are in result.error."""
|
| 46 |
+
path = Path(file_path)
|
| 47 |
+
|
| 48 |
+
if not path.exists():
|
| 49 |
+
return ConversionResultV2(success=False, error=f"File not found: {path}")
|
| 50 |
+
if not path.is_file():
|
| 51 |
+
return ConversionResultV2(success=False, error=f"Not a regular file: {path}")
|
| 52 |
+
if path.stat().st_size == 0:
|
| 53 |
+
return ConversionResultV2(success=False, error=f"File is empty: {path.name}")
|
| 54 |
+
|
| 55 |
+
file_type = self._detect_file_type(path)
|
| 56 |
+
|
| 57 |
+
if file_type == FileTypeV2.PDF:
|
| 58 |
+
return self._convert_pdf(path)
|
| 59 |
+
if file_type in (FileTypeV2.DOCX, FileTypeV2.DOC):
|
| 60 |
+
return self._convert_word(path, file_type)
|
| 61 |
+
|
| 62 |
+
return ConversionResultV2(
|
| 63 |
+
success=False,
|
| 64 |
+
error=f"Unsupported file type '{path.suffix}'. Accepted: .pdf, .docx, .doc",
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
@staticmethod
|
| 68 |
+
def _detect_file_type(path: Path) -> FileTypeV2:
|
| 69 |
+
return {".pdf": FileTypeV2.PDF, ".docx": FileTypeV2.DOCX, ".doc": FileTypeV2.DOC}.get(
|
| 70 |
+
path.suffix.lower(), FileTypeV2.UNKNOWN
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
def _convert_pdf(self, path: Path) -> ConversionResultV2:
|
| 74 |
+
"""Extract text via pymupdf4llm. Returns 422-style error for scanned/image PDFs."""
|
| 75 |
+
try:
|
| 76 |
+
import fitz
|
| 77 |
+
import pymupdf4llm
|
| 78 |
+
except ImportError as exc:
|
| 79 |
+
return ConversionResultV2(success=False, error=f"pymupdf4llm not installed: {exc}")
|
| 80 |
+
|
| 81 |
+
try:
|
| 82 |
+
doc = fitz.open(str(path))
|
| 83 |
+
page_count = len(doc)
|
| 84 |
+
if page_count == 0:
|
| 85 |
+
doc.close()
|
| 86 |
+
return ConversionResultV2(success=False, error=f"'{path.name}' has zero pages.")
|
| 87 |
+
|
| 88 |
+
total_chars = sum(len(page.get_text().strip()) for page in doc)
|
| 89 |
+
avg_chars = total_chars / page_count
|
| 90 |
+
doc.close()
|
| 91 |
+
except Exception as exc:
|
| 92 |
+
return ConversionResultV2(success=False, error=f"PDF inspection failed: {exc}")
|
| 93 |
+
|
| 94 |
+
if avg_chars < _MIN_CHARS_PER_PAGE:
|
| 95 |
+
return ConversionResultV2(
|
| 96 |
+
success=False,
|
| 97 |
+
is_scanned=True,
|
| 98 |
+
file_type=FileTypeV2.PDF.value,
|
| 99 |
+
page_count=page_count,
|
| 100 |
+
error=(
|
| 101 |
+
"This PDF appears to be a scanned image and cannot be processed. "
|
| 102 |
+
"Please upload a text-based PDF or convert it to DOCX first."
|
| 103 |
+
),
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
try:
|
| 107 |
+
markdown = pymupdf4llm.to_markdown(str(path))
|
| 108 |
+
except Exception as exc:
|
| 109 |
+
return ConversionResultV2(success=False, error=f"pymupdf4llm failed: {exc}")
|
| 110 |
+
|
| 111 |
+
if not markdown or not markdown.strip():
|
| 112 |
+
return ConversionResultV2(success=False, error=f"No text extracted from '{path.name}'.")
|
| 113 |
+
|
| 114 |
+
return ConversionResultV2(
|
| 115 |
+
success=True,
|
| 116 |
+
markdown=self._clean_markdown(markdown),
|
| 117 |
+
file_type=FileTypeV2.PDF.value,
|
| 118 |
+
is_scanned=False,
|
| 119 |
+
page_count=page_count,
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
def _convert_word(self, path: Path, file_type: FileTypeV2) -> ConversionResultV2:
|
| 123 |
+
"""DOCX β GFM via pandoc. DOC first goes through LibreOffice β DOCX."""
|
| 124 |
+
try:
|
| 125 |
+
import pypandoc # noqa: F401
|
| 126 |
+
except ImportError:
|
| 127 |
+
return ConversionResultV2(success=False, error="pypandoc not installed.")
|
| 128 |
+
|
| 129 |
+
warnings: list[str] = []
|
| 130 |
+
|
| 131 |
+
if file_type == FileTypeV2.DOC:
|
| 132 |
+
try:
|
| 133 |
+
path, warnings = self._doc_to_docx(path, warnings)
|
| 134 |
+
except RuntimeError as exc:
|
| 135 |
+
return ConversionResultV2(success=False, error=str(exc))
|
| 136 |
+
|
| 137 |
+
try:
|
| 138 |
+
import pypandoc
|
| 139 |
+
markdown = pypandoc.convert_file(
|
| 140 |
+
str(path),
|
| 141 |
+
to="gfm",
|
| 142 |
+
extra_args=["--wrap=none", "--strip-comments", "--markdown-headings=atx"],
|
| 143 |
+
)
|
| 144 |
+
except Exception as exc:
|
| 145 |
+
return ConversionResultV2(success=False, error=f"Pandoc failed: {exc}")
|
| 146 |
+
|
| 147 |
+
if not markdown or not markdown.strip():
|
| 148 |
+
return ConversionResultV2(success=False, error=f"Pandoc returned empty output for '{path.name}'.")
|
| 149 |
+
|
| 150 |
+
return ConversionResultV2(
|
| 151 |
+
success=True,
|
| 152 |
+
markdown=self._clean_markdown(markdown),
|
| 153 |
+
file_type=file_type.value,
|
| 154 |
+
is_scanned=False,
|
| 155 |
+
warnings=warnings,
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
def _doc_to_docx(self, path: Path, warnings: list[str]) -> tuple[Path, list[str]]:
|
| 159 |
+
"""Convert legacy .doc to .docx via LibreOffice headless."""
|
| 160 |
+
tmp_dir = Path(tempfile.gettempdir())
|
| 161 |
+
docx_path = tmp_dir / (path.stem + ".docx")
|
| 162 |
+
|
| 163 |
+
try:
|
| 164 |
+
proc = subprocess.run(
|
| 165 |
+
["libreoffice", "--headless", "--convert-to", "docx", "--outdir", str(tmp_dir), str(path)],
|
| 166 |
+
capture_output=True, text=True, timeout=_LIBREOFFICE_TIMEOUT,
|
| 167 |
+
)
|
| 168 |
+
except FileNotFoundError:
|
| 169 |
+
raise RuntimeError("LibreOffice not found on PATH. Install it to convert .doc files.")
|
| 170 |
+
except subprocess.TimeoutExpired:
|
| 171 |
+
raise RuntimeError(f"LibreOffice timed out after {_LIBREOFFICE_TIMEOUT}s.")
|
| 172 |
+
|
| 173 |
+
if proc.returncode != 0:
|
| 174 |
+
raise RuntimeError(f"LibreOffice error: {proc.stderr.strip()}")
|
| 175 |
+
if not docx_path.exists():
|
| 176 |
+
raise RuntimeError("LibreOffice ran but no .docx was produced.")
|
| 177 |
+
|
| 178 |
+
warnings.append("Legacy .doc converted to .docx via LibreOffice.")
|
| 179 |
+
return docx_path, warnings
|
| 180 |
+
|
| 181 |
+
@staticmethod
|
| 182 |
+
def _clean_markdown(text: str) -> str:
|
| 183 |
+
"""Normalize line endings, strip converter artefacts, collapse blank lines."""
|
| 184 |
+
text = text.replace("\r\n", "\n").replace("\r", "\n")
|
| 185 |
+
for bad, good in {"\x00": "", "\uf0b7": "-", "\uf0a7": "-", "\uf020": " ", "\uf0fc": "-"}.items():
|
| 186 |
+
text = text.replace(bad, good)
|
| 187 |
+
text = "\n".join(line.rstrip() for line in text.split("\n"))
|
| 188 |
+
text = re.sub(r"(?m)^[-=]{3,}\s*$", "", text)
|
| 189 |
+
text = re.sub(r"\n{3,}", "\n\n", text)
|
| 190 |
+
return text.strip()
|
services/new/cv_llm_extractor.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LLM-powered CV field extractor. Downloads a GGUF model on first use and caches it."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import logging
|
| 7 |
+
import re
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Any, Dict, List, Optional
|
| 10 |
+
|
| 11 |
+
from services.new.config import MAX_CV_CHARS, MODEL_CACHE_DIR, MODELS
|
| 12 |
+
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
# ---------------------------------------------------------------------------
|
| 16 |
+
# Prompts
|
| 17 |
+
# ---------------------------------------------------------------------------
|
| 18 |
+
|
| 19 |
+
_SYSTEM_PROMPT = (
|
| 20 |
+
"You are a professional CV/Resume parser. "
|
| 21 |
+
"Extract all information from the CV and return a single valid JSON object. "
|
| 22 |
+
"Extract ONLY what is explicitly in the CV β never invent data."
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
_USER_PROMPT = """\
|
| 26 |
+
Parse the CV below and return a JSON object with EXACTLY this structure.
|
| 27 |
+
Use "" for missing strings and [] for missing arrays. Do not add extra keys.
|
| 28 |
+
|
| 29 |
+
{{
|
| 30 |
+
"cv_title": "professional title or most recent job title",
|
| 31 |
+
"seniority": "one of: intern | entry | mid | senior | lead",
|
| 32 |
+
"years_experience": 0,
|
| 33 |
+
"category": "one of: engineering | design | finance | marketing | sales | operations | healthcare | legal | education | hr | other",
|
| 34 |
+
"summary": "professional summary text or empty string",
|
| 35 |
+
"contact": {{"email": "", "phone": "", "location": ""}},
|
| 36 |
+
"links": [{{"label": "GitHub | LinkedIn | Portfolio | Website | Twitter", "url": "full URL"}}],
|
| 37 |
+
"skills": {{
|
| 38 |
+
"items": ["every skill as listed in CV"],
|
| 39 |
+
"technical": ["technical/hard skills only"],
|
| 40 |
+
"soft": ["soft/interpersonal skills only"]
|
| 41 |
+
}},
|
| 42 |
+
"experience": [{{"role": "", "company": "", "period": "", "responsibilities": []}}],
|
| 43 |
+
"education": [{{"institution": "", "degree": "", "period": ""}}],
|
| 44 |
+
"projects": [{{"name": "", "description": "", "tech_stack": [], "url": ""}}],
|
| 45 |
+
"awards": [{{"title": "", "year": "", "issuer": ""}}],
|
| 46 |
+
"sections": [{{"title": "EXACT heading as written in CV", "type": "summary | experience | education | skills | projects | awards | unknown", "content": "full section text"}}]
|
| 47 |
+
}}
|
| 48 |
+
|
| 49 |
+
Seniority: intern=0-1yr, entry=1-2yr, mid=2-5yr, senior=5-8yr, lead=8+yr or people manager.
|
| 50 |
+
years_experience: integer from earliest job start to now. 0 for students.
|
| 51 |
+
sections.title: copy heading EXACTLY as it appears (e.g. "My Professional Journey").
|
| 52 |
+
|
| 53 |
+
CV:
|
| 54 |
+
{cv_markdown}"""
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# ---------------------------------------------------------------------------
|
| 58 |
+
# Extractor
|
| 59 |
+
# ---------------------------------------------------------------------------
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class CvLlmExtractor:
|
| 63 |
+
"""Downloads, caches, and runs a local GGUF model for structured CV extraction."""
|
| 64 |
+
|
| 65 |
+
def __init__(self) -> None:
|
| 66 |
+
self._llm = None
|
| 67 |
+
self._active_cfg: Optional[Dict] = None
|
| 68 |
+
|
| 69 |
+
@property
|
| 70 |
+
def llm(self):
|
| 71 |
+
"""Lazy-load the model on first access."""
|
| 72 |
+
if self._llm is None:
|
| 73 |
+
self._load_model()
|
| 74 |
+
return self._llm
|
| 75 |
+
|
| 76 |
+
def _load_model(self) -> None:
|
| 77 |
+
"""Try each model in MODELS order. Download GGUF if not cached, then load."""
|
| 78 |
+
from huggingface_hub import hf_hub_download
|
| 79 |
+
from llama_cpp import Llama
|
| 80 |
+
|
| 81 |
+
cache_dir = Path(MODEL_CACHE_DIR)
|
| 82 |
+
cache_dir.mkdir(parents=True, exist_ok=True)
|
| 83 |
+
|
| 84 |
+
last_error: Optional[Exception] = None
|
| 85 |
+
|
| 86 |
+
for cfg in MODELS:
|
| 87 |
+
try:
|
| 88 |
+
logger.info("Downloading/loading model: %s", cfg["label"])
|
| 89 |
+
model_path = hf_hub_download(
|
| 90 |
+
repo_id=cfg["repo_id"],
|
| 91 |
+
filename=cfg["filename"],
|
| 92 |
+
cache_dir=str(cache_dir),
|
| 93 |
+
)
|
| 94 |
+
self._llm = Llama(
|
| 95 |
+
model_path=model_path,
|
| 96 |
+
n_ctx=cfg["n_ctx"],
|
| 97 |
+
n_threads=cfg.get("n_threads", 2),
|
| 98 |
+
n_gpu_layers=0,
|
| 99 |
+
verbose=False,
|
| 100 |
+
)
|
| 101 |
+
self._active_cfg = cfg
|
| 102 |
+
logger.info("Model ready: %s", cfg["label"])
|
| 103 |
+
return
|
| 104 |
+
except Exception as exc:
|
| 105 |
+
logger.warning("Model '%s' failed: %s β trying next.", cfg["label"], exc)
|
| 106 |
+
last_error = exc
|
| 107 |
+
|
| 108 |
+
raise RuntimeError(f"All models failed. Last error: {last_error}")
|
| 109 |
+
|
| 110 |
+
def extract(self, markdown: str) -> Dict[str, Any]:
|
| 111 |
+
"""Run LLM over CV markdown and return all fields needed for CvProfile."""
|
| 112 |
+
cfg = self._active_cfg or MODELS[0]
|
| 113 |
+
|
| 114 |
+
cv_text = markdown[:MAX_CV_CHARS]
|
| 115 |
+
if len(markdown) > MAX_CV_CHARS:
|
| 116 |
+
logger.warning("CV truncated from %d to %d chars.", len(markdown), MAX_CV_CHARS)
|
| 117 |
+
|
| 118 |
+
response = self.llm.create_chat_completion(
|
| 119 |
+
messages=[
|
| 120 |
+
{"role": "system", "content": _SYSTEM_PROMPT},
|
| 121 |
+
{"role": "user", "content": _USER_PROMPT.format(cv_markdown=cv_text)},
|
| 122 |
+
],
|
| 123 |
+
response_format={"type": "json_object"},
|
| 124 |
+
temperature=0.1,
|
| 125 |
+
max_tokens=cfg.get("max_tokens", 2048),
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
raw = response["choices"][0]["message"]["content"]
|
| 129 |
+
data = self._parse_json(raw)
|
| 130 |
+
data = self._normalize(data)
|
| 131 |
+
data["completeness_score"] = self._completeness(data)
|
| 132 |
+
data["markdown"] = markdown
|
| 133 |
+
return data
|
| 134 |
+
|
| 135 |
+
@staticmethod
|
| 136 |
+
def _parse_json(raw: str) -> Dict[str, Any]:
|
| 137 |
+
"""Parse JSON from LLM response; falls back to regex extraction."""
|
| 138 |
+
try:
|
| 139 |
+
return json.loads(raw.strip())
|
| 140 |
+
except json.JSONDecodeError:
|
| 141 |
+
match = re.search(r"\{.*\}", raw, re.DOTALL)
|
| 142 |
+
if match:
|
| 143 |
+
return json.loads(match.group())
|
| 144 |
+
raise ValueError(f"Could not parse JSON from LLM output: {raw[:300]}")
|
| 145 |
+
|
| 146 |
+
@staticmethod
|
| 147 |
+
def _normalize(data: Dict[str, Any]) -> Dict[str, Any]:
|
| 148 |
+
"""Ensure all keys exist with correct types; fill missing with safe defaults."""
|
| 149 |
+
data.setdefault("cv_title", "")
|
| 150 |
+
data.setdefault("seniority", "entry")
|
| 151 |
+
data.setdefault("years_experience", 0)
|
| 152 |
+
data.setdefault("category", "other")
|
| 153 |
+
data.setdefault("summary", "")
|
| 154 |
+
|
| 155 |
+
try:
|
| 156 |
+
data["years_experience"] = int(data["years_experience"])
|
| 157 |
+
except (TypeError, ValueError):
|
| 158 |
+
data["years_experience"] = 0
|
| 159 |
+
|
| 160 |
+
contact = data.get("contact")
|
| 161 |
+
if not isinstance(contact, dict):
|
| 162 |
+
data["contact"] = {"email": "", "phone": "", "location": ""}
|
| 163 |
+
else:
|
| 164 |
+
contact.setdefault("email", "")
|
| 165 |
+
contact.setdefault("phone", "")
|
| 166 |
+
contact.setdefault("location", "")
|
| 167 |
+
|
| 168 |
+
for key in ("links", "experience", "education", "projects", "awards", "sections"):
|
| 169 |
+
if not isinstance(data.get(key), list):
|
| 170 |
+
data[key] = []
|
| 171 |
+
|
| 172 |
+
skills = data.get("skills")
|
| 173 |
+
if not isinstance(skills, dict):
|
| 174 |
+
data["skills"] = {"items": [], "technical": [], "soft": []}
|
| 175 |
+
else:
|
| 176 |
+
for sub in ("items", "technical", "soft"):
|
| 177 |
+
if not isinstance(skills.get(sub), list):
|
| 178 |
+
skills[sub] = []
|
| 179 |
+
|
| 180 |
+
return data
|
| 181 |
+
|
| 182 |
+
@staticmethod
|
| 183 |
+
def _completeness(data: Dict[str, Any]) -> int:
|
| 184 |
+
"""Compute a 0β100 completeness score from the extracted data."""
|
| 185 |
+
score = 0
|
| 186 |
+
if isinstance(data.get("summary"), str) and len(data["summary"]) > 50:
|
| 187 |
+
score += 20
|
| 188 |
+
if data.get("experience"):
|
| 189 |
+
score += 25
|
| 190 |
+
if len(data.get("skills", {}).get("items", [])) >= 3:
|
| 191 |
+
score += 15
|
| 192 |
+
if data.get("education"):
|
| 193 |
+
score += 15
|
| 194 |
+
if data.get("contact", {}).get("email"):
|
| 195 |
+
score += 10
|
| 196 |
+
if data.get("years_experience", 0) > 0:
|
| 197 |
+
score += 5
|
| 198 |
+
if data.get("links"):
|
| 199 |
+
score += 5
|
| 200 |
+
title = data.get("cv_title", "")
|
| 201 |
+
if title and title.strip().lower() not in ("", "unknown"):
|
| 202 |
+
score += 5
|
| 203 |
+
return min(100, score)
|
services/new/cv_processor_v2.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Orchestrates V2 CV processing: file β markdown β LLM extraction β payload."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import logging
|
| 6 |
+
import tempfile
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Any, Dict
|
| 9 |
+
|
| 10 |
+
from services.new.cv_converter_v2 import CvConverterV2
|
| 11 |
+
from services.new.cv_llm_extractor import CvLlmExtractor
|
| 12 |
+
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class CvProcessorV2:
|
| 17 |
+
"""Single entry point for V2 processing. Instantiate once, reuse across requests."""
|
| 18 |
+
|
| 19 |
+
def __init__(self) -> None:
|
| 20 |
+
self.converter = CvConverterV2()
|
| 21 |
+
self.extractor = CvLlmExtractor()
|
| 22 |
+
|
| 23 |
+
def process(self, file_bytes: bytes, filename: str) -> Dict[str, Any]:
|
| 24 |
+
"""
|
| 25 |
+
Convert file β markdown, then run LLM extraction.
|
| 26 |
+
Returns a dict with all fields to be saved to CvProfile.
|
| 27 |
+
Raises ValueError on conversion failure.
|
| 28 |
+
"""
|
| 29 |
+
suffix = Path(filename).suffix.lower() if filename else ".pdf"
|
| 30 |
+
tmp_path = None
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
|
| 34 |
+
tmp.write(file_bytes)
|
| 35 |
+
tmp_path = Path(tmp.name)
|
| 36 |
+
|
| 37 |
+
# Step 1 β file β markdown
|
| 38 |
+
conversion = self.converter.convert(tmp_path)
|
| 39 |
+
if not conversion.success:
|
| 40 |
+
raise ValueError(conversion.error or "Conversion failed")
|
| 41 |
+
|
| 42 |
+
# Step 2 β markdown β structured fields via LLM
|
| 43 |
+
extracted = self.extractor.extract(conversion.markdown)
|
| 44 |
+
|
| 45 |
+
return {
|
| 46 |
+
# ββ LLM-extracted fields ββ
|
| 47 |
+
"markdown": extracted.get("markdown", conversion.markdown),
|
| 48 |
+
"cv_title": extracted.get("cv_title", ""),
|
| 49 |
+
"seniority": extracted.get("seniority", "entry"),
|
| 50 |
+
"years_experience": extracted.get("years_experience", 0),
|
| 51 |
+
"category": extracted.get("category", "other"),
|
| 52 |
+
"completeness_score": extracted.get("completeness_score", 0),
|
| 53 |
+
"summary": extracted.get("summary", ""),
|
| 54 |
+
"contact": extracted.get("contact", {}),
|
| 55 |
+
"links": extracted.get("links", []),
|
| 56 |
+
"skills": extracted.get("skills", {}),
|
| 57 |
+
"experience": extracted.get("experience", []),
|
| 58 |
+
"education": extracted.get("education", []),
|
| 59 |
+
"projects": extracted.get("projects", []),
|
| 60 |
+
"awards": extracted.get("awards", []),
|
| 61 |
+
"sections": extracted.get("sections", []),
|
| 62 |
+
# ββ Conversion metadata ββ
|
| 63 |
+
"file_type": conversion.file_type,
|
| 64 |
+
"is_scanned": conversion.is_scanned,
|
| 65 |
+
"page_count": conversion.page_count,
|
| 66 |
+
"warnings": conversion.warnings,
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
finally:
|
| 70 |
+
if tmp_path is not None:
|
| 71 |
+
try:
|
| 72 |
+
tmp_path.unlink(missing_ok=True)
|
| 73 |
+
except Exception:
|
| 74 |
+
pass
|