-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathgui.py
More file actions
790 lines (710 loc) · 40.3 KB
/
gui.py
File metadata and controls
790 lines (710 loc) · 40.3 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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
import tkinter as tk
from tkinter import filedialog, messagebox, scrolledtext
import threading
import queue
import sys
import os
import shutil
import webbrowser
import locale
from tkinterdnd2 import DND_FILES, TkinterDnD
from converter.generator import convert_mineru_to_ppt, TEXT_CLEANUP_MARGIN_RATIO
from converter.ocr_merge import OCR_FONT_DISTANCE_THRESHOLD, OCR_FONT_DISTANCE_THRESHOLD_LITE
# --- i18n Setup ---
def _resolve_model_variant_value(selected_label: str, i18n: dict[str, str]) -> str:
mapping = {
i18n.get("ocr_model_variant_auto", ""): "auto",
i18n.get("ocr_model_variant_lite", ""): "lite",
i18n.get("ocr_model_variant_server", ""): "server",
}
return mapping.get(selected_label, "auto")
def _default_font_threshold_for_variant(variant: str) -> float:
if variant == "lite":
return OCR_FONT_DISTANCE_THRESHOLD_LITE
return OCR_FONT_DISTANCE_THRESHOLD
TRANSLATIONS = {
"en": {
"app_title": "File to PPT Converter",
"input_file_label": "Input File (PDF/Image, Drag & Drop):",
"json_file_label": "MinerU JSON File (Drag & Drop here):",
"output_file_label": "Output PPTX File:",
"browse_button": "Browse...",
"save_as_button": "Save As...",
"help_button": "?",
"remove_watermark_checkbox": "Remove Watermark",
"debug_images_checkbox": "Generate Debug Images",
"text_cleanup_margin_label": "Text Box Background Expand Ratio:",
"ocr_font_distance_threshold_label": "Font Sensitivity (Higher = Larger Text Box):",
"ocr_model_variant_label": "OCR Model Variant:",
"ocr_model_variant_auto": "Auto (GPU=Server, CPU=Lite)",
"ocr_model_variant_lite": "Lite",
"ocr_model_variant_server": "Server",
"ocr_advanced_show": "Advanced OCR Options ▸",
"ocr_advanced_hide": "Advanced OCR Options ▾",
"ocr_det_db_thresh_label": "OCR Det Thresh (higher = stricter):",
"ocr_det_db_box_thresh_label": "OCR Box Thresh:",
"ocr_det_db_unclip_ratio_label": "OCR Unclip Ratio (lower = tighter):",
"start_button": "Start Conversion",
"converting_button": "Converting...",
"output_folder_button": "Open Output Folder",
"debug_folder_button": "Open Debug Folder",
"log_label": "Log",
"json_help_title": "MinerU JSON Help",
"json_help_text": "This tool requires a JSON file from the MinerU PDF/Image Extractor for all conversions.\n\nClick OK to open the extractor website.",
"error_title": "Error", "info_title": "Info", "complete_title": "Complete",
"error_all_paths": "Please fill in all file paths.",
"error_dir_not_found": "Output directory not found: {}",
"info_no_output": "No output file has been generated yet.",
"info_debug_not_found": "Debug folder not found. Run a conversion with 'Generate Debug Images' enabled to create output_dir/debug.",
"log_success": "\n--- CONVERSION FINISHED SUCCESSFULLY ---\n",
"log_error": "\n--- ERROR ---\n{}\n",
"msg_conversion_complete": "Conversion process has finished. Check the log for details.",
"batch_mode_button": "Batch Mode",
"single_mode_button": "Single Mode",
"add_task_button": "Add Task",
"delete_task_button": "Delete Task",
"start_batch_button": "Start Batch Conversion",
"task_list_label": "Task List",
"error_no_tasks": "Please add at least one task to the list.",
"log_batch_start": "\n--- STARTING BATCH CONVERSION ---\n",
"log_batch_complete": "\n--- BATCH CONVERSION FINISHED ---\n",
"log_task_start": "Starting task {} of {}: {}",
"log_task_complete": "Finished task: {}\n",
"add_task_title": "Add New Task",
"page_range_label": "PDF Page Range (optional, e.g. 1,3,5-8):",
"ok_button": "OK",
"cancel_button": "Cancel",
},
"zh": {
"app_title": "MinerU 转 PPT 转换器",
"input_file_label": "输入文件 (PDF/图片, 可拖拽):",
"json_file_label": "MinerU JSON 文件 (可拖拽):",
"output_file_label": "输出 PPTX 文件:",
"browse_button": "浏览...",
"save_as_button": "另存为...",
"help_button": "?",
"remove_watermark_checkbox": "移除水印",
"debug_images_checkbox": "生成调试图片",
"text_cleanup_margin_label": "文本框背景扩大比例:",
"ocr_font_distance_threshold_label": "字体敏感度(越大文本框越大):",
"ocr_model_variant_label": "OCR 模型版本:",
"ocr_model_variant_auto": "自动(有 GPU 用 Server,无 GPU 用 Lite)",
"ocr_model_variant_lite": "Lite",
"ocr_model_variant_server": "Server",
"ocr_advanced_show": "OCR 高级选项 ▸",
"ocr_advanced_hide": "OCR 高级选项 ▾",
"ocr_det_db_thresh_label": "OCR 检测阈值(越高越严格):",
"ocr_det_db_box_thresh_label": "OCR 框置信度阈值:",
"ocr_det_db_unclip_ratio_label": "OCR 框扩张比例(越小越紧):",
"start_button": "开始转换",
"converting_button": "转换中...",
"output_folder_button": "打开输出文件夹",
"debug_folder_button": "打开调试文件夹",
"log_label": "日志",
"json_help_title": "MinerU JSON 帮助",
"json_help_text": "所有转换都需要由 MinerU PDF/图片提取器生成的 JSON 文件。\n\n点击“确定”在浏览器中打开提取器网站。",
"error_title": "错误", "info_title": "信息", "complete_title": "完成",
"error_all_paths": "请填写所有文件路径。",
"error_dir_not_found": "输出目录未找到: {}",
"info_no_output": "尚未生成输出文件。",
"info_debug_not_found": "未找到调试文件夹。请启用“生成调试图片”运行转换,会在输出目录下创建 debug 文件夹。",
"log_success": "\n--- 转换成功 ---\n",
"log_error": "\n--- 错误 ---\n{}\n",
"msg_conversion_complete": "转换过程已结束。请查看日志了解详情。",
"batch_mode_button": "批量模式",
"single_mode_button": "单个模式",
"add_task_button": "添加任务",
"delete_task_button": "删除任务",
"start_batch_button": "开始批量转换",
"task_list_label": "任务列表",
"error_no_tasks": "请至少添加一个任务到列表。",
"log_batch_start": "\n--- 开始批量转换 ---\n",
"log_batch_complete": "\n--- 批量转换完成 ---\n",
"log_task_start": "开始任务 {} of {}: {}",
"log_task_complete": "完成任务: {}\n",
"add_task_title": "添加新任务",
"page_range_label": "PDF 页码范围(可选,如 1,3,5-8):",
"ok_button": "确定",
"cancel_button": "取消",
}
}
def get_language():
try:
lang_code, _ = locale.getdefaultlocale()
return 'zh' if lang_code and lang_code.lower().startswith('zh') else 'en'
except Exception: return 'en'
class QueueHandler:
def __init__(self, queue): self.queue = queue
def write(self, text): self.queue.put(text)
def flush(self): pass
class AddTaskDialog(tk.Toplevel):
def __init__(self, parent):
super().__init__(parent)
self.i18n = parent.i18n
self.title(self.i18n['add_task_title'])
self.geometry("640x360")
self.minsize(640, 360)
self.input_path = tk.StringVar()
self.json_path = tk.StringVar()
self.output_path = tk.StringVar()
self.page_range = tk.StringVar()
self.text_cleanup_margin_ratio = tk.StringVar(value=str(TEXT_CLEANUP_MARGIN_RATIO))
self.ocr_font_distance_threshold = tk.StringVar()
self.ocr_model_variant = tk.StringVar(value=self.i18n["ocr_model_variant_auto"])
self.ocr_det_db_thresh = tk.StringVar()
self.ocr_det_db_box_thresh = tk.StringVar()
self.ocr_det_db_unclip_ratio = tk.StringVar()
self.show_ocr_advanced = tk.BooleanVar(value=False)
self.remove_watermark = tk.BooleanVar(value=True)
self.result = None
self._font_threshold_is_default = True
self._font_threshold_updating = False
self._set_font_threshold_default("auto")
self.ocr_font_distance_threshold.trace_add("write", self._on_font_threshold_edit)
self._create_widgets()
self.transient(parent)
self.grab_set()
self.wait_window(self)
def _create_widgets(self):
frame = tk.Frame(self, padx=10, pady=10)
frame.pack(fill=tk.BOTH, expand=True)
frame.grid_columnconfigure(1, weight=1)
frame.grid_columnconfigure(2, weight=0)
tk.Label(frame, text=self.i18n['input_file_label']).grid(row=0, column=0, sticky="w", pady=5)
input_entry = tk.Entry(frame, textvariable=self.input_path)
input_entry.grid(row=0, column=1, sticky="ew", padx=5)
input_entry.drop_target_register(DND_FILES)
input_entry.dnd_bind('<<Drop>>', lambda e: self._on_drop(e, self.input_path))
tk.Button(frame, text=self.i18n['browse_button'], command=self._browse_input).grid(row=0, column=2, padx=5)
tk.Label(frame, text=self.i18n['json_file_label']).grid(row=1, column=0, sticky="w", pady=5)
json_entry = tk.Entry(frame, textvariable=self.json_path)
json_entry.grid(row=1, column=1, sticky="ew", padx=5)
json_entry.drop_target_register(DND_FILES)
json_entry.dnd_bind('<<Drop>>', lambda e: self._on_drop(e, self.json_path))
tk.Button(frame, text=self.i18n['browse_button'], command=self._browse_json).grid(row=1, column=2, padx=5)
tk.Label(frame, text=self.i18n['output_file_label']).grid(row=2, column=0, sticky="w", pady=5)
tk.Entry(frame, textvariable=self.output_path).grid(row=2, column=1, sticky="ew", padx=5)
tk.Button(frame, text=self.i18n['save_as_button'], command=self._save_pptx).grid(row=2, column=2, padx=5)
tk.Label(frame, text=self.i18n['page_range_label']).grid(row=3, column=0, sticky="w", pady=5)
tk.Entry(frame, textvariable=self.page_range).grid(row=3, column=1, sticky="ew", padx=5)
tk.Label(frame, text=self.i18n['text_cleanup_margin_label']).grid(row=4, column=0, sticky="w", pady=5)
tk.Entry(frame, textvariable=self.text_cleanup_margin_ratio).grid(row=4, column=1, sticky="ew", padx=5)
tk.Label(frame, text=self.i18n['ocr_font_distance_threshold_label']).grid(row=5, column=0, sticky="w", pady=5)
tk.Entry(frame, textvariable=self.ocr_font_distance_threshold).grid(row=5, column=1, sticky="ew", padx=5)
tk.Label(frame, text=self.i18n['ocr_model_variant_label']).grid(row=6, column=0, sticky="w", pady=5)
variant_options = (
self.i18n['ocr_model_variant_auto'],
self.i18n['ocr_model_variant_lite'],
self.i18n['ocr_model_variant_server'],
)
tk.OptionMenu(
frame,
self.ocr_model_variant,
*variant_options,
command=self._on_model_variant_change,
).grid(row=6, column=1, sticky="ew", padx=5)
advanced_toggle = tk.Checkbutton(
frame,
text=self.i18n['ocr_advanced_show'],
variable=self.show_ocr_advanced,
command=self._toggle_ocr_advanced,
)
advanced_toggle.grid(row=7, column=0, columnspan=2, sticky="w", pady=5)
self.ocr_advanced_frame = tk.Frame(frame)
self.ocr_advanced_frame.grid(row=8, column=0, columnspan=3, sticky="ew")
tk.Label(self.ocr_advanced_frame, text=self.i18n['ocr_det_db_thresh_label']).grid(row=0, column=0, sticky="w", pady=5)
tk.Entry(self.ocr_advanced_frame, textvariable=self.ocr_det_db_thresh).grid(row=0, column=1, sticky="ew", padx=5)
tk.Label(self.ocr_advanced_frame, text=self.i18n['ocr_det_db_box_thresh_label']).grid(row=1, column=0, sticky="w", pady=5)
tk.Entry(self.ocr_advanced_frame, textvariable=self.ocr_det_db_box_thresh).grid(row=1, column=1, sticky="ew", padx=5)
tk.Label(self.ocr_advanced_frame, text=self.i18n['ocr_det_db_unclip_ratio_label']).grid(row=2, column=0, sticky="w", pady=5)
tk.Entry(self.ocr_advanced_frame, textvariable=self.ocr_det_db_unclip_ratio).grid(row=2, column=1, sticky="ew", padx=5)
self.ocr_advanced_frame.grid_remove()
self._toggle_ocr_advanced()
options_frame = tk.Frame(frame)
options_frame.grid(row=9, column=0, columnspan=3, pady=10, sticky="w")
tk.Checkbutton(options_frame, text=self.i18n['remove_watermark_checkbox'], variable=self.remove_watermark).pack(side=tk.LEFT)
buttons_frame = tk.Frame(frame)
buttons_frame.grid(row=10, column=0, columnspan=3, pady=5)
tk.Button(buttons_frame, text=self.i18n['ok_button'], command=self._on_ok, width=10).pack(side=tk.LEFT, padx=10)
tk.Button(buttons_frame, text=self.i18n['cancel_button'], command=self.destroy, width=10).pack(side=tk.LEFT, padx=10)
def _on_drop(self, event, var):
filepath = event.data.strip('{}')
var.set(filepath)
if var == self.input_path:
self._set_default_output_path(filepath)
def _set_default_output_path(self, in_path):
if not self.output_path.get() and in_path:
self.output_path.set(os.path.splitext(in_path)[0] + ".pptx")
def _browse_input(self):
filetypes = [("Supported Files", "*.pdf *.png *.jpg *.jpeg *.bmp"), ("All Files", "*.*")]
path = filedialog.askopenfilename(filetypes=filetypes, parent=self)
if path: self.input_path.set(path); self._set_default_output_path(path)
def _browse_json(self):
path = filedialog.askopenfilename(filetypes=[("JSON Files", "*.json"), ("All Files", "*.*")], parent=self)
if path: self.json_path.set(path)
def _save_pptx(self):
path = filedialog.asksaveasfilename(defaultextension=".pptx", filetypes=[("PowerPoint Files", "*.pptx"), ("All Files", "*.*")], parent=self)
if path: self.output_path.set(path)
def _on_ok(self):
input_f, json_f, output_f = self.input_path.get(), self.json_path.get(), self.output_path.get()
if not all([input_f, json_f, output_f]):
messagebox.showerror(self.i18n['error_title'], self.i18n['error_all_paths'], parent=self)
return
self.result = {
"input": input_f,
"json": json_f,
"output": output_f,
"page_range": self.page_range.get().strip() or None,
"text_cleanup_margin_ratio": self.text_cleanup_margin_ratio.get().strip() or None,
"ocr_font_distance_threshold": self._resolved_font_threshold_value(),
"ocr_model_variant": _resolve_model_variant_value(self.ocr_model_variant.get(), self.i18n),
"ocr_det_db_thresh": self.ocr_det_db_thresh.get().strip() or None,
"ocr_det_db_box_thresh": self.ocr_det_db_box_thresh.get().strip() or None,
"ocr_det_db_unclip_ratio": self.ocr_det_db_unclip_ratio.get().strip() or None,
"remove_watermark": self.remove_watermark.get(),
}
self.destroy()
def _resolved_font_threshold_value(self):
if self._font_threshold_is_default:
return None
return self.ocr_font_distance_threshold.get().strip() or None
def _on_font_threshold_edit(self, *_args):
if self._font_threshold_updating:
return
value = self.ocr_font_distance_threshold.get().strip()
if value == "":
self._font_threshold_is_default = True
return
self._font_threshold_is_default = False
def _set_font_threshold_default(self, variant: str):
default_value = _default_font_threshold_for_variant(variant)
self._font_threshold_updating = True
self.ocr_font_distance_threshold.set(str(default_value))
self._font_threshold_updating = False
self._font_threshold_is_default = True
def _on_model_variant_change(self, selected_label):
self.ocr_model_variant.set(selected_label)
if self._font_threshold_is_default:
self._set_font_threshold_default(_resolve_model_variant_value(selected_label, self.i18n))
def _toggle_ocr_advanced(self):
show = self.show_ocr_advanced.get()
label = self.i18n['ocr_advanced_hide'] if show else self.i18n['ocr_advanced_show']
if hasattr(self, "single_ocr_advanced_frame"):
frame = self.single_ocr_advanced_frame
else:
frame = self.ocr_advanced_frame
for widget in frame.master.winfo_children():
if isinstance(widget, tk.Checkbutton) and widget.cget('text') in {
self.i18n['ocr_advanced_show'],
self.i18n['ocr_advanced_hide'],
}:
widget.config(text=label)
break
if show:
frame.grid()
else:
frame.grid_remove()
class App(TkinterDnD.Tk):
def __init__(self):
super().__init__()
self.i18n = TRANSLATIONS[get_language()]
self.title(self.i18n['app_title'])
self.geometry("700x600")
self._set_app_icon()
self.debug_folder_path = None
self.input_path, self.json_path, self.output_path = tk.StringVar(), tk.StringVar(), tk.StringVar()
self.page_range = tk.StringVar()
self.text_cleanup_margin_ratio = tk.StringVar(value=str(TEXT_CLEANUP_MARGIN_RATIO))
self.ocr_font_distance_threshold = tk.StringVar()
self.ocr_model_variant = tk.StringVar(value=self.i18n["ocr_model_variant_auto"])
self.ocr_det_db_thresh = tk.StringVar()
self.ocr_det_db_box_thresh = tk.StringVar()
self.ocr_det_db_unclip_ratio = tk.StringVar()
self.show_ocr_advanced = tk.BooleanVar(value=False)
self.remove_watermark, self.generate_debug = tk.BooleanVar(value=True), tk.BooleanVar(value=False)
self.batch_mode = tk.BooleanVar(value=False)
self.task_list = []
self.shared_ocr_engine = None
self.log_queue = queue.Queue()
self.queue_handler = QueueHandler(self.log_queue)
self._font_threshold_is_default = True
self._font_threshold_updating = False
self._set_font_threshold_default("auto")
self.ocr_font_distance_threshold.trace_add("write", self._on_font_threshold_edit)
self._create_widgets()
self._poll_log_queue()
def _create_widgets(self):
self.main_frame = tk.Frame(self, padx=10, pady=10)
self.main_frame.pack(fill=tk.BOTH, expand=True)
self.main_frame.grid_columnconfigure(1, weight=1)
self.main_frame.grid_rowconfigure(4, weight=1)
self.mode_switch_button = tk.Button(self.main_frame, text=self.i18n['batch_mode_button'], command=self._toggle_batch_mode)
self.mode_switch_button.grid(row=0, column=2, sticky="e", pady=(0, 5))
# --- Single Mode Frame ---
self.single_mode_frame = tk.Frame(self.main_frame)
self.single_mode_frame.grid(row=1, column=0, columnspan=3, sticky="ew")
self.single_mode_frame.grid_columnconfigure(1, weight=1)
# (Content of single mode frame...)
tk.Label(self.single_mode_frame, text=self.i18n['input_file_label']).grid(row=0, column=0, sticky="w", pady=2)
input_entry = tk.Entry(self.single_mode_frame, textvariable=self.input_path, state="readonly")
input_entry.grid(row=0, column=1, sticky="ew", padx=5)
input_entry.drop_target_register(DND_FILES); input_entry.dnd_bind('<<Drop>>', lambda e: self._on_drop(e, self.input_path))
tk.Button(self.single_mode_frame, text=self.i18n['browse_button'], command=self._browse_input).grid(row=0, column=2, sticky="w")
tk.Label(self.single_mode_frame, text=self.i18n['json_file_label']).grid(row=1, column=0, sticky="w", pady=2)
json_entry = tk.Entry(self.single_mode_frame, textvariable=self.json_path, state="readonly")
json_entry.grid(row=1, column=1, sticky="ew", padx=5)
json_entry.drop_target_register(DND_FILES); json_entry.dnd_bind('<<Drop>>', lambda e: self._on_drop(e, self.json_path))
json_buttons_frame = tk.Frame(self.single_mode_frame)
json_buttons_frame.grid(row=1, column=2, sticky="w")
tk.Button(json_buttons_frame, text=self.i18n['browse_button'], command=self._browse_json).pack(side=tk.LEFT)
tk.Button(json_buttons_frame, text=self.i18n['help_button'], command=self._show_json_help, width=2).pack(side=tk.LEFT)
tk.Label(self.single_mode_frame, text=self.i18n['output_file_label']).grid(row=2, column=0, sticky="w", pady=2)
tk.Entry(self.single_mode_frame, textvariable=self.output_path).grid(row=2, column=1, sticky="ew", padx=5)
tk.Button(self.single_mode_frame, text=self.i18n['save_as_button'], command=self._save_pptx).grid(row=2, column=2, sticky="w")
tk.Label(self.single_mode_frame, text=self.i18n['page_range_label']).grid(row=3, column=0, sticky="w", pady=2)
tk.Entry(self.single_mode_frame, textvariable=self.page_range).grid(row=3, column=1, sticky="ew", padx=5)
tk.Label(self.single_mode_frame, text=self.i18n['text_cleanup_margin_label']).grid(row=4, column=0, sticky="w", pady=2)
tk.Entry(self.single_mode_frame, textvariable=self.text_cleanup_margin_ratio).grid(row=4, column=1, sticky="ew", padx=5)
tk.Label(self.single_mode_frame, text=self.i18n['ocr_font_distance_threshold_label']).grid(row=5, column=0, sticky="w", pady=2)
tk.Entry(self.single_mode_frame, textvariable=self.ocr_font_distance_threshold).grid(row=5, column=1, sticky="ew", padx=5)
tk.Label(self.single_mode_frame, text=self.i18n['ocr_model_variant_label']).grid(row=6, column=0, sticky="w", pady=2)
single_variant_options = (
self.i18n['ocr_model_variant_auto'],
self.i18n['ocr_model_variant_lite'],
self.i18n['ocr_model_variant_server'],
)
tk.OptionMenu(
self.single_mode_frame,
self.ocr_model_variant,
*single_variant_options,
command=self._on_model_variant_change,
).grid(row=6, column=1, sticky="ew", padx=5)
single_advanced_toggle = tk.Checkbutton(
self.single_mode_frame,
text=self.i18n['ocr_advanced_show'],
variable=self.show_ocr_advanced,
command=self._toggle_ocr_advanced,
)
single_advanced_toggle.grid(row=7, column=0, columnspan=2, sticky="w", pady=2)
self.single_ocr_advanced_frame = tk.Frame(self.single_mode_frame)
self.single_ocr_advanced_frame.grid(row=8, column=0, columnspan=3, sticky="ew")
tk.Label(self.single_ocr_advanced_frame, text=self.i18n['ocr_det_db_thresh_label']).grid(row=0, column=0, sticky="w", pady=2)
tk.Entry(self.single_ocr_advanced_frame, textvariable=self.ocr_det_db_thresh).grid(row=0, column=1, sticky="ew", padx=5)
tk.Label(self.single_ocr_advanced_frame, text=self.i18n['ocr_det_db_box_thresh_label']).grid(row=1, column=0, sticky="w", pady=2)
tk.Entry(self.single_ocr_advanced_frame, textvariable=self.ocr_det_db_box_thresh).grid(row=1, column=1, sticky="ew", padx=5)
tk.Label(self.single_ocr_advanced_frame, text=self.i18n['ocr_det_db_unclip_ratio_label']).grid(row=2, column=0, sticky="w", pady=2)
tk.Entry(self.single_ocr_advanced_frame, textvariable=self.ocr_det_db_unclip_ratio).grid(row=2, column=1, sticky="ew", padx=5)
self.single_ocr_advanced_frame.grid_remove()
# --- Batch Mode Frame ---
self.batch_frame = tk.Frame(self.main_frame)
self.batch_frame.grid_columnconfigure(0, weight=1); self.batch_frame.grid_rowconfigure(0, weight=1)
# (Content of batch mode frame...)
task_list_frame = tk.LabelFrame(self.batch_frame, text=self.i18n['task_list_label'], padx=5, pady=5)
task_list_frame.grid(row=0, column=0, columnspan=2, sticky="nsew", pady=5)
task_list_frame.grid_columnconfigure(0, weight=1); task_list_frame.grid_rowconfigure(0, weight=1)
self.task_listbox = tk.Listbox(task_list_frame, height=8)
self.task_listbox.grid(row=0, column=0, sticky="nsew")
task_scrollbar = tk.Scrollbar(task_list_frame, orient="vertical", command=self.task_listbox.yview)
task_scrollbar.grid(row=0, column=1, sticky="ns"); self.task_listbox.config(yscrollcommand=task_scrollbar.set)
batch_buttons_frame = tk.Frame(self.batch_frame)
batch_buttons_frame.grid(row=1, column=0, columnspan=2, pady=(5,0))
tk.Button(batch_buttons_frame, text=self.i18n['add_task_button'], command=self._add_task).pack(side=tk.LEFT, padx=5)
tk.Button(batch_buttons_frame, text=self.i18n['delete_task_button'], command=self._delete_task).pack(side=tk.LEFT, padx=5)
# --- Options (will be managed dynamically) ---
self.options_frame = tk.Frame(self.main_frame)
self.options_frame.grid(row=2, column=0, columnspan=3, pady=10, sticky="w")
self.remove_watermark_checkbox = tk.Checkbutton(self.options_frame, text=self.i18n['remove_watermark_checkbox'], variable=self.remove_watermark)
self.remove_watermark_checkbox.pack(side=tk.LEFT, padx=5)
self.debug_images_checkbox = tk.Checkbutton(self.options_frame, text=self.i18n['debug_images_checkbox'], variable=self.generate_debug, command=self._toggle_debug_button_visibility)
self.debug_images_checkbox.pack(side=tk.LEFT, padx=5)
# --- Actions and Log ---
action_frame = tk.Frame(self.main_frame)
action_frame.grid(row=3, column=0, columnspan=3, pady=10)
action_frame.grid_columnconfigure(0, weight=1)
button_container = tk.Frame(action_frame)
button_container.grid(row=0, column=0)
self.start_button = tk.Button(button_container, text=self.i18n['start_button'], command=self.start_conversion_thread)
self.start_button.pack(side=tk.LEFT, padx=10)
self.output_button = tk.Button(button_container, text=self.i18n['output_folder_button'], command=self._open_output_folder, state="disabled")
self.output_button.pack(side=tk.LEFT, padx=10)
self.debug_button = tk.Button(button_container, text=self.i18n['debug_folder_button'], command=self._open_debug_folder, state="disabled")
log_frame = tk.LabelFrame(self.main_frame, text=self.i18n['log_label'], padx=5, pady=5)
log_frame.grid(row=4, column=0, columnspan=3, sticky="nsew")
log_frame.grid_rowconfigure(0, weight=1); log_frame.grid_columnconfigure(0, weight=1)
self.log_area = scrolledtext.ScrolledText(log_frame, state="disabled", wrap=tk.WORD, height=10)
self.log_area.grid(row=0, column=0, sticky="nsew")
self._toggle_batch_mode() # Set initial state to single mode
self._toggle_batch_mode()
self._toggle_ocr_advanced()
def _resolved_font_threshold_value(self):
if self._font_threshold_is_default:
return None
return self.ocr_font_distance_threshold.get().strip() or None
def _on_font_threshold_edit(self, *_args):
if self._font_threshold_updating:
return
value = self.ocr_font_distance_threshold.get().strip()
if value == "":
self._font_threshold_is_default = True
return
self._font_threshold_is_default = False
def _set_font_threshold_default(self, variant: str):
default_value = _default_font_threshold_for_variant(variant)
self._font_threshold_updating = True
self.ocr_font_distance_threshold.set(str(default_value))
self._font_threshold_updating = False
self._font_threshold_is_default = True
def _on_model_variant_change(self, selected_label):
self.ocr_model_variant.set(selected_label)
if self._font_threshold_is_default:
self._set_font_threshold_default(_resolve_model_variant_value(selected_label, self.i18n))
def _toggle_ocr_advanced(self):
show = self.show_ocr_advanced.get()
label = self.i18n['ocr_advanced_hide'] if show else self.i18n['ocr_advanced_show']
if hasattr(self, "single_ocr_advanced_frame"):
frame = self.single_ocr_advanced_frame
else:
frame = self.ocr_advanced_frame
for widget in frame.master.winfo_children():
if isinstance(widget, tk.Checkbutton) and widget.cget('text') in {
self.i18n['ocr_advanced_show'],
self.i18n['ocr_advanced_hide'],
}:
widget.config(text=label)
break
if show:
frame.grid()
else:
frame.grid_remove()
def _set_app_icon(self):
try:
repo_root = os.path.dirname(os.path.abspath(__file__))
icon_path = os.path.join(repo_root, "img", "logo.png")
if os.path.exists(icon_path):
self._app_icon = tk.PhotoImage(file=icon_path)
self.iconphoto(False, self._app_icon)
except Exception:
pass
def _toggle_batch_mode(self):
is_batch = not self.batch_mode.get()
self.batch_mode.set(is_batch)
if is_batch:
self.single_mode_frame.grid_remove()
self.batch_frame.grid(row=1, column=0, columnspan=3, sticky="nsew")
self.mode_switch_button.config(text=self.i18n['single_mode_button'])
self.start_button.config(text=self.i18n['start_batch_button'])
# Hide options not relevant to batch mode
self.options_frame.grid_remove()
self.debug_button.pack_forget()
else:
self.batch_frame.grid_remove()
self.single_mode_frame.grid()
self.mode_switch_button.config(text=self.i18n['batch_mode_button'])
self.start_button.config(text=self.i18n['start_button'])
# Show options for single mode
self.options_frame.grid()
self._toggle_debug_button_visibility()
def _add_task(self):
dialog = AddTaskDialog(self)
if dialog.result:
task = dialog.result
self.task_list.append(task)
suffix_parts = []
if not task['remove_watermark']:
suffix_parts.append("Keep WM")
variant = task.get("ocr_model_variant")
if variant and variant != "auto":
suffix_parts.append(f"OCR:{variant}")
suffix = f" ({', '.join(suffix_parts)})" if suffix_parts else ""
self.task_listbox.insert(tk.END, f"IN: {os.path.basename(task['input'])} -> OUT: {os.path.basename(task['output'])}{suffix}")
def _delete_task(self):
selected_indices = self.task_listbox.curselection()
if not selected_indices: return
for index in sorted(selected_indices, reverse=True):
self.task_listbox.delete(index)
del self.task_list[index]
def _show_json_help(self):
if messagebox.askokcancel(self.i18n['json_help_title'], self.i18n['json_help_text']):
webbrowser.open_new("https://mineru.net/OpenSourceTools/Extractor")
def _toggle_debug_button_visibility(self):
if self.generate_debug.get() and not self.batch_mode.get():
self.debug_button.pack(side=tk.LEFT, padx=10)
else:
self.debug_button.pack_forget()
def _open_output_folder(self):
output_file = self.output_path.get()
if self.batch_mode.get() and self.task_list:
output_file = self.task_list[-1]['output']
if not output_file:
messagebox.showinfo(self.i18n['info_title'], self.i18n['info_no_output']); return
output_dir = os.path.dirname(output_file)
if os.path.exists(output_dir): os.startfile(output_dir)
else: messagebox.showerror(self.i18n['error_title'], self.i18n['error_dir_not_found'].format(output_dir))
def _open_debug_folder(self):
if os.path.exists(self.debug_folder_path): os.startfile(self.debug_folder_path)
else: messagebox.showinfo(self.i18n['info_title'], self.i18n['info_debug_not_found'])
def _set_default_output_path(self, in_path):
if not self.output_path.get(): self.output_path.set(os.path.splitext(in_path)[0] + ".pptx")
def _on_drop(self, event, var):
filepath = event.data.strip('{}')
var.set(filepath)
if var == self.input_path: self._set_default_output_path(filepath)
def _browse_input(self):
filetypes = [("Supported Files", "*.pdf *.png *.jpg *.jpeg *.bmp"), ("All Files", "*.*")]
path = filedialog.askopenfilename(filetypes=filetypes)
if path: self.input_path.set(path); self._set_default_output_path(path)
def _browse_json(self):
path = filedialog.askopenfilename(filetypes=[("JSON Files", "*.json"), ("All Files", "*.*")])
if path: self.json_path.set(path)
def _save_pptx(self):
path = filedialog.asksaveasfilename(defaultextension=".pptx", filetypes=[("PowerPoint Files", "*.pptx"), ("All Files", "*.*")])
if path: self.output_path.set(path)
def _poll_log_queue(self):
while True:
try:
record = self.log_queue.get_nowait()
self.log_area.config(state="normal"); self.log_area.insert(tk.END, record); self.log_area.see(tk.END); self.log_area.config(state="disabled")
except queue.Empty: break
self.after(100, self._poll_log_queue)
def start_conversion_thread(self):
if self.batch_mode.get():
if not self.task_list:
messagebox.showerror(self.i18n['error_title'], self.i18n['error_no_tasks'])
return
target_func, args = self._run_batch_conversion, ()
else:
input_file, json_f = self.input_path.get(), self.json_path.get()
if not self.output_path.get() and input_file: self._set_default_output_path(input_file)
output = self.output_path.get()
if not all([input_file, json_f, output]):
messagebox.showerror(self.i18n['error_title'], self.i18n['error_all_paths']); return
target_func, args = self._run_single_conversion, (json_f, input_file, output)
self.start_button.config(state="disabled", text=self.i18n['converting_button'])
self.output_button.config(state="disabled")
if not self.batch_mode.get(): self.debug_button.config(state="disabled")
self.log_area.config(state="normal"); self.log_area.delete(1.0, tk.END); self.log_area.config(state="disabled")
threading.Thread(target=self._run_conversion_wrapper, args=(target_func, args), daemon=True).start()
def _run_conversion_wrapper(self, conversion_func, args):
old_stdout, old_stderr = sys.stdout, sys.stderr
sys.stdout, sys.stderr = self.queue_handler, self.queue_handler
success = False
try:
conversion_func(*args)
success = True
except Exception as e:
self.log_queue.put(self.i18n['log_error'].format(e))
finally:
sys.stdout, sys.stderr = old_stdout, old_stderr
self.after(0, self._finalize_gui, success)
def _run_single_conversion(self, json_path, input_path, output_path):
resolved_variant = _resolve_model_variant_value(self.ocr_model_variant.get(), self.i18n)
threshold_value = self._resolved_font_threshold_value()
det_db_thresh = self.ocr_det_db_thresh.get().strip() or None
det_db_box_thresh = self.ocr_det_db_box_thresh.get().strip() or None
det_db_unclip_ratio = self.ocr_det_db_unclip_ratio.get().strip() or None
if self.shared_ocr_engine is None:
from converter.ocr_merge import PaddleOCREngine
self.shared_ocr_engine = PaddleOCREngine(
device_policy="auto",
use_angle_cls=False,
offline_only=False,
det_db_thresh=det_db_thresh,
det_db_box_thresh=det_db_box_thresh,
det_db_unclip_ratio=det_db_unclip_ratio,
refine_font_distance_threshold=threshold_value,
model_variant=resolved_variant,
)
else:
self.shared_ocr_engine.refine_font_distance_threshold = threshold_value
self.shared_ocr_engine.model_variant = resolved_variant
self.shared_ocr_engine.det_db_thresh = det_db_thresh
self.shared_ocr_engine.det_db_box_thresh = det_db_box_thresh
self.shared_ocr_engine.det_db_unclip_ratio = det_db_unclip_ratio
self.shared_ocr_engine._ocr = None
args = (
json_path,
input_path,
output_path,
self.remove_watermark.get(),
self.generate_debug.get(),
)
convert_mineru_to_ppt(
*args,
ocr_engine=self.shared_ocr_engine,
page_range=self.page_range.get().strip() or None,
text_cleanup_margin_ratio=self.text_cleanup_margin_ratio.get().strip() or None,
ocr_font_distance_threshold=threshold_value,
ocr_model_variant=_resolve_model_variant_value(self.ocr_model_variant.get(), self.i18n),
ocr_det_db_thresh=det_db_thresh,
ocr_det_db_box_thresh=det_db_box_thresh,
ocr_det_db_unclip_ratio=det_db_unclip_ratio,
)
self.log_queue.put(self.i18n['log_success'])
def _run_batch_conversion(self):
self.log_queue.put(self.i18n['log_batch_start'])
total_tasks = len(self.task_list)
for i, task in enumerate(self.task_list):
self.log_queue.put(self.i18n['log_task_start'].format(i + 1, total_tasks, os.path.basename(task['input'])))
try:
# Debug images are disabled for batch mode
args = (
task['json'],
task['input'],
task['output'],
task['remove_watermark'],
False,
)
variant = task.get('ocr_model_variant') or "auto"
threshold_value = task.get('ocr_font_distance_threshold') or None
det_db_thresh = task.get('ocr_det_db_thresh') or None
det_db_box_thresh = task.get('ocr_det_db_box_thresh') or None
det_db_unclip_ratio = task.get('ocr_det_db_unclip_ratio') or None
if self.shared_ocr_engine is None:
from converter.ocr_merge import PaddleOCREngine
self.shared_ocr_engine = PaddleOCREngine(
device_policy="auto",
use_angle_cls=False,
offline_only=False,
det_db_thresh=det_db_thresh,
det_db_box_thresh=det_db_box_thresh,
det_db_unclip_ratio=det_db_unclip_ratio,
refine_font_distance_threshold=threshold_value,
model_variant=variant,
)
else:
self.shared_ocr_engine.refine_font_distance_threshold = threshold_value
self.shared_ocr_engine.model_variant = variant
self.shared_ocr_engine.det_db_thresh = det_db_thresh
self.shared_ocr_engine.det_db_box_thresh = det_db_box_thresh
self.shared_ocr_engine.det_db_unclip_ratio = det_db_unclip_ratio
self.shared_ocr_engine._ocr = None
convert_mineru_to_ppt(
*args,
ocr_engine=self.shared_ocr_engine,
page_range=(task.get('page_range') or None),
text_cleanup_margin_ratio=(task.get('text_cleanup_margin_ratio') or None),
ocr_font_distance_threshold=threshold_value,
ocr_model_variant=variant,
ocr_det_db_thresh=det_db_thresh,
ocr_det_db_box_thresh=det_db_box_thresh,
ocr_det_db_unclip_ratio=det_db_unclip_ratio,
)
self.log_queue.put(self.i18n['log_task_complete'].format(os.path.basename(task['input'])))
except Exception as e:
self.log_queue.put(self.i18n['log_error'].format(e))
self.log_queue.put(self.i18n['log_batch_complete'])
def _finalize_gui(self, success):
start_text = self.i18n['start_batch_button'] if self.batch_mode.get() else self.i18n['start_button']
self.start_button.config(state="normal", text=start_text)
if success:
self.output_button.config(state="normal")
if self.generate_debug.get() and not self.batch_mode.get():
self.debug_button.config(state="normal")
messagebox.showinfo(self.i18n['complete_title'], self.i18n['msg_conversion_complete'])
if __name__ == "__main__":
if len(sys.argv) > 1:
from main import main as cli_main
cli_main()
else:
app = App()
app.mainloop()