xberg 1.1.2

High-performance document intelligence library for Rust. Extract text, metadata, and structured data from PDFs, Office documents, images, and 107 formats and 371 programming languages via tree-sitter code intelligence with async/sync APIs.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
//! hOCR → `InternalDocument` parser.
//!
//! Adapted from `html_to_markdown_rs::hocr` property and element parsing.
//!
//! This module parses hOCR HTML produced by Tesseract (and compatible engines)
//! into xberg's `InternalDocument` representation, preserving bounding boxes,
//! confidence scores, and page structure.
//!
//! ## hOCR hierarchy handled
//!
//! ```text
//! ocr_page  →  PageBreak between pages
//!   ocr_carea / ocrx_block
//!     ocr_par  →  InternalElement (OcrText::Block)
//!       ocr_line / ocrx_line  →  line break within paragraph
//!         ocrx_word  →  word text with bbox and confidence
//! ```

use memchr::memchr;

use crate::types::extraction::BoundingBox;
use crate::types::internal::{ElementKind, InternalDocument, InternalElement};
use crate::types::ocr_elements::{OcrBoundingGeometry, OcrConfidence, OcrElementLevel};

/// Attribute used to retain the logical hOCR block enclosing an `ocr_par`.
pub(crate) const HOCR_BLOCK_ID_ATTRIBUTE: &str = "hocr_block_id";

#[derive(Debug)]
struct HocrBlockExtent {
    end: usize,
    id: String,
}

/// Parse hOCR HTML into an `InternalDocument` with full spatial and confidence metadata.
///
/// This is the primary entry point. It replaces the older `convert_hocr_to_markdown` path
/// by producing structured [`InternalElement`]s directly, preserving OCR geometry and
/// confidence that the markdown conversion discards.
///
/// # Arguments
///
/// * `hocr_html` — raw hOCR output from Tesseract (or compatible engine).
///
/// # Output mapping
///
/// | hOCR element   | xberg element                             |
/// |---------------|-----------------------------------------------|
/// | `ocr_page`    | `PageBreak` between consecutive pages         |
/// | `ocr_par`     | `OcrText { level: Block }` with union bbox    |
/// | `ocr_line`    | newline separator within a paragraph          |
/// | `ocrx_word`   | word text, bbox, `x_wconf` → `OcrConfidence` |
///
/// Page numbers come from the `ppageno` title property (converted to 1-indexed).
#[cfg(test)]
pub(crate) fn parse_hocr_to_internal_document(hocr_html: &str) -> InternalDocument {
    parse_hocr_to_internal_document_with_dictionary_filter(hocr_html, None)
}

/// Same as [`parse_hocr_to_internal_document`], with an optional per-line
/// dictionary-invalid noise filter (#783). See [`DictionaryLineFilter`] for why this must
/// run here -- before a paragraph's `ocr_line` groups are joined into its `\n`-joined
/// `text` -- rather than against either of that text's two independent downstream
/// consumers.
///
/// Kept as a separate function (rather than adding a parameter to
/// [`parse_hocr_to_internal_document`] directly) so the ~30 existing call sites that only
/// ever want the unfiltered parse -- almost all of them tests -- do not need to change.
#[cfg(test)]
pub(crate) fn parse_hocr_to_internal_document_with_dictionary_filter(
    hocr_html: &str,
    dictionary_filter: Option<&DictionaryLineFilter<'_>>,
) -> InternalDocument {
    parse_hocr_to_internal_document_with_page_offset(hocr_html, dictionary_filter, 1)
}

/// Same as [`parse_hocr_to_internal_document_with_dictionary_filter`], except elements' page
/// numbers are computed as `ppageno + page_offset` instead of always `ppageno + 1`.
///
/// Tesseract numbers every single-image `recognize()` call's hOCR page as `ppageno 0`
/// regardless of which page of the source document that image actually is -- `perform_ocr`
/// (`ocr::processor::execution`) loads and recognizes exactly one image per call, so the hOCR
/// it gets back can never know the true page number on its own. Callers that OCR one page at a
/// time out of a larger document (the PDF OCR route) pass the real 1-indexed page number here,
/// via `TesseractConfig::page_number`, instead of letting every page collapse to `1`.
#[cfg(test)]
pub(crate) fn parse_hocr_to_internal_document_with_page_offset(
    hocr_html: &str,
    dictionary_filter: Option<&DictionaryLineFilter<'_>>,
    page_offset: u32,
) -> InternalDocument {
    parse_hocr_to_internal_document_with_page_offset_and_stats(hocr_html, dictionary_filter, page_offset).document
}

/// Parsed hOCR plus bounded counters needed by the OCR warning pipeline. ~keep
pub(crate) struct HocrParseResult {
    pub document: InternalDocument,
    pub dictionary_filtered_line_count: usize,
    pub retained_word_confidence_stats: RetainedWordConfidenceStats,
}

#[derive(Debug, Clone)]
pub(crate) struct RetainedWordConfidenceStats {
    histogram: [usize; 101],
    count: usize,
    sum: u64,
    low_confidence_count: usize,
}

impl Default for RetainedWordConfidenceStats {
    fn default() -> Self {
        Self {
            histogram: [0; 101],
            count: 0,
            sum: 0,
            low_confidence_count: 0,
        }
    }
}

impl RetainedWordConfidenceStats {
    pub(crate) fn record(&mut self, confidence: f64) {
        if !confidence.is_finite() || !(0.0..=100.0).contains(&confidence) {
            return;
        }
        let confidence = confidence.round() as usize;
        self.histogram[confidence] = self.histogram[confidence].saturating_add(1);
        self.count = self.count.saturating_add(1);
        self.sum = self.sum.saturating_add(confidence as u64);
        if confidence < 50 {
            self.low_confidence_count = self.low_confidence_count.saturating_add(1);
        }
    }

    pub(crate) fn word_count(&self) -> usize {
        self.count
    }

    pub(crate) fn mean(&self) -> Option<u64> {
        (self.count > 0).then(|| self.sum / self.count as u64)
    }

    pub(crate) fn median(&self) -> Option<usize> {
        if self.count == 0 {
            return None;
        }
        let upper = self.value_at_rank(self.count / 2)?;
        if self.count.is_multiple_of(2) {
            let lower = self.value_at_rank(self.count / 2 - 1)?;
            Some((lower + upper) / 2)
        } else {
            Some(upper)
        }
    }

    pub(crate) fn p10(&self) -> Option<usize> {
        if self.count == 0 {
            None
        } else {
            self.value_at_rank((self.count - 1) / 10)
        }
    }

    pub(crate) fn low_confidence_word_count(&self) -> usize {
        self.low_confidence_count
    }

    fn value_at_rank(&self, rank: usize) -> Option<usize> {
        let mut cumulative = 0usize;
        for (confidence, count) in self.histogram.iter().enumerate() {
            cumulative = cumulative.saturating_add(*count);
            if rank < cumulative {
                return Some(confidence);
            }
        }
        None
    }
}

/// Parse hOCR and report how many physical lines dictionary filtering removed. ~keep
pub(crate) fn parse_hocr_to_internal_document_with_page_offset_and_stats(
    hocr_html: &str,
    dictionary_filter: Option<&DictionaryLineFilter<'_>>,
    page_offset: u32,
) -> HocrParseResult {
    let mut doc = InternalDocument::new("ocr");
    doc.mime_type = "application/x-hocr".to_string();

    let mut element_index: u32 = 0;
    let mut last_page: Option<u32> = None;
    let mut dictionary_filtered_line_count = 0usize;
    let mut retained_word_confidence_stats = RetainedWordConfidenceStats::default();

    let bytes = hocr_html.as_bytes();
    let mut pos = 0;
    let mut block_extents = Vec::<HocrBlockExtent>::new();

    while pos < bytes.len() {
        let Some(tag_start) = memchr(b'<', &bytes[pos..]).map(|i| pos + i) else {
            break;
        };
        let Some(tag_end) = memchr(b'>', &bytes[tag_start..]).map(|i| tag_start + i) else {
            break;
        };
        let tag_content = &hocr_html[tag_start + 1..tag_end];
        pos = tag_end + 1;
        block_extents.retain(|extent| tag_start < extent.end);

        if tag_content.starts_with('/') || tag_content.ends_with('/') {
            continue;
        }

        if has_class(tag_content, "ocr_page") {
            let title = extract_title_attr(tag_content);
            let props = parse_title_properties(&title);
            let page_number = props.ppageno.map(|p| p + page_offset);

            if let Some(prev) = last_page
                && page_number != Some(prev)
            {
                let pb = InternalElement::text(ElementKind::PageBreak, "", 0).with_index(element_index);
                element_index += 1;
                doc.push_element(pb);
            }
            last_page = page_number;
            continue;
        }

        if has_class(tag_content, "ocr_carea") || has_class(tag_content, "ocrx_block") {
            let tag_name = tag_content
                .split_whitespace()
                .next()
                .unwrap_or("div")
                .to_ascii_lowercase();
            let end = skip_to_matching_close(hocr_html, pos, &tag_name);
            let id = extract_attribute(tag_content, "id")
                .filter(|id| !id.is_empty())
                .unwrap_or_else(|| format!("hocr-block-{tag_start}-{end}"));
            block_extents.push(HocrBlockExtent { end, id });
            continue;
        }

        if is_paragraph_tag(tag_content) {
            let par_tag_name = tag_content
                .split_whitespace()
                .next()
                .unwrap_or("p")
                .to_ascii_lowercase();
            let (paragraph, end_pos, filtered_lines) = parse_paragraph(
                hocr_html,
                pos,
                last_page.unwrap_or(page_offset),
                element_index,
                &par_tag_name,
                dictionary_filter,
                &mut retained_word_confidence_stats,
            );
            pos = end_pos;
            dictionary_filtered_line_count = dictionary_filtered_line_count.saturating_add(filtered_lines);

            if let Some(mut elem) = paragraph {
                if let Some(block) = block_extents.last() {
                    elem.attributes
                        .get_or_insert_with(Default::default)
                        .insert(HOCR_BLOCK_ID_ATTRIBUTE.to_string(), block.id.clone());
                }
                element_index += 1;
                doc.push_element(elem);
            }
        }
    }

    tracing::debug!(
        input_bytes = hocr_html.len(),
        elements = doc.elements.len(),
        total_text_chars = doc.elements.iter().map(|e| e.text.len()).sum::<usize>(),
        "hOCR parse complete"
    );

    HocrParseResult {
        document: doc,
        dictionary_filtered_line_count,
        retained_word_confidence_stats,
    }
}

/// Parsed properties from an hOCR `title` attribute.
#[derive(Debug, Default)]
struct HocrProperties {
    /// Bounding box: (x1, y1, x2, y2).
    bbox: Option<(u32, u32, u32, u32)>,
    /// Word confidence 0–100.
    x_wconf: Option<f64>,
    /// Physical page number (0-indexed from Tesseract).
    ppageno: Option<u32>,
    /// Text rotation angle.
    textangle: Option<f64>,
    /// Baseline (slope, constant).
    baseline: Option<(f64, i32)>,
    /// Font name.
    x_font: Option<String>,
    /// Font size in points.
    x_fsize: Option<u32>,
    /// Whether the word is rendered in a bold font, from the word's `x_bold`
    /// hOCR property. Only present on `ocrx_word` titles when Tesseract's
    /// `hocr_font_info` variable is enabled (`ocr/processor/config.rs`).
    x_bold: bool,
    /// Whether the word is rendered in an italic font, from the word's
    /// `x_italic` hOCR property. Same availability as `x_bold`.
    x_italic: bool,
    /// x-height in pixels — the height of the line's lowercase letters
    /// excluding ascenders/descenders. Emitted by Tesseract on `ocr_line`/
    /// `ocrx_line` titles, not on individual words. A better heading signal
    /// than raw bbox height because it is insensitive to how many ascenders
    /// or descenders happen to appear in a given line.
    x_size: Option<f64>,
    /// Ascender height in pixels, from the line's `x_ascenders` property.
    x_ascenders: Option<f64>,
    /// Descender height in pixels, from the line's `x_descenders` property.
    x_descenders: Option<f64>,
}

/// Parse all properties from an hOCR title attribute string.
///
/// Handles the semicolon-separated `key value ...` format produced by Tesseract:
///
/// ```text
/// bbox 100 50 200 150; x_wconf 95; ppageno 0
/// ```
fn parse_title_properties(title: &str) -> HocrProperties {
    let mut props = HocrProperties::default();

    for part in title.split(';') {
        let part = part.trim();
        if part.is_empty() {
            continue;
        }

        let mut tokens = part.split_whitespace();
        let Some(key) = tokens.next() else {
            continue;
        };

        match key {
            "bbox" => {
                let coords: Vec<u32> = tokens.filter_map(|s| s.parse().ok()).collect();
                if coords.len() == 4 {
                    props.bbox = Some((coords[0], coords[1], coords[2], coords[3]));
                }
            }
            "x_wconf" => {
                if let Some(val) = tokens.next().and_then(|s| s.parse::<f64>().ok()) {
                    props.x_wconf = Some(val);
                }
            }
            "ppageno" => {
                if let Some(val) = tokens.next().and_then(|s| s.parse::<u32>().ok()) {
                    props.ppageno = Some(val);
                }
            }
            "textangle" => {
                if let Some(val) = tokens.next().and_then(|s| s.parse::<f64>().ok()) {
                    props.textangle = Some(val);
                }
            }
            "baseline" => {
                let slope = tokens.next().and_then(|s| s.parse::<f64>().ok());
                let constant = tokens.next().and_then(|s| s.parse::<i32>().ok());
                if let (Some(s), Some(c)) = (slope, constant) {
                    props.baseline = Some((s, c));
                }
            }
            "x_font" => {
                props.x_font = parse_quoted_value(part);
            }
            "x_fsize" => {
                if let Some(val) = tokens.next().and_then(|s| s.parse::<u32>().ok()) {
                    props.x_fsize = Some(val);
                }
            }
            "x_bold" => {
                props.x_bold = true;
            }
            "x_italic" => {
                props.x_italic = true;
            }
            "x_size" => {
                if let Some(val) = tokens.next().and_then(|s| s.parse::<f64>().ok()) {
                    props.x_size = Some(val);
                }
            }
            "x_ascenders" => {
                if let Some(val) = tokens.next().and_then(|s| s.parse::<f64>().ok()) {
                    props.x_ascenders = Some(val);
                }
            }
            "x_descenders" => {
                if let Some(val) = tokens.next().and_then(|s| s.parse::<f64>().ok()) {
                    props.x_descenders = Some(val);
                }
            }
            _ => {}
        }
    }

    props
}

/// Extract a quoted string value from a property part like `x_font "Arial"`.
fn parse_quoted_value(part: &str) -> Option<String> {
    let start = part.find('"')?;
    let end = part[start + 1..].find('"')?;
    Some(part[start + 1..start + 1 + end].to_string())
}

/// A word extracted from hOCR with its metadata.
struct HocrWordInfo {
    text: String,
    x0: u32,
    y0: u32,
    x1: u32,
    y1: u32,
    confidence: Option<f64>,
    /// Font size in points, from the word's `x_fsize` hOCR property.
    font_size: Option<u32>,
    /// Text rotation angle in degrees, from the word's `textangle` hOCR property.
    text_angle: Option<f64>,
    /// Font family name, from the word's `x_font` hOCR property.
    font_name: Option<String>,
    /// Whether the word is bold, from the word's `x_bold` hOCR property.
    is_bold: bool,
    /// Whether the word is italic, from the word's `x_italic` hOCR property.
    is_italic: bool,
}

/// Per-`ocr_line`/`ocrx_line` metadata parsed from that tag's own `title`
/// attribute, plus the words it contains.
///
/// Kept as one entry per physical hOCR line (rather than folded immediately
/// into a paragraph-wide average) so a downstream consumer can recover a
/// line-level font size — the paragraph mean alone hides variation between,
/// say, a heading's first line and a wrapped continuation line at body size.
#[derive(Default)]
struct HocrLineInfo {
    words: Vec<HocrWordInfo>,
    /// x-height in pixels (`x_size`) — see [`HocrProperties::x_size`].
    x_size: Option<f64>,
    /// Ascender height in pixels (`x_ascenders`).
    x_ascenders: Option<f64>,
    /// Descender height in pixels (`x_descenders`).
    x_descenders: Option<f64>,
    /// Baseline (slope, constant), from the line's `baseline` property.
    baseline: Option<(f64, i32)>,
}

/// Per-line dictionary-invalid noise filter, threaded through hOCR parsing (#783).
///
/// Applied while a paragraph's `ocr_line` groups are still separate physical lines —
/// before their words are joined into the paragraph's `\n`-joined `text` — so every
/// consumer of that text sees the same, already-filtered lines. That matters because
/// there are two such consumers built from the same `InternalElement.text`:
/// `flatten_hocr_elements_to_text` (feeding the flat OCR page string) and
/// `pdf::structure::adapters::ocr_doc_to_paragraphs` / `ocr_doc_to_layout_paragraphs`
/// (feeding the rendered document's paragraphs). Filtering later, against either
/// rendering independently, risks the two silently drifting apart: a prior attempt at
/// this fix (reverted as `29738a1f29`) stripped noise lines only from the flat text
/// string, which never changed the rendered document for any page that also produced
/// structured paragraphs — exactly the elevations-page case this filter targets.
pub(crate) struct DictionaryLineFilter<'a> {
    /// Dictionary membership test, e.g. `TesseractAPI::is_valid_word`. `Some(true)` =
    /// valid, `Some(false)` = invalid, `None` = the lookup itself failed or was
    /// unavailable (never counted as evidence either way).
    pub is_valid_word: &'a dyn Fn(&str) -> Option<bool>,
    /// A line is dropped when its dictionary-checkable words' invalid fraction is
    /// STRICTLY GREATER than this. See [`DEFAULT_DICT_INVALID_LINE_RATIO`] for how the
    /// default value was derived.
    pub max_invalid_ratio: f64,
}

/// Minimum letters a word must have before a dictionary lookup on it is meaningful.
/// Mirrors `ocr::processor::execution::MIN_WORD_LEN_FOR_DICT_CHECK` — both filter the
/// same class of noise (an OCR fragment too short for the dictionary to judge either
/// way), kept as a separate constant here rather than a shared import so this module
/// does not need `ocr::processor::execution` to be `pub(crate)`.
const MIN_WORD_LEN_FOR_DICT_CHECK: usize = 3;

/// Minimum dictionary-checkable words a single hOCR line must contain before
/// [`is_dictionary_noise_line`] scores it at all.
///
/// A physical line is short (a title-block label, a heading), so a high floor would
/// silence this signal for nearly every line on a drawing page. Two independently
/// checkable words distinguish "every word on this line is nonsense" from "one unusual
/// term stands alone on this line" — the latter is exactly the shape of a real proper
/// noun or technical term (a plant genus, a part number) that must not be flagged from a
/// single data point. The blast radius of a wrong per-line call is only that one line,
/// not the whole page, which is what makes a lower floor than a page-level check safe.
pub(crate) const MIN_DICT_CANDIDATES_FOR_LINE: usize = 2;

/// Default [`DictionaryLineFilter::max_invalid_ratio`] (#783).
///
/// Not a config field: [`OcrQualityThresholds`](crate::core::config::OcrQualityThresholds)
/// is part of xberg's alef-generated multi-language binding surface, and every field on it
/// is regenerated into ~15 language bindings, so adding one requires a full `alef
/// generate` pass this fix does not perform. This constant is the internal default until
/// that threading is done deliberately, as its own change with its own binding regen.
///
/// `0.6`, derived directly from two measured examples (2026-08-22), not picked as a round
/// number:
/// - The motivating noise line, "OWATS DNDEVET OPMENT", scores 2 invalid of 3
///   dictionary-checkable candidates (0.667) even though Tesseract's DAWG lookup itself
///   falsely reports "OPMENT" as a valid word -- counting that false positive as valid
///   still leaves the line above 0.6.
/// - The plant-list guard line, "Ligustrum, Photinia, Azalea, Indian Hawthorne", scores 2
///   invalid of 5 (0.4) and must survive untouched.
///
/// 0.6 sits roughly the same distance below the first number as above the second, and
/// matches the existing `max_fragmented_word_ratio` convention in
/// `OcrQualityThresholds`. Unlike that struct's page-level
/// `max_ocr_output_dict_invalid_word_ratio` (disabled by default at `1.01` pending a
/// corpus-wide calibration), this is enabled from the start: the blast radius of a wrong
/// call here is exactly one line, never a whole page, so the acceptable cost of a false
/// positive is far lower.
pub(crate) const DEFAULT_DICT_INVALID_LINE_RATIO: f64 = 0.6;

/// Whether `line`'s dictionary-checkable words are, on balance, not real words.
///
/// Returns `false` (never noise) for a line with fewer than
/// [`MIN_DICT_CANDIDATES_FOR_LINE`] checkable words — see that constant's doc comment.
fn is_dictionary_noise_line(line: &HocrLineInfo, filter: &DictionaryLineFilter<'_>) -> bool {
    let mut candidates = 0usize;
    let mut invalid = 0usize;
    for word in &line.words {
        let text = word.text.trim();
        if text.chars().count() < MIN_WORD_LEN_FOR_DICT_CHECK || !text.chars().all(|c| c.is_alphabetic()) {
            continue;
        }
        match (filter.is_valid_word)(text) {
            Some(true) => candidates += 1,
            Some(false) => {
                candidates += 1;
                invalid += 1;
            }
            None => {}
        }
    }
    if candidates < MIN_DICT_CANDIDATES_FOR_LINE {
        return false;
    }
    (invalid as f64 / candidates as f64) > filter.max_invalid_ratio
}

/// Attribute key holding the paragraph's average word font size (points, as a
/// decimal string). Consumed by markdown assembly to promote large-font
/// paragraphs to headings (#185).
pub(crate) const HOCR_FONT_SIZE_ATTRIBUTE: &str = "x_fsize";

/// Attribute key holding the paragraph's average word text-rotation angle in
/// degrees (as a decimal string), when any word reported a non-zero angle.
pub(crate) const HOCR_TEXT_ANGLE_ATTRIBUTE: &str = "textangle";

/// Attribute key holding the paragraph's average line x-height in pixels (as
/// a decimal string), averaged over lines that reported an `x_size` on their
/// `ocr_line`/`ocrx_line` title. x-height is a better heading signal than raw
/// bbox height because it is insensitive to ascender/descender mix.
pub(crate) const HOCR_X_HEIGHT_ATTRIBUTE: &str = "x_size";

/// Attribute key holding the paragraph's average line ascender height in
/// pixels (as a decimal string).
pub(crate) const HOCR_X_ASCENDERS_ATTRIBUTE: &str = "x_ascenders";

/// Attribute key holding the paragraph's average line descender height in
/// pixels (as a decimal string).
pub(crate) const HOCR_X_DESCENDERS_ATTRIBUTE: &str = "x_descenders";

/// Attribute key holding the paragraph's average line baseline slope (as a
/// decimal string), averaged over lines that reported a `baseline` on their
/// `ocr_line`/`ocrx_line` title.
pub(crate) const HOCR_BASELINE_SLOPE_ATTRIBUTE: &str = "baseline_slope";

/// Attribute key holding the paragraph's average line baseline constant
/// (pixels, as a decimal string).
pub(crate) const HOCR_BASELINE_CONST_ATTRIBUTE: &str = "baseline_const";

/// Attribute key holding one average word font size (points) per physical
/// text line, comma-separated in the same order as the `\n`-separated lines
/// of the element's `text`. A line with no word reporting `x_fsize` is
/// rendered as an empty field so field position still lines up with `text`.
/// Lets a downstream consumer compute a line-level (not just paragraph-mean)
/// font size without carrying every word's bounding box.
pub(crate) const HOCR_LINE_FONT_SIZES_ATTRIBUTE: &str = "line_font_sizes";

/// Attribute key holding one line x-height (pixels, from `x_size`) per
/// physical text line, comma-separated in the same order as the
/// `\n`-separated lines of the element's `text`, with the same empty-field
/// alignment rule as [`HOCR_LINE_FONT_SIZES_ATTRIBUTE`].
pub(crate) const HOCR_LINE_X_HEIGHTS_ATTRIBUTE: &str = "line_x_heights";

/// Attribute key holding the fraction (0.0-1.0, as a decimal string) of the
/// paragraph's words that Tesseract reported as bold via `x_bold`. Only
/// populated on `ocrx_word` titles when `hocr_font_info` is enabled
/// (`ocr/processor/config.rs`). Boldness is an independent heading cue from
/// font size, restoring a signal `from_ocr_elements` consumed before it was
/// deleted as collateral of an unrelated refactor (commit `22161b0d1cc`).
pub(crate) const HOCR_BOLD_FRACTION_ATTRIBUTE: &str = "x_bold_fraction";

/// Attribute key holding the fraction (0.0-1.0, as a decimal string) of the
/// paragraph's words that Tesseract reported as italic via `x_italic`. Same
/// availability and provenance as [`HOCR_BOLD_FRACTION_ATTRIBUTE`].
pub(crate) const HOCR_ITALIC_FRACTION_ATTRIBUTE: &str = "x_italic_fraction";

/// Attribute key holding the most common font family name (from `x_font`)
/// among the paragraph's words, when at least one word reported one.
pub(crate) const HOCR_FONT_NAME_ATTRIBUTE: &str = "x_font";

/// Bold/italic fraction and dominant font name aggregated across a
/// paragraph's words.
struct WordStyleAggregate {
    bold_fraction: f64,
    italic_fraction: f64,
    dominant_font_name: Option<String>,
}

/// Aggregate the `x_bold`/`x_italic`/`x_font` hOCR word properties into
/// paragraph-level signals. `words` must be non-empty.
fn aggregate_word_style(words: &[&HocrWordInfo]) -> WordStyleAggregate {
    let word_count = words.len() as f64;
    let bold_count = words.iter().filter(|w| w.is_bold).count() as f64;
    let italic_count = words.iter().filter(|w| w.is_italic).count() as f64;

    let mut font_name_counts: std::collections::HashMap<&str, u32> = std::collections::HashMap::new();
    for word in words {
        if let Some(ref name) = word.font_name {
            *font_name_counts.entry(name.as_str()).or_insert(0) += 1;
        }
    }
    let dominant_font_name = font_name_counts
        .into_iter()
        .max_by_key(|(_, count)| *count)
        .map(|(name, _)| name.to_string());

    WordStyleAggregate {
        bold_fraction: bold_count / word_count,
        italic_fraction: italic_count / word_count,
        dominant_font_name,
    }
}

/// Render one optional numeric value per line as a comma-joined string,
/// preserving line position (a missing value becomes an empty field) so a
/// downstream consumer can zip the result back up against `text.split('\n')`.
fn join_per_line_values(values: &[Option<f64>]) -> String {
    values
        .iter()
        .map(|value| value.map(format_decimal).unwrap_or_default())
        .collect::<Vec<_>>()
        .join(",")
}

/// Format a float without a trailing `.0` for whole numbers, matching the
/// existing paragraph-average attribute formatting (`f64::to_string`).
fn format_decimal(value: f64) -> String {
    value.to_string()
}

/// Parse a single `<p class="ocr_par">` (or `<span class="ocr_par">`) and all nested
/// content up to the matching closing tag.
///
/// `par_tag` is the lowercase tag name of the paragraph element (e.g. "p", "span", "div").
/// Depth tracking uses ONLY matching tag names to find the paragraph's closing tag.
/// This prevents inner elements (lines, words, formatting) from interfering with
/// the paragraph boundary detection — even if their subtrees are malformed.
///
/// Returns the constructed element (if any words were found) and the byte position
/// after the closing tag.
fn parse_paragraph(
    html: &str,
    start: usize,
    page: u32,
    element_index: u32,
    par_tag: &str,
    dictionary_filter: Option<&DictionaryLineFilter<'_>>,
    retained_word_confidence_stats: &mut RetainedWordConfidenceStats,
) -> (Option<InternalElement>, usize, usize) {
    let bytes = html.as_bytes();
    let mut pos = start;

    let mut lines: Vec<HocrLineInfo> = Vec::new();
    let mut current_line = HocrLineInfo::default();
    let mut in_line = false;

    let mut depth: u32 = 1;

    while pos < bytes.len() {
        let Some(tag_start) = memchr(b'<', &bytes[pos..]).map(|i| pos + i) else {
            break;
        };
        let Some(tag_end) = memchr(b'>', &bytes[tag_start..]).map(|i| tag_start + i) else {
            break;
        };
        let tag_content = &html[tag_start + 1..tag_end];
        pos = tag_end + 1;

        if let Some(stripped) = tag_content.strip_prefix('/') {
            let closing_name = stripped.trim().to_ascii_lowercase();
            if closing_name == par_tag {
                depth = depth.saturating_sub(1);
                if depth == 0 {
                    if !current_line.words.is_empty() {
                        lines.push(std::mem::take(&mut current_line));
                    }
                    break;
                }
            }
            continue;
        }

        if tag_content.ends_with('/') {
            continue;
        }

        let tag_name = tag_content.split_whitespace().next().unwrap_or("").to_ascii_lowercase();

        if has_class(tag_content, "ocr_line") || has_class(tag_content, "ocrx_line") {
            if in_line && !current_line.words.is_empty() {
                lines.push(std::mem::take(&mut current_line));
            }
            in_line = true;
            let title = extract_title_attr(tag_content);
            let props = parse_title_properties(&title);
            current_line.x_size = props.x_size;
            current_line.x_ascenders = props.x_ascenders;
            current_line.x_descenders = props.x_descenders;
            current_line.baseline = props.baseline;
            if tag_name == par_tag {
                depth += 1;
            }
            continue;
        }

        if has_class(tag_content, "ocrx_word") {
            let title = extract_title_attr(tag_content);
            let props = parse_title_properties(&title);

            let word_text = extract_inner_text(html, pos);
            let trimmed = decode_html_entities(&word_text);
            let trimmed = trimmed.trim();

            pos = skip_to_matching_close(html, pos, &tag_name);

            if !trimmed.is_empty() {
                let (x0, y0, x1, y1) = props.bbox.unwrap_or((0, 0, 0, 0));
                current_line.words.push(HocrWordInfo {
                    text: trimmed.to_string(),
                    x0,
                    y0,
                    x1,
                    y1,
                    confidence: props.x_wconf,
                    font_size: props.x_fsize,
                    text_angle: props.textangle,
                    font_name: props.x_font,
                    is_bold: props.x_bold,
                    is_italic: props.x_italic,
                });
            }
            continue;
        }

        if tag_name == par_tag {
            depth += 1;
        }
    }

    let mut removed_line_count = 0usize;
    if let Some(filter) = dictionary_filter {
        let lines_before = lines.len();
        lines.retain(|line| !is_dictionary_noise_line(line, filter));
        removed_line_count = lines_before - lines.len();
        if removed_line_count > 0 {
            tracing::debug!(
                page,
                removed_line_count,
                max_invalid_ratio = filter.max_invalid_ratio,
                "removed OCR line(s) whose dictionary-checkable words are mostly not real words"
            );
        }
    }

    let all_words: Vec<&HocrWordInfo> = lines.iter().flat_map(|l| l.words.iter()).collect();
    if all_words.is_empty() {
        return (None, pos, removed_line_count);
    }

    let style = aggregate_word_style(&all_words);

    let text: String = lines
        .iter()
        .map(|line| line.words.iter().map(|w| w.text.as_str()).collect::<Vec<_>>().join(" "))
        .collect::<Vec<_>>()
        .join("\n");

    let mut min_x0 = u32::MAX;
    let mut min_y0 = u32::MAX;
    let mut max_x1 = 0u32;
    let mut max_y1 = 0u32;
    let mut conf_sum = 0.0f64;
    let mut conf_count = 0u32;
    let mut font_size_sum = 0u32;
    let mut font_size_count = 0u32;
    let mut angle_sum = 0.0f64;
    let mut angle_count = 0u32;

    for word in &all_words {
        if word.x1 > 0 || word.y1 > 0 {
            min_x0 = min_x0.min(word.x0);
            min_y0 = min_y0.min(word.y0);
            max_x1 = max_x1.max(word.x1);
            max_y1 = max_y1.max(word.y1);
        }
        if let Some(c) = word.confidence {
            conf_sum += c;
            conf_count += 1;
            retained_word_confidence_stats.record(c);
        }
        if let Some(fs) = word.font_size {
            font_size_sum += fs;
            font_size_count += 1;
        }
        if let Some(angle) = word.text_angle {
            angle_sum += angle;
            angle_count += 1;
        }
    }

    let mut x_size_sum = 0.0f64;
    let mut x_size_count = 0u32;
    let mut x_ascenders_sum = 0.0f64;
    let mut x_ascenders_count = 0u32;
    let mut x_descenders_sum = 0.0f64;
    let mut x_descenders_count = 0u32;
    let mut baseline_slope_sum = 0.0f64;
    let mut baseline_const_sum = 0.0f64;
    let mut baseline_count = 0u32;

    for line in &lines {
        if let Some(x_size) = line.x_size {
            x_size_sum += x_size;
            x_size_count += 1;
        }
        if let Some(ascenders) = line.x_ascenders {
            x_ascenders_sum += ascenders;
            x_ascenders_count += 1;
        }
        if let Some(descenders) = line.x_descenders {
            x_descenders_sum += descenders;
            x_descenders_count += 1;
        }
        if let Some((slope, constant)) = line.baseline {
            baseline_slope_sum += slope;
            baseline_const_sum += f64::from(constant);
            baseline_count += 1;
        }
    }

    // Per-line font size / x-height, aligned to the `\n`-separated lines of
    // `text` above, so a downstream consumer can recover line-level detail
    // instead of only the paragraph mean (#667, #669).
    let line_font_sizes: Vec<Option<f64>> = lines
        .iter()
        .map(|line| {
            let sizes: Vec<f64> = line.words.iter().filter_map(|w| w.font_size).map(f64::from).collect();
            if sizes.is_empty() {
                None
            } else {
                Some(sizes.iter().sum::<f64>() / sizes.len() as f64)
            }
        })
        .collect();
    let line_x_heights: Vec<Option<f64>> = lines.iter().map(|line| line.x_size).collect();
    let any_line_font_size = line_font_sizes.iter().any(Option::is_some);
    let any_line_x_height = line_x_heights.iter().any(Option::is_some);

    let has_valid_bbox = max_x1 > 0 || max_y1 > 0;

    let bbox = if has_valid_bbox {
        Some(BoundingBox {
            x0: min_x0 as f64,
            y0: min_y0 as f64,
            x1: max_x1 as f64,
            y1: max_y1 as f64,
        })
    } else {
        None
    };

    let ocr_geometry = if has_valid_bbox {
        Some(OcrBoundingGeometry::Rectangle {
            left: min_x0,
            top: min_y0,
            width: max_x1.saturating_sub(min_x0),
            height: max_y1.saturating_sub(min_y0),
        })
    } else {
        None
    };

    let ocr_confidence = if conf_count > 0 {
        #[cfg(feature = "ocr")]
        {
            Some(OcrConfidence::from_tesseract(conf_sum / conf_count as f64))
        }
        #[cfg(not(feature = "ocr"))]
        {
            Some(OcrConfidence {
                recognition: (conf_sum / conf_count as f64) / 100.0,
                detection: None,
            })
        }
    } else {
        None
    };

    let kind = ElementKind::OcrText {
        level: OcrElementLevel::Block,
    };

    let mut elem = InternalElement::text(kind, text, 0)
        .with_page(page)
        .with_index(element_index);

    elem.bbox = bbox;
    elem.ocr_geometry = ocr_geometry;
    elem.ocr_confidence = ocr_confidence;

    if font_size_count > 0 {
        let avg_font_size = font_size_sum as f64 / font_size_count as f64;
        elem.attributes
            .get_or_insert_with(Default::default)
            .insert(HOCR_FONT_SIZE_ATTRIBUTE.to_string(), avg_font_size.to_string());
    }
    if angle_count > 0 {
        let avg_angle = angle_sum / angle_count as f64;
        if avg_angle.abs() > 0.0 {
            elem.attributes
                .get_or_insert_with(Default::default)
                .insert(HOCR_TEXT_ANGLE_ATTRIBUTE.to_string(), avg_angle.to_string());
        }
    }
    if x_size_count > 0 {
        let avg_x_size = x_size_sum / f64::from(x_size_count);
        elem.attributes
            .get_or_insert_with(Default::default)
            .insert(HOCR_X_HEIGHT_ATTRIBUTE.to_string(), avg_x_size.to_string());
    }
    if x_ascenders_count > 0 {
        let avg_ascenders = x_ascenders_sum / f64::from(x_ascenders_count);
        elem.attributes
            .get_or_insert_with(Default::default)
            .insert(HOCR_X_ASCENDERS_ATTRIBUTE.to_string(), avg_ascenders.to_string());
    }
    if x_descenders_count > 0 {
        let avg_descenders = x_descenders_sum / f64::from(x_descenders_count);
        elem.attributes
            .get_or_insert_with(Default::default)
            .insert(HOCR_X_DESCENDERS_ATTRIBUTE.to_string(), avg_descenders.to_string());
    }
    if baseline_count > 0 {
        let avg_slope = baseline_slope_sum / f64::from(baseline_count);
        let avg_const = baseline_const_sum / f64::from(baseline_count);
        let attrs = elem.attributes.get_or_insert_with(Default::default);
        attrs.insert(HOCR_BASELINE_SLOPE_ATTRIBUTE.to_string(), avg_slope.to_string());
        attrs.insert(HOCR_BASELINE_CONST_ATTRIBUTE.to_string(), avg_const.to_string());
    }
    if any_line_font_size {
        elem.attributes.get_or_insert_with(Default::default).insert(
            HOCR_LINE_FONT_SIZES_ATTRIBUTE.to_string(),
            join_per_line_values(&line_font_sizes),
        );
    }
    if any_line_x_height {
        elem.attributes.get_or_insert_with(Default::default).insert(
            HOCR_LINE_X_HEIGHTS_ATTRIBUTE.to_string(),
            join_per_line_values(&line_x_heights),
        );
    }
    {
        let attrs = elem.attributes.get_or_insert_with(Default::default);
        attrs.insert(
            HOCR_BOLD_FRACTION_ATTRIBUTE.to_string(),
            style.bold_fraction.to_string(),
        );
        attrs.insert(
            HOCR_ITALIC_FRACTION_ATTRIBUTE.to_string(),
            style.italic_fraction.to_string(),
        );
        if let Some(font_name) = style.dominant_font_name {
            attrs.insert(HOCR_FONT_NAME_ATTRIBUTE.to_string(), font_name);
        }
    }

    (Some(elem), pos, removed_line_count)
}

/// Check if a tag's class attribute contains the given class name.
fn has_class(tag_content: &str, cls: &str) -> bool {
    if let Some(class_start) = tag_content.find("class=") {
        let rest = &tag_content[class_start + 6..];
        // `rest` is empty when `class=` is the last thing in `tag_content` (a
        // truncated or malformed tag). `.first()` (not `.unwrap_or(..)` on the
        // whole byte) is required here: defaulting a missing byte to `b'"'`
        // would make the `quote` check below pass on an empty `rest`, and the
        // following `&rest[1..]` then panics slicing byte index 1 out of a
        // 0-length string.
        if let Some(quote) = rest.as_bytes().first().copied()
            && (quote == b'"' || quote == b'\'')
        {
            let inner = &rest[1..];
            if let Some(end) = inner.find(quote as char) {
                let class_value = &inner[..end];
                return class_value.split_whitespace().any(|c| c == cls);
            }
        }
    }
    false
}

/// Check if tag content opens a paragraph element (`<p class="ocr_par">` or
/// `<span class="ocr_par">` etc.).
fn is_paragraph_tag(tag_content: &str) -> bool {
    has_class(tag_content, "ocr_par")
}

/// Extract the `title="..."` attribute value from raw tag content.
fn extract_title_attr(tag_content: &str) -> String {
    extract_attribute(tag_content, "title").unwrap_or_default()
}

/// Extract a quoted attribute value from raw tag content.
fn extract_attribute(tag_content: &str, attribute: &str) -> Option<String> {
    let marker = format!("{attribute}=");
    if let Some(attribute_start) = tag_content.find(&marker) {
        let rest = &tag_content[attribute_start + marker.len()..];
        // See the matching comment in `has_class`: `rest` can be empty when the
        // attribute marker is the last thing in `tag_content`, and defaulting a
        // missing byte to a quote char would make `&rest[1..]` panic below.
        if let Some(quote) = rest.as_bytes().first().copied()
            && (quote == b'"' || quote == b'\'')
        {
            let inner = &rest[1..];
            if let Some(end) = inner.find(quote as char) {
                return Some(inner[..end].to_string());
            }
        }
    }
    None
}

/// Extract all text content inside an element, stripping nested tags.
///
/// Walks from `pos` collecting text nodes and descending into nested tags
/// until the matching close tag for the current element is reached.
fn extract_inner_text(html: &str, start: usize) -> String {
    let bytes = html.as_bytes();
    let mut result = String::new();
    let mut pos = start;
    let mut depth: u32 = 1;

    while pos < bytes.len() && depth > 0 {
        if let Some(lt) = memchr(b'<', &bytes[pos..]).map(|i| pos + i) {
            result.push_str(&html[pos..lt]);

            if let Some(gt) = memchr(b'>', &bytes[lt..]).map(|i| lt + i) {
                let tag = &html[lt + 1..gt];
                if tag.starts_with('/') {
                    depth -= 1;
                } else if !tag.ends_with('/') {
                    depth += 1;
                }
                pos = gt + 1;
            } else {
                break;
            }
        } else {
            result.push_str(&html[pos..]);
            break;
        }
    }

    result
}

/// Skip past the matching closing tag for a tag that was just opened.
///
/// `tag_name` is the lowercase name of the opening tag (e.g. "span").
/// Returns the byte position after the closing `>`.
fn skip_to_matching_close(html: &str, start: usize, tag_name: &str) -> usize {
    let bytes = html.as_bytes();
    let mut pos = start;
    let mut depth: u32 = 1;

    while pos < bytes.len() && depth > 0 {
        let Some(lt) = memchr(b'<', &bytes[pos..]).map(|i| pos + i) else {
            break;
        };
        let Some(gt) = memchr(b'>', &bytes[lt..]).map(|i| lt + i) else {
            break;
        };
        let tag = &html[lt + 1..gt];

        if let Some(stripped) = tag.strip_prefix('/') {
            let name = stripped.split_whitespace().next().unwrap_or("");
            if name.eq_ignore_ascii_case(tag_name) {
                depth -= 1;
            }
        } else if !tag.ends_with('/') {
            let name = tag.split_whitespace().next().unwrap_or("");
            if name.eq_ignore_ascii_case(tag_name) {
                depth += 1;
            }
        }

        pos = gt + 1;
    }

    pos
}

/// Decode common HTML entities in text content.
fn decode_html_entities(text: &str) -> String {
    if !text.contains('&') {
        return text.to_string();
    }
    text.replace("&amp;", "&")
        .replace("&lt;", "<")
        .replace("&gt;", ">")
        .replace("&quot;", "\"")
        .replace("&#39;", "'")
        .replace("&apos;", "'")
        .replace("&#x27;", "'")
        .replace("&nbsp;", " ")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_empty_hocr() {
        let doc = parse_hocr_to_internal_document("");
        assert!(doc.elements.is_empty());
    }

    #[test]
    fn test_single_page_single_paragraph() {
        let hocr = r#"<div class="ocr_page" title="bbox 0 0 1000 1500; ppageno 0">
            <p class="ocr_par" title="bbox 100 100 900 200">
                <span class="ocr_line" title="bbox 100 100 900 150">
                    <span class="ocrx_word" title="bbox 100 100 200 140; x_wconf 95">Hello</span>
                    <span class="ocrx_word" title="bbox 210 100 350 140; x_wconf 90">World</span>
                </span>
            </p>
        </div>"#;

        let doc = parse_hocr_to_internal_document(hocr);
        let elements = doc.elements;

        assert_eq!(elements.len(), 1);

        let elem = &elements[0];
        assert_eq!(elem.text, "Hello World");
        assert_eq!(elem.page, Some(1));

        let bbox = elem.bbox.as_ref().unwrap();
        assert_eq!(bbox.x0, 100.0);
        assert_eq!(bbox.y0, 100.0);
        assert_eq!(bbox.x1, 350.0);
        assert_eq!(bbox.y1, 140.0);

        let conf = elem.ocr_confidence.as_ref().unwrap();
        assert!((conf.recognition - 0.925).abs() < 0.01);
    }

    /// Regression test: Tesseract numbers every single-image `recognize()` call's hOCR page
    /// as `ppageno 0`, since each `perform_ocr` call only ever loads one image. When that
    /// image is page 2 of a larger document, the parser must report the caller-supplied true
    /// page number rather than the ppageno-derived `1` every single-image hOCR call would
    /// otherwise produce for every page of the document.
    ///
    /// Fails against unfixed code: before `parse_hocr_to_internal_document_with_page_offset`
    /// existed, this exact hOCR (`ppageno 0`, identical to what Tesseract emits for page 2 of
    /// a document, page 5, or any other page) could only be parsed by
    /// `parse_hocr_to_internal_document`/`_with_dictionary_filter`, both of which hardcode the
    /// offset to `1` -- so every page of a multi-page source would assert `elem.page ==
    /// Some(1)`, never the true page number.
    #[test]
    fn should_report_the_true_page_number_for_each_ocr_element() {
        let hocr = r#"<div class="ocr_page" title="bbox 0 0 1000 1500; ppageno 0">
            <p class="ocr_par" title="bbox 100 100 900 200">
                <span class="ocr_line" title="bbox 100 100 900 150">
                    <span class="ocrx_word" title="bbox 100 100 200 140; x_wconf 95">Hello</span>
                    <span class="ocrx_word" title="bbox 210 100 350 140; x_wconf 90">World</span>
                </span>
            </p>
        </div>"#;

        // `page_offset: 2` stands in for `TesseractConfig::page_number` when `perform_ocr` is
        // called on page 2 of a multi-page document.
        let doc = parse_hocr_to_internal_document_with_page_offset(hocr, None, 2);
        let elements = doc.elements;

        assert_eq!(elements.len(), 1);
        let elem = &elements[0];
        assert_eq!(elem.text, "Hello World");
        assert_eq!(elem.page, Some(2));
    }

    #[test]
    fn test_multi_line_paragraph() {
        let hocr = r#"<div class="ocr_page" title="ppageno 0">
            <p class="ocr_par">
                <span class="ocr_line" title="bbox 10 10 200 30">
                    <span class="ocrx_word" title="bbox 10 10 50 30">Line</span>
                    <span class="ocrx_word" title="bbox 60 10 100 30">one</span>
                </span>
                <span class="ocr_line" title="bbox 10 40 200 60">
                    <span class="ocrx_word" title="bbox 10 40 50 60">Line</span>
                    <span class="ocrx_word" title="bbox 60 40 100 60">two</span>
                </span>
            </p>
        </div>"#;

        let doc = parse_hocr_to_internal_document(hocr);
        let elements = doc.elements;
        assert_eq!(elements.len(), 1);
        assert_eq!(elements[0].text, "Line one\nLine two");
    }

    #[test]
    fn test_multi_page_inserts_page_breaks() {
        let hocr = r#"
        <div class="ocr_page" title="ppageno 0">
            <p class="ocr_par">
                <span class="ocrx_word" title="bbox 10 10 50 30">Page1</span>
            </p>
        </div>
        <div class="ocr_page" title="ppageno 1">
            <p class="ocr_par">
                <span class="ocrx_word" title="bbox 10 10 50 30">Page2</span>
            </p>
        </div>"#;

        let doc = parse_hocr_to_internal_document(hocr);
        let elements = doc.elements;

        assert_eq!(elements.len(), 3);
        assert!(matches!(elements[0].kind, ElementKind::OcrText { .. }));
        assert!(matches!(elements[1].kind, ElementKind::PageBreak));
        assert!(matches!(elements[2].kind, ElementKind::OcrText { .. }));
        assert_eq!(elements[0].page, Some(1));
        assert_eq!(elements[2].page, Some(2));
    }

    #[test]
    fn test_html_entity_decoding() {
        let hocr = r#"<div class="ocr_page" title="ppageno 0">
            <p class="ocr_par">
                <span class="ocrx_word" title="bbox 10 10 50 30">&amp;foo&lt;bar&gt;</span>
            </p>
        </div>"#;

        let doc = parse_hocr_to_internal_document(hocr);
        assert_eq!(doc.elements[0].text, "&foo<bar>");
    }

    #[test]
    fn test_words_without_bbox_still_included() {
        let hocr = r#"<div class="ocr_page" title="ppageno 0">
            <p class="ocr_par">
                <span class="ocrx_word">NoBbox</span>
            </p>
        </div>"#;

        let doc = parse_hocr_to_internal_document(hocr);
        assert_eq!(doc.elements.len(), 1);
        assert_eq!(doc.elements[0].text, "NoBbox");
        assert!(doc.elements[0].bbox.is_none());
    }

    #[test]
    fn test_nested_formatting_tags() {
        let hocr = r#"<div class="ocr_page" title="ppageno 0">
            <p class="ocr_par">
                <span class="ocrx_word" title="bbox 10 10 50 30"><strong>Bold</strong></span>
                <span class="ocrx_word" title="bbox 60 10 100 30"><em>Italic</em></span>
            </p>
        </div>"#;

        let doc = parse_hocr_to_internal_document(hocr);
        assert_eq!(doc.elements[0].text, "Bold Italic");
    }

    #[test]
    fn test_property_parsing() {
        let props = parse_title_properties("bbox 100 50 200 150; x_wconf 95.5; ppageno 3; textangle 7.2");
        assert_eq!(props.bbox, Some((100, 50, 200, 150)));
        assert_eq!(props.x_wconf, Some(95.5));
        assert_eq!(props.ppageno, Some(3));
        assert_eq!(props.textangle, Some(7.2));
    }

    #[test]
    fn test_baseline_parsing() {
        let props = parse_title_properties("baseline 0.015 -18");
        assert_eq!(props.baseline, Some((0.015, -18)));
    }

    #[test]
    fn test_font_parsing() {
        let props = parse_title_properties("x_font \"Comic Sans MS\"; x_fsize 12");
        assert_eq!(props.x_font, Some("Comic Sans MS".to_string()));
        assert_eq!(props.x_fsize, Some(12));
    }

    #[test]
    fn test_bold_and_italic_flag_parsing() {
        let props = parse_title_properties("x_wconf 95; x_bold; x_italic");
        assert!(props.x_bold);
        assert!(props.x_italic);
    }

    #[test]
    fn test_bold_and_italic_default_to_false_when_absent() {
        let props = parse_title_properties("x_wconf 95");
        assert!(!props.x_bold);
        assert!(!props.x_italic);
    }

    #[test]
    fn test_has_class() {
        assert!(has_class(
            r#"div class="ocr_page" title="bbox 0 0 100 100""#,
            "ocr_page"
        ));
        assert!(!has_class(r#"div class="ocr_page""#, "ocr_par"));
        assert!(has_class(r#"span class="ocrx_word ocr_line""#, "ocrx_word"));
        assert!(has_class(r#"span class="ocrx_word ocr_line""#, "ocr_line"));
    }

    /// A tag whose `class=` marker is the very last thing in `tag_content` (no
    /// quote, no value, nothing after it — e.g. produced by truncated or
    /// malformed hOCR markup) used to panic: `rest` became an empty string,
    /// `rest.as_bytes().first().copied().unwrap_or(b'"')` masked the empty
    /// case by defaulting to a quote byte, and the following `&rest[1..]`
    /// then sliced byte index 1 out of a 0-length string ("byte index 1 is
    /// out of bounds of ``"). Must return `false`, not panic.
    #[test]
    fn has_class_returns_false_instead_of_panicking_when_class_marker_is_truncated() {
        assert!(!has_class("span class=", "ocr_par"));
    }

    #[test]
    fn test_extract_title_attr() {
        let title = extract_title_attr(r#"div class="ocr_page" title="bbox 0 0 100 200; ppageno 0""#);
        assert_eq!(title, "bbox 0 0 100 200; ppageno 0");
    }

    /// Same truncated-marker defect as `has_class`, exercised through
    /// `extract_attribute`/`extract_title_attr`: a tag content ending in
    /// `title=` with nothing after it must not panic.
    #[test]
    fn extract_title_attr_returns_empty_instead_of_panicking_when_title_marker_is_truncated() {
        assert_eq!(extract_title_attr("span title="), "");
    }

    #[test]
    fn test_paragraph_stores_average_font_size_attribute() {
        let hocr = r#"<div class="ocr_page" title="ppageno 0">
            <p class="ocr_par">
                <span class="ocr_line">
                    <span class="ocrx_word" title="bbox 10 10 50 30; x_wconf 90; x_fsize 24">BIG</span>
                    <span class="ocrx_word" title="bbox 60 10 100 30; x_wconf 90; x_fsize 20">Title</span>
                </span>
            </p>
        </div>"#;

        let doc = parse_hocr_to_internal_document(hocr);
        let attrs = doc.elements[0].attributes.as_ref().expect("attributes present");
        assert_eq!(attrs.get(HOCR_FONT_SIZE_ATTRIBUTE), Some(&"22".to_string()));
    }

    #[test]
    fn test_paragraph_stores_bold_italic_fraction_and_font_name_attributes() {
        // Two bold words out of four total ("HEADING" split into two spans),
        // one italic, and a single reported font family.
        let hocr = r#"<div class='ocr_page' title='ppageno 0'>
            <p class='ocr_par'>
                <span class='ocr_line'>
                    <span class='ocrx_word' title='bbox 10 10 50 30; x_wconf 90; x_font "Arial"; x_bold'>HEAD</span>
                    <span class='ocrx_word' title='bbox 60 10 100 30; x_wconf 90; x_font "Arial"; x_bold'>ING</span>
                    <span class='ocrx_word' title='bbox 110 10 150 30; x_wconf 90; x_font "Arial"; x_italic'>plain</span>
                    <span class='ocrx_word' title='bbox 160 10 200 30; x_wconf 90; x_font "Arial"'>text</span>
                </span>
            </p>
        </div>"#;

        let doc = parse_hocr_to_internal_document(hocr);
        let attrs = doc.elements[0].attributes.as_ref().expect("attributes present");

        // Without the fix, `HOCR_BOLD_FRACTION_ATTRIBUTE`/`HOCR_ITALIC_FRACTION_ATTRIBUTE`
        // are never inserted (parse_paragraph has no bold/italic aggregation), so this
        // lookup returns None and the assert_eq fails against `Some("0.5")`.
        assert_eq!(attrs.get(HOCR_BOLD_FRACTION_ATTRIBUTE), Some(&"0.5".to_string()));
        assert_eq!(attrs.get(HOCR_ITALIC_FRACTION_ATTRIBUTE), Some(&"0.25".to_string()));
        assert_eq!(attrs.get(HOCR_FONT_NAME_ATTRIBUTE), Some(&"Arial".to_string()));
    }

    #[test]
    fn test_paragraph_all_words_non_bold_reports_zero_bold_fraction() {
        let hocr = r#"<div class="ocr_page" title="ppageno 0">
            <p class="ocr_par">
                <span class="ocrx_word" title="bbox 10 10 50 30; x_wconf 90">plain</span>
            </p>
        </div>"#;

        let doc = parse_hocr_to_internal_document(hocr);
        let attrs = doc.elements[0].attributes.as_ref().expect("attributes present");

        assert_eq!(attrs.get(HOCR_BOLD_FRACTION_ATTRIBUTE), Some(&"0".to_string()));
        assert_eq!(attrs.get(HOCR_ITALIC_FRACTION_ATTRIBUTE), Some(&"0".to_string()));
        assert_eq!(attrs.get(HOCR_FONT_NAME_ATTRIBUTE), None);
    }

    #[test]
    fn test_paragraph_without_font_size_has_no_attribute() {
        let hocr = r#"<div class="ocr_page" title="ppageno 0">
            <p class="ocr_par">
                <span class="ocrx_word" title="bbox 10 10 50 30; x_wconf 90">NoFontSize</span>
            </p>
        </div>"#;

        let doc = parse_hocr_to_internal_document(hocr);
        let has_font_size = doc.elements[0]
            .attributes
            .as_ref()
            .is_some_and(|attrs| attrs.contains_key(HOCR_FONT_SIZE_ATTRIBUTE));
        assert!(
            !has_font_size,
            "should not synthesize a font size when hOCR provides none"
        );
    }

    #[test]
    fn test_paragraph_stores_average_text_angle_attribute() {
        let hocr = r#"<div class="ocr_page" title="ppageno 0">
            <p class="ocr_par">
                <span class="ocr_line">
                    <span class="ocrx_word" title="bbox 10 10 50 30; x_wconf 90; textangle 90">Rotated</span>
                </span>
            </p>
        </div>"#;

        let doc = parse_hocr_to_internal_document(hocr);
        let attrs = doc.elements[0].attributes.as_ref().expect("attributes present");
        assert_eq!(attrs.get(HOCR_TEXT_ANGLE_ATTRIBUTE), Some(&"90".to_string()));
    }

    #[test]
    fn test_ocr_geometry_set() {
        let hocr = r#"<div class="ocr_page" title="ppageno 0">
            <p class="ocr_par">
                <span class="ocrx_word" title="bbox 50 60 150 100; x_wconf 88">test</span>
            </p>
        </div>"#;

        let doc = parse_hocr_to_internal_document(hocr);
        let elem = &doc.elements[0];
        let geom = elem.ocr_geometry.as_ref().unwrap();
        match geom {
            OcrBoundingGeometry::Rectangle {
                left,
                top,
                width,
                height,
            } => {
                assert_eq!(left, &50);
                assert_eq!(top, &60);
                assert_eq!(width, &100);
                assert_eq!(height, &40);
            }
            _ => panic!("Expected Rectangle geometry"),
        }
    }

    #[test]
    fn test_english_pdf_real_data() {
        let hocr = include_str!("../../test_data/hocr/english_pdf_default.hocr");
        let doc = parse_hocr_to_internal_document(hocr);
        assert!(
            !doc.elements.is_empty(),
            "Should extract elements from English PDF hOCR"
        );
        let total_text: String = doc
            .elements
            .iter()
            .map(|e| e.text.as_str())
            .collect::<Vec<_>>()
            .join(" ");
        assert!(!total_text.trim().is_empty(), "Should have non-empty text");
        let has_pages = doc.elements.iter().any(|e| e.page.is_some());
        assert!(has_pages, "Should have page numbers");
    }

    #[test]
    fn test_german_pdf_real_data() {
        let hocr = include_str!("../../test_data/hocr/german_pdf_default.hocr");
        let doc = parse_hocr_to_internal_document(hocr);
        assert!(!doc.elements.is_empty(), "Should extract elements from German PDF hOCR");
        let total_text: String = doc
            .elements
            .iter()
            .map(|e| e.text.as_str())
            .collect::<Vec<_>>()
            .join(" ");
        assert!(!total_text.trim().is_empty(), "Should have non-empty German text");
    }

    #[test]
    fn test_invoice_image_real_data() {
        let hocr = include_str!("../../test_data/hocr/invoice_image_default.hocr");
        let doc = parse_hocr_to_internal_document(hocr);
        assert!(!doc.elements.is_empty(), "Should extract elements from invoice hOCR");
        let total_text: String = doc
            .elements
            .iter()
            .map(|e| e.text.as_str())
            .collect::<Vec<_>>()
            .join(" ");
        assert!(
            total_text.chars().any(|c| c.is_ascii_digit()),
            "Invoice should contain numbers"
        );
    }

    #[test]
    fn test_word_confidence_real_data() {
        let hocr = include_str!("../../test_data/hocr/word_confidence.hocr");
        let doc = parse_hocr_to_internal_document(hocr);
        assert!(
            doc.elements.is_empty(),
            "Non-hOCR-classed elements should not be extracted"
        );
    }

    #[test]
    fn test_utf8_encoding_real_data() {
        let hocr = include_str!("../../test_data/hocr/utf8_encoding.hocr");
        let doc = parse_hocr_to_internal_document(hocr);
        assert!(
            doc.elements.is_empty(),
            "Non-hOCR-classed UTF-8 content should not be extracted"
        );
    }

    #[test]
    fn test_v4_with_tables_and_code() {
        let hocr = include_str!("../../test_data/hocr/v4_code_formula.hocr");
        let doc = parse_hocr_to_internal_document(hocr);
        assert!(
            !doc.elements.is_empty(),
            "Should extract from v4 hOCR with code/formula"
        );
    }

    #[test]
    fn test_v4_embedded_tables() {
        let hocr = include_str!("../../test_data/hocr/v4_embedded_tables.hocr");
        let doc = parse_hocr_to_internal_document(hocr);
        assert!(
            !doc.elements.is_empty(),
            "Should extract from v4 hOCR with embedded tables"
        );
    }

    #[test]
    fn test_many_paragraphs_all_captured() {
        let paragraph_texts: Vec<&str> = vec![
            "First paragraph",
            "Second paragraph",
            "Third paragraph",
            "Fourth paragraph",
            "Fifth paragraph",
            "Sixth paragraph",
            "Seventh paragraph",
            "Eighth paragraph",
            "Ninth paragraph",
            "Tenth paragraph",
            "Eleventh paragraph",
            "Twelfth paragraph",
            "Thirteenth paragraph",
            "Fourteenth paragraph",
            "Fifteenth paragraph",
            "Sixteenth paragraph",
            "Seventeenth paragraph",
            "Eighteenth paragraph",
            "Nineteenth paragraph",
            "Twentieth paragraph",
            "Twenty-first paragraph",
            "Twenty-second paragraph",
            "Twenty-third paragraph",
            "Twenty-fourth paragraph",
            "Twenty-fifth paragraph",
            "Service category alpha",
            "Service category beta",
            "Service category gamma",
            "Service category delta",
            "All other categories",
            "Items provided by client",
            "*** Note this is the last paragraph",
        ];

        let mut hocr = String::from(
            r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 <head>
  <title></title>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
  <meta name='ocr-system' content='tesseract 5.5.1' />
 </head>
 <body>
  <div class='ocr_page' id='page_1' title='image "test.png"; bbox 0 0 2550 3300; ppageno 0; scan_res 300 300'>
"#,
        );

        let mut y = 100;
        for (i, text) in paragraph_texts.iter().enumerate() {
            let block_id = i + 1;
            let par_id = i + 1;
            let line_id = i + 1;
            let y0 = y;
            let y1 = y + 30;

            hocr.push_str(&format!(
                r#"   <div class='ocr_carea' id='block_1_{block_id}' title="bbox 100 {y0} 2400 {y1}">
    <p class='ocr_par' id='par_1_{par_id}' lang='eng' title="bbox 100 {y0} 2400 {y1}">
     <span class='ocr_line' id='line_1_{line_id}' title="bbox 100 {y0} 2400 {y1}; baseline 0 0; x_size 30; x_descenders 6; x_ascenders 8">
"#
            ));

            let mut wx = 100;
            for (wi, word) in text.split_whitespace().enumerate() {
                let word_id = i * 10 + wi + 1;
                let wx1 = wx + word.len() as u32 * 20;
                hocr.push_str(&format!(
                    "      <span class='ocrx_word' id='word_1_{word_id}' title='bbox {wx} {y0} {wx1} {y1}; x_wconf 90'>{word}</span>\n"
                ));
                wx = wx1 + 10;
            }

            hocr.push_str("     </span>\n    </p>\n   </div>\n");

            y = y1 + 10;
        }

        hocr.push_str("  </div>\n </body>\n</html>\n");

        let doc = parse_hocr_to_internal_document(&hocr);

        let text_elements: Vec<_> = doc
            .elements
            .iter()
            .filter(|e| matches!(e.kind, ElementKind::OcrText { .. }))
            .collect();

        assert_eq!(
            text_elements.len(),
            paragraph_texts.len(),
            "Expected {} paragraphs but got {}. Missing paragraphs from the end.",
            paragraph_texts.len(),
            text_elements.len()
        );

        for (i, (elem, expected)) in text_elements.iter().zip(paragraph_texts.iter()).enumerate() {
            assert_eq!(
                elem.text,
                *expected,
                "Paragraph {} mismatch: expected '{}', got '{}'",
                i + 1,
                expected,
                elem.text
            );
        }

        let last_text = &text_elements.last().unwrap().text;
        assert_eq!(
            last_text, "*** Note this is the last paragraph",
            "Last paragraph should be captured"
        );
    }

    #[test]
    fn test_paragraph_with_nested_span_in_word() {
        let hocr = r#"<div class="ocr_page" title="ppageno 0">
  <div class="ocr_carea">
    <p class="ocr_par">
      <span class="ocr_line">
        <span class="ocrx_word" title="bbox 10 10 50 30; x_wconf 90"><span class="ocrx_font" style="font-size:12px">Hello</span></span>
        <span class="ocrx_word" title="bbox 60 10 100 30; x_wconf 90">World</span>
      </span>
    </p>
  </div>
  <div class="ocr_carea">
    <p class="ocr_par">
      <span class="ocr_line">
        <span class="ocrx_word" title="bbox 10 50 80 70; x_wconf 90">Second</span>
        <span class="ocrx_word" title="bbox 90 50 180 70; x_wconf 90">paragraph</span>
      </span>
    </p>
  </div>
  <div class="ocr_carea">
    <p class="ocr_par">
      <span class="ocr_line">
        <span class="ocrx_word" title="bbox 10 90 80 110; x_wconf 90">Third</span>
        <span class="ocrx_word" title="bbox 90 90 180 110; x_wconf 90">paragraph</span>
      </span>
    </p>
  </div>
</div>"#;

        let doc = parse_hocr_to_internal_document(hocr);
        let text_elements: Vec<_> = doc
            .elements
            .iter()
            .filter(|e| matches!(e.kind, ElementKind::OcrText { .. }))
            .collect();

        assert_eq!(text_elements.len(), 3, "Should capture all 3 paragraphs");
        assert_eq!(text_elements[0].text, "Hello World");
        assert_eq!(text_elements[1].text, "Second paragraph");
        assert_eq!(text_elements[2].text, "Third paragraph");
    }

    #[test]
    fn test_paragraph_with_words_outside_line() {
        let hocr = r#"<div class="ocr_page" title="ppageno 0">
  <div class="ocr_carea">
    <p class="ocr_par">
      <span class="ocrx_word" title="bbox 10 10 50 30; x_wconf 90">Direct</span>
      <span class="ocrx_word" title="bbox 60 10 120 30; x_wconf 90">words</span>
    </p>
  </div>
  <div class="ocr_carea">
    <p class="ocr_par">
      <span class="ocr_line">
        <span class="ocrx_word" title="bbox 10 50 80 70; x_wconf 90">Next</span>
        <span class="ocrx_word" title="bbox 90 50 160 70; x_wconf 90">paragraph</span>
      </span>
    </p>
  </div>
</div>"#;

        let doc = parse_hocr_to_internal_document(hocr);
        let text_elements: Vec<_> = doc
            .elements
            .iter()
            .filter(|e| matches!(e.kind, ElementKind::OcrText { .. }))
            .collect();

        assert_eq!(text_elements.len(), 2, "Should capture both paragraphs");
        assert_eq!(text_elements[0].text, "Direct words");
        assert_eq!(text_elements[1].text, "Next paragraph");
    }

    #[test]
    fn test_paragraph_depth_with_extra_div_nesting() {
        let hocr = r#"<div class="ocr_page" title="ppageno 0">
  <div class="ocr_carea">
    <p class="ocr_par">
      <div class="ocr_column">
        <span class="ocr_line">
          <span class="ocrx_word" title="bbox 10 10 50 30; x_wconf 90">Nested</span>
        </span>
      </div>
    </p>
  </div>
  <div class="ocr_carea">
    <p class="ocr_par">
      <span class="ocr_line">
        <span class="ocrx_word" title="bbox 10 50 80 70; x_wconf 90">After</span>
        <span class="ocrx_word" title="bbox 90 50 160 70; x_wconf 90">nested</span>
      </span>
    </p>
  </div>
</div>"#;

        let doc = parse_hocr_to_internal_document(hocr);
        let text_elements: Vec<_> = doc
            .elements
            .iter()
            .filter(|e| matches!(e.kind, ElementKind::OcrText { .. }))
            .collect();

        assert_eq!(
            text_elements.len(),
            2,
            "Should capture both paragraphs even with extra div nesting"
        );
        assert_eq!(text_elements[0].text, "Nested");
        assert_eq!(text_elements[1].text, "After nested");
    }

    #[test]
    fn test_paragraph_div_swallows_carea_close() {
        let hocr = r#"<div class="ocr_page" title="ppageno 0">
  <div class="ocr_carea">
    <div class="ocr_par">
      <span class="ocr_line">
        <span class="ocrx_word" title="bbox 10 10 50 30; x_wconf 90">First</span>
      </span>
    </div>
  </div>
  <div class="ocr_carea">
    <div class="ocr_par">
      <span class="ocr_line">
        <span class="ocrx_word" title="bbox 10 50 50 70; x_wconf 90">Second</span>
      </span>
    </div>
  </div>
  <div class="ocr_carea">
    <div class="ocr_par">
      <span class="ocr_line">
        <span class="ocrx_word" title="bbox 10 90 50 110; x_wconf 90">Third</span>
      </span>
    </div>
  </div>
</div>"#;

        let doc = parse_hocr_to_internal_document(hocr);
        let text_elements: Vec<_> = doc
            .elements
            .iter()
            .filter(|e| matches!(e.kind, ElementKind::OcrText { .. }))
            .collect();

        assert_eq!(text_elements.len(), 3, "Should capture all 3 div-based paragraphs");
    }

    #[test]
    fn test_paragraph_unclosed_par_div_steals_carea_close() {
        let hocr = r#"<div class="ocr_page" title="ppageno 0">
  <div class="ocr_carea">
    <div class="ocr_par">
      <span class="ocr_line">
        <span class="ocrx_word" title="bbox 10 10 50 30; x_wconf 90">First</span>
      </span>
  </div>
  <div class="ocr_carea">
    <div class="ocr_par">
      <span class="ocr_line">
        <span class="ocrx_word" title="bbox 10 50 50 70; x_wconf 90">Second</span>
      </span>
  </div>
</div>"#;

        let doc = parse_hocr_to_internal_document(hocr);
        let text_elements: Vec<_> = doc
            .elements
            .iter()
            .filter(|e| matches!(e.kind, ElementKind::OcrText { .. }))
            .collect();

        assert_eq!(
            text_elements.len(),
            2,
            "Should find both paragraphs even with unclosed par divs. Got: {:?}",
            text_elements.iter().map(|e| e.text.as_str()).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_depth_tracking_uses_paragraph_tag_name() {
        let hocr_separate = r#"<div class="ocr_page" title="ppageno 0">
  <div class="ocr_carea">
    <p class="ocr_par">
      <span class="ocr_line">
        <span class="ocrx_word" title="bbox 10 10 50 30; x_wconf 90"><span>Styled</span></span>
        <span class="ocrx_word" title="bbox 60 10 120 30; x_wconf 90">text</span>
      </span>
    </p>
  </div>
  <div class="ocr_carea">
    <p class="ocr_par">
      <span class="ocr_line">
        <span class="ocrx_word" title="bbox 10 50 80 70; x_wconf 90">After</span>
      </span>
    </p>
  </div>
</div>"#;

        let doc = parse_hocr_to_internal_document(hocr_separate);
        let text_elements: Vec<_> = doc
            .elements
            .iter()
            .filter(|e| matches!(e.kind, ElementKind::OcrText { .. }))
            .collect();
        assert_eq!(text_elements.len(), 2);
        assert_eq!(text_elements[0].text, "Styled text");
        assert_eq!(text_elements[1].text, "After");

        let hocr_same_carea = r#"<div class="ocr_page" title="ppageno 0">
  <div class="ocr_carea">
    <p class="ocr_par">
      <span class="ocr_line">
        <span class="ocrx_word" title="bbox 10 10 50 30; x_wconf 90"><span>Styled</span></span>
      </span>
    </p>
    <p class="ocr_par">
      <span class="ocr_line">
        <span class="ocrx_word" title="bbox 10 50 80 70; x_wconf 90">Should</span>
        <span class="ocrx_word" title="bbox 90 50 180 70; x_wconf 90">be</span>
        <span class="ocrx_word" title="bbox 190 50 280 70; x_wconf 90">separate</span>
      </span>
    </p>
  </div>
</div>"#;

        let doc = parse_hocr_to_internal_document(hocr_same_carea);
        let text_elements: Vec<_> = doc
            .elements
            .iter()
            .filter(|e| matches!(e.kind, ElementKind::OcrText { .. }))
            .collect();
        assert_eq!(
            text_elements.len(),
            2,
            "Should find both paragraphs separately. Got: {:?}",
            text_elements.iter().map(|e| e.text.as_str()).collect::<Vec<_>>()
        );
        assert_eq!(text_elements[0].text, "Styled");
        assert_eq!(text_elements[1].text, "Should be separate");
    }

    #[test]
    fn test_paragraphs_retain_enclosing_hocr_block_id() {
        let hocr = r#"<div class="ocr_page" title="ppageno 0">
  <div class="ocr_carea" id="block_1_1">
    <div class="nested"><p class="ocr_par"><span class="ocrx_word">First</span></p></div>
    <p class="ocr_par"><span class="ocrx_word">Second</span></p>
  </div>
  <div class="ocr_carea" id="block_1_2">
    <p class="ocr_par"><span class="ocrx_word">Third</span></p>
  </div>
</div>"#;

        let doc = parse_hocr_to_internal_document(hocr);
        let block_ids = doc
            .elements
            .iter()
            .filter(|element| matches!(element.kind, ElementKind::OcrText { .. }))
            .map(|element| {
                element
                    .attributes
                    .as_ref()
                    .and_then(|attributes| attributes.get(HOCR_BLOCK_ID_ATTRIBUTE))
                    .map(String::as_str)
            })
            .collect::<Vec<_>>();

        assert_eq!(block_ids, vec![Some("block_1_1"), Some("block_1_1"), Some("block_1_2")]);
    }

    #[test]
    fn test_paragraph_with_ocr_separator_between_paragraphs() {
        let hocr = r#"<div class="ocr_page" title="ppageno 0">
  <div class="ocr_carea">
    <p class="ocr_par">
      <span class="ocr_line">
        <span class="ocrx_word" title="bbox 10 10 50 30; x_wconf 90">Before</span>
      </span>
    </p>
  </div>
  <div class="ocr_separator" title="bbox 10 40 500 42"></div>
  <div class="ocr_carea">
    <p class="ocr_par">
      <span class="ocr_line">
        <span class="ocrx_word" title="bbox 10 50 50 70; x_wconf 90">After</span>
      </span>
    </p>
  </div>
</div>"#;

        let doc = parse_hocr_to_internal_document(hocr);
        let text_elements: Vec<_> = doc
            .elements
            .iter()
            .filter(|e| matches!(e.kind, ElementKind::OcrText { .. }))
            .collect();

        assert_eq!(
            text_elements.len(),
            2,
            "Should capture both paragraphs around separator"
        );
    }

    #[test]
    fn test_property_parsing_recovers_x_size_ascenders_descenders() {
        // Fails against unfixed code: `HocrProperties` had no `x_size` /
        // `x_ascenders` / `x_descenders` fields at all, so these keys parsed
        // to nothing regardless of what the title string contained.
        let props =
            parse_title_properties("bbox 100 40 900 150; baseline 0.015 -18; x_size 30; x_descenders 6; x_ascenders 8");
        assert_eq!(props.x_size, Some(30.0));
        assert_eq!(props.x_ascenders, Some(8.0));
        assert_eq!(props.x_descenders, Some(6.0));
        assert_eq!(props.baseline, Some((0.015, -18)));
    }

    #[test]
    fn test_ocr_line_title_parsed_into_paragraph_x_height_and_baseline_attributes() {
        // Fails against unfixed code: the `ocr_line`/`ocrx_line` branch only
        // flipped `in_line` and never called `parse_title_properties` on that
        // tag's own title, so `baseline`/`x_size`/`x_ascenders`/`x_descenders`
        // were unreachable even though Tesseract emits them on the line tag
        // (not the word tag).
        let hocr = r#"<div class="ocr_page" title="ppageno 0">
            <p class="ocr_par">
                <span class="ocr_line"
                    title="bbox 100 40 900 150; baseline 0.01 -18; x_size 30; x_ascenders 8; x_descenders 6">
                    <span class="ocrx_word" title="bbox 100 40 300 150; x_wconf 95">Heading</span>
                </span>
            </p>
        </div>"#;

        let doc = parse_hocr_to_internal_document(hocr);
        let attrs = doc.elements[0].attributes.as_ref().expect("attributes present");

        assert_eq!(attrs.get(HOCR_X_HEIGHT_ATTRIBUTE), Some(&"30".to_string()));
        assert_eq!(attrs.get(HOCR_X_ASCENDERS_ATTRIBUTE), Some(&"8".to_string()));
        assert_eq!(attrs.get(HOCR_X_DESCENDERS_ATTRIBUTE), Some(&"6".to_string()));
        assert_eq!(attrs.get(HOCR_BASELINE_SLOPE_ATTRIBUTE), Some(&"0.01".to_string()));
        assert_eq!(attrs.get(HOCR_BASELINE_CONST_ATTRIBUTE), Some(&"-18".to_string()));
    }

    #[test]
    fn test_paragraph_without_line_title_has_no_x_height_attributes() {
        let hocr = r#"<div class="ocr_page" title="ppageno 0">
            <p class="ocr_par">
                <span class="ocr_line">
                    <span class="ocrx_word" title="bbox 10 10 50 30; x_wconf 90">Plain</span>
                </span>
            </p>
        </div>"#;

        let doc = parse_hocr_to_internal_document(hocr);
        let has_x_height = doc.elements[0]
            .attributes
            .as_ref()
            .is_some_and(|attrs| attrs.contains_key(HOCR_X_HEIGHT_ATTRIBUTE));
        assert!(!has_x_height, "should not synthesize x-height when hOCR provides none");
    }

    #[test]
    fn test_multi_line_paragraph_preserves_per_line_font_size_and_x_height() {
        // Fails against unfixed code in two ways: (1) `line_font_sizes` /
        // `line_x_heights` attributes don't exist at all pre-fix, so both
        // `get` calls return `None`; (2) even measuring only the paragraph
        // mean (22 = (24+20)/2) would hide that line one is a 24pt heading
        // and line two is 20pt body text, which is exactly the per-line
        // detail #667/#669 ask to preserve.
        let hocr = r#"<div class="ocr_page" title="ppageno 0">
            <p class="ocr_par">
                <span class="ocr_line" title="bbox 10 10 200 40; x_size 28">
                    <span class="ocrx_word" title="bbox 10 10 100 40; x_wconf 90; x_fsize 24">BIG</span>
                </span>
                <span class="ocr_line" title="bbox 10 50 200 70">
                    <span class="ocrx_word" title="bbox 10 50 100 70; x_wconf 90; x_fsize 20">small</span>
                </span>
            </p>
        </div>"#;

        let doc = parse_hocr_to_internal_document(hocr);
        let attrs = doc.elements[0].attributes.as_ref().expect("attributes present");

        // Paragraph mean still present for existing consumers (#185).
        assert_eq!(attrs.get(HOCR_FONT_SIZE_ATTRIBUTE), Some(&"22".to_string()));

        // Per-line detail: line one is 24pt/x_size 28, line two is 20pt with
        // no line-level x_size (second field empty, position preserved).
        assert_eq!(attrs.get(HOCR_LINE_FONT_SIZES_ATTRIBUTE), Some(&"24,20".to_string()));
        assert_eq!(attrs.get(HOCR_LINE_X_HEIGHTS_ATTRIBUTE), Some(&"28,".to_string()));
    }

    /// Coverage for the per-line dictionary-invalid noise filter (#783).
    ///
    /// Named-import trap check: the reverted prior attempt (`29738a1f29`) added its tests
    /// to a module that imported by name (`use super::{...}`), and the new function was
    /// never added to that list, so the tests silently never compiled. This module uses
    /// `use super::*;` (see the top of `mod tests`), so that specific failure mode cannot
    /// recur here.
    mod dictionary_line_filter_tests {
        use super::*;

        /// Elevations-page hOCR, reconstructed directly from the recorded GH#783 defect:
        /// a correctly-read heading line, a fully garbled title-block line, and a second
        /// correctly-read heading line, all in one `ocr_par` block (Tesseract commonly
        /// groups a title block's short lines into a single paragraph).
        const ELEVATIONS_PAGE_HOCR: &str = r#"<div class="ocr_page" title="ppageno 0">
            <p class="ocr_par">
                <span class="ocr_line">
                    <span class="ocrx_word" title="bbox 10 10 100 40">RIGHT</span>
                    <span class="ocrx_word" title="bbox 110 10 260 40">ELEVATION</span>
                </span>
                <span class="ocr_line">
                    <span class="ocrx_word" title="bbox 10 50 100 80">OWATS</span>
                    <span class="ocrx_word" title="bbox 110 50 220 80">DNDEVET</span>
                    <span class="ocrx_word" title="bbox 230 50 320 80">OPMENT</span>
                </span>
                <span class="ocr_line">
                    <span class="ocrx_word" title="bbox 10 90 100 120">LEFT</span>
                    <span class="ocrx_word" title="bbox 110 90 260 120">ELEVATION</span>
                </span>
            </p>
        </div>"#;

        /// Dictionary lookup matching the real measurement recorded against GH#783:
        /// "OWATS" and "DNDEVET" are invalid, "OPMENT" is a Tesseract DAWG false
        /// positive (reported valid), and the two "ELEVATION"/"RIGHT"/"LEFT" words are
        /// genuinely valid. Every test in this module uses this exact table so the
        /// scenario matches the measured behavior, not an idealized dictionary.
        fn measured_is_valid_word(word: &str) -> Option<bool> {
            Some(!matches!(word, "OWATS" | "DNDEVET"))
        }

        /// 0.6, matching [`DEFAULT_DICT_INVALID_LINE_RATIO`] -- duplicated here as a
        /// literal (rather than referencing the constant directly) because what this
        /// module tests is the *filtering mechanism* at a fixed, known threshold, not
        /// that the production default stays at any particular value.
        const TEST_THRESHOLD: f64 = 0.6;

        /// The exact defect from #783: with the real (imperfect) dictionary behavior,
        /// the garbage line is still removed -- 2 invalid of 3 candidates (0.667) clears
        /// the 0.6 threshold even though "OPMENT" is counted as valid -- while both
        /// correctly-read heading lines survive untouched.
        ///
        /// This is checked on `doc.elements[0].text` rather than on
        /// `ocr::processor::execution::flatten_hocr_elements_to_text`'s output (private to
        /// that module, not reachable from here) -- but that is exactly the point being
        /// proven: `flatten_hocr_elements_to_text` only ever concatenates/transforms
        /// element text that is already present, so a line filtered out here, before any
        /// `InternalElement` is constructed, cannot resurface in that flattening OR in the
        /// `PdfParagraph`s `pdf::structure::adapters` builds from these same elements. One
        /// filtered `text` field feeds both downstream renderings; there is no second
        /// place for the two to drift apart.
        #[test]
        fn removes_the_garbage_line_but_keeps_both_real_headings() {
            let filter = DictionaryLineFilter {
                is_valid_word: &measured_is_valid_word,
                max_invalid_ratio: TEST_THRESHOLD,
            };
            let doc = parse_hocr_to_internal_document_with_dictionary_filter(ELEVATIONS_PAGE_HOCR, Some(&filter));

            assert_eq!(
                doc.elements.len(),
                1,
                "the paragraph survives: two of its three lines are real text"
            );
            let text = &doc.elements[0].text;
            assert!(!text.contains("OWATS"), "the noise line must be gone: {text:?}");
            assert!(!text.contains("DNDEVET"), "the noise line must be gone: {text:?}");
            assert_eq!(
                text, "RIGHT ELEVATION\nLEFT ELEVATION",
                "exactly the two real lines remain, in order"
            );
        }

        #[test]
        fn reports_the_exact_number_of_dictionary_filtered_lines() {
            let hocr = ELEVATIONS_PAGE_HOCR.replacen(
                r#"<span class="ocr_line">
                    <span class="ocrx_word" title="bbox 10 90 100 120">LEFT</span>"#,
                r#"<span class="ocr_line">
                    <span class="ocrx_word" title="bbox 10 82 100 88">OWATS</span>
                    <span class="ocrx_word" title="bbox 110 82 220 88">DNDEVET</span>
                    <span class="ocrx_word" title="bbox 230 82 320 88">OPMENT</span>
                </span>
                <span class="ocr_line">
                    <span class="ocrx_word" title="bbox 10 90 100 120">LEFT</span>"#,
                1,
            );
            let filter = DictionaryLineFilter {
                is_valid_word: &measured_is_valid_word,
                max_invalid_ratio: TEST_THRESHOLD,
            };

            let result = parse_hocr_to_internal_document_with_page_offset_and_stats(&hocr, Some(&filter), 1);

            assert_eq!(result.dictionary_filtered_line_count, 2);
            assert_eq!(result.document.elements[0].text, "RIGHT ELEVATION\nLEFT ELEVATION");
        }

        #[test]
        fn retained_confidence_stats_exclude_dictionary_filtered_lines() {
            let hocr = r#"<div class="ocr_page" title="ppageno 0">
                <p class="ocr_par">
                    <span class="ocr_line">
                        <span class="ocrx_word" title="bbox 10 10 100 40; x_wconf 20">CLEAR</span>
                        <span class="ocrx_word" title="bbox 110 10 220 40; x_wconf 90">WORDS</span>
                    </span>
                    <span class="ocr_line">
                        <span class="ocrx_word" title="bbox 10 50 100 80; x_wconf 0">OWATS</span>
                        <span class="ocrx_word" title="bbox 110 50 220 80; x_wconf 0">DNDEVET</span>
                    </span>
                </p>
            </div>"#;
            let is_valid = |word: &str| Some(matches!(word, "CLEAR" | "WORDS"));
            let filter = DictionaryLineFilter {
                is_valid_word: &is_valid,
                max_invalid_ratio: TEST_THRESHOLD,
            };

            let unfiltered = parse_hocr_to_internal_document_with_page_offset_and_stats(hocr, None, 1);
            let unfiltered_stats = &unfiltered.retained_word_confidence_stats;
            assert_eq!(unfiltered_stats.word_count(), 4);
            assert_eq!(unfiltered_stats.mean(), Some(27));
            assert_eq!(unfiltered_stats.median(), Some(10));
            assert_eq!(unfiltered_stats.p10(), Some(0));
            assert_eq!(unfiltered_stats.low_confidence_word_count(), 3);

            let result = parse_hocr_to_internal_document_with_page_offset_and_stats(hocr, Some(&filter), 1);
            let stats = &result.retained_word_confidence_stats;

            assert_eq!(result.document.elements[0].text, "CLEAR WORDS");
            assert_eq!(result.dictionary_filtered_line_count, 1);
            assert_eq!(stats.word_count(), 2);
            assert_eq!(stats.mean(), Some(55));
            assert_eq!(stats.median(), Some(55));
            assert_eq!(stats.p10(), Some(20));
            assert_eq!(stats.low_confidence_word_count(), 1);
        }

        #[test]
        fn rejected_all_words_produces_empty_stats() {
            let hocr = r#"<div class="ocr_page" title="ppageno 0">
                <p class="ocr_par">
                    <span class="ocr_line">
                        <span class="ocrx_word" title="bbox 10 10 100 40; x_wconf 10">OWATS</span>
                        <span class="ocrx_word" title="bbox 110 10 220 40; x_wconf 90">DNDEVET</span>
                    </span>
                </p>
            </div>"#;
            let always_invalid = |_: &str| Some(false);
            let filter = DictionaryLineFilter {
                is_valid_word: &always_invalid,
                max_invalid_ratio: TEST_THRESHOLD,
            };

            let unfiltered = parse_hocr_to_internal_document_with_page_offset_and_stats(hocr, None, 1);
            assert_eq!(unfiltered.retained_word_confidence_stats.word_count(), 2);
            assert_eq!(unfiltered.retained_word_confidence_stats.median(), Some(50));

            let result = parse_hocr_to_internal_document_with_page_offset_and_stats(hocr, Some(&filter), 1);
            let stats = &result.retained_word_confidence_stats;

            assert!(result.document.elements.is_empty());
            assert_eq!(stats.word_count(), 0);
            assert_eq!(stats.mean(), None);
            assert_eq!(stats.median(), None);
            assert_eq!(stats.p10(), None);
            assert_eq!(stats.low_confidence_word_count(), 0);
        }

        /// A line with only ONE dictionary-checkable word must never be scored, even when
        /// that word is invalid -- a lone proper noun or a truncated title-block fragment
        /// standing alone on its own line must not be flagged from a single data point.
        #[test]
        fn a_single_candidate_line_is_never_flagged() {
            let hocr = r#"<div class="ocr_page" title="ppageno 0">
                <p class="ocr_par">
                    <span class="ocr_line">
                        <span class="ocrx_word" title="bbox 10 10 100 40">Ligustrum</span>
                    </span>
                </p>
            </div>"#;
            let always_invalid = |_: &str| Some(false);
            let filter = DictionaryLineFilter {
                is_valid_word: &always_invalid,
                max_invalid_ratio: 0.0,
            };

            let doc = parse_hocr_to_internal_document_with_dictionary_filter(hocr, Some(&filter));

            assert_eq!(
                doc.elements.len(),
                1,
                "a single-candidate line must survive regardless of the ratio"
            );
            assert_eq!(doc.elements[0].text, "Ligustrum");
        }

        /// A mixed line at or below the threshold survives -- the plant-list guard from
        /// the original #783 report ("Ligustrum, Photinia, Azalea, Indian Hawthorne" mixes
        /// recognized words with unrecognized botanical genus names, 2 invalid of 5 =
        /// 0.4), reconstructed here as a single hOCR line.
        #[test]
        fn a_mixed_line_below_threshold_survives_verbatim() {
            let hocr = r#"<div class="ocr_page" title="ppageno 0">
                <p class="ocr_par">
                    <span class="ocr_line">
                        <span class="ocrx_word" title="bbox 10 10 100 40">Ligustrum</span>
                        <span class="ocrx_word" title="bbox 110 10 220 40">Photinia</span>
                        <span class="ocrx_word" title="bbox 230 10 320 40">Azalea</span>
                        <span class="ocrx_word" title="bbox 330 10 420 40">Indian</span>
                        <span class="ocrx_word" title="bbox 430 10 560 40">Hawthorne</span>
                    </span>
                </p>
            </div>"#;
            let is_valid = |word: &str| Some(matches!(word, "Azalea" | "Indian" | "Hawthorne"));
            let filter = DictionaryLineFilter {
                is_valid_word: &is_valid,
                max_invalid_ratio: TEST_THRESHOLD,
            };

            let doc = parse_hocr_to_internal_document_with_dictionary_filter(hocr, Some(&filter));

            assert_eq!(doc.elements.len(), 1);
            assert_eq!(doc.elements[0].text, "Ligustrum Photinia Azalea Indian Hawthorne");
        }

        /// A ratio exactly AT the threshold must survive -- the check is strictly
        /// greater-than, matching the page-level `is_dictionary_invalid_noise` convention
        /// (`extractors::pdf::ocr`).
        #[test]
        fn a_line_exactly_at_the_threshold_is_not_removed() {
            let hocr = r#"<div class="ocr_page" title="ppageno 0">
                <p class="ocr_par">
                    <span class="ocr_line">
                        <span class="ocrx_word" title="bbox 10 10 100 40">Photinia</span>
                        <span class="ocrx_word" title="bbox 110 10 220 40">Ligustrum</span>
                    </span>
                </p>
            </div>"#;
            let always_invalid = |_: &str| Some(false);
            let filter = DictionaryLineFilter {
                is_valid_word: &always_invalid,
                max_invalid_ratio: 1.0,
            };

            let doc = parse_hocr_to_internal_document_with_dictionary_filter(hocr, Some(&filter));

            assert_eq!(
                doc.elements.len(),
                1,
                "ratio 1.0 is not > threshold 1.0, so the line must survive"
            );
        }

        /// A paragraph whose every line is noise disappears from the document entirely --
        /// the same "no words survived" path an all-empty paragraph already takes,
        /// exercised here via dictionary filtering rather than empty text.
        #[test]
        fn a_paragraph_left_with_no_lines_produces_no_element() {
            let hocr = r#"<div class="ocr_page" title="ppageno 0">
                <p class="ocr_par">
                    <span class="ocr_line">
                        <span class="ocrx_word" title="bbox 10 10 100 40">OWATS</span>
                        <span class="ocrx_word" title="bbox 110 10 220 40">DNDEVET</span>
                    </span>
                </p>
            </div>"#;
            let always_invalid = |_: &str| Some(false);
            let filter = DictionaryLineFilter {
                is_valid_word: &always_invalid,
                max_invalid_ratio: TEST_THRESHOLD,
            };

            let doc = parse_hocr_to_internal_document_with_dictionary_filter(hocr, Some(&filter));

            assert!(
                doc.elements.is_empty(),
                "a paragraph with no surviving lines must not appear at all"
            );
        }

        /// No filter at all (the plain [`parse_hocr_to_internal_document`] entry point,
        /// what every other test in this file uses) must behave exactly as before this
        /// feature existed: nothing is removed, no matter how garbled the text is.
        #[test]
        fn no_filter_leaves_every_line_untouched() {
            let doc = parse_hocr_to_internal_document(ELEVATIONS_PAGE_HOCR);
            assert_eq!(doc.elements.len(), 1);
            assert!(doc.elements[0].text.contains("OWATS DNDEVET OPMENT"));
        }
    }
}