-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhocr_parser.py
More file actions
6607 lines (5420 loc) · 199 KB
/
Copy pathhocr_parser.py
File metadata and controls
6607 lines (5420 loc) · 199 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
# TODO feature: copy/paste of HOCR source code from/to plain text editor
# to allow moving words in the plain text editor
# while preserving the word IDs and bboxes
# copying a word should copy a full HOCR document source
# but containing only the pages/areas/paragraphs/lines/words selected in the plain text editor
"""
HOCR Parser (HTML + XHTML) with Minimal-Diff Updates
====================================================
This module parses hOCR in either HTML or XHTML form using tree-sitter
(`tree-sitter-html` or `tree-sitter-xml`) and provides **minimal-diff** update
operations for word text, bbox, x_wconf, and id. It returns precise byte ranges
so only the changed spans are rewritten.
Requirements (pip):
pip install tree_sitter tree_sitter_language_pack
Usage:
from hocr_parser import HocrParser
src = Path("doc.hocr.html").read()
hp = HocrParser(src)
words = hp.find_words() # list[Word]
hp.update(word_id=words[0].id_bytes, text_bytes=b"NEW")
hp.update(word_id=words[0].id_bytes, bbox=(10,20,100,60), x_wconf=95)
new_src = hp.source_bytes # updated HTML/XML bytestring
Notes:
- Robust to both grammars' node/field name differences.
- For HTML, accepts attribute_value variants: 'quoted_attribute_value',
'attribute_value', 'unquoted_attribute_value'.
- For XHTML/XML, reads 'AttValue'.
- Class matching checks tokens (so 'ocrx_word other' works).
"""
from __future__ import annotations
from dataclasses import dataclass
from dataclasses import (
field,
)
from typing import Dict, Iterable, List, Optional, Tuple
from typing import (
Any,
Literal,
)
import re
import traceback
from tree_sitter import Parser
from tree_sitter_language_pack import get_language
debug = False
# debug = True
debug_word_id = None
# debug_word_id = b"word_1_15"
HTML_LANG = get_language("html")
XML_LANG = get_language("xml")
# ------------------------ utilities ------------------------
_TITLE_BBOX_RE = re.compile(rb"bbox\s+(-?\d+)\s+(-?\d+)\s+(-?\d+)\s+(-?\d+)", re.IGNORECASE)
_TITLE_XWCONF_RE = re.compile(rb"x_wconf\s+(-?\d+)", re.IGNORECASE)
# dont let qt swallow python exceptions
def print_exceptions(func):
def print_exceptions_wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as exc:
def filter_frame(frame):
remove_frame_suffix_list = [
"Traceback (most recent call last):\n",
# remove wrapper frames
", in print_exceptions_wrapper\n return func(*args, **kwargs)\n",
", in print_exceptions_wrapper\n stack = traceback.format_stack()\n",
# remove main frames
", in main\n sys.exit(app.exec())\n",
", in <module>\n main()\n",
]
for frame_suffix in remove_frame_suffix_list:
if frame.endswith(frame_suffix):
return False
return True
print("Traceback (most recent call last):")
# Incoming Python stack (where this call came from)
stack = traceback.format_stack()
if 0:
# debug: print all frames
for frame in stack:
print("frame", repr(frame))
stack = filter(filter_frame, stack)
print("".join(stack), end="")
# Exception traceback with locals
capture_locals = False
# capture_locals = True # also print function parameters. noisy but maybe helpful
stack = traceback.TracebackException.from_exception(exc, capture_locals=capture_locals).format()
stack = filter(filter_frame, stack)
print("".join(stack), end="")
return print_exceptions_wrapper
def _parse_title(title_value: bytes):
"""Return (bbox_tuple_or_None, x_wconf_or_None) from the raw 'title' value (no quotes)."""
s = (title_value or b"").strip()
bbox = None
xw = None
m = _TITLE_BBOX_RE.search(s)
if m:
try:
bbox = tuple(map(int, m.groups()))
except Exception:
bbox = None
m2 = _TITLE_XWCONF_RE.search(s)
if m2:
try:
xw = int(m2.group(1))
except Exception:
xw = None
# Fallback: token scan if regex failed
if bbox is None and b"bbox" in s.lower():
try:
parts = re.split(rb"[;\s]+", s)
for i, p in enumerate(parts):
if p.lower() == b"bbox" and i + 4 < len(parts):
bx = tuple(map(int, parts[i+1:i+5]))
if len(bx) == 4:
bbox = bx
break
except Exception:
pass
return bbox, xw
@print_exceptions
def _format_title(
existing: bytes,
**kwargs
) -> bytes:
"""Merge new title values (bbox, ...) into an existing semicolon-separated title value.
Preserves unknown fields and order.
"""
assert isinstance(existing, bytes)
# print("_format_title existing", repr(existing))
existing = existing or b""
# title_items = [] # preserve duplicate keys
title_dict = {}
for part in existing.split(b";"):
key_val = re.split(rb"\s+", part.strip(), 1)
if len(key_val) == 1:
if key_val[0] == b"": continue # both key and val are empty
key_val.append(b"")
key, val = key_val
# title_items.append((key, val))
title_dict[key] = val
# import json
# print("_format_title title_dict", json.dumps(title_dict, indent=2))
# print("_format_title kwargs", json.dumps(kwargs, indent=2))
@print_exceptions
def encode_val(val):
if isinstance(val, bytes):
return val
return str(val).encode("utf8")
for key, val in kwargs.items():
key = encode_val(key)
if isinstance(val, (list, tuple)):
val = b" ".join(map(encode_val, val))
val = encode_val(val)
title_dict[key] = val
new_title = b"; ".join([(key + b" " + val) for key, val in title_dict.items()])
if debug:
print(f"_format_title: {existing!r} -> {new_title!r}")
return new_title
@dataclass
class Word:
parent: "HocrLine"
id_bytes: bytes
text_bytes: bytes
bbox: Optional[Tuple[int, int, int, int]]
x_wconf: Optional[int]
# raw title value (without surrounding quotes)
title_value: Optional[bytes]
# precise byte ranges (start_byte, end_byte) in source_bytes
byte_range: Tuple[int, int]
title_value_range: Tuple[int, int]
id_value_range: Tuple[int, int]
element_byte_range: Tuple[int, int]
span_range: Tuple[int, int]
# @print_exceptions
# def __init__(self, *a, **k):
# super().__init__(*a, **k)
# assert isinstance(self.id_bytes, bytes)
# assert isinstance(self.text_bytes, bytes)
# assert isinstance(self.title_value, bytes)
@dataclass
class ProjectionSegment:
"""
Maps a range in the plain-text projection to the HOCR source.
plain_start_char/plain_end_char are Python string character offsets.
source_start_byte/source_end_byte are byte offsets into the original UTF-8
source bytes.
word_id is set for text belonging to an ocrx_word.
"""
# char offsets
plain_start_char: int
plain_end_char: int
# byte offsets
source_start_byte: int
source_end_byte: int
kind: Literal[
"word",
"space",
"line_break",
"paragraph_break",
]
word_id: Optional[str] = None
@dataclass
class PlainTextProjection:
"""
A rendered plain-text representation of the HOCR document.
"""
text_str: str
segments: list[ProjectionSegment]
@print_exceptions
def segment_at(self, char_position: int) -> Optional[ProjectionSegment]:
for segment in self.segments:
if segment.plain_start_char <= char_position < segment.plain_end_char:
return segment
return None
@print_exceptions
def word_segments(self) -> list[ProjectionSegment]:
return [
segment
for segment in self.segments
if segment.kind == "word"
]
def build_plain_text_projection(self) -> PlainTextProjection:
# FIXME use io.StringIO
str_parts = []
segments = []
plain_char_pos = 0
paragraphs = self.find_paragraphs()
for paragraph_index, paragraph in enumerate(paragraphs):
for line_index, line in enumerate(paragraph.lines):
for word_index, word in enumerate(line.words):
if word_index > 0:
str_parts.append(" ")
segments.append(
ProjectionSegment(
plain_start_char=plain_char_pos,
plain_end_char=plain_char_pos + 1,
source_start_byte=word.byte_range[0],
source_end_byte=word.byte_range[0],
kind="space",
)
)
plain_char_pos += 1
text_bytes = word.text_bytes
text_str = text_bytes.decode(self.source_encoding)
# str_parts.append(text_bytes)
str_parts.append(text_str)
segments.append(
ProjectionSegment(
plain_start_char=plain_char_pos,
# plain_end_char=plain_char_pos + len(text_bytes),
plain_end_char=plain_char_pos + len(text_str),
source_start_byte=word.byte_range[0],
source_end_byte=word.byte_range[1],
kind="word",
word_id=word.id_bytes,
)
)
# plain_char_pos += len(text_bytes)
plain_char_pos += len(text_str)
if line_index < len(paragraph.lines) - 1:
str_parts.append("\n")
segments.append(
ProjectionSegment(
plain_start_char=plain_char_pos,
plain_end_char=plain_char_pos + 1,
source_start_byte=0,
source_end_byte=0,
kind="line_break",
)
)
plain_char_pos += 1
if paragraph_index < len(paragraphs) - 1:
str_parts.append("\n\n")
segments.append(
ProjectionSegment(
plain_start_char=plain_char_pos,
plain_end_char=plain_char_pos + 2,
source_start_byte=0,
source_end_byte=0,
kind="paragraph_break",
)
)
plain_char_pos += 2
return PlainTextProjection(
text_str="".join(str_parts),
segments=segments,
)
def word_at_plain_position(
self,
projection: PlainTextProjection,
char_position: int,
) -> Optional[Word]:
r"""
find the Word corresponding to a plain-text position
Eventually, we should optimize this with a dictionary:
words_by_id = {
word.id_bytes: word
for word in self.find_words()
}
"""
segment = projection.segment_at(char_position)
if segment is None:
return None
if segment.kind != "word":
return None
for word in self.find_words():
if word.id_bytes == segment.word_id:
return word
return None
# NOTE instead we use: class Word
r'''
@dataclass
class HocrWord:
id_bytes: bytes
parent: "HocrLine"
# parents
line: "HocrLine"
paragraph: "HocrParagraph"
area: "HocrArea"
page: "HocrPage"
text_bytes: bytes
bbox: tuple[int, int, int, int] | None
x_wconf: int | None
# byte range of the complete word element
element_byte_range: tuple[int, int]
# byte range of the word text
byte_range: tuple[int, int]
'''
@dataclass
class HocrLine:
id_bytes: bytes
parent: "HocrParagraph"
words: list[Word] = field(default_factory=list)
# byte range of the complete line element
element_byte_range: tuple[int, int] = (0, 0)
@dataclass
class HocrParagraph:
id_bytes: bytes
parent: "HocrArea"
lines: list[HocrLine] = field(default_factory=list)
# byte range of the complete paragraph element
element_byte_range: tuple[int, int] = (0, 0)
@dataclass
class HocrArea:
id_bytes: bytes
parent: "HocrPage"
# byte range of the complete area element
element_byte_range: tuple[int, int]
paragraphs: list[HocrParagraph] = field(default_factory=list)
@dataclass
class HocrPage:
id_bytes: bytes
parent: "None"
# byte range of the complete page element
element_byte_range: tuple[int, int]
areas: list[HocrArea] = field(default_factory=list)
@dataclass
class TextSpan:
"""
One logical region of the plain-text representation.
Example:
hello world
[hello][ ][world]
W1 S W2
"""
start_char: int
end_char: int
kind: Literal[
"word",
"space",
"line_break",
"paragraph_break",
"markup",
]
word: Optional[Word] = None
word_id: Optional[bytes] = None
left_word: Optional[Word] = None
right_word: Optional[Word] = None
left_line: Optional[HocrLine] = None
right_line: Optional[HocrLine] = None
left_paragraph: Optional[HocrParagraph] = None
right_paragraph: Optional[HocrParagraph] = None
@property
def char_length(self) -> int:
return self.end_char - self.start_char
@dataclass
class ParsedLine:
id_bytes: bytes
words: list[Word]
# byte range of the complete line element
element_byte_range: tuple[int, int]
@dataclass
class ParsedParagraph:
id_bytes: bytes
lines: list[ParsedLine]
# byte range of the complete paragraph element
element_byte_range: tuple[int, int]
class HocrParser:
@print_exceptions
def __init__(self, source_bytes: bytes):
# tree-sitter setup
self.tree = None
# Persistent document model
self.pages: list[HocrPage] = []
self.pages_by_id: dict[bytes, HocrPage] = {}
self.areas_by_id: dict[bytes, HocrArea] = {}
self.paragraphs_by_id: dict[bytes, HocrParagraph] = {}
self.lines_by_id: dict[bytes, HocrLine] = {}
self.words_by_id: dict[bytes, Word] = {}
# Plain-text position index
self.text_spans: list[TextSpan] = []
self._model_initialized = False
# this also calls self._build_model()
self.set_source_bytes(source_bytes)
# ------------------------ public API ------------------------
@property
def is_xml(self) -> bool:
return self._lang == "xml"
@print_exceptions
def find_words(self) -> List[Word]:
return list(self._index_words().values())
@print_exceptions
def find_pages(self) -> List[Word]:
pages = []
stack = [self.tree.root_node]
sb = self.source_bytes
while stack:
n = stack.pop()
# Only consider element nodes
if n.type in ("element", "html_element", "div"):
page = self._extract_page_node(n, sb)
if page:
pages.append(page)
stack.extend(n.children)
return pages
@print_exceptions
def _extract_page_node(self, element, sb: bytes) -> Optional[Word]:
# Get start tag or STag
if self._lang == "html":
start_tag = next((c for c in element.children if c.type=="start_tag"), None)
if not start_tag:
return None
attrs: dict[bytes, Tuple[bytes, Tuple[int, int]]] = {}
for c in start_tag.children:
if c.type=="attribute":
n,v,vr = self._read_html_attribute(c, sb)
if n: attrs[n] = (v,vr)
cls_val = attrs.get(b"class", (b"", (0,0)))[0]
if b"ocr_page" not in cls_val.split(): return None
title_val, title_range = attrs.get(b"title", (b"", (0,0)))
bbox,_ = _parse_title(title_val)
if not bbox: bbox=(0,0,0,0)
# TODO dont use "class Word" here
return Word(
parent=None,
id_bytes=attrs.get(b"id", (b"", (0,0)))[0],
text_bytes=b"",
bbox=bbox,
x_wconf=None,
title_value=title_val,
byte_range=(0,0),
title_value_range=title_range,
id_value_range=attrs.get(b"id",(b"",(0,0)))[1],
element_byte_range=(element.start_byte, element.end_byte),
span_range=(0,0),
)
else: # xml / xhtml
# TODO rename to start_tags
stags = [c for c in element.children if c.type=="STag"]
if not stags: return None
# TODO rename to start_tag
st = stags[0]
attrs: dict[bytes, Tuple[bytes, Tuple[int, int]]] = {}
for c in st.children:
if c.type=="Attribute":
n,v,vr = self._read_xml_attribute(c, sb)
if n: attrs[n]=(v,vr)
cls_val = attrs.get(b"class", (b"", (0,0)))[0]
if b"ocr_page" not in cls_val.split(): return None
title_val, title_range = attrs.get(b"title", (b"", (0,0)))
bbox,_ = _parse_title(title_val)
if not bbox: bbox=(0,0,0,0)
# TODO dont use "class Word" here
return Word(
parent=None,
id_bytes=attrs.get(b"id", (b"", (0,0)))[0],
text_bytes=b"",
bbox=bbox,
x_wconf=None,
title_value=title_val,
byte_range=(0,0),
title_value_range=title_range,
id_value_range=attrs.get(b"id",(None,(0,0)))[1],
element_byte_range=(element.start_byte, element.end_byte),
span_range=(0,0),
)
@print_exceptions
def get_word(self, word_id: str) -> Optional[Word]:
return self._index_words().get(word_id)
@print_exceptions
def update(self,
word_id: str,
*,
text_bytes: Optional[bytes] = None,
bbox: Optional[Tuple[int, int, int, int]] = None,
x_wconf: Optional[int] = None,
new_id: Optional[str] = None) -> bool:
"""Apply one or more changes to a word by id using minimal diffs.
Returns True if the word was found and something changed.
"""
# print(f"parser.update: text_bytes {text_bytes!r} bbox {bbox!r}")
idx = self._index_words()
node = idx.get(word_id)
if not node:
return False
changed = False
if text_bytes is not None:
assert isinstance(text_bytes, bytes)
# 1) text
if text_bytes is not None and node.byte_range:
if debug_word_id and debug_word_id == word_id:
old_text = self.source_bytes[node.byte_range[0]:node.byte_range[1]]
print(f"word {word_id}: update: update text: {old_text!r} -> {text_bytes}")
self._replace_range(node.byte_range, text_bytes)
changed = True
# reindex to refresh ranges after _replace_range
idx = self._index_words()
node = idx.get(word_id) or node
# 2) title merge (bbox/x_wconf)
if bbox is not None or x_wconf is not None:
current_title = self.source_bytes[node.title_value_range[0]:node.title_value_range[1]]
kwargs: dict[str, Any] = dict()
if bbox is not None: kwargs["bbox"] = bbox
if x_wconf is not None: kwargs["x_wconf"] = x_wconf
new_title = _format_title(current_title, **kwargs)
if debug_word_id and debug_word_id == word_id:
if current_title == new_title:
print(f"word {word_id}: update: update title: no change in attribute @ {node.title_value_range}: title = {current_title!r}")
else:
print(f"word {word_id}: update: update title: attribute @ {node.title_value_range}: title = {current_title!r}")
print(f"word {word_id}: update: update title: {current_title!r} -> {new_title!r}")
# FIXME preserve the old x_wconf value (and all other semicolon-separated values in title)
if new_title != current_title:
self._replace_range(node.title_value_range, new_title)
changed = True
# reindex to refresh ranges after _replace_range
idx = self._index_words()
node = idx.get(word_id) or node
# 3) id change
if new_id is not None and new_id != node.id_bytes:
self._replace_range(node.id_value_range, new_id)
changed = True
return changed
@print_exceptions
def update_by_span(
self,
span_start: int,
*,
text_bytes: Optional[bytes] = None,
bbox: Optional[Tuple[int, int, int, int]] = None,
x_wconf: Optional[int] = None,
new_id: Optional[str] = None
) -> bool:
"""Update a word identified by its span start byte offset instead of id.
This avoids collisions when multiple elements share the same id value.
"""
word = self.find_word_by_span_start(span_start)
if not word:
return False
changed = False
if text_bytes is not None:
assert isinstance(text_bytes, bytes)
# 1) text
if text_bytes is not None and word.byte_range:
old_text = self.source_bytes[word.byte_range[0]:word.byte_range[1]]
print(f"word {word.id_bytes}: update_by_span: update text (by span): {old_text!r} -> {text_bytes!r}")
self._replace_range(word.byte_range, text_bytes)
changed = True
# re-find word after parse
word = self.find_word_by_span_start(span_start) or word
# 2) title merge (bbox/x_wconf)
if bbox is not None or x_wconf is not None:
current_title = self.source_bytes[word.title_value_range[0]:word.title_value_range[1]]
kwargs: dict[str, Any] = {}
if bbox is not None:
kwargs["bbox"] = bbox
if x_wconf is not None:
kwargs["x_wconf"] = x_wconf
new_title = _format_title(current_title, **kwargs)
if current_title == new_title:
if debug_word_id and debug_word_id == word.id_bytes:
print(f"word {word.id_bytes}: update_by_span: update title: no change in attribute @ {word.title_value_range}: title = {current_title!r}")
else:
if debug_word_id and debug_word_id == word.id_bytes:
print(f"word {word.id_bytes}: update_by_span: update title: attribute @ {word.title_value_range}: title = {current_title!r}")
print(f"word {word.id_bytes}: update_by_span: update title: {current_title!r} -> {new_title!r}")
self._replace_range(word.title_value_range, new_title)
changed = True
word = self.find_word_by_span_start(span_start) or word
# 3) id change
if new_id is not None and new_id != word.id_bytes:
self._replace_range(word.id_bytes_value_range, new_id)
changed = True
return changed
@print_exceptions
def find_word_by_span_start(self, span_start: int) -> Optional[Word]:
"""Return the Word whose span_range[0] equals span_start (or None)."""
for w in self.find_words():
if w.span_range and w.span_range[0] == span_start:
return w
return None
# ------------------------ core ------------------------
@print_exceptions
def set_source_bytes(self, source_bytes: bytes, source_encoding="utf-8"):
assert isinstance(source_bytes, bytes)
self.source_bytes = source_bytes
self.source_encoding = source_encoding
self._lang = _detect_lang(self.source_bytes)
lang = XML_LANG if self._lang == "xml" else HTML_LANG
self.parser = Parser(lang)
self.tree = self.parser.parse(self.source_bytes)
r'''
self.source_str = self.source_bytes.decode(self.source_encoding)
# TypeError: source must be a bytestring or a callable, not str
# self.tree = self.parser.parse(self.source_str)
def read_source_str(byte_offset, point):
# row, column = point
# TypeError: read callable must return a bytestring
# return self.source_str[byte_offset:]
return self.source_bytes[byte_offset:]
# fix: ValueError: encoding must be 'utf8', 'utf16', 'utf16le', or 'utf16be', not 'utf-8'
encoding = self.source_encoding.lower().replace("-", "")
self.tree = self.parser.parse(read_source_str, encoding=encoding)
'''
self._cached_index: Optional[Dict[bytes, Word]] = None
# Rebuild the logical model immediately.
debug = 0
if debug:
print(f"HocrParser.set_source_bytes: calling self._build_model")
self._build_model()
self._model_initialized = True
def byte_offset_to_char_offset(self, byte_offset: int) -> int:
return len(self.source_bytes[:byte_offset].decode(self.source_encoding))
@print_exceptions
def set_source_string(self, source: str, encoding=None):
self.source_encoding = encoding or self.source_encoding
assert isinstance(source, str)
source_bytes = source.encode(self.source_encoding, errors="replace")
self.set_source_bytes(source_bytes)
@print_exceptions
def get_source_string(self, encoding=None) -> str:
encoding = encoding or self.source_encoding
source = self.source_bytes.decode(encoding, errors="replace")
return source
@print_exceptions
def _index_words(self) -> Dict[bytes, Word]:
if self._cached_index is not None:
return self._cached_index
words: dict[bytes, Word] = {}
root = self.tree.root_node
stack = [root]
sb = self.source_bytes
while stack:
n = stack.pop()
if self._lang == "html":
if n.type == "element":
w = self._parse_word_html(n, sb)
if w:
words[w.id_bytes] = w
else: # xml
if n.type == "element":
w = self._parse_word_xml(n, sb)
if w:
words[w.id_bytes] = w
# DFS
stack.extend(n.children)
self._cached_index = words
return words
# ------------------------ extraction: HTML ------------------------
@print_exceptions
def _parse_word_html(self, element, sb: bytes) -> Optional[Word]:
# element = start_tag, (text|element)*, end_tag
# Find start_tag
if not element.children or element.children[0].type != "start_tag":
return None
start_tag = element.children[0]
tag_name = None
attrs: dict[bytes, Tuple[bytes, Tuple[int, int]]] = {}
for ch in start_tag.children:
t = ch.type
if t == "tag_name":
tag_name = sb[ch.start_byte:ch.end_byte]
elif t == "attribute":
n, v, vr = self._read_html_attribute(ch, sb)
if n:
attrs[n] = (v, vr)
if (tag_name or b"").lower() != b"span":
return None
cls_val = attrs.get(b"class", (b"", (0, 0)))[0]
if not _class_has(cls_val, b"ocrx_word"):
return None
# id & title
id_val, id_range = attrs.get(b"id", (b"", (0, 0)))
title_val, title_range = attrs.get(b"title", (b"", (0, 0)))
if debug_word_id and debug_word_id == id_val:
for n, (v, vr) in attrs.items():
print(f"_parse_word_html: attribute @ {vr}: {n} = {v!r}")
# inner text: first 'text' child directly under element
text_node = None
for ch in element.children:
if ch.type == "text":
text_node = ch
break
end_tag = element.children[-1]
if text_node is not None:
text_bytes = sb[text_node.start_byte:text_node.end_byte]
byte_range = (text_node.start_byte, text_node.end_byte)
else:
# empty span: zero-length before end_tag
text_bytes = b""
byte_range = (end_tag.start_byte, end_tag.start_byte)
bbox, xw = _parse_title(title_val)
if bbox is None:
print(f"word {id_val!r}: failed to parse bbox from title {title_val!r}")
return None
assert not (bbox is None), f"word {id_val!r}: failed to parse bbox from title {title_val!r}"
debug = 0
debug = 1
if debug:
print("\n========== _parse_word_html ==========")
print(
"id:",
repr(id_val),
)
print(
"text_bytes:",
repr(text_bytes),
)
print(
"byte_range:",
byte_range,
)
print(
"element range:",
(
element.start_byte,
element.end_byte,
),
)
if text_node is not None:
print(
"text_node:",
text_node,
)
print(
"text_node.type:",
text_node.type,
)
print(
"text_node.start_byte:",
text_node.start_byte,
)
print(
"text_node.end_byte:",
text_node.end_byte,
)
print(
"source_bytes[text_node range]:",
repr(
sb[
text_node.start_byte:
text_node.end_byte
]
),
)
print(
"source_bytes[byte_range]:",
repr(
sb[
byte_range[0]:
byte_range[1]
]
),
)
print(
"element source:",
repr(
sb[
element.start_byte:
element.end_byte
]
)[:500],
)
print(
"========================================"
)
return Word(
parent=None,
id_bytes=id_val,
text_bytes=text_bytes,
bbox=bbox,
x_wconf=xw,
title_value=title_val,
byte_range=byte_range,
title_value_range=title_range,
id_value_range=id_range,
element_byte_range=(element.start_byte, element.end_byte),
span_range=(start_tag.start_byte, end_tag.end_byte),
)
@print_exceptions
def _read_html_attribute(self, attr_node, sb: bytes) -> Tuple[Optional[bytes], bytes, Tuple[int, int]]:
"""
Returns (name, value_without_quotes, inner_range) for HTML grammar.
Handles multiple possible child node type names across html grammars.
"""
name_node = getattr(attr_node, "child_by_field_name", lambda *_: None)("name")
value_node = getattr(attr_node, "child_by_field_name", lambda *_: None)("value")
if not name_node or not value_node:
# Fallback: scan children for common node type names
for c in attr_node.children:
if not name_node and c.type in ("attribute_name", "property_identifier", "attribute_name_identifier", "name"):
name_node = c
if not value_node and c.type in ("quoted_attribute_value", "attribute_value", "unquoted_attribute_value", "string"):
value_node = c
if not name_node or not value_node:
return None, b"", (attr_node.start_byte, attr_node.start_byte)
name = sb[name_node.start_byte:name_node.end_byte]
raw = sb[value_node.start_byte:value_node.end_byte]
inner_start, inner_end = _strip_quote_range(value_node.start_byte, value_node.end_byte, raw)
value = sb[inner_start:inner_end]
return name, value, (inner_start, inner_end)