AI-powered Resume Generator Python, Java

👤 Sharing: AI
```python
import json
import re
from typing import List, Dict, Any

# --- Configuration ---
SKILL_WEIGHT = 0.6
EXPERIENCE_WEIGHT = 0.4
KEYWORD_WEIGHT = 0.8  # Weight for keywords from the job description

class ResumeGenerator:

    def __init__(self, resume_file: str = None, job_description: str = None):
        """
        Initializes the ResumeGenerator with resume data and job description.

        Args:
            resume_file (str, optional): Path to the resume JSON file. Defaults to None.
            job_description (str, optional):  Job description text. Defaults to None.
        """

        self.resume_data = self._load_resume(resume_file) if resume_file else {}
        self.job_description = job_description
        self.keywords = self._extract_keywords(job_description) if job_description else []

        self.skill_scores = {}
        self.experience_scores = {}


    def _load_resume(self, resume_file: str) -> Dict[str, Any]:
        """
        Loads resume data from a JSON file.

        Args:
            resume_file (str): Path to the resume JSON file.

        Returns:
            Dict[str, Any]: Resume data as a dictionary.

        Raises:
            FileNotFoundError: If the resume file is not found.
            json.JSONDecodeError: If the JSON is invalid.
        """
        try:
            with open(resume_file, 'r') as f:
                data = json.load(f)
            return data
        except FileNotFoundError:
            raise FileNotFoundError(f"Resume file not found: {resume_file}")
        except json.JSONDecodeError:
            raise json.JSONDecodeError("Invalid JSON format in resume file.", "", 0)

    def _extract_keywords(self, job_description: str) -> List[str]:
        """
        Extracts keywords from the job description.  A simple implementation focusing on
        alphanumeric words.  More advanced NLP techniques could be used.

        Args:
            job_description (str): The job description text.

        Returns:
            List[str]: A list of keywords.
        """
        if not job_description:
            return []

        # Split into words and remove punctuation
        words = re.findall(r'\b\w+\b', job_description.lower())  # Use regex for word boundary

        # Remove duplicates and filter out common stop words (very basic list)
        stop_words = set(['and', 'the', 'a', 'an', 'is', 'are', 'was', 'were', 'in', 'on', 'of', 'to', 'for', 'with', 'by', 'as', 'at', 'from', 'that', 'this', 'these', 'those', 'it', 'he', 'she', 'they'])
        keywords = [word for word in set(words) if word not in stop_words]

        return keywords


    def _calculate_skill_scores(self) -> None:
        """
        Calculates the skill scores based on the presence of job description keywords.
        """

        if not self.resume_data or 'skills' not in self.resume_data:
            self.skill_scores = {}
            return

        skills = self.resume_data['skills']
        self.skill_scores = {}

        for skill in skills:
            skill_name = skill.lower()
            score = 0
            for keyword in self.keywords:
                if keyword in skill_name:
                    score += KEYWORD_WEIGHT  # More weight to exact keywords from JD

            self.skill_scores[skill] = score  # Accumulate scores


    def _calculate_experience_scores(self) -> None:
        """
        Calculates experience scores based on matching job description keywords in
        job titles and descriptions.
        """

        if not self.resume_data or 'experience' not in self.resume_data:
            self.experience_scores = {}
            return

        experiences = self.resume_data['experience']
        self.experience_scores = {}

        for i, exp in enumerate(experiences):
            score = 0
            title = exp.get('title', '').lower()
            description = exp.get('description', '').lower()

            for keyword in self.keywords:
                if keyword in title:
                    score += KEYWORD_WEIGHT # Job title match is valuable
                if keyword in description:
                    score += (KEYWORD_WEIGHT / 2)  # Description match, lesser value

            self.experience_scores[i] = score # Accumulate scores


    def generate_resume(self) -> Dict[str, Any]:
        """
        Generates a tailored resume based on the job description.

        Returns:
            Dict[str, Any]: Tailored resume data.
        """

        self._calculate_skill_scores()
        self._calculate_experience_scores()

        tailored_resume = {}

        # Copy basic information
        for key in self.resume_data:
             if key not in ['skills', 'experience']:
                 tailored_resume[key] = self.resume_data[key]

        # Add tailored skills
        sorted_skills = sorted(self.skill_scores.items(), key=lambda item: item[1], reverse=True) # Sort Skills
        tailored_resume['skills'] = [skill for skill, score in sorted_skills if score > 0]

        # Add tailored experience (prioritize highest scored experiences)
        sorted_experiences = sorted(self.experience_scores.items(), key=lambda item: item[1], reverse=True)  # Sort experiences

        tailored_resume['experience'] = []
        for i, score in sorted_experiences:
            if score > 0:
                tailored_resume['experience'].append(self.resume_data['experience'][i])

        return tailored_resume

    def run(self):
        """
        Runs the resume generation process.  This is the main entry point.
        """
        if not self.resume_data:
            print("Error: No resume data loaded.  Please provide a resume file.")
            return

        if not self.job_description:
            print("Warning: No job description provided.  The resume will be based solely on the original resume data.")
            return

        tailored_resume = self.generate_resume()

        # Output the tailored resume (e.g., to console, to a file)
        print(json.dumps(tailored_resume, indent=4))

# --- Example Usage ---
if __name__ == "__main__":
    # Create a dummy resume file for testing
    dummy_resume = {
        "name": "John Doe",
        "email": "john.doe@example.com",
        "skills": ["Python", "Java", "Data Analysis", "Machine Learning", "SQL", "Communication", "Project Management"],
        "experience": [
            {
                "title": "Software Engineer",
                "company": "Acme Corp",
                "description": "Developed web applications using Python and Java. Managed projects and collaborated with cross-functional teams."
            },
            {
                "title": "Data Scientist",
                "company": "Beta Inc",
                "description": "Performed data analysis and built machine learning models using Python and SQL."
            }
        ]
    }

    # Write the dummy data to a JSON file
    with open("dummy_resume.json", "w") as f:
        json.dump(dummy_resume, f, indent=4)

    # Example job description
    job_description = """
    We are looking for a Data Scientist with strong Python and Machine Learning skills.
    Experience with data analysis and SQL is also required. Excellent communication skills are essential.
    """

    # Instantiate the ResumeGenerator
    generator = ResumeGenerator(resume_file="dummy_resume.json", job_description=job_description)

    # Run the generator
    generator.run()
```
👁️ Viewed: 9

Comments