-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathocr_app.py
More file actions
303 lines (251 loc) · 9.6 KB
/
ocr_app.py
File metadata and controls
303 lines (251 loc) · 9.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
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
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
"""
PDF OCR Application
Converts scanned/image PDFs to searchable text PDFs using OCRmyPDF.
"""
import subprocess
import sys
import os
import threading
from pathlib import Path
from tkinter import filedialog, messagebox
import customtkinter as ctk
# Configure Tesseract and Ghostscript paths for Windows
TESSERACT_PATH = r"C:\Program Files\Tesseract-OCR"
GHOSTSCRIPT_PATH = r"C:\Program Files\gs\gs10.03.0\bin"
# Add both to PATH
extra_paths = []
if os.path.exists(TESSERACT_PATH):
extra_paths.append(TESSERACT_PATH)
if os.path.exists(GHOSTSCRIPT_PATH):
extra_paths.append(GHOSTSCRIPT_PATH)
if extra_paths:
os.environ["PATH"] = os.pathsep.join(extra_paths) + os.pathsep + os.environ.get("PATH", "")
class OCRApp(ctk.CTk):
def __init__(self):
super().__init__()
# Configure window
self.title("PDF OCR Converter")
self.geometry("600x500")
self.minsize(500, 400)
# Set appearance
ctk.set_appearance_mode("dark")
ctk.set_default_color_theme("blue")
# Variables
self.selected_files = []
self.is_processing = False
# Create UI
self.create_widgets()
def create_widgets(self):
# Main container
self.main_frame = ctk.CTkFrame(self, fg_color="transparent")
self.main_frame.pack(fill="both", expand=True, padx=20, pady=20)
# Title
self.title_label = ctk.CTkLabel(
self.main_frame,
text="📄 PDF OCR Converter",
font=ctk.CTkFont(size=28, weight="bold")
)
self.title_label.pack(pady=(0, 5))
# Subtitle
self.subtitle_label = ctk.CTkLabel(
self.main_frame,
text="Convert scanned PDFs to searchable text PDFs",
font=ctk.CTkFont(size=14),
text_color="gray"
)
self.subtitle_label.pack(pady=(0, 20))
# Select files button
self.select_btn = ctk.CTkButton(
self.main_frame,
text="📁 Select PDF Files",
command=self.select_files,
height=45,
font=ctk.CTkFont(size=15)
)
self.select_btn.pack(fill="x", pady=(0, 15))
# Files list frame
self.files_frame = ctk.CTkFrame(self.main_frame)
self.files_frame.pack(fill="both", expand=True, pady=(0, 15))
self.files_label = ctk.CTkLabel(
self.files_frame,
text="Selected Files:",
font=ctk.CTkFont(size=13, weight="bold"),
anchor="w"
)
self.files_label.pack(fill="x", padx=10, pady=(10, 5))
# Scrollable file list
self.files_textbox = ctk.CTkTextbox(
self.files_frame,
height=150,
font=ctk.CTkFont(size=12)
)
self.files_textbox.pack(fill="both", expand=True, padx=10, pady=(0, 10))
self.files_textbox.insert("1.0", "No files selected...")
self.files_textbox.configure(state="disabled")
# Options frame
self.options_frame = ctk.CTkFrame(self.main_frame, fg_color="transparent")
self.options_frame.pack(fill="x", pady=(0, 15))
# Language selection
self.lang_label = ctk.CTkLabel(
self.options_frame,
text="OCR Language:",
font=ctk.CTkFont(size=13)
)
self.lang_label.pack(side="left", padx=(0, 10))
self.lang_var = ctk.StringVar(value="eng+ara")
self.lang_dropdown = ctk.CTkOptionMenu(
self.options_frame,
variable=self.lang_var,
values=["eng", "ara", "eng+ara", "deu", "fra", "spa", "chi_sim", "jpn"],
width=150
)
self.lang_dropdown.pack(side="left")
# Skip text checkbox
self.skip_text_var = ctk.BooleanVar(value=True)
self.skip_text_cb = ctk.CTkCheckBox(
self.options_frame,
text="Skip pages with text",
variable=self.skip_text_var
)
self.skip_text_cb.pack(side="right")
# Progress bar
self.progress = ctk.CTkProgressBar(self.main_frame)
self.progress.pack(fill="x", pady=(0, 10))
self.progress.set(0)
# Status label
self.status_label = ctk.CTkLabel(
self.main_frame,
text="Ready",
font=ctk.CTkFont(size=12),
text_color="gray"
)
self.status_label.pack(pady=(0, 15))
# Convert button
self.convert_btn = ctk.CTkButton(
self.main_frame,
text="🚀 Convert to Searchable PDF",
command=self.start_conversion,
height=50,
font=ctk.CTkFont(size=16, weight="bold"),
fg_color="#2d8a2d",
hover_color="#238a23"
)
self.convert_btn.pack(fill="x")
def select_files(self):
files = filedialog.askopenfilenames(
title="Select PDF Files",
filetypes=[("PDF files", "*.pdf"), ("All files", "*.*")]
)
if files:
self.selected_files = list(files)
self.update_file_list()
def update_file_list(self):
self.files_textbox.configure(state="normal")
self.files_textbox.delete("1.0", "end")
if self.selected_files:
for i, f in enumerate(self.selected_files, 1):
self.files_textbox.insert("end", f"{i}. {Path(f).name}\n")
else:
self.files_textbox.insert("1.0", "No files selected...")
self.files_textbox.configure(state="disabled")
def start_conversion(self):
if not self.selected_files:
messagebox.showwarning("No Files", "Please select PDF files first!")
return
if self.is_processing:
return
self.is_processing = True
self.convert_btn.configure(state="disabled", text="Processing...")
self.select_btn.configure(state="disabled")
# Run conversion in a separate thread
thread = threading.Thread(target=self.convert_files)
thread.daemon = True
thread.start()
def convert_files(self):
total = len(self.selected_files)
successful = 0
failed = []
for i, input_file in enumerate(self.selected_files):
input_path = Path(input_file)
output_path = input_path.parent / f"{input_path.stem}_ocr.pdf"
self.update_status(f"Processing {i+1}/{total}: {input_path.name}")
self.update_progress((i) / total)
try:
# Build ocrmypdf command
cmd = [
sys.executable, "-m", "ocrmypdf",
"-l", self.lang_var.get(),
"--output-type", "pdf"
]
if self.skip_text_var.get():
cmd.append("--skip-text")
cmd.extend([str(input_path), str(output_path)])
# Run ocrmypdf
result = subprocess.run(
cmd,
capture_output=True,
text=True,
creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
)
if result.returncode == 0:
successful += 1
elif result.returncode == 6: # Already has text
successful += 1 # Still counts as success
else:
failed.append(f"{input_path.name}: {result.stderr[:100]}")
except Exception as e:
failed.append(f"{input_path.name}: {str(e)}")
self.update_progress(1.0)
self.finish_conversion(successful, total, failed)
def update_status(self, text):
self.after(0, lambda: self.status_label.configure(text=text))
def update_progress(self, value):
self.after(0, lambda: self.progress.set(value))
def finish_conversion(self, successful, total, failed):
def update_ui():
self.is_processing = False
self.convert_btn.configure(state="normal", text="🚀 Convert to Searchable PDF")
self.select_btn.configure(state="normal")
self.status_label.configure(text="Ready")
if failed:
msg = f"Converted {successful}/{total} files.\n\nFailed:\n" + "\n".join(failed[:5])
if len(failed) > 5:
msg += f"\n... and {len(failed) - 5} more"
messagebox.showwarning("Conversion Complete", msg)
else:
messagebox.showinfo("Success", f"Successfully converted {successful} file(s)!\n\nOutput files saved with '_ocr' suffix.")
self.after(0, update_ui)
def check_tesseract():
"""Check if Tesseract is installed and accessible."""
import shutil
from tkinter import Tk, messagebox
tesseract_path = shutil.which("tesseract")
if tesseract_path is None:
# Check common Windows installation paths
common_paths = [
r"C:\Program Files\Tesseract-OCR\tesseract.exe",
r"C:\Program Files (x86)\Tesseract-OCR\tesseract.exe",
]
for path in common_paths:
if os.path.exists(path):
return True
# Tesseract not found - show error
root = Tk()
root.withdraw()
messagebox.showerror(
"Tesseract Not Found",
"Tesseract OCR is required but not installed.\n\n"
"Please install it from:\n"
"https://github.com/UB-Mannheim/tesseract/wiki\n\n"
"After installing, restart this application."
)
root.destroy()
return False
return True
def main():
if not check_tesseract():
return
app = OCRApp()
app.mainloop()
if __name__ == "__main__":
main()