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