Spaces:
Running
Running
Upload 3 files
Browse files- app.py +208 -188
- post-install.sh +3 -0
app.py
CHANGED
@@ -1,189 +1,209 @@
|
|
1 |
-
import os
|
2 |
-
import
|
3 |
-
import
|
4 |
-
import
|
5 |
-
|
6 |
-
from
|
7 |
-
from
|
8 |
-
from
|
9 |
-
from
|
10 |
-
from surya.
|
11 |
-
from surya.model.
|
12 |
-
from surya.model.recognition.
|
13 |
-
|
14 |
-
import
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
#
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
self.
|
30 |
-
self.
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
# Step
|
89 |
-
os.system(f"
|
90 |
-
|
91 |
-
#
|
92 |
-
os.
|
93 |
-
|
94 |
-
# Step
|
95 |
-
os.system(f"
|
96 |
-
|
97 |
-
|
98 |
-
"
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
# Correct
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
""
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
# Save
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|