from __future__ import annotations import tempfile import httpx from datetime import datetime, timezone from pathlib import Path from typing import Optional from services import job_store from services.cv_chunker import chunk_cv from services.cv_converter import CVConverter class CvWorker: """Handles background tasks for CV processing.""" def __init__(self, converter: CVConverter): self.converter = converter async def run_cv_processing( self, job_id: str, file_bytes: bytes, filename: str, callback_url: str, callback_secret: str = None ) -> None: """Background task: process CV then POST result to Java callback endpoint.""" tmp_path: Optional[Path] = None try: job_store.set_processing(job_id) start_time = datetime.now(timezone.utc).isoformat() suffix = Path(filename).suffix.lower() if filename else ".pdf" with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp: tmp.write(file_bytes) tmp_path = Path(tmp.name) conversion = self.converter.convert(tmp_path) if not conversion.success: error_msg = conversion.error or "Conversion failed" job_store.set_failed(job_id, error_msg) await self.post_callback(callback_url, { "message": error_msg, "statusCode": 422, "payload": None, }, callback_secret) return chunks = chunk_cv(conversion.markdown) end_time = datetime.now(timezone.utc).isoformat() 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, } job_store.set_completed(job_id, payload) await self.post_callback(callback_url, { "message": "CV processed successfully", "statusCode": 200, "payload": payload, }, callback_secret) except Exception as exc: error_msg = f"Processing error: {exc}" job_store.set_failed(job_id, error_msg) await self.post_callback(callback_url, { "message": error_msg, "statusCode": 500, "payload": None, }, callback_secret) finally: if tmp_path and tmp_path.exists(): tmp_path.unlink() async def post_callback(self, callback_url: str, body: dict, callback_secret: str = None) -> None: """POST the processing result back to Java.""" try: headers = {} if callback_secret: headers["X-Callback-Secret"] = callback_secret async with httpx.AsyncClient(timeout=30.0) as client: response = await client.post(callback_url, json=body, headers=headers) response.raise_for_status() except Exception as exc: # Log but don't crash — Java will see job stay in PROCESSING and can time out print(f"[CV-ASYNC] Failed to POST callback to {callback_url}: {exc}")