File size: 8,205 Bytes
bf0e217
 
 
d572e10
bf0e217
ebdf65e
95ac724
bf0e217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66f7872
 
 
 
 
95ac724
 
 
 
 
 
 
 
 
 
 
 
 
 
bf0e217
9708aa4
 
 
f97dc11
 
 
 
597bbca
bf0e217
95ac724
597bbca
 
 
 
 
95ac724
597bbca
 
 
 
831ab6e
 
597bbca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
831ab6e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95ac724
 
831ab6e
 
 
 
 
 
9708aa4
831ab6e
ff32b52
ebdf65e
25877a7
8e10984
597bbca
 
 
831ab6e
d22fc6f
831ab6e
 
 
 
 
 
 
d30c79b
 
831ab6e
 
d30c79b
 
831ab6e
 
d30c79b
 
831ab6e
 
d30c79b
 
8e10984
d22fc6f
 
ebdf65e
 
 
 
 
 
9708aa4
 
 
8e10984
25877a7
831ab6e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
import os
import re
from datetime import datetime
import PyPDF2
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from sentence_transformers import SentenceTransformer, util
from groq import Groq
import gradio as gr

# Set your API key for Groq
os.environ["GROQ_API_KEY"] = "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"
client = Groq(api_key=os.environ.get("GROQ_API_KEY"))

# --- PDF/Text Extraction Functions --- #
def extract_text_from_file(file_path):
    """Extracts text from PDF or TXT files based on file extension."""
    if file_path.endswith('.pdf'):
        return extract_text_from_pdf(file_path)
    elif file_path.endswith('.txt'):
        return extract_text_from_txt(file_path)
    else:
        raise ValueError("Unsupported file type. Only PDF and TXT files are accepted.")

def extract_text_from_pdf(pdf_file_path):
    """Extracts text from a PDF file."""
    with open(pdf_file_path, 'rb') as pdf_file:
        pdf_reader = PyPDF2.PdfReader(pdf_file)
        text = ''.join(page.extract_text() for page in pdf_reader.pages if page.extract_text())
    return text

def extract_text_from_txt(txt_file_path):
    """Extracts text from a .txt file."""
    with open(txt_file_path, 'r', encoding='utf-8') as txt_file:
        return txt_file.read()

# --- Skill Extraction with Llama Model --- #
def extract_skills_llama(text):
    """Extracts skills from the text using the Llama model via Groq API."""
    try:
        response = client.chat.completions.create(
            messages=[{"role": "user", "content": f"Extract skills from the following text: {text}"}],
            model="llama3-70b-8192",
        )
        skills = response.choices[0].message.content.split(', ')  # Expecting a comma-separated list
        return skills
    except Exception as e:
        raise RuntimeError(f"Error during skill extraction: {e}")

# --- Job Description Processing Function --- #
def process_job_description(text):
    """Extracts skills or relevant keywords from the job description."""
    return extract_skills_llama(text)

# --- Qualification and Experience Extraction --- #
def extract_qualifications(text):
    """Extracts qualifications from text (e.g., degrees, certifications)."""
    qualifications = re.findall(r'(bachelor|master|phd|certified|degree)', text, re.IGNORECASE)
    return qualifications if qualifications else ['No specific qualifications found']

def extract_experience(text):
    """Extracts years of experience from the text."""
    experience_years = re.findall(r'(\d+)\s*(years|year) of experience', text, re.IGNORECASE)
    job_titles = re.findall(r'\b(software engineer|developer|manager|analyst)\b', text, re.IGNORECASE)
    experience_years = [int(year[0]) for year in experience_years]
    return experience_years, job_titles

# --- Updated Resume Analysis Function --- #
def analyze_resume(resume_file, job_description_file):
    if not resume_file or not job_description_file:
        return "", "", "", "Please upload both files."

    # Load and preprocess resume and job description
    resume_text = extract_text_from_file(resume_file)
    job_description_text = extract_text_from_file(job_description_file)

    # Extract skills, qualifications, and experience from the resume
    resume_skills = extract_skills_llama(resume_text)
    resume_qualifications = extract_qualifications(resume_text)
    resume_experience, _ = extract_experience(resume_text)
    total_experience = sum(resume_experience)  # Assuming this returns a list of experiences

    # Extract required skills, qualifications, and experience from the job description
    job_description_skills = process_job_description(job_description_text)
    job_description_qualifications = extract_qualifications(job_description_text)
    job_description_experience, _ = extract_experience(job_description_text)
    required_experience = sum(job_description_experience)  # Assuming total years required

    # Calculate similarity scores
    skills_similarity = len(set(resume_skills).intersection(set(job_description_skills))) / len(job_description_skills) * 100 if job_description_skills else 0
    qualifications_similarity = len(set(resume_qualifications).intersection(set(job_description_qualifications))) / len(job_description_qualifications) * 100 if job_description_qualifications else 0
    experience_similarity = 1.0 if total_experience >= required_experience else 0.0

    # Fit assessment logic
    fit_score = 0
    if total_experience >= required_experience:
        fit_score += 1
    if skills_similarity > 50:  # Define a threshold for skills match
        fit_score += 1
    if qualifications_similarity > 50:  # Define a threshold for qualifications match
        fit_score += 1

    # Determine fit
    if fit_score == 3:
        fit_assessment = "Strong fit"
    elif fit_score == 2:
        fit_assessment = "Moderate fit"
    else:
        fit_assessment = "Not a fit"

    # Prepare output messages for tab display
    summary_message = (
        f"### Summary of Analysis\n"
        f"- **Skills Similarity**: {skills_similarity:.2f}%\n"
        f"- **Qualifications Similarity**: {qualifications_similarity:.2f}%\n"
        f"- **Experience Similarity**: {experience_similarity * 100:.2f}%\n"
        f"- **Candidate Experience**: {total_experience} years\n"
        f"- **Fit Assessment**: {fit_assessment}\n"
    )

    skills_message = (
        f"### Skills Overview\n"
        f"- **Resume Skills:**\n" + "\n".join(f"  - {skill}" for skill in resume_skills) + "\n"
        f"- **Job Description Skills:**\n" + "\n".join(f"  - {skill}" for skill in job_description_skills) + "\n"
    )

    qualifications_message = (
        f"### Qualifications Overview\n"
        f"- **Resume Qualifications:** " + ", ".join(resume_qualifications) + "\n" +
        f"- **Job Description Qualifications:** " + ", ".join(job_description_qualifications) + "\n"
    )

    experience_message = (
        f"### Experience Overview\n"
        f"- **Total Experience:** {total_experience} years\n"
        f"- **Required Experience:** {required_experience} years\n"
    )

    return summary_message, skills_message, qualifications_message, experience_message


# --- Gradio Interface --- #
def run_gradio_interface():
    with gr.Blocks() as demo:
        gr.Markdown("## Resume and Job Description Analyzer")
        resume_file = gr.File(label="Upload Resume")
        job_description_file = gr.File(label="Upload Job Description")

        # Create placeholders for output messages
        summary_output = gr.Textbox(label="Summary of Analysis", interactive=False, lines=10)
        skills_output = gr.Textbox(label="Skills Overview", interactive=False, lines=10)
        qualifications_output = gr.Textbox(label="Qualifications Overview", interactive=False, lines=10)
        experience_output = gr.Textbox(label="Experience Overview", interactive=False, lines=10)

        # Create tabs for output sections
        with gr.Tab("Analysis Summary"):
            gr.Markdown("### Summary of Analysis")
            summary_output  # This automatically renders the output box

        with gr.Tab("Skills Overview"):
            gr.Markdown("### Skills Overview")
            skills_output  # This automatically renders the output box

        with gr.Tab("Qualifications Overview"):
            gr.Markdown("### Qualifications Overview")
            qualifications_output  # This automatically renders the output box

        with gr.Tab("Experience Overview"):
            gr.Markdown("### Experience Overview")
            experience_output  # This automatically renders the output box

        analyze_button = gr.Button("Analyze")

        # Button action
        analyze_button.click(analyze, inputs=[resume_file, job_description_file], outputs=[summary_output, skills_output, qualifications_output, experience_output])

    demo.launch()

def analyze(resume, job_desc):
    # Always ensure the correct number of return values
    summary, skills, qualifications, experience = analyze_resume(resume, job_desc)
    return summary, skills, qualifications, experience

if __name__ == "__main__":
    run_gradio_interface()