Update app.py
Browse files
app.py
CHANGED
|
@@ -1,7 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import numpy as np
|
| 2 |
-
|
|
|
|
|
|
|
| 3 |
from collections import defaultdict
|
| 4 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
def improved_combine_ocr_results(results, weights):
|
| 6 |
combined_words = defaultdict(list)
|
| 7 |
|
|
@@ -41,25 +165,105 @@ def post_process_text(text):
|
|
| 41 |
text = text.replace('|', 'I').replace('0', 'O') # Common OCR confusions
|
| 42 |
return text
|
| 43 |
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
-
#
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
-
#
|
| 58 |
-
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
st.write(f"
|
|
|
|
| 64 |
|
| 65 |
-
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import importlib
|
| 4 |
+
import time
|
| 5 |
+
import streamlit as st
|
| 6 |
+
from PIL import Image
|
| 7 |
+
import boto3
|
| 8 |
+
from doctr.io import DocumentFile
|
| 9 |
+
from doctr.models import ocr_predictor
|
| 10 |
+
import easyocr
|
| 11 |
+
from paddleocr import PaddleOCR
|
| 12 |
+
import langid
|
| 13 |
import numpy as np
|
| 14 |
+
import logging
|
| 15 |
+
from shapely.geometry import Polygon
|
| 16 |
+
import re
|
| 17 |
from collections import defaultdict
|
| 18 |
|
| 19 |
+
# Configure logging
|
| 20 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 21 |
+
|
| 22 |
+
# AWS Textract client
|
| 23 |
+
textract_client = boto3.client('textract', region_name='us-west-2')
|
| 24 |
+
|
| 25 |
+
# Weights for different OCR methods
|
| 26 |
+
weights = {
|
| 27 |
+
'aws': 1.2, # Increased AWS weight
|
| 28 |
+
'doctr': 0.9,
|
| 29 |
+
'easyocr': 0.8,
|
| 30 |
+
'paddleocr': 0.7
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
def load_models(language):
|
| 34 |
+
try:
|
| 35 |
+
doctr_model = ocr_predictor(pretrained=True)
|
| 36 |
+
easyocr_reader = easyocr.Reader([language])
|
| 37 |
+
paddleocr_reader = PaddleOCR(use_angle_cls=True, lang=language)
|
| 38 |
+
return doctr_model, easyocr_reader, paddleocr_reader
|
| 39 |
+
except Exception as e:
|
| 40 |
+
logging.error(f"Error loading models: {str(e)}")
|
| 41 |
+
return None, None, None
|
| 42 |
+
|
| 43 |
+
def extract_text_aws(file_content):
|
| 44 |
+
try:
|
| 45 |
+
response = textract_client.detect_document_text(Document={'Bytes': file_content})
|
| 46 |
+
return [(item['Text'], item['Geometry']['BoundingBox'], item['Confidence'])
|
| 47 |
+
for item in response['Blocks'] if item['BlockType'] == 'WORD']
|
| 48 |
+
except Exception as e:
|
| 49 |
+
logging.error(f"Error in AWS Textract: {str(e)}")
|
| 50 |
+
return []
|
| 51 |
+
|
| 52 |
+
def extract_text_doctr(image, model):
|
| 53 |
+
try:
|
| 54 |
+
doc = DocumentFile.from_images([image])
|
| 55 |
+
result = model(doc)
|
| 56 |
+
return [(word.value, word.geometry, word.confidence)
|
| 57 |
+
for block in result.pages[0].blocks for line in block.lines for word in line.words]
|
| 58 |
+
except Exception as e:
|
| 59 |
+
logging.error(f"Error in Doctr OCR: {str(e)}")
|
| 60 |
+
return []
|
| 61 |
+
|
| 62 |
+
def extract_text_easyocr(image, reader):
|
| 63 |
+
try:
|
| 64 |
+
result = reader.readtext(np.array(image))
|
| 65 |
+
return [(detection[1], detection[0], detection[2]) for detection in result]
|
| 66 |
+
except Exception as e:
|
| 67 |
+
logging.error(f"Error in EasyOCR: {str(e)}")
|
| 68 |
+
return []
|
| 69 |
+
|
| 70 |
+
def extract_text_paddleocr(image, reader):
|
| 71 |
+
try:
|
| 72 |
+
result = reader.ocr(image, cls=True)
|
| 73 |
+
return [(line[1][0], line[0], line[1][1]) for line in result[0]]
|
| 74 |
+
except Exception as e:
|
| 75 |
+
logging.error(f"Error in PaddleOCR: {str(e)}")
|
| 76 |
+
return []
|
| 77 |
+
|
| 78 |
+
def read_text_file(file_path):
|
| 79 |
+
with open(file_path, 'r', encoding='utf-8') as file:
|
| 80 |
+
return file.read()
|
| 81 |
+
|
| 82 |
+
def preprocess_text(text):
|
| 83 |
+
return set(word.lower() for word in text.replace(',', ' ').replace('.', ' ').split())
|
| 84 |
+
|
| 85 |
+
def calculate_metrics(extracted_words, reference_words):
|
| 86 |
+
true_positives = len(extracted_words.intersection(reference_words))
|
| 87 |
+
false_positives = len(extracted_words - reference_words)
|
| 88 |
+
false_negatives = len(reference_words - extracted_words)
|
| 89 |
+
|
| 90 |
+
precision = true_positives / (true_positives + false_positives) if (true_positives + false_positives) > 0 else 0
|
| 91 |
+
recall = true_positives / (true_positives + false_negatives) if (true_positives + false_negatives) > 0 else 0
|
| 92 |
+
f1_score = 2 * (precision * recall) / (precision + recall) if (precision + recall) > 0 else 0
|
| 93 |
+
|
| 94 |
+
return precision, recall, f1_score
|
| 95 |
+
|
| 96 |
+
def bbox_to_polygon(bbox):
|
| 97 |
+
if isinstance(bbox, dict): # Format AWS
|
| 98 |
+
return Polygon([(bbox['Left'], bbox['Top']),
|
| 99 |
+
(bbox['Left']+bbox['Width'], bbox['Top']),
|
| 100 |
+
(bbox['Left']+bbox['Width'], bbox['Top']+bbox['Height']),
|
| 101 |
+
(bbox['Left'], bbox['Top']+bbox['Height'])])
|
| 102 |
+
elif len(bbox) == 4 and all(isinstance(p, (list, tuple)) for p in bbox): # Format EasyOCR
|
| 103 |
+
return Polygon(bbox)
|
| 104 |
+
elif len(bbox) == 2: # Format Doctr
|
| 105 |
+
x, y, w, h = bbox[0][0], bbox[0][1], bbox[1][0] - bbox[0][0], bbox[1][1] - bbox[0][1]
|
| 106 |
+
return Polygon([(x, y), (x+w, y), (x+w, y+h), (x, y+h)])
|
| 107 |
+
else:
|
| 108 |
+
raise ValueError(f"Unsupported bbox format: {bbox}")
|
| 109 |
+
|
| 110 |
+
def simple_similarity(s1, s2):
|
| 111 |
+
s1 = re.sub(r'\W+', '', s1.lower())
|
| 112 |
+
s2 = re.sub(r'\W+', '', s2.lower())
|
| 113 |
+
|
| 114 |
+
if len(s1) < len(s2):
|
| 115 |
+
s1, s2 = s2, s1
|
| 116 |
+
|
| 117 |
+
distances = range(len(s2) + 1)
|
| 118 |
+
for i, c1 in enumerate(s1):
|
| 119 |
+
distances_ = [i+1]
|
| 120 |
+
for j, c2 in enumerate(s2):
|
| 121 |
+
if c1 == c2:
|
| 122 |
+
distances_.append(distances[j])
|
| 123 |
+
else:
|
| 124 |
+
distances_.append(1 + min((distances[j], distances[j+1], distances_[-1])))
|
| 125 |
+
distances = distances_
|
| 126 |
+
|
| 127 |
+
return 1 - (distances[-1] / max(len(s1), len(s2)))
|
| 128 |
+
|
| 129 |
def improved_combine_ocr_results(results, weights):
|
| 130 |
combined_words = defaultdict(list)
|
| 131 |
|
|
|
|
| 165 |
text = text.replace('|', 'I').replace('0', 'O') # Common OCR confusions
|
| 166 |
return text
|
| 167 |
|
| 168 |
+
def detect_language(text):
|
| 169 |
+
try:
|
| 170 |
+
lang, _ = langid.classify(text)
|
| 171 |
+
return lang
|
| 172 |
+
except Exception as e:
|
| 173 |
+
logging.error(f"Error in language detection: {str(e)}")
|
| 174 |
+
return 'en' # Default to English
|
| 175 |
|
| 176 |
+
# Streamlit application
|
| 177 |
+
st.title("OCR Text Extraction and Evaluation")
|
| 178 |
+
|
| 179 |
+
# Directories containing the images and text files
|
| 180 |
+
image_dir = 'Images CV'
|
| 181 |
+
text_dir = 'ground_truth'
|
| 182 |
+
|
| 183 |
+
# List files in the directories
|
| 184 |
+
image_files = [f for f in os.listdir(image_dir) if f.endswith(('.png', '.jpg', '.jpeg'))]
|
| 185 |
+
text_files = [f for f in os.listdir(text_dir) if f.endswith('.txt')]
|
| 186 |
+
|
| 187 |
+
# Initialize variables for averages
|
| 188 |
+
total_precision = 0.0
|
| 189 |
+
total_recall = 0.0
|
| 190 |
+
total_f1 = 0.0
|
| 191 |
+
total_similarity = 0.0
|
| 192 |
+
num_files = 0
|
| 193 |
+
|
| 194 |
+
# Ensure uploaded files are matched
|
| 195 |
+
if len(image_files) == len(text_files):
|
| 196 |
+
for image_filename, text_filename in zip(image_files, text_files):
|
| 197 |
+
start_time = time.time()
|
| 198 |
+
|
| 199 |
+
# Read the image
|
| 200 |
+
image_path = os.path.join(image_dir, image_filename)
|
| 201 |
+
image = Image.open(image_path)
|
| 202 |
+
|
| 203 |
+
# Read text from the corresponding text file
|
| 204 |
+
text_file_path = os.path.join(text_dir, text_filename)
|
| 205 |
+
pre_existing_text = read_text_file(text_file_path)
|
| 206 |
+
|
| 207 |
+
# Detect language of the reference text
|
| 208 |
+
detected_language = detect_language(pre_existing_text)
|
| 209 |
+
|
| 210 |
+
# Load models for the detected language
|
| 211 |
+
doctr_model, easyocr_reader, paddleocr_reader = load_models(detected_language)
|
| 212 |
+
|
| 213 |
+
# Extract text from the image using different OCR methods
|
| 214 |
+
with open(image_path, 'rb') as image_file:
|
| 215 |
+
image_content = image_file.read()
|
| 216 |
+
|
| 217 |
+
results = {
|
| 218 |
+
'aws': extract_text_aws(image_content),
|
| 219 |
+
'doctr': extract_text_doctr(image_path, doctr_model),
|
| 220 |
+
'easyocr': extract_text_easyocr(image, easyocr_reader),
|
| 221 |
+
'paddleocr': extract_text_paddleocr(image, paddleocr_reader)
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
# Combine results from different OCR methods
|
| 225 |
+
combined_text = improved_combine_ocr_results(results, weights)
|
| 226 |
+
combined_text = post_process_text(combined_text)
|
| 227 |
+
|
| 228 |
+
# Calculate precision, recall, and F1 score
|
| 229 |
+
extracted_words = preprocess_text(combined_text)
|
| 230 |
+
reference_words = preprocess_text(pre_existing_text)
|
| 231 |
+
precision, recall, f1_score = calculate_metrics(extracted_words, reference_words)
|
| 232 |
+
|
| 233 |
+
# Calculate similarity score
|
| 234 |
+
similarity_score = simple_similarity(combined_text, pre_existing_text)
|
| 235 |
+
|
| 236 |
+
# Update totals and count
|
| 237 |
+
total_precision += precision
|
| 238 |
+
total_recall += recall
|
| 239 |
+
total_f1 += f1_score
|
| 240 |
+
total_similarity += similarity_score
|
| 241 |
+
num_files += 1
|
| 242 |
+
|
| 243 |
+
# Display results for each file
|
| 244 |
+
st.subheader(f"Results for {image_filename} (Detected Language: {detected_language})")
|
| 245 |
+
st.write(f"Precision: {precision:.2f}")
|
| 246 |
+
st.write(f"Recall: {recall:.2f}")
|
| 247 |
+
st.write(f"F1 Score: {f1_score:.2f}")
|
| 248 |
+
st.write(f"Text Similarity Score: {similarity_score:.2f}")
|
| 249 |
+
|
| 250 |
+
# Display combined text
|
| 251 |
+
st.text_area("Combined OCR Text", combined_text, height=200)
|
| 252 |
+
|
| 253 |
+
# Display reference text
|
| 254 |
+
st.text_area("Reference Text", pre_existing_text, height=200)
|
| 255 |
|
| 256 |
+
# Calculate and display average precision, recall, F1 score, and similarity
|
| 257 |
+
if num_files > 0:
|
| 258 |
+
average_precision = total_precision / num_files
|
| 259 |
+
average_recall = total_recall / num_files
|
| 260 |
+
average_f1 = total_f1 / num_files
|
| 261 |
+
average_similarity = total_similarity / num_files
|
| 262 |
|
| 263 |
+
st.write(f"\nAverage Precision: {average_precision:.2f}")
|
| 264 |
+
st.write(f"Average Recall: {average_recall:.2f}")
|
| 265 |
+
st.write(f"Average F1 Score: {average_f1:.2f}")
|
| 266 |
+
st.write(f"Average Text Similarity Score: {average_similarity:.2f}")
|
| 267 |
|
| 268 |
+
else:
|
| 269 |
+
st.write("The number of images and text files do not match.")
|