-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathpolyscriptor_batch_gui.py
More file actions
executable file
·1359 lines (1161 loc) · 53 KB
/
polyscriptor_batch_gui.py
File metadata and controls
executable file
·1359 lines (1161 loc) · 53 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
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Polyscriptor Batch - Minimal GUI Launcher for Batch HTR Processing
A lightweight Qt6 GUI that builds and executes batch_processing.py commands.
Design philosophy: CLI wrapper, not reimplementation.
"""
import sys
import os
import json
import subprocess
from pathlib import Path
from typing import Dict, Any, Optional, List
# Load environment variables from .env file
try:
from dotenv import load_dotenv
# Look for .env in the project root
env_path = Path(__file__).parent / ".env"
if env_path.exists():
load_dotenv(env_path)
except ImportError:
pass # dotenv not installed, will fall back to environment variables
from PyQt6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QGroupBox, QLabel, QLineEdit, QPushButton, QComboBox, QCheckBox,
QFileDialog, QSpinBox, QDoubleSpinBox, QMessageBox, QTextEdit
)
from PyQt6.QtCore import Qt, QProcess, pyqtSignal
from PyQt6.QtGui import QFont
# Available engines with their configuration needs
ENGINES = {
"CRNN-CTC": {
"needs_model_path": True,
"needs_model_id": False,
"default_segmentation": "kraken",
"supports_beams": False,
},
"TrOCR": {
"needs_model_path": True,
"needs_model_id": True,
"default_segmentation": "kraken",
"supports_beams": True,
},
"Qwen3-VL": {
"needs_model_path": True, # Local model path OR HF model ID
"needs_model_id": True, # Both available for flexibility
"needs_adapter": True, # For local LoRA adapters (with HF base)
"supports_line_mode": True, # For line-trained models
"default_segmentation": "none",
"supports_beams": False,
"warning": "VERY SLOW: ~1-2 min/page. Use only for small batches!",
"model_path_tooltip": "Local Qwen model folder (use this OR Model ID, not both)",
},
"Party": {
"needs_model_path": True,
"needs_model_id": False,
"default_segmentation": "none",
"supports_beams": False,
"requires_pagexml": True,
},
"Kraken": {
"needs_model_path": True,
"needs_model_id": False,
"default_segmentation": "none",
"supports_beams": False,
},
"Churro": {
"needs_model_path": True,
"needs_model_id": True,
"default_segmentation": "kraken",
"supports_beams": False,
},
"OpenWebUI": {
"needs_model_path": False,
"needs_model_id": True, # Model name from server
"needs_api_key": True, # Requires API key
"default_segmentation": "none", # VLM processes full pages
"supports_beams": False,
"warning": "API-based: Requires API key from openwebui.uni-freiburg.de",
},
"LightOnOCR": {
"needs_model_path": False,
"needs_model_id": True, # HuggingFace model ID
"default_segmentation": "kraken", # LINE-LEVEL model
"supports_beams": False,
"has_lighton_options": True, # Enable LightOnOCR-specific controls
"warning": "Requires transformers from git: pip install git+https://github.com/huggingface/transformers.git",
},
"DeepSeek-OCR": {
"needs_model_path": False,
"needs_model_id": False, # Uses default deepseek-ai/DeepSeek-OCR-2 from HF cache
"default_segmentation": "none", # Page-level VLM
"supports_beams": False,
"has_deepseek_options": True,
"warning": "PAGE-LEVEL model (~6 GB VRAM). Requires venv_deepseek with transformers==4.46.3.",
},
"PaddleOCR": {
"needs_model_path": False,
"needs_model_id": False,
"default_segmentation": "none", # PaddleOCR does its own detection
"supports_beams": False,
"has_paddle_options": True,
"warning": "Requires separate PaddleOCR venv (venv_paddle). Models download on first use.",
},
}
# Built-in presets
BUILTIN_PRESETS = {
"Church Slavonic (CRNN-CTC + Kraken)": {
"engine": "CRNN-CTC",
"model_path": "models/pylaia_church_slavonic_20251103_162857/best_model.pt",
"segmentation_method": "kraken",
"use_pagexml": True,
"device": "cuda:0",
"output_formats": ["txt"],
},
"Ukrainian (CRNN-CTC + Kraken)": {
"engine": "CRNN-CTC",
"model_path": "models/pylaia_ukrainian_pagexml_20251101_182736/best_model.pt",
"segmentation_method": "kraken",
"use_pagexml": True,
"device": "cuda:0",
"output_formats": ["txt"],
},
"Glagolitic (CRNN-CTC + Kraken)": {
"engine": "CRNN-CTC",
"model_path": "models/pylaia_glagolitic_with_spaces_20251102_182103/best_model.pt",
"segmentation_method": "kraken",
"use_pagexml": True,
"device": "cuda:0",
"output_formats": ["txt"],
},
"Russian (TrOCR HF)": {
"engine": "TrOCR",
"model_id": "kazars24/trocr-base-handwritten-ru",
"segmentation_method": "kraken",
"use_pagexml": True,
"device": "cuda:0",
"output_formats": ["txt"],
"num_beams": 4,
},
"Church Slavonic (Qwen3-VL Pages)": {
"engine": "Qwen3-VL",
"model_id": "wjbmattingly/Qwen3-VL-8B-old-church-slavonic",
"segmentation_method": "none",
"use_pagexml": False,
"device": "cuda:0",
"output_formats": ["txt"],
},
"Ukrainian (Qwen3-VL + LoRA Adapter)": {
"engine": "Qwen3-VL",
"model_id": "Qwen/Qwen3-VL-8B-Instruct",
"adapter": "models/Qwen3-VL-8B-ukrainian/final_model",
"segmentation_method": "none",
"use_pagexml": False,
"device": "cuda:0",
"output_formats": ["txt"],
},
"Glagolitic (Qwen3-VL + LoRA Adapter)": {
"engine": "Qwen3-VL",
"model_id": "Qwen/Qwen3-VL-8B-Instruct",
"adapter": "models/Qwen3-VL-8B-glagolitic/final_model",
"segmentation_method": "none",
"use_pagexml": False,
"device": "cuda:0",
"output_formats": ["txt"],
},
"Church Slavonic (Qwen3-VL Lines + PAGE XML)": {
"engine": "Qwen3-VL",
"model_id": "wjbmattingly/Qwen3-VL-8B-old-church-slavonic-line-3-epochs",
"segmentation_method": "kraken",
"use_pagexml": True,
"line_mode": True, # Force line segmentation for line-trained model
"device": "cuda:0",
"output_formats": ["txt"],
},
"German Shorthand (LightOnOCR)": {
"engine": "LightOnOCR",
"model_id": "wjbmattingly/LightOnOCR-2-1B-german-shorthand-line",
"segmentation_method": "kraken",
"use_pagexml": True,
"device": "cuda:0",
"output_formats": ["txt"],
"longest_edge": 700,
"max_new_tokens": 256,
},
"Multilingual (LightOnOCR Base)": {
"engine": "LightOnOCR",
"model_id": "lightonai/LightOnOCR-2-1B-base",
"segmentation_method": "kraken",
"use_pagexml": True,
"device": "cuda:0",
"output_formats": ["txt"],
"longest_edge": 700,
"max_new_tokens": 256,
},
}
class PolyscriptorBatchGUI(QMainWindow):
"""Minimal GUI launcher for batch HTR processing."""
def __init__(self):
super().__init__()
self.setWindowTitle("Polyscriptor Batch - HTR Batch Processing")
self.resize(800, 900)
# Central widget
central = QWidget()
self.setCentralWidget(central)
layout = QVBoxLayout(central)
# Input/Output section
input_group = self._create_input_output_group()
layout.addWidget(input_group)
# Engine configuration
engine_group = self._create_engine_group()
layout.addWidget(engine_group)
# Segmentation options
seg_group = self._create_segmentation_group()
layout.addWidget(seg_group)
# Output options
output_group = self._create_output_options_group()
layout.addWidget(output_group)
# Presets
preset_group = self._create_preset_group()
layout.addWidget(preset_group)
# Action buttons
button_layout = self._create_action_buttons()
layout.addLayout(button_layout)
# Command preview
self.command_preview = QTextEdit()
self.command_preview.setMaximumHeight(100)
self.command_preview.setReadOnly(True)
self.command_preview.setFont(QFont("Monospace", 9))
layout.addWidget(QLabel("Command Preview:"))
layout.addWidget(self.command_preview)
# Update command preview on any change
self._connect_update_signals()
self._update_command_preview()
def _create_input_output_group(self) -> QGroupBox:
"""Create input/output folder selection group."""
group = QGroupBox("Input/Output")
layout = QVBoxLayout()
# Input folder
input_layout = QHBoxLayout()
input_layout.addWidget(QLabel("Input Folder:"))
self.input_folder_edit = QLineEdit("HTR_Images/")
input_layout.addWidget(self.input_folder_edit)
self.input_browse_btn = QPushButton("Browse...")
self.input_browse_btn.clicked.connect(self._browse_input_folder)
input_layout.addWidget(self.input_browse_btn)
layout.addLayout(input_layout)
# Output folder
output_layout = QHBoxLayout()
output_layout.addWidget(QLabel("Output Folder:"))
self.output_folder_edit = QLineEdit("output")
output_layout.addWidget(self.output_folder_edit)
self.output_browse_btn = QPushButton("Browse...")
self.output_browse_btn.clicked.connect(self._browse_output_folder)
output_layout.addWidget(self.output_browse_btn)
layout.addLayout(output_layout)
group.setLayout(layout)
return group
def _create_engine_group(self) -> QGroupBox:
"""Create engine configuration group."""
group = QGroupBox("Engine Configuration")
layout = QVBoxLayout()
# Engine selection
engine_layout = QHBoxLayout()
engine_layout.addWidget(QLabel("Engine:"))
self.engine_combo = QComboBox()
self.engine_combo.addItems(list(ENGINES.keys()))
self.engine_combo.currentTextChanged.connect(self._on_engine_changed)
engine_layout.addWidget(self.engine_combo)
layout.addLayout(engine_layout)
# Model path (local file)
model_path_layout = QHBoxLayout()
model_path_layout.addWidget(QLabel("Model Path:"))
self.model_path_edit = QLineEdit()
model_path_layout.addWidget(self.model_path_edit)
self.model_browse_btn = QPushButton("Browse...")
self.model_browse_btn.clicked.connect(self._browse_model_path)
model_path_layout.addWidget(self.model_browse_btn)
layout.addLayout(model_path_layout)
# Model ID (HuggingFace)
model_id_layout = QHBoxLayout()
model_id_layout.addWidget(QLabel("Model ID (HF):"))
self.model_id_edit = QLineEdit()
self.model_id_edit.setPlaceholderText("username/model-name")
model_id_layout.addWidget(self.model_id_edit)
layout.addLayout(model_id_layout)
# Adapter path (for Qwen3 LoRA models)
adapter_layout = QHBoxLayout()
adapter_layout.addWidget(QLabel("Adapter Path:"))
self.adapter_edit = QLineEdit()
self.adapter_edit.setPlaceholderText("Optional: path to LoRA adapter folder")
adapter_layout.addWidget(self.adapter_edit)
self.adapter_browse_btn = QPushButton("Browse...")
self.adapter_browse_btn.clicked.connect(self._browse_adapter_path)
adapter_layout.addWidget(self.adapter_browse_btn)
layout.addLayout(adapter_layout)
# Initially hidden, shown only for Qwen3-VL
self.adapter_edit.setVisible(False)
self.adapter_browse_btn.setVisible(False)
# Store the label for visibility toggle
self.adapter_label = adapter_layout.itemAt(0).widget()
self.adapter_label.setVisible(False)
# Line mode checkbox (for line-trained Qwen3 models)
self.line_mode_check = QCheckBox("Line Mode (for line-trained models)")
self.line_mode_check.setToolTip(
"Enable for Qwen3 models trained on line images.\n"
"Forces segmentation so each line is processed separately.\n"
"Leave unchecked for page-trained models that output line breaks."
)
self.line_mode_check.setVisible(False) # Hidden by default, shown for Qwen3-VL
layout.addWidget(self.line_mode_check)
# API Key (for OpenWebUI)
api_key_layout = QHBoxLayout()
self.api_key_label = QLabel("API Key:")
api_key_layout.addWidget(self.api_key_label)
self.api_key_edit = QLineEdit()
self.api_key_edit.setPlaceholderText("OpenWebUI API key (or set OPENWEBUI_API_KEY env var)")
self.api_key_edit.setEchoMode(QLineEdit.EchoMode.Password)
api_key_layout.addWidget(self.api_key_edit)
self.api_key_show_check = QCheckBox("Show")
self.api_key_show_check.toggled.connect(
lambda checked: self.api_key_edit.setEchoMode(
QLineEdit.EchoMode.Normal if checked else QLineEdit.EchoMode.Password
)
)
api_key_layout.addWidget(self.api_key_show_check)
layout.addLayout(api_key_layout)
# Initially hidden, shown only for OpenWebUI
self.api_key_label.setVisible(False)
self.api_key_edit.setVisible(False)
self.api_key_show_check.setVisible(False)
# OpenWebUI Model selection (dropdown with refresh)
openwebui_model_layout = QHBoxLayout()
self.openwebui_model_label = QLabel("Model:")
openwebui_model_layout.addWidget(self.openwebui_model_label)
self.openwebui_model_combo = QComboBox()
self.openwebui_model_combo.setMinimumWidth(250)
self.openwebui_model_combo.addItem("Click 'Refresh' to load models")
openwebui_model_layout.addWidget(self.openwebui_model_combo)
self.openwebui_refresh_btn = QPushButton("Refresh")
self.openwebui_refresh_btn.setToolTip("Fetch available models from OpenWebUI server")
self.openwebui_refresh_btn.clicked.connect(self._refresh_openwebui_models)
openwebui_model_layout.addWidget(self.openwebui_refresh_btn)
layout.addLayout(openwebui_model_layout)
# Initially hidden, shown only for OpenWebUI
self.openwebui_model_label.setVisible(False)
self.openwebui_model_combo.setVisible(False)
self.openwebui_refresh_btn.setVisible(False)
# Device selection
device_layout = QHBoxLayout()
device_layout.addWidget(QLabel("Device:"))
self.device_combo = QComboBox()
self.device_combo.addItems(["cuda:0", "cuda:1", "cpu"])
device_layout.addWidget(self.device_combo)
layout.addLayout(device_layout)
# Batch size
batch_layout = QHBoxLayout()
batch_layout.addWidget(QLabel("Batch Size:"))
self.batch_spin = QSpinBox()
self.batch_spin.setRange(1, 128)
self.batch_spin.setValue(16)
self.batch_spin.setToolTip("Leave at default for auto-optimization")
batch_layout.addWidget(self.batch_spin)
batch_layout.addWidget(QLabel("(auto-optimized if default)"))
batch_layout.addStretch()
layout.addLayout(batch_layout)
# Num beams (for TrOCR)
beams_layout = QHBoxLayout()
beams_layout.addWidget(QLabel("Num Beams:"))
self.num_beams_spin = QSpinBox()
self.num_beams_spin.setRange(1, 10)
self.num_beams_spin.setValue(1)
self.num_beams_spin.setToolTip("Beam search width (1=greedy, 4=quality, slower)")
beams_layout.addWidget(self.num_beams_spin)
beams_layout.addStretch()
layout.addLayout(beams_layout)
self.beams_layout_widget = QWidget()
self.beams_layout_widget.setLayout(beams_layout)
self.beams_layout_widget.setVisible(False) # Hidden by default
# LightOnOCR-specific controls
self.lighton_group = QGroupBox("LightOnOCR Settings")
lighton_layout = QVBoxLayout()
# Longest edge
edge_layout = QHBoxLayout()
edge_layout.addWidget(QLabel("Longest Edge:"))
self.longest_edge_spin = QSpinBox()
self.longest_edge_spin.setRange(512, 1024)
self.longest_edge_spin.setValue(700)
self.longest_edge_spin.setSingleStep(50)
self.longest_edge_spin.setToolTip(
"Image resize target (512-1024, default 700)\n"
"Larger = better quality but slower and more VRAM"
)
edge_layout.addWidget(self.longest_edge_spin)
edge_layout.addWidget(QLabel("px"))
edge_layout.addStretch()
lighton_layout.addLayout(edge_layout)
# Max new tokens
tokens_layout = QHBoxLayout()
tokens_layout.addWidget(QLabel("Max Tokens:"))
self.max_new_tokens_spin = QSpinBox()
self.max_new_tokens_spin.setRange(64, 512)
self.max_new_tokens_spin.setValue(256)
self.max_new_tokens_spin.setSingleStep(32)
self.max_new_tokens_spin.setToolTip("Maximum output length (default 256)")
tokens_layout.addWidget(self.max_new_tokens_spin)
tokens_layout.addStretch()
lighton_layout.addLayout(tokens_layout)
# Custom prompt (optional)
prompt_layout = QVBoxLayout()
self.lighton_prompt_label = QLabel("Custom Prompt (optional):")
prompt_layout.addWidget(self.lighton_prompt_label)
self.lighton_prompt_edit = QLineEdit()
self.lighton_prompt_edit.setPlaceholderText("e.g., 'Transcribe the German shorthand text'")
self.lighton_prompt_edit.setToolTip("Leave empty for default OCR prompt")
prompt_layout.addWidget(self.lighton_prompt_edit)
lighton_layout.addLayout(prompt_layout)
self.lighton_group.setLayout(lighton_layout)
self.lighton_group.setVisible(False) # Hidden by default
layout.addWidget(self.lighton_group)
# DeepSeek-OCR-specific controls
self.deepseek_group = QGroupBox("DeepSeek-OCR Settings")
deepseek_layout = QVBoxLayout()
mode_layout = QHBoxLayout()
mode_layout.addWidget(QLabel("OCR Mode:"))
self.deepseek_mode_combo = QComboBox()
self.deepseek_mode_combo.addItems(["document", "free"])
self.deepseek_mode_combo.setToolTip(
"document: includes layout analysis (markdown output)\nfree: plain text output"
)
mode_layout.addWidget(self.deepseek_mode_combo)
mode_layout.addStretch()
deepseek_layout.addLayout(mode_layout)
self.deepseek_strip_md_check = QCheckBox("Strip Markdown formatting")
self.deepseek_strip_md_check.setToolTip("Remove markdown symbols from output text")
deepseek_layout.addWidget(self.deepseek_strip_md_check)
self.deepseek_group.setLayout(deepseek_layout)
self.deepseek_group.setVisible(False)
layout.addWidget(self.deepseek_group)
# PaddleOCR-specific controls
self.paddle_group = QGroupBox("PaddleOCR Settings")
paddle_layout = QVBoxLayout()
venv_layout = QHBoxLayout()
venv_layout.addWidget(QLabel("Venv path:"))
self.paddle_venv_edit = QLineEdit()
self.paddle_venv_edit.setPlaceholderText("venv_paddle (leave blank for default)")
self.paddle_venv_edit.setToolTip("Path to PaddleOCR virtualenv. Default: venv_paddle next to this script.")
venv_layout.addWidget(self.paddle_venv_edit)
paddle_venv_browse = QPushButton("Browse")
paddle_venv_browse.clicked.connect(self._browse_paddle_venv)
venv_layout.addWidget(paddle_venv_browse)
paddle_layout.addLayout(venv_layout)
lang_layout = QHBoxLayout()
lang_layout.addWidget(QLabel("Language:"))
self.paddle_lang_edit = QLineEdit("en")
self.paddle_lang_edit.setToolTip(
"PaddleOCR language code. Examples: en, ch, de, fr, ru, uk, la, ar, japan, korean"
)
lang_layout.addWidget(self.paddle_lang_edit)
lang_layout.addStretch()
paddle_layout.addLayout(lang_layout)
self.paddle_group.setLayout(paddle_layout)
self.paddle_group.setVisible(False)
layout.addWidget(self.paddle_group)
group.setLayout(layout)
return group
def _create_segmentation_group(self) -> QGroupBox:
"""Create segmentation options group."""
group = QGroupBox("Segmentation")
layout = QVBoxLayout()
# Method selection
method_layout = QHBoxLayout()
method_layout.addWidget(QLabel("Method:"))
self.seg_method_combo = QComboBox()
self.seg_method_combo.addItems(["kraken", "kraken-blla", "hpp", "none"])
self.seg_method_combo.setToolTip(
"kraken: Kraken classical segmentation\n"
"kraken-blla: Kraken Neural (blla) — multi-column, baseline-aware\n"
"hpp: Horizontal projection (fast)\n"
"none: Pre-segmented line images"
)
method_layout.addWidget(self.seg_method_combo)
layout.addLayout(method_layout)
# Custom segmentation model (for kraken-blla)
seg_model_layout = QHBoxLayout()
seg_model_layout.addWidget(QLabel("Seg Model:"))
self.seg_model_edit = QLineEdit()
self.seg_model_edit.setPlaceholderText("Default blla model (leave blank)")
self.seg_model_edit.setToolTip(
"Path to a custom kraken blla .mlmodel file.\n"
"Only used when segmentation method is kraken-blla.\n"
"Leave blank to use the built-in default.")
seg_model_browse = QPushButton("Browse…")
seg_model_browse.clicked.connect(self._browse_seg_model)
seg_model_layout.addWidget(self.seg_model_edit)
seg_model_layout.addWidget(seg_model_browse)
layout.addLayout(seg_model_layout)
# PAGE XML checkbox
self.pagexml_check = QCheckBox("Use PAGE XML (auto-detect from page/ folder)")
self.pagexml_check.setChecked(True)
self.pagexml_check.setToolTip("Auto-detect and use PAGE XML for segmentation")
layout.addWidget(self.pagexml_check)
# Sensitivity slider (for HPP/Kraken)
sens_layout = QHBoxLayout()
sens_layout.addWidget(QLabel("Sensitivity:"))
self.sensitivity_spin = QDoubleSpinBox()
self.sensitivity_spin.setRange(0.01, 1.0)
self.sensitivity_spin.setValue(0.1)
self.sensitivity_spin.setSingleStep(0.01)
self.sensitivity_spin.setDecimals(2)
self.sensitivity_spin.setToolTip("Segmentation sensitivity (lower = fewer lines)")
sens_layout.addWidget(self.sensitivity_spin)
sens_layout.addStretch()
layout.addLayout(sens_layout)
group.setLayout(layout)
return group
def _create_output_options_group(self) -> QGroupBox:
"""Create output options group."""
group = QGroupBox("Output Options")
layout = QVBoxLayout()
# Output formats
format_layout = QHBoxLayout()
format_layout.addWidget(QLabel("Formats:"))
self.txt_check = QCheckBox("TXT")
self.txt_check.setChecked(True)
format_layout.addWidget(self.txt_check)
self.csv_check = QCheckBox("CSV")
format_layout.addWidget(self.csv_check)
self.pagexml_out_check = QCheckBox("PAGE XML")
format_layout.addWidget(self.pagexml_out_check)
format_layout.addStretch()
layout.addLayout(format_layout)
# Flags
self.resume_check = QCheckBox("Resume (skip already processed images)")
self.resume_check.setChecked(False)
layout.addWidget(self.resume_check)
self.verbose_check = QCheckBox("Verbose logging")
self.verbose_check.setChecked(False)
layout.addWidget(self.verbose_check)
group.setLayout(layout)
return group
def _create_preset_group(self) -> QGroupBox:
"""Create preset management group."""
group = QGroupBox("Presets")
layout = QHBoxLayout()
self.preset_combo = QComboBox()
self.preset_combo.addItem("-- Custom --")
self.preset_combo.addItems(list(BUILTIN_PRESETS.keys()))
self.preset_combo.currentTextChanged.connect(self._on_preset_changed)
layout.addWidget(self.preset_combo)
self.save_preset_btn = QPushButton("Save")
self.save_preset_btn.clicked.connect(self._save_preset)
layout.addWidget(self.save_preset_btn)
self.load_preset_btn = QPushButton("Load")
self.load_preset_btn.clicked.connect(self._load_preset_file)
layout.addWidget(self.load_preset_btn)
layout.addStretch()
group.setLayout(layout)
return group
def _create_action_buttons(self) -> QHBoxLayout:
"""Create action buttons (Dry Run, Start)."""
layout = QHBoxLayout()
self.dry_run_btn = QPushButton("Dry Run (Test First)")
self.dry_run_btn.clicked.connect(self._run_dry_run)
self.dry_run_btn.setToolTip("Test configuration with first image")
layout.addWidget(self.dry_run_btn)
self.start_btn = QPushButton("Start Batch Processing")
self.start_btn.clicked.connect(self._start_batch)
self.start_btn.setStyleSheet("font-weight: bold; padding: 10px;")
layout.addWidget(self.start_btn)
return layout
def _browse_input_folder(self):
"""Browse for input folder."""
folder = QFileDialog.getExistingDirectory(self, "Select Input Folder")
if folder:
self.input_folder_edit.setText(folder)
def _browse_output_folder(self):
"""Browse for output folder."""
folder = QFileDialog.getExistingDirectory(self, "Select Output Folder")
if folder:
self.output_folder_edit.setText(folder)
def _browse_model_path(self):
"""Browse for model file."""
file_path, _ = QFileDialog.getOpenFileName(
self, "Select Model File", "",
"Model Files (*.pt *.pth *.safetensors *.mlmodel);;All Files (*)"
)
if file_path:
self.model_path_edit.setText(file_path)
def _browse_adapter_path(self):
"""Browse for adapter directory (Qwen3 LoRA)."""
folder = QFileDialog.getExistingDirectory(
self, "Select Adapter Directory", "models"
)
if folder:
self.adapter_edit.setText(folder)
def _browse_paddle_venv(self):
"""Browse for PaddleOCR venv directory."""
folder = QFileDialog.getExistingDirectory(self, "Select PaddleOCR Venv Directory")
if folder:
self.paddle_venv_edit.setText(folder)
def _refresh_openwebui_models(self):
"""Fetch available models from OpenWebUI API."""
api_key = self.api_key_edit.text().strip()
if not api_key:
self.openwebui_model_combo.clear()
self.openwebui_model_combo.addItem("Enter API key first")
return
try:
from openai import OpenAI
# Create temporary client to fetch models
client = OpenAI(
base_url="https://openwebui.uni-freiburg.de/api",
api_key=api_key
)
# Fetch models
models = client.models.list()
available_models = []
for model in models.data:
available_models.append(model.id)
# Update combo box
self.openwebui_model_combo.clear()
if available_models:
self.openwebui_model_combo.addItems(sorted(available_models))
print(f"[OpenWebUI] Loaded {len(available_models)} models")
else:
self.openwebui_model_combo.addItem("No models found")
self._update_command_preview()
except ImportError:
self.openwebui_model_combo.clear()
self.openwebui_model_combo.addItem("Error: openai package not installed")
except Exception as e:
print(f"Error fetching models: {e}")
self.openwebui_model_combo.clear()
self.openwebui_model_combo.addItem(f"Error: {str(e)[:40]}")
def _on_engine_changed(self, engine_name: str):
"""Handle engine selection change."""
if engine_name not in ENGINES:
return
config = ENGINES[engine_name]
# Show/hide model path/ID based on engine
self.model_path_edit.setEnabled(config.get("needs_model_path", True))
self.model_browse_btn.setEnabled(config.get("needs_model_path", True))
self.model_id_edit.setEnabled(config.get("needs_model_id", False))
# Update tooltip for model path (Qwen3 has special instructions)
if "model_path_tooltip" in config:
self.model_path_edit.setToolTip(config["model_path_tooltip"])
else:
self.model_path_edit.setToolTip("")
# Show/hide adapter path for Qwen3-VL
needs_adapter = config.get("needs_adapter", False)
self.adapter_label.setVisible(needs_adapter)
self.adapter_edit.setVisible(needs_adapter)
self.adapter_browse_btn.setVisible(needs_adapter)
# Show/hide line mode checkbox for Qwen3-VL
supports_line_mode = config.get("supports_line_mode", False)
self.line_mode_check.setVisible(supports_line_mode)
if not supports_line_mode:
self.line_mode_check.setChecked(False) # Reset when switching away
# Show/hide API key and model dropdown for OpenWebUI
needs_api_key = config.get("needs_api_key", False)
is_openwebui = (engine_name == "OpenWebUI")
self.api_key_label.setVisible(needs_api_key)
self.api_key_edit.setVisible(needs_api_key)
self.api_key_show_check.setVisible(needs_api_key)
self.openwebui_model_label.setVisible(is_openwebui)
self.openwebui_model_combo.setVisible(is_openwebui)
self.openwebui_refresh_btn.setVisible(is_openwebui)
# Auto-populate API key from environment if empty
if needs_api_key and not self.api_key_edit.text():
env_key = os.environ.get("OPENWEBUI_API_KEY", "")
if env_key:
self.api_key_edit.setText(env_key)
# Auto-refresh models if API key is available
if is_openwebui:
self._refresh_openwebui_models()
# Show/hide num_beams for TrOCR
self.beams_layout_widget.setVisible(config.get("supports_beams", False))
# Show/hide LightOnOCR-specific controls
has_lighton = config.get("has_lighton_options", False)
self.lighton_group.setVisible(has_lighton)
# Show/hide DeepSeek-OCR-specific controls
self.deepseek_group.setVisible(config.get("has_deepseek_options", False))
# Show/hide PaddleOCR-specific controls
self.paddle_group.setVisible(config.get("has_paddle_options", False))
# Set default segmentation method
default_seg = config.get("default_segmentation", "kraken")
idx = self.seg_method_combo.findText(default_seg)
if idx >= 0:
self.seg_method_combo.setCurrentIndex(idx)
# Show warning for slow engines
if "warning" in config:
QMessageBox.warning(self, "Engine Warning", config["warning"])
self._update_command_preview()
def _on_preset_changed(self, preset_name: str):
"""Load preset configuration."""
if preset_name == "-- Custom --":
return
if preset_name in BUILTIN_PRESETS:
self._load_preset_dict(BUILTIN_PRESETS[preset_name])
def _load_preset_dict(self, preset: Dict[str, Any]):
"""Load configuration from preset dictionary."""
# Engine
if "engine" in preset:
idx = self.engine_combo.findText(preset["engine"])
if idx >= 0:
self.engine_combo.setCurrentIndex(idx)
# Model
if "model_path" in preset:
self.model_path_edit.setText(preset["model_path"])
else:
self.model_path_edit.clear()
if "model_id" in preset:
self.model_id_edit.setText(preset["model_id"])
else:
self.model_id_edit.clear()
if "adapter" in preset:
self.adapter_edit.setText(preset["adapter"])
else:
self.adapter_edit.clear()
# Device
if "device" in preset:
idx = self.device_combo.findText(preset["device"])
if idx >= 0:
self.device_combo.setCurrentIndex(idx)
# Segmentation
if "segmentation_method" in preset:
idx = self.seg_method_combo.findText(preset["segmentation_method"])
if idx >= 0:
self.seg_method_combo.setCurrentIndex(idx)
if "use_pagexml" in preset:
self.pagexml_check.setChecked(preset["use_pagexml"])
# Output formats
if "output_formats" in preset:
formats = preset["output_formats"]
self.txt_check.setChecked("txt" in formats)
self.csv_check.setChecked("csv" in formats)
self.pagexml_out_check.setChecked("pagexml" in formats)
# Num beams
if "num_beams" in preset:
self.num_beams_spin.setValue(preset["num_beams"])
# Line mode
if "line_mode" in preset:
self.line_mode_check.setChecked(preset["line_mode"])
else:
self.line_mode_check.setChecked(False)
# LightOnOCR-specific
if "longest_edge" in preset:
self.longest_edge_spin.setValue(preset["longest_edge"])
else:
self.longest_edge_spin.setValue(700) # Reset to default
if "max_new_tokens" in preset:
self.max_new_tokens_spin.setValue(preset["max_new_tokens"])
else:
self.max_new_tokens_spin.setValue(256) # Reset to default
if "lighton_prompt" in preset:
self.lighton_prompt_edit.setText(preset["lighton_prompt"])
else:
self.lighton_prompt_edit.clear()
self._update_command_preview()
def _save_preset(self):
"""Save current configuration as preset."""
from PyQt6.QtWidgets import QInputDialog
name, ok = QInputDialog.getText(self, "Save Preset", "Preset name:")
if not ok or not name:
return
preset = self._get_current_config()
preset_file = Path.home() / ".config" / "polyscriptor" / "presets.json"
preset_file.parent.mkdir(parents=True, exist_ok=True)
# Load existing presets
presets = {}
if preset_file.exists():
try:
with open(preset_file, 'r') as f:
presets = json.load(f)
except:
pass
# Add new preset
presets[name] = preset
# Save
with open(preset_file, 'w') as f:
json.dump(presets, f, indent=2)
QMessageBox.information(self, "Preset Saved", f"Preset '{name}' saved successfully!")
# Update combo box
if self.preset_combo.findText(name) < 0:
self.preset_combo.addItem(name)
def _load_preset_file(self):
"""Load preset from file."""
preset_file = Path.home() / ".config" / "polyscriptor" / "presets.json"
if not preset_file.exists():
QMessageBox.warning(self, "No Presets", "No saved presets found.")
return
try:
with open(preset_file, 'r') as f:
presets = json.load(f)
if not presets:
QMessageBox.warning(self, "No Presets", "No saved presets found.")
return
from PyQt6.QtWidgets import QInputDialog
name, ok = QInputDialog.getItem(
self, "Load Preset", "Select preset:", list(presets.keys()), 0, False
)
if ok and name:
self._load_preset_dict(presets[name])
except Exception as e:
QMessageBox.critical(self, "Error", f"Failed to load presets: {e}")
def _browse_seg_model(self):
"""Open file dialog to select a custom blla segmentation model."""
from PyQt6.QtWidgets import QFileDialog
path, _ = QFileDialog.getOpenFileName(
self, "Select Segmentation Model", "",
"Kraken Models (*.mlmodel);;All Files (*)"
)
if path:
self.seg_model_edit.setText(path)
def _get_current_config(self) -> Dict[str, Any]:
"""Get current configuration as dictionary."""
config = {
"input_folder": self.input_folder_edit.text(),
"output_folder": self.output_folder_edit.text(),
"engine": self.engine_combo.currentText(),
"device": self.device_combo.currentText(),
"segmentation_method": self.seg_method_combo.currentText(),
"seg_model": self.seg_model_edit.text().strip() or None,
"use_pagexml": self.pagexml_check.isChecked(),
}
# Model
if self.model_path_edit.text():
config["model_path"] = self.model_path_edit.text()
# For OpenWebUI, use the model dropdown instead of model_id_edit
if config["engine"] == "OpenWebUI":
model_text = self.openwebui_model_combo.currentText()
# Only use if it's a valid model (not placeholder text)
if model_text and not model_text.startswith(("Click", "Enter", "Error", "No models")):
config["model_id"] = model_text
elif self.model_id_edit.text():
config["model_id"] = self.model_id_edit.text()
if self.adapter_edit.text():
config["adapter"] = self.adapter_edit.text()
# API key (for OpenWebUI)
if self.api_key_edit.text():
config["api_key"] = self.api_key_edit.text()
# Line mode (for line-trained Qwen3 models)
if self.line_mode_check.isChecked():
config["line_mode"] = True
# Output formats
formats = []
if self.txt_check.isChecked():
formats.append("txt")
if self.csv_check.isChecked():
formats.append("csv")
if self.pagexml_out_check.isChecked():
formats.append("pagexml")
config["output_formats"] = formats
# Flags
config["resume"] = self.resume_check.isChecked()
config["verbose"] = self.verbose_check.isChecked()
# Engine-specific
if self.num_beams_spin.value() > 1:
config["num_beams"] = self.num_beams_spin.value()
if self.sensitivity_spin.value() != 0.1:
config["sensitivity"] = self.sensitivity_spin.value()
# LightOnOCR-specific
if config["engine"] == "LightOnOCR":
config["longest_edge"] = self.longest_edge_spin.value()
config["max_new_tokens"] = self.max_new_tokens_spin.value()
prompt = self.lighton_prompt_edit.text().strip()