off / app.py
Nassira's picture
Create app.py
eb02c5b verified
Raw History Blame Contribute Delete
4.81 kB
import streamlit as st
from PIL import Image
import boto3
import os
from doctr.io import DocumentFile
from doctr.models import ocr_predictor
from paddleocr import PaddleOCR
import numpy as np
from shapely.geometry import Polygon
# Initialize OCR models outside the main app flow
@st.cache_resource
def load_models():
doctr_model = ocr_predictor(pretrained=True)
paddleocr_model = PaddleOCR(use_angle_cls=True, lang='en')
return doctr_model, paddleocr_model
doctr_model, paddleocr_model = load_models()
# AWS Textract client
textract_client = boto3.client('textract', region_name='us-west-2')
def extract_text_aws(image_bytes):
try:
response = textract_client.detect_document_text(Document={'Bytes': image_bytes})
return [(item['Text'], item['Geometry']['BoundingBox'], item['Confidence'])
for item in response['Blocks'] if item['BlockType'] == 'WORD']
except Exception as e:
st.error(f"Error in AWS Textract: {str(e)}")
return []
def extract_text_doctr(image_path):
try:
doc = DocumentFile.from_images(image_path)
result = doctr_model(doc)
return [(word.value, word.geometry, word.confidence)
for block in result.pages[0].blocks for line in block.lines for word in line.words]
except Exception as e:
st.error(f"Error in Doctr OCR: {str(e)}")
return []
def extract_text_paddleocr(image_path):
try:
result = paddleocr_model.ocr(image_path, cls=True)
return [(line[1][0], line[0], line[1][1]) for line in result[0] if len(line) > 1]
except Exception as e:
st.error(f"Error in PaddleOCR: {str(e)}")
return []
def bbox_to_polygon(bbox):
if isinstance(bbox, dict): # AWS format
return Polygon([(bbox['Left'], bbox['Top']),
(bbox['Left']+bbox['Width'], bbox['Top']),
(bbox['Left']+bbox['Width'], bbox['Top']+bbox['Height']),
(bbox['Left'], bbox['Top']+bbox['Height'])])
elif len(bbox) == 4 and all(isinstance(p, (list, tuple)) for p in bbox): # PaddleOCR format
return Polygon(bbox)
elif len(bbox) == 2: # Doctr format
x, y, w, h = bbox[0][0], bbox[0][1], bbox[1][0] - bbox[0][0], bbox[1][1] - bbox[0][1]
return Polygon([(x, y), (x+w, y), (x+w, y+h), (x, y+h)])
else:
raise ValueError(f"Unsupported bbox format: {bbox}")
def combine_ocr_results(results, weights):
combined_words = []
for method, words in results.items():
for word, bbox, confidence in words:
try:
polygon = bbox_to_polygon(bbox)
combined_words.append((word, polygon, float(confidence) * weights[method]))
except Exception as e:
st.warning(f"Error processing word '{word}' from {method}: {str(e)}")
final_words = []
while combined_words:
current_word = combined_words.pop(0)
overlapping = [w for w in combined_words if current_word[1].intersects(w[1])]
if overlapping:
best_word = max([current_word] + overlapping, key=lambda x: x[2])
final_words.append(best_word[0])
for word in overlapping:
combined_words.remove(word)
else:
final_words.append(current_word[0])
return ' '.join(final_words)
def main():
st.title("CV Text Extraction and Combination")
uploaded_file = st.file_uploader("Choose a CV image file", type=["png", "jpg", "jpeg"])
if uploaded_file is not None:
image = Image.open(uploaded_file)
with st.spinner('Extracting and combining text from CV...'):
with open("temp_cv_image.png", "wb") as temp_file:
temp_file.write(uploaded_file.getvalue())
st.image(image, caption='Uploaded CV', use_column_width=True)
results = {
"aws": extract_text_aws(uploaded_file.getvalue()),
"doctr": extract_text_doctr("temp_cv_image.png"),
"paddleocr": extract_text_paddleocr("temp_cv_image.png")
}
weights = {"aws": 0.5, "doctr": 0.3, "paddleocr": 0.2}
combined_text = combine_ocr_results(results, weights)
st.subheader("Extracted and Combined Text:")
st.text_area("Result", combined_text, height=300)
st.subheader("Individual OCR Results:")
for method, result in results.items():
with st.expander(f"{method.capitalize()} Results"):
st.write(' '.join([word[0] for word in result]))
os.remove("temp_cv_image.png")
st.write("Note: This application combines text extracted from the CV using multiple OCR methods to improve accuracy.")
if __name__ == "__main__":
main()