Nassira commited on
Commit
6dad202
·
verified ·
1 Parent(s): 333e296

Create ocr_utils.py

Browse files
Files changed (1) hide show
  1. ocr_utils.py +103 -0
ocr_utils.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import importlib
3
+ import streamlit as st
4
+ import boto3
5
+ from doctr.io import DocumentFile
6
+ from doctr.models import ocr_predictor
7
+ import easyocr
8
+ from shapely.geometry import Polygon
9
+ from paddleocr import PaddleOCR
10
+ import langid
11
+
12
+ # Check if python-bidi is installed
13
+ if importlib.util.find_spec("bidi") is None:
14
+ print("Error: python-bidi is not installed. Please add it to requirements.txt")
15
+ sys.exit(1)
16
+
17
+ # Initialize OCR models outside the main app flow
18
+ @st.cache_resource
19
+ def load_models(language):
20
+ doctr_model = ocr_predictor(pretrained=True)
21
+ easyocr_reader = easyocr.Reader([language])
22
+ paddleocr_reader = PaddleOCR(use_angle_cls=True, lang=language)
23
+ return doctr_model, easyocr_reader, paddleocr_reader
24
+
25
+ # AWS Textract client
26
+ textract_client = boto3.client('textract', region_name='us-west-2')
27
+
28
+ def extract_text_aws(image_bytes):
29
+ try:
30
+ response = textract_client.detect_document_text(Document={'Bytes': image_bytes})
31
+ return [(item['Text'], item['Geometry']['BoundingBox'], item['Confidence'])
32
+ for item in response['Blocks'] if item['BlockType'] == 'WORD']
33
+ except Exception as e:
34
+ st.error(f"Error in AWS Textract: {str(e)}")
35
+ return []
36
+
37
+ def extract_text_doctr(image_path, doctr_model):
38
+ try:
39
+ doc = DocumentFile.from_images(image_path)
40
+ result = doctr_model(doc)
41
+ return [(word.value, word.geometry, word.confidence)
42
+ for block in result.pages[0].blocks for line in block.lines for word in line.words]
43
+ except Exception as e:
44
+ st.error(f"Error in Doctr OCR: {str(e)}")
45
+ return []
46
+
47
+ def extract_text_easyocr(image_path, easyocr_reader):
48
+ try:
49
+ result = easyocr_reader.readtext(image_path)
50
+ return [(detection[1], detection[0], detection[2]) for detection in result]
51
+ except Exception as e:
52
+ st.error(f"Error in EasyOCR: {str(e)}")
53
+ return []
54
+
55
+ def extract_text_paddleocr(image_path, paddleocr_reader):
56
+ try:
57
+ result = paddleocr_reader.ocr(image_path, cls=True)
58
+ return [(line[1][0], line[0], line[1][1]) for line in result[0]]
59
+ except Exception as e:
60
+ st.error(f"Error in PaddleOCR: {str(e)}")
61
+ return []
62
+
63
+ def bbox_to_polygon(bbox):
64
+ if isinstance(bbox, dict): # AWS format
65
+ return Polygon([(bbox['Left'], bbox['Top']),
66
+ (bbox['Left']+bbox['Width'], bbox['Top']),
67
+ (bbox['Left']+bbox['Width'], bbox['Top']+bbox['Height']),
68
+ (bbox['Left'], bbox['Top']+bbox['Height'])])
69
+ elif len(bbox) == 4 and all(isinstance(p, (list, tuple)) for p in bbox): # EasyOCR format
70
+ return Polygon(bbox)
71
+ elif len(bbox) == 2: # Doctr format
72
+ x, y, w, h = bbox[0][0], bbox[0][1], bbox[1][0] - bbox[0][0], bbox[1][1] - bbox[0][1]
73
+ return Polygon([(x, y), (x+w, y), (x+w, y+h), (x, y+h)])
74
+ else:
75
+ raise ValueError(f"Unsupported bbox format: {bbox}")
76
+
77
+ def combine_ocr_results(results, weights):
78
+ combined_words = []
79
+ for method, words in results.items():
80
+ for word, bbox, confidence in words:
81
+ try:
82
+ polygon = bbox_to_polygon(bbox)
83
+ combined_words.append((word, polygon, float(confidence) * weights[method]))
84
+ except Exception as e:
85
+ st.warning(f"Error processing word '{word}' from {method}: {str(e)}")
86
+
87
+ final_words = []
88
+ while combined_words:
89
+ current_word = combined_words.pop(0)
90
+ overlapping = [w for w in combined_words if current_word[1].intersects(w[1])]
91
+ if overlapping:
92
+ best_word = max([current_word] + overlapping, key=lambda x: x[2])
93
+ final_words.append(best_word[0])
94
+ for word in overlapping:
95
+ combined_words.remove(word)
96
+ else:
97
+ final_words.append(current_word[0])
98
+
99
+ return ' '.join(final_words)
100
+
101
+ def detect_language(text):
102
+ language, _ = langid.classify(text)
103
+ return language