Update cv_analyzer.py
Browse files- cv_analyzer.py +36 -194
cv_analyzer.py
CHANGED
|
@@ -1,87 +1,51 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
import asyncio
|
| 4 |
-
import
|
| 5 |
-
|
|
|
|
| 6 |
from PIL import Image
|
| 7 |
import io
|
| 8 |
import boto3
|
| 9 |
-
import easyocr
|
| 10 |
-
from paddleocr import PaddleOCR
|
| 11 |
from doctr.io import DocumentFile
|
| 12 |
from doctr.models import ocr_predictor
|
| 13 |
-
import numpy as np
|
| 14 |
-
from huggingface_hub import hf_hub_download
|
| 15 |
-
from llama_cpp import Llama
|
| 16 |
-
import functools
|
| 17 |
-
from prompts import LOCATION_PROMPT, SPELLING_GRAMMAR_PROMPT, IDENTIFY_SECTIONS_PROMPT, ASSESS_SECTION_QUALITY_PROMPT
|
| 18 |
import logging
|
| 19 |
-
import ujson
|
| 20 |
-
from tenacity import retry, stop_after_attempt, wait_exponential
|
| 21 |
|
| 22 |
-
|
|
|
|
| 23 |
logger = logging.getLogger(__name__)
|
| 24 |
|
| 25 |
-
# Load configurations
|
| 26 |
-
with open('cv_scoring.json', 'r') as f:
|
| 27 |
-
SCORING = json.load(f)
|
| 28 |
-
|
| 29 |
# Initialize OCR models
|
| 30 |
-
easyocr_reader =
|
| 31 |
-
|
| 32 |
-
doctr_model = None
|
| 33 |
|
| 34 |
# AWS Textract client
|
| 35 |
textract_client = boto3.client('textract', region_name='us-west-2')
|
| 36 |
|
| 37 |
-
#
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
global easyocr_reader, paddleocr_reader, doctr_model
|
| 46 |
-
if easyocr_reader is None:
|
| 47 |
-
easyocr_reader = easyocr.Reader(['en'])
|
| 48 |
-
if paddleocr_reader is None:
|
| 49 |
-
paddleocr_reader = PaddleOCR(use_angle_cls=True, lang='en')
|
| 50 |
-
if doctr_model is None:
|
| 51 |
-
doctr_model = ocr_predictor(pretrained=True)
|
| 52 |
-
|
| 53 |
-
def get_llm():
|
| 54 |
-
global llm
|
| 55 |
-
if llm is None:
|
| 56 |
-
model_path = hf_hub_download("TheBloke/Mistral-7B-Instruct-v0.2-GGUF", filename="mistral-7b-instruct-v0.2.Q4_K_M.gguf")
|
| 57 |
-
llm = Llama(model_path=model_path, n_ctx=2048, n_gpu_layers=1)
|
| 58 |
-
return llm
|
| 59 |
-
|
| 60 |
-
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
|
| 61 |
-
async def llm_generate_with_retry(prompt: str) -> str:
|
| 62 |
-
model = get_llm()
|
| 63 |
-
response = model(prompt, max_tokens=512, stop=["</s>"], echo=False)
|
| 64 |
-
return response['choices'][0]['text'].strip()
|
| 65 |
-
|
| 66 |
-
async def batch_llm_generate(prompts: List[str]) -> List[str]:
|
| 67 |
-
return await asyncio.gather(*[llm_generate_with_retry(prompt) for prompt in prompts])
|
| 68 |
|
| 69 |
def extract_text_aws(image_bytes):
|
| 70 |
response = textract_client.detect_document_text(Document={'Bytes': image_bytes})
|
| 71 |
return " ".join([item['Text'] for item in response['Blocks'] if item['BlockType'] == 'WORD'])
|
| 72 |
|
| 73 |
def extract_text_easyocr(image):
|
| 74 |
-
lazy_load_ocr_models()
|
| 75 |
result = easyocr_reader.readtext(np.array(image))
|
| 76 |
return " ".join([detection[1] for detection in result])
|
| 77 |
|
| 78 |
def extract_text_paddleocr(image):
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
|
|
|
| 82 |
|
| 83 |
def extract_text_doctr(image):
|
| 84 |
-
lazy_load_ocr_models()
|
| 85 |
doc = DocumentFile.from_images(image)
|
| 86 |
result = doctr_model(doc)
|
| 87 |
return " ".join([word.value for block in result.pages[0].blocks for line in block.lines for word in line.words])
|
|
@@ -97,150 +61,28 @@ def extract_text_combined(file):
|
|
| 97 |
image_bytes = file.read()
|
| 98 |
image = Image.open(io.BytesIO(image_bytes))
|
| 99 |
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
future_paddleocr = executor.submit(extract_text_paddleocr, image)
|
| 104 |
-
future_doctr = executor.submit(extract_text_doctr, image)
|
| 105 |
-
|
| 106 |
-
aws_text = future_aws.result()
|
| 107 |
-
easyocr_text = future_easyocr.result()
|
| 108 |
-
paddleocr_text = future_paddleocr.result()
|
| 109 |
-
doctr_text = future_doctr.result()
|
| 110 |
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
def extract_personal_info(text: str) -> Dict[str, Any]:
|
| 119 |
-
email = EMAIL_PATTERN.search(text)
|
| 120 |
-
phone = PHONE_PATTERN.search(text)
|
| 121 |
|
| 122 |
-
|
| 123 |
-
phone = phone.group() if phone else None
|
| 124 |
-
|
| 125 |
-
async def extract_location():
|
| 126 |
-
prompt = LOCATION_PROMPT.format(text=text[:500])
|
| 127 |
-
return ujson.loads(await llm_generate_with_retry(prompt))
|
| 128 |
-
|
| 129 |
-
location = asyncio.run(extract_location())
|
| 130 |
-
|
| 131 |
-
info = {
|
| 132 |
-
"email": email,
|
| 133 |
-
"phone": phone,
|
| 134 |
-
"location": location
|
| 135 |
-
}
|
| 136 |
-
|
| 137 |
-
score = sum(SCORING['personal_info'][key] for key, value in info.items() if value is not None and value != "null")
|
| 138 |
-
if info['location']['city']:
|
| 139 |
-
score += SCORING['personal_info']['location']['city']
|
| 140 |
-
if info['location']['country']:
|
| 141 |
-
score += SCORING['personal_info']['location']['country']
|
| 142 |
-
|
| 143 |
-
return {
|
| 144 |
-
"info": info,
|
| 145 |
-
"score": score,
|
| 146 |
-
"max_score": sum(SCORING['personal_info'].values()) + sum(SCORING['personal_info']['location'].values())
|
| 147 |
-
}
|
| 148 |
-
|
| 149 |
-
async def analyze_cv(cv_content: str) -> Dict[str, Any]:
|
| 150 |
-
logger.debug("Starting CV analysis")
|
| 151 |
-
# 1. Personal information
|
| 152 |
-
first_page_content = cv_content.split('\n\n', 1)[0] # Extract first page or first paragraph
|
| 153 |
-
personal_info = extract_personal_info(first_page_content)
|
| 154 |
-
|
| 155 |
-
# 2, 3, and 4. Parallel processing of spelling/grammar, completeness, and content quality
|
| 156 |
-
prompts = [
|
| 157 |
-
SPELLING_GRAMMAR_PROMPT.format(text=cv_content[:1000]),
|
| 158 |
-
IDENTIFY_SECTIONS_PROMPT.format(
|
| 159 |
-
sections=', '.join(SCORING['completeness'].keys()),
|
| 160 |
-
text=cv_content[:2000]
|
| 161 |
-
)
|
| 162 |
-
]
|
| 163 |
-
spelling_grammar_result, sections_result = await batch_llm_generate(prompts)
|
| 164 |
-
|
| 165 |
-
spelling_grammar = {"error_percentage": float(spelling_grammar_result)}
|
| 166 |
-
present_sections = ujson.loads(sections_result)
|
| 167 |
-
|
| 168 |
-
spelling_grammar["score"] = next(score['score'] for score in SCORING['spelling_grammar'] if spelling_grammar["error_percentage"] <= score['max_error_percentage'])
|
| 169 |
-
spelling_grammar["max_score"] = max(score['score'] for score in SCORING['spelling_grammar'])
|
| 170 |
-
|
| 171 |
-
completeness_score = sum(SCORING['completeness'][section] for section, is_present in present_sections.items() if is_present)
|
| 172 |
-
|
| 173 |
-
main_sections = SCORING['content_quality']['main_sections']
|
| 174 |
-
content_quality_tasks = [
|
| 175 |
-
assess_section_quality(cv_content, section, SCORING['content_quality'][section]['elements'])
|
| 176 |
-
for section in main_sections if present_sections.get(section, False)
|
| 177 |
-
]
|
| 178 |
-
|
| 179 |
-
content_quality_results = await asyncio.gather(*content_quality_tasks)
|
| 180 |
-
|
| 181 |
-
content_quality = {}
|
| 182 |
-
content_quality_score = 0
|
| 183 |
-
content_quality_max_score = 0
|
| 184 |
-
|
| 185 |
-
for section, quality_result in zip((s for s in main_sections if present_sections.get(s, False)), content_quality_results):
|
| 186 |
-
subsection_scores = ujson.loads(quality_result)['subsections']
|
| 187 |
-
overall_score = sum(sum(subsection.values()) for subsection in subsection_scores)
|
| 188 |
-
max_score = len(subsection_scores) * len(SCORING['content_quality'][section]['elements']) * 2 # 2 is the max score per element
|
| 189 |
-
|
| 190 |
-
content_quality[section] = {
|
| 191 |
-
"subsection_scores": subsection_scores,
|
| 192 |
-
"overall_score": overall_score,
|
| 193 |
-
"max_score": max_score,
|
| 194 |
-
"overall_feedback": ujson.loads(quality_result)['overall_feedback']
|
| 195 |
-
}
|
| 196 |
-
|
| 197 |
-
content_quality_score += overall_score
|
| 198 |
-
content_quality_max_score += max_score
|
| 199 |
-
|
| 200 |
-
for section in main_sections:
|
| 201 |
-
if section not in content_quality:
|
| 202 |
-
content_quality[section] = {
|
| 203 |
-
"subsection_scores": [],
|
| 204 |
-
"overall_score": 0,
|
| 205 |
-
"max_score": 0,
|
| 206 |
-
"overall_feedback": f"{section} section not present in the CV"
|
| 207 |
-
}
|
| 208 |
-
|
| 209 |
-
total_score = (
|
| 210 |
-
personal_info['score'] +
|
| 211 |
-
spelling_grammar['score'] +
|
| 212 |
-
completeness_score +
|
| 213 |
-
content_quality_score
|
| 214 |
-
)
|
| 215 |
-
max_total_score = (
|
| 216 |
-
personal_info['max_score'] +
|
| 217 |
-
spelling_grammar['max_score'] +
|
| 218 |
-
sum(SCORING['completeness'].values()) +
|
| 219 |
-
content_quality_max_score
|
| 220 |
-
)
|
| 221 |
|
| 222 |
-
|
| 223 |
-
return {
|
| 224 |
-
"personalInfo": personal_info,
|
| 225 |
-
"spellingGrammar": spelling_grammar,
|
| 226 |
-
"completeness": {
|
| 227 |
-
"present_sections": present_sections,
|
| 228 |
-
"score": completeness_score,
|
| 229 |
-
"max_score": sum(SCORING['completeness'].values())
|
| 230 |
-
},
|
| 231 |
-
"contentQuality": content_quality,
|
| 232 |
-
"totalScore": total_score,
|
| 233 |
-
"maxTotalScore": max_total_score
|
| 234 |
-
}
|
| 235 |
|
| 236 |
async def process_cv(file):
|
| 237 |
try:
|
| 238 |
-
logger.debug("Starting CV processing")
|
| 239 |
cv_content = extract_text_combined(file)
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
return result
|
| 244 |
except Exception as e:
|
| 245 |
logger.exception(f"An error occurred during CV analysis: {str(e)}")
|
| 246 |
raise
|
|
|
|
| 1 |
+
# cv_analyzer.py
|
| 2 |
+
|
| 3 |
import asyncio
|
| 4 |
+
from typing import Dict, Any
|
| 5 |
+
import easyocr
|
| 6 |
+
import numpy as np
|
| 7 |
from PIL import Image
|
| 8 |
import io
|
| 9 |
import boto3
|
|
|
|
|
|
|
| 10 |
from doctr.io import DocumentFile
|
| 11 |
from doctr.models import ocr_predictor
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
import logging
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
# Set up logging
|
| 15 |
+
logging.basicConfig(level=logging.INFO)
|
| 16 |
logger = logging.getLogger(__name__)
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
# Initialize OCR models
|
| 19 |
+
easyocr_reader = easyocr.Reader(['en'])
|
| 20 |
+
doctr_model = ocr_predictor(pretrained=True)
|
|
|
|
| 21 |
|
| 22 |
# AWS Textract client
|
| 23 |
textract_client = boto3.client('textract', region_name='us-west-2')
|
| 24 |
|
| 25 |
+
# Try to import paddleocr, but don't fail if it's not available
|
| 26 |
+
try:
|
| 27 |
+
from paddleocr import PaddleOCR
|
| 28 |
+
paddleocr_reader = PaddleOCR(use_angle_cls=True, lang='en')
|
| 29 |
+
paddle_available = True
|
| 30 |
+
except ImportError:
|
| 31 |
+
logger.warning("PaddleOCR not available. Continuing without it.")
|
| 32 |
+
paddle_available = False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
def extract_text_aws(image_bytes):
|
| 35 |
response = textract_client.detect_document_text(Document={'Bytes': image_bytes})
|
| 36 |
return " ".join([item['Text'] for item in response['Blocks'] if item['BlockType'] == 'WORD'])
|
| 37 |
|
| 38 |
def extract_text_easyocr(image):
|
|
|
|
| 39 |
result = easyocr_reader.readtext(np.array(image))
|
| 40 |
return " ".join([detection[1] for detection in result])
|
| 41 |
|
| 42 |
def extract_text_paddleocr(image):
|
| 43 |
+
if paddle_available:
|
| 44 |
+
result = paddleocr_reader.ocr(np.array(image), cls=True)
|
| 45 |
+
return " ".join([line[1][0] for line in result[0]])
|
| 46 |
+
return ""
|
| 47 |
|
| 48 |
def extract_text_doctr(image):
|
|
|
|
| 49 |
doc = DocumentFile.from_images(image)
|
| 50 |
result = doctr_model(doc)
|
| 51 |
return " ".join([word.value for block in result.pages[0].blocks for line in block.lines for word in line.words])
|
|
|
|
| 61 |
image_bytes = file.read()
|
| 62 |
image = Image.open(io.BytesIO(image_bytes))
|
| 63 |
|
| 64 |
+
aws_text = extract_text_aws(image_bytes)
|
| 65 |
+
easyocr_text = extract_text_easyocr(image)
|
| 66 |
+
doctr_text = extract_text_doctr(image)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
+
if paddle_available:
|
| 69 |
+
paddleocr_text = extract_text_paddleocr(image)
|
| 70 |
+
texts = [aws_text, easyocr_text, paddleocr_text, doctr_text]
|
| 71 |
+
weights = [0.4, 0.2, 0.2, 0.2]
|
| 72 |
+
else:
|
| 73 |
+
texts = [aws_text, easyocr_text, doctr_text]
|
| 74 |
+
weights = [0.5, 0.25, 0.25]
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
+
return combine_texts(texts, weights)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
+
# ... (rest of your CV analysis functions)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
async def process_cv(file):
|
| 81 |
try:
|
|
|
|
| 82 |
cv_content = extract_text_combined(file)
|
| 83 |
+
# Perform your CV analysis here
|
| 84 |
+
# For now, we'll just return the extracted text
|
| 85 |
+
return {"extracted_text": cv_content}
|
|
|
|
| 86 |
except Exception as e:
|
| 87 |
logger.exception(f"An error occurred during CV analysis: {str(e)}")
|
| 88 |
raise
|