Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142import sysimport importlibimport streamlit as stfrom PIL import Imageimport boto3import osfrom doctr.io import DocumentFilefrom doctr.models import ocr_predictorimport easyocrimport numpy as npfrom shapely.geometry import Polygonfrom paddleocr import PaddleOCR
# Check if python-bidi is installedif importlib.util.find_spec("bidi") is None: print("Error: python-bidi is not installed. Please add it to requirements.txt") sys.exit(1)
# Initialize OCR models outside the main app flow@st.cache_resourcedef load_models(): doctr_model = ocr_predictor(pretrained=True) easyocr_reader = easyocr.Reader(['en']) paddleocr_reader = PaddleOCR(use_angle_cls=True, lang='en') return doctr_model, easyocr_reader, paddleocr_reader
doctr_model, easyocr_reader, paddleocr_reader = load_models()
# AWS Textract clienttextract_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_easyocr(image_path): try: result = easyocr_reader.readtext(image_path) return [(detection[1], detection[0], detection[2]) for detection in result] except Exception as e: st.error(f"Error in EasyOCR: {str(e)}") return []
def extract_text_paddleocr(image_path): try: result = paddleocr_reader.ocr(image_path, cls=True) return [(line[1][0], line[0], line[1][1]) for line in result[0]] 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): # EasyOCR 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"), "easyocr": extract_text_easyocr("temp_cv_image.png"), "paddleocr": extract_text_paddleocr("temp_cv_image.png"), }
weights = {"aws": 0.4, "doctr": 0.3, "easyocr": 0.2, "paddleocr": 0.1} 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()app.pyAdded+142