AmrElsayeh commited on
Commit
196a045
·
verified ·
1 Parent(s): 8f8ab7c

Upload 3 files

Browse files
Files changed (2) hide show
  1. app.py +208 -188
  2. post-install.sh +3 -0
app.py CHANGED
@@ -1,189 +1,209 @@
1
- import os
2
- import json
3
- import logging
4
- import cv2
5
- import numpy as np
6
- from PIL import Image
7
- from pdf2image import convert_from_path
8
- from pytesseract import Output, pytesseract
9
- from scipy.ndimage import rotate
10
- from surya.ocr import run_ocr
11
- from surya.model.detection.model import load_model as load_det_model, load_processor as load_det_processor
12
- from surya.model.recognition.model import load_model as load_rec_model
13
- from surya.model.recognition.processor import load_processor as load_rec_processor
14
- import imutils
15
- import shutil
16
- import gradio as gr
17
-
18
- # Configure logging
19
- logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
20
-
21
- # Initialize OCR models
22
- det_processor, det_model = load_det_processor(), load_det_model()
23
- rec_model, rec_processor = load_rec_model(), load_rec_processor()
24
-
25
- class DocumentProcessor:
26
- def __init__(self, output_dir: str = "output"):
27
- self.output_dir = output_dir
28
- self.corrected_images_dir = os.path.join(output_dir, "corrected_images")
29
- self.extracted_text_dir = os.path.join(output_dir, "extracted_text")
30
- self._create_dirs()
31
-
32
- def _create_dirs(self):
33
- """Create output directories if they don't exist."""
34
- os.makedirs(self.corrected_images_dir, exist_ok=True)
35
- os.makedirs(self.extracted_text_dir, exist_ok=True)
36
-
37
- def process_document(self, input_path: str):
38
- """
39
- Process a PDF or image to:
40
- 1. Correct image skew and rotation.
41
- 2. Extract text using OCR.
42
- 3. Save corrected images and extracted text.
43
- """
44
- try:
45
- if input_path.endswith(".pdf"):
46
- images = self._convert_pdf_to_images(input_path)
47
- else:
48
- images = [Image.open(input_path)]
49
-
50
- # Run Surya detection and layout
51
- self._run_surya_detection(input_path)
52
-
53
- for i, image in enumerate(images):
54
- logging.info(f"Processing page {i + 1}")
55
- corrected_image = self._correct_image_rotation(image)
56
- extracted_text = self._extract_text(corrected_image)
57
-
58
- # Save results
59
- self._save_results(corrected_image, extracted_text, i + 1)
60
-
61
- except Exception as e:
62
- logging.error(f"Error processing document: {e}")
63
- raise
64
-
65
- def _convert_pdf_to_images(self, pdf_path: str):
66
- """Convert PDF to a list of images."""
67
- logging.info(f"Converting PDF to images: {pdf_path}")
68
- return convert_from_path(pdf_path)
69
-
70
- def _run_surya_detection(self, input_path: str):
71
- """Run Surya detection and layout commands."""
72
- logging.info("Running Surya detection and layout")
73
- detected_text_dir = "/home/output/Detected_Text_Line"
74
- detected_layout_dir = "/home/output/Detected_layout"
75
- ocr_dir = "/home/output/OCR"
76
-
77
- # Ensure the results directories exist
78
- os.makedirs(detected_text_dir, exist_ok=True)
79
- os.makedirs(detected_layout_dir, exist_ok=True)
80
- os.makedirs(ocr_dir, exist_ok=True)
81
-
82
- # Step 1: Run surya_detect
83
- os.system(f"surya_detect --results_dir {detected_text_dir} --images {input_path}")
84
-
85
- # Extract the PDF name (without extension)
86
- pdf_name = os.path.splitext(os.path.basename(input_path))[0]
87
-
88
- # Step 2: Remove column files
89
- os.system(f"rm {detected_text_dir}/{pdf_name}/*column*")
90
-
91
- # Step 3: Run surya_layout
92
- os.system(f"surya_layout --results_dir {detected_layout_dir} --images {input_path}")
93
-
94
- # Step 4: Run surya_ocr
95
- os.system(f"surya_ocr --results_dir {ocr_dir} --images {input_path}")
96
-
97
- def _correct_image_rotation(self, image: Image.Image):
98
- """Correct the skew and rotation of the image."""
99
- logging.info("Correcting image rotation")
100
- if isinstance(image, Image.Image):
101
- image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
102
-
103
- # Correct skew
104
- corrected_image = self._correct_skew(image)
105
-
106
- # Correct rotation
107
- results = pytesseract.image_to_osd(
108
- corrected_image,
109
- output_type=Output.DICT,
110
- config='--dpi 300 --psm 0 -c min_characters_to_try=5 -c tessedit_script_lang=Arabic'
111
- )
112
- if results["orientation"] != 0:
113
- corrected_image = imutils.rotate_bound(corrected_image, angle=results["rotate"])
114
-
115
- return Image.fromarray(cv2.cvtColor(corrected_image, cv2.COLOR_BGR2RGB))
116
-
117
- def _correct_skew(self, image: np.ndarray, delta: float = 0.1, limit: int = 3):
118
- """Correct the skew of an image by finding the best angle."""
119
- gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
120
- thresh = cv2.adaptiveThreshold(
121
- gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
122
- cv2.THRESH_BINARY_INV, 41, 15
123
- )
124
-
125
- scores = []
126
- angles = np.arange(-limit, limit + delta, delta)
127
- for angle in angles:
128
- _, score = self._determine_score(thresh, angle)
129
- scores.append(score)
130
-
131
- best_angle = angles[scores.index(max(scores))]
132
-
133
- (h, w) = image.shape[:2]
134
- center = (w // 2, h // 2)
135
- M = cv2.getRotationMatrix2D(center, best_angle, 1.0)
136
- rotated = cv2.warpAffine(
137
- image, M, (w, h), flags=cv2.INTER_LINEAR,
138
- borderMode=cv2.BORDER_CONSTANT, borderValue=(255, 255, 255)
139
- )
140
-
141
- logging.info(f"Detected skew angle: {best_angle} degrees")
142
- return rotated
143
-
144
- def _determine_score(self, arr: np.ndarray, angle: float):
145
- """Rotate the image and calculate the score based on pixel intensity."""
146
- data = rotate(arr, angle, reshape=False, order=0)
147
- histogram = np.sum(data, axis=1, dtype=float)
148
- score = np.sum((histogram[1:] - histogram[:-1]) ** 2, dtype=float)
149
- return histogram, score
150
-
151
- def _extract_text(self, image: Image.Image):
152
- """Extract text from the image using OCR."""
153
- logging.info("Extracting text")
154
- extracted_text_surya = run_ocr([image], [["en"]], det_model, det_processor, rec_model, rec_processor)
155
- surya_text = [line.text for line in extracted_text_surya[0].text_lines]
156
- return "\n".join(surya_text)
157
-
158
- def _save_results(self, corrected_image: Image.Image, extracted_text: str, page_num: int):
159
- """Save corrected images and extracted text."""
160
- # Save corrected image
161
- corrected_image.save(os.path.join(self.corrected_images_dir, f"page_{page_num}_corrected.png"))
162
-
163
- # Save extracted text
164
- with open(os.path.join(self.extracted_text_dir, f"page_{page_num}_text.txt"), "w", encoding="utf-8") as f:
165
- f.write(extracted_text)
166
- logging.info(f"Saved results for page {page_num}")
167
-
168
- # Gradio Interface
169
- def process_document_interface(file):
170
- processor = DocumentProcessor(output_dir="/home/output")
171
- processor.process_document(file.name)
172
- corrected_image_path = os.path.join("/home/output/corrected_images", "page_1_corrected.png")
173
- extracted_text_path = os.path.join("/home/output/extracted_text", "page_1_text.txt")
174
-
175
- with open(extracted_text_path, "r", encoding="utf-8") as f:
176
- extracted_text = f.read()
177
-
178
- return corrected_image_path, extracted_text
179
-
180
- iface = gr.Interface(
181
- fn=process_document_interface,
182
- inputs=gr.File(label="Upload PDF or Image"),
183
- outputs=[gr.Image(label="Corrected Image"), gr.Textbox(label="Extracted Text")],
184
- title="Document Processor",
185
- description="Upload a PDF or image to correct skew/rotation and extract text using OCR."
186
- )
187
-
188
- if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
189
  iface.launch()
 
1
+ import os
2
+ import logging
3
+ import cv2
4
+ import numpy as np
5
+ from PIL import Image
6
+ from pdf2image import convert_from_path
7
+ from pytesseract import Output, pytesseract
8
+ from scipy.ndimage import rotate
9
+ from surya.ocr import run_ocr
10
+ from surya.model.detection.model import load_model as load_det_model, load_processor as load_det_processor
11
+ from surya.model.recognition.model import load_model as load_rec_model
12
+ from surya.model.recognition.processor import load_processor as load_rec_processor
13
+ import imutils
14
+ import gradio as gr
15
+
16
+ # Set the Tesseract path (update this path based on your system)
17
+ pytesseract.pytesseract.tesseract_cmd = r'/usr/bin/tesseract' # Linux
18
+ # pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' # Windows
19
+
20
+ # Configure logging
21
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
22
+
23
+ # Initialize OCR models
24
+ det_processor, det_model = load_det_processor(), load_det_model()
25
+ rec_model, rec_processor = load_rec_model(), load_rec_processor()
26
+
27
+ class DocumentProcessor:
28
+ def __init__(self, output_dir: str = "output"):
29
+ self.output_dir = output_dir
30
+ self.corrected_images_dir = os.path.join(output_dir, "corrected_images")
31
+ self.extracted_text_dir = os.path.join(output_dir, "extracted_text")
32
+ self.detected_text_dir = os.path.join(output_dir, "Detected_Text_Line")
33
+ self.detected_layout_dir = os.path.join(output_dir, "Detected_layout")
34
+ self._create_dirs()
35
+
36
+ def _create_dirs(self):
37
+ """Create output directories if they don't exist."""
38
+ os.makedirs(self.corrected_images_dir, exist_ok=True)
39
+ os.makedirs(self.extracted_text_dir, exist_ok=True)
40
+ os.makedirs(self.detected_text_dir, exist_ok=True)
41
+ os.makedirs(self.detected_layout_dir, exist_ok=True)
42
+
43
+ def process_document(self, input_path: str):
44
+ """
45
+ Process a PDF or image to:
46
+ 1. Correct image skew and rotation.
47
+ 2. Extract text using OCR.
48
+ 3. Save corrected images, detected images, and extracted text.
49
+ """
50
+ try:
51
+ if input_path.endswith(".pdf"):
52
+ images = self._convert_pdf_to_images(input_path)
53
+ else:
54
+ images = [Image.open(input_path)]
55
+
56
+ # Run Surya detection and layout
57
+ self._run_surya_detection(input_path)
58
+
59
+ corrected_images = []
60
+ extracted_texts = []
61
+
62
+ for i, image in enumerate(images):
63
+ logging.info(f"Processing page {i + 1}")
64
+ corrected_image = self._correct_image_rotation(image)
65
+ extracted_text = self._extract_text(corrected_image)
66
+
67
+ # Save results
68
+ self._save_results(corrected_image, extracted_text, i + 1)
69
+
70
+ corrected_images.append(corrected_image)
71
+ extracted_texts.append(extracted_text)
72
+
73
+ return corrected_images, extracted_texts
74
+
75
+ except Exception as e:
76
+ logging.error(f"Error processing document: {e}")
77
+ raise
78
+
79
+ def _convert_pdf_to_images(self, pdf_path: str):
80
+ """Convert PDF to a list of images."""
81
+ logging.info(f"Converting PDF to images: {pdf_path}")
82
+ return convert_from_path(pdf_path)
83
+
84
+ def _run_surya_detection(self, input_path: str):
85
+ """Run Surya detection and layout commands."""
86
+ logging.info("Running Surya detection and layout")
87
+
88
+ # Step 1: Run surya_detect
89
+ os.system(f"surya_detect --results_dir {self.detected_text_dir} --images {input_path}")
90
+
91
+ # Extract the PDF name (without extension)
92
+ pdf_name = os.path.splitext(os.path.basename(input_path))[0]
93
+
94
+ # Step 2: Remove column files
95
+ os.system(f"rm {self.detected_text_dir}/{pdf_name}/*column*")
96
+
97
+ # Step 3: Run surya_layout
98
+ os.system(f"surya_layout --results_dir {self.detected_layout_dir} --images {input_path}")
99
+
100
+ def _correct_image_rotation(self, image: Image.Image):
101
+ """Correct the skew and rotation of the image."""
102
+ logging.info("Correcting image rotation")
103
+ if isinstance(image, Image.Image):
104
+ image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
105
+
106
+ # Correct skew
107
+ corrected_image = self._correct_skew(image)
108
+
109
+ # Correct rotation
110
+ results = pytesseract.image_to_osd(
111
+ corrected_image,
112
+ output_type=Output.DICT,
113
+ config='--dpi 300 --psm 0 -c min_characters_to_try=5 -c tessedit_script_lang=Arabic'
114
+ )
115
+ if results["orientation"] != 0:
116
+ corrected_image = imutils.rotate_bound(corrected_image, angle=results["rotate"])
117
+
118
+ return Image.fromarray(cv2.cvtColor(corrected_image, cv2.COLOR_BGR2RGB))
119
+
120
+ def _correct_skew(self, image: np.ndarray, delta: float = 0.1, limit: int = 3):
121
+ """Correct the skew of an image by finding the best angle."""
122
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
123
+ thresh = cv2.adaptiveThreshold(
124
+ gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
125
+ cv2.THRESH_BINARY_INV, 41, 15
126
+ )
127
+
128
+ scores = []
129
+ angles = np.arange(-limit, limit + delta, delta)
130
+ for angle in angles:
131
+ _, score = self._determine_score(thresh, angle)
132
+ scores.append(score)
133
+
134
+ best_angle = angles[scores.index(max(scores))]
135
+
136
+ (h, w) = image.shape[:2]
137
+ center = (w // 2, h // 2)
138
+ M = cv2.getRotationMatrix2D(center, best_angle, 1.0)
139
+ rotated = cv2.warpAffine(
140
+ image, M, (w, h), flags=cv2.INTER_LINEAR,
141
+ borderMode=cv2.BORDER_CONSTANT, borderValue=(255, 255, 255)
142
+ )
143
+
144
+ logging.info(f"Detected skew angle: {best_angle} degrees")
145
+ return rotated
146
+
147
+ def _determine_score(self, arr: np.ndarray, angle: float):
148
+ """Rotate the image and calculate the score based on pixel intensity."""
149
+ data = rotate(arr, angle, reshape=False, order=0)
150
+ histogram = np.sum(data, axis=1, dtype=float)
151
+ score = np.sum((histogram[1:] - histogram[:-1]) ** 2, dtype=float)
152
+ return histogram, score
153
+
154
+ def _extract_text(self, image: Image.Image):
155
+ """Extract text from the image using OCR."""
156
+ logging.info("Extracting text")
157
+ extracted_text_surya = run_ocr([image], [["en"]], det_model, det_processor, rec_model, rec_processor)
158
+ surya_text = [line.text for line in extracted_text_surya[0].text_lines]
159
+ return "\n".join(surya_text)
160
+
161
+ def _save_results(self, corrected_image: Image.Image, extracted_text: str, page_num: int):
162
+ """Save corrected images and extracted text."""
163
+ # Save corrected image
164
+ corrected_image.save(os.path.join(self.corrected_images_dir, f"page_{page_num}_corrected.png"))
165
+
166
+ # Save extracted text
167
+ with open(os.path.join(self.extracted_text_dir, f"page_{page_num}_text.txt"), "w", encoding="utf-8") as f:
168
+ f.write(extracted_text)
169
+ logging.info(f"Saved results for page {page_num}")
170
+
171
+ # Gradio Interface
172
+ def process_document_interface(file):
173
+ processor = DocumentProcessor(output_dir="output")
174
+ corrected_images, extracted_texts = processor.process_document(file.name)
175
+
176
+ # Get detected images
177
+ pdf_name = os.path.splitext(os.path.basename(file.name))[0]
178
+ detected_text_images = [
179
+ os.path.join(processor.detected_text_dir, pdf_name, f"{pdf_name}_{i}_bbox.png")
180
+ for i in range(len(corrected_images))
181
+ ]
182
+ detected_layout_images = [
183
+ os.path.join(processor.detected_layout_dir, pdf_name, f"{pdf_name}_{i}_bbox.png")
184
+ for i in range(len(corrected_images))
185
+ ]
186
+
187
+ # Prepare outputs
188
+ outputs = []
189
+ for i, (corrected_image, extracted_text, detected_text_image, detected_layout_image) in enumerate(zip(corrected_images, extracted_texts, detected_text_images, detected_layout_images)):
190
+ outputs.append((corrected_image, detected_text_image, detected_layout_image, extracted_text))
191
+
192
+ return outputs
193
+
194
+ # Gradio App
195
+ iface = gr.Interface(
196
+ fn=process_document_interface,
197
+ inputs=gr.File(label="Upload PDF or Image"),
198
+ outputs=[
199
+ gr.Gallery(label="Corrected Images"),
200
+ gr.Gallery(label="Detected Text Images"),
201
+ gr.Gallery(label="Detected Layout Images"),
202
+ gr.Textbox(label="Extracted Text")
203
+ ],
204
+ title="Document Processor",
205
+ description="Upload a PDF or image to correct skew/rotation, detect text/layout, and extract text using OCR."
206
+ )
207
+
208
+ if __name__ == "__main__":
209
  iface.launch()
post-install.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ apt-get update
3
+ apt-get install -y tesseract-ocr poppler-utils