utkarsh134 commited on
Commit
f245c77
·
verified ·
1 Parent(s): 329b6ea

Upload 15 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,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel
2
+ from typing import List
3
+
4
+ class RelevantSkill(BaseModel):
5
+ position: str
6
+ company: str
7
+ duration: str
8
+ relevant_experience: str
9
+
10
+ class RelevantExperienceResponse(BaseModel):
11
+ relevant_experiences: List[RelevantSkill]
12
+ experience_summary: str
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 RelevantExperienceResponse
5
+ from services.resume_service import analyze_resume_document
6
+
7
+ router = APIRouter()
8
+
9
+ @router.post("/analyze-resume", response_model=RelevantExperienceResponse)
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,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pymupdf
2
+ from io import BytesIO
3
+ import docx2txt
4
+
5
+
6
+ def extract_text_from_bytes(pdf_bytes):
7
+ try:
8
+ memory_stream = BytesIO(pdf_bytes)
9
+
10
+ doc = pymupdf.open(stream=memory_stream, filetype="pdf")
11
+
12
+ text = ""
13
+ for page in doc:
14
+ text += page.get_text()
15
+ doc.close()
16
+ return text
17
+ except Exception as e:
18
+ return f"Error reading PDF: {str(e)}"
19
+
20
+
21
+ def extract_text_from_docx(docx_bytes):
22
+ try:
23
+ docx_stream = BytesIO(docx_bytes)
24
+
25
+ text = docx2txt.process(docx_stream)
26
+
27
+ return text
28
+ except Exception as e:
29
+ return f"Error reading DOCX: {str(e)}"
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,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from langchain_google_genai import GoogleGenerativeAIEmbeddings
3
+ from langchain_community.vectorstores import Chroma
4
+ from langchain.docstore.document import Document
5
+ from chromadb.config import Settings
6
+
7
+
8
+ def create_or_load_vectorstore(text_chunks):
9
+ embeddings = GoogleGenerativeAIEmbeddings(
10
+ model="models/embedding-001", google_api_key=os.getenv("GOOGLE_API_KEY")
11
+ )
12
+
13
+ documents = [
14
+ Document(page_content=chunk, metadata={"source": "resume"})
15
+ for chunk in text_chunks
16
+ ]
17
+
18
+ vectorstore = Chroma.from_documents(
19
+ documents=documents,
20
+ embedding=embeddings,
21
+ client_settings=Settings(anonymized_telemetry=False, is_persistent=False),
22
+ )
23
+
24
+ return vectorstore
25
+
26
+
27
+ def similarity_search(vectorstore, query, k=5):
28
+ documents = vectorstore.similarity_search(query, k=k)
29
+ return documents
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)
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn
3
+ python-multipart
4
+ pymupdf
5
+ langchain
6
+ langchain-google-genai
7
+ python-dotenv
8
+ requests
9
+ docx2txt
10
+ pydantic
11
+ langchain_community
services/__init__.py ADDED
File without changes
services/llm_service.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
9
+ return ChatGoogleGenerativeAI(
10
+ model=settings["llm_model"],
11
+ temperature=settings["temperature"],
12
+ google_api_key=settings["google_api_key"],
13
+ )
14
+
15
+
16
+ def get_experience_prompt():
17
+ return PromptTemplate(
18
+ input_variables=["resume_text", "relevant_content", "job_role"],
19
+ template="""You are a professional resume analyzer with expertise in technical recruiting.
20
+
21
+ Your task is to STRICTLY extract ONLY work experience from a resume that is DIRECTLY RELEVANT to the specific job role.
22
+ Be extremely strict about matching - only include experience that explicitly uses the exact technologies/skills of the job role.
23
+
24
+ RESUME CONTENT:
25
+ {resume_text}
26
+
27
+ MOST RELEVANT SECTIONS (semantically similar to job requirements):
28
+ {relevant_content}
29
+
30
+ TARGET JOB ROLE: {job_role}
31
+
32
+ TASK INSTRUCTIONS:
33
+ 1. Extract ONLY the professional work experience sections from the resume that are DIRECTLY relevant to the specified job role.
34
+ 2. For each relevant position, extract specific responsibilities, projects, and achievements that directly relate to the target job role.
35
+ 3. Be EXTREMELY STRICT - only include experiences that explicitly demonstrate use of the exact technologies/tools required for the job role.
36
+ 4. EXCLUDE any experiences that don't directly use the core technologies of the job role.
37
+ 5. EXCLUDE any projects, education, certificates, or other non-work experience sections.
38
+ 6. EXCLUDE experiences that use similar but different technologies (e.g. for a Python role, exclude Ruby/PHP/JavaScript experience).
39
+ 7. If NO relevant experience is found, return an empty list for relevant_experiences.
40
+
41
+ For example:
42
+ - For "Python Developer": ONLY include experience entries that explicitly show Python programming. Exclude experience with Java, JavaScript, PHP etc.
43
+ - For "React Developer": ONLY include experience with React.js specifically. Exclude Vue.js, Angular or general JavaScript work.
44
+ - For "Java Developer": ONLY include Java programming experience. Exclude Python, JavaScript or other languages.
45
+
46
+ FORMAT YOUR RESPONSE AS A VALID JSON OBJECT WITH THIS EXACT STRUCTURE:
47
+ {{
48
+ "relevant_experiences": [
49
+ {{
50
+ "position": "exact job title from resume",
51
+ "company": "company name",
52
+ "duration": "time period(convert it into terms of year/months, i.e., 2 years, 5 months, 3 years 6 months)",
53
+ "relevant_experience": "detailed description of responsibilities, projects, and achievements that specifically relate to the target job role. Focus on technical details and technologies used that match the job role requirements."
54
+ }}
55
+ ],
56
+ "experience_summary": "comprehensive summary analyzing how ALL the candidate's relevant experiences align with the job role. Include specific examples of work done across different positions and highlight progression of skills relevant to the role. Summarize the total relevant experience and key technologies/tools used."
57
+ }}
58
+
59
+ IMPORTANT:
60
+ - DO NOT INVENT OR ADD INFORMATION that is not in the resume
61
+ - BE EXTREMELY STRICT - only include experiences that explicitly use the exact technologies of the job role
62
+ - DO NOT include experiences with similar but different technologies
63
+ - Make both the position-specific relevant_experience and overall experience_summary detailed and specific
64
+ - Response must be a valid JSON object
65
+ """,
66
+ )
services/resume_service.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from typing import Dict
3
+
4
+ from core.doc_processor import extract_text_from_bytes, extract_text_from_docx
5
+ from core.text_processor import chunk_text
6
+ from core.vector_store import create_or_load_vectorstore, similarity_search
7
+ from services.llm_service import get_llm, get_experience_prompt
8
+
9
+
10
+ def analyze_resume_document(
11
+ file_bytes: bytes, job_role: str, file_extension: str
12
+ ) -> Dict:
13
+ if file_extension.lower() == ".pdf":
14
+ resume_text = extract_text_from_bytes(file_bytes)
15
+ elif file_extension.lower() == ".docx":
16
+ resume_text = extract_text_from_docx(file_bytes)
17
+ else:
18
+ raise ValueError(f"Unsupported file format: {file_extension}")
19
+
20
+ if resume_text.startswith("Error"):
21
+ raise ValueError(resume_text)
22
+
23
+ chunks = chunk_text(resume_text)
24
+
25
+ vector_store = create_or_load_vectorstore(chunks)
26
+
27
+ return analyze_experience_with_llm(vector_store, resume_text, job_role)
28
+
29
+
30
+ def analyze_experience_with_llm(vectorstore, resume_text, job_role):
31
+ try:
32
+ retrieved_docs = similarity_search(vectorstore, job_role)
33
+ relevant_content = "\n".join([doc.page_content for doc in retrieved_docs])
34
+
35
+ experience_prompt = get_experience_prompt()
36
+ llm = get_llm()
37
+ chain = experience_prompt | llm
38
+
39
+ response = chain.invoke(
40
+ {
41
+ "resume_text": resume_text,
42
+ "relevant_content": relevant_content,
43
+ "job_role": job_role,
44
+ }
45
+ )
46
+
47
+ response = response.content.strip("`")
48
+ if response.startswith("json"):
49
+ response = response[4:]
50
+
51
+ parsed_response = json.loads(response.strip())
52
+ cleaned_response = {
53
+ "relevant_experiences": [],
54
+ "experience_summary": parsed_response.get(
55
+ "experience_summary", "No relevant experience found"
56
+ ),
57
+ }
58
+
59
+ for exp in parsed_response.get("relevant_experiences", []):
60
+ cleaned_exp = {
61
+ "position": exp.get("position", ""),
62
+ "company": exp.get("company", ""),
63
+ "duration": exp.get("duration", ""),
64
+ "relevant_experience": exp.get("relevant_experience", ""),
65
+ }
66
+ cleaned_response["relevant_experiences"].append(cleaned_exp)
67
+
68
+ return cleaned_response
69
+
70
+ except json.JSONDecodeError as e:
71
+ print(f"JSON Parse Error: {str(e)}")
72
+ return {
73
+ "relevant_experiences": [],
74
+ "experience_summary": "Could not parse experience details from response",
75
+ }
76
+ except Exception as e:
77
+ print(f"Unexpected Error: {str(e)}")
78
+ return {
79
+ "relevant_experiences": [],
80
+ "experience_summary": f"Error analyzing experience: {str(e)}",
81
+ }