Amr Elsayeh commited on
Commit
0598282
·
1 Parent(s): ad90a3b

Add Application file

Browse files
Files changed (1) hide show
  1. app.py +189 -0
app.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()