Nassira commited on
Commit
a0a29b2
·
verified ·
1 Parent(s): a6cbb98

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +202 -44
app.py CHANGED
@@ -1,45 +1,203 @@
1
- # streamlit_app.py
2
-
 
 
3
  import streamlit as st
4
- import pandas as pd
5
- import matplotlib.pyplot as plt
6
- import main # Import your main OCR processing script
7
-
8
- def run_ocr_evaluation():
9
- return main.run_evaluation()
10
-
11
- def main():
12
- st.title("OCR Evaluation Results")
13
-
14
- if st.button("Run OCR Evaluation"):
15
- with st.spinner("Processing images..."):
16
- avg_precision, avg_recall, avg_f1 = run_ocr_evaluation()
17
-
18
- # Display results
19
- st.subheader("Average Metrics")
20
- col1, col2, col3 = st.columns(3)
21
- col1.metric("Precision", f"{avg_precision:.2f}")
22
- col2.metric("Recall", f"{avg_recall:.2f}")
23
- col3.metric("F1 Score", f"{avg_f1:.2f}")
24
-
25
- # Create a bar chart
26
- fig, ax = plt.subplots()
27
- metrics = ['Precision', 'Recall', 'F1 Score']
28
- values = [avg_precision, avg_recall, avg_f1]
29
- ax.bar(metrics, values)
30
- ax.set_ylim(0, 1)
31
- ax.set_ylabel('Score')
32
- ax.set_title('OCR Evaluation Metrics')
33
- for i, v in enumerate(values):
34
- ax.text(i, v + 0.01, f'{v:.2f}', ha='center')
35
- st.pyplot(fig)
36
-
37
- # Display results in a table
38
- df = pd.DataFrame({
39
- 'Metric': metrics,
40
- 'Score': values
41
- })
42
- st.table(df)
43
-
44
- if __name__ == "__main__":
45
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from config import weights # Importing weights from config.py
17
+
18
+ # Configure logging
19
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
20
+
21
+ # AWS Textract client
22
+ textract_client = boto3.client('textract', region_name='us-west-2')
23
+
24
+ def load_models(language):
25
+ try:
26
+ doctr_model = ocr_predictor(pretrained=True)
27
+ easyocr_reader = easyocr.Reader([language])
28
+ paddleocr_reader = PaddleOCR(use_angle_cls=True, lang=language)
29
+ return doctr_model, easyocr_reader, paddleocr_reader
30
+ except Exception as e:
31
+ logging.error(f"Error loading models: {str(e)}")
32
+ return None, None, None
33
+
34
+ def extract_text_doctr(image, model):
35
+ try:
36
+ doc = DocumentFile.from_images([image])
37
+ result = model(doc)
38
+ return [(word.value, word.geometry, word.confidence)
39
+ for block in result.pages[0].blocks for line in block.lines for word in line.words]
40
+ except Exception as e:
41
+ logging.error(f"Error in Doctr OCR: {str(e)}")
42
+ return []
43
+
44
+ def extract_text_easyocr(image, reader):
45
+ try:
46
+ result = reader.readtext(np.array(image))
47
+ return [(detection[1], detection[0], detection[2]) for detection in result]
48
+ except Exception as e:
49
+ logging.error(f"Error in EasyOCR: {str(e)}")
50
+ return []
51
+
52
+ def extract_text_paddleocr(image, reader):
53
+ try:
54
+ result = reader.ocr(image, cls=True)
55
+ return [(line[1][0], line[0], line[1][1]) for line in result[0]]
56
+ except Exception as e:
57
+ logging.error(f"Error in PaddleOCR: {str(e)}")
58
+ return []
59
+
60
+ def read_text_file(file_path):
61
+ with open(file_path, 'r', encoding='utf-8') as file:
62
+ return file.read()
63
+
64
+ def calculate_precision(extracted_text, reference_text):
65
+ extracted_words = extracted_text.split()
66
+ reference_words = reference_text.split()
67
+
68
+ correct_count = sum(1 for word in extracted_words if word in reference_words)
69
+ total_extracted = len(extracted_words)
70
+
71
+ if total_extracted == 0:
72
+ return 0.0 # To handle division by zero if no words were extracted
73
+
74
+ precision = correct_count / total_extracted
75
+ return precision
76
+
77
+ def calculate_recall(extracted_text, reference_text):
78
+ extracted_words = extracted_text.split()
79
+ reference_words = reference_text.split()
80
+
81
+ correct_count = sum(1 for word in extracted_words if word in reference_words)
82
+ total_reference = len(reference_words)
83
+
84
+ if total_reference == 0:
85
+ return 0.0 # To handle division by zero if no words were in reference
86
+
87
+ recall = correct_count / total_reference
88
+ return recall
89
+
90
+ def calculate_f1(precision, recall):
91
+ if precision + recall == 0:
92
+ return 0.0 # To handle division by zero
93
+ f1_score = 2 * (precision * recall) / (precision + recall)
94
+ return 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 combine_ocr_results(results):
111
+ combined_words = []
112
+ for method, words in results.items():
113
+ for word, bbox, confidence in words:
114
+ try:
115
+ polygon = bbox_to_polygon(bbox)
116
+ combined_words.append((word, polygon, float(confidence) * weights[method]))
117
+ except Exception as e:
118
+ logging.error(f"Error processing word '{word}' from {method}: {str(e)}")
119
+
120
+ final_words = []
121
+ while combined_words:
122
+ current_word = combined_words.pop(0)
123
+ overlapping = [w for w in combined_words if current_word[1].intersects(w[1])]
124
+ if overlapping:
125
+ best_word = max([current_word] + overlapping, key=lambda x: x[2])
126
+ final_words.append(best_word[0])
127
+ for word in overlapping:
128
+ combined_words.remove(word)
129
+ else:
130
+ final_words.append(current_word[0])
131
+
132
+ return ' '.join(final_words)
133
+
134
+ # Load models
135
+ language = 'en' # Set default language
136
+ doctr_model, easyocr_reader, paddleocr_reader = load_models(language)
137
+
138
+ # Streamlit application
139
+ st.title("OCR Text Extraction and Evaluation")
140
+
141
+ # Upload image files
142
+ uploaded_files = st.file_uploader("Choose image files", type=["png", "jpg", "jpeg"], accept_multiple_files=True)
143
+
144
+ # Upload ground truth text files
145
+ uploaded_truth_files = st.file_uploader("Choose ground truth text files", type=["txt"], accept_multiple_files=True)
146
+
147
+ if uploaded_files and uploaded_truth_files:
148
+ total_precision = 0.0
149
+ total_recall = 0.0
150
+ total_f1 = 0.0
151
+ num_files = 0
152
+
153
+ for image_file, truth_file in zip(uploaded_files, uploaded_truth_files):
154
+ start_time = time.time()
155
+
156
+ # Read the image
157
+ image = Image.open(image_file)
158
+
159
+ # Extract text from the image using different OCR methods
160
+ results = {
161
+ 'doctr': extract_text_doctr(image_file, doctr_model),
162
+ 'easyocr': extract_text_easyocr(image, easyocr_reader),
163
+ 'paddleocr': extract_text_paddleocr(image, paddleocr_reader)
164
+ }
165
+
166
+ # Combine results from different OCR methods
167
+ combined_text = combine_ocr_results(results)
168
+
169
+ # Read text from the pre-existing text file
170
+ pre_existing_text = truth_file.getvalue().decode('utf-8')
171
+
172
+ # Calculate precision
173
+ precision = calculate_precision(combined_text, pre_existing_text)
174
+ # Calculate recall
175
+ recall = calculate_recall(combined_text, pre_existing_text)
176
+ # Calculate F1 score
177
+ f1_score = calculate_f1(precision, recall)
178
+
179
+ # Add to total precision, recall, F1 score and increment file count
180
+ total_precision += precision
181
+ total_recall += recall
182
+ total_f1 += f1_score
183
+ num_files += 1
184
+
185
+ # Display results for each file
186
+ st.subheader(f"Results for {image_file.name}")
187
+ st.write(f"Extracted Text: {combined_text}")
188
+ st.write(f"Ground Truth Text: {pre_existing_text}")
189
+ st.write(f"Precision: {precision:.2f}")
190
+ st.write(f"Recall: {recall:.2f}")
191
+ st.write(f"F1 Score: {f1_score:.2f}")
192
+
193
+ # Calculate and output the average precision, recall, F1 score
194
+ if num_files > 0:
195
+ average_precision = total_precision / num_files
196
+ average_recall = total_recall / num_files
197
+ average_f1 = total_f1 / num_files
198
+ st.subheader("Average Results")
199
+ st.write(f"Average Precision: {average_precision:.2f}")
200
+ st.write(f"Average Recall: {average_recall:.2f}")
201
+ st.write(f"Average F1 Score: {average_f1:.2f}")
202
+ else:
203
+ st.write("No matching text files found for any images.")