Nassira commited on
Commit
bb6f897
·
verified ·
1 Parent(s): f968645

Delete cv_analyzer.py

Browse files
Files changed (1) hide show
  1. cv_analyzer.py +0 -293
cv_analyzer.py DELETED
@@ -1,293 +0,0 @@
1
- import asyncio
2
- from typing import Dict, Any, List, Tuple
3
- import easyocr
4
- import numpy as np
5
- from PIL import Image
6
- import io
7
- import boto3
8
- from doctr.io import DocumentFile
9
- from doctr.models import ocr_predictor
10
- import logging
11
- import json
12
- import re
13
- from huggingface_hub import hf_hub_download
14
- from llama_cpp import Llama
15
- from functools import lru_cache
16
-
17
- # Set up logging
18
- logging.basicConfig(level=logging.INFO)
19
- logger = logging.getLogger(__name__)
20
-
21
- # Load configurations
22
- with open('cv_scoring.json', 'r') as f:
23
- SCORING = json.load(f)
24
-
25
- # Initialize OCR models
26
- easyocr_reader = easyocr.Reader(['en'])
27
- doctr_model = ocr_predictor(pretrained=True)
28
-
29
- # AWS Textract client
30
- textract_client = boto3.client('textract', region_name='us-west-2')
31
-
32
- # Try to import paddleocr, but don't fail if it's not available
33
- try:
34
- from paddleocr import PaddleOCR
35
- paddleocr_reader = PaddleOCR(use_angle_cls=True, lang='en')
36
- paddle_available = True
37
- except ImportError:
38
- logger.warning("PaddleOCR not available. Continuing without it.")
39
- paddle_available = False
40
-
41
- @lru_cache(maxsize=1)
42
- def get_llm():
43
- model_path = hf_hub_download("TheBloke/Mistral-7B-Instruct-v0.2-GGUF", filename="mistral-7b-instruct-v0.2.Q4_K_M.gguf")
44
- return Llama(model_path=model_path, n_ctx=2048, n_gpu_layers=1)
45
-
46
- async def llm_generate(prompt: str) -> str:
47
- model = get_llm()
48
- loop = asyncio.get_running_loop()
49
- response = await loop.run_in_executor(None, model, prompt, 512, ["</s>"], False)
50
- return response['choices'][0]['text'].strip()
51
-
52
- def optimize_image(image_data):
53
- """Optimize the image for processing."""
54
- if isinstance(image_data, Image.Image):
55
- return image_data
56
- elif isinstance(image_data, np.ndarray):
57
- return Image.fromarray(image_data)
58
- elif isinstance(image_data, (bytes, io.BytesIO)):
59
- return Image.open(io.BytesIO(image_data) if isinstance(image_data, bytes) else image_data)
60
- else:
61
- raise ValueError("Unsupported image type")
62
-
63
- def extract_text_aws(image_bytes):
64
- response = textract_client.detect_document_text(Document={'Bytes': image_bytes})
65
- return " ".join([item['Text'] for item in response['Blocks'] if item['BlockType'] == 'WORD'])
66
-
67
- def extract_text_easyocr(image_np):
68
- result = easyocr_reader.readtext(image_np)
69
- return " ".join([detection[1] for detection in result])
70
-
71
- def extract_text_paddleocr(image_np):
72
- if paddle_available:
73
- result = paddleocr_reader.ocr(image_np, cls=True)
74
- return " ".join([line[1][0] for line in result[0] if line])
75
- return ""
76
-
77
- def extract_text_doctr(image):
78
- doc = DocumentFile.from_images(image)
79
- result = doctr_model(doc)
80
- return " ".join([word.value for block in result.pages[0].blocks for line in block.lines for word in line.words])
81
-
82
- def extract_text_combined(file):
83
- file_bytes = file.getvalue()
84
- image = optimize_image(file_bytes)
85
-
86
- # Convert image to numpy array for OCR processing
87
- image_np = np.array(image)
88
-
89
- aws_text = extract_text_aws(file_bytes)
90
- easyocr_text = extract_text_easyocr(image_np)
91
- doctr_text = extract_text_doctr(image)
92
-
93
- if paddle_available:
94
- paddleocr_text = extract_text_paddleocr(image_np)
95
- texts = [aws_text, easyocr_text, paddleocr_text, doctr_text]
96
- weights = [0.4, 0.2, 0.2, 0.2]
97
- else:
98
- texts = [aws_text, easyocr_text, doctr_text]
99
- weights = [0.5, 0.25, 0.25]
100
-
101
- return combine_texts(texts, weights)
102
-
103
- def combine_texts(texts, weights):
104
- word_scores = {}
105
- for text, weight in zip(texts, weights):
106
- for word in text.split():
107
- word_scores[word] = word_scores.get(word, 0) + weight
108
- return " ".join(sorted(word_scores, key=word_scores.get, reverse=True))
109
-
110
- @lru_cache(maxsize=100)
111
- async def cached_extract_personal_info(text: str) -> Dict[str, Any]:
112
- email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
113
- phone_pattern = r'\b(?:\+\d{1,3}[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b'
114
-
115
- email = re.search(email_pattern, text)
116
- phone = re.search(phone_pattern, text)
117
-
118
- email = email.group() if email else None
119
- phone = phone.group() if phone else None
120
-
121
- prompt = f"""Extract the city and country from the following text. If not found, return null.
122
- Text:
123
- {text[:500]}
124
- Respond in JSON format:
125
- {{
126
- "city": "extracted city or null if not found",
127
- "country": "extracted country or null if not found"
128
- }}"""
129
-
130
- location = json.loads(await llm_generate(prompt))
131
-
132
- info = {
133
- "email": email,
134
- "phone": phone,
135
- "location": location
136
- }
137
-
138
- score = sum(SCORING['personal_info'][key] for key, value in info.items() if value is not None and value != "null")
139
- if info['location']['city']:
140
- score += SCORING['personal_info']['location']['city']
141
- if info['location']['country']:
142
- score += SCORING['personal_info']['location']['country']
143
-
144
- return {
145
- "info": info,
146
- "score": score,
147
- "max_score": sum(SCORING['personal_info'].values()) + sum(SCORING['personal_info']['location'].values())
148
- }
149
-
150
- @lru_cache(maxsize=100)
151
- async def cached_check_spelling_grammar(text: str) -> Dict[str, Any]:
152
- prompt = f"""Analyze the following CV text for spelling and grammar errors. Provide the percentage of words with errors.
153
- CV text:
154
- {text[:1000]}
155
-
156
- Respond with a number representing the error percentage (e.g., 2.5 for 2.5%)."""
157
-
158
- error_percentage = float(await llm_generate(prompt))
159
-
160
- score = next(score['score'] for score in SCORING['spelling_grammar'] if error_percentage <= score['max_error_percentage'])
161
-
162
- return {
163
- "error_percentage": error_percentage,
164
- "score": score,
165
- "max_score": max(score['score'] for score in SCORING['spelling_grammar'])
166
- }
167
-
168
- @lru_cache(maxsize=100)
169
- async def cached_identify_sections(text: str) -> Dict[str, bool]:
170
- prompt = f"""Identify which of the following sections are present in the CV text:
171
- {', '.join(SCORING['completeness'].keys())}
172
- CV text:
173
- {text[:2000]}
174
-
175
- Respond with a JSON object where keys are section names and values are true if present, false if not."""
176
-
177
- return json.loads(await llm_generate(prompt))
178
-
179
- @lru_cache(maxsize=100)
180
- async def cached_assess_section_quality(text: str, section: str, elements: Tuple[str]) -> Dict[str, Any]:
181
- prompt = f"""Evaluate the quality of the "{section}" section in the CV.
182
- This section may contain multiple subsections (e.g., multiple education entries or work experiences).
183
- For each subsection, check for the presence and quality of the following elements:
184
- {', '.join(elements)}
185
- For each element in each subsection, respond with one of these values:
186
- 0 - Missing or inadequate
187
- 1 - Present but could be improved
188
- 2 - Present and well-written
189
- CV text:
190
- {text[:2000]}
191
-
192
- Respond in JSON format:
193
- {{
194
- "subsections": [
195
- {{
196
- "element_name1": score,
197
- "element_name2": score,
198
- ...
199
- }},
200
- {{
201
- "element_name1": score,
202
- "element_name2": score,
203
- ...
204
- }},
205
- ...
206
- ],
207
- "overall_feedback": "Your overall feedback for the section here"
208
- }}"""
209
-
210
- return json.loads(await llm_generate(prompt))
211
-
212
- async def analyze_cv(cv_content: str) -> Dict[str, Any]:
213
- logger.info("Starting CV analysis")
214
- # 1. Personal information
215
- first_page_content = cv_content.split('\n\n', 1)[0] # Extract first page or first paragraph
216
- personal_info = await cached_extract_personal_info(first_page_content)
217
-
218
- # 2. Spelling and grammar
219
- spelling_grammar = await cached_check_spelling_grammar(cv_content)
220
-
221
- # 3. Completeness
222
- present_sections = await cached_identify_sections(cv_content)
223
- completeness_score = sum(SCORING['completeness'][section] for section, is_present in present_sections.items() if is_present)
224
-
225
- # 4. Content Quality
226
- content_quality = {}
227
- content_quality_score = 0
228
- content_quality_max_score = 0
229
-
230
- main_sections = SCORING['content_quality']['main_sections']
231
- for section in main_sections:
232
- if present_sections.get(section, False):
233
- quality_result = await cached_assess_section_quality(cv_content, section, tuple(SCORING['content_quality'][section]['elements']))
234
-
235
- subsection_scores = quality_result['subsections']
236
- overall_score = sum(sum(subsection.values()) for subsection in subsection_scores)
237
- max_score = len(subsection_scores) * len(SCORING['content_quality'][section]['elements']) * 2 # 2 is the max score per element
238
-
239
- content_quality[section] = {
240
- "subsection_scores": subsection_scores,
241
- "overall_score": overall_score,
242
- "max_score": max_score,
243
- "overall_feedback": quality_result['overall_feedback']
244
- }
245
-
246
- content_quality_score += overall_score
247
- content_quality_max_score += max_score
248
- else:
249
- content_quality[section] = {
250
- "subsection_scores": [],
251
- "overall_score": 0,
252
- "max_score": 0,
253
- "overall_feedback": f"{section} section not present in the CV"
254
- }
255
-
256
- total_score = (
257
- personal_info['score'] +
258
- spelling_grammar['score'] +
259
- completeness_score +
260
- content_quality_score
261
- )
262
- max_total_score = (
263
- personal_info['max_score'] +
264
- spelling_grammar['max_score'] +
265
- sum(SCORING['completeness'].values()) +
266
- content_quality_max_score
267
- )
268
-
269
- logger.info("CV analysis completed")
270
- return {
271
- "personalInfo": personal_info,
272
- "spellingGrammar": spelling_grammar,
273
- "completeness": {
274
- "present_sections": present_sections,
275
- "score": completeness_score,
276
- "max_score": sum(SCORING['completeness'].values())
277
- },
278
- "contentQuality": content_quality,
279
- "totalScore": total_score,
280
- "maxTotalScore": max_total_score
281
- }
282
-
283
- async def process_cv(file):
284
- try:
285
- logger.info("Starting CV processing")
286
- cv_content = extract_text_combined(file)
287
- logger.info(f"Extracted text: {cv_content[:100]}...")
288
- result = await analyze_cv(cv_content)
289
- logger.info("CV analysis completed successfully")
290
- return result
291
- except Exception as e:
292
- logger.exception(f"An error occurred during CV analysis: {str(e)}")
293
- raise