AI-Powered Resume Evaluator

← Back to Projects

AI-Powered Resume Evaluator in Python

About the project: Here, we are building an AI-Powered Resume Evaluator.This is a very good use case for the Gemini API.

AI-Powered Resume Evaluator can quickly score and critique resumes against a target job description.

Prerequisites

Before running the code, You will need to have the requests library installed to run this code:


  pip install requests
  


Project Level: Advance

Here we are creating a single Python file, resume_evaluator.py, that includes a sample resume and job description, then uses the Gemini API with a structured request to generate a detailed, score-based evaluation.


import requests
import json
import time
import os

# --- Configuration ---
# NOTE: The Canvas environment will automatically provide the API key 
# if this variable is left as an empty string.
API_KEY = "" 
MODEL_NAME = "gemini-2.5-flash-preview-09-2025"
API_URL = f"https://generativelanguage.googleapis.com/v1beta/models/{MODEL_NAME}:generateContent"

# --- Sample Input Data ---

# Target Job Description (used as context for evaluation)
TARGET_JOB_DESCRIPTION = """
Senior Python Developer (Full Stack)
We are seeking a seasoned Python Developer with expertise in Flask or Django, 
strong proficiency in front-end technologies (React/Vue), and deep experience 
with SQL databases (PostgreSQL preferred). Responsibilities include designing 
and implementing microservices, optimizing database queries, and leading code reviews. 
Must have 5+ years of experience and be proficient in Git and cloud deployment (AWS/GCP).
"""

# Sample Resume Text (simulating a parsed resume file)
SAMPLE_RESUME_TEXT = """
abcd efg
(011) 123-4567 | abcd.efg@email.com | LinkedIn: /in/abcdefg

Summary
Passionate developer with 7 years of experience building scalable web applications. 
Expert in JavaScript and relational databases. Seeking a Senior role.

Experience
Software Engineer, TechCorp (2022 - Present)
- Developed and maintained critical features using Node.js and MongoDB.
- Led migration of legacy systems to a modern, microservice architecture.
- Mentored junior staff on best practices and performance tuning.

Full Stack Developer, StartUp X (2018 - 2021)
- Built user interfaces using Vue.js and REST APIs in Java.
- Managed deployment pipelines using Jenkins and Docker.

Skills
Python (Intermediate), JavaScript (Expert), Node.js, Vue.js, MongoDB, Java, 
Docker, Jenkins, AWS (Basic), Git, SQL (PostgreSQL, MySQL).

Education
M.S. Computer Science, State University
"""

# --- Gemini API Call Implementation ---

def exponential_backoff_fetch(url, payload, max_retries=5):
    """Fetches data from the API with exponential backoff on failure."""
    headers = {'Content-Type': 'application/json'}
    
    for attempt in range(max_retries):
        try:
            response = requests.post(url, headers=headers, json=payload)
            response.raise_for_status() # Raises HTTPError for bad responses (4xx or 5xx)
            return response.json()
        except requests.exceptions.HTTPError as e:
            if attempt == max_retries - 1:
                print(f"Error: Maximum retries reached. Failed to get response: {e}")
                return None
            
            wait_time = 2 ** attempt
            # print(f"HTTP Error: {e}. Retrying in {wait_time}s...")
            time.sleep(wait_time)
        except requests.exceptions.RequestException as e:
            print(f"Connection error: {e}")
            return None
    return None

def evaluate_resume(resume_text, job_description):
    """
    Constructs the request payload and calls the Gemini API 
    to get a structured resume evaluation.
    """
    
    # 1. Define the AI's persona and rules
    system_prompt = (
        "You are a Senior Technical Recruiter and AI-Powered Resume Evaluator. "
        "Your task is to analyze a candidate's resume against a specific job description. "
        "Provide an objective, structured evaluation in the requested JSON format. "
        "Scores must be out of 100. Focus strictly on relevance, experience depth, and required skills."
    )

    # 2. Define the specific task query
    user_query = (
        "Please evaluate the following RESUME TEXT against the TARGET JOB DESCRIPTION. "
        "Provide scores, strengths, weaknesses, and a recommendation based on the fit."
        f"\n\n--- TARGET JOB DESCRIPTION ---\n{job_description}"
        f"\n\n--- CANDIDATE RESUME TEXT ---\n{resume_text}"
    )
    
    # 3. Define the desired structured output format (JSON Schema)
    response_schema = {
        "type": "OBJECT",
        "properties": {
            "overallScore": {
                "type": "INTEGER", 
                "description": "The overall suitability score from 1 to 100."
            },
            "matchScore": {
                "type": "INTEGER", 
                "description": "Score 1-100 indicating technical skill relevance and experience length compared to the job description."
            },
            "strengths": {
                "type": "ARRAY", 
                "items": {"type": "STRING"},
                "description": "Key points on the resume that align well with the job."
            },
            "weaknesses": {
                "type": "ARRAY", 
                "items": {"type": "STRING"},
                "description": "Areas where the resume falls short compared to the requirements."
            },
            "recommendation": {
                "type": "STRING", 
                "description": "A hiring recommendation (e.g., 'Strong Interview', 'Review Later', 'Reject', 'Needs Python Experience')."
            }
        },
        "required": ["overallScore", "matchScore", "strengths", "weaknesses", "recommendation"]
    }

    # 4. Construct the full API payload
    payload = {
        "contents": [{ "parts": [{ "text": user_query }] }],
        "systemInstruction": { "parts": [{ "text": system_prompt }] },
        "config": {
            "responseMimeType": "application/json",
            "responseSchema": response_schema
        }
    }
    
    # Add API key to the URL if provided (not strictly needed in Canvas environment)
    url_with_key = f"{API_URL}?key={API_KEY}" if API_KEY else API_URL
    
    # 5. Make the API call
    api_response = exponential_backoff_fetch(url_with_key, payload)
    
    if api_response:
        try:
            # The structured JSON is inside the first part's text field
            json_text = api_response["candidates"][0]["content"]["parts"][0]["text"]
            return json.loads(json_text)
        except (KeyError, IndexError, json.JSONDecodeError) as e:
            print(f"Failed to parse model response: {e}")
            # Fallback to returning raw text if JSON parsing fails
            if api_response:
                return api_response["candidates"][0]["content"]["parts"][0]["text"]
            return None
    return None

# --- Main Execution ---

if __name__ == "__main__":
    print("--- AI-POWERED RESUME EVALUATOR ---")
    print("\nTARGET JOB:")
    print(TARGET_JOB_DESCRIPTION.strip())
    print("\n-------------------------------------")
    print("CANDIDATE RESUME:")
    print(SAMPLE_RESUME_TEXT.strip())
    print("\n-------------------------------------")
    print("Running AI Evaluation...\n")

    evaluation_report = evaluate_resume(SAMPLE_RESUME_TEXT, TARGET_JOB_DESCRIPTION)

    if evaluation_report:
        print("--- EVALUATION REPORT (Structured JSON) ---")
        if isinstance(evaluation_report, dict):
            # Pretty print the structured report
            print(json.dumps(evaluation_report, indent=4))
        else:
            # Handle case where parsing failed and raw text was returned
            print("Evaluation Text (Could not parse as JSON):")
            print(evaluation_report)
    else:
        print("Evaluation failed. Check connectivity or API key.")

  


How to Run

  1. Save: Save the code above as a single file named resume_evaluator.py.
  2. Open your terminal in the same directory.
  3. Run the application:
  4. 
          python resume_evaluator.py
        


The above file is ready to run. It uses a System Prompt to define the AI's role and a structured JSON schema (responseSchema) to ensure the output is consistent, making it easy to integrate the results into a larger application.



← Back to Projects