File size: 5,694 Bytes
3241f25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14e5f56
3241f25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3341e2f
 
 
3241f25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3341e2f
3241f25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3341e2f
3241f25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from typing import List

from src.ats.types import Candidate, CandidateScore, ScoredCandidate
import csv
from  openai import OpenAI,OpenAIError  
import docx
import pdfplumber
import json
import os
import csv
import smtplib
from email.mime.text import MIMEText
import base64
import streamlit as st

def extract_text_from_pdf(file):
    text = ""
    with pdfplumber.open(file) as pdf:
        for page in pdf.pages:
            text += page.extract_text() + "\n"
    return text

def extract_text_from_docx(file):
    doc = docx.Document(file)
    text = "\n".join([para.text for para in doc.paragraphs])
    return text

def get_resume_text(file):
    if file.type == "application/pdf":
        return extract_text_from_pdf(file)
    elif file.type in ["application/vnd.openxmlformats-officedocument.wordprocessingml.document", "application/msword"]:
        return extract_text_from_docx(file)
    else:
        return None

def extract_candidate_info(resume_text,id)-> Candidate:
    prompt = (
        f"Extract the following information from the candidate resume:\n"
        f"- Full Name\n"
        f"- Email Address\n"
        f"- A short biodata (concise 3-4 line professional summary)\n"
        f"- Total Years of Professional Experience\n"
        f"- List of Key Skills (comma-separated)\n\n"
        f"Resume:\n{resume_text}\n\n"
        f"Respond in the following JSON format:\n"
        f"""{{
            "name": "<name>",
            "email": "<email>",
            "biodata": "<biodata>",
            "years_of_experience": "<years>",
            "skills": ["<skill1>", "<skill2>", "..."],
        }}"""
    )

    #To generate specific JSON structure from openai
    candidate_schema = {
    "name": "extract_candidate_info",
    "description": "Extracts structured candidate information from a resume.",
    "parameters": Candidate.model_json_schema()
    }   
    
    client = OpenAI()
    try:
        response = client.chat.completions.create(
            model="gpt-4o",
            messages=[
                {"role": "system", "content": "You are an expert resume screener and recruiter."},
                {"role": "user", "content": prompt}
            ],
            functions=[candidate_schema],
            function_call={"name": "extract_candidate_info"},
        )

        #print("RESPONSE : ",response)

        # Get and parse the arguments
        function_args = response.choices[0].message.function_call.arguments
    except OpenAIError as e:
        print(f"OpenAI API call failed: {e}")
        return None

    try:
        data = json.loads(function_args)
    except json.JSONDecodeError:
        # fallback if model responds badly
        return None
    data["id"] = str(id)
    return Candidate(**data)


def combine_candidates_with_scores(
    candidates: List[Candidate], candidate_scores: List[CandidateScore]
) -> List[ScoredCandidate]:
    """
    Combine the candidates with their scores using a dictionary for efficient lookups.
    """
    # print("COMBINING CANDIDATES WITH SCORES")
    # print("SCORES:", candidate_scores)
    # print("CANDIDATES:", candidates)
    # Create a dictionary to map score IDs to their corresponding CandidateScore objects
    score_dict = {score.id: score for score in candidate_scores}

    scored_candidates = []
    for candidate in candidates:
        score = score_dict.get(candidate.id)
        if score:
            scored_candidates.append(
                ScoredCandidate(
                    id=candidate.id,
                    name=candidate.name,
                    email=candidate.email,
                    bio=candidate.bio,
                    skills=candidate.skills,
                    score=score.score,
                    reason=score.reason,
                )
            )

    with open("lead_scores.csv", "w", newline="") as f:
        writer = csv.writer(f)
        writer.writerow(["id", "name", "email", "score"])
        for candidate in scored_candidates:
            writer.writerow(
                [
                    candidate.id,
                    candidate.name,
                    candidate.email,
                    candidate.score
                ]
            )
    #print("Lead scores saved to lead_scores.csv")
    return scored_candidates

def send_email(file_path,to_email):
    EMAIL_ADDRESS = os.getenv("EMAIL_ADDRESS")
    EMAIL_PASSWORD = os.getenv("EMAIL_PASSWORD")
    SMTP_SERVER = 'smtp.gmail.com'
    SMTP_PORT = 587
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            lines = f.readlines()

        if not lines[0].lower().startswith("subject:"):
            raise ValueError(f"File {file_path} does not start with 'Subject:'")

        subject = lines[0][8:].strip()
        body = "".join(lines[1:]).strip()

        msg = MIMEText(body)
        msg['Subject'] = subject
        msg['From'] = EMAIL_ADDRESS
        msg['To'] = to_email

        with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
            server.starttls()
            server.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
            server.send_message(msg)
            #print(f"Email sent to {to_email}")

    except Exception as e:
        print(f"Error sending to {to_email}: {e}")


def display_resume(file_bytes: bytes, file_name: str):
    """Displays the uploaded PDF in an iframe."""
    base64_pdf = base64.b64encode(file_bytes).decode("utf-8")
    pdf_display = f"""
    <iframe 
        src="data:application/pdf;base64,{base64_pdf}" 
        width="100%" 
        height="600px" 
        type="application/pdf"
    >
    </iframe>
    """
    st.markdown(f"### Preview of {file_name}")
    st.markdown(pdf_display, unsafe_allow_html=True)