utkarsh134 commited on
Commit
a88785b
·
verified ·
1 Parent(s): 42fbd8c

Upload 14 files

Browse files
Dockerfile ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use Python 3.10 as base image
2
+ FROM python:3.11-slim
3
+
4
+ # Set working directory
5
+ WORKDIR /app
6
+
7
+ # Install system dependencies
8
+ RUN apt-get update && apt-get install -y \
9
+ build-essential \
10
+ python3-dev \
11
+ && rm -rf /var/lib/apt/lists/*
12
+
13
+ # Copy requirements file
14
+ COPY requirements.txt .
15
+
16
+ # Install Python dependencies
17
+ RUN pip install --no-cache-dir -r requirements.txt
18
+
19
+ # Copy the application code
20
+ COPY . .
21
+
22
+ # Expose the port the app runs on
23
+ EXPOSE 8000
24
+
25
+ # Command to run the application
26
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
api/__init__.py ADDED
File without changes
api/models.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel
2
+ from typing import List, Optional
3
+ from datetime import datetime
4
+
5
+ class ResumeAnalysisResponse(BaseModel):
6
+ candidate_name: str = ""
7
+ gender: Optional[str] = None
8
+ date_of_birth: Optional[str] = None
9
+ email: Optional[str] = None
10
+ mobile_number: Optional[str] = None
11
+ address: Optional[str] = None
12
+ pan_number: Optional[str] = None
13
+ aadhar_number: Optional[str] = None
14
+ passport_number: Optional[str] = None
15
+ highest_education: Optional[str] = None
16
+ designation: Optional[str] = None
17
+ skills: Optional[str] = ""
18
+ total_experience: Optional[str] = None
19
+ region: Optional[str] = None
20
+ relevant_experience: Optional[str] = None
21
+ experience_summary: Optional[str] = None
22
+ file_modified_date: Optional[datetime] = None
api/routes.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, File, UploadFile, Form, HTTPException
2
+ import os
3
+
4
+ from api.models import ResumeAnalysisResponse
5
+ from services.resume_service import analyze_resume_document
6
+
7
+ router = APIRouter()
8
+
9
+ @router.post("/analyze-resume", response_model=ResumeAnalysisResponse)
10
+ async def analyze_resume(
11
+ resume_file: UploadFile = File(...),
12
+ job_role: str = Form(...)
13
+ ):
14
+ _, file_extension = os.path.splitext(resume_file.filename)
15
+ file_extension = file_extension.lower()
16
+
17
+ allowed_extensions = ['.pdf', '.docx']
18
+ if file_extension not in allowed_extensions:
19
+ raise HTTPException(
20
+ status_code=400,
21
+ detail=f"Only PDF and DOCX files are supported. Got: {file_extension}"
22
+ )
23
+
24
+ try:
25
+ file_bytes = await resume_file.read()
26
+
27
+ result = analyze_resume_document(file_bytes, job_role, file_extension)
28
+ return result
29
+
30
+ except Exception as e:
31
+ raise HTTPException(status_code=500, detail=f"Error processing resume: {str(e)}")
config/__init__.py ADDED
File without changes
config/settings.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+
4
+ DEFAULT_CHUNK_SIZE = 1000
5
+ DEFAULT_CHUNK_OVERLAP = 200
6
+ DEFAULT_LLM_MODEL = "gemini-2.0-flash"
7
+ DEFAULT_EMBEDDING_MODEL = "models/embedding-001"
8
+ DEFAULT_TEMPERATURE = 0
9
+
10
+ def init_settings():
11
+ load_dotenv()
12
+
13
+ if not os.getenv("GOOGLE_API_KEY"):
14
+ raise ValueError("GOOGLE_API_KEY environment variable is not set")
15
+
16
+ def get_settings():
17
+ return {
18
+ "chunk_size": int(os.getenv("CHUNK_SIZE", DEFAULT_CHUNK_SIZE)),
19
+ "chunk_overlap": int(os.getenv("CHUNK_OVERLAP", DEFAULT_CHUNK_OVERLAP)),
20
+ "llm_model": os.getenv("LLM_MODEL", DEFAULT_LLM_MODEL),
21
+ "embedding_model": os.getenv("EMBEDDING_MODEL", DEFAULT_EMBEDDING_MODEL),
22
+ "temperature": float(os.getenv("TEMPERATURE", DEFAULT_TEMPERATURE)),
23
+ "google_api_key": os.getenv("GOOGLE_API_KEY")
24
+ }
core/__init__.py ADDED
File without changes
core/doc_processor.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pymupdf
2
+ from io import BytesIO
3
+ import docx2txt
4
+ from datetime import datetime
5
+ import zipfile
6
+ from xml.etree import ElementTree as ET
7
+
8
+
9
+ def extract_text_from_bytes(pdf_bytes):
10
+ try:
11
+ memory_stream = BytesIO(pdf_bytes)
12
+ doc = pymupdf.open(stream=memory_stream, filetype="pdf")
13
+
14
+ # Extract text
15
+ text = ""
16
+ for page in doc:
17
+ text += page.get_text()
18
+
19
+ # Get modification date
20
+ metadata = doc.metadata
21
+ mod_date = metadata.get("modDate", None)
22
+
23
+ doc.close()
24
+ return text, mod_date
25
+ except Exception as e:
26
+ return f"Error reading PDF: {str(e)}", None
27
+
28
+
29
+ def get_docx_last_modified(docx_stream):
30
+
31
+ try:
32
+ docx_stream.seek(0) # Reset stream position to start
33
+ with zipfile.ZipFile(docx_stream, 'r') as docx:
34
+ if 'docProps/core.xml' in docx.namelist():
35
+ with docx.open('docProps/core.xml') as f:
36
+ core_xml = f.read()
37
+
38
+ root = ET.fromstring(core_xml)
39
+
40
+ namespaces = {
41
+ 'cp': 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties',
42
+ 'dcterms': 'http://purl.org/dc/terms/'
43
+ }
44
+
45
+ modified_element = root.find('.//dcterms:modified', namespaces)
46
+
47
+ if modified_element is not None:
48
+ modified_date_str = modified_element.text
49
+ return datetime.fromisoformat(modified_date_str.replace('Z', '+00:00'))
50
+ except Exception as e:
51
+ print(f"Error extracting DOCX metadata: {e}")
52
+ return None
53
+
54
+
55
+ def extract_text_from_docx(docx_bytes):
56
+ try:
57
+ docx_stream = BytesIO(docx_bytes)
58
+ text = docx2txt.process(docx_stream)
59
+
60
+ metadata_stream = BytesIO(docx_bytes)
61
+ mod_date = get_docx_last_modified(metadata_stream)
62
+
63
+ return text, mod_date
64
+ except Exception as e:
65
+ return f"Error reading DOCX: {str(e)}", None
66
+
67
+
68
+ def parse_pdf_date(pdf_date: str) -> datetime:
69
+
70
+ if not pdf_date or not pdf_date.startswith("D:"):
71
+ return datetime.now()
72
+
73
+ try:
74
+ date_str = pdf_date[2:14]
75
+ return datetime.strptime(date_str, "%Y%m%d%H%M")
76
+ except Exception:
77
+ return datetime.now()
core/text_processor.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
2
+
3
+
4
+ def chunk_text(text, chunk_size=1000, chunk_overlap=200):
5
+ text_splitter = RecursiveCharacterTextSplitter(
6
+ chunk_size=chunk_size,
7
+ chunk_overlap=chunk_overlap,
8
+ length_function=len,
9
+ is_separator_regex=False,
10
+ )
11
+
12
+ chunks = text_splitter.split_text(text)
13
+ return chunks
core/vector_store.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from langchain_google_genai import GoogleGenerativeAIEmbeddings
3
+ from langchain_community.vectorstores import FAISS
4
+ from langchain_core.documents import Document
5
+
6
+ def create_or_load_vectorstore(text_chunks):
7
+ embeddings = GoogleGenerativeAIEmbeddings(
8
+ model="models/embedding-001", google_api_key=os.getenv("GOOGLE_API_KEY")
9
+ )
10
+
11
+ documents = [
12
+ Document(page_content=chunk, metadata={"source": "resume"})
13
+ for chunk in text_chunks
14
+ ]
15
+
16
+ vectorstore = FAISS.from_documents(
17
+ documents=documents,
18
+ embedding=embeddings
19
+ )
20
+
21
+ return vectorstore
22
+
23
+
24
+ def similarity_search(vectorstore, query, k=5):
25
+ try:
26
+ documents = vectorstore.similarity_search(query, k=k)
27
+ return documents
28
+ except Exception as e:
29
+ print(f"Error in similarity search: {str(e)}")
30
+ return []
31
+
32
+
main.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+
4
+
5
+ from api.routes import router as api_router
6
+ from config.settings import init_settings
7
+
8
+
9
+ app = FastAPI(
10
+ title="Relevant Experience Analyzer",
11
+ description="API for extracting job-relevant experience from resumes using semantic search",
12
+ version="1.0.0"
13
+ )
14
+
15
+ app.add_middleware(
16
+ CORSMiddleware,
17
+ allow_origins=["*"],
18
+ allow_credentials=True,
19
+ allow_methods=["*"],
20
+ allow_headers=["*"],
21
+ )
22
+
23
+ init_settings()
24
+
25
+ app.include_router(api_router)
services/__init__.py ADDED
File without changes
services/llm_service.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_google_genai import ChatGoogleGenerativeAI
2
+ from langchain.prompts import PromptTemplate
3
+ from config.settings import get_settings
4
+
5
+
6
+ def get_llm():
7
+ settings = get_settings()
8
+ return ChatGoogleGenerativeAI(
9
+ model=settings["llm_model"],
10
+ temperature=settings["temperature"],
11
+ google_api_key=settings["google_api_key"],
12
+ )
13
+
14
+
15
+ def get_unified_resume_prompt():
16
+ return PromptTemplate(
17
+ input_variables=["resume_text", "relevant_content", "job_role"],
18
+ template='''You are a professional resume analyzer with expertise in technical recruiting.
19
+
20
+ Your task is to extract both basic information and relevant work experience from the resume.
21
+
22
+ RESUME CONTENT:
23
+ {resume_text}
24
+
25
+ MOST RELEVANT SECTIONS (semantically similar to job requirements):
26
+ {relevant_content}
27
+
28
+ TARGET JOB ROLE: {job_role}
29
+
30
+ TASK INSTRUCTIONS:
31
+ Basic Information:
32
+ 1. Extract all personally identifiable information that is explicitly stated in the text
33
+ 2. For fields where information is not found, use null
34
+ 3. Do not invent or infer information not present in the text
35
+ 4. For education, only return the highest level completed (postgraduate > undergraduate > 12th > 10th)
36
+ 5. For role, use the most recent/current position mentioned
37
+ 6. Return complete values - do not truncate or summarize unnecessarily
38
+ 7. Maintain exact formatting/capitalization as shown in the resume
39
+ 8. Extract all contact information including email and phone number (just the primary number)
40
+ 9. Look for any government ID numbers (PAN, Aadhar, Passport) that might be present
41
+
42
+ Experience Analysis:
43
+ 1. Create a single concise paragraph summarizing ALL relevant professional experience that directly relates to the job role
44
+ 2. Focus only on experiences that explicitly demonstrate use of the exact technologies/tools required
45
+ 3. If NO relevant experience is found, return null for relevant_experience
46
+ 4. Provide a brief summary analyzing how well the candidate's experience matches the job role
47
+
48
+ FORMAT YOUR RESPONSE AS A VALID JSON OBJECT WITH THIS EXACT STRUCTURE:
49
+ {{
50
+ "candidate_name": "full name of the candidate",
51
+ "gender": "gender if mentioned",
52
+ "date_of_birth": "DOB in YYYY/MM/DD format if mentioned",
53
+ "email": "email address if mentioned",
54
+ "mobile_number": "primary phone number if mentioned",
55
+ "address": "complete physical address if mentioned",
56
+ "pan_number": "PAN number if mentioned",
57
+ "aadhar_number": "Aadhar number if mentioned",
58
+ "passport_number": "Passport number if mentioned",
59
+ "highest_education": "most advanced completed education level, interpret from the data and return only 4 of these options : 10th, 12th, UG, PG",
60
+ "designation": "current or most recent role/position",
61
+ "skills": "comma-separated list of technical and professional skills",
62
+ "total_experience": "total work experience in terms of years i.e., if experience is 6 months return "0.5", divide the number of months found by 12 and return the number as a string",
63
+ "region": "geographical region/city of work",
64
+ "relevant_experience": "single paragraph summarizing all experience relevant to the job role",
65
+ "experience_summary": "brief analysis of how well the experience matches the job role"
66
+ }}
67
+
68
+ IMPORTANT:
69
+ - DO NOT INVENT OR ADD INFORMATION that is not in the resume
70
+ - BE EXTREMELY STRICT about experience relevance
71
+ - Response must be a valid JSON object
72
+ - For sensitive information like Aadhar/PAN, return only if explicitly mentioned in resume
73
+ - Skills should be returned as a comma-separated string (e.g. "Java, Spring Boot, Docker, AWS, PostgreSQL")'''
74
+ )
services/resume_service.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from typing import Dict
3
+ from datetime import datetime
4
+
5
+ from core.doc_processor import (
6
+ extract_text_from_bytes,
7
+ extract_text_from_docx,
8
+ parse_pdf_date
9
+ )
10
+ from core.text_processor import chunk_text
11
+ from core.vector_store import create_or_load_vectorstore, similarity_search
12
+ from services.llm_service import get_llm, get_unified_resume_prompt
13
+
14
+
15
+ def analyze_resume_document(
16
+ file_bytes: bytes, job_role: str, file_extension: str
17
+ ) -> Dict:
18
+ if file_extension.lower() == ".pdf":
19
+ resume_text, mod_date = extract_text_from_bytes(file_bytes)
20
+ file_modified_date = parse_pdf_date(mod_date) if mod_date else datetime.now()
21
+ elif file_extension.lower() == ".docx":
22
+ resume_text, mod_date = extract_text_from_docx(file_bytes)
23
+ file_modified_date = mod_date if mod_date else datetime.now()
24
+ else:
25
+ raise ValueError(f"Unsupported file format: {file_extension}")
26
+
27
+ if resume_text.startswith("Error"):
28
+ raise ValueError(resume_text)
29
+
30
+ chunks = chunk_text(resume_text)
31
+ vector_store = create_or_load_vectorstore(chunks)
32
+ return analyze_resume_with_llm(vector_store, resume_text, job_role, file_modified_date)
33
+
34
+
35
+ def analyze_resume_with_llm(vectorstore, resume_text: str, job_role: str, file_modified_date: datetime) -> Dict:
36
+ try:
37
+ retrieved_docs = similarity_search(vectorstore, job_role)
38
+ relevant_content = "\n".join([doc.page_content for doc in retrieved_docs])
39
+
40
+ unified_prompt = get_unified_resume_prompt()
41
+ llm = get_llm()
42
+ chain = unified_prompt | llm
43
+
44
+ response = chain.invoke(
45
+ {
46
+ "resume_text": resume_text,
47
+ "relevant_content": relevant_content,
48
+ "job_role": job_role,
49
+ }
50
+ )
51
+
52
+ response_text = response.content.strip()
53
+ if response_text.startswith("`"):
54
+ response_text = response_text.strip("`")
55
+ if response_text.startswith("json"):
56
+ response_text = response_text[4:]
57
+
58
+ parsed_response = json.loads(response_text.strip())
59
+
60
+ default_response = {
61
+ "candidate_name": "",
62
+ "gender": None,
63
+ "date_of_birth": None,
64
+ "email": None,
65
+ "mobile_number": None,
66
+ "address": None,
67
+ "pan_number": None,
68
+ "aadhar_number": None,
69
+ "passport_number": None,
70
+ "highest_education": None,
71
+ "designation": None,
72
+ "skills": "",
73
+ "total_experience": None,
74
+ "region": None,
75
+ "relevant_experience": None,
76
+ "experience_summary": "No relevant experience analysis available",
77
+ "file_modified_date": file_modified_date
78
+ }
79
+
80
+ result = {**default_response, **parsed_response}
81
+
82
+ result["file_modified_date"] = file_modified_date
83
+
84
+ return result
85
+
86
+ except json.JSONDecodeError as e:
87
+ print(f"JSON Parse Error: {str(e)}")
88
+ return {
89
+ "candidate_name": "",
90
+ "gender": None,
91
+ "date_of_birth": None,
92
+ "email": None,
93
+ "mobile_number": None,
94
+ "address": None,
95
+ "pan_number": None,
96
+ "aadhar_number": None,
97
+ "passport_number": None,
98
+ "highest_education": None,
99
+ "designation": None,
100
+ "skills": "",
101
+ "total_experience": None,
102
+ "region": None,
103
+ "relevant_experience": None,
104
+ "experience_summary": "Could not parse resume details from response",
105
+ "file_modified_date": file_modified_date
106
+ }
107
+ except Exception as e:
108
+ print(f"Unexpected Error: {str(e)}")
109
+ return {
110
+ "candidate_name": "",
111
+ "gender": None,
112
+ "date_of_birth": None,
113
+ "email": None,
114
+ "mobile_number": None,
115
+ "address": None,
116
+ "pan_number": None,
117
+ "aadhar_number": None,
118
+ "passport_number": None,
119
+ "highest_education": None,
120
+ "designation": None,
121
+ "skills": "",
122
+ "total_experience": None,
123
+ "region": None,
124
+ "relevant_experience": None,
125
+ "experience_summary": f"Error analyzing resume: {str(e)}",
126
+ "file_modified_date": file_modified_date
127
+ }