File size: 13,726 Bytes
37c64f2
4aa1d92
37c64f2
aa5d8fe
9d16a7f
8c1c745
37c64f2
aa5d8fe
37c64f2
7f331eb
 
 
37c64f2
9d16a7f
0918462
9d16a7f
37c64f2
9d16a7f
37c64f2
764f46a
37c64f2
7f331eb
4aa1d92
aa5d8fe
 
 
 
 
 
 
 
2d765ca
 
aa5d8fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37c64f2
 
 
 
2d765ca
 
 
4c6ffbd
7f331eb
aa5d8fe
7f331eb
 
 
 
 
 
aa5d8fe
37c64f2
 
 
aa5d8fe
7f331eb
37c64f2
764f46a
37c64f2
 
 
 
4aa1d92
2d765ca
4aa1d92
2d765ca
4aa1d92
2d765ca
764f46a
aa5d8fe
 
9d16a7f
aa5d8fe
 
2d765ca
37c64f2
 
70da0b3
 
 
9d16a7f
aa5d8fe
 
70da0b3
 
aa5d8fe
70da0b3
 
 
 
 
 
aa5d8fe
 
70da0b3
 
aa5d8fe
70da0b3
 
 
 
 
 
aa5d8fe
 
70da0b3
37c64f2
 
 
 
aa5d8fe
 
2d765ca
37c64f2
4aa1d92
764f46a
 
1f80b9f
aa5d8fe
 
 
37c64f2
2d765ca
1f80b9f
 
37c64f2
 
 
aa5d8fe
37c64f2
aa5d8fe
 
 
 
37c64f2
aa5d8fe
 
1f80b9f
764f46a
 
aa5d8fe
 
764f46a
aa5d8fe
37c64f2
1f80b9f
 
37c64f2
aa5d8fe
 
1f80b9f
 
764f46a
aa5d8fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
764f46a
 
 
aa5d8fe
 
37c64f2
aa5d8fe
 
 
37c64f2
aa5d8fe
 
 
 
 
 
 
 
 
 
764f46a
aa5d8fe
 
f45de3b
1f80b9f
 
 
764f46a
2d765ca
 
 
 
 
 
aa5d8fe
d581f2c
2d765ca
 
 
 
d581f2c
2d765ca
 
 
d581f2c
aa5d8fe
 
 
2d765ca
 
 
 
 
aa5d8fe
 
2d765ca
 
aa5d8fe
 
37c64f2
1f80b9f
764f46a
37c64f2
764f46a
37c64f2
 
764f46a
 
 
aa5d8fe
 
 
 
 
 
0918462
 
 
aa5d8fe
0918462
 
2d765ca
9d16a7f
 
 
 
 
 
 
 
 
7f331eb
9d16a7f
 
 
 
aa5d8fe
 
9d16a7f
aa5d8fe
9d16a7f
 
 
 
 
aa5d8fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d16a7f
 
7f331eb
 
 
 
 
aa5d8fe
9d16a7f
2ab506e
 
 
 
 
 
 
aa5d8fe
 
 
 
2ab506e
9d16a7f
 
 
 
2ab506e
9d16a7f
 
 
aa5d8fe
 
 
 
2d765ca
9d16a7f
 
aa5d8fe
9d16a7f
 
 
 
860fadf
 
 
aa5d8fe
860fadf
9d16a7f
860fadf
9d16a7f
860fadf
9d16a7f
 
 
aa5d8fe
 
 
 
2d765ca
aa5d8fe
 
2d765ca
aa5d8fe
 
 
 
 
 
f9dde88
 
 
 
 
 
 
 
aa5d8fe
 
 
 
 
 
 
 
 
 
 
0d2be35
 
 
f9dde88
 
 
0d2be35
aa5d8fe
bc461ab
 
aa5d8fe
 
 
 
2d765ca
aa5d8fe
 
 
 
 
 
2d765ca
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
from __future__ import annotations

import tempfile
import uuid
import httpx
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, List, Optional

from contextlib import asynccontextmanager

from fastapi import 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, QueueManager, CvTask

# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------

MAX_FILE_BYTES = 20 * 1024 * 1024  # 20 MB

# Magic byte signatures for MIME sniffing
_MIME_SIGS = {
    b"%PDF": ".pdf",
    b"PK\x03\x04": ".docx",  # DOCX (ZIP-based)
    b"\xd0\xcf\x11\xe0": ".doc",  # Legacy OLE compound (DOC, XLS)
}

_ALLOWED_EXT = (".pdf", ".docx", ".doc")


def _check_mime(file_bytes: bytes, declared_ext: str) -> bool:
    """Return True when magic bytes agree with the declared extension."""
    sig = file_bytes[:4]
    for magic, expected_ext in _MIME_SIGS.items():
        if sig.startswith(magic):
            # DOCX declared but is actually a ZIP: both .docx and (rarely) .doc
            if expected_ext == ".docx":
                return declared_ext in (".docx", ".doc")
            return declared_ext == expected_ext
    return True  # unknown signature β€” let the converter decide


# ---------------------------------------------------------------------------
# App setup
# ---------------------------------------------------------------------------

converter = CVConverter()
matcher = JobMatcher()  # SentenceTransformer loaded once at startup
cv_worker = CvWorker(converter, matcher)
queue_manager = QueueManager(cv_worker, concurrency=1)


@asynccontextmanager
async def lifespan(app: FastAPI):
    await queue_manager.start()
    yield
    await queue_manager.stop()


app = FastAPI(
    title="Job Processor API",
    description="CV parsing, chunking, and job-match prediction service.",
    version="3.0.0",
    lifespan=lifespan,
)


# ---------------------------------------------------------------------------
# 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, blocking β€” intentional during testing)
# ---------------------------------------------------------------------------


@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, awards)
    - Detected CV metadata (title, seniority, category, years of experience)
    - CV quality completeness_score (0–100)
    - section_embeddings  β€” pre-computed ML vectors for fast /match-cv reuse
    - File metadata (type, method, page count, warnings)
    - Per-phase timing (conversion_ms, chunking_ms, total_ms)
    """
    request_id = str(uuid.uuid4())

    if not file.filename:
        return APIResponse(message="No file uploaded", statusCode=400)

    ext = Path(file.filename).suffix.lower()
    if ext not in _ALLOWED_EXT:
        return APIResponse(
            message=f"Invalid file format. Allowed: {', '.join(_ALLOWED_EXT)}",
            statusCode=400,
        )

    tmp_path: Optional[Path] = None
    t_start = datetime.now(timezone.utc)

    try:
        file_bytes = await file.read()

        # P1 β€” file size guard
        if len(file_bytes) > MAX_FILE_BYTES:
            return APIResponse(
                message=f"File too large. Maximum size is {MAX_FILE_BYTES // (1024*1024)} MB.",
                statusCode=413,
            )

        # P4 β€” MIME sniff
        if not _check_mime(file_bytes, ext):
            return APIResponse(
                message="File content does not match the declared extension.",
                statusCode=400,
            )

        # Write temp file
        with tempfile.NamedTemporaryFile(delete=False, suffix=ext) as tmp:
            tmp.write(file_bytes)
            tmp_path = Path(tmp.name)

        # P7 β€” Conversion phase timer
        t_conv_start = datetime.now(timezone.utc)
        conversion = converter.convert(tmp_path)
        t_conv_end = datetime.now(timezone.utc)
        conversion_ms = int((t_conv_end - t_conv_start).total_seconds() * 1000)

        if not conversion.success:
            return APIResponse(
                message=conversion.error or "Conversion failed",
                statusCode=422,
            )

        # P7 β€” Chunking phase timer (includes ML embedding)
        t_chunk_start = datetime.now(timezone.utc)
        chunks = chunk_cv(conversion.markdown, embedder=matcher._embed)
        t_chunk_end = datetime.now(timezone.utc)
        chunking_ms = int((t_chunk_end - t_chunk_start).total_seconds() * 1000)

        t_end = datetime.now(timezone.utc)
        total_ms = int((t_end - t_start).total_seconds() * 1000)

        return APIResponse(
            message="CV processed successfully",
            statusCode=200,
            payload={
                "request_id": request_id,
                "markdown": conversion.markdown,
                "cv_title": chunks["cv_title"],
                "seniority": chunks["seniority"],
                "years_experience": chunks["years_experience"],
                "category": chunks["category"],
                "completeness_score": chunks["completeness_score"],
                "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"],
                },
                # Pre-computed ML section vectors β€” pass these to /match-cv or
                # /batch-match-cv to avoid re-encoding the CV on every match request.
                "section_embeddings": chunks.get("section_embeddings"),
                "file_type": conversion.file_type,
                "method_used": conversion.method_used,
                "is_scanned": conversion.is_scanned,
                "page_count": conversion.page_count,
                "warnings": conversion.warnings,
                "timing": {
                    "conversion_ms": conversion_ms,
                    "chunking_ms": chunking_ms,
                    "total_ms": total_ms,
                },
                "processed_at": t_end.isoformat(),
            },
        )

    except Exception as exc:
        return APIResponse(
            message=f"An error occurred during processing: {exc}",
            statusCode=500,
        )

    finally:
        # P3 β€” guaranteed temp file cleanup
        if tmp_path is not None:
            try:
                tmp_path.unlink(missing_ok=True)
            except Exception:
                pass


# ---------------------------------------------------------------------------
# POST /process-cv-async  (queued, used by Java async worker)
# ---------------------------------------------------------------------------


@app.post("/process-cv-async", response_model=APIResponse)
async def process_cv_async(
    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.
    Returns 202 immediately; processes the CV in a queued background task.
    """
    if not file.filename:
        return APIResponse(message="No file uploaded", statusCode=400)

    ext = Path(file.filename).suffix.lower()
    if ext not in _ALLOWED_EXT:
        return APIResponse(
            message=f"Invalid file format. Allowed: {', '.join(_ALLOWED_EXT)}",
            statusCode=400,
        )

    file_bytes = await file.read()

    # Size guard (async path)
    if len(file_bytes) > MAX_FILE_BYTES:
        return APIResponse(
            message=f"File too large. Maximum size is {MAX_FILE_BYTES // (1024*1024)} MB.",
            statusCode=413,
        )

    # MIME sniff (async path)
    if not _check_mime(file_bytes, ext):
        return APIResponse(
            message="File content does not match the declared extension.",
            statusCode=400,
        )

    filename = file.filename
    job_store.create_job(job_id)

    task = CvTask(
        job_id=job_id,
        file_bytes=file_bytes,
        filename=filename,
        callback_url=callback_url,
        callback_secret=callback_secret,
    )

    try:
        await queue_manager.enqueue(task)
    except ValueError as exc:
        return APIResponse(
            message=str(exc),
            statusCode=409,
            payload={
                "job_id": job_id,
                "status": job_store.get_job(job_id)["status"],
            },
        )

    return APIResponse(
        message="CV processing started",
        statusCode=202,
        payload={"job_id": job_id, "status": "QUEUED"},
    )


# ---------------------------------------------------------------------------
# GET /job-status/{job_id}
# ---------------------------------------------------------------------------


@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."""
    job = job_store.get_job(job_id)
    if job is None:
        return APIResponse(message="Job not found", statusCode=404)

    status = job["status"]
    if status == "QUEUED":
        pos = queue_manager.get_queue_position(job_id)
        status = f"QUEUE({pos})" if pos is not None else "QUEUE(1)"

    return APIResponse(
        message=f"Job status: {status}",
        statusCode=200,
        payload={"job_id": job_id, "status": status},
    )


# ---------------------------------------------------------------------------
# POST /batch-match-cv  (one CV vs. array of jobs β€” optimised)
# ---------------------------------------------------------------------------


class BatchMatchCVRequest(BaseModel):
    """Request body for POST /batch-match-cv."""

    jobs: List[JobInput] = Field(
        ...,
        min_length=1,
        max_length=100,
        description="Array of job postings (1–100).",
    )
    cv_markdown: str
    cv_title: str
    cv_years: int
    cv_seniority: str
    cv_skills_canonical: List[str]
    cv_skills_technical: List[str]
    cv_skills_soft: List[str]
    cv_category: str


@app.post("/batch-match-cv", response_model=APIResponse)
def batch_match_cv(payload: BatchMatchCVRequest):
    """
    Match one CV against an array of job postings in a single request.
    """
    try:
        results = matcher.predict_batch(
            jobs=[j.model_dump() for j in payload.jobs],
            cv_markdown=payload.cv_markdown,
            cv_title=payload.cv_title,
            cv_years=payload.cv_years,
            cv_seniority=payload.cv_seniority,
            cv_skills_canonical=payload.cv_skills_canonical,
            cv_skills_technical=payload.cv_skills_technical,
            cv_skills_soft=payload.cv_skills_soft,
            cv_category=payload.cv_category,
        )

        return APIResponse(
            message=f"Batch match completed: {len(results)} result(s)",
            statusCode=200,
            payload={
                "matches": results,
                "total": len(results),
            },
        )
    except Exception as exc:
        return APIResponse(
            message=f"Batch match error: {exc}",
            statusCode=500,
        )