Download app.py from Ayush-003/AtsParser: direct link, hf CLI and curl.
- Browser
- Download file 8.21 kB
-
https://huggingface.co/spaces/Ayush-003/AtsParser/resolve/main/app.py
- Command line
-
hf download hf://spaces/Ayush-003/AtsParser/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Ayush-003/AtsParser/resolve/main/app.py
8.21 kB
| import logging | |
| from fastapi import FastAPI, HTTPException, Body, Query | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from typing import List, Dict, Any | |
| from ats_pipeline.schemas import ( | |
| Resume, JobDescription, MatchRequest, MatchResponse, | |
| FeatureRequest, FeatureResponse, SkillRequest, SkillResponse, | |
| SemanticIndexRequest, SearchResult, SampleDataResponse | |
| ) | |
| from ats_pipeline.core import ( | |
| load_data, parse_resume_text, extract_features, | |
| get_jd_search_rankings, get_sample_data, | |
| build_and_save_semantic_index, semantic_search_jobs, | |
| canonicalize_skills as util_canonicalize_skills, | |
| is_semantic_index_ready, get_dataset_status | |
| ) | |
| # Configure logging | |
| logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') | |
| logger = logging.getLogger(__name__) | |
| # --- FastAPI App Initialization --- | |
| app = FastAPI( | |
| title="ATS Scoring and Matching Pipeline API", | |
| description="A modular API for parsing resumes, extracting features, and matching them against job descriptions.", | |
| version="0.1.0" | |
| ) | |
| # --- Middleware --- | |
| # WARNING: This is a permissive CORS configuration for development. | |
| # Tighten these rules for production environments. | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], # Allows all origins | |
| allow_credentials=True, | |
| allow_methods=["*"], # Allows all methods | |
| allow_headers=["*"], # Allows all headers | |
| ) | |
| # --- API Endpoints --- | |
| def read_root(): | |
| """Check if the API is running.""" | |
| return {"status": "ok", "version": app.version} | |
| def parse_resume(resume_text: str = Body(..., embed=True, description="The full text content of the resume.")): | |
| """ | |
| Parses raw resume text to extract structured information like skills, experience, and education. | |
| """ | |
| try: | |
| parsed_data = parse_resume_text(resume_text) | |
| return Resume(**parsed_data) | |
| except Exception as e: | |
| logger.error(f"Error parsing resume: {e}", exc_info=True) | |
| raise HTTPException(status_code=500, detail="Failed to parse resume text.") | |
| def get_features(request: FeatureRequest): | |
| """ | |
| Extracts a comprehensive set of features from a resume and a target job description. | |
| This includes resume-only features and comparison features. | |
| """ | |
| try: | |
| features = extract_features(request.resume, request.jd) | |
| return FeatureResponse(features=features) | |
| except Exception as e: | |
| logger.error(f"Error extracting features: {e}", exc_info=True) | |
| raise HTTPException(status_code=500, detail="Failed to extract features.") | |
| def match_resume_to_jd(request: MatchRequest): | |
| """ | |
| Calculates a match score between a resume and a job description. | |
| This is the core endpoint that orchestrates parsing, feature extraction, and scoring. | |
| """ | |
| try: | |
| # 1. Parse the resume text | |
| parsed_resume_data = parse_resume_text(request.resume_text) | |
| resume = Resume(**parsed_resume_data) | |
| # 2. Extract features based on the parsed resume and the provided JD | |
| features = extract_features(resume, request.jd) | |
| # 3. The match score is part of the extracted features | |
| match_score = features.get("jd_aware_features", {}).get("match_score", 0.0) | |
| return MatchResponse( | |
| match_score=match_score, | |
| resume=resume, | |
| features=features | |
| ) | |
| except Exception as e: | |
| logger.error(f"Error during matching process: {e}", exc_info=True) | |
| raise HTTPException(status_code=500, detail="An unexpected error occurred during the matching process.") | |
| def canonicalize_skills_endpoint(request: SkillRequest): | |
| """ | |
| Maps a list of raw skill strings to their canonical forms using ESCO/O*NET datasets. | |
| """ | |
| try: | |
| canonicalized = util_canonicalize_skills(request.raw_skills) | |
| return [SkillResponse(raw_skill=k, canonical_skill=v) for k, v in canonicalized.items()] | |
| except Exception as e: | |
| logger.error(f"Error canonicalizing skills: {e}", exc_info=True) | |
| raise HTTPException(status_code=500, detail="Failed to canonicalize skills.") | |
| def search_jd(q: str = Query(..., description="The search query string.")): | |
| """ | |
| Performs a lightweight keyword search over job descriptions using the BM25 algorithm. | |
| """ | |
| try: | |
| results = get_jd_search_rankings(q) | |
| return results | |
| except Exception as e: | |
| logger.error(f"Error during BM25 search: {e}", exc_info=True) | |
| raise HTTPException(status_code=500, detail="Failed to perform BM25 search.") | |
| def get_data_status(): | |
| """Checks the availability and status of the required datasets.""" | |
| return get_dataset_status() | |
| def fetch_sample_data(): | |
| """Retrieves a sample resume and job description for demonstration purposes.""" | |
| try: | |
| return get_sample_data() | |
| except Exception as e: | |
| logger.error(f"Could not fetch sample data: {e}", exc_info=True) | |
| raise HTTPException(status_code=404, detail="Sample data not found or failed to load.") | |
| async def build_semantic_index(request: SemanticIndexRequest): | |
| """ | |
| Builds and saves a FAISS index for semantic search. This can be a long-running operation. | |
| """ | |
| try: | |
| logger.info(f"Starting semantic index build for dataset: {request.dataset} with limit: {request.limit}") | |
| result = build_and_save_semantic_index(dataset_name=request.dataset, limit=request.limit, persist=request.persist) | |
| logger.info("Semantic index build completed.") | |
| return result | |
| except Exception as e: | |
| logger.error(f"Failed to build semantic index: {e}", exc_info=True) | |
| raise HTTPException(status_code=500, detail=f"Failed to build semantic index: {str(e)}") | |
| def semantic_search(q: str = Query(..., description="The search query for semantic similarity search."), k: int = Query(5, ge=1, le=50, description="Number of results to return.")): | |
| """ | |
| Performs a semantic search using the pre-built FAISS index to find the most similar job descriptions. | |
| """ | |
| if not is_semantic_index_ready(): | |
| raise HTTPException(status_code=400, detail="Semantic index has not been built. Please call POST /build_semantic_index first.") | |
| try: | |
| results = semantic_search_jobs(q, k) | |
| return results | |
| except Exception as e: | |
| logger.error(f"Error during semantic search: {e}", exc_info=True) | |
| raise HTTPException(status_code=500, detail="Failed to perform semantic search.") | |
| # --- Application Startup Logic --- | |
| async def startup_event(): | |
| """ | |
| On application startup, log status and load necessary models and data. | |
| """ | |
| logger.info("Application startup...") | |
| logger.info("Loading datasets and initializing search models...") | |
| try: | |
| # This function pre-caches the necessary data and models on startup | |
| load_data() | |
| logger.info("Successfully loaded initial data and models.") | |
| except Exception as e: | |
| logger.error(f"Failed to load data on startup: {e}", exc_info=True) | |
| # Depending on the use case, you might want to prevent the app from starting | |
| # raise RuntimeError("Could not initialize application data.") |