forked from wynick27/DigitizationTools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathocr_proofreading.py
More file actions
4337 lines (3716 loc) · 181 KB
/
Copy pathocr_proofreading.py
File metadata and controls
4337 lines (3716 loc) · 181 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
import sys
import os
import json
import re
import fitz # PyMuPDF
import difflib
import time
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QTextEdit, QPlainTextEdit, QLabel, QPushButton, QSplitter, QFileDialog,
QMessageBox, QGraphicsView, QGraphicsScene,
QGraphicsRectItem, QLineEdit, QSpinBox, QToolBar, QComboBox, QCheckBox,
QDialog, QListWidget, QStackedWidget, QRadioButton, QDialogButtonBox,
QToolButton, QMenu)
from PyQt6.QtGui import (QTextCursor, QColor, QSyntaxHighlighter, QTextCharFormat, QTextFormat,
QAction, QPixmap, QImage, QPainter, QPen, QFont, QTextOption)
from PyQt6.QtWidgets import QProgressBar
from PyQt6.QtCore import (
Qt, QEvent, QSignalBlocker, pyqtSignal, QTimer, QThread, pyqtSlot, QSize, QRect,
QUrl,
)
import bisect
from tools.pdf_tools import SplitPdfDialog, ExportPdfImageDialog
from tools.text_tools import MergeTextDialog, read_text_to_pages, write_pages_to_file, PAGE_PATTERN
from tools.furigana import generate_furigana_string, HAS_FURIGANA, HAS_KAKASI
from tools.project_manager_ui import ProjectManagerDialog
from tools.export_manager import ExportManager
from tools.similarity_tools import SimilarityDialog, calculate_page_similarities, text_similarity
from tools.headword_compare_tools import HeadwordCompareDialog
from tools.report_review_tools import ReportReviewDialog
from tools.revision_view import RevisionViewWidget
from tools.markup_support import (
MarkupPreviewEdit,
apply_visible_text_edit,
build_markup_projection,
map_projection_opcodes,
projection_for_rendered_text,
)
from find_replace import FindReplaceDialog
from lang.i18n import text_from_config
# ==========================================
# 0.0 Unicode Helpers
# ==========================================
def to_qt_pos(full_text: str, py_pos: int) -> int:
"""Convert Python string index to Qt TextCursor position (UTF-16 code units)."""
head = full_text[:py_pos]
return len(head.encode('utf-16-le')) // 2
def to_py_pos(full_text: str, qt_pos: int) -> int:
"""Convert Qt TextCursor position to Python string index."""
curr_qt = 0
for i, c in enumerate(full_text):
if curr_qt >= qt_pos:
return i
curr_qt += 2 if ord(c) > 0xFFFF else 1
return len(full_text)
def map_diff_index(opcodes, index, source_is_left=True):
"""Map a Python character index through SequenceMatcher opcodes."""
for tag, i1, i2, j1, j2 in opcodes:
s1, s2 = (i1, i2) if source_is_left else (j1, j2)
d1, d2 = (j1, j2) if source_is_left else (i1, i2)
if s1 <= index < s2:
source_len = s2 - s1
target_len = d2 - d1
if tag == 'equal':
return d1 + (index - s1)
if source_len > 0 and target_len > 0:
relative = (index - s1) * target_len // source_len
return d1 + min(relative, target_len - 1)
return d1
# A cursor may legally sit just after the final character.
if opcodes:
_tag, i1, i2, j1, j2 = opcodes[-1]
source_end = i2 if source_is_left else j2
target_end = j2 if source_is_left else i2
if index == source_end:
return target_end
return -1
# ==========================================
# 0.1 Default Configuration
# ==========================================
DEFAULT_GLOBAL_CONFIG = {
"ocr_api_token": "",
"ocr_api_model": "PaddleOCR-VL-1.6",
"ocr_retry_count": 3,
"ocr_concurrent_tasks": 2,
"ocr_engine": "paddleocr",
"ocr_excluded_categories": [
"image", "table", "formula", "chart", "header", "footer", "page_number"
],
"find_history": [],
"replace_history": [],
"replace_execution_history": [],
"shortcuts_alt": [""] * 10,
"shortcut_furigana": "Ctrl+Shift+F",
"furigana_left_marker": "[",
"furigana_right_marker": "]",
"furigana_kana_type": "hiragana",
"furigana_use_jmdict_split": True,
"ui_lang": "zh"
}
DEFAULT_PROJECT_CONFIG = {
"name": "Default Project",
"pdf_path": "",
"image_dir": "",
"start_page": 1,
"end_page": 1,
"page_offset": 0,
"text_path_left": "",
"text_path_right": "",
"ocr_json_path": "ocr_results",
"regex_left": r"^\*\*(.*?)\*\*",
"regex_right": r"^([a-zA-Z]*?)",
"regex_group_left": 0,
"regex_group_right": 0,
"use_pdf_render": False,
}
# ==========================================
# 0.1b OCR Utility Imports & Detection
# ==========================================
from ocr.ocr_utils import get_page_image, get_page_image_path, TextToBBoxMapper, BBoxMerger, ImageStitcher
from ocr.ocr_worker import OCRWorker, ImageExportWorker, get_available_engines, refresh_remote_engine_label, V2_MODELS
from ocr.ocr_engines import discover_ocr_results, normalize_ocr_result, PADDLE_ENGINE_ID, canonical_engine_id, sort_ocr_results_by_priority
# ==========================================
# 0.2 Config Manager
# ==========================================
class ConfigManager:
def __init__(self, filepath="config.json"):
self.filepath = filepath
self.data = {
"global": DEFAULT_GLOBAL_CONFIG.copy(),
"projects": [DEFAULT_PROJECT_CONFIG.copy()],
"active_project": "Default Project"
}
self.load()
def load(self):
if not os.path.exists(self.filepath):
return
try:
with open(self.filepath, "r", encoding="utf-8") as f:
loaded = json.load(f)
# Migration Logic: Check if it's flat (old style)
if "projects" not in loaded:
print("Migrating legacy config to new structure...")
# It's a flat config, migrate to Default Project
new_project = DEFAULT_PROJECT_CONFIG.copy()
# Copy known project keys
for key in new_project:
if key in loaded:
new_project[key] = loaded[key]
new_project["name"] = "Default Project"
# Copy known global keys
if "ocr_api_url" in loaded:
self.data["global"]["ocr_api_url"] = loaded["ocr_api_url"]
if "ocr_api_token" in loaded:
self.data["global"]["ocr_api_token"] = loaded["ocr_api_token"]
self.data["projects"] = [new_project]
else:
self.data = loaded
# Ensure structure integrity
if "global" not in self.data:
self.data["global"] = DEFAULT_GLOBAL_CONFIG.copy()
else:
for k, v in DEFAULT_GLOBAL_CONFIG.items():
if k not in self.data["global"]:
self.data["global"][k] = v
if "projects" not in self.data:
self.data["projects"] = [DEFAULT_PROJECT_CONFIG.copy()]
if "active_project" not in self.data:
self.data["active_project"] = self.data["projects"][0]["name"]
category_config = self.data["global"]
category_version = int(category_config.get("ocr_category_defaults_version", 1))
current_categories = set(category_config.get("ocr_excluded_categories") or [])
if category_version < 2:
if current_categories == {"image", "table", "formula"}:
current_categories.update({"chart", "header", "footer", "page_number"})
category_config["ocr_excluded_categories"] = sorted(current_categories)
category_config["ocr_category_defaults_version"] = 2
if self.data.get("global", {}).get("ocr_engine") == "remote":
self.data["global"]["ocr_engine"] = "paddleocr"
except Exception as e:
print(f"Config load error: {e}")
def save(self):
try:
with open(self.filepath, "w", encoding="utf-8") as f:
json.dump(self.data, f, indent=4, ensure_ascii=False)
except Exception as e:
print(f"Config save error: {e}")
def get_global(self):
return self.data["global"]
def get_projects(self):
return self.data["projects"]
def get_project(self, name):
for p in self.data["projects"]:
if p["name"] == name:
return p
return None
def get_active_project(self):
name = self.data.get("active_project")
p = self.get_project(name)
if p: return p
# Fallback
if self.data["projects"]:
self.data["active_project"] = self.data["projects"][0]["name"]
return self.data["projects"][0]
return DEFAULT_PROJECT_CONFIG.copy()
def set_active_project(self, name):
if self.get_project(name):
self.data["active_project"] = name
self.save()
def create_project(self, name):
if self.get_project(name): return False
new_p = DEFAULT_PROJECT_CONFIG.copy()
new_p["name"] = name
self.data["projects"].append(new_p)
self.save()
return True
def delete_project(self, name):
# Don't delete if it's the only one
if len(self.data["projects"]) <= 1: return False
self.data["projects"] = [p for p in self.data["projects"] if p["name"] != name]
# Reset active if needed
if self.data["active_project"] == name:
self.data["active_project"] = self.data["projects"][0]["name"]
self.save()
return True
# ==========================================
# 0.6 Language Dictionary (i18n)
# ==========================================
# ==========================================
# 1. 自定义编辑器 (支持 Diff 交互) & Highlighter
# ==========================================
class DiffSyntaxHighlighter(QSyntaxHighlighter):
def __init__(self, document):
super().__init__(document)
self.diff_ranges = [] # List of tuples (start, end)
self.diff_starts = [] # List of start positions for bisect
self.diff_ranges = [] # List of tuples (start, end)
self.diff_starts = [] # List of start positions for bisect
self.regex_pattern = None
self.regex_group = 0
# 预定义格式
self.diff_fmt = QTextCharFormat()
self.diff_fmt.setForeground(QColor("red"))
self.diff_fmt.setBackground(QColor("#FFEEEE")) # 浅红背景
self.regex_fmt = QTextCharFormat()
self.regex_fmt.setBackground(QColor("#E0F0FF")) # 浅蓝
# Merge Format (Diff FG + Regex BG)
self.both_fmt = QTextCharFormat()
self.both_fmt.setForeground(QColor("red"))
self.both_fmt.setBackground(QColor("#E0F0FF"))
def set_diff_data(self, opcodes, is_left):
self.diff_ranges = []
text = self.document().toPlainText()
for tag, i1, i2, j1, j2 in opcodes:
if tag == 'equal': continue
s_py, e_py = (i1, i2) if is_left else (j1, j2)
if s_py < e_py:
s_qt = to_qt_pos(text, s_py)
e_qt = to_qt_pos(text, e_py)
self.diff_ranges.append((s_qt, e_qt))
self.diff_ranges.sort() # Ensure sorted
self.diff_starts = [r[0] for r in self.diff_ranges]
self.rehighlight()
def set_regex(self, regex_str, group_id=0):
if not regex_str:
self.regex_pattern = None
else:
try:
self.regex_pattern = re.compile(regex_str)
except:
self.regex_pattern = None
self.regex_group = group_id
self.rehighlight()
def highlightBlock(self, text):
length = len(text)
if length == 0: return
# Optimization: use boolean array to track states
has_diff = [False] * length
has_regex = [False] * length
block_start = self.currentBlock().position()
block_end = block_start + length
# 1. Fill Diff
if self.diff_ranges:
end_idx = bisect.bisect_right(self.diff_starts, block_end)
start_search = bisect.bisect_right(self.diff_starts, block_start)
if start_search > 0: start_search -= 1
count = 0
for i in range(start_search, end_idx):
if count > 1000: break
s, e = self.diff_ranges[i]
intersect_start = max(s, block_start)
intersect_end = min(e, block_end)
if intersect_start < intersect_end:
rel_s = intersect_start - block_start
rel_e = intersect_end - block_start
has_diff[rel_s:rel_e] = [True] * (rel_e - rel_s)
count += 1
# 2. Fill Regex
if self.regex_pattern:
count = 0
for match in self.regex_pattern.finditer(text):
if count > 100: break
try:
s, e = match.start(self.regex_group), match.end(self.regex_group)
except IndexError:
# Fallback if group not found
s, e = match.start(), match.end()
# Bound checks although finditer on text should be within text
s = max(0, s); e = min(length, e)
if s < e:
has_regex[s:e] = [True] * (e - s)
count += 1
# 3. Apply Formats
# Run-Length Encoding approach to minimize setFormat calls
current_start = 0
current_type = (has_diff[0], has_regex[0])
for i in range(1, length):
new_type = (has_diff[i], has_regex[i])
if new_type != current_type:
self.apply_format_chunk(current_start, i - current_start, current_type)
current_start = i
current_type = new_type
self.apply_format_chunk(current_start, length - current_start, current_type)
def apply_format_chunk(self, start, length, flags):
is_diff, is_regex = flags
if not is_diff and not is_regex: return
fmt = None
if is_diff and is_regex:
fmt = self.both_fmt
elif is_diff:
fmt = self.diff_fmt
elif is_regex:
fmt = self.regex_fmt
if fmt:
self.setFormat(start, length, fmt)
class LineNumberArea(QWidget):
def __init__(self, editor):
super().__init__(editor)
self.codeEditor = editor
def sizeHint(self):
return QSize(self.codeEditor.line_number_area_width(), 0)
def paintEvent(self, event):
self.codeEditor.lineNumberAreaPaintEvent(event)
class DiffTextEdit(QPlainTextEdit):
"""
支持 Ctrl+Hover 高亮和 Ctrl+Click 应用补丁的文本框
"""
focus_in_signal = pyqtSignal()
# 信号:点击了某个 Diff 块,请求应用到另一侧 (self_index_range, target_text)
apply_patch_signal = pyqtSignal(tuple, str)
# 信号:Alt+Click 将本侧内容推送到另一侧 (target_range, my_content)
push_patch_signal = pyqtSignal(tuple, str)
# 信号:Ctrl+Wheel 缩放请求 (delta)
zoom_signal = pyqtSignal(int)
def focusInEvent(self, event):
self.focus_in_signal.emit()
super().focusInEvent(event)
def wheelEvent(self, event):
if event.modifiers() & Qt.KeyboardModifier.ControlModifier:
# Emit zoom signal, consume event
self.zoom_signal.emit(event.angleDelta().y())
event.accept()
else:
super().wheelEvent(event)
def __init__(self, side="left"):
super().__init__()
self.side = side # 'left' or 'right'
self.diff_opcodes = [] # 存储 difflib 的 opcodes
self.other_text_content = "" # 另一侧的完整文本,用于提取
self.setFont(QFont("Consolas", 11))
# 启用鼠标追踪以支持 Hover
self.setMouseTracking(True)
self._hovering_diff = False
self.line_number_area = LineNumberArea(self)
self.blockCountChanged.connect(self.update_line_number_area_width)
self.updateRequest.connect(self.update_line_number_area)
self.update_line_number_area_width(0)
def line_number_area_width(self):
digits = 1
max_val = max(1, self.blockCount())
while max_val >= 10:
max_val //= 10
digits += 1
space = 3 + self.fontMetrics().horizontalAdvance('9') * digits + 5 # Margin
return space
def update_line_number_area_width(self, new_block_count):
self.setViewportMargins(self.line_number_area_width(), 0, 0, 0)
def update_line_number_area(self, rect, dy):
if dy:
self.line_number_area.scroll(0, dy)
else:
self.line_number_area.update(0, rect.y(), self.line_number_area.width(), rect.height())
if rect.contains(self.viewport().rect()):
self.update_line_number_area_width(0)
def resizeEvent(self, event):
super().resizeEvent(event)
cr = self.contentsRect()
self.line_number_area.setGeometry(QRect(cr.left(), cr.top(), self.line_number_area_width(), cr.height()))
def lineNumberAreaPaintEvent(self, event):
painter = QPainter(self.line_number_area)
painter.fillRect(event.rect(), QColor("#F0F0F0")) # Background
block = self.firstVisibleBlock()
block_number = block.blockNumber()
top = self.blockBoundingGeometry(block).translated(self.contentOffset()).top()
bottom = top + self.blockBoundingRect(block).height()
painter.setPen(Qt.GlobalColor.black)
while block.isValid() and top <= event.rect().bottom():
if block.isVisible() and bottom >= event.rect().top():
number = str(block_number + 1)
painter.drawText(0, int(top), self.line_number_area.width() - 3, self.fontMetrics().height(),
Qt.AlignmentFlag.AlignRight, number)
block = block.next()
top = bottom
bottom = top + self.blockBoundingRect(block).height()
block_number += 1
def highlight_line_at_index(self, idx):
"""高亮指定字符索引所在的行"""
self.blockSignals(True)
# 清除之前的 ExtraSelections (除了 Diff 高亮?)
# 实际上 diff 高亮是直接作用于 TextCharFormat 的,而 ExtraSelections 是独立的图层
# 这里仅用于行高亮
cursor = self.textCursor()
cursor.setPosition(idx)
selection = QTextEdit.ExtraSelection()
selection.format.setBackground(QColor("#FFFFAA")) # 淡黄色行高亮
fmt = selection.format
fmt.setProperty(QTextFormat.Property.FullWidthSelection, True)
selection.format = fmt
selection.cursor = cursor
selection.cursor.clearSelection() #只是定位
self.setExtraSelections([selection])
self.blockSignals(False)
def set_diff_data(self, opcodes, other_text):
self.diff_opcodes = opcodes
self.other_text_content = other_text
def get_opcode_at_position(self, pos):
"""根据鼠标坐标获取对应的 opcode"""
cursor = self.cursorForPosition(pos)
qt_idx = cursor.position()
# Convert to Python index for opcode lookup
text = self.toPlainText()
idx = to_py_pos(text, qt_idx)
# 遍历 opcodes 查找当前索引是否在差异区间内
for tag, i1, i2, j1, j2 in self.diff_opcodes:
if tag == 'equal': continue
# 判断是在左侧还是右侧
if self.side == 'left':
if i1 <= idx <= i2:
return (tag, i1, i2, j1, j2)
else:
if j1 <= idx <= j2:
return (tag, i1, i2, j1, j2)
return None
def mouseMoveEvent(self, event):
# 检查是否按住 Ctrl
modifiers = QApplication.keyboardModifiers()
if modifiers & Qt.KeyboardModifier.ControlModifier:
opcode = self.get_opcode_at_position(event.pos())
if opcode:
self.viewport().setCursor(Qt.CursorShape.PointingHandCursor)
self._hovering_diff = True
else:
self.viewport().setCursor(Qt.CursorShape.IBeamCursor)
self._hovering_diff = False
elif modifiers & Qt.KeyboardModifier.AltModifier:
opcode = self.get_opcode_at_position(event.pos())
if opcode:
self.viewport().setCursor(Qt.CursorShape.PointingHandCursor)
self._hovering_diff = True
else:
self.viewport().setCursor(Qt.CursorShape.IBeamCursor)
self._hovering_diff = False
else:
self.viewport().setCursor(Qt.CursorShape.IBeamCursor)
self._hovering_diff = False
super().mouseMoveEvent(event)
def clear_highlight(self):
"""清除高亮(ExtraSelections)"""
self.setExtraSelections([])
def mousePressEvent(self, event):
# 处理 Ctrl + Click
modifiers = QApplication.keyboardModifiers()
if (modifiers & Qt.KeyboardModifier.ControlModifier) and event.button() == Qt.MouseButton.LeftButton:
opcode = self.get_opcode_at_position(event.pos())
if opcode:
self.handle_patch_click(opcode)
return # 拦截事件,不移动光标
# 处理 Alt + Click (Push)
if (modifiers & Qt.KeyboardModifier.AltModifier) and event.button() == Qt.MouseButton.LeftButton:
opcode = self.get_opcode_at_position(event.pos())
if opcode:
self.handle_push_click(opcode)
return
super().mousePressEvent(event)
def handle_patch_click(self, opcode):
tag, i1, i2, j1, j2 = opcode
# 逻辑:点击某侧的差异块,意为“将这一块的内容变成另一侧的样子”
# 或者“将这一块的内容推送到另一侧”。
# 通常 Beyond Compare 的逻辑是:点击箭头将当前侧内容覆盖到另一侧。
# 这里的实现:点击红色区域 -> 将该区域内容替换为另一侧对应区域的内容 (Accept Change)
target_text = ""
my_range = (0, 0)
if self.side == 'left':
my_range = (i1, i2)
# 获取右侧对应文本 (j1:j2)
target_text = self.other_text_content[j1:j2]
else:
my_range = (j1, j2)
# 获取左侧对应文本 (i1:i2)
target_text = self.other_text_content[i1:i2]
# 发射信号,由主窗口执行替换操作
self.apply_patch_signal.emit(my_range, target_text)
def handle_push_click(self, opcode):
tag, i1, i2, j1, j2 = opcode
# Logic: Alt+Click = 将“我”的内容推送到“另一侧”
# 我是 left: 我的内容在 i1:i2, 目标在 j1:j2
# 我是 right: 我的内容在 j1:j2, 目标在 i1:i2
my_range = (0, 0)
target_range = (0, 0)
text_to_push = ""
current_text = self.toPlainText()
if self.side == 'left':
my_range = (i1, i2)
target_range = (j1, j2)
text_to_push = current_text[i1:i2]
else:
my_range = (j1, j2) # Index in right text
target_range = (i1, i2) # Index in left text
text_to_push = current_text[j1:j2]
# 发射信号: (目标区间, 要替换成的内容)
self.push_patch_signal.emit(target_range, text_to_push)
# ==========================================
# 2. 图像画布 (支持缩放、BBox)
# ==========================================
class ImageCanvas(QGraphicsView):
bbox_clicked = pyqtSignal(int, int) # OCR 块索引、块内字符偏移
def __init__(self):
super().__init__()
self.scene = QGraphicsScene()
self.setScene(self.scene)
#self.setRenderHint(QPixmap.TransformationMode.SmoothTransformation)
self.scale_factor = 1.0
self.bboxes_visible = True
self.bbox_items = []
self.highlight_items = []
self.bbox_click_targets = []
# 拖拽相关
self.setDragMode(QGraphicsView.DragMode.ScrollHandDrag)
def load_content(self, pixmap, ocr_data=None):
self.scene.clear()
self.highlight_item = None # Fix: Reset C++ object wrapper
self.bbox_items = []
self.highlight_items = []
self.bbox_click_targets = []
if pixmap:
self.scene.addPixmap(pixmap)
self.setSceneRect(0, 0, pixmap.width(), pixmap.height())
if ocr_data:
self.draw_bboxes(ocr_data)
# self.scale_factor = 1.0 # Removed to persist zoom
# self.resetTransform() # Removed to persist zoom
def normalize_bbox_for_scene(self, bbox, coordinate_type=None):
if not bbox or len(bbox) != 4:
return None
x1, y1, x2, y2 = bbox
sw = self.sceneRect().width()
sh = self.sceneRect().height()
if sw <= 0 or sh <= 0:
return [x1, y1, x2, y2]
if coordinate_type == "mineru_page_1000":
return [
x1 * sw / 1000.0,
y1 * sh / 1000.0,
x2 * sw / 1000.0,
y2 * sh / 1000.0,
]
if max(abs(x1), abs(y1), abs(x2), abs(y2)) <= 1.5:
return [x1 * sw, y1 * sh, x2 * sw, y2 * sh]
return [x1, y1, x2, y2]
def draw_bboxes(self, ocr_data):
pen = QPen(QColor(255, 0, 0, 200))
pen.setWidth(3)
pen.setCosmetic(True) # 缩放图片时保持固定的屏幕线宽
for i, item in enumerate(ocr_data):
# 兼容 PaddleOCR 格式
# item 可能是 dict {'bbox':...} (v3代码) 或 list [points, (text, conf)]
x, y, w, h = 0, 0, 0, 0
text = ""
if isinstance(item, dict) and 'bbox' in item:
bbox = item['bbox'] # [x1, y1, x2, y2]
scene_bbox = self.normalize_bbox_for_scene(bbox, item.get('bbox_coordinate_type'))
if not scene_bbox:
continue
x, y, x2, y2 = scene_bbox
w, h = x2 - x, y2 - y
text = item.get('text', '')
elif isinstance(item, list) and len(item) == 2:
# Paddle raw: [[[x1,y1],...], ("text", conf)]
pts = item[0]
xs = [p[0] for p in pts]
ys = [p[1] for p in pts]
x, y = min(xs), min(ys)
w, h = max(xs)-x, max(ys)-y
text = item[1][0]
rect = QGraphicsRectItem(x, y, w, h)
rect.setPen(pen)
rect.setToolTip(text) # 鼠标悬停显示文字
rect.setData(0, i)
rect.setVisible(self.bboxes_visible)
self.bbox_items.append(rect)
self.scene.addItem(rect)
area = max(0.0, w) * max(0.0, h)
self.bbox_click_targets.append((3, area, i, 0, (x, y, w, h)))
if isinstance(item, dict):
priority = {'char': 0, 'word': 1, 'line': 2}
for sub in item.get('sub_items') or []:
sub_bbox = self.normalize_bbox_for_scene(
sub.get('bbox'),
sub.get('bbox_coordinate_type') or item.get('bbox_coordinate_type'),
)
if not sub_bbox:
continue
sx1, sy1, sx2, sy2 = sub_bbox
sw, sh = sx2 - sx1, sy2 - sy1
if sw <= 0 or sh <= 0:
continue
level = sub.get('level') or 'block'
self.bbox_click_targets.append((
priority.get(level, 3),
sw * sh,
i,
int(sub.get('start', 0) or 0),
(sx1, sy1, sw, sh),
))
def set_bboxes_visible(self, visible):
"""显示或隐藏普通 OCR 框及当前定位框。"""
self.bboxes_visible = bool(visible)
for item in self.bbox_items:
item.setVisible(self.bboxes_visible)
for item in self.highlight_items:
item.setVisible(self.bboxes_visible)
def mousePressEvent(self, event):
if (event.modifiers() & Qt.KeyboardModifier.ControlModifier) and (event.button() == Qt.MouseButton.LeftButton):
scene_pos = self.mapToScene(event.pos())
matches = []
for priority, area, block_idx, local_offset, (x, y, w, h) in self.bbox_click_targets:
if x <= scene_pos.x() <= x + w and y <= scene_pos.y() <= y + h:
matches.append((priority, area, block_idx, local_offset))
if matches:
_priority, _area, block_idx, local_offset = min(matches)
self.bbox_clicked.emit(block_idx, local_offset)
event.accept()
return
super().mousePressEvent(event)
def wheelEvent(self, event):
if event.modifiers() & Qt.KeyboardModifier.ControlModifier:
if event.angleDelta().y() > 0:
self.zoom(1.1)
else:
self.zoom(0.9)
event.accept()
else:
super().wheelEvent(event)
def zoom(self, factor):
self.scale(factor, factor)
self.scale_factor *= factor
def ensure_visible_bbox(self, x, y, w, h):
"""确保指定的矩形区域在视图中可见"""
# 获取场景坐标对应的 Rect
# 这里 x,y,w,h 已经是场景坐标(基于 Pixmap)
self.ensureVisible(x, y, w, h, 50, 50) # margin 50
def set_highlight_bbox(self, x, y, w, h):
"""设置单个定位矩形。"""
self.set_highlight_bboxes([(x, y, w, h, 'block')])
def set_highlight_bboxes(self, bboxes, ensure_visible=True):
"""同时显示字符/词及其所属行的定位框。"""
for item in getattr(self, 'highlight_items', []):
try:
self.scene.removeItem(item)
except RuntimeError:
pass # Already deleted by C++
self.highlight_items = []
self.highlight_item = None
valid_bboxes = [bbox for bbox in bboxes if bbox[2] > 0 and bbox[3] > 0]
colors = {
'char': QColor(0, 180, 0, 220), # 绿色:字符级
'word': QColor(255, 140, 0, 220), # 橙色:词级
'line': QColor(0, 102, 255, 210), # 蓝色:行级
'block': QColor(0, 102, 255, 210), # 蓝色:无细粒度回退框
}
z_values = {'char': 13, 'word': 12, 'line': 11, 'block': 11}
for bbox in valid_bboxes:
x, y, w, h = bbox[:4]
level = bbox[4] if len(bbox) > 4 else 'block'
pen = QPen(colors.get(level, colors['block']))
pen.setWidth(4)
pen.setCosmetic(True) # 定位框始终比普通 OCR 框更醒目
item = QGraphicsRectItem(x, y, w, h)
item.setPen(pen)
level_names = {'char': '字符级', 'word': '词级', 'line': '行级', 'block': '行/块级'}
item.setToolTip(f"当前定位:{level_names.get(level, '块级')}")
item.setZValue(z_values.get(level, 11))
item.setVisible(self.bboxes_visible)
self.scene.addItem(item)
self.highlight_items.append(item)
if self.highlight_items:
self.highlight_item = self.highlight_items[0]
if valid_bboxes and ensure_visible:
# 滚动位置优先保证所属整行可见;细粒度框仍照常绘制。
navigation_bbox = next(
(bbox for bbox in valid_bboxes if len(bbox) > 4 and bbox[4] == 'line'),
None,
)
if navigation_bbox is None:
navigation_bbox = next(
(bbox for bbox in valid_bboxes if len(bbox) > 4 and bbox[4] == 'block'),
valid_bboxes[0],
)
x, y, w, h = navigation_bbox[:4]
self.ensure_visible_bbox(x, y, w, h)
# A full line can be wider than the viewport. After positioning the
# line vertically, also bring the finest character/word box into
# view so the actual target cannot remain off-screen horizontally.
target_bbox = next(
(bbox for bbox in valid_bboxes if len(bbox) > 4 and bbox[4] == 'char'),
None,
)
if target_bbox is None:
target_bbox = next(
(bbox for bbox in valid_bboxes if len(bbox) > 4 and bbox[4] == 'word'),
valid_bboxes[0],
)
if target_bbox is not navigation_bbox:
tx, ty, tw, th = target_bbox[:4]
self.ensure_visible_bbox(tx, ty, tw, th)
# ==========================================
# 2.2 OCR Worker (Async)
# ==========================================
# OCRWorker moved to ocr.ocr_worker
class DiffWorker(QThread):
result_ready = pyqtSignal(list, list, list, list)
def __init__(
self, text_l, text_r, ocr_text_full, need_ocr_map,
ignore_markup=False, mode_left="plain", mode_right="plain",
):
super().__init__()
self.text_l = text_l
self.text_r = text_r
self.ocr_text_full = ocr_text_full
self.need_ocr_map = need_ocr_map
self.ignore_markup = ignore_markup
self.mode_left = mode_left
self.mode_right = mode_right
def run(self):
# Main Diff
errors = []
if self.ignore_markup:
projection_left = build_markup_projection(self.text_l, self.mode_left)
projection_right = build_markup_projection(self.text_r, self.mode_right)
matcher = difflib.SequenceMatcher(
None,
projection_left.visible_text,
projection_right.visible_text,
autojunk=False,
)
visible_opcodes = matcher.get_opcodes()
opcodes = map_projection_opcodes(
visible_opcodes, projection_left, projection_right
)
errors.extend(f"左侧:{error.display()}" for error in projection_left.errors)
errors.extend(f"右侧:{error.display()}" for error in projection_right.errors)
else:
matcher = difflib.SequenceMatcher(None, self.text_l, self.text_r, autojunk=False)
opcodes = matcher.get_opcodes()
visible_opcodes = opcodes
# OCR Mapping Diff
ocr_opcodes = []
if self.need_ocr_map and self.ocr_text_full:
m2 = difflib.SequenceMatcher(None, self.text_l, self.ocr_text_full, autojunk=False)
ocr_opcodes = m2.get_opcodes()
self.result_ready.emit(opcodes, ocr_opcodes, visible_opcodes, errors)
# ==========================================
# 4. Smart Image Export Helpers
# ==========================================
# TextToBBoxMapper, BBoxMerger, ImageStitcher moved to ocr.ocr_utils
# ImageExportWorker moved to ocr.ocr_worker
# ==========================================
# 5. Export Logic (Generic Parser)
# ==========================================
class ExportParser:
def __init__(self, pages_dict: dict, regex_str: str, group_id: int = 0):
self.pages_dict = pages_dict # {page_num: text}
self.group_id = group_id
if regex_str:
try:
self.regex = re.compile(regex_str)
except:
self.regex = None
else:
self.regex = None
def parse(self):
"""
Returns list of entries:
[
{
"headword": str,
"text": str, # merged text
"pages": [int],
"page_index": int
}, ...
]
"""
entries = []
if not self.pages_dict or not self.regex:
return entries
sorted_pages = sorted(self.pages_dict.keys())
current_entry = None
# Buffer for text that appears before first headword on non-first page
# This text belongs to the PREVIOUS entry (if exists)
for page_num in sorted_pages:
page_text = self.pages_dict[page_num]
lines = page_text.split('\n')
# Find all headwords in this page
page_headword_indices = [] # list of (line_idx, match_obj)
for i, line in enumerate(lines):
m = self.regex.search(line)
if m:
page_headword_indices.append((i, m))
if not page_headword_indices:
# Whole page has no headword -> append to current entry
if current_entry:
self._append_text_to_entry(current_entry, lines, page_num)
# Else: Orphan text? (Before first entry of first page... ignore or new entry?)
continue
# Process segments
prev_line_idx = 0
# 1. Text BEFORE first headword on this page
first_hw_line_idx = page_headword_indices[0][0]
if first_hw_line_idx > 0:
pre_text_lines = lines[0:first_hw_line_idx]
if current_entry:
self._append_text_to_entry(current_entry, pre_text_lines, page_num)
# 2. Iterate headwords
for k, (line_idx, match) in enumerate(page_headword_indices):
try:
headword = match.group(self.group_id)
except IndexError:
headword = match.group(0)
# Content for this entry ranges from line_idx to next_headword_line_idx
content_lines = []