-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdesktop_app.py
More file actions
303 lines (243 loc) · 11 KB
/
desktop_app.py
File metadata and controls
303 lines (243 loc) · 11 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
import os
import tempfile
import zipfile
import threading
import queue
import re
import sys
import tkinter as tk
from tkinter import filedialog, messagebox
from tkinter import ttk
import fitz # PyMuPDF
import cv2
import numpy as np
# --- Core Vision Logic ---
def _nms_iou(boxes, iou_thresh=0.4):
"""Non-Maximum Suppression using Intersection over Union."""
if not boxes: return []
boxes = np.array(boxes, dtype=float)
x1 = boxes[:,0]; y1 = boxes[:,1]
x2 = x1 + boxes[:,2]; y2 = y1 + boxes[:,3]
areas = boxes[:,4]
order = areas.argsort()[::-1]
keep = []
while order.size > 0:
i = order[0]
keep.append(boxes[i])
xx1 = np.maximum(x1[i], x1[order[1:]])
yy1 = np.maximum(y1[i], y1[order[1:]])
xx2 = np.minimum(x2[i], x2[order[1:]])
yy2 = np.minimum(y2[i], y2[order[1:]])
w = np.maximum(0.0, xx2 - xx1)
h = np.maximum(0.0, yy2 - yy1)
inter = w * h
iou = inter / (areas[i] + areas[order[1:]] - inter + 1e-9)
inds = np.where(iou <= iou_thresh)[0] + 1
order = order[inds]
return [list(map(int, k[:5])) for k in keep]
def _reading_order_sort(boxes, rtl=False):
"""Sorts panels into reading order dynamically based on median panel height."""
if not boxes: return []
for b in boxes:
b['cy'] = b['y'] + b['height'] / 2.0
med_h = np.median([b['height'] for b in boxes])
row_tol = max(10, 0.5 * med_h)
rows = []
for b in sorted(boxes, key=lambda d: d['cy']):
placed = False
for row in rows:
if abs(row['cy'] - b['cy']) <= row_tol:
row['items'].append(b)
row['cy'] = np.mean([x['cy'] for x in row['items']])
placed = True
break
if not placed:
rows.append({'cy': b['cy'], 'items': [b]})
rows.sort(key=lambda r: r['cy'])
for r in rows:
r['items'].sort(key=lambda d: (-d['x'] if rtl else d['x']))
ordered = [b for r in rows for b in r['items']]
for b in ordered:
b.pop('cy', None)
return ordered
def detect_panels_from_img(img, rtl=False):
if img is None: return []
h, w = img.shape[:2]
page_area = float(w * h)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, otsu = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
white_ratio = (otsu == 255).mean()
if white_ratio < 0.15 or white_ratio > 0.85:
bin_img = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, blockSize=31, C=5)
else:
bin_img = otsu
inv = cv2.bitwise_not(bin_img)
k = max(3, int(round(min(w, h) * 0.003)))
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (k, k))
closed = cv2.morphologyEx(inv, cv2.MORPH_CLOSE, kernel, iterations=1)
# Use RETR_EXTERNAL to ignore speech bubbles inside panels
contours, _ = cv2.findContours(closed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cand = []
for cnt in contours:
x, y, bw, bh = cv2.boundingRect(cnt)
area = float(bw * bh)
if area < 0.02 * page_area or area > 0.90 * page_area: continue
ar = bw / (bh + 1e-9)
if ar < 0.15 or ar > 6.5: continue
cand.append([x, y, bw, bh, area])
kept = _nms_iou(cand, iou_thresh=0.4)
panels = []
pad = max(5, int(round(0.005 * min(w, h))))
for x, y, bw, bh, _ in kept:
# Correctly bound the math so crops don't exceed image dimensions
px = max(0, x - pad)
py = max(0, y - pad)
pw = min(w - px, bw + 2 * pad)
ph = min(h - py, bh + 2 * pad)
panels.append({"x": int(px), "y": int(py), "width": int(pw), "height": int(ph)})
return _reading_order_sort(panels, rtl=rtl)
def _natural_key(s):
return [int(t) if t.isdigit() else t.lower() for t in re.split(r'(\d+)', s)]
# --- Processing Engine ---
def process_comic(input_path, output_path, status_q):
try:
with tempfile.TemporaryDirectory() as temp_dir:
extract_dir = os.path.join(temp_dir, "pages")
output_dir = os.path.join(temp_dir, "panels")
os.makedirs(extract_dir)
os.makedirs(output_dir)
status_q.put(("status", "Extracting pages at 300 DPI... (This takes a moment)"))
if input_path.lower().endswith('.cbz'):
with zipfile.ZipFile(input_path, 'r') as zip_ref:
zip_ref.extractall(extract_dir)
elif input_path.lower().endswith('.pdf'):
pdf_document = fitz.open(input_path)
for page_num in range(len(pdf_document)):
page = pdf_document.load_page(page_num)
pix = page.get_pixmap(dpi=300)
pix.save(os.path.join(extract_dir, f"page_{page_num:03d}.png"))
image_exts = {'.png', '.jpg', '.jpeg', '.webp'}
extracted_files = []
# Recursive scan for nested folders in CBZs
for rootdir, _, files in os.walk(extract_dir):
for f in files:
if os.path.splitext(f.lower())[1] in image_exts:
extracted_files.append(os.path.join(rootdir, f))
extracted_files.sort(key=lambda p: _natural_key(os.path.relpath(p, extract_dir)))
total_pages = len(extracted_files)
panel_counter = 0
for page_idx, img_file in enumerate(extracted_files):
status_q.put(("status", f"AI Cropping Page {page_idx + 1} of {total_pages}..."))
img = cv2.imread(img_file)
if img is None: continue
full_page_filename = f"{panel_counter:04d}_Page_{page_idx:03d}_Full.jpg"
cv2.imwrite(os.path.join(output_dir, full_page_filename), img, [cv2.IMWRITE_JPEG_QUALITY, 90])
panel_counter += 1
panels = detect_panels_from_img(img, rtl=False)
for p_idx, panel in enumerate(panels):
x, y, w, h = panel['x'], panel['y'], panel['width'], panel['height']
cropped_img = img[y:y+h, x:x+w]
panel_filename = f"{panel_counter:04d}_Page_{page_idx:03d}_Panel_{p_idx+1:02d}.jpg"
cv2.imwrite(os.path.join(output_dir, panel_filename), cropped_img, [cv2.IMWRITE_JPEG_QUALITY, 90])
panel_counter += 1
status_q.put(("status", "Zipping final mobile comic..."))
with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
for rootdir, _, files in os.walk(output_dir):
for f in files:
zipf.write(os.path.join(rootdir, f), arcname=f)
status_q.put(("done", output_path))
except Exception as e:
status_q.put(("error", str(e)))
# --- Windows UI & Thread Management ---
status_q = queue.Queue()
def poll_status():
"""Safely updates the UI from the background thread's queue."""
try:
while True:
kind, payload = status_q.get_nowait()
if kind == "status":
status_var.set(f"Status: {payload}")
elif kind == "done":
status_var.set("Status: Ready.")
progress_bar.stop() # --- Stop animation ---
messagebox.showinfo("Success!", f"Comic successfully converted and saved to:\n{payload}")
btn_select.config(state=tk.NORMAL)
elif kind == "error":
status_var.set("Status: Error occurred.")
progress_bar.stop() # --- Stop animation ---
messagebox.showerror("Error", f"An error occurred:\n{payload}")
btn_select.config(state=tk.NORMAL)
except queue.Empty:
pass
root.after(100, poll_status)
def select_file():
input_path = filedialog.askopenfilename(
title="Select a Comic File",
filetypes=[("Comic Files", "*.pdf *.cbz")]
)
if not input_path: return
default_out = input_path.rsplit('.', 1)[0] + "_Mobile.cbz"
output_path = filedialog.asksaveasfilename(
title="Save Converted Comic As...",
initialfile=os.path.basename(default_out),
defaultextension=".cbz",
filetypes=[("CBZ File", "*.cbz")]
)
if not output_path: return
btn_select.config(state=tk.DISABLED)
# --- Start the animation (sweeps every 15ms) ---
progress_bar.start(15)
threading.Thread(target=process_comic, args=(input_path, output_path, status_q), daemon=True).start()
def resource_path(relative_path):
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
root = tk.Tk()
root.title("AI Comic Panel Extractor")
root.geometry("600x520")
root.eval('tk::PlaceWindow . center')
try:
icon_path = resource_path(os.path.join("images", "icon.ico"))
root.iconbitmap(icon_path)
except Exception as e:
pass # Silent fail if icon is missing
try:
img_path = resource_path(os.path.join("images", "banner_col.png"))
logo_img = tk.PhotoImage(file=img_path)
root.logo_img = logo_img
tk.Label(root, image=logo_img).pack(pady=(15, 0))
except Exception as e:
pass
# Header Section
ttk.Label(root, text="AI Comic Panel Extractor", font=("Segoe UI", 16, "bold")).pack(pady=(20, 10))
# Description Section
info_frame = ttk.Frame(root)
info_frame.pack(fill=tk.X, padx=40)
# Tighter, punchier copy
desc_text = "• Automatically processes .cbz and .pdf comic files.\n" \
"• Detects individual panels using AI vision.\n" \
"• Exports a mobile-optimized .cbz for panel-by-panel reading."
ttk.Label(info_frame, text=desc_text, font=("Segoe UI", 10), justify=tk.LEFT).pack(fill=tk.X, pady=(0, 15))
# Action Section
action_frame = ttk.Frame(root)
action_frame.pack(pady=10)
ttk.Label(action_frame, text="Select a comic to generate a mobile-optimized file:", font=("Segoe UI", 10)).pack(pady=5)
# Progress Bar
progress_bar = ttk.Progressbar(action_frame, orient="horizontal", length=250, mode="indeterminate")
progress_bar.pack(pady=(0, 10))
# A ttk.Button automatically looks like a native OS button with modern hover states.
btn_select = ttk.Button(action_frame, text="Select Comic File", command=select_file, width=25)
btn_select.pack(pady=10)
status_var = tk.StringVar()
status_var.set("Status: Ready.")
# We keep standard tk.Label here just because it's easier to hardcode the blue text color
tk.Label(action_frame, textvariable=status_var, font=("Segoe UI", 9, "bold"), fg="#005A9E").pack(pady=5)
footer_frame = tk.Frame(root)
footer_frame.pack(side=tk.BOTTOM, fill=tk.X, padx=10, pady=10)
tk.Frame(footer_frame, height=1, bg="#ddd").pack(fill=tk.X, pady=(0, 10))
tk.Label(footer_frame, text="Version: 1.0 (March 2026)", font=("Arial", 8), fg="gray").pack()
tk.Label(footer_frame, text="Karim, ME. (2026). AI Comic Panel Extractor. GitHub. https://github.com/ehsanx/Comic-Panel-Extractor", font=("Arial", 8), fg="gray", wraplength=550, justify=tk.CENTER).pack()
poll_status() # Kick off the queue listener loop
root.mainloop()