Spaces:
Running

File size: 4,346 Bytes
9d16a7f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
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}")