File size: 9,105 Bytes
37c64f2
4aa1d92
37c64f2
9d16a7f
8c1c745
37c64f2
 
 
9d16a7f
37c64f2
9d16a7f
0918462
9d16a7f
37c64f2
9d16a7f
37c64f2
764f46a
37c64f2
9d16a7f
4aa1d92
37c64f2
 
 
 
 
 
 
 
 
764f46a
 
37c64f2
9d16a7f
37c64f2
 
 
 
 
4aa1d92
 
 
 
 
764f46a
9d16a7f
37c64f2
 
70da0b3
 
 
9d16a7f
70da0b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37c64f2
 
 
 
 
4aa1d92
764f46a
 
1f80b9f
37c64f2
9d16a7f
37c64f2
1f80b9f
 
37c64f2
 
 
 
 
 
 
1f80b9f
764f46a
 
37c64f2
764f46a
37c64f2
 
1f80b9f
 
37c64f2
1f80b9f
8c1c745
1f80b9f
764f46a
 
 
 
 
 
37c64f2
 
 
764f46a
37c64f2
8c1c745
f45de3b
1f80b9f
 
 
764f46a
37c64f2
 
 
 
 
d581f2c
 
 
 
 
 
 
 
 
 
9d16a7f
 
 
 
 
 
 
37c64f2
1f80b9f
764f46a
37c64f2
764f46a
37c64f2
 
764f46a
 
 
 
0918462
 
 
 
9d16a7f
 
 
 
 
0918462
 
9d16a7f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0918462
 
 
 
 
 
 
 
 
 
 
 
37c64f2
0918462
 
 
 
 
 
 
 
 
 
 
 
 
 
37c64f2
0918462
37c64f2
0918462
 
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
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,
        )