Spaces:
Running on Zero

ats-engine / app /server.py
aseemlais's picture
fix(parser): support pre-extracted text streams for docx and pdf from MCP
7f2d2d6
Raw History Blame Contribute Delete
45.1 kB
import os import sys import io import json import hmac import logging import collections import time import zipfile import threading from contextlib import asynccontextmanager from pathlib import Path from typing import List, Dict, Any, Optional, Tuple import uvicorn from fastapi import FastAPI, UploadFile, File, Form, Request, HTTPException, Query from pydantic import BaseModel from app.services.embedding_service import EmbeddingUnavailableError from fastapi.responses import JSONResponse, FileResponse, HTMLResponse from fastapi.staticfiles import StaticFiles from fastapi.middleware.cors import CORSMiddleware # Ensure ATS module importable ROOT_DIR = Path(__file__).resolve().parent.parent if str(ROOT_DIR) not in sys.path: sys.path.insert(0, str(ROOT_DIR)) from app.adapters.screening_adapter import ATSScreeningAdapter from app.services.resume_parser import ResumeParserService from app.services.structured_extractor import StructuredResumeExtractor from app.services.extraction_service import ExtractionService from app.adapters.extraction_adapter import ExtractionAdapter from app.services.mcp_client import mcp_client_service from app.storage.supabase_client import is_supabase_configured, get_missing_supabase_env_vars from app.storage.resume_storage import store_resume, ResumePersistenceError, StorageError from app.storage.candidate_repository import ( list_candidates, search_candidates, get_candidate, get_resume_download_url, delete_candidate, CandidateNotFoundError, RepositoryUnavailableError, PartialDeletionError, DatabaseError, DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE, ) logger = logging.getLogger("ats_server") logging.basicConfig(level=logging.INFO) # --------------------------------------------------------------------------- # Security & Rate Limiting Constants # --------------------------------------------------------------------------- MAX_UPLOAD_SIZE_BYTES = int(os.getenv("MAX_UPLOAD_SIZE_BYTES", str(5 * 1024 * 1024))) # 5 MB MAX_PAGE_COUNT = int(os.getenv("MAX_PAGE_COUNT", "15")) # 15 pages MAX_DOCX_UNCOMPRESSED_BYTES = int(os.getenv("MAX_DOCX_UNCOMPRESSED_BYTES", str(20 * 1024 * 1024))) # 20 MB # Global safety-net caps; per-user rate limiting is the Node layer's job. RATE_LIMIT_GLOBAL_EXTRACT_MAX = int(os.getenv("RATE_LIMIT_GLOBAL_EXTRACT_MAX", "120")) # 120 / min RATE_LIMIT_GLOBAL_JOBS_MAX = int(os.getenv("RATE_LIMIT_GLOBAL_JOBS_MAX", "600")) # 600 / min _INTERNAL_SECRET_ENV = "ATS_INTERNAL_SECRET" def is_production_mode() -> bool: """Detects whether server is running in production mode.""" env = os.getenv("ENVIRONMENT", "").lower() is_prod_flag = os.getenv("PRODUCTION", "").lower() in ("true", "1") is_hf_space = bool(os.getenv("SPACE_ID")) return env in ("production", "prod") or is_prod_flag or is_hf_space _rate_limit_records: Dict[str, list] = collections.defaultdict(list) _rate_limit_lock = threading.Lock() def check_rate_limit(key: str, max_requests: int, window_seconds: int = 60) -> bool: """Global sliding-window rate limiter with timestamp eviction. Thread-safe.""" now = time.time() with _rate_limit_lock: timestamps = _rate_limit_records[key] # Evict stale entries _rate_limit_records[key] = [t for t in timestamps if now - t < window_seconds] if len(_rate_limit_records[key]) >= max_requests: return False _rate_limit_records[key].append(now) return True def verify_internal_secret(request: Request) -> None: """ Validates the X-ATS-Internal-Secret header using constant-time compare. - In production mode, rejects with 401 if ATS_INTERNAL_SECRET is unset. - If ATS_INTERNAL_SECRET is configured, requires matching header. - In non-production mode with unset secret, allows request for local dev/testing. Raises HTTPException(401) on failure. """ configured = os.environ.get(_INTERNAL_SECRET_ENV, "").strip() if not configured: if is_production_mode(): raise HTTPException( status_code=401, detail={ "error": "Internal secret not configured. Set ATS_INTERNAL_SECRET on the HF Space.", "header": "X-ATS-Internal-Secret", }, ) return # skip in non-production when secret is unset provided = request.headers.get("X-ATS-Internal-Secret", "") if not hmac.compare_digest(provided, configured): raise HTTPException( status_code=401, detail={"error": "Invalid or missing X-ATS-Internal-Secret header."}, ) def check_lfs_assets_status() -> Tuple[bool, Dict[str, int]]: """Checks file sizes of required ML/DB assets to distinguish real binaries from LFS text pointers.""" asset_files = [ ROOT_DIR / "data" / "ats_metadata.db", ROOT_DIR / "data" / "bm25_index.pkl", ROOT_DIR / "data" / "xgb_ranker.joblib", ] sizes = {} all_ok = True for f in asset_files: if f.exists(): sz = os.path.getsize(f) sizes[f.name] = sz if sz <= 1000: # LFS text pointer is ~130 bytes all_ok = False else: sizes[f.name] = 0 all_ok = False return all_ok, sizes def validate_uploaded_file(content: bytes, filename: str) -> None: """Enforces size limits, extension matching, magic bytes, and page caps.""" if len(content) > MAX_UPLOAD_SIZE_BYTES: raise HTTPException( status_code=413, detail=f"File exceeds maximum allowed size ({MAX_UPLOAD_SIZE_BYTES // (1024 * 1024)}MB).", ) ext = Path(filename).suffix.lower() if ext == ".pdf": if not content.startswith(b"%PDF-"): raise HTTPException(status_code=400, detail="Corrupted or invalid PDF magic bytes.") try: import fitz doc = fitz.open(stream=content, filetype="pdf") if doc.page_count > MAX_PAGE_COUNT: raise HTTPException( status_code=400, detail=f"PDF exceeds maximum allowed length of {MAX_PAGE_COUNT} pages (received {doc.page_count}).", ) except HTTPException: raise except Exception as e: raise HTTPException(status_code=400, detail=f"Unreadable PDF document: {e}") elif ext == ".docx": if not content.startswith(b"PK\x03\x04"): raise HTTPException(status_code=400, detail="Corrupted or invalid DOCX magic bytes.") try: with zipfile.ZipFile(io.BytesIO(content)) as zf: # 1. Must contain word/document.xml — otherwise it's not a valid DOCX member_names = {info.filename for info in zf.infolist()} if "word/document.xml" not in member_names: raise HTTPException( status_code=400, detail="Invalid DOCX file: missing word/document.xml (not a Word document).", ) # 2. Cap total uncompressed size to guard against zip-bomb total_uncompressed = sum(info.file_size for info in zf.infolist()) if total_uncompressed > MAX_DOCX_UNCOMPRESSED_BYTES: raise HTTPException( status_code=400, detail=( f"DOCX uncompressed content exceeds maximum allowed size " f"({MAX_DOCX_UNCOMPRESSED_BYTES // (1024 * 1024)}MB)." ), ) except HTTPException: raise except zipfile.BadZipFile: raise HTTPException(status_code=400, detail="Corrupted DOCX file: could not open as ZIP archive.") except Exception as exc: raise HTTPException(status_code=400, detail=f"Unreadable DOCX document: {exc}") elif ext == ".txt": try: decoded = content.decode("utf-8") if "\x00" in decoded: raise HTTPException(status_code=400, detail="Invalid text file: binary NUL byte detected.") except UnicodeDecodeError: raise HTTPException(status_code=400, detail="Invalid text file: cannot decode as UTF-8.") else: raise HTTPException(status_code=400, detail="Unsupported file format. Please upload PDF, DOCX, or TXT.") # Reference client build path REF_CLIENT_DIST = Path(r"C:\Users\LENOVO\Downloads\Resume Screening and Shortlisting agent\Resume Screening and Shortlisting agent\e2e-chatbot-app-next\client\dist") adapter = ATSScreeningAdapter() parser = ResumeParserService() structured_extractor = StructuredResumeExtractor(nlp_extractor=adapter.nlp_extractor) extraction_service = ExtractionService(fallback_extractor=structured_extractor) extraction_adapter = ExtractionAdapter( extraction_service=extraction_service, legacy_extractor=structured_extractor, ) @asynccontextmanager async def lifespan(app: FastAPI): """Lifespan context manager for FastAPI startup and shutdown.""" logger.info("[Server] Lifespan startup: Starting ExtractionService...") assets_ok, asset_sizes = check_lfs_assets_status() logger.info("[Server] LFS assets verification on boot: assets_ok=%s, sizes=%s", assets_ok, asset_sizes) try: await extraction_service.start() logger.info("[Server] ExtractionService started successfully.") except Exception as exc: logger.error("[Server] ExtractionService failed to start during lifespan startup: %s", exc, exc_info=True) yield logger.info("[Server] Lifespan shutdown: Stopping ExtractionService...") try: await extraction_service.stop() logger.info("[Server] ExtractionService stopped successfully.") except Exception as exc: logger.error("[Server] ExtractionService failed to stop during lifespan shutdown: %s", exc, exc_info=True) app = FastAPI( title="Hybrid Semantic ATS - Reference UI Server", version="1.0.0", lifespan=lifespan, ) # Enable CORS restricted to configured origins allowed_origins_env = os.getenv("ALLOWED_ORIGINS") if allowed_origins_env: origins = [o.strip() for o in allowed_origins_env.split(",") if o.strip()] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) else: origin_regex = os.getenv( "ALLOWED_ORIGIN_REGEX", r"^https?://(localhost|127\.0\.0\.1)(:\d+)?$|^https://.*\.onrender\.com$|^https://.*\.hf\.space$", ) app.add_middleware( CORSMiddleware, allow_origin_regex=origin_regex, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @app.get("/") def root(): return { "status": "healthy", "service": "Hybrid Semantic ATS Engine", "docs": "/docs", "health": "/health" } @app.get("/health") async def health(): if not extraction_service.running or not extraction_service.is_model_loaded: await extraction_service.ensure_worker() assets_ok, _ = check_lfs_assets_status() rss_mb = extraction_service.get_current_rss_mb() is_loading = ( extraction_service.model_loader_task is not None and not extraction_service.model_loader_task.done() ) return { "status": "healthy", "service": "Hybrid Semantic ATS", "assets_ok": assets_ok, "model_loaded": extraction_service.is_model_loaded, "model_loading": is_loading, "shadow_enabled": extraction_service.is_shadow_mode_active, "queue_depth": extraction_service.queue_depth, "rss_mb": round(rss_mb, 2), "cutover_percentage": extraction_service.current_cutover_percentage, } @app.get("/api/session") async def get_session(request: Request): """ Session endpoint required by SessionContext.tsx. Detects Databricks auth headers when running on Databricks Apps, or returns an authenticated local reviewer session for browser access. """ user_email = ( request.headers.get("X-Forwarded-Email") or request.headers.get("X-Forwarded-User") or request.headers.get("X-Forwarded-Preferred-Username") or "reviewer@ats-workspace.local" ) user_name = ( request.headers.get("X-Forwarded-Preferred-Username") or request.headers.get("X-Forwarded-User") or "ATS Reviewer" ) return { "user": { "email": user_email, "name": user_name, "preferredUsername": user_name, } } @app.get("/api/config") async def get_config(): """ Configuration endpoint required by AppConfigContext.tsx. """ return { "features": { "chatHistory": False, "feedback": False, }, "greeting": "Hybrid Semantic ATS Candidate Screening", } def process_resume_upload( filename: str, content: bytes, content_type: str = "application/pdf" ) -> Dict[str, Any] | JSONResponse: """ Core resume ingestion logic: 1. Parses resume text from PDF, DOCX, or TXT. 2. If Supabase is configured, extracts structured candidate details and persists both original file and metadata with SHA-256 duplicate detection. """ suffix = Path(filename).suffix.lower() if suffix not in (".pdf", ".docx", ".txt"): return JSONResponse( status_code=400, content={"error": "Please upload a PDF, DOCX, or TXT resume."} ) # Save to temp location temp_dir = ROOT_DIR / "data" / "temp_uploads" temp_dir.mkdir(parents=True, exist_ok=True) temp_path = temp_dir / filename with open(temp_path, "wb") as f: f.write(content) try: ok, raw_text, cleaned_text, file_hash, err = parser.parse_file(temp_path) if not ok or not (cleaned_text or raw_text): # Check if content is already pre-extracted text (e.g. from MCP read_file tool) try: decoded = content.decode("utf-8", errors="ignore") if decoded and len(decoded.strip()) > 20: import ftfy from app.utils.text_cleaner import clean_text raw_text = ftfy.fix_text(decoded) cleaned_text = clean_text(raw_text) file_hash = hashlib.sha256(content).hexdigest() ok = True except Exception: pass if not ok or not (cleaned_text or raw_text): return JSONResponse( status_code=400, content={"error": err or "The resume was uploaded, but no readable text could be extracted."} ) text_to_return = cleaned_text or raw_text response_payload = { "success": True, "pathname": filename, "contentType": content_type, "resumeText": text_to_return } # Persistent storage integration if is_supabase_configured(): try: # Structured extraction using the feature-flagged adapter (SLM if enabled, with safe fallback) extracted = extraction_adapter.extract( raw_text=raw_text or cleaned_text, cleaned_text=cleaned_text or raw_text ) candidate_name = extracted.get("candidateName") or "Unknown" candidate_role = extracted.get("jobTitle") or "Role not identified" email = extracted.get("email") # strictly valid email or None (no em-dashes or blank strings) skills = extracted.get("skills") # Fallback to deterministic NLP skills if empty if not skills: parsed_cand = adapter.nlp_extractor.extract_structured( candidate_id="temp_upload", source_file=filename, file_hash=file_hash, raw_text=raw_text or cleaned_text, cleaned_text=cleaned_text or raw_text ) skills = parsed_cand.skills current_ver = ( extraction_service.current_extractor_version if extraction_service else "ats-slm:qwen2.5-1.5b-instruct:chatml-v1:schema-v1" ) storage_res = store_resume( file_bytes=content, filename=filename, file_hash=file_hash, candidate_name=candidate_name, email=email, resume_text=text_to_return, skills=skills or [], job_role=candidate_role, content_type=content_type or "application/pdf", extracted_data=extracted, extractor_version=current_ver, extraction_source=extracted.get("extractionSource", "legacy"), ) response_payload.update({ "persistenceStatus": storage_res.get("persistenceStatus", "persisted"), "candidateId": storage_res.get("candidateId"), "isDuplicate": storage_res.get("isDuplicate", False), "storageObjectPath": storage_res.get("storageObjectPath"), "candidateName": storage_res.get("candidateName"), "jobRole": storage_res.get("jobRole"), "extractedData": extracted, "extractorVersion": current_ver, "extractionSource": extracted.get("extractionSource", "legacy"), }) except Exception as store_err: logger.error( f"[Storage] Failed to persist resume '{filename}' (hash: {file_hash[:12]}...): {store_err}", exc_info=True, ) return JSONResponse( status_code=500, content={ "success": False, "error": f"Failed to persist resume in Supabase: {str(store_err)}", "persistenceStatus": "failed", "pathname": filename, } ) else: missing_vars = get_missing_supabase_env_vars() logger.warning( "[Storage] Supabase persistent storage is not configured (missing: %s). Operating in temporary in-memory mode.", ", ".join(missing_vars) if missing_vars else "unknown", ) response_payload.update({ "persistenceStatus": "temporary_in_memory", "candidateId": None, "isDuplicate": False, "storageObjectPath": None, "persistenceNotice": f"Resume processed in temporary in-memory mode. Missing configuration: {', '.join(missing_vars)}.", }) return response_payload finally: if temp_path.exists(): temp_path.unlink() @app.post("/api/files/upload") async def upload_resume_file(file: UploadFile = File(...)): """ Implements the exact /api/files/upload endpoint expected by NewChatPage.tsx. Extracts text from PDF, DOCX, and TXT using our layout-aware ATS ResumeParserService. If Supabase is configured, persists the resume file in Supabase Storage and candidate metadata in Supabase Postgres with SHA-256 duplicate detection. """ filename = file.filename or "uploaded_resume.pdf" content = await file.read() return process_resume_upload(filename, content, file.content_type or "application/pdf") # ============================================================================= # SharePoint / Microsoft 365 MCP Ingestion Routes # ============================================================================= class SharePointImportPayload(BaseModel): paths: List[str] class SharePointFetchPayload(BaseModel): sharePointLink: str @app.get("/api/sharepoint/status") async def sharepoint_status(): """Returns current MCP connection status and mode (mock vs live).""" provider = mcp_client_service.get_provider() identity = await provider.whoami() return { "status": "ok", "mock_mode": mcp_client_service.is_mock_mode, "mcp_url": getattr(provider, "mcp_url", "https://mcp-resource.onrender.com/mcp"), "identity": identity, } @app.get("/api/sharepoint/folders") async def sharepoint_folders(path: str = Query("", description="Folder path in SharePoint")): """ Lists files and subfolders from SharePoint via MCP provider. Supports directory navigation, parent path backtracking, and item metadata. """ provider = mcp_client_service.get_provider() try: folder_res = await provider.list_folder(path) return folder_res.to_dict() except Exception as exc: logger.error(f"[SharePoint] Failed to list folder '{path}': {exc}") raise HTTPException(status_code=500, detail=f"Failed to list SharePoint folder: {exc}") @app.post("/api/sharepoint/import") async def sharepoint_import(payload: SharePointImportPayload): """ Imports a batch of selected resume files from SharePoint via MCP provider. Streams each file's binary content directly into ResumeParserService and Supabase. """ if not payload.paths: raise HTTPException(status_code=400, detail="No file paths provided for import.") provider = mcp_client_service.get_provider() results = [] successful = 0 failed = 0 for item_path in payload.paths: try: filename, content, mime_type = await provider.get_file_content(item_path) res = process_resume_upload(filename, content, mime_type) if isinstance(res, JSONResponse): body = json.loads(res.body.decode("utf-8")) if hasattr(res, "body") else {} failed += 1 results.append({ "path": item_path, "filename": filename, "success": False, "error": body.get("error", "Failed to parse resume."), }) else: successful += 1 results.append({ "path": item_path, "filename": filename, "success": True, "candidateId": res.get("candidateId"), "candidateName": res.get("candidateName"), "jobRole": res.get("jobRole"), "resumeText": res.get("resumeText"), "isDuplicate": res.get("isDuplicate", False), "persistenceStatus": res.get("persistenceStatus", "persisted"), "storageObjectPath": res.get("storageObjectPath"), }) except Exception as exc: logger.error(f"[SharePoint] Failed importing file {item_path}: {exc}") failed += 1 results.append({ "path": item_path, "filename": Path(item_path).name, "success": False, "error": str(exc), }) return { "total": len(payload.paths), "successful": successful, "failed": failed, "items": results, } @app.post("/api/sharepoint/fetch-resumes") async def sharepoint_fetch_resumes(payload: SharePointFetchPayload): """ Backwards-compatible endpoint for existing SharePoint folder link input in NewChatPage. Scans the targeted folder, fetches all resumes, and returns structured resume objects. """ provider = mcp_client_service.get_provider() raw_link = payload.sharePointLink.strip() # Extract target folder path if specified in link target_path = "" # Check for Canada / Repository role folders in link from app.services.mcp_client import CANADA_REPOSITORY_ROLES for role in CANADA_REPOSITORY_ROLES: if role.lower() in raw_link.lower(): target_path = f"Repository/{role}" break if not target_path and "repository" in raw_link.lower(): target_path = "Repository/AI Engineer" try: folder_res = await provider.list_folder(target_path) file_items = [ it for it in folder_res.items if it.item_type == "file" and it.extension in (".pdf", ".docx", ".txt", "") ] resumes = [] for it in file_items: try: fn, content, mime = await provider.get_file_content(it.path) res = process_resume_upload(fn, content, mime) if not isinstance(res, JSONResponse): resumes.append({ "fileName": fn, "resumeText": res.get("resumeText", ""), "candidateId": res.get("candidateId"), "candidateName": res.get("candidateName"), "jobRole": res.get("jobRole"), }) except Exception as item_err: logger.warning(f"[SharePoint] Skipping file {it.path}: {item_err}") return {"resumes": resumes, "count": len(resumes)} except Exception as exc: logger.error(f"[SharePoint] Error fetching resumes from {raw_link}: {exc}") raise HTTPException(status_code=500, detail=str(exc)) @app.get("/api/mcp/callback") async def mcp_oauth_callback(code: Optional[str] = None, state: Optional[str] = None, error: Optional[str] = None): """ OAuth redirect callback endpoint for Microsoft sign-in via Resource MCP. """ if error: return HTMLResponse( f"<html><body style='font-family:sans-serif;padding:40px;text-align:center;'>" f"<h2 style='color:#b91c1c;'>Microsoft Authentication Failed</h2>" f"<p>{error}</p>" f"</body></html>", status_code=400, ) return HTMLResponse( "<html><body style='font-family:sans-serif;padding:40px;text-align:center;background:#f8fafc;'>" "<div style='max-width:480px;margin:auto;padding:30px;background:#fff;border-radius:12px;box-shadow:0 4px 12px rgba(0,0,0,0.08);'>" "<h2 style='color:#033c67;'>Authentication Successful!</h2>" "<p style='color:#64748b;font-size:14px;'>Your session with the Resource MCP has been verified.</p>" "<p style='color:#033c67;font-weight:600;'>You may now close this tab and return to the ATS application.</p>" "</div>" "<script>" "if (window.opener) {" " window.opener.postMessage({ type: 'MCP_AUTH_SUCCESS', code: '" + (code or "") + "' }, '*');" "}" "</script>" "</body></html>" ) # ============================================================================= # Batch 2: Candidate Repository API # ============================================================================= def _supabase_required(): """Return 503 JSON if Supabase is not configured.""" if not is_supabase_configured(): missing = get_missing_supabase_env_vars() raise HTTPException( status_code=503, detail={ "error": "Candidate repository is unavailable: Supabase not configured.", "missingConfig": missing, }, ) def _require_delete_auth(request: Request) -> None: """ Guard for destructive (DELETE) endpoints. Checks the `Authorization: Bearer <token>` header against the `ATS_ADMIN_TOKEN` environment variable on the backend. Security model: - ATS_ADMIN_TOKEN must be set as a secret env var on the HF Space backend. - The Render Node.js proxy should forward the token in an `Authorization: Bearer` header when calling DELETE /api/candidates/{id}. - If ATS_ADMIN_TOKEN is not set, the endpoint is disabled (503) to prevent unauthenticated destructive access in any deployment. - CORS and the Supabase service-role key are NOT used as user auth. - This token protects the Python backend's direct URL; the Node.js frontend's own authMiddleware provides a separate layer on the proxy side. Frontend configuration required (Render env or Node proxy): Forward the header: Authorization: Bearer <ATS_ADMIN_TOKEN value> Env var name on HF Space: ATS_ADMIN_TOKEN """ configured_token = os.environ.get("ATS_ADMIN_TOKEN", "").strip() if not configured_token: raise HTTPException( status_code=503, detail={ "error": "Destructive operations are disabled: ATS_ADMIN_TOKEN is not configured on this deployment.", "action": "Set ATS_ADMIN_TOKEN as a secret environment variable on the backend to enable candidate deletion.", }, ) auth_header = request.headers.get("Authorization", "") if not auth_header.startswith("Bearer "): raise HTTPException( status_code=401, detail={"error": "Authorization header with Bearer token is required for this operation."}, ) provided_token = auth_header[len("Bearer "):] # Constant-time comparison to prevent timing attacks import hmac if not hmac.compare_digest(provided_token, configured_token): raise HTTPException( status_code=403, detail={"error": "Invalid admin token."}, ) @app.get("/api/candidates") async def list_candidates_endpoint( limit: int = Query(default=DEFAULT_PAGE_SIZE, ge=1, le=MAX_PAGE_SIZE), offset: int = Query(default=0, ge=0), ): """ List stored candidates with pagination, sorted by newest first. Does not return full resume text or internal credentials. """ _supabase_required() try: result = list_candidates(limit=limit, offset=offset) return result except RepositoryUnavailableError as exc: raise HTTPException(status_code=503, detail=str(exc)) except DatabaseError as exc: logger.error("[API] list_candidates error: %s", exc) raise HTTPException(status_code=500, detail="Failed to retrieve candidates.") @app.get("/api/candidates/search") async def search_candidates_endpoint( q: str = Query(default="", description="Search query (name, email, skills, job role)"), limit: int = Query(default=DEFAULT_PAGE_SIZE, ge=1, le=MAX_PAGE_SIZE), offset: int = Query(default=0, ge=0), ): """ Case-insensitive search across candidateName, email, jobRole, and skills. Returns paginated results. Empty query returns all candidates (same as list). """ _supabase_required() try: result = search_candidates(query=q, limit=limit, offset=offset) return result except RepositoryUnavailableError as exc: raise HTTPException(status_code=503, detail=str(exc)) except DatabaseError as exc: logger.error("[API] search_candidates error (q=%r): %s", q, exc) raise HTTPException(status_code=500, detail="Search failed.") @app.get("/api/candidates/{candidate_id}") async def get_candidate_endpoint( candidate_id: str, include_resume_text: bool = Query(default=False), ): """ Retrieve a single candidate's metadata by UUID. Set include_resume_text=true to also return the full extracted resume text. """ _supabase_required() try: candidate = get_candidate(candidate_id, include_resume_text=include_resume_text) return candidate except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) except CandidateNotFoundError: raise HTTPException(status_code=404, detail=f"Candidate '{candidate_id}' not found.") except RepositoryUnavailableError as exc: raise HTTPException(status_code=503, detail=str(exc)) except DatabaseError as exc: logger.error("[API] get_candidate(%s) error: %s", candidate_id, exc) raise HTTPException(status_code=500, detail="Failed to retrieve candidate.") @app.get("/api/candidates/{candidate_id}/download") async def get_candidate_download_url_endpoint(candidate_id: str): """ Generate a short-lived signed URL (5 min TTL) for the candidate's resume file. The service-role key is never exposed; permanent public links are not issued. """ _supabase_required() try: url = get_resume_download_url(candidate_id) return {"signedUrl": url, "expiresInSeconds": 300} except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) except CandidateNotFoundError: raise HTTPException(status_code=404, detail=f"Candidate '{candidate_id}' not found.") except RepositoryUnavailableError as exc: raise HTTPException(status_code=503, detail=str(exc)) except Exception as exc: logger.error("[API] get_candidate_download_url(%s) error: %s", candidate_id, exc) raise HTTPException(status_code=500, detail="Failed to generate download URL.") @app.delete("/api/candidates/{candidate_id}") async def delete_candidate_endpoint(candidate_id: str, request: Request): """ Delete a candidate's storage file and metadata record. Authorization: requires `Authorization: Bearer <ATS_ADMIN_TOKEN>` header. ATS_ADMIN_TOKEN must be set as a secret env var on the HF Space backend. Deletion order: 1. Storage object is deleted first. - If Storage deletion fails, returns 409 with the error; the DB row is untouched and the operation is safe to retry. - If the Storage object is already absent, deletion proceeds normally. 2. DB row is deleted after Storage succeeds. - If DB deletion fails after Storage was removed, returns 207 (partial failure) with enough detail to identify and clean up the orphaned row. 3. ExtractionJobs rows for this candidate's fileHash are cleaned up. - Failures here are non-fatal and logged; the main deletion result is returned. """ _require_delete_auth(request) _supabase_required() try: # First, resolve fileHash before deleting — needed for cascade cleanup file_hash: Optional[str] = None try: candidate_detail = get_candidate(candidate_id, include_resume_text=False) file_hash = candidate_detail.get("fileHash") except Exception: pass # Non-fatal; we still attempt deletion result = delete_candidate(candidate_id) # Cascade: delete ExtractionJobs rows and clear extractedData for the same fileHash if file_hash and is_supabase_configured(): from app.storage.supabase_client import get_supabase_client from app.storage.resume_storage import _get_table_ref as _storage_table_ref try: from app.storage.candidate_repository import _get_table_ref as _repo_table_ref client = get_supabase_client() if client: # Delete all ExtractionJobs for this fileHash _repo_table_ref(client, "ExtractionJobs").delete().eq("fileHash", file_hash).execute() logger.info("[API] Deleted ExtractionJobs for fileHash %s (candidate %s)", file_hash[:12], candidate_id) # Clear extractedData + extractorVersion on CandidateResume (may be absent after delete) # Swallow 404-equivalent; the row was just deleted _repo_table_ref(client, "CandidateResume").update({ "extractedData": None, "extractorVersion": None, }).eq("fileHash", file_hash).execute() except Exception as cascade_err: logger.warning( "[API] Cascade cleanup failed for fileHash %s (candidate %s): %s", file_hash[:12] if file_hash else "?", candidate_id, cascade_err, ) return result except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) except CandidateNotFoundError: raise HTTPException(status_code=404, detail=f"Candidate '{candidate_id}' not found.") except RepositoryUnavailableError as exc: raise HTTPException(status_code=503, detail=str(exc)) except PartialDeletionError as exc: # Storage was deleted but DB row could not be removed. # Return 207 Multi-Status so the caller knows the state precisely. logger.error("[API] Partial deletion for candidate %s: %s", candidate_id, exc) return JSONResponse( status_code=207, content={ "deleted": False, "partialFailure": True, "candidateId": candidate_id, "storageDeleted": True, "storageAlreadyAbsent": False, "dbRowDeleted": False, "storageObjectPath": exc.storage_object_path, "error": ( "Storage file was deleted but the database row could not be removed. " "Retry the DELETE request; the storage step will be skipped automatically." ), }, ) except StorageError as exc: # Storage deletion failed — DB row is intact, operation is safe to retry. logger.error("[API] Storage deletion failed for candidate %s: %s", candidate_id, exc) raise HTTPException( status_code=409, detail={ "error": "Could not delete the resume file from storage. The candidate record is intact and the operation is safe to retry.", "detail": str(exc), }, ) except DatabaseError as exc: logger.error("[API] delete_candidate(%s) DB error: %s", candidate_id, exc) raise HTTPException(status_code=500, detail="Failed to delete candidate record.") @app.post("/extract") async def extract_resume_endpoint( request: Request, file: UploadFile = File(...), ): """ Submits a resume file for async structured extraction: - Requires X-ATS-Internal-Secret header (set via env var on HF Space) - Enforces global rate limiting (env-configurable, default 120 req/min) - Validates file size cap (5MB) and magic bytes (PDF, DOCX, TXT) and page cap (15 pages) - Returns 200 (cache hit with full extracted schema) or 202 (queued/deduplicated) or 429 (queue full/rate limit) - Never exposes internal storageObjectPath """ # 1. Internal secret authentication (Node proxy must forward X-ATS-Internal-Secret) verify_internal_secret(request) # 2. Global Rate Limiting (safety net; per-user limiting is Node layer's job) if not check_rate_limit("global:extract", max_requests=RATE_LIMIT_GLOBAL_EXTRACT_MAX, window_seconds=60): raise HTTPException(status_code=429, detail="Rate limit exceeded for resume upload. Please slow down.") try: content = await file.read() if not content: raise HTTPException(status_code=400, detail="Uploaded file is empty.") filename = file.filename or "uploaded_resume.pdf" # 3. File Validation (magic bytes, size, page cap, DOCX zip-bomb) validate_uploaded_file(content, filename) status_code, response_data = await extraction_service.submit_job( file_bytes=content, filename=filename, content_type=file.content_type or "application/pdf", ) return JSONResponse(status_code=status_code, content=response_data) except HTTPException: raise except Exception as exc: logger.error("[API] /extract error: %s", exc, exc_info=True) raise HTTPException(status_code=500, detail=f"Failed to submit extraction job: {str(exc)}") @app.get("/jobs/{job_id}") async def get_job_status_endpoint(job_id: str, request: Request): """ Polls the status of an asynchronous resume extraction job. - Requires X-ATS-Internal-Secret header - Enforces global rate limiting (default 600 req/min) - Returns: status ('pending', 'processing', 'completed', 'failed') and result payload when complete. - Never exposes internal storageObjectPath """ verify_internal_secret(request) if not check_rate_limit("global:jobs", max_requests=RATE_LIMIT_GLOBAL_JOBS_MAX, window_seconds=60): raise HTTPException(status_code=429, detail="Rate limit exceeded for job polling. Please slow down.") job = extraction_service.get_job(job_id) if not job: raise HTTPException(status_code=404, detail="Job not found.") res_payload = job.get("result") if res_payload and isinstance(res_payload, dict): res_payload = dict(res_payload) res_payload.pop("storageObjectPath", None) return { "job_id": job["id"], "status": job["status"], "extractionSource": job.get("extractionSource"), "result": res_payload, "error": job.get("error"), "created_at": job.get("created_at"), "updated_at": job.get("updated_at"), } @app.post("/invocations") async def invocations_endpoint(request: Request): """ Implements MLflow's ResponsesAgent / OpenAI Responses API /invocations endpoint. Consumes requests from NewChatPage.tsx (callAgent) and executes the deterministic ATS. """ body = await request.json() messages = body.get("input", []) if not messages: return JSONResponse( status_code=400, content={"error": "Empty input messages in request."} ) # Get last user prompt user_prompt = "" for msg in reversed(messages): if msg.get("role") == "user": content = msg.get("content") if isinstance(content, str): user_prompt = content break elif isinstance(content, list): parts = [p.get("text", "") for p in content if isinstance(p, dict)] user_prompt = " ".join(parts).strip() break if not user_prompt: user_prompt = str(messages[-1]) # Check if this is an interview question generation request if "interview questions" in user_prompt.lower(): parsed_input = adapter.parse_screening_prompt(user_prompt) result_dict = adapter.generate_interview_questions( job_title=parsed_input["job_title"], job_description=parsed_input["job_description"], resume_text=parsed_input["resume_text"] ) final_text = json.dumps(result_dict) else: # Standard candidate screening request parsed_input = adapter.parse_screening_prompt(user_prompt) try: result_dict = adapter.evaluate_candidate( job_title=parsed_input["job_title"], job_description=parsed_input["job_description"], resume_text=parsed_input["resume_text"] ) except EmbeddingUnavailableError as e: # explicit failure instead of a fabricated semantic score (set ALLOW_DEGRADED_SEMANTIC=true to opt in) raise HTTPException(status_code=503, detail=str(e)) final_text = json.dumps(result_dict) # Return standard MLflow ResponsesAgent response format return { "output": [ { "type": "message", "role": "assistant", "content": [ { "type": "output_text", "text": final_text } ] } ], "output_text": final_text, "text": final_text } # Mount static files from reference client build if available try: client_dist_exists = REF_CLIENT_DIST.exists() except Exception: client_dist_exists = False if client_dist_exists: app.mount("/assets", StaticFiles(directory=str(REF_CLIENT_DIST / "assets")), name="assets") @app.get("/{full_path:path}") async def serve_spa(full_path: str): target = REF_CLIENT_DIST / full_path no_cache_headers = { "Cache-Control": "no-cache, no-store, must-revalidate", "Pragma": "no-cache", "Expires": "0" } if target.is_file(): return FileResponse(target, headers=no_cache_headers) index_file = REF_CLIENT_DIST / "index.html" if index_file.exists(): return FileResponse(index_file, headers=no_cache_headers) raise HTTPException(status_code=404, detail="File not found") def main(): port = int(os.environ.get("PORT", "8000")) uvicorn.run("app.server:app", host="0.0.0.0", port=port, reload=False) if __name__ == "__main__": main()
import os
import sys
import io
import json
import hmac
import logging
import collections
import time
import zipfile
import threading
from contextlib import asynccontextmanager
from pathlib import Path
from typing import List, Dict, Any, Optional, Tuple
import uvicorn
from fastapi import FastAPI, UploadFile, File, Form, Request, HTTPException, Query
from pydantic import BaseModel
from app.services.embedding_service import EmbeddingUnavailableError
from fastapi.responses import JSONResponse, FileResponse, HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
# Ensure ATS module importable
ROOT_DIR = Path(__file__).resolve().parent.parent
if str(ROOT_DIR) not in sys.path:
sys.path.insert(0, str(ROOT_DIR))
from app.adapters.screening_adapter import ATSScreeningAdapter
from app.services.resume_parser import ResumeParserService
from app.services.structured_extractor import StructuredResumeExtractor
from app.services.extraction_service import ExtractionService
from app.adapters.extraction_adapter import ExtractionAdapter
from app.services.mcp_client import mcp_client_service
from app.storage.supabase_client import is_supabase_configured, get_missing_supabase_env_vars
from app.storage.resume_storage import store_resume, ResumePersistenceError, StorageError
from app.storage.candidate_repository import (
list_candidates,
search_candidates,
get_candidate,
get_resume_download_url,
delete_candidate,
CandidateNotFoundError,
RepositoryUnavailableError,
PartialDeletionError,
DatabaseError,
DEFAULT_PAGE_SIZE,
MAX_PAGE_SIZE,
)
logger = logging.getLogger("ats_server")
logging.basicConfig(level=logging.INFO)
# ---------------------------------------------------------------------------
# Security & Rate Limiting Constants
# ---------------------------------------------------------------------------
MAX_UPLOAD_SIZE_BYTES = int(os.getenv("MAX_UPLOAD_SIZE_BYTES", str(5 * 1024 * 1024))) # 5 MB
MAX_PAGE_COUNT = int(os.getenv("MAX_PAGE_COUNT", "15")) # 15 pages
MAX_DOCX_UNCOMPRESSED_BYTES = int(os.getenv("MAX_DOCX_UNCOMPRESSED_BYTES", str(20 * 1024 * 1024))) # 20 MB
# Global safety-net caps; per-user rate limiting is the Node layer's job.
RATE_LIMIT_GLOBAL_EXTRACT_MAX = int(os.getenv("RATE_LIMIT_GLOBAL_EXTRACT_MAX", "120")) # 120 / min
RATE_LIMIT_GLOBAL_JOBS_MAX = int(os.getenv("RATE_LIMIT_GLOBAL_JOBS_MAX", "600")) # 600 / min
_INTERNAL_SECRET_ENV = "ATS_INTERNAL_SECRET"
def is_production_mode() -> bool:
"""Detects whether server is running in production mode."""
env = os.getenv("ENVIRONMENT", "").lower()
is_prod_flag = os.getenv("PRODUCTION", "").lower() in ("true", "1")
is_hf_space = bool(os.getenv("SPACE_ID"))
return env in ("production", "prod") or is_prod_flag or is_hf_space
_rate_limit_records: Dict[str, list] = collections.defaultdict(list)
_rate_limit_lock = threading.Lock()
def check_rate_limit(key: str, max_requests: int, window_seconds: int = 60) -> bool:
"""Global sliding-window rate limiter with timestamp eviction. Thread-safe."""
now = time.time()
with _rate_limit_lock:
timestamps = _rate_limit_records[key]
# Evict stale entries
_rate_limit_records[key] = [t for t in timestamps if now - t < window_seconds]
if len(_rate_limit_records[key]) >= max_requests:
return False
_rate_limit_records[key].append(now)
return True
def verify_internal_secret(request: Request) -> None:
"""
Validates the X-ATS-Internal-Secret header using constant-time compare.
- In production mode, rejects with 401 if ATS_INTERNAL_SECRET is unset.
- If ATS_INTERNAL_SECRET is configured, requires matching header.
- In non-production mode with unset secret, allows request for local dev/testing.
Raises HTTPException(401) on failure.
"""
configured = os.environ.get(_INTERNAL_SECRET_ENV, "").strip()