File size: 10,548 Bytes
a11ab1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
from typing import Dict, Any, List, Optional
# from langchain.tools import Tool
# from langchain.agents import AgentExecutor, create_react_agent
# from langchain.prompts import PromptTemplate
# from bs4 import BeautifulSoup
import requests
import json
import logging

# Set up logging
logger = logging.getLogger(__name__)
import re  

def extract_json_from_text(text: str) -> str:
    """
    Extract JSON string from LLM response with markdown formatting.
    """
    match = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", text, re.DOTALL)
    if match:
        return match.group(1).strip()

    match = re.search(r"(\{.*\})", text, re.DOTALL)
    if match:
        return match.group(1).strip()

    raise ValueError("No valid JSON found in LLM response")


class ResumeMatcher:
    def __init__(
        self,
        llm_client: Any,
        current_user: str,
        current_time: str
    ):
        self.llm = llm_client
        self.current_user = current_user
        self.current_time = current_time
        
        # self.tools = [
        #     Tool(
        #         name="job_scraper",
        #         func=self._scrape_job_posting,
        #         description="Scrapes job descriptions from URLs. Input should be a URL."
        #     )
        # ]
        
        logger.info("ResumeMatcher initialized successfully")

    def _get_llm_response(self, messages: List[Dict[str, str]]) -> str:
        """Helper method to get LLM response"""
        try:
            # Use the generate method directly as implemented in your LLMClient
            response = self.llm.generate(messages)
            
            # Handle the response based on your LLMClient's output format
            return response
            
        except Exception as e:
            logger.error(f"Error getting LLM response: {e}")
            raise

    def analyze_resume(self, resume_text: str) -> Dict[str, Any]:
        """Analyze resume and extract information"""
        if not resume_text or not resume_text.strip():
            raise ValueError("Empty response from LLM")

        try:
            messages = [
                {
                    "role": "system",
                    "content": "You are an expert resume analyzer. Extract key information from the resume and return it in a structured JSON format."
                },
                {
                    "role": "user",
                    "content": f"""Analyze this resume and extract information:
{resume_text}

Return a JSON object with these exact keys:
{{
    "personal_info": {{
        "name": "Full name",
        "email": "Email address",
        "phone": "Phone number",
        "location": "Current location",
        "linkedin": "LinkedIn URL if available"
    }},
    "current_role": "Most recent/current job title",
    "years_of_experience": "Total years of professional experience as a number",
    "education": [
        {{
            "degree": "Degree name",
            "field": "Field of study",
            "institution": "Institution name",
            "year": "Year of completion"
        }}
    ],
    "technical_skills": ["List of technical skills"],
    "soft_skills": ["List of soft skills"],
    "industries": ["List of industries worked in"],
    "key_achievements": ["List of key achievements"],
    "certifications": ["List of relevant certifications"],
    "languages": ["List of languages known"]
}}"""
                }
            ]

            response_text = self._get_llm_response(messages)
            clean_json = extract_json_from_text(response_text)
            return json.loads(clean_json)
            
        except Exception as e:
            logger.error(f"Resume analysis error: {e}")
            return {
                "error": str(e),
                "timestamp": self.current_time
            }

#     def _scrape_job_posting(self, url: str) -> str:
#         """Scrape job posting from URL"""
#         try:
#             headers = {
#                 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
#             }
#             response = requests.get(url, headers=headers)
#             soup = BeautifulSoup(response.text, 'html.parser')
            
#             for script in soup(["script", "style"]):
#                 script.decompose()
            
#             text = soup.get_text()
#             lines = (line.strip() for line in text.splitlines())
#             chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
#             result = ' '.join(chunk for chunk in chunks if chunk)
#             print(result)
#             return result
            
#         except Exception as e:
#             logger.error(f"Error scraping job posting: {e}")
#             return f"Error: {str(e)}"

#     def parse_job(self, url: str) -> Dict[str, Any]:
#         """Parse job posting from URL"""
#         try:
#             job_text = self._scrape_job_posting(url)
            
#             messages = [
#                 {
#                     "role": "system",
#                     "content": "You are an expert at parsing job descriptions. Extract key information accurately."
#                 },
#                 {
#                     "role": "user",
#                     "content": f"""Extract key information from this job description:
# {job_text}

# Return a JSON object with:
# {{
#     "title": "Job title",
#     "required_skills": ["List of required technical skills"],
#     "preferred_skills": ["List of preferred skills"],
#     "experience_required": "Years of experience required",
#     "education_required": "Required education level",
#     "responsibilities": ["List of key responsibilities"]
# }}"""
#                 }
#             ]

#             response_text = self._get_llm_response(messages)
#             return json.loads(response_text)
            
#         except Exception as e:
#             logger.error(f"Job parsing error: {e}")
#             return {
#                 "error": str(e),
#                 "timestamp": self.current_time
#             }
        
    def parse_job_from_text(self, job_text: str) -> Dict[str, Any]:
        """Parse manually pasted job description"""
        try:
            if not job_text.strip():
                raise ValueError("Empty job description text")

            messages = [
                {
                    "role": "system",
                    "content": "You are an expert at parsing job descriptions. Extract key information accurately."
                },
                {
                    "role": "user",
                    "content": f"""Extract key information from this job description:
                {job_text}

                Return a JSON object with:
                {{
                    "title": "Job title",
                    "required_skills": ["List of required technical skills"],
                    "preferred_skills": ["List of preferred skills"],
                    "experience_required": "Years of experience required",
                    "education_required": "Required education level",
                    "responsibilities": ["List of key responsibilities"]
                }}"""
            }
        ]

            response_text = self._get_llm_response(messages)
            clean_json = extract_json_from_text(response_text)
            return json.loads(clean_json)

        except Exception as e:
            logger.error(f"Job parsing error (manual input): {e}")
        return {
            "error": str(e),
            "timestamp": self.current_time
        }

    def calculate_match(
        self,
        resume_data: Dict[str, Any],
        job_data: Dict[str, Any]
    ) -> Dict[str, Any]:
        """Calculate match between resume and job"""
        try:
            messages = [
                {
                    "role": "system",
                    "content": "You are an expert at matching resumes to job requirements. Provide detailed analysis and concrete improvement suggestions."
                },
                {
                    "role": "user",
                    "content": f"""Calculate the match between this resume and job description:

Resume Data:
{json.dumps(resume_data, indent=2)}

Job Requirements:
{json.dumps(job_data, indent=2)}

Return a JSON object with:
{{
    "match_score": "Overall match percentage (0-100)",
    "confidence_score": "Analysis confidence level (0-100)",
    "skills_analysis": [
        {{
            "skill": "Name of required skill",
            "status": "found/missing/partial",
            "found_in_resume": "Where/how skill appears in resume",
            "relevance_score": "Relevance score (0-100)"
        }}
    ],
    "detailed_analysis": "Detailed analysis of the match",
    "improvement_suggestions": ["Specific suggestions to improve match"]
}}"""
                }
            ]

            response_text = self._get_llm_response(messages)
            clean_json = extract_json_from_text(response_text)
            return json.loads(clean_json)
            
        except Exception as e:
            logger.error(f"Match calculation error: {e}")
            return {
                "error": str(e),
                "timestamp": self.current_time,
                "match_score": 0,
                "confidence_score": 0,
                "skills_analysis": [],
                "detailed_analysis": f"Error: {str(e)}",
                "improvement_suggestions": ["An error occurred during analysis"]
            }
        
    def generate_cover_letter(self, resume_data: dict, job_data: dict) -> str:
        """Generate a personalized cover letter"""
        try:
            messages = [
                {
                "role": "system",
                "content": "You are a career coach writing customized cover letters."
                },
                {
                "role": "user",
                "content": f"""
Based on the following resume and job description, generate a compelling, personalized cover letter.

Resume:
{json.dumps(resume_data, indent=2)}

Job Description:
{json.dumps(job_data, indent=2)}

Make sure to:
- Mention the candidate's name and relevant experience
- Relate skills to job responsibilities
- End with a call to action
- Avoid placeholders
"""
            }
        ]
            return self._get_llm_response(messages).strip()
        except Exception as e:
            logger.error(f"Cover letter generation error: {e}")
            return f"Error generating cover letter: {str(e)}"