-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhocr-editor.py
More file actions
executable file
·2602 lines (2234 loc) · 90.3 KB
/
Copy pathhocr-editor.py
File metadata and controls
executable file
·2602 lines (2234 loc) · 90.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
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
import os
import sys
import re
import io
import argparse
import signal
import random
import string
import traceback
import shutil
import subprocess
import PIL.Image
if os.name == "nt":
import winreg
from typing import (
Optional,
Tuple,
Any,
)
from PySide6.QtWidgets import (
QApplication, QMainWindow, QGraphicsView, QGraphicsScene,
QGraphicsRectItem, QGraphicsTextItem, QGraphicsItem,
QGraphicsSimpleTextItem, QGraphicsProxyWidget,
QWidget, QVBoxLayout, QLabel, QLineEdit, QSplitter,
QTabWidget,
QGraphicsEllipseItem,
QDockWidget,
QFileDialog,
QMessageBox,
QStyleOptionGraphicsItem,
QStyle,
QPlainTextEdit,
QColorDialog,
QStyleFactory,
)
from PySide6.QtGui import QBrush, QColor, QPen, QFont, QMouseEvent
from PySide6.QtGui import (
QPixmap,
QImage,
QPainter,
QTransform,
QShortcut,
QKeySequence,
QTextCursor,
QWheelEvent,
QIcon,
QAction,
QColor,
QPalette,
)
from PySide6.QtCore import QRectF, Qt, QPointF
from PySide6.QtCore import (
QTimer,
QSize,
QSizeF,
QTranslator,
QLocale,
QLibraryInfo,
QEvent,
QSignalBlocker,
)
from hocr_parser import HocrParser, Word
from hocr_parser import print_exceptions
from hocr_parser import debug, debug_word_id
from epub_fxl_parser import EpubFxlParser, EpubFxlWord
from hocr_source_editor import HocrSourceEditor
from resizable_rect_item import ResizableRectItem
import git_helpers
import color_helpers
debug_word_item = False
bbox_re = re.compile(r"bbox (\d+) (\d+) (\d+) (\d+)")
xwconf_re = re.compile(r"x_wconf (\d+)")
# --- utilities for images / dark mode ---
def _extract_image_from_title(title: bytes) -> Optional[bytes]:
m = re.search(rb'image\s+"([^"]+)"', title)
return m.group(1) if m else None
def _is_dark_mode(widget: QWidget) -> bool:
"""
Cross-platform luminance-based dark mode check.
Uses the application's palette rather than an individual widget.
"""
# fix: the "is dark mode" check only works in one direction
# dark -> light: ok
# light -> dark: fail
if os.name == "nt":
try:
key = winreg.OpenKey(
winreg.HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"
)
value, _ = winreg.QueryValueEx(key, "AppsUseLightTheme")
return value == 0
except OSError:
return False
pal = widget.palette()
bg = pal.color(QPalette.Window)
luminance = 0.299 * bg.red() + 0.587 * bg.green() + 0.114 * bg.blue()
return luminance < 128
def _invert_pixmap(pixmap: QPixmap) -> QPixmap:
img = pixmap.toImage().convertToFormat(QImage.Format_ARGB32)
img.invertPixels()
return QPixmap.fromImage(img)
class WordItem(ResizableRectItem):
@print_exceptions
def __init__(self, word, word_selected_cb, word_changed_cb):
x0, y0, x1, y1 = word.bbox
w = x1 - x0
h = y1 - y0
super().__init__(
# QRectF(x0, y0, w, h), # broken text position
QRectF(0, 0, w, h), # local rect
move_done_cb=self.move_done_cb,
resize_done_cb=self.resize_done_cb,
)
self.setPos(x0, y0) # scene position
self.setFlag(QGraphicsItem.ItemIsSelectable, True)
self.word = word
self.word_selected_cb = word_selected_cb
self.word_changed_cb = word_changed_cb
self.editor = None
if 0:
# Text
# note: text position is (0, 0) relative to its parent setPos(x0, y0)
self.text_item = QGraphicsSimpleTextItem(word.text_bytes, self)
self._update_text_position()
else:
# disable text overlay
self.text_item = None
# debug
# However, __del__ is not necessarily reliable for detecting C++ deletion.
# Better is to explicitly observe the Qt lifecycle -> debug_word_item_state
@print_exceptions
def __del__(self):
try:
print(
"DELETE WordItem",
"item=", getattr(self, "_debug_instance_id", None),
"word_id=", getattr(self, "_debug_word_id", None),
)
except Exception:
pass
@print_exceptions
def __str__(self):
try:
pos = self.scenePos()
pos = (pos.x(), pos.y())
except RuntimeError:
# Internal C++ object (WordItem) already deleted.
pos = "?"
return (
f"WordItem(" +
f"span_range={self.word.span_range!r}" +
f", id_bytes={self.word.id_bytes!r}" +
f", text_bytes={self.word.text_bytes!r}" +
f", bbox={self.word.bbox!r}" +
f", pos={pos!r}" +
f")"
)
@print_exceptions
def move_done_cb(self, pos1, pos2):
self._update_text_position()
self.update_word_bbox()
@print_exceptions
def resize_done_cb(self, rect1, rect2):
self._update_text_position()
self.update_word_bbox()
@print_exceptions
def mouseReleaseEvent(self, event):
try:
super().mouseReleaseEvent(event)
except RuntimeError:
# Internal C++ object (WordItem) already deleted.
# the word was removed by self.scene.clear() in self.refresh_page_view()
# TODO better?
# shiboken6.isValid(self) always returns True
# self.destroyed.connect(self.on_destroyed) signal is never emitted
return
self.word_selected_cb(self)
@print_exceptions
def set_theme_colors(self):
"""Call this after item is in a scene."""
if self.scene() and self.scene().views():
view = self.scene().views()[0]
palette = view.palette()
# no: 'PySide6.QtGui.QPalette' object has no attribute 'Text'
# fg_color = palette.color(palette.Text) # text / line color
# bg_color = palette.color(palette.Base) # background color (optional)
fg_color = palette.color(palette.ColorRole.Text) # text / line color
bg_color = palette.color(palette.ColorRole.Base) # background color (optional)
if self.text_item:
# Text color
self.text_item.setBrush(QBrush(fg_color))
# Rectangle outline
# pen = QPen(fg_color, 1) # solid line
# pen = QPen(fg_color, 1, Qt.DashLine) # dashed line
pen = QPen(fg_color, 1, Qt.DotLine) # dotted line
self.setPen(pen)
# no, this is ugly
# Optional: fill color with some transparency
# self.setBrush(QBrush(fg_color, Qt.Dense4Pattern)) # or light alpha
@print_exceptions
def set_text_color(self, color):
"""Apply color to text and bbox outline."""
if self.text_item:
self.text_item.setBrush(color)
self.setPen(QPen(color, 1))
# Override QGraphicsItem hook when added to scene
@print_exceptions
def itemChange(self, change, value):
# print("itemChange", change, value)
# if change == QGraphicsItem.ItemSceneChange:
if change == QGraphicsItem.ItemSceneHasChanged:
self.set_theme_colors()
return super().itemChange(change, value)
# ---------------- Helpers ----------------
@print_exceptions
def _update_text_position(self):
if not self.text_item: return
self.text_item.setPos(self.rect().x() + 2, self.rect().y() + 2)
font = self.text_item.font()
font.setPointSizeF(max(10, self.rect().height() * 0.6))
self.text_item.setFont(font)
@print_exceptions
def update_word_bbox(self):
top_left = self.mapToScene(self.rect().topLeft())
bottom_right = self.mapToScene(self.rect().bottomRight())
new_bbox = (
int(top_left.x()),
int(top_left.y()),
int(bottom_right.x()),
int(bottom_right.y())
)
old_bbox = self.word.bbox
if old_bbox != new_bbox:
if debug_word_id and debug_word_id == self.word.id_bytes:
print(f"word {self.word.id_bytes}: update_word_bbox: {old_bbox} -> {new_bbox}")
self.word.bbox = new_bbox
self.word_changed_cb(
self.word.id_bytes,
bbox=new_bbox,
span_start=self.word.span_range[0],
)
else:
if debug_word_id and debug_word_id == self.word.id_bytes:
print(f"word {self.word.id_bytes}: update_word_bbox: no change")
@print_exceptions
def mouseDoubleClickEvent(self, event):
if self.editor is None:
line_edit = QLineEdit(self.word.text_bytes)
line_edit.setFrame(False)
line_edit.setFixedWidth(int(self.rect().width()))
self.editor = QGraphicsProxyWidget(self)
self.editor.setWidget(line_edit)
self.editor.setPos(2, 2)
# Select all text so user can overwrite immediately
line_edit.selectAll()
line_edit.setFocus(Qt.FocusReason.MouseFocusReason)
line_edit.editingFinished.connect(self.finish_editing)
# ---------------- Helpers ----------------
@print_exceptions
def commit_text(self, new_text):
# print(f"commit_text: word.text_bytes {self.word.text_bytes!r} -> {new_text!r}")
self.word.text_bytes = new_text
if self.text_item:
self.text_item.setText(new_text)
if debug_word_id and debug_word_id == self.word.id_bytes:
print(f"word {self.word.id_bytes}: commit_text: new_text={new_text!r}")
self.word_changed_cb(
self.word.id_bytes, new_text,
bbox=self.word.bbox,
span_start=self.word.span_range[0],
)
self.word_selected_cb(self)
@print_exceptions
def finish_editing(self):
if self.editor:
line_edit = self.editor.widget()
new_text = line_edit.text()
# Disconnect signal immediately
try:
line_edit.editingFinished.disconnect()
except Exception:
pass
if new_text != self.word.text_bytes:
# Delay update until after editor fully closes
QTimer.singleShot(0, lambda: self.commit_text(new_text))
# Remove proxy safely after current events
proxy = self.editor
self.editor = None
QTimer.singleShot(0, lambda: self.scene().removeItem(proxy))
class PageView(QGraphicsView):
@print_exceptions
def __init__(
self,
editor: "HocrEditor",
add_new_word_cb: Any,
):
super().__init__(editor.scene)
self.editor = editor
self.setRenderHint(QPainter.Antialiasing)
self.setDragMode(QGraphicsView.ScrollHandDrag)
self.setViewportUpdateMode(QGraphicsView.FullViewportUpdate)
self._zoom = 0
# For new word creation
self.add_new_word_cb = add_new_word_cb
self._creating_new_word = False
self._new_word_start_pos: QPointF | None = None
self._new_word_rect_item: QGraphicsRectItem | None = None
@print_exceptions
def fit_width(self):
"""Scale so that scene width fits view width."""
if not self.scene() or self.scene().width() == 0:
return
view_width = self.viewport().width()
scene_width = self.scene().width()
factor = view_width / scene_width
self.setTransform(QTransform()) # reset
self.scale(factor, factor)
self._zoom = 0
@print_exceptions
def wheelEvent(self, event):
"""Zoom with Ctrl+wheel"""
modifiers = event.modifiers()
if modifiers & Qt.ControlModifier:
# --- Zoom ---
delta = event.angleDelta().y()
if delta > 0:
self.zoom_in()
else:
self.zoom_out()
event.accept()
elif modifiers & Qt.ShiftModifier:
# --- Horizontal scroll ---
delta = event.angleDelta().y() # vertical wheel normally
if delta != 0:
step = delta
self.horizontalScrollBar().setValue(
self.horizontalScrollBar().value() - step
)
event.accept()
else:
super().wheelEvent(event)
@print_exceptions
def zoom_in(self):
self._zoom += 1
self.scale(1.2, 1.2)
@print_exceptions
def zoom_out(self):
self._zoom -= 1
self.scale(1/1.2, 1/1.2)
@print_exceptions
def mouseDoubleClickEvent(self, event):
if event.button() == Qt.LeftButton:
pos = self.mapToScene(event.pos()) # FIXME DeprecationWarning
# pos = event.scenePos() # AttributeError
self._creating_new_word = True
self._new_word_start_pos = pos
# initial rectangle (default size)
default_w, default_h = 50, 20
self._new_word_rect_item = QGraphicsRectItem(
QRectF(pos.x(), pos.y(), default_w, default_h)
)
pen = QPen(Qt.blue, 1, Qt.DashLine)
self._new_word_rect_item.setPen(pen)
self.scene().addItem(self._new_word_rect_item)
event.accept()
else:
super().mouseDoubleClickEvent(event)
# TODO remove
@print_exceptions
def mouseMoveEvent(self, event):
if self._creating_new_word and self._new_word_start_pos:
pos = self.mapToScene(event.pos()) # FIXME DeprecationWarning
rect = QRectF(self._new_word_start_pos, pos).normalized()
self._new_word_rect_item.setRect(rect)
else:
super().mouseMoveEvent(event)
@print_exceptions
def mouseReleaseEvent(self, event):
if self._creating_new_word and self._new_word_rect_item:
rect = self._new_word_rect_item.rect()
self._creating_new_word = False
self.scene().removeItem(self._new_word_rect_item)
self._new_word_rect_item = None
# crop + OCR
cropped = self._crop_pixmap(rect)
hocr_bytes = None
if cropped:
try:
hocr_bytes = self._ocr_image(cropped)
except subprocess.TimeoutExpired as exc:
print(f"mouseReleaseEvent: _ocr_image failed: {exc}")
if hocr_bytes:
# TODO parse hocr, merge with self.parser.source_bytes
# similar to add_new_word_cb -> add_new_word_from_page_view
# print("mouseReleaseEvent: hocr_bytes:\n" + hocr_bytes.decode("utf8"))
parser = HocrParser(hocr_bytes)
parse_id = get_random_bytestring()
# rect is QRectF of user selection in scene/pixmap coordinates
x_offset, y_offset = rect.x(), rect.y()
scale_x = rect.width() / cropped.width()
scale_y = rect.height() / cropped.height()
for word in parser.find_words():
# expand word.id_bytes to avoid collisions
# assume that word.id_bytes has the pattern "word_[0-9]+_[0-9]+"
# the first number is the page number
# the second number is the word number on this page
word.id_bytes = word.id_bytes[:5] + parse_id + word.id_bytes[4:]
(x0, y0, x1, y1) = word.bbox
# scale bbox from cropped-image space to scene/pixmap space
old_bbox = word.bbox
word.bbox = (
int(x0 * scale_x + x_offset),
int(y0 * scale_y + y_offset),
int(x1 * scale_x + x_offset),
int(y1 * scale_y + y_offset),
)
# FIXME update the range values in add_new_word_cb
word.byte_range = (0, 0)
word.title_value_range = (0, 0)
word.id_bytes_value_range = (0, 0)
word.element_range = (0, 0)
word.span_range = (0, 0)
self.add_new_word_cb(word=word)
else:
self.add_new_word_cb(rect=rect)
event.accept()
else:
super().mouseReleaseEvent(event)
def _crop_pixmap(self, rect: QRectF) -> QImage:
if not self.editor.page_pixmap:
return None
# Clamp rect to image bounds
img_rect = QRectF(self.editor.page_pixmap.rect())
rect = rect.intersected(img_rect)
if rect.isEmpty():
return None
return self.editor.page_pixmap.copy(rect.toRect()).toImage()
def _qimage_to_pil(self, qimage: QImage) -> PIL.Image.Image:
qimage = qimage.convertToFormat(QImage.Format_RGBA8888)
width, height = qimage.width(), qimage.height()
ptr = qimage.bits()
buf = bytes(ptr)
img = PIL.Image.frombuffer("RGBA", (width, height), buf, "raw", "RGBA", 0, 1)
return img.convert("RGB")
def _ocr_image(self, qimage: QImage, langs: Optional[str] = None, timeout: int = 30) -> bytes:
if shutil.which(self.editor.args.tesseract_command) is None:
# tesseract is not installed
return None
langs = langs or self.editor.ocr_langs
pil_img = self._qimage_to_pil(qimage)
# pytesseract creates PNG tempfiles in /tmp/
# https://github.com/madmaze/pytesseract/issues/172
# https://stackoverflow.com/questions/34248492
# TODO? use https://github.com/sirfz/tesserocr
tiff_bytes = pil_to_tiff_bytes(pil_img)
args = [
self.editor.args.tesseract_command,
"-", # input: stdin
"-", # output: stdout
"-l", langs,
"-c", "tessedit_create_hocr=1",
# TODO get dpi value from hocr file
# <div class='ocr_page' id='page_1' title='...; scan_res 300 300'>
# "--dpi", "300",
"--loglevel", "WARN", # ALL, TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF
]
if self.editor.args.tessdata_dir:
args += [
"--oem", "1",
"--psm", "6",
"--tessdata-dir", self.editor.args.tessdata_dir,
]
hocr_bytes = subprocess.check_output(args, input=tiff_bytes, timeout=timeout)
return hocr_bytes
def pil_to_tiff_bytes(img: PIL.Image.Image) -> bytes:
# why? TIFF is faster than PNG
buf = io.BytesIO()
img.save(buf, format="tiff")
return buf.getvalue()
class HocrEditor(QMainWindow):
# debug
def debug_word_item_state(self, item, label=""):
try:
scene = item.scene()
except RuntimeError:
print(
f"[STALE] {label}",
"item=", id(item),
"word_id=", getattr(item.word, "id_bytes", None),
)
return False
print(
f"[ALIVE] {label}",
"item=", id(item),
"word_id=", getattr(item.word, "id_bytes", None),
"scene_is_current=", scene is self.scene,
"scene=", scene,
)
return True
# debug
def debug_word_item_state_dump(self, label=""):
print()
print("=" * 80)
print("WORD ITEM STATE:", label)
print("=" * 80)
# Parser
parser_words = self.parser.find_words()
print()
print("PARSER WORDS:", len(parser_words))
parser_by_id = {}
for word in parser_words:
wid = word.id_bytes
parser_by_id.setdefault(wid, []).append(word)
print(
" PARSER",
"id=", wid,
"text=", repr(word.text_bytes),
"bbox=", word.bbox,
"byte_range=", word.byte_range,
"span_range=", getattr(word, "span_range", None),
)
# word_items
print()
print("WORD_ITEMS DICT:", len(self.word_items))
for wid, items in self.word_items.items():
print()
print(" WORD_ID:", wid)
print(" parser_count:", len(parser_by_id.get(wid, [])))
print(" item_count:", len(items))
for item in items:
try:
scene = item.scene()
alive = True
except RuntimeError:
scene = None
alive = False
print(
" ITEM",
"python_id=", id(item),
"alive=", alive,
"scene_is_current=", scene is self.scene if alive else False,
"word_id=", (
getattr(item.word, "id_bytes", None)
if alive
else "<stale>"
),
"word_text=", (
repr(item.word.text_bytes)
if alive
else "<stale>"
),
)
# Scene
print()
print("SCENE ITEMS:")
scene_word_items = []
for item in self.scene.items():
if isinstance(item, WordItem):
scene_word_items.append(item)
print(
" SCENE ITEM",
"python_id=", id(item),
"word_id=", item.word.id_bytes,
"text=", repr(item.word.text_bytes),
"bbox=", item.word.bbox,
)
print()
print("SCENE WORD ITEMS:", len(scene_word_items))
print("=" * 80)
print()
# debug
def debug_assert_word_item_consistency(self, where=""):
scene_items = [
item
for item in self.scene.items()
if isinstance(item, WordItem)
]
tracked_items = [
item
for items in self.word_items.values()
for item in items
]
scene_ids = {id(item) for item in scene_items}
tracked_ids = {id(item) for item in tracked_items}
if scene_ids != tracked_ids:
print()
print("=" * 80)
print("WORD ITEM INVARIANT VIOLATION:", where)
print("=" * 80)
print("Scene items:")
for item in scene_items:
print(
" ",
id(item),
getattr(item.word, "id_bytes", None),
getattr(item.word, "span_range", None),
)
print("Tracked items:")
for item in tracked_items:
print(
" ",
id(item),
getattr(item.word, "id_bytes", None),
getattr(item.word, "span_range", None),
)
print(
"ONLY IN SCENE:",
scene_ids - tracked_ids,
)
print(
"ONLY IN word_items:",
tracked_ids - scene_ids,
)
raise AssertionError(
f"WordItem bookkeeping inconsistent at {where}"
)
@print_exceptions
def __init__(self, args: Any):
super().__init__()
self.args = args
self.hocr_file = args.hocr_file # remember original filename
self._hocr_editor = self
self.overlay_color = None
if args.overlay_color:
overlay_color = QColor(args.overlay_color)
if overlay_color.isValid():
self.overlay_color = overlay_color
else:
print(f"Warning: invalid overlay color {args.overlay_color}")
self.scene = QGraphicsScene()
# TODO update self.modified from page_view and source_editor
self.modified = False
self.modified = True # always ask to save before exit # TODO remove
# TODO rename to self.page_view
self.view = PageView(
self,
add_new_word_cb=self.add_new_word_from_page_view,
)
self.page_view = self.view
self.setWindowTitle(f"{os.path.basename(self.hocr_file)} - HOCR Editor")
self.setWindowIcon(QIcon(os.path.dirname(__file__) + "/Eo_circle_blue_letter-h.2.png"))
# track chosen overlay color
self.overlay_color = QColor("black")
# Prevent recursive updates between:
# plain text editor
# HOCR source editor
# page view
# TODO reduce this to one or two variables
# one variable: self._updating_views
# two variables: self._updating_plain_text, self._updating_hocr_source
self._updating_views = False
self._updating_plain_text = False
self._updating_hocr_source = False
self._syncing_from_parser = False
# TODO reduce this to one variable?
# in hocr_source_editor.py we have this:
# self._updating = False # avoid recursive updates
self._rebuild_timer = QTimer(self)
self._rebuild_timer.setSingleShot(True)
self._rebuild_timer.setInterval(2000)
self._rebuild_timer.timeout.connect(self._rebuild_hocr_model)
# plain text editor
# from plain_text_editor import PlainTextEditor
# self.plain_text_editor = PlainTextEditor()
self.plain_text_editor = QPlainTextEdit()
self.plain_text_editor.document().contentsChange.connect(
self.on_plain_text_contents_change
)
# self.plain_text_editor.document().contentsChange.connect(
# self.on_plain_text_changed
# )
self.plain_text_editor.cursorPositionChanged.connect(
self.on_plain_text_cursor_changed
)
font = self.plain_text_editor.font()
if font.pointSizeF() > 0:
# increase the font size to 200%
font.setPointSizeF(font.pointSizeF() * 2.0)
self.plain_text_editor.setFont(font)
# load words into scene
# set self.parser
self.words: list[Word] = []
self.word_items: dict[str, list[WordItem]] = {}
self.page_pixmap = None
self.ocr_langs = "eng"
self.load_hocr(self.hocr_file)
# no, this is redundant
# TODO where do we call parser._build_model()
# # Build the paragraph/line/word model used by
# # the plain-text projection.
# self.parser.rebuild_model()
# no, this requires self.bottom_tabs -> move down
# self.plain_text_editor.setPlainText(
# self.parser.get_plain_text()
# )
self.changed_word_id: Optional[bytes] = None
# HOCR source editor dock
# TODO rename to self.hocr_source_editor
self.source_editor = HocrSourceEditor(
self.parser,
update_page_cb=self.refresh_page_view,
cursor_sync_cb=self.on_code_cursor_changed,
parent=self,
)
self.hocr_source_editor = self.source_editor
# TODO what
self.hocr_source_editor.editor.document().setDocumentMargin(4)
self.hocr_source_editor.editor.setLineWrapMode(QPlainTextEdit.NoWrap)
if debug:
print("HocrEditor.__init__: self.bottom_tabs = QTabWidget()")
self.bottom_tabs = QTabWidget()
self.bottom_tabs.addTab(
self.plain_text_editor,
"Text",
)
self.bottom_tabs.addTab(
self.source_editor,
"HOCR",
)
self.bottom_tabs.setCurrentWidget(
self.plain_text_editor
)
self.bottom_tabs.currentChanged.connect(
self.on_bottom_tab_changed
)
# Splitter to control widths
splitter = QSplitter(Qt.Vertical)
splitter.addWidget(self.view)
splitter.addWidget(self.bottom_tabs)
container = QWidget()
layout = QVBoxLayout(container)
layout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(splitter)
self.setCentralWidget(container)
# Menu bar
self._create_menubar()
# --- zoom shortcuts ---
QShortcut(QKeySequence("Ctrl++"), self, self.view.zoom_in)
QShortcut(QKeySequence("Ctrl+-"), self, self.view.zoom_out)
QShortcut(QKeySequence("Ctrl+0"), self, self.view.fit_width)
self.showMaximized() # use full screen size
# give more height to source_editor
view_height, source_editor_height = 100, 200
splitter.setSizes([view_height, source_editor_height])
splitter.setStretchFactor(0, view_height) # self.view
splitter.setStretchFactor(1, source_editor_height) # self.source_editor
# TODO better
for delay in [1, 10, 20, 50, 100, 200, 500]:
QTimer.singleShot(delay, self.view.fit_width) # fit width after layout
self._syncing_from_parser = True
if debug:
print("HocrEditor.__init__: calling self.plain_text_editor.setPlainText")
try:
self.plain_text_editor.setPlainText(
self.parser.get_plain_text()
)
if debug:
print("HocrEditor.__init__: calling self.hocr_source_editor.editor.setPlainText")
self.hocr_source_editor.editor.setPlainText(
self.parser.get_source_string()
)
finally:
self._syncing_from_parser = False
@print_exceptions
def on_bottom_tab_changed(self, index):
print("HocrEditor.on_bottom_tab_changed: current_widget = self.bottom_tabs.widget(index)")
current_widget = self.bottom_tabs.widget(index)
if current_widget is self.plain_text_editor:
self._updating_plain_text = True
try:
print("HocrEditor.on_bottom_tab_changed: calling self.plain_text_editor.setPlainText")
self.plain_text_editor.setPlainText(
self.parser.get_plain_text()
)
finally:
self._updating_plain_text = False
elif current_widget is self.hocr_source_editor:
self._updating_hocr_source = True
self._updating_views = True
try:
print("HocrEditor.on_bottom_tab_changed: calling self.hocr_source_editor.editor.setPlainText")
self.hocr_source_editor.editor.setPlainText(
self.parser.get_source_string()
)
finally:
self._updating_hocr_source = False
self._updating_views = False
@print_exceptions
def _rebuild_hocr_model(self):
print("HocrEditor._rebuild_hocr_model: calling self.parser.rebuild_model")
self.parser.rebuild_model()
self.reconcile_page_items()
self.refresh_plain_text_editor()
self.refresh_source_editor()
@print_exceptions
def on_plain_text_contents_change_zzzzzzzzz(
self,
position,
chars_removed,
chars_added,
):
# if self._updating_views:
if self._updating_plain_text:
return
if self._syncing_from_parser:
return
inserted_text = ""
if chars_added:
cursor = self.plain_text_editor.textCursor()
# contentsChange is emitted after the document has changed,
# so reconstruct the inserted range.
print(f"line 640: setPosition {position} {position + chars_added} # chars_removed={chars_removed!r} # chars_added={chars_added!r}")
cursor.setPosition(position)
# FIXME QTextCursor::setPosition: Position '1' out of range
cursor.setPosition(
position + chars_added,
QTextCursor.MoveMode.KeepAnchor,
)
inserted_text = cursor.selectedText()
# Qt represents newline characters in QTextDocument
# as paragraph separators.
inserted_text = inserted_text.replace(
"\u2029",
"\n",
)
success = self.parser.apply_plain_text_edit(
position=position,
chars_removed=chars_removed,
inserted_text=inserted_text,
)
if success:
self.schedule_model_rebuild_check()
else:
self.schedule_full_rebuild()
@print_exceptions
def on_plain_text_contents_change_zzzzzzzzzz(
self,
position,
chars_removed,
chars_added,
):
# if self._updating_views:
if self._updating_plain_text:
return
print(
f"contentsChange: "
f"position={position}, "
f"removed={chars_removed}, "
f"added={chars_added}"
)
# Process after Qt has finished modifying the document.
QTimer.singleShot(
0,
lambda: self.process_plain_text_change(
position,
chars_removed,
chars_added,
),
)
@print_exceptions
def on_plain_text_contents_change_zzzzzzzz(
self,
position,
chars_removed,
chars_added,
):
if self._updating_plain_text:
return
# Wait until Qt has finished applying the edit.
# Process after Qt has finished modifying the document.
QTimer.singleShot(
0,
lambda: self.process_plain_text_change(
position,
chars_removed,
chars_added,
),
)
@print_exceptions
def on_plain_text_contents_change(
self,
position,
chars_removed,
chars_added,
):