all_code / ocr_extractor.py
Nassira's picture
Update ocr_extractor.py
aba4f30 verified
Raw History Blame Contribute Delete
4.19 kB
import os
import json
import tempfile
from PIL import Image
import pytesseract
import pdf2image
import boto3
import easyocr
import paddleocr
from doctr.models import ocr_predictor
from doctr.io import DocumentFile
from collections import defaultdict
import streamlit as st
# Charger les variables d'environnement pour AWS
aws_access_key_id = os.environ.get('AWS_ACCESS_KEY_ID')
aws_secret_access_key = os.environ.get('AWS_SECRET_ACCESS_KEY')
@st.cache_data
def load_weights(json_file):
with open(json_file, 'r') as file:
return json.load(file)
def aws_textract(file_path):
client = boto3.client('textract',
region_name='eu-west-3',
aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key)
with open(file_path, 'rb') as file:
response = client.detect_document_text(Document={'Bytes': file.read()})
return [(item['Text'], item['Geometry']['BoundingBox']) for item in response['Blocks'] if item['BlockType'] == 'WORD']
def doctr_ocr(file_path):
model = ocr_predictor(pretrained=True)
doc = DocumentFile.from_images(file_path)
result = model(doc)
return [(word.value, word.geometry) for block in result.pages for line in block.lines for word in line.words]
def easyocr_extract(file_path):
reader = easyocr.Reader(['all']) # 'all' pour prendre en charge toutes les langues disponibles
result = reader.readtext(file_path)
return [(text, bbox) for bbox, text, _ in result]
def paddleocr_extract(file_path):
ocr = paddleocr.PaddleOCR(use_angle_cls=True, lang='ml') # 'ml' pour multilingue
result = ocr.ocr(file_path)
return [(line[1][0], line[0]) for line in result]
def extract_text(file_path, method):
extractors = {
'aws': aws_textract,
'doctr': doctr_ocr,
'easyocr': easyocr_extract,
'paddleocr': paddleocr_extract
}
return extractors[method](file_path)
def calculate_overlap(box1, box2):
x1 = max(box1[0], box2[0])
y1 = max(box1[1], box2[1])
x2 = min(box1[0] + box1[2], box2[0] + box2[2])
y2 = min(box1[1] + box1[3], box2[1] + box2[3])
if x2 <= x1 or y2 <= y1:
return 0
overlap_area = (x2 - x1) * (y2 - y1)
box1_area = box1[2] * box1[3]
box2_area = box2[2] * box2[3]
return overlap_area / min(box1_area, box2_area)
def weighted_vote(results, weights):
word_votes = defaultdict(float)
for method, words in results.items():
for word, bbox in words:
found_match = False
for existing_word in word_votes:
if calculate_overlap(bbox, existing_word[1]) > 0.5: # 50% overlap
word_votes[existing_word] += weights[method]
found_match = True
break
if not found_match:
word_votes[(word, bbox)] += weights[method]
sorted_words = sorted(word_votes.items(), key=lambda x: (x[1], x[0][1][0], x[0][1][1]), reverse=True)
return [word for (word, _), _ in sorted_words]
def process_file(file, weights_file):
weights = load_weights(weights_file)
with tempfile.NamedTemporaryFile(delete=True, suffix=os.path.splitext(file.name)[1]) as temp_file:
temp_file.write(file.getvalue())
temp_file_path = temp_file.name
if file.name.lower().endswith('.pdf'):
images = pdf2image.convert_from_path(temp_file_path)
texts = []
for i, image in enumerate(images):
with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as img_temp_file:
temp_image_path = img_temp_file.name
image.save(temp_image_path, 'PNG')
results = {method: extract_text(temp_image_path, method) for method in weights.keys()}
texts.extend(weighted_vote(results, weights))
os.remove(temp_image_path)
extracted_text = ' '.join(texts)
else:
results = {method: extract_text(temp_file_path, method) for method in weights.keys()}
extracted_text = ' '.join(weighted_vote(results, weights))
os.remove(temp_file_path)
return extracted_text