Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from PIL import Image
|
| 3 |
+
import boto3
|
| 4 |
+
import os
|
| 5 |
+
from doctr.io import DocumentFile
|
| 6 |
+
from doctr.models import ocr_predictor
|
| 7 |
+
from paddleocr import PaddleOCR
|
| 8 |
+
import numpy as np
|
| 9 |
+
from shapely.geometry import box, Polygon
|
| 10 |
+
|
| 11 |
+
# Initialize OCR models outside the main app flow
|
| 12 |
+
@st.cache_resource
|
| 13 |
+
def load_models():
|
| 14 |
+
doctr_model = ocr_predictor(pretrained=True)
|
| 15 |
+
paddleocr_model = PaddleOCR(use_angle_cls=True, lang='en')
|
| 16 |
+
return doctr_model, paddleocr_model
|
| 17 |
+
|
| 18 |
+
doctr_model, paddleocr_model = load_models()
|
| 19 |
+
|
| 20 |
+
# AWS Textract client
|
| 21 |
+
textract_client = boto3.client('textract', region_name='us-west-2')
|
| 22 |
+
|
| 23 |
+
def extract_text_aws(image_bytes):
|
| 24 |
+
try:
|
| 25 |
+
response = textract_client.detect_document_text(Document={'Bytes': image_bytes})
|
| 26 |
+
return [(item['Text'], item['Geometry']['BoundingBox'], item['Confidence'])
|
| 27 |
+
for item in response['Blocks'] if item['BlockType'] == 'WORD']
|
| 28 |
+
except Exception as e:
|
| 29 |
+
st.error(f"Error in AWS Textract: {str(e)}")
|
| 30 |
+
return []
|
| 31 |
+
|
| 32 |
+
def extract_text_doctr(image_path):
|
| 33 |
+
try:
|
| 34 |
+
doc = DocumentFile.from_images(image_path)
|
| 35 |
+
result = doctr_model(doc)
|
| 36 |
+
return [(word.value, word.geometry, word.confidence)
|
| 37 |
+
for block in result.pages[0].blocks for line in block.lines for word in line.words]
|
| 38 |
+
except Exception as e:
|
| 39 |
+
st.error(f"Error in Doctr OCR: {str(e)}")
|
| 40 |
+
return []
|
| 41 |
+
|
| 42 |
+
def extract_text_paddleocr(image_path):
|
| 43 |
+
try:
|
| 44 |
+
result = paddleocr_model.ocr(image_path, cls=True)
|
| 45 |
+
return [(line[1][0], line[0], line[1][1]) for line in result[0] if len(line) > 1]
|
| 46 |
+
except Exception as e:
|
| 47 |
+
st.error(f"Error in PaddleOCR: {str(e)}")
|
| 48 |
+
return []
|
| 49 |
+
|
| 50 |
+
def bbox_to_polygon(bbox):
|
| 51 |
+
if isinstance(bbox, dict): # AWS format
|
| 52 |
+
return Polygon([(bbox['Left'], bbox['Top']),
|
| 53 |
+
(bbox['Left']+bbox['Width'], bbox['Top']),
|
| 54 |
+
(bbox['Left']+bbox['Width'], bbox['Top']+bbox['Height']),
|
| 55 |
+
(bbox['Left'], bbox['Top']+bbox['Height'])])
|
| 56 |
+
elif len(bbox) == 4 and all(isinstance(p, (list, tuple)) for p in bbox): # PaddleOCR format
|
| 57 |
+
return Polygon(bbox)
|
| 58 |
+
elif len(bbox) == 2: # Doctr format
|
| 59 |
+
x, y, w, h = bbox[0][0], bbox[0][1], bbox[1][0] - bbox[0][0], bbox[1][1] - bbox[0][1]
|
| 60 |
+
return Polygon([(x, y), (x+w, y), (x+w, y+h), (x, y+h)])
|
| 61 |
+
else:
|
| 62 |
+
raise ValueError(f"Unsupported bbox format: {bbox}")
|
| 63 |
+
|
| 64 |
+
def combine_ocr_results(results, weights):
|
| 65 |
+
combined_words = []
|
| 66 |
+
for method, words in results.items():
|
| 67 |
+
for word, bbox, confidence in words:
|
| 68 |
+
try:
|
| 69 |
+
polygon = bbox_to_polygon(bbox)
|
| 70 |
+
combined_words.append((word, polygon, float(confidence) * weights[method]))
|
| 71 |
+
except Exception as e:
|
| 72 |
+
st.warning(f"Error processing word '{word}' from {method}: {str(e)}")
|
| 73 |
+
|
| 74 |
+
final_words = []
|
| 75 |
+
while combined_words:
|
| 76 |
+
current_word = combined_words.pop(0)
|
| 77 |
+
overlapping = [w for w in combined_words if current_word[1].intersects(w[1])]
|
| 78 |
+
if overlapping:
|
| 79 |
+
best_word = max([current_word] + overlapping, key=lambda x: x[2])
|
| 80 |
+
final_words.append(best_word[0])
|
| 81 |
+
for word in overlapping:
|
| 82 |
+
combined_words.remove(word)
|
| 83 |
+
else:
|
| 84 |
+
final_words.append(current_word[0])
|
| 85 |
+
|
| 86 |
+
return ' '.join(final_words)
|
| 87 |
+
|
| 88 |
+
st.title("CV Text Extraction and Combination")
|
| 89 |
+
|
| 90 |
+
uploaded_file = st.file_uploader("Choose a CV image file", type=["png", "jpg", "jpeg"])
|
| 91 |
+
|
| 92 |
+
if uploaded_file is not None:
|
| 93 |
+
image = Image.open(uploaded_file)
|
| 94 |
+
|
| 95 |
+
with st.spinner('Extracting and combining text from CV...'):
|
| 96 |
+
with open("temp_cv_image.png", "wb") as temp_file:
|
| 97 |
+
temp_file.write(uploaded_file.getvalue())
|
| 98 |
+
|
| 99 |
+
st.image(image, caption='Uploaded CV', use_column_width=True)
|
| 100 |
+
|
| 101 |
+
results = {
|
| 102 |
+
"aws": extract_text_aws(uploaded_file.getvalue()),
|
| 103 |
+
"doctr": extract_text_doctr("temp_cv_image.png"),
|
| 104 |
+
"paddleocr": extract_text_paddleocr("temp_cv_image.png")
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
weights = {"aws": 0.5, "doctr": 0.3, "paddleocr": 0.2}
|
| 108 |
+
combined_text = combine_ocr_results(results, weights)
|
| 109 |
+
|
| 110 |
+
st.subheader("Extracted and Combined Text:")
|
| 111 |
+
st.text_area("Result", combined_text, height=300)
|
| 112 |
+
|
| 113 |
+
st.subheader("Individual OCR Results:")
|
| 114 |
+
for method, result in results.items():
|
| 115 |
+
with st.expander(f"{method.capitalize()} Results"):
|
| 116 |
+
st.write(' '.join([word[0] for word in result]))
|
| 117 |
+
|
| 118 |
+
os.remove("temp_cv_image.png")
|
| 119 |
+
|
| 120 |
+
st.write("Note: This application combines text extracted from the CV using multiple OCR methods to improve accuracy.")
|