job-processor / main.py
Eng-Musa's picture
add process cv async
9d16a7f
Raw History Blame
9.11 kB
from __future__ import annotations
import tempfile
import httpx
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Optional
from fastapi import BackgroundTasks, FastAPI, File, Form, UploadFile
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from starlette.exceptions import HTTPException as StarletteHTTPException
from services import job_store
from services.cv_chunker import chunk_cv
from services.cv_converter import CVConverter
from services.job_matcher import JobInput, JobMatcher
from services.workers import CvWorker
# ---------------------------------------------------------------------------
# App setup
# ---------------------------------------------------------------------------
app = FastAPI(
title="Job Processor API",
description="CV parsing, chunking, and job-match prediction service.",
version="2.0.0",
)
converter = CVConverter()
matcher = JobMatcher() # SentenceTransformer loaded once at startup
cv_worker = CvWorker(converter)
# ---------------------------------------------------------------------------
# Shared response model
# ---------------------------------------------------------------------------
class APIResponse(BaseModel):
message: str
statusCode: int
payload: Optional[Any] = None
# Exception handlers
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
return JSONResponse(
status_code=400,
content=APIResponse(
message="Invalid request: " + str(exc.errors()),
statusCode=400
).model_dump()
)
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request, exc):
return JSONResponse(
status_code=exc.status_code,
content=APIResponse(
message=str(exc.detail),
statusCode=exc.status_code
).model_dump()
)
@app.exception_handler(Exception)
async def global_exception_handler(request, exc):
return JSONResponse(
status_code=500,
content=APIResponse(
message="Internal server error: " + str(exc),
statusCode=500
).model_dump()
)
# ---------------------------------------------------------------------------
# Health check
@app.get("/", response_model=APIResponse)
def home():
return APIResponse(message="Job Processor API is running", statusCode=200)
# POST /process-cv (synchronous)
_ALLOWED_EXT = (".pdf", ".docx", ".doc")
@app.post("/process-cv", response_model=APIResponse)
async def process_cv(file: UploadFile = File(...)):
"""
Upload a CV file (PDF, DOCX, DOC) and receive:
- Raw Markdown text
- Structured chunks (summary, experience, education, skills, projects)
- Detected CV metadata (title, seniority, category, years of experience)
- File metadata (type, method used, page count, warnings)
"""
if not file.filename:
return APIResponse(message="No file uploaded", statusCode=400)
if not file.filename.lower().endswith(_ALLOWED_EXT):
return APIResponse(
message=f"Invalid file format. Allowed formats: {', '.join(_ALLOWED_EXT)}",
statusCode=400,
)
tmp_path: Optional[Path] = None
try:
start_time = datetime.now(timezone.utc).isoformat()
file_bytes = await file.read()
suffix = Path(file.filename).suffix.lower()
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
tmp.write(file_bytes)
tmp_path = Path(tmp.name)
conversion = converter.convert(tmp_path)
if not conversion.success:
return APIResponse(message=conversion.error or "Conversion failed", statusCode=422)
chunks = chunk_cv(conversion.markdown)
end_time = datetime.now(timezone.utc).isoformat()
return APIResponse(
message="CV processed successfully",
statusCode=200,
payload={
"markdown": conversion.markdown,
"cv_title": chunks["cv_title"],
"seniority": chunks["seniority"],
"years_experience": chunks["years_experience"],
"category": chunks["category"],
"chunks": {
"summary": chunks["chunks"]["summary"],
"contact": chunks["chunks"]["contact"],
"links": chunks["chunks"]["links"],
"skills": chunks["chunks"]["skills"],
"experience": chunks["chunks"]["experience"],
"education": chunks["chunks"]["education"],
"projects": chunks["chunks"]["projects"],
"awards": chunks["chunks"]["awards"],
},
"file_type": conversion.file_type,
"method_used": conversion.method_used,
"is_scanned": conversion.is_scanned,
"page_count": conversion.page_count,
"warnings": conversion.warnings,
"start_time": start_time,
"end_time": end_time,
},
)
except Exception as exc:
return APIResponse(
message=f"An error occurred during processing: {exc}",
statusCode=500,
)
finally:
if tmp_path and tmp_path.exists():
tmp_path.unlink()
# ---------------------------------------------------------------------------
# POST /process-cv-async (NEW — used by Java async worker)
#
# Accepts the CV file plus job_id and callback_url as form fields.
# Returns 202 immediately and processes the CV in a BackgroundTask.
# On completion (success or failure) POSTs the result to callback_url.
# ---------------------------------------------------------------------------
@app.post("/process-cv-async", response_model=APIResponse)
async def process_cv_async(
background_tasks: BackgroundTasks,
file: UploadFile = File(...),
job_id: str = Form(...),
callback_url: str = Form(...),
callback_secret: str = Form(None),
):
"""
Async entry point called by the Java async worker.
Accepts the CV file + job_id + callback_url as multipart form fields.
Returns 202 immediately; processes the CV in a background task.
"""
if not file.filename:
return APIResponse(message="No file uploaded", statusCode=400)
if not file.filename.lower().endswith(_ALLOWED_EXT):
return APIResponse(
message=f"Invalid file format. Allowed formats: {', '.join(_ALLOWED_EXT)}",
statusCode=400,
)
# Read bytes before the background task starts (request closes after response)
file_bytes = await file.read()
filename = file.filename
job_store.create_job(job_id)
background_tasks.add_task(
cv_worker.run_cv_processing,
job_id,
file_bytes,
filename,
callback_url,
callback_secret,
)
return APIResponse(
message="CV processing started",
statusCode=202,
payload={"job_id": job_id, "status": "PENDING"},
)
# GET /job-status/{job_id} (Python-side status check)
@app.get("/job-status/{job_id}", response_model=APIResponse)
def get_job_status(job_id: str):
"""
Returns the current status of a CV processing job from the in-memory store.
Primarily useful for debugging; Java tracks state authoritatively in its DB.
"""
job = job_store.get_job(job_id)
if job is None:
return APIResponse(message="Job not found", statusCode=404)
return APIResponse(
message=f"Job status: {job['status']}",
statusCode=200,
payload={"job_id": job_id, "status": job["status"]},
)
# POST /match-cv (ORIGINAL — unchanged)
class MatchCVRequest(BaseModel):
"""Request body for POST /match-cv."""
job: JobInput = Field(..., description="Structured job posting to match against.")
cv_markdown: str = Field(..., min_length=20, description="The candidate's CV as a Markdown string.")
@app.post("/match-cv", response_model=APIResponse)
def match_cv_to_job(payload: MatchCVRequest):
"""
Match a Markdown CV against a structured job posting.
Returns a detailed qualification prediction including:
- Overall match score (0–100 %)
- Match level label (e.g. "Strong Match")
- Per-dimension score breakdown (skill, semantic, title, category, seniority, experience)
- Mismatch analysis and improvement advice
"""
try:
result = matcher.predict(
job_json=payload.job.model_dump(),
cv_markdown=payload.cv_markdown,
)
return APIResponse(
message="Match prediction completed successfully",
statusCode=200,
payload=result,
)
except Exception as exc:
return APIResponse(
message=f"An error occurred during matching: {exc}",
statusCode=500,
)