|
|
|
import os |
|
from huggingface_hub import InferenceClient |
|
from dotenv import load_dotenv |
|
import json |
|
import re |
|
|
|
from PIL import Image, ImageEnhance, ImageDraw |
|
import cv2 |
|
import numpy as np |
|
from paddleocr import PaddleOCR |
|
import logging |
|
from datetime import datetime |
|
|
|
|
|
logging.basicConfig( |
|
level=logging.INFO, |
|
handlers=[ |
|
logging.StreamHandler() |
|
] |
|
) |
|
|
|
|
|
|
|
os.environ['PADDLEOCR_HOME'] = '/tmp/.paddleocr' |
|
|
|
RESULT_FOLDER = 'static/results/' |
|
JSON_FOLDER = 'static/json/' |
|
|
|
if not os.path.exists('/tmp/.paddleocr'): |
|
os.makedirs(RESULT_FOLDER, exist_ok=True) |
|
|
|
|
|
if not os.path.exists('/tmp/.paddleocr'): |
|
os.makedirs('/tmp/.paddleocr', exist_ok=True) |
|
logging.info("Created PaddleOCR home directory.") |
|
else: |
|
logging.info("PaddleOCR home directory exists.") |
|
|
|
|
|
load_dotenv() |
|
|
|
|
|
HFT = os.getenv('HF_TOKEN') |
|
|
|
|
|
client = InferenceClient(model="mistralai/Mistral-7B-Instruct-v0.3", token=HFT) |
|
|
|
def load_image(image_path): |
|
ext = os.path.splitext(image_path)[1].lower() |
|
if ext in ['.png', '.jpg', '.jpeg', '.webp', '.tiff']: |
|
image = cv2.imread(image_path) |
|
if image is None: |
|
raise ValueError(f"Failed to load image from {image_path}. The file may be corrupted or unreadable.") |
|
return image |
|
else: |
|
raise ValueError(f"Unsupported image format: {ext}") |
|
|
|
|
|
def upscale_image(image, scale=2): |
|
height, width = image.shape[:2] |
|
upscaled_image = cv2.resize(image, (width * scale, height * scale), interpolation=cv2.INTER_CUBIC) |
|
return upscaled_image |
|
|
|
|
|
def reduce_noise(image): |
|
return cv2.fastNlMeansDenoisingColored(image, None, 10, 10, 7, 21) |
|
|
|
|
|
def sharpen_image(image): |
|
kernel = np.array([[0, -1, 0], |
|
[-1, 5, -1], |
|
[0, -1, 0]]) |
|
sharpened_image = cv2.filter2D(image, -1, kernel) |
|
return sharpened_image |
|
|
|
|
|
def enhance_image(image): |
|
pil_img = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) |
|
enhancer = ImageEnhance.Contrast(pil_img) |
|
enhanced_image = enhancer.enhance(1.5) |
|
enhanced_image_bgr = cv2.cvtColor(np.array(enhanced_image), cv2.COLOR_RGB2BGR) |
|
return enhanced_image_bgr |
|
|
|
|
|
def process_image(image_path, scale=2): |
|
|
|
image = load_image(image_path) |
|
|
|
|
|
upscaled_image = upscale_image(image, scale) |
|
|
|
|
|
denoised_image = reduce_noise(upscaled_image) |
|
|
|
|
|
sharpened_image = sharpen_image(denoised_image) |
|
|
|
|
|
final_image = enhance_image(sharpened_image) |
|
|
|
return final_image |
|
|
|
|
|
def ocr_with_paddle(img): |
|
final_text = '' |
|
boxes = [] |
|
|
|
|
|
ocr = PaddleOCR( |
|
lang='en', |
|
use_angle_cls=True, |
|
det_model_dir=os.path.join(os.environ['PADDLEOCR_HOME'], 'whl/det'), |
|
rec_model_dir=os.path.join(os.environ['PADDLEOCR_HOME'], 'whl/rec/en/en_PP-OCRv4_rec_infer'), |
|
cls_model_dir=os.path.join(os.environ['PADDLEOCR_HOME'], 'whl/cls/ch_ppocr_mobile_v2.0_cls_infer') |
|
) |
|
|
|
|
|
if isinstance(img, str): |
|
img = cv2.imread(img) |
|
|
|
|
|
result = ocr.ocr(img) |
|
|
|
|
|
for line in result[0]: |
|
|
|
if len(line) == 3: |
|
box, (text, confidence), _ = line |
|
elif len(line) == 2: |
|
box, (text, confidence) = line |
|
|
|
|
|
final_text += ' ' + text |
|
boxes.append(box) |
|
|
|
|
|
points = [(int(point[0]), int(point[1])) for point in box] |
|
cv2.polylines(img, [np.array(points)], isClosed=True, color=(0, 255, 0), thickness=2) |
|
|
|
|
|
img_with_boxes = img |
|
|
|
return final_text, img_with_boxes |
|
|
|
def extract_text_from_images(image_paths): |
|
all_extracted_texts = {} |
|
all_extracted_imgs = {} |
|
for image_path in image_paths: |
|
try: |
|
|
|
enhanced_image = process_image(image_path, scale=2) |
|
|
|
|
|
result, img_with_boxes = ocr_with_paddle(enhanced_image) |
|
|
|
|
|
img_result = Image.fromarray(enhanced_image) |
|
|
|
|
|
|
|
|
|
current_time = datetime.now() |
|
|
|
|
|
unique_id = current_time.strftime("%Y%m%d%H%M%S%f") |
|
|
|
|
|
|
|
|
|
result_image_path = os.path.join(RESULT_FOLDER, f'result_{unique_id}_{os.path.basename(image_path)}') |
|
|
|
cv2.imwrite(result_image_path, img_with_boxes) |
|
|
|
|
|
all_extracted_texts[image_path] = result |
|
all_extracted_imgs[image_path] = result_image_path |
|
except ValueError as ve: |
|
print(f"Error processing image {image_path}: {ve}") |
|
continue |
|
|
|
|
|
all_extracted_imgs_json = {str(k): str(v) for k, v in all_extracted_imgs.items()} |
|
return all_extracted_texts, all_extracted_imgs_json |
|
|
|
|
|
def Data_Extractor(data, client=client): |
|
text = f'''Act as a Text extractor for the following text given in text: {data} |
|
extract text in the following output JSON string: |
|
{{ |
|
"Name": ["Identify and Extract All the person's name from the text."], |
|
"Designation": ["Extract All the designation or job title mentioned in the text."], |
|
"Company": ["Extract All the company or organization name if mentioned."], |
|
"Contact": ["Extract All phone number, including country codes if present."], |
|
"Address": ["Extract All the full postal address or location mentioned in the text."], |
|
"Email": ["Identify and Extract All valid email addresses mentioned in the text else 'Not found'."], |
|
"Link": ["Identify and Extract any website URLs or social media links present in the text."] |
|
}} |
|
Output: |
|
''' |
|
|
|
|
|
response = client.text_generation(text, max_new_tokens=1000) |
|
|
|
print("parse in text ---:",response) |
|
|
|
|
|
try: |
|
json_data = json.loads(response) |
|
print("Json_data-------------->",json_data) |
|
return json_data |
|
except json.JSONDecodeError as e: |
|
return {"error": f"Error decoding JSON: {e}"} |
|
|
|
|
|
def json_to_llm_str(textJson): |
|
str='' |
|
for file,item in textJson.items(): |
|
str+=item + ' ' |
|
return str |
|
|
|
|
|
def extract_contact_details(text): |
|
|
|
|
|
combined_phone_regex = re.compile(r''' |
|
(?: |
|
#(?:(?:\+91[-.\s]?)?\d{5}[-.\s]?\d{5})|(?:\+?\d{1,3})?[-.\s()]?\d{5,}[-.\s()]?\d{5,}[-.\s()]?\d{1,9} | /^[\.-)( ]*([0-9]{3})[\.-)( ]*([0-9]{3})[\.-)( ]*([0-9]{4})$/ | |
|
\+1\s\(\d{3}\)\s\d{3}-\d{4} | # USA/Canada Intl +1 (XXX) XXX-XXXX |
|
\(\d{3}\)\s\d{3}-\d{4} | # USA/Canada STD (XXX) XXX-XXXX |
|
\(\d{3}\)\s\d{3}\s\d{4} | # USA/Canada (XXX) XXX XXXX |
|
\(\d{3}\)\s\d{3}\s\d{3} | # USA/Canada (XXX) XXX XXX |
|
\+1\d{10} | # +1 XXXXXXXXXX |
|
\d{10} | # XXXXXXXXXX |
|
\+44\s\d{4}\s\d{6} | # UK Intl +44 XXXX XXXXXX |
|
\+44\s\d{3}\s\d{3}\s\d{4} | # UK Intl +44 XXX XXX XXXX |
|
0\d{4}\s\d{6} | # UK STD 0XXXX XXXXXX |
|
0\d{3}\s\d{3}\s\d{4} | # UK STD 0XXX XXX XXXX |
|
\+44\d{10} | # +44 XXXXXXXXXX |
|
0\d{10} | # 0XXXXXXXXXX |
|
\+61\s\d\s\d{4}\s\d{4} | # Australia Intl +61 X XXXX XXXX |
|
0\d\s\d{4}\s\d{4} | # Australia STD 0X XXXX XXXX |
|
\+61\d{9} | # +61 XXXXXXXXX |
|
0\d{9} | # 0XXXXXXXXX |
|
\+91\s\d{5}-\d{5} | # India Intl +91 XXXXX-XXXXX |
|
\+91\s\d{4}-\d{6} | # India Intl +91 XXXX-XXXXXX |
|
\+91\s\d{10} | # India Intl +91 XXXXXXXXXX |
|
\+91\s\d{3}\s\d{3}\s\d{4} | # India Intl +91 XXX XXX XXXX |
|
\+91\s\d{3}-\d{3}-\d{4} | # India Intl +91 XXX-XXX-XXXX |
|
\+91\s\d{2}\s\d{4}\s\d{4} | # India Intl +91 XX XXXX XXXX |
|
\+91\s\d{2}-\d{4}-\d{4} | # India Intl +91 XX-XXXX-XXXX |
|
\+91\s\d{5}\s\d{5} | # India Intl +91 XXXXX XXXXX |
|
\d{5}\s\d{5} | # India XXXXX XXXXX |
|
\d{5}-\d{5} | # India XXXXX-XXXXX |
|
0\d{2}-\d{7} | # India STD 0XX-XXXXXXX |
|
\+91\d{10} | # +91 XXXXXXXXXX |
|
\d{10} | # XXXXXXXXXX # Here is the regex to handle all possible combination of the contact |
|
\d{6}-\d{4} | # XXXXXX-XXXX |
|
\d{4}-\d{6} | # XXXX-XXXXXX |
|
\d{3}\s\d{3}\s\d{4} | # XXX XXX XXXX |
|
\d{3}-\d{3}-\d{4} | # XXX-XXX-XXXX |
|
\d{4}\s\d{3}\s\d{3} | # XXXX XXX XXX |
|
\d{4}-\d{3}-\d{3} | # XXXX-XXX-XXX #----- |
|
\+49\s\d{4}\s\d{8} | # Germany Intl +49 XXXX XXXXXXXX |
|
\+49\s\d{3}\s\d{7} | # Germany Intl +49 XXX XXXXXXX |
|
0\d{3}\s\d{8} | # Germany STD 0XXX XXXXXXXX |
|
\+49\d{12} | # +49 XXXXXXXXXXXX |
|
\+49\d{10} | # +49 XXXXXXXXXX |
|
0\d{11} | # 0XXXXXXXXXXX |
|
\+86\s\d{3}\s\d{4}\s\d{4} | # China Intl +86 XXX XXXX XXXX |
|
0\d{3}\s\d{4}\s\d{4} | # China STD 0XXX XXXX XXXX |
|
\+86\d{11} | # +86 XXXXXXXXXXX |
|
\+81\s\d\s\d{4}\s\d{4} | # Japan Intl +81 X XXXX XXXX |
|
\+81\s\d{2}\s\d{4}\s\d{4} | # Japan Intl +81 XX XXXX XXXX |
|
0\d\s\d{4}\s\d{4} | # Japan STD 0X XXXX XXXX |
|
\+81\d{10} | # +81 XXXXXXXXXX |
|
\+81\d{9} | # +81 XXXXXXXXX |
|
0\d{9} | # 0XXXXXXXXX |
|
\+55\s\d{2}\s\d{5}-\d{4} | # Brazil Intl +55 XX XXXXX-XXXX |
|
\+55\s\d{2}\s\d{4}-\d{4} | # Brazil Intl +55 XX XXXX-XXXX |
|
0\d{2}\s\d{4}\s\d{4} | # Brazil STD 0XX XXXX XXXX |
|
\+55\d{11} | # +55 XXXXXXXXXXX |
|
\+55\d{10} | # +55 XXXXXXXXXX |
|
0\d{10} | # 0XXXXXXXXXX |
|
\+33\s\d\s\d{2}\s\d{2}\s\d{2}\s\d{2} | # France Intl +33 X XX XX XX XX |
|
0\d\s\d{2}\s\d{2}\s\d{2}\s\d{2} | # France STD 0X XX XX XX XX |
|
\+33\d{9} | # +33 XXXXXXXXX |
|
0\d{9} | # 0XXXXXXXXX |
|
\+7\s\d{3}\s\d{3}-\d{2}-\d{2} | # Russia Intl +7 XXX XXX-XX-XX |
|
8\s\d{3}\s\d{3}-\d{2}-\d{2} | # Russia STD 8 XXX XXX-XX-XX |
|
\+7\d{10} | # +7 XXXXXXXXXX |
|
8\d{10} | # 8 XXXXXXXXXX |
|
\+27\s\d{2}\s\d{3}\s\d{4} | # South Africa Intl +27 XX XXX XXXX |
|
0\d{2}\s\d{3}\s\d{4} | # South Africa STD 0XX XXX XXXX |
|
\+27\d{9} | # +27 XXXXXXXXX |
|
0\d{9} | # 0XXXXXXXXX |
|
\+52\s\d{3}\s\d{3}\s\d{4} | # Mexico Intl +52 XXX XXX XXXX |
|
\+52\s\d{2}\s\d{4}\s\d{4} | # Mexico Intl +52 XX XXXX XXXX |
|
01\s\d{3}\s\d{4} | # Mexico STD 01 XXX XXXX |
|
\+52\d{10} | # +52 XXXXXXXXXX |
|
01\d{7} | # 01 XXXXXXX |
|
\+234\s\d{3}\s\d{3}\s\d{4} | # Nigeria Intl +234 XXX XXX XXXX |
|
0\d{3}\s\d{3}\s\d{4} | # Nigeria STD 0XXX XXX XXXX |
|
\+234\d{10} | # +234 XXXXXXXXXX |
|
0\d{10} | # 0XXXXXXXXXX |
|
\+971\s\d\s\d{3}\s\d{4} | # UAE Intl +971 X XXX XXXX |
|
0\d\s\d{3}\s\d{4} | # UAE STD 0X XXX XXXX |
|
\+971\d{8} | # +971 XXXXXXXX |
|
0\d{8} | # 0XXXXXXXX |
|
\+54\s9\s\d{3}\s\d{3}\s\d{4} | # Argentina Intl +54 9 XXX XXX XXXX |
|
\+54\s\d{1}\s\d{4}\s\d{4} | # Argentina Intl +54 X XXXX XXXX |
|
0\d{3}\s\d{4} | # Argentina STD 0XXX XXXX |
|
\+54\d{10} | # +54 9 XXXXXXXXXX |
|
\+54\d{9} | # +54 XXXXXXXXX |
|
0\d{7} | # 0XXXXXXX |
|
\+966\s\d\s\d{3}\s\d{4} | # Saudi Intl +966 X XXX XXXX |
|
0\d\s\d{3}\s\d{4} | # Saudi STD 0X XXX XXXX |
|
\+966\d{8} | # +966 XXXXXXXX |
|
0\d{8} | # 0XXXXXXXX |
|
\+1\d{10} | # +1 XXXXXXXXXX |
|
\+1\s\d{3}\s\d{3}\s\d{4} | # +1 XXX XXX XXXX |
|
\d{5}\s\d{5} | # XXXXX XXXXX |
|
\d{10} | # XXXXXXXXXX |
|
\+44\d{10} | # +44 XXXXXXXXXX |
|
0\d{10} | # 0XXXXXXXXXX |
|
\+61\d{9} | # +61 XXXXXXXXX |
|
0\d{9} | # 0XXXXXXXXX |
|
\+91\d{10} | # +91 XXXXXXXXXX |
|
\+49\d{12} | # +49 XXXXXXXXXXXX |
|
\+49\d{10} | # +49 XXXXXXXXXX |
|
0\d{11} | # 0XXXXXXXXXXX |
|
\+86\d{11} | # +86 XXXXXXXXXXX |
|
\+81\d{10} | # +81 XXXXXXXXXX |
|
\+81\d{9} | # +81 XXXXXXXXX |
|
0\d{9} | # 0XXXXXXXXX |
|
\+55\d{11} | # +55 XXXXXXXXXXX |
|
\+55\d{10} | # +55 XXXXXXXXXX |
|
0\d{10} | # 0XXXXXXXXXX |
|
\+33\d{9} | # +33 XXXXXXXXX |
|
0\d{9} | # 0XXXXXXXXX |
|
\+7\d{10} | # +7 XXXXXXXXXX |
|
8\d{10} | # 8 XXXXXXXXXX |
|
\+27\d{9} | # +27 XXXXXXXXX |
|
0\d{9} | # 0XXXXXXXXX (South Africa STD) |
|
\+52\d{10} | # +52 XXXXXXXXXX |
|
01\d{7} | # 01 XXXXXXX |
|
\+234\d{10} | # +234 XXXXXXXXXX |
|
0\d{10} | # 0XXXXXXXXXX |
|
\+971\d{8} | # +971 XXXXXXXX |
|
0\d{8} | # 0XXXXXXXX |
|
\+54\s9\s\d{10} | # +54 9 XXXXXXXXXX |
|
\+54\d{9} | # +54 XXXXXXXXX |
|
0\d{7} | # 0XXXXXXX |
|
\+966\d{8} | # +966 XXXXXXXX |
|
0\d{8} # 0XXXXXXXX |
|
\+\d{3}-\d{3}-\d{4} |
|
) |
|
|
|
''',re.VERBOSE) |
|
|
|
|
|
email_regex = re.compile(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b') |
|
|
|
|
|
link_regex = re.compile(r'\b(?:https?:\/\/)?(?:www\.)[a-zA-Z0-9-]+\.(?:com|co\.in|co|io|org|net|edu|gov|mil|int|uk|us|in|de|au|app|tech|xyz|info|biz|fr|dev)\b') |
|
|
|
|
|
phone_numbers = [num for num in combined_phone_regex.findall(text) if len(num) >= 5] |
|
|
|
emails = email_regex.findall(text) |
|
|
|
links_RE = [link for link in link_regex.findall(text) if len(link)>=11] |
|
|
|
|
|
links_RE = [link for link in links_RE if not any(email in link for email in emails)] |
|
|
|
return { |
|
"phone_numbers": phone_numbers, |
|
"emails": emails, |
|
"links_RE": links_RE |
|
} |
|
|
|
|
|
def process_extracted_text(extracted_text): |
|
|
|
data = json.dumps(extracted_text, indent=4) |
|
data = json.loads(data) |
|
|
|
|
|
combined_results = { |
|
"phone_numbers": [], |
|
"emails": [], |
|
"links_RE": [] |
|
} |
|
|
|
|
|
for filename, text in data.items(): |
|
contact_details = extract_contact_details(text) |
|
|
|
combined_results["phone_numbers"].extend(contact_details["phone_numbers"]) |
|
combined_results["emails"].extend(contact_details["emails"]) |
|
combined_results["links_RE"].extend(contact_details["links_RE"]) |
|
|
|
|
|
|
|
combined_results_json = combined_results |
|
|
|
|
|
print("Combined contact details in JSON format:") |
|
print(combined_results_json) |
|
|
|
return combined_results_json |
|
|
|
|
|
def remove_duplicates_case_insensitive(data_dict): |
|
for key, value_list in data_dict.items(): |
|
seen = set() |
|
unique_list = [] |
|
|
|
for item in value_list: |
|
if item.lower() not in seen: |
|
unique_list.append(item) |
|
seen.add(item.lower()) |
|
|
|
|
|
data_dict[key] = unique_list |
|
return data_dict |
|
|
|
|
|
def process_resume_data(LLMdata,cont_data,extracted_text): |
|
|
|
|
|
unique_emails = [] |
|
for email in cont_data['emails']: |
|
if not any(email.lower() == existing_email.lower() for existing_email in LLMdata['Email']): |
|
unique_emails.append(email) |
|
|
|
|
|
unique_links = [] |
|
for link in cont_data['links_RE']: |
|
if not any(link.lower() == existing_link.lower() for existing_link in LLMdata['Link']): |
|
unique_links.append(link) |
|
|
|
|
|
normalized_contact = [num[-10:] for num in LLMdata['Contact']] |
|
unique_numbers = [] |
|
for num in cont_data['phone_numbers']: |
|
if num[-10:] not in normalized_contact: |
|
unique_numbers.append(num) |
|
|
|
|
|
LLMdata['Email'] += unique_emails |
|
LLMdata['Link'] += unique_links |
|
LLMdata['Contact'] += unique_numbers |
|
|
|
|
|
LLMdata=remove_duplicates_case_insensitive(LLMdata) |
|
|
|
|
|
processed_data = { |
|
"name": [], |
|
"contact_number": [], |
|
"Designation":[], |
|
"email": [], |
|
"Location": [], |
|
"Link": [], |
|
"Company":[], |
|
"extracted_text": extracted_text |
|
} |
|
|
|
|
|
processed_data['name'].extend(LLMdata.get('Name', None)) |
|
|
|
processed_data['Designation'].extend(LLMdata.get('Designation', [])) |
|
|
|
processed_data['Location'].extend(LLMdata.get('Address', [])) |
|
|
|
processed_data['Company'].extend(LLMdata.get('Company', [])) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
processed_data['email'].extend(LLMdata['Email']) |
|
processed_data['contact_number'].extend(LLMdata['Contact']) |
|
processed_data['Link'].extend(LLMdata['Link']) |
|
|
|
|
|
|
|
keys_to_check = ["name", "contact_number", "Designation", "email", "Location", "Link", "Company"] |
|
|
|
|
|
for key in keys_to_check: |
|
if processed_data[key] == ['Not found'] or processed_data[key] == ['not found']: |
|
processed_data[key] = [] |
|
|
|
return processed_data |