forked from achimrabus/polyscriptor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtranscription_gui_plugin.py
More file actions
2171 lines (1814 loc) · 88.4 KB
/
transcription_gui_plugin.py
File metadata and controls
2171 lines (1814 loc) · 88.4 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
"""
HTR Transcription GUI - Plugin-Based Version
Unified interface for multiple HTR engines using the plugin system.
Features:
- Dropdown engine selection (TrOCR, Qwen3, CRNN-CTC, Commercial APIs)
- Dynamic configuration panels per engine
- Seamless zoom/pan with QGraphicsView
- Drag & drop + file dialog import
- Automatic line segmentation
- Export to TXT/CSV
Usage:
python transcription_gui_plugin.py
"""
import sys
import json
import time
from pathlib import Path
# Windows console defaults to CP-1252; reconfigure to UTF-8 so Cyrillic output
# and emoji from engine code don't raise UnicodeEncodeError. No-op on Linux/macOS.
if sys.platform == "win32":
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
except AttributeError:
pass # Python < 3.7 — reconfigure not available
from typing import List, Optional, Tuple, Dict, Any
import numpy as np
from PIL import Image
# Disable PIL DecompressionBomb protection for large manuscript images
Image.MAX_IMAGE_PIXELS = None
from PyQt6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QGridLayout,
QSplitter, QGraphicsView, QGraphicsScene, QGraphicsPixmapItem,
QPushButton, QLabel, QTextEdit, QLineEdit, QComboBox,
QFileDialog, QProgressBar, QStatusBar, QMessageBox,
QListWidget, QListWidgetItem, QGroupBox, QScrollArea, QSlider, QSpinBox, QCheckBox,
QFontDialog, QToolButton, QSizePolicy, QStackedWidget
)
from PyQt6.QtCore import Qt, QThread, pyqtSignal, QRectF, QPointF, QSettings
from PyQt6.QtGui import QPixmap, QImage, QPainter, QPen, QColor, QFont, QAction, QShortcut, QKeySequence, QPalette
# Import segmentation components
from inference_page import LineSegmenter, PageXMLSegmenter, LineSegment
from page_xml_exporter import PageXMLExporter
# Import HTR Engine Plugin System
from htr_engine_base import get_global_registry, HTREngine, TranscriptionResult
# Import comparison widget
from comparison_widget import ComparisonWidget
# Import logo handler
from logo_handler import get_logo_handler
# Get available engines
engine_registry = get_global_registry()
available_engines = engine_registry.get_available_engines()
print(f"HTR Engine Plugin System: {len(available_engines)} engines available")
for engine in available_engines:
print(f" - {engine.get_name()}: {engine.get_description()}")
class CollapsibleSection(QWidget):
"""Section with a clickable header that collapses/expands its content."""
def __init__(self, title, expanded=True, parent=None):
super().__init__(parent)
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
# Header button (full-width, checkable, with arrow indicator)
self._header = QToolButton()
self._header.setText(title)
self._header.setCheckable(True)
self._header.setChecked(expanded)
self._header.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
self._header.setArrowType(
Qt.ArrowType.DownArrow if expanded else Qt.ArrowType.RightArrow
)
self._header.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
self._header.setStyleSheet(
"QToolButton { font-weight: bold; border: 1px solid palette(mid); "
"border-radius: 3px; padding: 4px 8px; background: palette(button); "
"color: palette(buttonText); }"
"QToolButton:hover { background: palette(midlight); }"
)
self._header.toggled.connect(self._on_toggled)
layout.addWidget(self._header)
# Content area
self._content = QWidget()
self.content_layout = QVBoxLayout(self._content)
self.content_layout.setContentsMargins(2, 4, 2, 4)
self._content.setVisible(expanded)
layout.addWidget(self._content)
def _on_toggled(self, checked):
self._content.setVisible(checked)
self._header.setArrowType(
Qt.ArrowType.DownArrow if checked else Qt.ArrowType.RightArrow
)
# Notify parent layout that our size hint changed
self.updateGeometry()
def set_expanded(self, expanded):
self._header.setChecked(expanded)
def is_expanded(self):
return self._header.isChecked()
class ZoomableGraphicsView(QGraphicsView):
"""Graphics view with smooth zoom and pan capabilities."""
rects_changed = pyqtSignal(int) # emits len(drawn_rects) after add/clear
escape_pressed = pyqtSignal()
def __init__(self):
super().__init__()
self.setRenderHint(QPainter.RenderHint.Antialiasing)
self.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform)
self.setDragMode(QGraphicsView.DragMode.ScrollHandDrag)
self.setTransformationAnchor(QGraphicsView.ViewportAnchor.AnchorUnderMouse)
self.setResizeAnchor(QGraphicsView.ViewportAnchor.AnchorUnderMouse)
self._zoom = 0
self._empty = True
self._scene = QGraphicsScene(self)
self.setScene(self._scene)
self.line_items = []
# Draw mode state
self.draw_mode: bool = False
self.drawn_rects: List[Tuple[int, int, int, int]] = []
self.drawn_rect_items: List = []
self._drag_start = None # QPointF (scene coords) while dragging
self._drag_item = None # live QGraphicsRectItem during drag
def has_image(self):
return not self._empty
def fit_in_view(self):
"""Fit image to view."""
rect = QRectF(self._scene.itemsBoundingRect())
if not rect.isNull():
self.fitInView(rect, Qt.AspectRatioMode.KeepAspectRatio)
self._zoom = 0
def set_image(self, pixmap: QPixmap):
"""Load image into view."""
self._scene.clear()
self.line_items = []
self.drawn_rect_items = []
self.drawn_rects = []
self._drag_start = None
self._drag_item = None
self._scene.addPixmap(pixmap)
self._empty = False
self.fit_in_view()
def draw_line_boxes(self, lines: List[LineSegment], color: QColor = QColor(0, 255, 0)):
"""Draw bounding boxes for detected lines."""
# Remove old boxes
for item in self.line_items:
self._scene.removeItem(item)
self.line_items = []
# Draw new boxes
pen = QPen(color)
pen.setWidth(2)
for line in lines:
x1, y1, x2, y2 = line.bbox
rect_item = self._scene.addRect(x1, y1, x2 - x1, y2 - y1, pen)
self.line_items.append(rect_item)
def wheelEvent(self, event):
"""Zoom with mouse wheel."""
if self.has_image():
factor = 1.25 if event.angleDelta().y() > 0 else 0.8
self.scale(factor, factor)
self._zoom += 1 if factor > 1 else -1
def set_draw_mode(self, enabled: bool):
"""Toggle rectangle draw mode on/off."""
self.draw_mode = enabled
if enabled:
self.setDragMode(QGraphicsView.DragMode.NoDrag)
self.setCursor(Qt.CursorShape.CrossCursor)
else:
if self._drag_item is not None:
self._scene.removeItem(self._drag_item)
self._drag_item = None
self._drag_start = None
self.setDragMode(QGraphicsView.DragMode.ScrollHandDrag)
self.setCursor(Qt.CursorShape.ArrowCursor)
def clear_drawn_rects(self):
"""Remove all drawn rectangles from the scene."""
for item in self.drawn_rect_items:
self._scene.removeItem(item)
self.drawn_rect_items = []
self.drawn_rects = []
if self._drag_item is not None:
self._scene.removeItem(self._drag_item)
self._drag_item = None
self.rects_changed.emit(0)
def mousePressEvent(self, event):
if self.draw_mode and event.button() == Qt.MouseButton.LeftButton:
self._drag_start = self.mapToScene(event.pos())
pen = QPen(QColor(180, 0, 0))
pen.setWidth(2)
pen.setStyle(Qt.PenStyle.DashLine)
self._drag_item = self._scene.addRect(
self._drag_start.x(), self._drag_start.y(), 0, 0, pen
)
event.accept()
else:
super().mousePressEvent(event)
def mouseMoveEvent(self, event):
if self.draw_mode and self._drag_start is not None:
pos = self.mapToScene(event.pos())
x1 = min(self._drag_start.x(), pos.x())
y1 = min(self._drag_start.y(), pos.y())
x2 = max(self._drag_start.x(), pos.x())
y2 = max(self._drag_start.y(), pos.y())
self._drag_item.setRect(x1, y1, x2 - x1, y2 - y1)
event.accept()
else:
super().mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
if self.draw_mode and event.button() == Qt.MouseButton.LeftButton:
if self._drag_start is not None:
pos = self.mapToScene(event.pos())
x1 = int(min(self._drag_start.x(), pos.x()))
y1 = int(min(self._drag_start.y(), pos.y()))
x2 = int(max(self._drag_start.x(), pos.x()))
y2 = int(max(self._drag_start.y(), pos.y()))
if (x2 - x1) >= 10 and (y2 - y1) >= 10:
self.drawn_rects.append((x1, y1, x2, y2))
self.drawn_rect_items.append(self._drag_item)
self.rects_changed.emit(len(self.drawn_rects))
else:
self._scene.removeItem(self._drag_item)
self._drag_start = None
self._drag_item = None
event.accept()
else:
super().mouseReleaseEvent(event)
def keyPressEvent(self, event):
if self.draw_mode and event.key() == Qt.Key.Key_Escape:
self.escape_pressed.emit()
event.accept()
else:
super().keyPressEvent(event)
class StatisticsPanel(QWidget):
"""Panel displaying transcription metadata and statistics."""
def __init__(self, parent=None):
super().__init__(parent)
self._init_ui()
self.clear()
def _init_ui(self):
"""Initialize UI components."""
layout = QVBoxLayout(self)
layout.setContentsMargins(5, 5, 5, 5)
layout.setSpacing(8)
# Model Information Group
model_group = QGroupBox("Model Information")
model_layout = QGridLayout()
model_layout.setColumnStretch(1, 1)
model_layout.setSpacing(5)
model_layout.addWidget(QLabel("Engine:"), 0, 0)
self.lbl_engine = QLabel("N/A")
self.lbl_engine.setStyleSheet("font-weight: bold;")
model_layout.addWidget(self.lbl_engine, 0, 1)
model_layout.addWidget(QLabel("Model:"), 1, 0)
self.lbl_model = QLabel("N/A")
self.lbl_model.setWordWrap(True)
self.lbl_model.setStyleSheet("font-size: 10pt;")
model_layout.addWidget(self.lbl_model, 1, 1)
model_group.setLayout(model_layout)
layout.addWidget(model_group)
# Transcription Statistics Group
stats_group = QGroupBox("Statistics")
stats_layout = QGridLayout()
stats_layout.setColumnStretch(1, 1)
stats_layout.setSpacing(5)
stats_layout.addWidget(QLabel("Lines:"), 0, 0)
self.lbl_lines = QLabel("0")
stats_layout.addWidget(self.lbl_lines, 0, 1)
stats_layout.addWidget(QLabel("Characters:"), 1, 0)
self.lbl_chars = QLabel("0")
stats_layout.addWidget(self.lbl_chars, 1, 1)
stats_group.setLayout(stats_layout)
layout.addWidget(stats_group)
# Timing Statistics Group
timing_group = QGroupBox("Performance")
timing_layout = QGridLayout()
timing_layout.setColumnStretch(1, 1)
timing_layout.setSpacing(5)
timing_layout.addWidget(QLabel("Time:"), 0, 0)
self.lbl_time = QLabel("0.0s")
timing_layout.addWidget(self.lbl_time, 0, 1)
timing_layout.addWidget(QLabel("Speed:"), 1, 0)
self.lbl_speed = QLabel("0.0 l/s")
timing_layout.addWidget(self.lbl_speed, 1, 1)
timing_group.setLayout(timing_layout)
layout.addWidget(timing_group)
# Confidence Statistics Group
conf_group = QGroupBox("Confidence")
conf_layout = QGridLayout()
conf_layout.setColumnStretch(1, 1)
conf_layout.setSpacing(5)
conf_layout.addWidget(QLabel("Average:"), 0, 0)
self.lbl_avg_conf = QLabel("N/A")
conf_layout.addWidget(self.lbl_avg_conf, 0, 1)
conf_layout.addWidget(QLabel("Range:"), 1, 0)
self.lbl_conf_range = QLabel("N/A")
conf_layout.addWidget(self.lbl_conf_range, 1, 1)
conf_layout.addWidget(QLabel("Low (<80%):"), 2, 0)
self.lbl_low_conf = QLabel("0")
conf_layout.addWidget(self.lbl_low_conf, 2, 1)
conf_group.setLayout(conf_layout)
layout.addWidget(conf_group)
layout.addStretch()
def clear(self):
"""Clear all statistics."""
self.lbl_engine.setText("N/A")
self.lbl_model.setText("N/A")
self.lbl_lines.setText("0")
self.lbl_chars.setText("0")
self.lbl_time.setText("0.0s")
self.lbl_speed.setText("0.0 l/s")
self.lbl_avg_conf.setText("N/A")
self.lbl_conf_range.setText("N/A")
self.lbl_low_conf.setText("0")
def update_statistics(self, stats: Dict[str, Any]):
"""Update statistics display with new data."""
# Model information
if "engine" in stats:
self.lbl_engine.setText(stats["engine"])
if "model_name" in stats:
model_name = stats["model_name"]
# Truncate long paths
if len(model_name) > 40:
model_name = "..." + model_name[-37:]
self.lbl_model.setText(model_name)
# Transcription statistics
if "line_count" in stats:
self.lbl_lines.setText(str(stats["line_count"]))
if "char_count" in stats:
self.lbl_chars.setText(f"{stats['char_count']:,}")
# Timing statistics
if "inference_time" in stats:
time_val = stats["inference_time"]
self.lbl_time.setText(f"{time_val:.2f}s")
# Calculate speed
line_count = stats.get("line_count", 0)
if line_count > 0 and time_val > 0:
speed = line_count / time_val
self.lbl_speed.setText(f"{speed:.2f} l/s")
# Confidence statistics
if "avg_confidence" in stats:
avg = stats["avg_confidence"]
if avg is not None:
self.lbl_avg_conf.setText(f"{avg*100:.1f}%")
# Color code by confidence
if avg >= 0.9:
color = "green"
elif avg >= 0.75:
color = "orange"
else:
color = "red"
self.lbl_avg_conf.setStyleSheet(f"color: {color}; font-weight: bold;")
if "min_confidence" in stats and "max_confidence" in stats:
min_conf = stats["min_confidence"]
max_conf = stats["max_confidence"]
if min_conf is not None and max_conf is not None:
self.lbl_conf_range.setText(f"{min_conf*100:.0f}% - {max_conf*100:.0f}%")
if "low_confidence_lines" in stats:
self.lbl_low_conf.setText(str(stats["low_confidence_lines"]))
class TranscriptionWorker(QThread):
"""Background worker for HTR transcription."""
progress = pyqtSignal(int, int, str) # current, total, text
finished = pyqtSignal(list, dict) # List of transcriptions, metadata dict
error = pyqtSignal(str)
def __init__(self, engine: HTREngine, line_segments: List[LineSegment], image: Image.Image, image_path: Optional[Path] = None):
super().__init__()
self.engine = engine
self.line_segments = line_segments
self.image = image
self.image_path = image_path # Store original image path for Party
def run(self):
"""Process all line segments."""
import time
start_time = time.time()
try:
transcriptions = []
results_with_confidence = [] # Store full results for confidence stats
# Check if engine prefers batch processing with original image context
# (CRITICAL for Party to correctly recognize scripts like Glagolitic)
if hasattr(self.engine, 'prefers_batch_with_context') and self.engine.prefers_batch_with_context() and self.image_path:
# Batch processing with original image (Party-specific)
line_images = []
line_bboxes = []
for line_seg in self.line_segments:
x1, y1, x2, y2 = line_seg.bbox
line_img = self.image.crop((x1, y1, x2, y2))
line_array = np.array(line_img)
line_images.append(line_array)
line_bboxes.append((x1, y1, x2, y2))
# Call batch transcription with original image context
results = self.engine.transcribe_lines(
line_images,
config=None,
original_image_path=str(self.image_path),
line_bboxes=line_bboxes
)
# Extract text from results
for i, result in enumerate(results):
text = str(result.text) if hasattr(result, 'text') else str(result)
transcriptions.append(text)
results_with_confidence.append(result)
self.progress.emit(i + 1, len(self.line_segments), text)
else:
# Line-by-line processing (default behavior)
for i, line_seg in enumerate(self.line_segments):
# Crop line from image
x1, y1, x2, y2 = line_seg.bbox
line_img = self.image.crop((x1, y1, x2, y2))
line_array = np.array(line_img)
# Transcribe with engine
result = self.engine.transcribe_line(line_array)
# Ensure we get the text as a string
text = str(result.text) if hasattr(result, 'text') else str(result)
transcriptions.append(text)
results_with_confidence.append(result)
self.progress.emit(i + 1, len(self.line_segments), text)
# Calculate statistics
elapsed_time = time.time() - start_time
# Build metadata dictionary
metadata = {
"inference_time": elapsed_time,
"line_count": len(transcriptions),
"char_count": sum(len(t) for t in transcriptions),
"engine": self.engine.get_name() if hasattr(self.engine, 'get_name') else "Unknown"
}
# Extract confidence statistics if available
confidences = []
for result in results_with_confidence:
if hasattr(result, 'confidence') and result.confidence is not None:
# Ensure confidence is a valid number (0-1 range)
conf = float(result.confidence)
if 0 <= conf <= 1:
confidences.append(conf)
elif conf > 1:
# If confidence is in percentage (0-100), normalize it
confidences.append(conf / 100.0)
if confidences:
metadata["avg_confidence"] = sum(confidences) / len(confidences)
metadata["min_confidence"] = min(confidences)
metadata["max_confidence"] = max(confidences)
metadata["low_confidence_lines"] = sum(1 for c in confidences if c < 0.8)
else:
# No confidence data available
metadata["avg_confidence"] = None
metadata["min_confidence"] = None
metadata["max_confidence"] = None
metadata["low_confidence_lines"] = 0
# Add model name from engine metadata
if results_with_confidence and hasattr(results_with_confidence[0], 'metadata'):
result_meta = results_with_confidence[0].metadata
if isinstance(result_meta, dict) and 'model' in result_meta:
metadata["model_name"] = result_meta['model']
self.finished.emit(transcriptions, metadata)
except Exception as e:
self.error.emit(str(e))
class TranscriptionGUI(QMainWindow):
"""Main GUI window."""
def __init__(self):
super().__init__()
self.setWindowTitle("Polyscriptor - Multi-Engine HTR Tool")
self.setGeometry(100, 100, 1400, 900)
# Set application icon
logo_handler = get_logo_handler()
self.setWindowIcon(logo_handler.get_icon())
# State
self.current_image_path: Optional[Path] = None
self.current_image: Optional[Image.Image] = None
self.line_segments: List[LineSegment] = []
self.transcriptions: List[str] = []
self.current_engine: Optional[HTREngine] = None
self.transcription_engine: Optional[HTREngine] = None # engine that produced self.transcriptions
self.worker: Optional[TranscriptionWorker] = None
self.comparison_widget: Optional[ComparisonWidget] = None
self.comparison_mode_active: bool = False
self.regions: list = [] # SegRegion list from blla segmentation
# Multi-page navigation state
self.image_list: List[Path] = []
self.current_image_index: int = -1
# Cache config widgets to prevent deletion
self.config_widgets_cache: Dict[str, QWidget] = {}
self.setup_ui()
self.restore_settings()
def setup_ui(self):
"""Setup user interface."""
central_widget = QWidget()
self.setCentralWidget(central_widget)
# Main container layout
container_layout = QVBoxLayout(central_widget)
container_layout.setContentsMargins(0, 0, 0, 0)
# Top-level splitter: Image panel (left) ↔ Controls+Results (right)
self.main_splitter = QSplitter(Qt.Orientation.Horizontal)
self.main_splitter.setHandleWidth(4)
self.main_splitter.setStyleSheet("""
QSplitter::handle {
background-color: palette(mid);
}
QSplitter::handle:hover {
background-color: palette(midlight);
}
""")
container_layout.addWidget(self.main_splitter)
# Left panel: Image view
left_panel = QWidget()
left_layout = QVBoxLayout(left_panel)
# Logo display at top (smaller on FHD to save space)
logo_handler = get_logo_handler()
logo_label = QLabel()
screen_height = QApplication.primaryScreen().availableGeometry().height()
logo_width = 200 if screen_height < 1200 else 300
logo_pixmap = logo_handler.get_logo_pixmap(width=logo_width)
logo_label.setPixmap(logo_pixmap)
logo_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
logo_label.setStyleSheet("padding: 5px;" if screen_height < 1200 else "padding: 10px;")
left_layout.addWidget(logo_label)
# Image view
self.image_view = ZoomableGraphicsView()
left_layout.addWidget(self.image_view)
# Image controls - row 1: load and segmentation
img_controls = QHBoxLayout()
btn_load = QPushButton("Load Images...")
btn_load.clicked.connect(self._load_images)
btn_load.setToolTip("Select one or more images to process (Ctrl+O)")
QShortcut(QKeySequence("Ctrl+O"), self, self._load_images)
img_controls.addWidget(btn_load)
btn_segment = QPushButton("Segment Lines")
btn_segment.clicked.connect(self.segment_lines)
img_controls.addWidget(btn_segment)
btn_fit = QPushButton("Fit to View")
btn_fit.clicked.connect(self.image_view.fit_in_view)
img_controls.addWidget(btn_fit)
left_layout.addLayout(img_controls)
# Draw mode controls: rectangle drawing for manual re-segmentation
# Hidden until blla segmentation populates self.regions
self.draw_controls_widget = QWidget()
draw_controls = QHBoxLayout(self.draw_controls_widget)
draw_controls.setContentsMargins(0, 0, 0, 0)
self.btn_draw_mode = QPushButton("Draw Regions")
self.btn_draw_mode.setCheckable(True)
self.btn_draw_mode.setToolTip(
"Toggle draw mode: click and drag to draw rectangles on the image.\n"
"Each rectangle marks an area to re-segment with blla.\n"
"Press Escape or click again to exit draw mode.")
draw_controls.addWidget(self.btn_draw_mode)
self.btn_resegment_drawn = QPushButton("Re-segment Drawn")
self.btn_resegment_drawn.setEnabled(False)
self.btn_resegment_drawn.setToolTip(
"Run blla segmentation within each drawn rectangle.\n"
"Replaces existing regions that overlap the drawn areas.")
draw_controls.addWidget(self.btn_resegment_drawn)
btn_clear_drawn = QPushButton("Clear Drawn")
btn_clear_drawn.setToolTip("Remove all drawn rectangles.")
draw_controls.addWidget(btn_clear_drawn)
self.draw_controls_widget.setVisible(False)
left_layout.addWidget(self.draw_controls_widget)
self.btn_draw_mode.toggled.connect(self._toggle_draw_mode)
self.btn_resegment_drawn.clicked.connect(self._resegment_drawn_regions)
btn_clear_drawn.clicked.connect(self._clear_drawn_regions)
self.image_view.rects_changed.connect(
lambda n: self.btn_resegment_drawn.setEnabled(n > 0))
self.image_view.escape_pressed.connect(
lambda: self.btn_draw_mode.setChecked(False))
# Image navigation - row 2: prev/next buttons and page counter
nav_controls = QHBoxLayout()
self.btn_prev_image = QPushButton("< Prev")
self.btn_prev_image.clicked.connect(self._load_previous_image)
self.btn_prev_image.setEnabled(False)
self.btn_prev_image.setToolTip("Previous image (PageUp)")
nav_controls.addWidget(self.btn_prev_image)
self.lbl_image_index = QLabel("No images loaded")
self.lbl_image_index.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.lbl_image_index.setMinimumWidth(100)
nav_controls.addWidget(self.lbl_image_index, stretch=1)
self.btn_next_image = QPushButton("Next >")
self.btn_next_image.clicked.connect(self._load_next_image)
self.btn_next_image.setEnabled(False)
self.btn_next_image.setToolTip("Next image (PageDown)")
nav_controls.addWidget(self.btn_next_image)
left_layout.addLayout(nav_controls)
# Add left panel to main splitter
self.main_splitter.addWidget(left_panel)
# Right panel: Controls and Results
right_panel = QWidget()
right_layout = QVBoxLayout(right_panel)
# --- Segmentation Settings (collapsible) ---
self.seg_section = CollapsibleSection("Segmentation Settings")
seg_layout = self.seg_section.content_layout
# Check if Kraken is available
try:
from kraken_segmenter import KrakenLineSegmenter
KRAKEN_AVAILABLE = True
except ImportError:
KRAKEN_AVAILABLE = False
# Method selector
method_layout = QHBoxLayout()
method_layout.addWidget(QLabel("Method:"))
self.seg_method_combo = QComboBox()
self.seg_method_combo.addItem("HPP (Fast)", "HPP")
if KRAKEN_AVAILABLE:
self.seg_method_combo.addItem("Kraken Classical", "Kraken")
self.seg_method_combo.addItem("Kraken Neural (blla)", "KrakenBLLA")
self.seg_method_combo.setCurrentIndex(1) # Default to Kraken Classical if available
else:
self.seg_method_combo.addItem("Kraken (Not installed)", None)
self.seg_method_combo.model().item(1).setEnabled(False)
self.seg_method_combo.currentIndexChanged.connect(self._on_seg_method_changed)
method_layout.addWidget(self.seg_method_combo)
seg_layout.addLayout(method_layout)
# HPP-specific parameters
self.hpp_params_widget = QWidget()
hpp_layout = QVBoxLayout()
hpp_layout.setContentsMargins(0, 0, 0, 0)
sensitivity_layout = QHBoxLayout()
sensitivity_layout.addWidget(QLabel("Threshold:"))
self.sensitivity_slider = QSlider(Qt.Orientation.Horizontal)
self.sensitivity_slider.setRange(5, 150) # 0.5% to 15%
self.sensitivity_slider.setValue(50) # Default 5%
self.sensitivity_label = QLabel("5.0%")
self.sensitivity_slider.valueChanged.connect(
lambda v: self.sensitivity_label.setText(f"{v/10:.1f}%")
)
self.sensitivity_slider.setToolTip("Detection threshold: Higher = more selective (0.5-15%)")
sensitivity_layout.addWidget(self.sensitivity_slider)
sensitivity_layout.addWidget(self.sensitivity_label)
hpp_layout.addLayout(sensitivity_layout)
min_height_layout = QHBoxLayout()
min_height_layout.addWidget(QLabel("Min Height:"))
self.min_height_spin = QSpinBox()
self.min_height_spin.setRange(5, 100)
self.min_height_spin.setValue(10)
self.min_height_spin.setSuffix(" px")
self.min_height_spin.setToolTip("Minimum line height in pixels")
min_height_layout.addWidget(self.min_height_spin)
min_height_layout.addStretch()
hpp_layout.addLayout(min_height_layout)
self.use_morph_check = QCheckBox("Morph. Ops")
self.use_morph_check.setChecked(True)
self.use_morph_check.setToolTip("Apply morphological operations to connect broken characters")
hpp_layout.addWidget(self.use_morph_check)
self.hpp_params_widget.setLayout(hpp_layout)
seg_layout.addWidget(self.hpp_params_widget)
# Kraken-specific parameters
self.kraken_params_widget = QWidget()
kraken_layout = QVBoxLayout()
kraken_layout.setContentsMargins(0, 0, 0, 0)
self.use_binarization_check = QCheckBox("Use Binarization")
self.use_binarization_check.setChecked(True)
self.use_binarization_check.setToolTip("Apply neural binarization preprocessing (recommended for degraded documents)")
kraken_layout.addWidget(self.use_binarization_check)
self.kraken_params_widget.setLayout(kraken_layout)
seg_layout.addWidget(self.kraken_params_widget)
# Kraken Neural (blla) parameters
self.blla_params_widget = QWidget()
blla_layout = QVBoxLayout()
blla_layout.setContentsMargins(0, 0, 0, 0)
blla_device_layout = QHBoxLayout()
blla_device_layout.addWidget(QLabel("Device:"))
self.blla_device_combo = QComboBox()
self.blla_device_combo.addItem("CPU", "cpu")
try:
import torch
if torch.cuda.is_available():
for i in range(torch.cuda.device_count()):
name = torch.cuda.get_device_name(i)
self.blla_device_combo.addItem(f"GPU {i}: {name}", f"cuda:{i}")
# Default to first GPU (only if GPUs were actually added)
if torch.cuda.device_count() > 0:
self.blla_device_combo.setCurrentIndex(1)
except ImportError:
pass
blla_device_layout.addWidget(self.blla_device_combo)
blla_layout.addLayout(blla_device_layout)
# Max columns
blla_cols_layout = QHBoxLayout()
blla_cols_layout.addWidget(QLabel("Max Columns:"))
self.blla_max_columns_spin = QSpinBox()
self.blla_max_columns_spin.setRange(1, 8)
self.blla_max_columns_spin.setValue(4)
self.blla_max_columns_spin.setToolTip(
"Maximum number of text columns to detect per region (1-8).\n"
"Set to 2 for single-page two-column, 4 for double-page two-column.")
blla_cols_layout.addWidget(self.blla_max_columns_spin)
blla_cols_layout.addStretch()
blla_layout.addLayout(blla_cols_layout)
# Split width threshold
blla_split_layout = QHBoxLayout()
blla_split_layout.addWidget(QLabel("Split Width:"))
self.blla_split_slider = QSlider(Qt.Orientation.Horizontal)
self.blla_split_slider.setRange(10, 80) # 10% to 80%
self.blla_split_slider.setValue(40) # default 40%
self.blla_split_label = QLabel("40%")
self.blla_split_slider.valueChanged.connect(
lambda v: self.blla_split_label.setText(f"{v}%")
)
self.blla_split_slider.setToolTip(
"Regions wider than this % of page width get sub-split into columns.\n"
"Lower = more aggressive splitting.\n"
"Portrait single-page: 40% (default)\n"
"Landscape double-page: try 20-25%")
blla_split_layout.addWidget(self.blla_split_slider)
blla_split_layout.addWidget(self.blla_split_label)
blla_layout.addLayout(blla_split_layout)
# Min lines to split
blla_minlines_layout = QHBoxLayout()
blla_minlines_layout.addWidget(QLabel("Min Lines:"))
self.blla_min_lines_spin = QSpinBox()
self.blla_min_lines_spin.setRange(3, 50)
self.blla_min_lines_spin.setValue(10)
self.blla_min_lines_spin.setToolTip(
"Minimum lines in a region before attempting column split.\n"
"Lower = split regions with fewer lines.")
blla_minlines_layout.addWidget(self.blla_min_lines_spin)
blla_minlines_layout.addStretch()
blla_layout.addLayout(blla_minlines_layout)
# Custom model path
blla_model_layout = QHBoxLayout()
blla_model_layout.addWidget(QLabel("Model:"))
self.blla_model_edit = QLineEdit()
self.blla_model_edit.setPlaceholderText("Default (pagexml/blla.mlmodel)")
self.blla_model_edit.setToolTip(
"Path to a custom kraken blla .mlmodel segmentation file.\n"
"Leave blank to use the built-in default (pagexml/blla.mlmodel).\n"
"Any kraken blla-compatible model can be used here.")
blla_model_btn = QPushButton("Browse…")
blla_model_btn.clicked.connect(self._browse_blla_model)
blla_model_layout.addWidget(self.blla_model_edit)
blla_model_layout.addWidget(blla_model_btn)
blla_layout.addLayout(blla_model_layout)
self.blla_params_widget.setLayout(blla_layout)
seg_layout.addWidget(self.blla_params_widget)
# Set initial visibility based on default method
self._on_seg_method_changed(self.seg_method_combo.currentIndex())
right_layout.addWidget(self.seg_section)
# --- HTR Engine (collapsible) ---
self.engine_section = CollapsibleSection("HTR Engine", expanded=False)
engine_content = self.engine_section.content_layout
self.engine_combo = QComboBox()
if not available_engines:
self.engine_combo.addItem("No engines available")
else:
for engine in available_engines:
self.engine_combo.addItem(engine.get_name())
self.engine_combo.currentTextChanged.connect(self.on_engine_changed)
engine_content.addWidget(self.engine_combo)
# Engine description
self.engine_desc_label = QLabel("")
self.engine_desc_label.setWordWrap(True)
self.engine_desc_label.setStyleSheet("color: gray; font-size: 12pt;")
engine_content.addWidget(self.engine_desc_label)
# Dynamic engine configuration container
# Wrapped in a scroll area so tall configs don't push export buttons off-screen.
# No minimum height (collapses if empty); max height caps growth.
config_scroll = QScrollArea()
config_scroll.setWidgetResizable(True)
config_scroll.setFrameShape(config_scroll.Shape.NoFrame)
self.config_container = QWidget()
self.config_layout = QVBoxLayout(self.config_container)
self.config_layout.addStretch()
config_scroll.setWidget(self.config_container)
engine_content.addWidget(config_scroll)
right_layout.addWidget(self.engine_section)
# Load/Process buttons — outside collapsible section so always visible
process_layout = QHBoxLayout()
self.btn_load_model = QPushButton("Load Model")
self.btn_load_model.clicked.connect(self.load_model)
process_layout.addWidget(self.btn_load_model)
self.btn_process = QPushButton("Process Image")
self.btn_process.clicked.connect(self.process_image)
self.btn_process.setEnabled(False)
process_layout.addWidget(self.btn_process)
right_layout.addLayout(process_layout)
# Progress bar
self.progress_bar = QProgressBar()
self.progress_bar.setVisible(False)
right_layout.addWidget(self.progress_bar)
# Transcription results — splitter fills all remaining space
self.results_group = QGroupBox("Transcriptions")
results_layout = QVBoxLayout()
# Horizontal splitter for text and statistics
self.results_splitter = QSplitter(Qt.Orientation.Horizontal)
# Left: Transcription text
self.text_container = QWidget()
text_layout = QVBoxLayout(self.text_container)
text_layout.setContentsMargins(0, 0, 0, 0)
self.transcription_text = QTextEdit()
self.transcription_text.setReadOnly(True)
text_layout.addWidget(self.transcription_text)
self.results_splitter.addWidget(self.text_container)
# Right: Statistics panel (hidden by default on FHD, toggle via button below)
self.stats_scroll = QScrollArea()
self.stats_scroll.setWidgetResizable(True)
self.stats_scroll.setMinimumWidth(180)
self.stats_panel = StatisticsPanel()
self.stats_scroll.setWidget(self.stats_panel)
self.results_splitter.addWidget(self.stats_scroll)
self.transcription_text.setMinimumWidth(400)
self.results_splitter.setCollapsible(0, False)
self.results_splitter.setCollapsible(1, True)
# Stats panel hidden by default; user clicks Stats button to show
self.results_splitter.setSizes([1, 0])
results_layout.addWidget(self.results_splitter)
self.results_group.setLayout(results_layout)
# Wrap results_group in a QStackedWidget so comparison can take over the full area
self.results_stack = QStackedWidget()
self.results_stack.addWidget(self.results_group) # page 0: normal view
# comparison widget will be added as page 1 dynamically
right_layout.addWidget(self.results_stack, stretch=1)
# When engine section expands, hide results area (gives config room to breathe)
self.engine_section._header.toggled.connect(
lambda checked: self.results_stack.setVisible(not checked)
)
# Set initial state to match engine section (collapsed → results visible)
self.results_stack.setVisible(not self.engine_section.is_expanded())
# Export + comparison + stats toggle row — pinned at the very bottom of right_layout
# (outside results_group so it is always visible regardless of section heights)
export_layout = QHBoxLayout()
self.btn_compare = QPushButton("⚖ Compare")
self.btn_compare.setCheckable(True)
self.btn_compare.setStyleSheet("""
QPushButton {
min-height: 30px;
font-weight: bold;
}
QPushButton:checked {
background-color: #4CAF50;
color: white;
}
""")
self.btn_compare.toggled.connect(self.toggle_comparison_mode)
export_layout.addWidget(self.btn_compare)
export_layout.addStretch()
btn_export_txt = QPushButton("Export TXT")
btn_export_txt.clicked.connect(self.export_txt)
export_layout.addWidget(btn_export_txt)
btn_export_csv = QPushButton("Export CSV")
btn_export_csv.clicked.connect(self.export_csv)