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"
" f"{error}
" f"", status_code=400, ) return HTMLResponse( "" "Your session with the Resource MCP has been verified.
" "You may now close this tab and return to the ATS application.
" "